nwo
stringlengths 5
86
| sha
stringlengths 40
40
| path
stringlengths 4
189
| language
stringclasses 1
value | identifier
stringlengths 1
94
| parameters
stringlengths 2
4.03k
| argument_list
stringclasses 1
value | return_statement
stringlengths 0
11.5k
| docstring
stringlengths 1
33.2k
| docstring_summary
stringlengths 0
5.15k
| docstring_tokens
sequence | function
stringlengths 34
151k
| function_tokens
sequence | url
stringlengths 90
278
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Slicer/Slicer | ba9fadf332cb0303515b68d8d06a344c82e3e3e5 | Base/Python/slicer/util.py | python | removeParameterEditWidgetConnections | (parameterEditWidgets, updateParameterNodeFromGUI) | Remove connections created by :py:meth:`addParameterEditWidgetConnections`. | Remove connections created by :py:meth:`addParameterEditWidgetConnections`. | [
"Remove",
"connections",
"created",
"by",
":",
"py",
":",
"meth",
":",
"addParameterEditWidgetConnections",
"."
] | def removeParameterEditWidgetConnections(parameterEditWidgets, updateParameterNodeFromGUI):
""" Remove connections created by :py:meth:`addParameterEditWidgetConnections`.
"""
for (widget, parameterName) in parameterEditWidgets:
widgetClassName = widget.className()
if widgetClassName=="QSpinBox":
widget.disconnect("valueChanged(int)", updateParameterNodeFromGUI)
elif widgetClassName=="QPushButton":
widget.disconnect("toggled(bool)", updateParameterNodeFromGUI)
elif widgetClassName=="qMRMLNodeComboBox":
widget.disconnect("currentNodeIDChanged(QString)", updateParameterNodeFromGUI)
elif widgetClassName=="QComboBox":
widget.disconnect("currentIndexChanged(int)", updateParameterNodeFromGUI)
elif widgetClassName=="ctkSliderWidget":
widget.disconnect("valueChanged(double)", updateParameterNodeFromGUI) | [
"def",
"removeParameterEditWidgetConnections",
"(",
"parameterEditWidgets",
",",
"updateParameterNodeFromGUI",
")",
":",
"for",
"(",
"widget",
",",
"parameterName",
")",
"in",
"parameterEditWidgets",
":",
"widgetClassName",
"=",
"widget",
".",
"className",
"(",
")",
"if",
"widgetClassName",
"==",
"\"QSpinBox\"",
":",
"widget",
".",
"disconnect",
"(",
"\"valueChanged(int)\"",
",",
"updateParameterNodeFromGUI",
")",
"elif",
"widgetClassName",
"==",
"\"QPushButton\"",
":",
"widget",
".",
"disconnect",
"(",
"\"toggled(bool)\"",
",",
"updateParameterNodeFromGUI",
")",
"elif",
"widgetClassName",
"==",
"\"qMRMLNodeComboBox\"",
":",
"widget",
".",
"disconnect",
"(",
"\"currentNodeIDChanged(QString)\"",
",",
"updateParameterNodeFromGUI",
")",
"elif",
"widgetClassName",
"==",
"\"QComboBox\"",
":",
"widget",
".",
"disconnect",
"(",
"\"currentIndexChanged(int)\"",
",",
"updateParameterNodeFromGUI",
")",
"elif",
"widgetClassName",
"==",
"\"ctkSliderWidget\"",
":",
"widget",
".",
"disconnect",
"(",
"\"valueChanged(double)\"",
",",
"updateParameterNodeFromGUI",
")"
] | https://github.com/Slicer/Slicer/blob/ba9fadf332cb0303515b68d8d06a344c82e3e3e5/Base/Python/slicer/util.py#L407-L422 |
||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/StdSuites/AppleScript_Suite.py | python | AppleScript_Suite_Events._3e_ | (self, _object, _attributes={}, **_arguments) | >: Greater than
Required argument: an AE object reference
Keyword argument _attributes: AppleEvent attribute dictionary
Returns: anything | >: Greater than
Required argument: an AE object reference
Keyword argument _attributes: AppleEvent attribute dictionary
Returns: anything | [
">",
":",
"Greater",
"than",
"Required",
"argument",
":",
"an",
"AE",
"object",
"reference",
"Keyword",
"argument",
"_attributes",
":",
"AppleEvent",
"attribute",
"dictionary",
"Returns",
":",
"anything"
] | def _3e_(self, _object, _attributes={}, **_arguments):
""">: Greater than
Required argument: an AE object reference
Keyword argument _attributes: AppleEvent attribute dictionary
Returns: anything
"""
_code = 'ascr'
_subcode = '> '
if _arguments: raise TypeError, 'No optional args expected'
_arguments['----'] = _object
_reply, _arguments, _attributes = self.send(_code, _subcode,
_arguments, _attributes)
if _arguments.get('errn', 0):
raise aetools.Error, aetools.decodeerror(_arguments)
# XXXX Optionally decode result
if _arguments.has_key('----'):
return _arguments['----'] | [
"def",
"_3e_",
"(",
"self",
",",
"_object",
",",
"_attributes",
"=",
"{",
"}",
",",
"*",
"*",
"_arguments",
")",
":",
"_code",
"=",
"'ascr'",
"_subcode",
"=",
"'> '",
"if",
"_arguments",
":",
"raise",
"TypeError",
",",
"'No optional args expected'",
"_arguments",
"[",
"'----'",
"]",
"=",
"_object",
"_reply",
",",
"_arguments",
",",
"_attributes",
"=",
"self",
".",
"send",
"(",
"_code",
",",
"_subcode",
",",
"_arguments",
",",
"_attributes",
")",
"if",
"_arguments",
".",
"get",
"(",
"'errn'",
",",
"0",
")",
":",
"raise",
"aetools",
".",
"Error",
",",
"aetools",
".",
"decodeerror",
"(",
"_arguments",
")",
"# XXXX Optionally decode result",
"if",
"_arguments",
".",
"has_key",
"(",
"'----'",
")",
":",
"return",
"_arguments",
"[",
"'----'",
"]"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/StdSuites/AppleScript_Suite.py#L141-L160 |
||
rdkit/rdkit | ede860ae316d12d8568daf5ee800921c3389c84e | rdkit/sping/PDF/pdfgen.py | python | Canvas.beginPath | (self) | return PDFPathObject() | Returns a fresh path object | Returns a fresh path object | [
"Returns",
"a",
"fresh",
"path",
"object"
] | def beginPath(self):
"""Returns a fresh path object"""
return PDFPathObject() | [
"def",
"beginPath",
"(",
"self",
")",
":",
"return",
"PDFPathObject",
"(",
")"
] | https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/sping/PDF/pdfgen.py#L533-L535 |
|
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/optim/lr_scheduler.py | python | _LRScheduler.state_dict | (self) | return {key: value for key, value in self.__dict__.items() if key != 'optimizer'} | Returns the state of the scheduler as a :class:`dict`.
It contains an entry for every variable in self.__dict__ which
is not the optimizer. | Returns the state of the scheduler as a :class:`dict`. | [
"Returns",
"the",
"state",
"of",
"the",
"scheduler",
"as",
"a",
":",
"class",
":",
"dict",
"."
] | def state_dict(self):
"""Returns the state of the scheduler as a :class:`dict`.
It contains an entry for every variable in self.__dict__ which
is not the optimizer.
"""
return {key: value for key, value in self.__dict__.items() if key != 'optimizer'} | [
"def",
"state_dict",
"(",
"self",
")",
":",
"return",
"{",
"key",
":",
"value",
"for",
"key",
",",
"value",
"in",
"self",
".",
"__dict__",
".",
"items",
"(",
")",
"if",
"key",
"!=",
"'optimizer'",
"}"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/optim/lr_scheduler.py#L79-L85 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/wizard.py | python | PyWizardPage.DoSetClientSize | (*args, **kwargs) | return _wizard.PyWizardPage_DoSetClientSize(*args, **kwargs) | DoSetClientSize(self, int width, int height) | DoSetClientSize(self, int width, int height) | [
"DoSetClientSize",
"(",
"self",
"int",
"width",
"int",
"height",
")"
] | def DoSetClientSize(*args, **kwargs):
"""DoSetClientSize(self, int width, int height)"""
return _wizard.PyWizardPage_DoSetClientSize(*args, **kwargs) | [
"def",
"DoSetClientSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_wizard",
".",
"PyWizardPage_DoSetClientSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/wizard.py#L159-L161 |
|
swift/swift | 12d031cf8177fdec0137f9aa7e2912fa23c4416b | 3rdParty/SCons/scons-3.0.1/engine/SCons/Node/Alias.py | python | Alias.get_contents | (self) | return ''.join(childsigs) | The contents of an alias is the concatenation
of the content signatures of all its sources. | The contents of an alias is the concatenation
of the content signatures of all its sources. | [
"The",
"contents",
"of",
"an",
"alias",
"is",
"the",
"concatenation",
"of",
"the",
"content",
"signatures",
"of",
"all",
"its",
"sources",
"."
] | def get_contents(self):
"""The contents of an alias is the concatenation
of the content signatures of all its sources."""
childsigs = [n.get_csig() for n in self.children()]
return ''.join(childsigs) | [
"def",
"get_contents",
"(",
"self",
")",
":",
"childsigs",
"=",
"[",
"n",
".",
"get_csig",
"(",
")",
"for",
"n",
"in",
"self",
".",
"children",
"(",
")",
"]",
"return",
"''",
".",
"join",
"(",
"childsigs",
")"
] | https://github.com/swift/swift/blob/12d031cf8177fdec0137f9aa7e2912fa23c4416b/3rdParty/SCons/scons-3.0.1/engine/SCons/Node/Alias.py#L130-L134 |
|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/base.py | python | IndexOpsMixin.tolist | (self) | return self._values.tolist() | Return a list of the values.
These are each a scalar type, which is a Python scalar
(for str, int, float) or a pandas scalar
(for Timestamp/Timedelta/Interval/Period)
Returns
-------
list
See Also
--------
numpy.ndarray.tolist : Return the array as an a.ndim-levels deep
nested list of Python scalars. | Return a list of the values. | [
"Return",
"a",
"list",
"of",
"the",
"values",
"."
] | def tolist(self):
"""
Return a list of the values.
These are each a scalar type, which is a Python scalar
(for str, int, float) or a pandas scalar
(for Timestamp/Timedelta/Interval/Period)
Returns
-------
list
See Also
--------
numpy.ndarray.tolist : Return the array as an a.ndim-levels deep
nested list of Python scalars.
"""
if not isinstance(self._values, np.ndarray):
# check for ndarray instead of dtype to catch DTA/TDA
return list(self._values)
return self._values.tolist() | [
"def",
"tolist",
"(",
"self",
")",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"_values",
",",
"np",
".",
"ndarray",
")",
":",
"# check for ndarray instead of dtype to catch DTA/TDA",
"return",
"list",
"(",
"self",
".",
"_values",
")",
"return",
"self",
".",
"_values",
".",
"tolist",
"(",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/base.py#L713-L733 |
|
ablab/quast | 5f6709528129a6ad266a6b24ef3f40b88f0fe04b | quast_libs/site_packages/jsontemplate/jsontemplate.py | python | PrefixRegistry.__init__ | (self, functions) | Args:
functions: List of 2-tuples (prefix, function), e.g.
[('pluralize', _Pluralize), ('cycle', _Cycle)] | Args:
functions: List of 2-tuples (prefix, function), e.g.
[('pluralize', _Pluralize), ('cycle', _Cycle)] | [
"Args",
":",
"functions",
":",
"List",
"of",
"2",
"-",
"tuples",
"(",
"prefix",
"function",
")",
"e",
".",
"g",
".",
"[",
"(",
"pluralize",
"_Pluralize",
")",
"(",
"cycle",
"_Cycle",
")",
"]"
] | def __init__(self, functions):
"""
Args:
functions: List of 2-tuples (prefix, function), e.g.
[('pluralize', _Pluralize), ('cycle', _Cycle)]
"""
self.functions = functions | [
"def",
"__init__",
"(",
"self",
",",
"functions",
")",
":",
"self",
".",
"functions",
"=",
"functions"
] | https://github.com/ablab/quast/blob/5f6709528129a6ad266a6b24ef3f40b88f0fe04b/quast_libs/site_packages/jsontemplate/jsontemplate.py#L193-L199 |
||
BSVino/DoubleAction | c550b168a3e919926c198c30240f506538b92e75 | mp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/reflection.py | python | _ExtensionDict.__init__ | (self, extended_message) | extended_message: Message instance for which we are the Extensions dict. | extended_message: Message instance for which we are the Extensions dict. | [
"extended_message",
":",
"Message",
"instance",
"for",
"which",
"we",
"are",
"the",
"Extensions",
"dict",
"."
] | def __init__(self, extended_message):
"""extended_message: Message instance for which we are the Extensions dict.
"""
self._extended_message = extended_message | [
"def",
"__init__",
"(",
"self",
",",
"extended_message",
")",
":",
"self",
".",
"_extended_message",
"=",
"extended_message"
] | https://github.com/BSVino/DoubleAction/blob/c550b168a3e919926c198c30240f506538b92e75/mp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/reflection.py#L1059-L1063 |
||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/mimetypes.py | python | guess_all_extensions | (type, strict=True) | return _db.guess_all_extensions(type, strict) | Guess the extensions for a file based on its MIME type.
Return value is a list of strings giving the possible filename
extensions, including the leading dot ('.'). The extension is not
guaranteed to have been associated with any particular data
stream, but would be mapped to the MIME type `type' by
guess_type(). If no extension can be guessed for `type', None
is returned.
Optional `strict' argument when false adds a bunch of commonly found,
but non-standard types. | Guess the extensions for a file based on its MIME type. | [
"Guess",
"the",
"extensions",
"for",
"a",
"file",
"based",
"on",
"its",
"MIME",
"type",
"."
] | def guess_all_extensions(type, strict=True):
"""Guess the extensions for a file based on its MIME type.
Return value is a list of strings giving the possible filename
extensions, including the leading dot ('.'). The extension is not
guaranteed to have been associated with any particular data
stream, but would be mapped to the MIME type `type' by
guess_type(). If no extension can be guessed for `type', None
is returned.
Optional `strict' argument when false adds a bunch of commonly found,
but non-standard types.
"""
if _db is None:
init()
return _db.guess_all_extensions(type, strict) | [
"def",
"guess_all_extensions",
"(",
"type",
",",
"strict",
"=",
"True",
")",
":",
"if",
"_db",
"is",
"None",
":",
"init",
"(",
")",
"return",
"_db",
".",
"guess_all_extensions",
"(",
"type",
",",
"strict",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/mimetypes.py#L297-L312 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/plugins/Launch/launch/cfgdlg.py | python | ConfigPanel.UpdateForHandler | (self) | Update the panel for the current filetype handler | Update the panel for the current filetype handler | [
"Update",
"the",
"panel",
"for",
"the",
"current",
"filetype",
"handler"
] | def UpdateForHandler(self):
"""Update the panel for the current filetype handler"""
handler = self.GetCurrentHandler()
elist = self.FindWindowById(ID_EXECUTABLES)
elist.DeleteAllItems()
def_ch = self.FindWindowById(wx.ID_DEFAULT)
def_ch.SetItems(handler.GetAliases())
def_ch.SetStringSelection(handler.GetDefault())
self.SetListItems(handler.GetCommands())
# Enable control states
transient = handler.meta.transient
def_ch.Enable(not transient)
elist.Enable(not transient)
self.addbtn.Enable(not transient)
self.delbtn.Enable(not transient)
if self.infotxt.Show(transient):
self.Layout() | [
"def",
"UpdateForHandler",
"(",
"self",
")",
":",
"handler",
"=",
"self",
".",
"GetCurrentHandler",
"(",
")",
"elist",
"=",
"self",
".",
"FindWindowById",
"(",
"ID_EXECUTABLES",
")",
"elist",
".",
"DeleteAllItems",
"(",
")",
"def_ch",
"=",
"self",
".",
"FindWindowById",
"(",
"wx",
".",
"ID_DEFAULT",
")",
"def_ch",
".",
"SetItems",
"(",
"handler",
".",
"GetAliases",
"(",
")",
")",
"def_ch",
".",
"SetStringSelection",
"(",
"handler",
".",
"GetDefault",
"(",
")",
")",
"self",
".",
"SetListItems",
"(",
"handler",
".",
"GetCommands",
"(",
")",
")",
"# Enable control states",
"transient",
"=",
"handler",
".",
"meta",
".",
"transient",
"def_ch",
".",
"Enable",
"(",
"not",
"transient",
")",
"elist",
".",
"Enable",
"(",
"not",
"transient",
")",
"self",
".",
"addbtn",
".",
"Enable",
"(",
"not",
"transient",
")",
"self",
".",
"delbtn",
".",
"Enable",
"(",
"not",
"transient",
")",
"if",
"self",
".",
"infotxt",
".",
"Show",
"(",
"transient",
")",
":",
"self",
".",
"Layout",
"(",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/plugins/Launch/launch/cfgdlg.py#L348-L364 |
||
OSGeo/gdal | 3748fc4ba4fba727492774b2b908a2130c864a83 | swig/python/osgeo/osr.py | python | SpatialReference.SetEquirectangular2 | (self, *args, **kwargs) | return _osr.SpatialReference_SetEquirectangular2(self, *args, **kwargs) | r"""SetEquirectangular2(SpatialReference self, double clat, double clong, double pseudostdparallellat, double fe, double fn) -> OGRErr | r"""SetEquirectangular2(SpatialReference self, double clat, double clong, double pseudostdparallellat, double fe, double fn) -> OGRErr | [
"r",
"SetEquirectangular2",
"(",
"SpatialReference",
"self",
"double",
"clat",
"double",
"clong",
"double",
"pseudostdparallellat",
"double",
"fe",
"double",
"fn",
")",
"-",
">",
"OGRErr"
] | def SetEquirectangular2(self, *args, **kwargs):
r"""SetEquirectangular2(SpatialReference self, double clat, double clong, double pseudostdparallellat, double fe, double fn) -> OGRErr"""
return _osr.SpatialReference_SetEquirectangular2(self, *args, **kwargs) | [
"def",
"SetEquirectangular2",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_osr",
".",
"SpatialReference_SetEquirectangular2",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/osr.py#L570-L572 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/asyncio/events.py | python | AbstractEventLoop._timer_handle_cancelled | (self, handle) | Notification that a TimerHandle has been cancelled. | Notification that a TimerHandle has been cancelled. | [
"Notification",
"that",
"a",
"TimerHandle",
"has",
"been",
"cancelled",
"."
] | def _timer_handle_cancelled(self, handle):
"""Notification that a TimerHandle has been cancelled."""
raise NotImplementedError | [
"def",
"_timer_handle_cancelled",
"(",
"self",
",",
"handle",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/asyncio/events.py#L259-L261 |
||
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/intelc.py | python | get_intel_compiler_top | (version, abi) | return top | Return the main path to the top-level dir of the Intel compiler,
using the given version.
The compiler will be in <top>/bin/icl.exe (icc on linux),
the include dir is <top>/include, etc. | Return the main path to the top-level dir of the Intel compiler,
using the given version.
The compiler will be in <top>/bin/icl.exe (icc on linux),
the include dir is <top>/include, etc. | [
"Return",
"the",
"main",
"path",
"to",
"the",
"top",
"-",
"level",
"dir",
"of",
"the",
"Intel",
"compiler",
"using",
"the",
"given",
"version",
".",
"The",
"compiler",
"will",
"be",
"in",
"<top",
">",
"/",
"bin",
"/",
"icl",
".",
"exe",
"(",
"icc",
"on",
"linux",
")",
"the",
"include",
"dir",
"is",
"<top",
">",
"/",
"include",
"etc",
"."
] | def get_intel_compiler_top(version, abi):
"""
Return the main path to the top-level dir of the Intel compiler,
using the given version.
The compiler will be in <top>/bin/icl.exe (icc on linux),
the include dir is <top>/include, etc.
"""
if is_windows:
if not SCons.Util.can_read_reg:
raise NoRegistryModuleError("No Windows registry module was found")
top = get_intel_registry_value('ProductDir', version, abi)
archdir={'x86_64': 'intel64',
'amd64' : 'intel64',
'em64t' : 'intel64',
'x86' : 'ia32',
'i386' : 'ia32',
'ia32' : 'ia32'
}[abi] # for v11 and greater
# pre-11, icl was in Bin. 11 and later, it's in Bin/<abi> apparently.
if not os.path.exists(os.path.join(top, "Bin", "icl.exe")) \
and not os.path.exists(os.path.join(top, "Bin", abi, "icl.exe")) \
and not os.path.exists(os.path.join(top, "Bin", archdir, "icl.exe")):
raise MissingDirError("Can't find Intel compiler in %s"%(top))
elif is_mac or is_linux:
def find_in_2008style_dir(version):
# first dir is new (>=9.0) style, second is old (8.0) style.
dirs=('/opt/intel/cc/%s', '/opt/intel_cc_%s')
if abi == 'x86_64':
dirs=('/opt/intel/cce/%s',) # 'e' stands for 'em64t', aka x86_64 aka amd64
top=None
for d in dirs:
if os.path.exists(os.path.join(d%version, "bin", "icc")):
top = d%version
break
return top
def find_in_2010style_dir(version):
dirs=('/opt/intel/Compiler/%s/*'%version)
# typically /opt/intel/Compiler/11.1/064 (then bin/intel64/icc)
dirs=glob.glob(dirs)
# find highest sub-version number by reverse sorting and picking first existing one.
dirs.sort()
dirs.reverse()
top=None
for d in dirs:
if (os.path.exists(os.path.join(d, "bin", "ia32", "icc")) or
os.path.exists(os.path.join(d, "bin", "intel64", "icc"))):
top = d
break
return top
def find_in_2011style_dir(version):
# The 2011 (compiler v12) dirs are inconsistent, so just redo the search from
# get_all_compiler_versions and look for a match (search the newest form first)
top=None
for d in glob.glob('/opt/intel/composer_xe_*'):
# Typical dir here is /opt/intel/composer_xe_2011_sp1.11.344
# The _sp1 is useless, the installers are named 2011.9.x, 2011.10.x, 2011.11.x
m = re.search(r'([0-9]{0,4})(?:_sp\d*)?\.([0-9][0-9.]*)$', d)
if m:
cur_ver = "%s.%s"%(m.group(1), m.group(2))
if cur_ver == version and \
(os.path.exists(os.path.join(d, "bin", "ia32", "icc")) or
os.path.exists(os.path.join(d, "bin", "intel64", "icc"))):
top = d
break
if not top:
for d in glob.glob('/opt/intel/composerxe-*'):
# Typical dir here is /opt/intel/composerxe-2011.4.184
m = re.search(r'([0-9][0-9.]*)$', d)
if m and m.group(1) == version and \
(os.path.exists(os.path.join(d, "bin", "ia32", "icc")) or
os.path.exists(os.path.join(d, "bin", "intel64", "icc"))):
top = d
break
return top
def find_in_2016style_dir(version):
# The 2016 (compiler v16) dirs are inconsistent from previous.
top = None
for d in glob.glob('/opt/intel/compilers_and_libraries_%s/linux'%version):
if os.path.exists(os.path.join(d, "bin", "ia32", "icc")) or os.path.exists(os.path.join(d, "bin", "intel64", "icc")):
top = d
break
return top
top = find_in_2016style_dir(version) or find_in_2011style_dir(version) or find_in_2010style_dir(version) or find_in_2008style_dir(version)
# print "INTELC: top=",top
if not top:
raise MissingDirError("Can't find version %s Intel compiler in %s (abi='%s')"%(version,top, abi))
return top | [
"def",
"get_intel_compiler_top",
"(",
"version",
",",
"abi",
")",
":",
"if",
"is_windows",
":",
"if",
"not",
"SCons",
".",
"Util",
".",
"can_read_reg",
":",
"raise",
"NoRegistryModuleError",
"(",
"\"No Windows registry module was found\"",
")",
"top",
"=",
"get_intel_registry_value",
"(",
"'ProductDir'",
",",
"version",
",",
"abi",
")",
"archdir",
"=",
"{",
"'x86_64'",
":",
"'intel64'",
",",
"'amd64'",
":",
"'intel64'",
",",
"'em64t'",
":",
"'intel64'",
",",
"'x86'",
":",
"'ia32'",
",",
"'i386'",
":",
"'ia32'",
",",
"'ia32'",
":",
"'ia32'",
"}",
"[",
"abi",
"]",
"# for v11 and greater",
"# pre-11, icl was in Bin. 11 and later, it's in Bin/<abi> apparently.",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"top",
",",
"\"Bin\"",
",",
"\"icl.exe\"",
")",
")",
"and",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"top",
",",
"\"Bin\"",
",",
"abi",
",",
"\"icl.exe\"",
")",
")",
"and",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"top",
",",
"\"Bin\"",
",",
"archdir",
",",
"\"icl.exe\"",
")",
")",
":",
"raise",
"MissingDirError",
"(",
"\"Can't find Intel compiler in %s\"",
"%",
"(",
"top",
")",
")",
"elif",
"is_mac",
"or",
"is_linux",
":",
"def",
"find_in_2008style_dir",
"(",
"version",
")",
":",
"# first dir is new (>=9.0) style, second is old (8.0) style.",
"dirs",
"=",
"(",
"'/opt/intel/cc/%s'",
",",
"'/opt/intel_cc_%s'",
")",
"if",
"abi",
"==",
"'x86_64'",
":",
"dirs",
"=",
"(",
"'/opt/intel/cce/%s'",
",",
")",
"# 'e' stands for 'em64t', aka x86_64 aka amd64",
"top",
"=",
"None",
"for",
"d",
"in",
"dirs",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"d",
"%",
"version",
",",
"\"bin\"",
",",
"\"icc\"",
")",
")",
":",
"top",
"=",
"d",
"%",
"version",
"break",
"return",
"top",
"def",
"find_in_2010style_dir",
"(",
"version",
")",
":",
"dirs",
"=",
"(",
"'/opt/intel/Compiler/%s/*'",
"%",
"version",
")",
"# typically /opt/intel/Compiler/11.1/064 (then bin/intel64/icc)",
"dirs",
"=",
"glob",
".",
"glob",
"(",
"dirs",
")",
"# find highest sub-version number by reverse sorting and picking first existing one.",
"dirs",
".",
"sort",
"(",
")",
"dirs",
".",
"reverse",
"(",
")",
"top",
"=",
"None",
"for",
"d",
"in",
"dirs",
":",
"if",
"(",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"d",
",",
"\"bin\"",
",",
"\"ia32\"",
",",
"\"icc\"",
")",
")",
"or",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"d",
",",
"\"bin\"",
",",
"\"intel64\"",
",",
"\"icc\"",
")",
")",
")",
":",
"top",
"=",
"d",
"break",
"return",
"top",
"def",
"find_in_2011style_dir",
"(",
"version",
")",
":",
"# The 2011 (compiler v12) dirs are inconsistent, so just redo the search from",
"# get_all_compiler_versions and look for a match (search the newest form first)",
"top",
"=",
"None",
"for",
"d",
"in",
"glob",
".",
"glob",
"(",
"'/opt/intel/composer_xe_*'",
")",
":",
"# Typical dir here is /opt/intel/composer_xe_2011_sp1.11.344",
"# The _sp1 is useless, the installers are named 2011.9.x, 2011.10.x, 2011.11.x",
"m",
"=",
"re",
".",
"search",
"(",
"r'([0-9]{0,4})(?:_sp\\d*)?\\.([0-9][0-9.]*)$'",
",",
"d",
")",
"if",
"m",
":",
"cur_ver",
"=",
"\"%s.%s\"",
"%",
"(",
"m",
".",
"group",
"(",
"1",
")",
",",
"m",
".",
"group",
"(",
"2",
")",
")",
"if",
"cur_ver",
"==",
"version",
"and",
"(",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"d",
",",
"\"bin\"",
",",
"\"ia32\"",
",",
"\"icc\"",
")",
")",
"or",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"d",
",",
"\"bin\"",
",",
"\"intel64\"",
",",
"\"icc\"",
")",
")",
")",
":",
"top",
"=",
"d",
"break",
"if",
"not",
"top",
":",
"for",
"d",
"in",
"glob",
".",
"glob",
"(",
"'/opt/intel/composerxe-*'",
")",
":",
"# Typical dir here is /opt/intel/composerxe-2011.4.184",
"m",
"=",
"re",
".",
"search",
"(",
"r'([0-9][0-9.]*)$'",
",",
"d",
")",
"if",
"m",
"and",
"m",
".",
"group",
"(",
"1",
")",
"==",
"version",
"and",
"(",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"d",
",",
"\"bin\"",
",",
"\"ia32\"",
",",
"\"icc\"",
")",
")",
"or",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"d",
",",
"\"bin\"",
",",
"\"intel64\"",
",",
"\"icc\"",
")",
")",
")",
":",
"top",
"=",
"d",
"break",
"return",
"top",
"def",
"find_in_2016style_dir",
"(",
"version",
")",
":",
"# The 2016 (compiler v16) dirs are inconsistent from previous.",
"top",
"=",
"None",
"for",
"d",
"in",
"glob",
".",
"glob",
"(",
"'/opt/intel/compilers_and_libraries_%s/linux'",
"%",
"version",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"d",
",",
"\"bin\"",
",",
"\"ia32\"",
",",
"\"icc\"",
")",
")",
"or",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"d",
",",
"\"bin\"",
",",
"\"intel64\"",
",",
"\"icc\"",
")",
")",
":",
"top",
"=",
"d",
"break",
"return",
"top",
"top",
"=",
"find_in_2016style_dir",
"(",
"version",
")",
"or",
"find_in_2011style_dir",
"(",
"version",
")",
"or",
"find_in_2010style_dir",
"(",
"version",
")",
"or",
"find_in_2008style_dir",
"(",
"version",
")",
"# print \"INTELC: top=\",top",
"if",
"not",
"top",
":",
"raise",
"MissingDirError",
"(",
"\"Can't find version %s Intel compiler in %s (abi='%s')\"",
"%",
"(",
"version",
",",
"top",
",",
"abi",
")",
")",
"return",
"top"
] | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/intelc.py#L304-L392 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/stc.py | python | StyledTextCtrl.LineUpRectExtend | (*args, **kwargs) | return _stc.StyledTextCtrl_LineUpRectExtend(*args, **kwargs) | LineUpRectExtend(self)
Move caret up one line, extending rectangular selection to new caret position. | LineUpRectExtend(self) | [
"LineUpRectExtend",
"(",
"self",
")"
] | def LineUpRectExtend(*args, **kwargs):
"""
LineUpRectExtend(self)
Move caret up one line, extending rectangular selection to new caret position.
"""
return _stc.StyledTextCtrl_LineUpRectExtend(*args, **kwargs) | [
"def",
"LineUpRectExtend",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_LineUpRectExtend",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/stc.py#L5375-L5381 |
|
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | addon-sdk/source/python-lib/jetpack_sdk_env.py | python | welcome | () | Perform a bunch of sanity tests to make sure the Add-on SDK
environment is sane, and then display a welcome message. | Perform a bunch of sanity tests to make sure the Add-on SDK
environment is sane, and then display a welcome message. | [
"Perform",
"a",
"bunch",
"of",
"sanity",
"tests",
"to",
"make",
"sure",
"the",
"Add",
"-",
"on",
"SDK",
"environment",
"is",
"sane",
"and",
"then",
"display",
"a",
"welcome",
"message",
"."
] | def welcome():
"""
Perform a bunch of sanity tests to make sure the Add-on SDK
environment is sane, and then display a welcome message.
"""
try:
if sys.version_info[0] > 2:
print ("Error: You appear to be using Python %d, but "
"the Add-on SDK only supports the Python 2.x line." %
(sys.version_info[0]))
return
import mozrunner
if 'CUDDLEFISH_ROOT' not in os.environ:
print ("Error: CUDDLEFISH_ROOT environment variable does "
"not exist! It should point to the root of the "
"Add-on SDK repository.")
return
env_root = os.environ['CUDDLEFISH_ROOT']
bin_dir = os.path.join(env_root, 'bin')
python_lib_dir = os.path.join(env_root, 'python-lib')
path = os.environ['PATH'].split(os.path.pathsep)
if bin_dir not in path:
print ("Warning: the Add-on SDK binary directory %s "
"does not appear to be in your PATH. You may "
"not be able to run 'cfx' or other SDK tools." %
bin_dir)
if python_lib_dir not in sys.path:
print ("Warning: the Add-on SDK python-lib directory %s "
"does not appear to be in your sys.path, which "
"is odd because I'm running from it." % python_lib_dir)
if not mozrunner.__path__[0].startswith(env_root):
print ("Warning: your mozrunner package is installed at %s, "
"which does not seem to be located inside the Jetpack "
"SDK. This may cause problems, and you may want to "
"uninstall the other version. See bug 556562 for "
"more information." % mozrunner.__path__[0])
except Exception:
# Apparently we can't get the actual exception object in the
# 'except' clause in a way that's syntax-compatible for both
# Python 2.x and 3.x, so we'll have to use the traceback module.
import traceback
_, e, _ = sys.exc_info()
print ("Verification of Add-on SDK environment failed (%s)." % e)
print ("Your SDK may not work properly.")
return
print ("Welcome to the Add-on SDK. For the docs, visit https://developer.mozilla.org/en-US/Add-ons/SDK") | [
"def",
"welcome",
"(",
")",
":",
"try",
":",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
">",
"2",
":",
"print",
"(",
"\"Error: You appear to be using Python %d, but \"",
"\"the Add-on SDK only supports the Python 2.x line.\"",
"%",
"(",
"sys",
".",
"version_info",
"[",
"0",
"]",
")",
")",
"return",
"import",
"mozrunner",
"if",
"'CUDDLEFISH_ROOT'",
"not",
"in",
"os",
".",
"environ",
":",
"print",
"(",
"\"Error: CUDDLEFISH_ROOT environment variable does \"",
"\"not exist! It should point to the root of the \"",
"\"Add-on SDK repository.\"",
")",
"return",
"env_root",
"=",
"os",
".",
"environ",
"[",
"'CUDDLEFISH_ROOT'",
"]",
"bin_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"env_root",
",",
"'bin'",
")",
"python_lib_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"env_root",
",",
"'python-lib'",
")",
"path",
"=",
"os",
".",
"environ",
"[",
"'PATH'",
"]",
".",
"split",
"(",
"os",
".",
"path",
".",
"pathsep",
")",
"if",
"bin_dir",
"not",
"in",
"path",
":",
"print",
"(",
"\"Warning: the Add-on SDK binary directory %s \"",
"\"does not appear to be in your PATH. You may \"",
"\"not be able to run 'cfx' or other SDK tools.\"",
"%",
"bin_dir",
")",
"if",
"python_lib_dir",
"not",
"in",
"sys",
".",
"path",
":",
"print",
"(",
"\"Warning: the Add-on SDK python-lib directory %s \"",
"\"does not appear to be in your sys.path, which \"",
"\"is odd because I'm running from it.\"",
"%",
"python_lib_dir",
")",
"if",
"not",
"mozrunner",
".",
"__path__",
"[",
"0",
"]",
".",
"startswith",
"(",
"env_root",
")",
":",
"print",
"(",
"\"Warning: your mozrunner package is installed at %s, \"",
"\"which does not seem to be located inside the Jetpack \"",
"\"SDK. This may cause problems, and you may want to \"",
"\"uninstall the other version. See bug 556562 for \"",
"\"more information.\"",
"%",
"mozrunner",
".",
"__path__",
"[",
"0",
"]",
")",
"except",
"Exception",
":",
"# Apparently we can't get the actual exception object in the",
"# 'except' clause in a way that's syntax-compatible for both",
"# Python 2.x and 3.x, so we'll have to use the traceback module.",
"import",
"traceback",
"_",
",",
"e",
",",
"_",
"=",
"sys",
".",
"exc_info",
"(",
")",
"print",
"(",
"\"Verification of Add-on SDK environment failed (%s).\"",
"%",
"e",
")",
"print",
"(",
"\"Your SDK may not work properly.\"",
")",
"return",
"print",
"(",
"\"Welcome to the Add-on SDK. For the docs, visit https://developer.mozilla.org/en-US/Add-ons/SDK\"",
")"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/addon-sdk/source/python-lib/jetpack_sdk_env.py#L8-L63 |
||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/indexes/multi.py | python | MultiIndex._maybe_match_names | (self, other) | return names | Try to find common names to attach to the result of an operation between
a and b. Return a consensus list of names if they match at least partly
or list of None if they have completely different names. | Try to find common names to attach to the result of an operation between
a and b. Return a consensus list of names if they match at least partly
or list of None if they have completely different names. | [
"Try",
"to",
"find",
"common",
"names",
"to",
"attach",
"to",
"the",
"result",
"of",
"an",
"operation",
"between",
"a",
"and",
"b",
".",
"Return",
"a",
"consensus",
"list",
"of",
"names",
"if",
"they",
"match",
"at",
"least",
"partly",
"or",
"list",
"of",
"None",
"if",
"they",
"have",
"completely",
"different",
"names",
"."
] | def _maybe_match_names(self, other):
"""
Try to find common names to attach to the result of an operation between
a and b. Return a consensus list of names if they match at least partly
or list of None if they have completely different names.
"""
if len(self.names) != len(other.names):
return [None] * len(self.names)
names = []
for a_name, b_name in zip(self.names, other.names):
if a_name == b_name:
names.append(a_name)
else:
# TODO: what if they both have np.nan for their names?
names.append(None)
return names | [
"def",
"_maybe_match_names",
"(",
"self",
",",
"other",
")",
":",
"if",
"len",
"(",
"self",
".",
"names",
")",
"!=",
"len",
"(",
"other",
".",
"names",
")",
":",
"return",
"[",
"None",
"]",
"*",
"len",
"(",
"self",
".",
"names",
")",
"names",
"=",
"[",
"]",
"for",
"a_name",
",",
"b_name",
"in",
"zip",
"(",
"self",
".",
"names",
",",
"other",
".",
"names",
")",
":",
"if",
"a_name",
"==",
"b_name",
":",
"names",
".",
"append",
"(",
"a_name",
")",
"else",
":",
"# TODO: what if they both have np.nan for their names?",
"names",
".",
"append",
"(",
"None",
")",
"return",
"names"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/indexes/multi.py#L3579-L3594 |
|
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/irc/irclib.py | python | ServerConnection.whois | (self, targets) | Send a WHOIS command. | Send a WHOIS command. | [
"Send",
"a",
"WHOIS",
"command",
"."
] | def whois(self, targets):
"""Send a WHOIS command."""
self.send_raw("WHOIS " + ",".join(targets)) | [
"def",
"whois",
"(",
"self",
",",
"targets",
")",
":",
"self",
".",
"send_raw",
"(",
"\"WHOIS \"",
"+",
"\",\"",
".",
"join",
"(",
"targets",
")",
")"
] | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/irc/irclib.py#L844-L846 |
||
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/contrib/tensor_forest/hybrid/python/hybrid_model.py | python | HybridModel.loss | (self, data, labels) | return loss | The loss to minimize while training. | The loss to minimize while training. | [
"The",
"loss",
"to",
"minimize",
"while",
"training",
"."
] | def loss(self, data, labels):
"""The loss to minimize while training."""
if self.is_regression:
diff = self.training_inference_graph(data) - math_ops.to_float(labels)
mean_squared_error = math_ops.reduce_mean(diff * diff)
root_mean_squared_error = math_ops.sqrt(mean_squared_error, name="loss")
loss = root_mean_squared_error
else:
loss = math_ops.reduce_mean(
nn_ops.sparse_softmax_cross_entropy_with_logits(
self.training_inference_graph(data),
array_ops.squeeze(math_ops.to_int32(labels))),
name="loss")
if self.regularizer:
loss += layers.apply_regularization(self.regularizer,
variables.trainable_variables())
return loss | [
"def",
"loss",
"(",
"self",
",",
"data",
",",
"labels",
")",
":",
"if",
"self",
".",
"is_regression",
":",
"diff",
"=",
"self",
".",
"training_inference_graph",
"(",
"data",
")",
"-",
"math_ops",
".",
"to_float",
"(",
"labels",
")",
"mean_squared_error",
"=",
"math_ops",
".",
"reduce_mean",
"(",
"diff",
"*",
"diff",
")",
"root_mean_squared_error",
"=",
"math_ops",
".",
"sqrt",
"(",
"mean_squared_error",
",",
"name",
"=",
"\"loss\"",
")",
"loss",
"=",
"root_mean_squared_error",
"else",
":",
"loss",
"=",
"math_ops",
".",
"reduce_mean",
"(",
"nn_ops",
".",
"sparse_softmax_cross_entropy_with_logits",
"(",
"self",
".",
"training_inference_graph",
"(",
"data",
")",
",",
"array_ops",
".",
"squeeze",
"(",
"math_ops",
".",
"to_int32",
"(",
"labels",
")",
")",
")",
",",
"name",
"=",
"\"loss\"",
")",
"if",
"self",
".",
"regularizer",
":",
"loss",
"+=",
"layers",
".",
"apply_regularization",
"(",
"self",
".",
"regularizer",
",",
"variables",
".",
"trainable_variables",
"(",
")",
")",
"return",
"loss"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/tensor_forest/hybrid/python/hybrid_model.py#L109-L126 |
|
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_pytorch/pytorch_binding/pytorch_nndct/nn/qat/modules/quantizer.py | python | TQTQuantizer.export_quant_info | (self) | return [bitwidth, int(bitwidth - 1 - ceil_log2t)] | Export trained threshold to TorchQuantizer's quant info [bitwidth, fp].
(1) TQT: qx = clip(round(fx / scale)) * scale, scale = 2^ceil(log2t) / 2^(b-1)
(2) NndctFixNeron: qx = clip(round(fx * scale)) * (1 / scale), scale = 2^fp
Let (1) equals (2), we can get
(3): 2^(b-1) / 2^ceil(log2t) = 2^fp
=> fp = b - 1 - ceil(log2t)
For more details, see nndct/include/cuda/nndct_fix_kernels.cuh::_fix_neuron_v2_device | Export trained threshold to TorchQuantizer's quant info [bitwidth, fp]. | [
"Export",
"trained",
"threshold",
"to",
"TorchQuantizer",
"s",
"quant",
"info",
"[",
"bitwidth",
"fp",
"]",
"."
] | def export_quant_info(self):
"""Export trained threshold to TorchQuantizer's quant info [bitwidth, fp].
(1) TQT: qx = clip(round(fx / scale)) * scale, scale = 2^ceil(log2t) / 2^(b-1)
(2) NndctFixNeron: qx = clip(round(fx * scale)) * (1 / scale), scale = 2^fp
Let (1) equals (2), we can get
(3): 2^(b-1) / 2^ceil(log2t) = 2^fp
=> fp = b - 1 - ceil(log2t)
For more details, see nndct/include/cuda/nndct_fix_kernels.cuh::_fix_neuron_v2_device
"""
bitwidth = self.bitwidth.item()
ceil_log2t = torch.ceil(self.log_threshold).item()
return [bitwidth, int(bitwidth - 1 - ceil_log2t)] | [
"def",
"export_quant_info",
"(",
"self",
")",
":",
"bitwidth",
"=",
"self",
".",
"bitwidth",
".",
"item",
"(",
")",
"ceil_log2t",
"=",
"torch",
".",
"ceil",
"(",
"self",
".",
"log_threshold",
")",
".",
"item",
"(",
")",
"return",
"[",
"bitwidth",
",",
"int",
"(",
"bitwidth",
"-",
"1",
"-",
"ceil_log2t",
")",
"]"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_pytorch/pytorch_binding/pytorch_nndct/nn/qat/modules/quantizer.py#L353-L366 |
|
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReflectometryILLPreprocess.py | python | ReflectometryILLPreprocess._convertToWavelength | (self, ws) | return wavelengthWS | Convert the X units of ws to wavelength. | Convert the X units of ws to wavelength. | [
"Convert",
"the",
"X",
"units",
"of",
"ws",
"to",
"wavelength",
"."
] | def _convertToWavelength(self, ws):
"""Convert the X units of ws to wavelength."""
wavelengthWSName = self._names.withSuffix('in_wavelength')
wavelengthWS = ConvertUnits(
InputWorkspace=ws,
OutputWorkspace=wavelengthWSName,
Target='Wavelength',
EMode='Elastic',
EnableLogging=self._subalgLogging
)
self._cleanup.cleanup(ws)
return wavelengthWS | [
"def",
"_convertToWavelength",
"(",
"self",
",",
"ws",
")",
":",
"wavelengthWSName",
"=",
"self",
".",
"_names",
".",
"withSuffix",
"(",
"'in_wavelength'",
")",
"wavelengthWS",
"=",
"ConvertUnits",
"(",
"InputWorkspace",
"=",
"ws",
",",
"OutputWorkspace",
"=",
"wavelengthWSName",
",",
"Target",
"=",
"'Wavelength'",
",",
"EMode",
"=",
"'Elastic'",
",",
"EnableLogging",
"=",
"self",
".",
"_subalgLogging",
")",
"self",
".",
"_cleanup",
".",
"cleanup",
"(",
"ws",
")",
"return",
"wavelengthWS"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReflectometryILLPreprocess.py#L269-L280 |
|
htcondor/htcondor | 4829724575176d1d6c936e4693dfd78a728569b0 | src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/client.py | python | IClient.OpenGettingStartedWizard | (self) | Opens getting started wizard. | Opens getting started wizard. | [
"Opens",
"getting",
"started",
"wizard",
"."
] | def OpenGettingStartedWizard(self):
'''Opens getting started wizard.
'''
self.OpenDialog('GETTINGSTARTED') | [
"def",
"OpenGettingStartedWizard",
"(",
"self",
")",
":",
"self",
".",
"OpenDialog",
"(",
"'GETTINGSTARTED'",
")"
] | https://github.com/htcondor/htcondor/blob/4829724575176d1d6c936e4693dfd78a728569b0/src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/client.py#L162-L165 |
||
floooh/oryol | eb08cffe1b1cb6b05ed14ec692bca9372cef064e | fips-files/generators/util/png.py | python | isarray | (x) | Same as ``isinstance(x, array)`` except on Python 2.2, where it
always returns ``False``. This helps PyPNG work on Python 2.2. | Same as ``isinstance(x, array)`` except on Python 2.2, where it
always returns ``False``. This helps PyPNG work on Python 2.2. | [
"Same",
"as",
"isinstance",
"(",
"x",
"array",
")",
"except",
"on",
"Python",
"2",
".",
"2",
"where",
"it",
"always",
"returns",
"False",
".",
"This",
"helps",
"PyPNG",
"work",
"on",
"Python",
"2",
".",
"2",
"."
] | def isarray(x):
"""Same as ``isinstance(x, array)`` except on Python 2.2, where it
always returns ``False``. This helps PyPNG work on Python 2.2.
"""
try:
return isinstance(x, array)
except:
return False | [
"def",
"isarray",
"(",
"x",
")",
":",
"try",
":",
"return",
"isinstance",
"(",
"x",
",",
"array",
")",
"except",
":",
"return",
"False"
] | https://github.com/floooh/oryol/blob/eb08cffe1b1cb6b05ed14ec692bca9372cef064e/fips-files/generators/util/png.py#L206-L214 |
||
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/buildscripts/eslint.py | python | ESLint._validate_version | (self, warn=False) | return False | Validate ESLint is the expected version | Validate ESLint is the expected version | [
"Validate",
"ESLint",
"is",
"the",
"expected",
"version"
] | def _validate_version(self, warn=False):
"""Validate ESLint is the expected version
"""
esl_version = callo([self.path, "--version"]).rstrip()
# Ignore the leading v in the version string.
if ESLINT_VERSION == esl_version[1:]:
return True
if warn:
print("WARNING: eslint found in path, but incorrect version found at " +
self.path + " with version: " + esl_version)
return False | [
"def",
"_validate_version",
"(",
"self",
",",
"warn",
"=",
"False",
")",
":",
"esl_version",
"=",
"callo",
"(",
"[",
"self",
".",
"path",
",",
"\"--version\"",
"]",
")",
".",
"rstrip",
"(",
")",
"# Ignore the leading v in the version string.",
"if",
"ESLINT_VERSION",
"==",
"esl_version",
"[",
"1",
":",
"]",
":",
"return",
"True",
"if",
"warn",
":",
"print",
"(",
"\"WARNING: eslint found in path, but incorrect version found at \"",
"+",
"self",
".",
"path",
"+",
"\" with version: \"",
"+",
"esl_version",
")",
"return",
"False"
] | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/eslint.py#L149-L160 |
|
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/tools/saved_model_cli.py | python | _get_outputs_tensor_info_from_meta_graph_def | (meta_graph_def,
signature_def_key) | return signature_def_utils.get_signature_def_by_key(meta_graph_def,
signature_def_key).outputs | Gets TensorInfos for all outputs of the SignatureDef.
Returns a dictionary that maps each output key to its TensorInfo for the given
signature_def_key in the meta_graph_def.
Args:
meta_graph_def: MetaGraphDef protocol buffer with the SignatureDefmap to
look up signature_def_key.
signature_def_key: A SignatureDef key string.
Returns:
A dictionary that maps output tensor keys to TensorInfos. | Gets TensorInfos for all outputs of the SignatureDef. | [
"Gets",
"TensorInfos",
"for",
"all",
"outputs",
"of",
"the",
"SignatureDef",
"."
] | def _get_outputs_tensor_info_from_meta_graph_def(meta_graph_def,
signature_def_key):
"""Gets TensorInfos for all outputs of the SignatureDef.
Returns a dictionary that maps each output key to its TensorInfo for the given
signature_def_key in the meta_graph_def.
Args:
meta_graph_def: MetaGraphDef protocol buffer with the SignatureDefmap to
look up signature_def_key.
signature_def_key: A SignatureDef key string.
Returns:
A dictionary that maps output tensor keys to TensorInfos.
"""
return signature_def_utils.get_signature_def_by_key(meta_graph_def,
signature_def_key).outputs | [
"def",
"_get_outputs_tensor_info_from_meta_graph_def",
"(",
"meta_graph_def",
",",
"signature_def_key",
")",
":",
"return",
"signature_def_utils",
".",
"get_signature_def_by_key",
"(",
"meta_graph_def",
",",
"signature_def_key",
")",
".",
"outputs"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/tools/saved_model_cli.py#L97-L113 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_gdi.py | python | GraphicsContext.GetPartialTextExtents | (*args, **kwargs) | return _gdi_.GraphicsContext_GetPartialTextExtents(*args, **kwargs) | GetPartialTextExtents(self, text) -> [widths]
Returns a list of widths from the beginning of ``text`` to the
coresponding character in ``text``. | GetPartialTextExtents(self, text) -> [widths] | [
"GetPartialTextExtents",
"(",
"self",
"text",
")",
"-",
">",
"[",
"widths",
"]"
] | def GetPartialTextExtents(*args, **kwargs):
"""
GetPartialTextExtents(self, text) -> [widths]
Returns a list of widths from the beginning of ``text`` to the
coresponding character in ``text``.
"""
return _gdi_.GraphicsContext_GetPartialTextExtents(*args, **kwargs) | [
"def",
"GetPartialTextExtents",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"GraphicsContext_GetPartialTextExtents",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L6582-L6589 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/http/cookiejar.py | python | time2netscape | (t=None) | return "%s, %02d-%s-%04d %02d:%02d:%02d GMT" % (
DAYS[dt.weekday()], dt.day, MONTHS[dt.month-1],
dt.year, dt.hour, dt.minute, dt.second) | Return a string representing time in seconds since epoch, t.
If the function is called without an argument, it will use the current
time.
The format of the returned string is like this:
Wed, DD-Mon-YYYY HH:MM:SS GMT | Return a string representing time in seconds since epoch, t. | [
"Return",
"a",
"string",
"representing",
"time",
"in",
"seconds",
"since",
"epoch",
"t",
"."
] | def time2netscape(t=None):
"""Return a string representing time in seconds since epoch, t.
If the function is called without an argument, it will use the current
time.
The format of the returned string is like this:
Wed, DD-Mon-YYYY HH:MM:SS GMT
"""
if t is None:
dt = datetime.datetime.utcnow()
else:
dt = datetime.datetime.utcfromtimestamp(t)
return "%s, %02d-%s-%04d %02d:%02d:%02d GMT" % (
DAYS[dt.weekday()], dt.day, MONTHS[dt.month-1],
dt.year, dt.hour, dt.minute, dt.second) | [
"def",
"time2netscape",
"(",
"t",
"=",
"None",
")",
":",
"if",
"t",
"is",
"None",
":",
"dt",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"else",
":",
"dt",
"=",
"datetime",
".",
"datetime",
".",
"utcfromtimestamp",
"(",
"t",
")",
"return",
"\"%s, %02d-%s-%04d %02d:%02d:%02d GMT\"",
"%",
"(",
"DAYS",
"[",
"dt",
".",
"weekday",
"(",
")",
"]",
",",
"dt",
".",
"day",
",",
"MONTHS",
"[",
"dt",
".",
"month",
"-",
"1",
"]",
",",
"dt",
".",
"year",
",",
"dt",
".",
"hour",
",",
"dt",
".",
"minute",
",",
"dt",
".",
"second",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/http/cookiejar.py#L105-L122 |
|
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/ros_comm/rosbag/src/rosbag/bag.py | python | Bag.mode | (self) | return self._mode | Get the mode. | Get the mode. | [
"Get",
"the",
"mode",
"."
] | def mode(self):
"""Get the mode."""
return self._mode | [
"def",
"mode",
"(",
"self",
")",
":",
"return",
"self",
".",
"_mode"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rosbag/src/rosbag/bag.py#L204-L206 |
|
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/sets.py | python | BaseSet.union | (self, other) | return result | Return the union of two sets as a new set.
(I.e. all elements that are in either set.) | Return the union of two sets as a new set. | [
"Return",
"the",
"union",
"of",
"two",
"sets",
"as",
"a",
"new",
"set",
"."
] | def union(self, other):
"""Return the union of two sets as a new set.
(I.e. all elements that are in either set.)
"""
result = self.__class__(self)
result._update(other)
return result | [
"def",
"union",
"(",
"self",
",",
"other",
")",
":",
"result",
"=",
"self",
".",
"__class__",
"(",
"self",
")",
"result",
".",
"_update",
"(",
"other",
")",
"return",
"result"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/sets.py#L187-L194 |
|
nghttp2/nghttp2 | a67822b3828a71b2993a68202465148c0fa3f228 | doc/_exts/rubydomain/rubydomain.py | python | RubyObject.handle_signature | (self, sig, signode) | return fullname, name_prefix | Transform a Ruby signature into RST nodes.
Returns (fully qualified name of the thing, classname if any).
If inside a class, the current class name is handled intelligently:
* it is stripped from the displayed name if present
* it is added to the full name (return value) if not present | Transform a Ruby signature into RST nodes.
Returns (fully qualified name of the thing, classname if any). | [
"Transform",
"a",
"Ruby",
"signature",
"into",
"RST",
"nodes",
".",
"Returns",
"(",
"fully",
"qualified",
"name",
"of",
"the",
"thing",
"classname",
"if",
"any",
")",
"."
] | def handle_signature(self, sig, signode):
"""
Transform a Ruby signature into RST nodes.
Returns (fully qualified name of the thing, classname if any).
If inside a class, the current class name is handled intelligently:
* it is stripped from the displayed name if present
* it is added to the full name (return value) if not present
"""
m = rb_sig_re.match(sig)
if m is None:
raise ValueError
name_prefix, name, arglist, retann = m.groups()
if not name_prefix:
name_prefix = ""
# determine module and class name (if applicable), as well as full name
modname = self.options.get(
'module', self.env.temp_data.get('rb:module'))
classname = self.env.temp_data.get('rb:class')
if self.objtype == 'global':
add_module = False
modname = None
classname = None
fullname = name
elif classname:
add_module = False
if name_prefix and name_prefix.startswith(classname):
fullname = name_prefix + name
# class name is given again in the signature
name_prefix = name_prefix[len(classname):].lstrip('.')
else:
separator = separators[self.objtype]
fullname = classname + separator + name_prefix + name
else:
add_module = True
if name_prefix:
classname = name_prefix.rstrip('.')
fullname = name_prefix + name
else:
classname = ''
fullname = name
signode['module'] = modname
signode['class'] = self.class_name = classname
signode['fullname'] = fullname
sig_prefix = self.get_signature_prefix(sig)
if sig_prefix:
signode += addnodes.desc_annotation(sig_prefix, sig_prefix)
if name_prefix:
signode += addnodes.desc_addname(name_prefix, name_prefix)
# exceptions are a special case, since they are documented in the
# 'exceptions' module.
elif add_module and self.env.config.add_module_names:
if self.objtype == 'global':
nodetext = ''
signode += addnodes.desc_addname(nodetext, nodetext)
else:
modname = self.options.get(
'module', self.env.temp_data.get('rb:module'))
if modname and modname != 'exceptions':
nodetext = modname + separators[self.objtype]
signode += addnodes.desc_addname(nodetext, nodetext)
signode += addnodes.desc_name(name, name)
if not arglist:
if self.needs_arglist():
# for callables, add an empty parameter list
signode += addnodes.desc_parameterlist()
if retann:
signode += addnodes.desc_returns(retann, retann)
return fullname, name_prefix
signode += addnodes.desc_parameterlist()
stack = [signode[-1]]
for token in rb_paramlist_re.split(arglist):
if token == '[':
opt = addnodes.desc_optional()
stack[-1] += opt
stack.append(opt)
elif token == ']':
try:
stack.pop()
except IndexError:
raise ValueError
elif not token or token == ',' or token.isspace():
pass
else:
token = token.strip()
stack[-1] += addnodes.desc_parameter(token, token)
if len(stack) != 1:
raise ValueError
if retann:
signode += addnodes.desc_returns(retann, retann)
return fullname, name_prefix | [
"def",
"handle_signature",
"(",
"self",
",",
"sig",
",",
"signode",
")",
":",
"m",
"=",
"rb_sig_re",
".",
"match",
"(",
"sig",
")",
"if",
"m",
"is",
"None",
":",
"raise",
"ValueError",
"name_prefix",
",",
"name",
",",
"arglist",
",",
"retann",
"=",
"m",
".",
"groups",
"(",
")",
"if",
"not",
"name_prefix",
":",
"name_prefix",
"=",
"\"\"",
"# determine module and class name (if applicable), as well as full name",
"modname",
"=",
"self",
".",
"options",
".",
"get",
"(",
"'module'",
",",
"self",
".",
"env",
".",
"temp_data",
".",
"get",
"(",
"'rb:module'",
")",
")",
"classname",
"=",
"self",
".",
"env",
".",
"temp_data",
".",
"get",
"(",
"'rb:class'",
")",
"if",
"self",
".",
"objtype",
"==",
"'global'",
":",
"add_module",
"=",
"False",
"modname",
"=",
"None",
"classname",
"=",
"None",
"fullname",
"=",
"name",
"elif",
"classname",
":",
"add_module",
"=",
"False",
"if",
"name_prefix",
"and",
"name_prefix",
".",
"startswith",
"(",
"classname",
")",
":",
"fullname",
"=",
"name_prefix",
"+",
"name",
"# class name is given again in the signature",
"name_prefix",
"=",
"name_prefix",
"[",
"len",
"(",
"classname",
")",
":",
"]",
".",
"lstrip",
"(",
"'.'",
")",
"else",
":",
"separator",
"=",
"separators",
"[",
"self",
".",
"objtype",
"]",
"fullname",
"=",
"classname",
"+",
"separator",
"+",
"name_prefix",
"+",
"name",
"else",
":",
"add_module",
"=",
"True",
"if",
"name_prefix",
":",
"classname",
"=",
"name_prefix",
".",
"rstrip",
"(",
"'.'",
")",
"fullname",
"=",
"name_prefix",
"+",
"name",
"else",
":",
"classname",
"=",
"''",
"fullname",
"=",
"name",
"signode",
"[",
"'module'",
"]",
"=",
"modname",
"signode",
"[",
"'class'",
"]",
"=",
"self",
".",
"class_name",
"=",
"classname",
"signode",
"[",
"'fullname'",
"]",
"=",
"fullname",
"sig_prefix",
"=",
"self",
".",
"get_signature_prefix",
"(",
"sig",
")",
"if",
"sig_prefix",
":",
"signode",
"+=",
"addnodes",
".",
"desc_annotation",
"(",
"sig_prefix",
",",
"sig_prefix",
")",
"if",
"name_prefix",
":",
"signode",
"+=",
"addnodes",
".",
"desc_addname",
"(",
"name_prefix",
",",
"name_prefix",
")",
"# exceptions are a special case, since they are documented in the",
"# 'exceptions' module.",
"elif",
"add_module",
"and",
"self",
".",
"env",
".",
"config",
".",
"add_module_names",
":",
"if",
"self",
".",
"objtype",
"==",
"'global'",
":",
"nodetext",
"=",
"''",
"signode",
"+=",
"addnodes",
".",
"desc_addname",
"(",
"nodetext",
",",
"nodetext",
")",
"else",
":",
"modname",
"=",
"self",
".",
"options",
".",
"get",
"(",
"'module'",
",",
"self",
".",
"env",
".",
"temp_data",
".",
"get",
"(",
"'rb:module'",
")",
")",
"if",
"modname",
"and",
"modname",
"!=",
"'exceptions'",
":",
"nodetext",
"=",
"modname",
"+",
"separators",
"[",
"self",
".",
"objtype",
"]",
"signode",
"+=",
"addnodes",
".",
"desc_addname",
"(",
"nodetext",
",",
"nodetext",
")",
"signode",
"+=",
"addnodes",
".",
"desc_name",
"(",
"name",
",",
"name",
")",
"if",
"not",
"arglist",
":",
"if",
"self",
".",
"needs_arglist",
"(",
")",
":",
"# for callables, add an empty parameter list",
"signode",
"+=",
"addnodes",
".",
"desc_parameterlist",
"(",
")",
"if",
"retann",
":",
"signode",
"+=",
"addnodes",
".",
"desc_returns",
"(",
"retann",
",",
"retann",
")",
"return",
"fullname",
",",
"name_prefix",
"signode",
"+=",
"addnodes",
".",
"desc_parameterlist",
"(",
")",
"stack",
"=",
"[",
"signode",
"[",
"-",
"1",
"]",
"]",
"for",
"token",
"in",
"rb_paramlist_re",
".",
"split",
"(",
"arglist",
")",
":",
"if",
"token",
"==",
"'['",
":",
"opt",
"=",
"addnodes",
".",
"desc_optional",
"(",
")",
"stack",
"[",
"-",
"1",
"]",
"+=",
"opt",
"stack",
".",
"append",
"(",
"opt",
")",
"elif",
"token",
"==",
"']'",
":",
"try",
":",
"stack",
".",
"pop",
"(",
")",
"except",
"IndexError",
":",
"raise",
"ValueError",
"elif",
"not",
"token",
"or",
"token",
"==",
"','",
"or",
"token",
".",
"isspace",
"(",
")",
":",
"pass",
"else",
":",
"token",
"=",
"token",
".",
"strip",
"(",
")",
"stack",
"[",
"-",
"1",
"]",
"+=",
"addnodes",
".",
"desc_parameter",
"(",
"token",
",",
"token",
")",
"if",
"len",
"(",
"stack",
")",
"!=",
"1",
":",
"raise",
"ValueError",
"if",
"retann",
":",
"signode",
"+=",
"addnodes",
".",
"desc_returns",
"(",
"retann",
",",
"retann",
")",
"return",
"fullname",
",",
"name_prefix"
] | https://github.com/nghttp2/nghttp2/blob/a67822b3828a71b2993a68202465148c0fa3f228/doc/_exts/rubydomain/rubydomain.py#L95-L190 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/html.py | python | HtmlCell.SetPos | (*args, **kwargs) | return _html.HtmlCell_SetPos(*args, **kwargs) | SetPos(self, int x, int y) | SetPos(self, int x, int y) | [
"SetPos",
"(",
"self",
"int",
"x",
"int",
"y",
")"
] | def SetPos(*args, **kwargs):
"""SetPos(self, int x, int y)"""
return _html.HtmlCell_SetPos(*args, **kwargs) | [
"def",
"SetPos",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_html",
".",
"HtmlCell_SetPos",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/html.py#L678-L680 |
|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/integrate/_ivp/common.py | python | validate_tol | (rtol, atol, n) | return rtol, atol | Validate tolerance values. | Validate tolerance values. | [
"Validate",
"tolerance",
"values",
"."
] | def validate_tol(rtol, atol, n):
"""Validate tolerance values."""
if rtol < 100 * EPS:
warn("`rtol` is too low, setting to {}".format(100 * EPS))
rtol = 100 * EPS
atol = np.asarray(atol)
if atol.ndim > 0 and atol.shape != (n,):
raise ValueError("`atol` has wrong shape.")
if np.any(atol < 0):
raise ValueError("`atol` must be positive.")
return rtol, atol | [
"def",
"validate_tol",
"(",
"rtol",
",",
"atol",
",",
"n",
")",
":",
"if",
"rtol",
"<",
"100",
"*",
"EPS",
":",
"warn",
"(",
"\"`rtol` is too low, setting to {}\"",
".",
"format",
"(",
"100",
"*",
"EPS",
")",
")",
"rtol",
"=",
"100",
"*",
"EPS",
"atol",
"=",
"np",
".",
"asarray",
"(",
"atol",
")",
"if",
"atol",
".",
"ndim",
">",
"0",
"and",
"atol",
".",
"shape",
"!=",
"(",
"n",
",",
")",
":",
"raise",
"ValueError",
"(",
"\"`atol` has wrong shape.\"",
")",
"if",
"np",
".",
"any",
"(",
"atol",
"<",
"0",
")",
":",
"raise",
"ValueError",
"(",
"\"`atol` must be positive.\"",
")",
"return",
"rtol",
",",
"atol"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/integrate/_ivp/common.py#L44-L57 |
|
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/_op_impl/tbe/apply_adam.py | python | _apply_adam_tbe | () | return | ApplyAdam TBE register | ApplyAdam TBE register | [
"ApplyAdam",
"TBE",
"register"
] | def _apply_adam_tbe():
"""ApplyAdam TBE register"""
return | [
"def",
"_apply_adam_tbe",
"(",
")",
":",
"return"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/tbe/apply_adam.py#L77-L79 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/idna/intranges.py | python | intranges_contain | (int_, ranges) | return False | Determine if `int_` falls into one of the ranges in `ranges`. | Determine if `int_` falls into one of the ranges in `ranges`. | [
"Determine",
"if",
"int_",
"falls",
"into",
"one",
"of",
"the",
"ranges",
"in",
"ranges",
"."
] | def intranges_contain(int_, ranges):
"""Determine if `int_` falls into one of the ranges in `ranges`."""
tuple_ = _encode_range(int_, 0)
pos = bisect.bisect_left(ranges, tuple_)
# we could be immediately ahead of a tuple (start, end)
# with start < int_ <= end
if pos > 0:
left, right = _decode_range(ranges[pos-1])
if left <= int_ < right:
return True
# or we could be immediately behind a tuple (int_, end)
if pos < len(ranges):
left, _ = _decode_range(ranges[pos])
if left == int_:
return True
return False | [
"def",
"intranges_contain",
"(",
"int_",
",",
"ranges",
")",
":",
"tuple_",
"=",
"_encode_range",
"(",
"int_",
",",
"0",
")",
"pos",
"=",
"bisect",
".",
"bisect_left",
"(",
"ranges",
",",
"tuple_",
")",
"# we could be immediately ahead of a tuple (start, end)",
"# with start < int_ <= end",
"if",
"pos",
">",
"0",
":",
"left",
",",
"right",
"=",
"_decode_range",
"(",
"ranges",
"[",
"pos",
"-",
"1",
"]",
")",
"if",
"left",
"<=",
"int_",
"<",
"right",
":",
"return",
"True",
"# or we could be immediately behind a tuple (int_, end)",
"if",
"pos",
"<",
"len",
"(",
"ranges",
")",
":",
"left",
",",
"_",
"=",
"_decode_range",
"(",
"ranges",
"[",
"pos",
"]",
")",
"if",
"left",
"==",
"int_",
":",
"return",
"True",
"return",
"False"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/idna/intranges.py#L38-L53 |
|
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | third_party/numpy/files/numpy/ma/core.py | python | MaskedArray._get_recordmask | (self) | return np.all(flatten_structured_array(_mask), axis= -1) | Return the mask of the records.
A record is masked when all the fields are masked. | Return the mask of the records.
A record is masked when all the fields are masked. | [
"Return",
"the",
"mask",
"of",
"the",
"records",
".",
"A",
"record",
"is",
"masked",
"when",
"all",
"the",
"fields",
"are",
"masked",
"."
] | def _get_recordmask(self):
"""
Return the mask of the records.
A record is masked when all the fields are masked.
"""
_mask = ndarray.__getattribute__(self, '_mask').view(ndarray)
if _mask.dtype.names is None:
return _mask
return np.all(flatten_structured_array(_mask), axis= -1) | [
"def",
"_get_recordmask",
"(",
"self",
")",
":",
"_mask",
"=",
"ndarray",
".",
"__getattribute__",
"(",
"self",
",",
"'_mask'",
")",
".",
"view",
"(",
"ndarray",
")",
"if",
"_mask",
".",
"dtype",
".",
"names",
"is",
"None",
":",
"return",
"_mask",
"return",
"np",
".",
"all",
"(",
"flatten_structured_array",
"(",
"_mask",
")",
",",
"axis",
"=",
"-",
"1",
")"
] | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/ma/core.py#L3133-L3142 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/propgrid.py | python | NewStringProperty | (*args, **kwargs) | return _propgrid.NewStringProperty(*args, **kwargs) | NewStringProperty(String label=(*wxPGProperty::sm_wxPG_LABEL), String name=(*wxPGProperty::sm_wxPG_LABEL),
String value=wxEmptyString) -> PGProperty | NewStringProperty(String label=(*wxPGProperty::sm_wxPG_LABEL), String name=(*wxPGProperty::sm_wxPG_LABEL),
String value=wxEmptyString) -> PGProperty | [
"NewStringProperty",
"(",
"String",
"label",
"=",
"(",
"*",
"wxPGProperty",
"::",
"sm_wxPG_LABEL",
")",
"String",
"name",
"=",
"(",
"*",
"wxPGProperty",
"::",
"sm_wxPG_LABEL",
")",
"String",
"value",
"=",
"wxEmptyString",
")",
"-",
">",
"PGProperty"
] | def NewStringProperty(*args, **kwargs):
"""
NewStringProperty(String label=(*wxPGProperty::sm_wxPG_LABEL), String name=(*wxPGProperty::sm_wxPG_LABEL),
String value=wxEmptyString) -> PGProperty
"""
return _propgrid.NewStringProperty(*args, **kwargs) | [
"def",
"NewStringProperty",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"NewStringProperty",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L3657-L3662 |
|
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/debug/cli/curses_ui.py | python | CursesUI._show_array_indices | (self) | Show array indices for the lines at the top and bottom of the output.
For the top line and bottom line of the output display area, show the
element indices of the array being displayed.
Returns:
If either the top of the bottom row has any matching array indices,
a dict from line index (0 being the top of the display area, -1
being the bottom of the display area) to array element indices. For
example:
{0: [0, 0], -1: [10, 0]}
Otherwise, None. | Show array indices for the lines at the top and bottom of the output. | [
"Show",
"array",
"indices",
"for",
"the",
"lines",
"at",
"the",
"top",
"and",
"bottom",
"of",
"the",
"output",
"."
] | def _show_array_indices(self):
"""Show array indices for the lines at the top and bottom of the output.
For the top line and bottom line of the output display area, show the
element indices of the array being displayed.
Returns:
If either the top of the bottom row has any matching array indices,
a dict from line index (0 being the top of the display area, -1
being the bottom of the display area) to array element indices. For
example:
{0: [0, 0], -1: [10, 0]}
Otherwise, None.
"""
indices_top = self._show_array_index_at_line(0)
output_top = self._output_top_row
if self._main_menu_pad:
output_top += 1
bottom_line_index = (
self._output_pad_screen_location.bottom - output_top - 1)
indices_bottom = self._show_array_index_at_line(bottom_line_index)
if indices_top or indices_bottom:
return {0: indices_top, -1: indices_bottom}
else:
return None | [
"def",
"_show_array_indices",
"(",
"self",
")",
":",
"indices_top",
"=",
"self",
".",
"_show_array_index_at_line",
"(",
"0",
")",
"output_top",
"=",
"self",
".",
"_output_top_row",
"if",
"self",
".",
"_main_menu_pad",
":",
"output_top",
"+=",
"1",
"bottom_line_index",
"=",
"(",
"self",
".",
"_output_pad_screen_location",
".",
"bottom",
"-",
"output_top",
"-",
"1",
")",
"indices_bottom",
"=",
"self",
".",
"_show_array_index_at_line",
"(",
"bottom_line_index",
")",
"if",
"indices_top",
"or",
"indices_bottom",
":",
"return",
"{",
"0",
":",
"indices_top",
",",
"-",
"1",
":",
"indices_bottom",
"}",
"else",
":",
"return",
"None"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/debug/cli/curses_ui.py#L1455-L1482 |
||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/wsgiref/headers.py | python | _formatparam | (param, value=None, quote=1) | Convenience function to format and return a key=value pair.
This will quote the value if needed or if quote is true. | Convenience function to format and return a key=value pair. | [
"Convenience",
"function",
"to",
"format",
"and",
"return",
"a",
"key",
"=",
"value",
"pair",
"."
] | def _formatparam(param, value=None, quote=1):
"""Convenience function to format and return a key=value pair.
This will quote the value if needed or if quote is true.
"""
if value is not None and len(value) > 0:
if quote or tspecials.search(value):
value = value.replace('\\', '\\\\').replace('"', r'\"')
return '%s="%s"' % (param, value)
else:
return '%s=%s' % (param, value)
else:
return param | [
"def",
"_formatparam",
"(",
"param",
",",
"value",
"=",
"None",
",",
"quote",
"=",
"1",
")",
":",
"if",
"value",
"is",
"not",
"None",
"and",
"len",
"(",
"value",
")",
">",
"0",
":",
"if",
"quote",
"or",
"tspecials",
".",
"search",
"(",
"value",
")",
":",
"value",
"=",
"value",
".",
"replace",
"(",
"'\\\\'",
",",
"'\\\\\\\\'",
")",
".",
"replace",
"(",
"'\"'",
",",
"r'\\\"'",
")",
"return",
"'%s=\"%s\"'",
"%",
"(",
"param",
",",
"value",
")",
"else",
":",
"return",
"'%s=%s'",
"%",
"(",
"param",
",",
"value",
")",
"else",
":",
"return",
"param"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/wsgiref/headers.py#L13-L25 |
||
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/ninja/misc/ninja_syntax.py | python | Writer._line | (self, text, indent=0) | Write 'text' word-wrapped at self.width characters. | Write 'text' word-wrapped at self.width characters. | [
"Write",
"text",
"word",
"-",
"wrapped",
"at",
"self",
".",
"width",
"characters",
"."
] | def _line(self, text, indent=0):
"""Write 'text' word-wrapped at self.width characters."""
leading_space = ' ' * indent
while len(leading_space) + len(text) > self.width:
# The text is too wide; wrap if possible.
# Find the rightmost space that would obey our width constraint and
# that's not an escaped space.
available_space = self.width - len(leading_space) - len(' $')
space = available_space
while True:
space = text.rfind(' ', 0, space)
if (space < 0 or
self._count_dollars_before_index(text, space) % 2 == 0):
break
if space < 0:
# No such space; just use the first unescaped space we can find.
space = available_space - 1
while True:
space = text.find(' ', space + 1)
if (space < 0 or
self._count_dollars_before_index(text, space) % 2 == 0):
break
if space < 0:
# Give up on breaking.
break
self.output.write(leading_space + text[0:space] + ' $\n')
text = text[space+1:]
# Subsequent lines are continuations, so indent them.
leading_space = ' ' * (indent+2)
self.output.write(leading_space + text + '\n') | [
"def",
"_line",
"(",
"self",
",",
"text",
",",
"indent",
"=",
"0",
")",
":",
"leading_space",
"=",
"' '",
"*",
"indent",
"while",
"len",
"(",
"leading_space",
")",
"+",
"len",
"(",
"text",
")",
">",
"self",
".",
"width",
":",
"# The text is too wide; wrap if possible.",
"# Find the rightmost space that would obey our width constraint and",
"# that's not an escaped space.",
"available_space",
"=",
"self",
".",
"width",
"-",
"len",
"(",
"leading_space",
")",
"-",
"len",
"(",
"' $'",
")",
"space",
"=",
"available_space",
"while",
"True",
":",
"space",
"=",
"text",
".",
"rfind",
"(",
"' '",
",",
"0",
",",
"space",
")",
"if",
"(",
"space",
"<",
"0",
"or",
"self",
".",
"_count_dollars_before_index",
"(",
"text",
",",
"space",
")",
"%",
"2",
"==",
"0",
")",
":",
"break",
"if",
"space",
"<",
"0",
":",
"# No such space; just use the first unescaped space we can find.",
"space",
"=",
"available_space",
"-",
"1",
"while",
"True",
":",
"space",
"=",
"text",
".",
"find",
"(",
"' '",
",",
"space",
"+",
"1",
")",
"if",
"(",
"space",
"<",
"0",
"or",
"self",
".",
"_count_dollars_before_index",
"(",
"text",
",",
"space",
")",
"%",
"2",
"==",
"0",
")",
":",
"break",
"if",
"space",
"<",
"0",
":",
"# Give up on breaking.",
"break",
"self",
".",
"output",
".",
"write",
"(",
"leading_space",
"+",
"text",
"[",
"0",
":",
"space",
"]",
"+",
"' $\\n'",
")",
"text",
"=",
"text",
"[",
"space",
"+",
"1",
":",
"]",
"# Subsequent lines are continuations, so indent them.",
"leading_space",
"=",
"' '",
"*",
"(",
"indent",
"+",
"2",
")",
"self",
".",
"output",
".",
"write",
"(",
"leading_space",
"+",
"text",
"+",
"'\\n'",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/ninja/misc/ninja_syntax.py#L114-L148 |
||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/core/arrays/datetimelike.py | python | DatetimeLikeArrayMixin._add_delta | (self, other) | return new_values | Add a timedelta-like, Tick or TimedeltaIndex-like object
to self, yielding an int64 numpy array
Parameters
----------
delta : {timedelta, np.timedelta64, Tick,
TimedeltaIndex, ndarray[timedelta64]}
Returns
-------
result : ndarray[int64]
Notes
-----
The result's name is set outside of _add_delta by the calling
method (__add__ or __sub__), if necessary (i.e. for Indexes). | Add a timedelta-like, Tick or TimedeltaIndex-like object
to self, yielding an int64 numpy array | [
"Add",
"a",
"timedelta",
"-",
"like",
"Tick",
"or",
"TimedeltaIndex",
"-",
"like",
"object",
"to",
"self",
"yielding",
"an",
"int64",
"numpy",
"array"
] | def _add_delta(self, other):
"""
Add a timedelta-like, Tick or TimedeltaIndex-like object
to self, yielding an int64 numpy array
Parameters
----------
delta : {timedelta, np.timedelta64, Tick,
TimedeltaIndex, ndarray[timedelta64]}
Returns
-------
result : ndarray[int64]
Notes
-----
The result's name is set outside of _add_delta by the calling
method (__add__ or __sub__), if necessary (i.e. for Indexes).
"""
if isinstance(other, (Tick, timedelta, np.timedelta64)):
new_values = self._add_timedeltalike_scalar(other)
elif is_timedelta64_dtype(other):
# ndarray[timedelta64] or TimedeltaArray/index
new_values = self._add_delta_tdi(other)
return new_values | [
"def",
"_add_delta",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"(",
"Tick",
",",
"timedelta",
",",
"np",
".",
"timedelta64",
")",
")",
":",
"new_values",
"=",
"self",
".",
"_add_timedeltalike_scalar",
"(",
"other",
")",
"elif",
"is_timedelta64_dtype",
"(",
"other",
")",
":",
"# ndarray[timedelta64] or TimedeltaArray/index",
"new_values",
"=",
"self",
".",
"_add_delta_tdi",
"(",
"other",
")",
"return",
"new_values"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/arrays/datetimelike.py#L941-L966 |
|
Harick1/caffe-yolo | eea92bf3ddfe4d0ff6b0b3ba9b15c029a83ed9a3 | scripts/cpp_lint.py | python | ProcessFile | (filename, vlevel, extra_check_functions=[]) | Does google-lint on a single file.
Args:
filename: The name of the file to parse.
vlevel: The level of errors to report. Every error of confidence
>= verbose_level will be reported. 0 is a good default.
extra_check_functions: An array of additional check functions that will be
run on each source line. Each function takes 4
arguments: filename, clean_lines, line, error | Does google-lint on a single file. | [
"Does",
"google",
"-",
"lint",
"on",
"a",
"single",
"file",
"."
] | def ProcessFile(filename, vlevel, extra_check_functions=[]):
"""Does google-lint on a single file.
Args:
filename: The name of the file to parse.
vlevel: The level of errors to report. Every error of confidence
>= verbose_level will be reported. 0 is a good default.
extra_check_functions: An array of additional check functions that will be
run on each source line. Each function takes 4
arguments: filename, clean_lines, line, error
"""
_SetVerboseLevel(vlevel)
try:
# Support the UNIX convention of using "-" for stdin. Note that
# we are not opening the file with universal newline support
# (which codecs doesn't support anyway), so the resulting lines do
# contain trailing '\r' characters if we are reading a file that
# has CRLF endings.
# If after the split a trailing '\r' is present, it is removed
# below. If it is not expected to be present (i.e. os.linesep !=
# '\r\n' as in Windows), a warning is issued below if this file
# is processed.
if filename == '-':
lines = codecs.StreamReaderWriter(sys.stdin,
codecs.getreader('utf8'),
codecs.getwriter('utf8'),
'replace').read().split('\n')
else:
lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n')
carriage_return_found = False
# Remove trailing '\r'.
for linenum in range(len(lines)):
if lines[linenum].endswith('\r'):
lines[linenum] = lines[linenum].rstrip('\r')
carriage_return_found = True
except IOError:
sys.stderr.write(
"Skipping input '%s': Can't open for reading\n" % filename)
return
# Note, if no dot is found, this will give the entire filename as the ext.
file_extension = filename[filename.rfind('.') + 1:]
# When reading from stdin, the extension is unknown, so no cpplint tests
# should rely on the extension.
if filename != '-' and file_extension not in _valid_extensions:
sys.stderr.write('Ignoring %s; not a valid file name '
'(%s)\n' % (filename, ', '.join(_valid_extensions)))
else:
ProcessFileData(filename, file_extension, lines, Error,
extra_check_functions)
if carriage_return_found and os.linesep != '\r\n':
# Use 0 for linenum since outputting only one error for potentially
# several lines.
Error(filename, 0, 'whitespace/newline', 1,
'One or more unexpected \\r (^M) found;'
'better to use only a \\n')
sys.stderr.write('Done processing %s\n' % filename) | [
"def",
"ProcessFile",
"(",
"filename",
",",
"vlevel",
",",
"extra_check_functions",
"=",
"[",
"]",
")",
":",
"_SetVerboseLevel",
"(",
"vlevel",
")",
"try",
":",
"# Support the UNIX convention of using \"-\" for stdin. Note that",
"# we are not opening the file with universal newline support",
"# (which codecs doesn't support anyway), so the resulting lines do",
"# contain trailing '\\r' characters if we are reading a file that",
"# has CRLF endings.",
"# If after the split a trailing '\\r' is present, it is removed",
"# below. If it is not expected to be present (i.e. os.linesep !=",
"# '\\r\\n' as in Windows), a warning is issued below if this file",
"# is processed.",
"if",
"filename",
"==",
"'-'",
":",
"lines",
"=",
"codecs",
".",
"StreamReaderWriter",
"(",
"sys",
".",
"stdin",
",",
"codecs",
".",
"getreader",
"(",
"'utf8'",
")",
",",
"codecs",
".",
"getwriter",
"(",
"'utf8'",
")",
",",
"'replace'",
")",
".",
"read",
"(",
")",
".",
"split",
"(",
"'\\n'",
")",
"else",
":",
"lines",
"=",
"codecs",
".",
"open",
"(",
"filename",
",",
"'r'",
",",
"'utf8'",
",",
"'replace'",
")",
".",
"read",
"(",
")",
".",
"split",
"(",
"'\\n'",
")",
"carriage_return_found",
"=",
"False",
"# Remove trailing '\\r'.",
"for",
"linenum",
"in",
"range",
"(",
"len",
"(",
"lines",
")",
")",
":",
"if",
"lines",
"[",
"linenum",
"]",
".",
"endswith",
"(",
"'\\r'",
")",
":",
"lines",
"[",
"linenum",
"]",
"=",
"lines",
"[",
"linenum",
"]",
".",
"rstrip",
"(",
"'\\r'",
")",
"carriage_return_found",
"=",
"True",
"except",
"IOError",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"Skipping input '%s': Can't open for reading\\n\"",
"%",
"filename",
")",
"return",
"# Note, if no dot is found, this will give the entire filename as the ext.",
"file_extension",
"=",
"filename",
"[",
"filename",
".",
"rfind",
"(",
"'.'",
")",
"+",
"1",
":",
"]",
"# When reading from stdin, the extension is unknown, so no cpplint tests",
"# should rely on the extension.",
"if",
"filename",
"!=",
"'-'",
"and",
"file_extension",
"not",
"in",
"_valid_extensions",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'Ignoring %s; not a valid file name '",
"'(%s)\\n'",
"%",
"(",
"filename",
",",
"', '",
".",
"join",
"(",
"_valid_extensions",
")",
")",
")",
"else",
":",
"ProcessFileData",
"(",
"filename",
",",
"file_extension",
",",
"lines",
",",
"Error",
",",
"extra_check_functions",
")",
"if",
"carriage_return_found",
"and",
"os",
".",
"linesep",
"!=",
"'\\r\\n'",
":",
"# Use 0 for linenum since outputting only one error for potentially",
"# several lines.",
"Error",
"(",
"filename",
",",
"0",
",",
"'whitespace/newline'",
",",
"1",
",",
"'One or more unexpected \\\\r (^M) found;'",
"'better to use only a \\\\n'",
")",
"sys",
".",
"stderr",
".",
"write",
"(",
"'Done processing %s\\n'",
"%",
"filename",
")"
] | https://github.com/Harick1/caffe-yolo/blob/eea92bf3ddfe4d0ff6b0b3ba9b15c029a83ed9a3/scripts/cpp_lint.py#L4689-L4754 |
||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/build/waf-1.7.13/waflib/Tools/dbus.py | python | add_dbus_file | (self, filename, prefix, mode) | Add a dbus file to the list of dbus files to process. Store them in the attribute *dbus_lst*.
:param filename: xml file to compile
:type filename: string
:param prefix: dbus binding tool prefix (--prefix=prefix)
:type prefix: string
:param mode: dbus binding tool mode (--mode=mode)
:type mode: string | Add a dbus file to the list of dbus files to process. Store them in the attribute *dbus_lst*. | [
"Add",
"a",
"dbus",
"file",
"to",
"the",
"list",
"of",
"dbus",
"files",
"to",
"process",
".",
"Store",
"them",
"in",
"the",
"attribute",
"*",
"dbus_lst",
"*",
"."
] | def add_dbus_file(self, filename, prefix, mode):
"""
Add a dbus file to the list of dbus files to process. Store them in the attribute *dbus_lst*.
:param filename: xml file to compile
:type filename: string
:param prefix: dbus binding tool prefix (--prefix=prefix)
:type prefix: string
:param mode: dbus binding tool mode (--mode=mode)
:type mode: string
"""
if not hasattr(self, 'dbus_lst'):
self.dbus_lst = []
if not 'process_dbus' in self.meths:
self.meths.append('process_dbus')
self.dbus_lst.append([filename, prefix, mode]) | [
"def",
"add_dbus_file",
"(",
"self",
",",
"filename",
",",
"prefix",
",",
"mode",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'dbus_lst'",
")",
":",
"self",
".",
"dbus_lst",
"=",
"[",
"]",
"if",
"not",
"'process_dbus'",
"in",
"self",
".",
"meths",
":",
"self",
".",
"meths",
".",
"append",
"(",
"'process_dbus'",
")",
"self",
".",
"dbus_lst",
".",
"append",
"(",
"[",
"filename",
",",
"prefix",
",",
"mode",
"]",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/Tools/dbus.py#L26-L41 |
||
intel/llvm | e6d0547e9d99b5a56430c4749f6c7e328bf221ab | lldb/third_party/Python/module/pexpect-4.6/pexpect/pty_spawn.py | python | spawn.eof | (self) | return self.flag_eof | This returns True if the EOF exception was ever raised. | This returns True if the EOF exception was ever raised. | [
"This",
"returns",
"True",
"if",
"the",
"EOF",
"exception",
"was",
"ever",
"raised",
"."
] | def eof(self):
'''This returns True if the EOF exception was ever raised.
'''
return self.flag_eof | [
"def",
"eof",
"(",
"self",
")",
":",
"return",
"self",
".",
"flag_eof"
] | https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/lldb/third_party/Python/module/pexpect-4.6/pexpect/pty_spawn.py#L604-L607 |
|
nvdla/sw | 79538ba1b52b040a4a4645f630e457fa01839e90 | umd/external/protobuf-2.6/python/google/protobuf/message.py | python | Message.__setstate__ | (self, state) | Support the pickle protocol. | Support the pickle protocol. | [
"Support",
"the",
"pickle",
"protocol",
"."
] | def __setstate__(self, state):
"""Support the pickle protocol."""
self.__init__()
self.ParseFromString(state['serialized']) | [
"def",
"__setstate__",
"(",
"self",
",",
"state",
")",
":",
"self",
".",
"__init__",
"(",
")",
"self",
".",
"ParseFromString",
"(",
"state",
"[",
"'serialized'",
"]",
")"
] | https://github.com/nvdla/sw/blob/79538ba1b52b040a4a4645f630e457fa01839e90/umd/external/protobuf-2.6/python/google/protobuf/message.py#L281-L284 |
||
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/MooseDocs/base/Extension.py | python | Extension.postWrite | (self, page) | Called after renderer has written content.
Inputs:
page[pages.Source]: The source object representing the content | Called after renderer has written content. | [
"Called",
"after",
"renderer",
"has",
"written",
"content",
"."
] | def postWrite(self, page):
"""
Called after renderer has written content.
Inputs:
page[pages.Source]: The source object representing the content
"""
pass | [
"def",
"postWrite",
"(",
"self",
",",
"page",
")",
":",
"pass"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/MooseDocs/base/Extension.py#L160-L167 |
||
openmm/openmm | cb293447c4fc8b03976dfe11399f107bab70f3d9 | wrappers/python/openmm/app/internal/pdbstructure.py | python | Atom.iter_positions | (self) | Iterate over atomic positions. Returns Quantity(Vec3(), unit) objects, unlike
iter_locations, which returns Atom.Location objects. | Iterate over atomic positions. Returns Quantity(Vec3(), unit) objects, unlike
iter_locations, which returns Atom.Location objects. | [
"Iterate",
"over",
"atomic",
"positions",
".",
"Returns",
"Quantity",
"(",
"Vec3",
"()",
"unit",
")",
"objects",
"unlike",
"iter_locations",
"which",
"returns",
"Atom",
".",
"Location",
"objects",
"."
] | def iter_positions(self):
"""
Iterate over atomic positions. Returns Quantity(Vec3(), unit) objects, unlike
iter_locations, which returns Atom.Location objects.
"""
for loc in self.iter_locations():
yield loc.position | [
"def",
"iter_positions",
"(",
"self",
")",
":",
"for",
"loc",
"in",
"self",
".",
"iter_locations",
"(",
")",
":",
"yield",
"loc",
".",
"position"
] | https://github.com/openmm/openmm/blob/cb293447c4fc8b03976dfe11399f107bab70f3d9/wrappers/python/openmm/app/internal/pdbstructure.py#L828-L834 |
||
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/idl/idl/syntax.py | python | FieldTypeArray.__init__ | (self, element_type) | Construct a FieldTypeArray. | Construct a FieldTypeArray. | [
"Construct",
"a",
"FieldTypeArray",
"."
] | def __init__(self, element_type):
# type: (FieldTypeSingle) -> None
"""Construct a FieldTypeArray."""
self.element_type = element_type # type: FieldTypeSingle
super(FieldTypeArray, self).__init__(element_type.file_name, element_type.line,
element_type.column) | [
"def",
"__init__",
"(",
"self",
",",
"element_type",
")",
":",
"# type: (FieldTypeSingle) -> None",
"self",
".",
"element_type",
"=",
"element_type",
"# type: FieldTypeSingle",
"super",
"(",
"FieldTypeArray",
",",
"self",
")",
".",
"__init__",
"(",
"element_type",
".",
"file_name",
",",
"element_type",
".",
"line",
",",
"element_type",
".",
"column",
")"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/idl/idl/syntax.py#L747-L753 |
||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/media.py | python | MediaCtrl.GetPlaybackRate | (*args, **kwargs) | return _media.MediaCtrl_GetPlaybackRate(*args, **kwargs) | GetPlaybackRate(self) -> double | GetPlaybackRate(self) -> double | [
"GetPlaybackRate",
"(",
"self",
")",
"-",
">",
"double"
] | def GetPlaybackRate(*args, **kwargs):
"""GetPlaybackRate(self) -> double"""
return _media.MediaCtrl_GetPlaybackRate(*args, **kwargs) | [
"def",
"GetPlaybackRate",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_media",
".",
"MediaCtrl_GetPlaybackRate",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/media.py#L125-L127 |
|
LisaAnne/lisa-caffe-public | 49b8643ddef23a4f6120017968de30c45e693f59 | python/caffe/io.py | python | blobproto_to_array | (blob, return_diff=False) | Convert a blob proto to an array. In default, we will just return the data,
unless return_diff is True, in which case we will return the diff. | Convert a blob proto to an array. In default, we will just return the data,
unless return_diff is True, in which case we will return the diff. | [
"Convert",
"a",
"blob",
"proto",
"to",
"an",
"array",
".",
"In",
"default",
"we",
"will",
"just",
"return",
"the",
"data",
"unless",
"return_diff",
"is",
"True",
"in",
"which",
"case",
"we",
"will",
"return",
"the",
"diff",
"."
] | def blobproto_to_array(blob, return_diff=False):
"""Convert a blob proto to an array. In default, we will just return the data,
unless return_diff is True, in which case we will return the diff.
"""
if return_diff:
return np.array(blob.diff).reshape(
blob.num, blob.channels, blob.height, blob.width)
else:
return np.array(blob.data).reshape(
blob.num, blob.channels, blob.height, blob.width) | [
"def",
"blobproto_to_array",
"(",
"blob",
",",
"return_diff",
"=",
"False",
")",
":",
"if",
"return_diff",
":",
"return",
"np",
".",
"array",
"(",
"blob",
".",
"diff",
")",
".",
"reshape",
"(",
"blob",
".",
"num",
",",
"blob",
".",
"channels",
",",
"blob",
".",
"height",
",",
"blob",
".",
"width",
")",
"else",
":",
"return",
"np",
".",
"array",
"(",
"blob",
".",
"data",
")",
".",
"reshape",
"(",
"blob",
".",
"num",
",",
"blob",
".",
"channels",
",",
"blob",
".",
"height",
",",
"blob",
".",
"width",
")"
] | https://github.com/LisaAnne/lisa-caffe-public/blob/49b8643ddef23a4f6120017968de30c45e693f59/python/caffe/io.py#L18-L27 |
||
panda3d/panda3d | 833ad89ebad58395d0af0b7ec08538e5e4308265 | direct/src/controls/GravityWalker.py | python | GravityWalker.setAvatarPhysicsIndicator | (self, indicator) | indicator is a NodePath | indicator is a NodePath | [
"indicator",
"is",
"a",
"NodePath"
] | def setAvatarPhysicsIndicator(self, indicator):
"""
indicator is a NodePath
"""
assert self.notify.debugStateCall(self)
self.cWallSphereNodePath.show() | [
"def",
"setAvatarPhysicsIndicator",
"(",
"self",
",",
"indicator",
")",
":",
"assert",
"self",
".",
"notify",
".",
"debugStateCall",
"(",
"self",
")",
"self",
".",
"cWallSphereNodePath",
".",
"show",
"(",
")"
] | https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/controls/GravityWalker.py#L255-L260 |
||
yun-liu/RCF | 91bfb054ad04187dbbe21e539e165ad9bd3ff00b | scripts/cpp_lint.py | python | _CppLintState.SetFilters | (self, filters) | Sets the error-message filters.
These filters are applied when deciding whether to emit a given
error message.
Args:
filters: A string of comma-separated filters (eg "+whitespace/indent").
Each filter should start with + or -; else we die.
Raises:
ValueError: The comma-separated filters did not all start with '+' or '-'.
E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter" | Sets the error-message filters. | [
"Sets",
"the",
"error",
"-",
"message",
"filters",
"."
] | def SetFilters(self, filters):
"""Sets the error-message filters.
These filters are applied when deciding whether to emit a given
error message.
Args:
filters: A string of comma-separated filters (eg "+whitespace/indent").
Each filter should start with + or -; else we die.
Raises:
ValueError: The comma-separated filters did not all start with '+' or '-'.
E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter"
"""
# Default filters always have less priority than the flag ones.
self.filters = _DEFAULT_FILTERS[:]
for filt in filters.split(','):
clean_filt = filt.strip()
if clean_filt:
self.filters.append(clean_filt)
for filt in self.filters:
if not (filt.startswith('+') or filt.startswith('-')):
raise ValueError('Every filter in --filters must start with + or -'
' (%s does not)' % filt) | [
"def",
"SetFilters",
"(",
"self",
",",
"filters",
")",
":",
"# Default filters always have less priority than the flag ones.",
"self",
".",
"filters",
"=",
"_DEFAULT_FILTERS",
"[",
":",
"]",
"for",
"filt",
"in",
"filters",
".",
"split",
"(",
"','",
")",
":",
"clean_filt",
"=",
"filt",
".",
"strip",
"(",
")",
"if",
"clean_filt",
":",
"self",
".",
"filters",
".",
"append",
"(",
"clean_filt",
")",
"for",
"filt",
"in",
"self",
".",
"filters",
":",
"if",
"not",
"(",
"filt",
".",
"startswith",
"(",
"'+'",
")",
"or",
"filt",
".",
"startswith",
"(",
"'-'",
")",
")",
":",
"raise",
"ValueError",
"(",
"'Every filter in --filters must start with + or -'",
"' (%s does not)'",
"%",
"filt",
")"
] | https://github.com/yun-liu/RCF/blob/91bfb054ad04187dbbe21e539e165ad9bd3ff00b/scripts/cpp_lint.py#L717-L740 |
||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/plot.py | python | PlotCanvas.GetPointLabelFunc | (self) | return self._pointLabelFunc | Returns pointLabel Drawing Function | Returns pointLabel Drawing Function | [
"Returns",
"pointLabel",
"Drawing",
"Function"
] | def GetPointLabelFunc(self):
"""Returns pointLabel Drawing Function"""
return self._pointLabelFunc | [
"def",
"GetPointLabelFunc",
"(",
"self",
")",
":",
"return",
"self",
".",
"_pointLabelFunc"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/plot.py#L994-L996 |
|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/hotshot/__init__.py | python | Profile.fileno | (self) | return self._prof.fileno() | Return the file descriptor of the profiler's log file. | Return the file descriptor of the profiler's log file. | [
"Return",
"the",
"file",
"descriptor",
"of",
"the",
"profiler",
"s",
"log",
"file",
"."
] | def fileno(self):
"""Return the file descriptor of the profiler's log file."""
return self._prof.fileno() | [
"def",
"fileno",
"(",
"self",
")",
":",
"return",
"self",
".",
"_prof",
".",
"fileno",
"(",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/hotshot/__init__.py#L30-L32 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/flatmenu.py | python | FlatMenu.OnMouseMove | (self, event) | Handles the ``wx.EVT_MOTION`` event for :class:`FlatMenu`.
:param `event`: a :class:`MouseEvent` event to be processed. | Handles the ``wx.EVT_MOTION`` event for :class:`FlatMenu`. | [
"Handles",
"the",
"wx",
".",
"EVT_MOTION",
"event",
"for",
":",
"class",
":",
"FlatMenu",
"."
] | def OnMouseMove(self, event):
"""
Handles the ``wx.EVT_MOTION`` event for :class:`FlatMenu`.
:param `event`: a :class:`MouseEvent` event to be processed.
"""
if "__WXMSW__" in wx.Platform:
# Ignore dummy mouse move events
pt = wx.GetMousePosition()
if self._mousePtAtStartup == pt:
return
pos = event.GetPosition()
# we need to ignore extra mouse events: example when this happens is when
# the mouse is on the menu and we open a submenu from keyboard - Windows
# then sends us a dummy mouse move event, we (correctly) determine that it
# happens in the parent menu and so immediately close the just opened
# submenunot
if "__WXMSW__" in wx.Platform:
ptCur = self.ClientToScreen(pos)
if ptCur == self._ptLast:
return
self._ptLast = ptCur
# first let the scrollbar handle it
self.TryScrollButtons(event)
self.ProcessMouseMove(pos) | [
"def",
"OnMouseMove",
"(",
"self",
",",
"event",
")",
":",
"if",
"\"__WXMSW__\"",
"in",
"wx",
".",
"Platform",
":",
"# Ignore dummy mouse move events",
"pt",
"=",
"wx",
".",
"GetMousePosition",
"(",
")",
"if",
"self",
".",
"_mousePtAtStartup",
"==",
"pt",
":",
"return",
"pos",
"=",
"event",
".",
"GetPosition",
"(",
")",
"# we need to ignore extra mouse events: example when this happens is when",
"# the mouse is on the menu and we open a submenu from keyboard - Windows",
"# then sends us a dummy mouse move event, we (correctly) determine that it",
"# happens in the parent menu and so immediately close the just opened",
"# submenunot",
"if",
"\"__WXMSW__\"",
"in",
"wx",
".",
"Platform",
":",
"ptCur",
"=",
"self",
".",
"ClientToScreen",
"(",
"pos",
")",
"if",
"ptCur",
"==",
"self",
".",
"_ptLast",
":",
"return",
"self",
".",
"_ptLast",
"=",
"ptCur",
"# first let the scrollbar handle it",
"self",
".",
"TryScrollButtons",
"(",
"event",
")",
"self",
".",
"ProcessMouseMove",
"(",
"pos",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/flatmenu.py#L6075-L6106 |
||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/ipython/py2/IPython/core/oinspect.py | python | _get_wrapped | (obj) | return obj | Get the original object if wrapped in one or more @decorators
Some objects automatically construct similar objects on any unrecognised
attribute access (e.g. unittest.mock.call). To protect against infinite loops,
this will arbitrarily cut off after 100 levels of obj.__wrapped__
attribute access. --TK, Jan 2016 | Get the original object if wrapped in one or more @decorators | [
"Get",
"the",
"original",
"object",
"if",
"wrapped",
"in",
"one",
"or",
"more",
"@decorators"
] | def _get_wrapped(obj):
"""Get the original object if wrapped in one or more @decorators
Some objects automatically construct similar objects on any unrecognised
attribute access (e.g. unittest.mock.call). To protect against infinite loops,
this will arbitrarily cut off after 100 levels of obj.__wrapped__
attribute access. --TK, Jan 2016
"""
orig_obj = obj
i = 0
while safe_hasattr(obj, '__wrapped__'):
obj = obj.__wrapped__
i += 1
if i > 100:
# __wrapped__ is probably a lie, so return the thing we started with
return orig_obj
return obj | [
"def",
"_get_wrapped",
"(",
"obj",
")",
":",
"orig_obj",
"=",
"obj",
"i",
"=",
"0",
"while",
"safe_hasattr",
"(",
"obj",
",",
"'__wrapped__'",
")",
":",
"obj",
"=",
"obj",
".",
"__wrapped__",
"i",
"+=",
"1",
"if",
"i",
">",
"100",
":",
"# __wrapped__ is probably a lie, so return the thing we started with",
"return",
"orig_obj",
"return",
"obj"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py2/IPython/core/oinspect.py#L294-L310 |
|
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/bisect.py | python | insort_right | (a, x, lo=0, hi=None) | Insert item x in list a, and keep it sorted assuming a is sorted.
If x is already in a, insert it to the right of the rightmost x.
Optional args lo (default 0) and hi (default len(a)) bound the
slice of a to be searched. | Insert item x in list a, and keep it sorted assuming a is sorted. | [
"Insert",
"item",
"x",
"in",
"list",
"a",
"and",
"keep",
"it",
"sorted",
"assuming",
"a",
"is",
"sorted",
"."
] | def insort_right(a, x, lo=0, hi=None):
"""Insert item x in list a, and keep it sorted assuming a is sorted.
If x is already in a, insert it to the right of the rightmost x.
Optional args lo (default 0) and hi (default len(a)) bound the
slice of a to be searched.
"""
if lo < 0:
raise ValueError('lo must be non-negative')
if hi is None:
hi = len(a)
while lo < hi:
mid = (lo+hi)//2
if x < a[mid]: hi = mid
else: lo = mid+1
a.insert(lo, x) | [
"def",
"insort_right",
"(",
"a",
",",
"x",
",",
"lo",
"=",
"0",
",",
"hi",
"=",
"None",
")",
":",
"if",
"lo",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'lo must be non-negative'",
")",
"if",
"hi",
"is",
"None",
":",
"hi",
"=",
"len",
"(",
"a",
")",
"while",
"lo",
"<",
"hi",
":",
"mid",
"=",
"(",
"lo",
"+",
"hi",
")",
"//",
"2",
"if",
"x",
"<",
"a",
"[",
"mid",
"]",
":",
"hi",
"=",
"mid",
"else",
":",
"lo",
"=",
"mid",
"+",
"1",
"a",
".",
"insert",
"(",
"lo",
",",
"x",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/bisect.py#L3-L20 |
||
facebook/proxygen | a9ca025af207787815cb01eee1971cd572c7a81e | build/fbcode_builder/getdeps/builder.py | python | CargoBuilder._resolve_dep_to_git | (self) | return dep_to_git | For each direct dependency of the currently build manifest check if it
is also cargo-builded and if yes then extract it's git configs and
install dir | For each direct dependency of the currently build manifest check if it
is also cargo-builded and if yes then extract it's git configs and
install dir | [
"For",
"each",
"direct",
"dependency",
"of",
"the",
"currently",
"build",
"manifest",
"check",
"if",
"it",
"is",
"also",
"cargo",
"-",
"builded",
"and",
"if",
"yes",
"then",
"extract",
"it",
"s",
"git",
"configs",
"and",
"install",
"dir"
] | def _resolve_dep_to_git(self):
"""
For each direct dependency of the currently build manifest check if it
is also cargo-builded and if yes then extract it's git configs and
install dir
"""
dependencies = self.manifest.get_dependencies(self.ctx)
if not dependencies:
return []
dep_to_git = {}
for dep in dependencies:
dep_manifest = self.loader.load_manifest(dep)
dep_builder = dep_manifest.get("build", "builder", ctx=self.ctx)
if dep_builder not in ["cargo", "nop"] or dep == "rust":
# This is a direct dependency, but it is not build with cargo
# and it is not simply copying files with nop, so ignore it.
# The "rust" dependency is an exception since it contains the
# toolchain.
continue
git_conf = dep_manifest.get_section_as_dict("git", self.ctx)
if "repo_url" not in git_conf:
raise Exception(
"A cargo dependency requires git.repo_url to be defined."
)
source_dir = self.loader.get_project_install_dir(dep_manifest)
if dep_builder == "cargo":
source_dir = os.path.join(source_dir, "source")
git_conf["source_dir"] = source_dir
dep_to_git[dep] = git_conf
return dep_to_git | [
"def",
"_resolve_dep_to_git",
"(",
"self",
")",
":",
"dependencies",
"=",
"self",
".",
"manifest",
".",
"get_dependencies",
"(",
"self",
".",
"ctx",
")",
"if",
"not",
"dependencies",
":",
"return",
"[",
"]",
"dep_to_git",
"=",
"{",
"}",
"for",
"dep",
"in",
"dependencies",
":",
"dep_manifest",
"=",
"self",
".",
"loader",
".",
"load_manifest",
"(",
"dep",
")",
"dep_builder",
"=",
"dep_manifest",
".",
"get",
"(",
"\"build\"",
",",
"\"builder\"",
",",
"ctx",
"=",
"self",
".",
"ctx",
")",
"if",
"dep_builder",
"not",
"in",
"[",
"\"cargo\"",
",",
"\"nop\"",
"]",
"or",
"dep",
"==",
"\"rust\"",
":",
"# This is a direct dependency, but it is not build with cargo",
"# and it is not simply copying files with nop, so ignore it.",
"# The \"rust\" dependency is an exception since it contains the",
"# toolchain.",
"continue",
"git_conf",
"=",
"dep_manifest",
".",
"get_section_as_dict",
"(",
"\"git\"",
",",
"self",
".",
"ctx",
")",
"if",
"\"repo_url\"",
"not",
"in",
"git_conf",
":",
"raise",
"Exception",
"(",
"\"A cargo dependency requires git.repo_url to be defined.\"",
")",
"source_dir",
"=",
"self",
".",
"loader",
".",
"get_project_install_dir",
"(",
"dep_manifest",
")",
"if",
"dep_builder",
"==",
"\"cargo\"",
":",
"source_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"source_dir",
",",
"\"source\"",
")",
"git_conf",
"[",
"\"source_dir\"",
"]",
"=",
"source_dir",
"dep_to_git",
"[",
"dep",
"]",
"=",
"git_conf",
"return",
"dep_to_git"
] | https://github.com/facebook/proxygen/blob/a9ca025af207787815cb01eee1971cd572c7a81e/build/fbcode_builder/getdeps/builder.py#L1363-L1394 |
|
cztomczak/cefpython | 5679f28cec18a57a56e298da2927aac8d8f83ad6 | tools/automate.py | python | update_cef_patches | () | Update cef/patch/ directory with CEF Python patches.
Issue73 is applied in getenv() by setting appropriate env var.
Note that this modifies only cef_build_dir/cef/ directory. If the
build was run previously then there is a copy of the cef/ directory
in the cef_build_dir/chromium/ directory which is not being updated. | Update cef/patch/ directory with CEF Python patches.
Issue73 is applied in getenv() by setting appropriate env var. | [
"Update",
"cef",
"/",
"patch",
"/",
"directory",
"with",
"CEF",
"Python",
"patches",
".",
"Issue73",
"is",
"applied",
"in",
"getenv",
"()",
"by",
"setting",
"appropriate",
"env",
"var",
"."
] | def update_cef_patches():
"""Update cef/patch/ directory with CEF Python patches.
Issue73 is applied in getenv() by setting appropriate env var.
Note that this modifies only cef_build_dir/cef/ directory. If the
build was run previously then there is a copy of the cef/ directory
in the cef_build_dir/chromium/ directory which is not being updated.
"""
print("[automate.py] Updating CEF patches with CEF Python patches")
cef_dir = os.path.join(Options.cef_build_dir, "cef")
cef_patch_dir = os.path.join(cef_dir, "patch")
cef_patches_dir = os.path.join(cef_patch_dir, "patches")
# Copy src/patches/*.patch to cef/patch/patches/
cefpython_patches_dir = os.path.join(Options.cefpython_dir, "patches")
cefpython_patches = glob.glob(os.path.join(cefpython_patches_dir,
"*.patch"))
for file_ in cefpython_patches:
print("[automate.py] Copying %s to %s"
% (os.path.basename(file_), cef_patches_dir))
shutil.copy(file_, cef_patches_dir)
# Append cefpython/patches/patch.py to cef/patch/patch.cfg
cef_patch_cfg = os.path.join(cef_patch_dir, "patch.cfg")
print("[automate.py] Overwriting %s" % cef_patch_cfg)
with open(cef_patch_cfg, "rb") as fp:
cef_patch_cfg_contents = fp.read().decode("utf-8")
cef_patch_cfg_contents += "\n"
cefpython_patch_cfg = os.path.join(cefpython_patches_dir, "patch.py")
with open(cefpython_patch_cfg, "rb") as fp:
cefpython_patch_cfg_contents = fp.read().decode("utf-8")
with open(cef_patch_cfg, "wb") as fp:
cef_patch_cfg_contents = cef_patch_cfg_contents.replace("\r\n", "\n")
cefpython_patch_cfg_contents = cefpython_patch_cfg_contents.replace(
"\r\n", "\n")
new_contents = cef_patch_cfg_contents + cefpython_patch_cfg_contents
fp.write(new_contents.encode("utf-8")) | [
"def",
"update_cef_patches",
"(",
")",
":",
"print",
"(",
"\"[automate.py] Updating CEF patches with CEF Python patches\"",
")",
"cef_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"Options",
".",
"cef_build_dir",
",",
"\"cef\"",
")",
"cef_patch_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"cef_dir",
",",
"\"patch\"",
")",
"cef_patches_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"cef_patch_dir",
",",
"\"patches\"",
")",
"# Copy src/patches/*.patch to cef/patch/patches/",
"cefpython_patches_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"Options",
".",
"cefpython_dir",
",",
"\"patches\"",
")",
"cefpython_patches",
"=",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"cefpython_patches_dir",
",",
"\"*.patch\"",
")",
")",
"for",
"file_",
"in",
"cefpython_patches",
":",
"print",
"(",
"\"[automate.py] Copying %s to %s\"",
"%",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"file_",
")",
",",
"cef_patches_dir",
")",
")",
"shutil",
".",
"copy",
"(",
"file_",
",",
"cef_patches_dir",
")",
"# Append cefpython/patches/patch.py to cef/patch/patch.cfg",
"cef_patch_cfg",
"=",
"os",
".",
"path",
".",
"join",
"(",
"cef_patch_dir",
",",
"\"patch.cfg\"",
")",
"print",
"(",
"\"[automate.py] Overwriting %s\"",
"%",
"cef_patch_cfg",
")",
"with",
"open",
"(",
"cef_patch_cfg",
",",
"\"rb\"",
")",
"as",
"fp",
":",
"cef_patch_cfg_contents",
"=",
"fp",
".",
"read",
"(",
")",
".",
"decode",
"(",
"\"utf-8\"",
")",
"cef_patch_cfg_contents",
"+=",
"\"\\n\"",
"cefpython_patch_cfg",
"=",
"os",
".",
"path",
".",
"join",
"(",
"cefpython_patches_dir",
",",
"\"patch.py\"",
")",
"with",
"open",
"(",
"cefpython_patch_cfg",
",",
"\"rb\"",
")",
"as",
"fp",
":",
"cefpython_patch_cfg_contents",
"=",
"fp",
".",
"read",
"(",
")",
".",
"decode",
"(",
"\"utf-8\"",
")",
"with",
"open",
"(",
"cef_patch_cfg",
",",
"\"wb\"",
")",
"as",
"fp",
":",
"cef_patch_cfg_contents",
"=",
"cef_patch_cfg_contents",
".",
"replace",
"(",
"\"\\r\\n\"",
",",
"\"\\n\"",
")",
"cefpython_patch_cfg_contents",
"=",
"cefpython_patch_cfg_contents",
".",
"replace",
"(",
"\"\\r\\n\"",
",",
"\"\\n\"",
")",
"new_contents",
"=",
"cef_patch_cfg_contents",
"+",
"cefpython_patch_cfg_contents",
"fp",
".",
"write",
"(",
"new_contents",
".",
"encode",
"(",
"\"utf-8\"",
")",
")"
] | https://github.com/cztomczak/cefpython/blob/5679f28cec18a57a56e298da2927aac8d8f83ad6/tools/automate.py#L331-L367 |
||
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py | python | validateNamesValue | (value) | return ret | Validate that the given value match Names production | Validate that the given value match Names production | [
"Validate",
"that",
"the",
"given",
"value",
"match",
"Names",
"production"
] | def validateNamesValue(value):
"""Validate that the given value match Names production """
ret = libxml2mod.xmlValidateNamesValue(value)
return ret | [
"def",
"validateNamesValue",
"(",
"value",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlValidateNamesValue",
"(",
"value",
")",
"return",
"ret"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L1845-L1848 |
|
mingchen/protobuf-ios | 0958df34558cd54cb7b6e6ca5c8855bf3d475046 | compiler/python/google/protobuf/internal/containers.py | python | RepeatedCompositeFieldContainer.__init__ | (self, message_listener, message_descriptor) | Note that we pass in a descriptor instead of the generated directly,
since at the time we construct a _RepeatedCompositeFieldContainer we
haven't yet necessarily initialized the type that will be contained in the
container.
Args:
message_listener: A MessageListener implementation.
The RepeatedCompositeFieldContainer will call this object's
TransitionToNonempty() method when it transitions from being empty to
being nonempty.
message_descriptor: A Descriptor instance describing the protocol type
that should be present in this container. We'll use the
_concrete_class field of this descriptor when the client calls add(). | Note that we pass in a descriptor instead of the generated directly,
since at the time we construct a _RepeatedCompositeFieldContainer we
haven't yet necessarily initialized the type that will be contained in the
container. | [
"Note",
"that",
"we",
"pass",
"in",
"a",
"descriptor",
"instead",
"of",
"the",
"generated",
"directly",
"since",
"at",
"the",
"time",
"we",
"construct",
"a",
"_RepeatedCompositeFieldContainer",
"we",
"haven",
"t",
"yet",
"necessarily",
"initialized",
"the",
"type",
"that",
"will",
"be",
"contained",
"in",
"the",
"container",
"."
] | def __init__(self, message_listener, message_descriptor):
"""
Note that we pass in a descriptor instead of the generated directly,
since at the time we construct a _RepeatedCompositeFieldContainer we
haven't yet necessarily initialized the type that will be contained in the
container.
Args:
message_listener: A MessageListener implementation.
The RepeatedCompositeFieldContainer will call this object's
TransitionToNonempty() method when it transitions from being empty to
being nonempty.
message_descriptor: A Descriptor instance describing the protocol type
that should be present in this container. We'll use the
_concrete_class field of this descriptor when the client calls add().
"""
super(RepeatedCompositeFieldContainer, self).__init__(message_listener)
self._message_descriptor = message_descriptor | [
"def",
"__init__",
"(",
"self",
",",
"message_listener",
",",
"message_descriptor",
")",
":",
"super",
"(",
"RepeatedCompositeFieldContainer",
",",
"self",
")",
".",
"__init__",
"(",
"message_listener",
")",
"self",
".",
"_message_descriptor",
"=",
"message_descriptor"
] | https://github.com/mingchen/protobuf-ios/blob/0958df34558cd54cb7b6e6ca5c8855bf3d475046/compiler/python/google/protobuf/internal/containers.py#L179-L196 |
||
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Tools/CryVersionSelector/cryselect.py | python | error_project_json_decode | (args) | Error to specify that the json file is corrupt and couldn't be parsed. | Error to specify that the json file is corrupt and couldn't be parsed. | [
"Error",
"to",
"specify",
"that",
"the",
"json",
"file",
"is",
"corrupt",
"and",
"couldn",
"t",
"be",
"parsed",
"."
] | def error_project_json_decode(args):
"""
Error to specify that the json file is corrupt and couldn't be parsed.
"""
message = "Unable to parse '{}'.\n".format(args.project_file)
if not args.silent and HAS_WIN_MODULES:
MESSAGEBOX(None, message, command_title(args),
win32con.MB_OK | win32con.MB_ICONERROR)
else:
sys.stderr.write(message)
sys.exit(601) | [
"def",
"error_project_json_decode",
"(",
"args",
")",
":",
"message",
"=",
"\"Unable to parse '{}'.\\n\"",
".",
"format",
"(",
"args",
".",
"project_file",
")",
"if",
"not",
"args",
".",
"silent",
"and",
"HAS_WIN_MODULES",
":",
"MESSAGEBOX",
"(",
"None",
",",
"message",
",",
"command_title",
"(",
"args",
")",
",",
"win32con",
".",
"MB_OK",
"|",
"win32con",
".",
"MB_ICONERROR",
")",
"else",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"message",
")",
"sys",
".",
"exit",
"(",
"601",
")"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Tools/CryVersionSelector/cryselect.py#L100-L110 |
||
cvmfs/cvmfs | 4637bdb5153178eadf885c1acf37bdc5c685bf8a | cpplint.py | python | _IncludeState.CanonicalizeAlphabeticalOrder | (self, header_path) | return header_path.replace('-inl.h', '.h').replace('-', '_').lower() | Returns a path canonicalized for alphabetical comparison.
- replaces "-" with "_" so they both cmp the same.
- removes '-inl' since we don't require them to be after the main header.
- lowercase everything, just in case.
Args:
header_path: Path to be canonicalized.
Returns:
Canonicalized path. | Returns a path canonicalized for alphabetical comparison. | [
"Returns",
"a",
"path",
"canonicalized",
"for",
"alphabetical",
"comparison",
"."
] | def CanonicalizeAlphabeticalOrder(self, header_path):
"""Returns a path canonicalized for alphabetical comparison.
- replaces "-" with "_" so they both cmp the same.
- removes '-inl' since we don't require them to be after the main header.
- lowercase everything, just in case.
Args:
header_path: Path to be canonicalized.
Returns:
Canonicalized path.
"""
return header_path.replace('-inl.h', '.h').replace('-', '_').lower() | [
"def",
"CanonicalizeAlphabeticalOrder",
"(",
"self",
",",
"header_path",
")",
":",
"return",
"header_path",
".",
"replace",
"(",
"'-inl.h'",
",",
"'.h'",
")",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
".",
"lower",
"(",
")"
] | https://github.com/cvmfs/cvmfs/blob/4637bdb5153178eadf885c1acf37bdc5c685bf8a/cpplint.py#L667-L680 |
|
floooh/oryol | eb08cffe1b1cb6b05ed14ec692bca9372cef064e | fips-files/generators/util/png.py | python | check_palette | (palette) | return p | Check a palette argument (to the :class:`Writer` class) for validity.
Returns the palette as a list if okay; raises an exception otherwise. | Check a palette argument (to the :class:`Writer` class) for validity.
Returns the palette as a list if okay; raises an exception otherwise. | [
"Check",
"a",
"palette",
"argument",
"(",
"to",
"the",
":",
"class",
":",
"Writer",
"class",
")",
"for",
"validity",
".",
"Returns",
"the",
"palette",
"as",
"a",
"list",
"if",
"okay",
";",
"raises",
"an",
"exception",
"otherwise",
"."
] | def check_palette(palette):
"""Check a palette argument (to the :class:`Writer` class) for validity.
Returns the palette as a list if okay; raises an exception otherwise.
"""
# None is the default and is allowed.
if palette is None:
return None
p = list(palette)
if not (0 < len(p) <= 256):
raise ValueError("a palette must have between 1 and 256 entries")
seen_triple = False
for i,t in enumerate(p):
if len(t) not in (3,4):
raise ValueError(
"palette entry %d: entries must be 3- or 4-tuples." % i)
if len(t) == 3:
seen_triple = True
if seen_triple and len(t) == 4:
raise ValueError(
"palette entry %d: all 4-tuples must precede all 3-tuples" % i)
for x in t:
if int(x) != x or not(0 <= x <= 255):
raise ValueError(
"palette entry %d: values must be integer: 0 <= x <= 255" % i)
return p | [
"def",
"check_palette",
"(",
"palette",
")",
":",
"# None is the default and is allowed.",
"if",
"palette",
"is",
"None",
":",
"return",
"None",
"p",
"=",
"list",
"(",
"palette",
")",
"if",
"not",
"(",
"0",
"<",
"len",
"(",
"p",
")",
"<=",
"256",
")",
":",
"raise",
"ValueError",
"(",
"\"a palette must have between 1 and 256 entries\"",
")",
"seen_triple",
"=",
"False",
"for",
"i",
",",
"t",
"in",
"enumerate",
"(",
"p",
")",
":",
"if",
"len",
"(",
"t",
")",
"not",
"in",
"(",
"3",
",",
"4",
")",
":",
"raise",
"ValueError",
"(",
"\"palette entry %d: entries must be 3- or 4-tuples.\"",
"%",
"i",
")",
"if",
"len",
"(",
"t",
")",
"==",
"3",
":",
"seen_triple",
"=",
"True",
"if",
"seen_triple",
"and",
"len",
"(",
"t",
")",
"==",
"4",
":",
"raise",
"ValueError",
"(",
"\"palette entry %d: all 4-tuples must precede all 3-tuples\"",
"%",
"i",
")",
"for",
"x",
"in",
"t",
":",
"if",
"int",
"(",
"x",
")",
"!=",
"x",
"or",
"not",
"(",
"0",
"<=",
"x",
"<=",
"255",
")",
":",
"raise",
"ValueError",
"(",
"\"palette entry %d: values must be integer: 0 <= x <= 255\"",
"%",
"i",
")",
"return",
"p"
] | https://github.com/floooh/oryol/blob/eb08cffe1b1cb6b05ed14ec692bca9372cef064e/fips-files/generators/util/png.py#L267-L293 |
|
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/symsrc/pefile.py | python | SectionStructure.entropy_H | (self, data) | return entropy | Calculate the entropy of a chunk of data. | Calculate the entropy of a chunk of data. | [
"Calculate",
"the",
"entropy",
"of",
"a",
"chunk",
"of",
"data",
"."
] | def entropy_H(self, data):
"""Calculate the entropy of a chunk of data."""
if len(data) == 0:
return 0.0
occurences = array.array('L', [0]*256)
for x in data:
occurences[ord(x)] += 1
entropy = 0
for x in occurences:
if x:
p_x = float(x) / len(data)
entropy -= p_x*math.log(p_x, 2)
return entropy | [
"def",
"entropy_H",
"(",
"self",
",",
"data",
")",
":",
"if",
"len",
"(",
"data",
")",
"==",
"0",
":",
"return",
"0.0",
"occurences",
"=",
"array",
".",
"array",
"(",
"'L'",
",",
"[",
"0",
"]",
"*",
"256",
")",
"for",
"x",
"in",
"data",
":",
"occurences",
"[",
"ord",
"(",
"x",
")",
"]",
"+=",
"1",
"entropy",
"=",
"0",
"for",
"x",
"in",
"occurences",
":",
"if",
"x",
":",
"p_x",
"=",
"float",
"(",
"x",
")",
"/",
"len",
"(",
"data",
")",
"entropy",
"-=",
"p_x",
"*",
"math",
".",
"log",
"(",
"p_x",
",",
"2",
")",
"return",
"entropy"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/symsrc/pefile.py#L913-L930 |
|
apple/foundationdb | f7118ad406f44ab7a33970fc8370647ed0085e18 | layers/taskbucket/__init__.py | python | TaskBucket.extend | (self, tr, taskDict) | Extends the lock on a task previously locked by get_one for another self.timeout seconds.
If the task has already timed out, raises TaskTimedOutException. | Extends the lock on a task previously locked by get_one for another self.timeout seconds.
If the task has already timed out, raises TaskTimedOutException. | [
"Extends",
"the",
"lock",
"on",
"a",
"task",
"previously",
"locked",
"by",
"get_one",
"for",
"another",
"self",
".",
"timeout",
"seconds",
".",
"If",
"the",
"task",
"has",
"already",
"timed",
"out",
"raises",
"TaskTimedOutException",
"."
] | def extend(self, tr, taskDict):
"""Extends the lock on a task previously locked by get_one for another self.timeout seconds.
If the task has already timed out, raises TaskTimedOutException."""
pass | [
"def",
"extend",
"(",
"self",
",",
"tr",
",",
"taskDict",
")",
":",
"pass"
] | https://github.com/apple/foundationdb/blob/f7118ad406f44ab7a33970fc8370647ed0085e18/layers/taskbucket/__init__.py#L208-L211 |
||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | contrib/gizmos/msw/gizmos.py | python | TreeListCtrl.SetColumnImage | (*args, **kwargs) | return _gizmos.TreeListCtrl_SetColumnImage(*args, **kwargs) | SetColumnImage(self, int column, int image) | SetColumnImage(self, int column, int image) | [
"SetColumnImage",
"(",
"self",
"int",
"column",
"int",
"image",
")"
] | def SetColumnImage(*args, **kwargs):
"""SetColumnImage(self, int column, int image)"""
return _gizmos.TreeListCtrl_SetColumnImage(*args, **kwargs) | [
"def",
"SetColumnImage",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gizmos",
".",
"TreeListCtrl_SetColumnImage",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/gizmos/msw/gizmos.py#L626-L628 |
|
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | build/mac/change_mach_o_flags.py | python | CheckedRead | (file, count) | return bytes | Reads |count| bytes from the file-like |file| object, raising a
MachOError if any other number of bytes is read. | Reads |count| bytes from the file-like |file| object, raising a
MachOError if any other number of bytes is read. | [
"Reads",
"|count|",
"bytes",
"from",
"the",
"file",
"-",
"like",
"|file|",
"object",
"raising",
"a",
"MachOError",
"if",
"any",
"other",
"number",
"of",
"bytes",
"is",
"read",
"."
] | def CheckedRead(file, count):
"""Reads |count| bytes from the file-like |file| object, raising a
MachOError if any other number of bytes is read."""
bytes = file.read(count)
if len(bytes) != count:
raise MachOError, \
'read: expected length %d, observed %d' % (count, len(bytes))
return bytes | [
"def",
"CheckedRead",
"(",
"file",
",",
"count",
")",
":",
"bytes",
"=",
"file",
".",
"read",
"(",
"count",
")",
"if",
"len",
"(",
"bytes",
")",
"!=",
"count",
":",
"raise",
"MachOError",
",",
"'read: expected length %d, observed %d'",
"%",
"(",
"count",
",",
"len",
"(",
"bytes",
")",
")",
"return",
"bytes"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/build/mac/change_mach_o_flags.py#L113-L122 |
|
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/src/robotsim.py | python | GeneralizedIKSolver.getJacobian | (self) | return _robotsim.GeneralizedIKSolver_getJacobian(self) | r"""
getJacobian(GeneralizedIKSolver self)
Returns a matrix describing the instantaneous derivative of the objective with
respect to the active parameters. | r"""
getJacobian(GeneralizedIKSolver self) | [
"r",
"getJacobian",
"(",
"GeneralizedIKSolver",
"self",
")"
] | def getJacobian(self) -> "void":
r"""
getJacobian(GeneralizedIKSolver self)
Returns a matrix describing the instantaneous derivative of the objective with
respect to the active parameters.
"""
return _robotsim.GeneralizedIKSolver_getJacobian(self) | [
"def",
"getJacobian",
"(",
"self",
")",
"->",
"\"void\"",
":",
"return",
"_robotsim",
".",
"GeneralizedIKSolver_getJacobian",
"(",
"self",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/src/robotsim.py#L7039-L7048 |
|
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/rfc822.py | python | Message.__getitem__ | (self, name) | return self.dict[name.lower()] | Get a specific header, as from a dictionary. | Get a specific header, as from a dictionary. | [
"Get",
"a",
"specific",
"header",
"as",
"from",
"a",
"dictionary",
"."
] | def __getitem__(self, name):
"""Get a specific header, as from a dictionary."""
return self.dict[name.lower()] | [
"def",
"__getitem__",
"(",
"self",
",",
"name",
")",
":",
"return",
"self",
".",
"dict",
"[",
"name",
".",
"lower",
"(",
")",
"]"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/rfc822.py#L386-L388 |
|
facebook/fbthrift | fb9c8562aba04c4fd9b17716eb5d970cc88a75bb | thrift/lib/py/util/Serializer.py | python | serialize | (protocol_factory, thr) | return transport.getvalue() | Convenience method for serializing objects using the given
protocol factory and a TMemoryBuffer. | Convenience method for serializing objects using the given
protocol factory and a TMemoryBuffer. | [
"Convenience",
"method",
"for",
"serializing",
"objects",
"using",
"the",
"given",
"protocol",
"factory",
"and",
"a",
"TMemoryBuffer",
"."
] | def serialize(protocol_factory, thr):
# type: (Any, Any) -> AnyStr
"""Convenience method for serializing objects using the given
protocol factory and a TMemoryBuffer."""
transport = TTransport.TMemoryBuffer()
protocol = protocol_factory.getProtocol(transport)
thr.write(protocol)
if isinstance(protocol, THeaderProtocol.THeaderProtocol):
protocol.trans.flush()
return transport.getvalue() | [
"def",
"serialize",
"(",
"protocol_factory",
",",
"thr",
")",
":",
"# type: (Any, Any) -> AnyStr",
"transport",
"=",
"TTransport",
".",
"TMemoryBuffer",
"(",
")",
"protocol",
"=",
"protocol_factory",
".",
"getProtocol",
"(",
"transport",
")",
"thr",
".",
"write",
"(",
"protocol",
")",
"if",
"isinstance",
"(",
"protocol",
",",
"THeaderProtocol",
".",
"THeaderProtocol",
")",
":",
"protocol",
".",
"trans",
".",
"flush",
"(",
")",
"return",
"transport",
".",
"getvalue",
"(",
")"
] | https://github.com/facebook/fbthrift/blob/fb9c8562aba04c4fd9b17716eb5d970cc88a75bb/thrift/lib/py/util/Serializer.py#L30-L39 |
|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/neural_network/multilayer_perceptron.py | python | BaseMultilayerPerceptron._compute_loss_grad | (self, layer, n_samples, activations, deltas,
coef_grads, intercept_grads) | return coef_grads, intercept_grads | Compute the gradient of loss with respect to coefs and intercept for
specified layer.
This function does backpropagation for the specified one layer. | Compute the gradient of loss with respect to coefs and intercept for
specified layer. | [
"Compute",
"the",
"gradient",
"of",
"loss",
"with",
"respect",
"to",
"coefs",
"and",
"intercept",
"for",
"specified",
"layer",
"."
] | def _compute_loss_grad(self, layer, n_samples, activations, deltas,
coef_grads, intercept_grads):
"""Compute the gradient of loss with respect to coefs and intercept for
specified layer.
This function does backpropagation for the specified one layer.
"""
coef_grads[layer] = safe_sparse_dot(activations[layer].T,
deltas[layer])
coef_grads[layer] += (self.alpha * self.coefs_[layer])
coef_grads[layer] /= n_samples
intercept_grads[layer] = np.mean(deltas[layer], 0)
return coef_grads, intercept_grads | [
"def",
"_compute_loss_grad",
"(",
"self",
",",
"layer",
",",
"n_samples",
",",
"activations",
",",
"deltas",
",",
"coef_grads",
",",
"intercept_grads",
")",
":",
"coef_grads",
"[",
"layer",
"]",
"=",
"safe_sparse_dot",
"(",
"activations",
"[",
"layer",
"]",
".",
"T",
",",
"deltas",
"[",
"layer",
"]",
")",
"coef_grads",
"[",
"layer",
"]",
"+=",
"(",
"self",
".",
"alpha",
"*",
"self",
".",
"coefs_",
"[",
"layer",
"]",
")",
"coef_grads",
"[",
"layer",
"]",
"/=",
"n_samples",
"intercept_grads",
"[",
"layer",
"]",
"=",
"np",
".",
"mean",
"(",
"deltas",
"[",
"layer",
"]",
",",
"0",
")",
"return",
"coef_grads",
",",
"intercept_grads"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/neural_network/multilayer_perceptron.py#L117-L131 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/ipaddress.py | python | _BaseNetwork.is_link_local | (self) | return (self.network_address.is_link_local and
self.broadcast_address.is_link_local) | Test if the address is reserved for link-local.
Returns:
A boolean, True if the address is reserved per RFC 4291. | Test if the address is reserved for link-local. | [
"Test",
"if",
"the",
"address",
"is",
"reserved",
"for",
"link",
"-",
"local",
"."
] | def is_link_local(self):
"""Test if the address is reserved for link-local.
Returns:
A boolean, True if the address is reserved per RFC 4291.
"""
return (self.network_address.is_link_local and
self.broadcast_address.is_link_local) | [
"def",
"is_link_local",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"network_address",
".",
"is_link_local",
"and",
"self",
".",
"broadcast_address",
".",
"is_link_local",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/ipaddress.py#L1135-L1143 |
|
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/setuptools/_vendor/pyparsing.py | python | tokenMap | (func, *args) | return pa | Helper to define a parse action by mapping a function to all elements of a ParseResults list.If any additional
args are passed, they are forwarded to the given function as additional arguments after
the token, as in C{hex_integer = Word(hexnums).setParseAction(tokenMap(int, 16))}, which will convert the
parsed data to an integer using base 16.
Example (compare the last to example in L{ParserElement.transformString}::
hex_ints = OneOrMore(Word(hexnums)).setParseAction(tokenMap(int, 16))
hex_ints.runTests('''
00 11 22 aa FF 0a 0d 1a
''')
upperword = Word(alphas).setParseAction(tokenMap(str.upper))
OneOrMore(upperword).runTests('''
my kingdom for a horse
''')
wd = Word(alphas).setParseAction(tokenMap(str.title))
OneOrMore(wd).setParseAction(' '.join).runTests('''
now is the winter of our discontent made glorious summer by this sun of york
''')
prints::
00 11 22 aa FF 0a 0d 1a
[0, 17, 34, 170, 255, 10, 13, 26]
my kingdom for a horse
['MY', 'KINGDOM', 'FOR', 'A', 'HORSE']
now is the winter of our discontent made glorious summer by this sun of york
['Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York'] | Helper to define a parse action by mapping a function to all elements of a ParseResults list.If any additional
args are passed, they are forwarded to the given function as additional arguments after
the token, as in C{hex_integer = Word(hexnums).setParseAction(tokenMap(int, 16))}, which will convert the
parsed data to an integer using base 16. | [
"Helper",
"to",
"define",
"a",
"parse",
"action",
"by",
"mapping",
"a",
"function",
"to",
"all",
"elements",
"of",
"a",
"ParseResults",
"list",
".",
"If",
"any",
"additional",
"args",
"are",
"passed",
"they",
"are",
"forwarded",
"to",
"the",
"given",
"function",
"as",
"additional",
"arguments",
"after",
"the",
"token",
"as",
"in",
"C",
"{",
"hex_integer",
"=",
"Word",
"(",
"hexnums",
")",
".",
"setParseAction",
"(",
"tokenMap",
"(",
"int",
"16",
"))",
"}",
"which",
"will",
"convert",
"the",
"parsed",
"data",
"to",
"an",
"integer",
"using",
"base",
"16",
"."
] | def tokenMap(func, *args):
"""
Helper to define a parse action by mapping a function to all elements of a ParseResults list.If any additional
args are passed, they are forwarded to the given function as additional arguments after
the token, as in C{hex_integer = Word(hexnums).setParseAction(tokenMap(int, 16))}, which will convert the
parsed data to an integer using base 16.
Example (compare the last to example in L{ParserElement.transformString}::
hex_ints = OneOrMore(Word(hexnums)).setParseAction(tokenMap(int, 16))
hex_ints.runTests('''
00 11 22 aa FF 0a 0d 1a
''')
upperword = Word(alphas).setParseAction(tokenMap(str.upper))
OneOrMore(upperword).runTests('''
my kingdom for a horse
''')
wd = Word(alphas).setParseAction(tokenMap(str.title))
OneOrMore(wd).setParseAction(' '.join).runTests('''
now is the winter of our discontent made glorious summer by this sun of york
''')
prints::
00 11 22 aa FF 0a 0d 1a
[0, 17, 34, 170, 255, 10, 13, 26]
my kingdom for a horse
['MY', 'KINGDOM', 'FOR', 'A', 'HORSE']
now is the winter of our discontent made glorious summer by this sun of york
['Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York']
"""
def pa(s,l,t):
return [func(tokn, *args) for tokn in t]
try:
func_name = getattr(func, '__name__',
getattr(func, '__class__').__name__)
except Exception:
func_name = str(func)
pa.__name__ = func_name
return pa | [
"def",
"tokenMap",
"(",
"func",
",",
"*",
"args",
")",
":",
"def",
"pa",
"(",
"s",
",",
"l",
",",
"t",
")",
":",
"return",
"[",
"func",
"(",
"tokn",
",",
"*",
"args",
")",
"for",
"tokn",
"in",
"t",
"]",
"try",
":",
"func_name",
"=",
"getattr",
"(",
"func",
",",
"'__name__'",
",",
"getattr",
"(",
"func",
",",
"'__class__'",
")",
".",
"__name__",
")",
"except",
"Exception",
":",
"func_name",
"=",
"str",
"(",
"func",
")",
"pa",
".",
"__name__",
"=",
"func_name",
"return",
"pa"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/setuptools/_vendor/pyparsing.py#L4825-L4867 |
|
panda3d/panda3d | 833ad89ebad58395d0af0b7ec08538e5e4308265 | direct/src/directnotify/Notifier.py | python | Notifier.setLogging | (self, enable) | Set the logging flag to int (1=on, 0=off) | Set the logging flag to int (1=on, 0=off) | [
"Set",
"the",
"logging",
"flag",
"to",
"int",
"(",
"1",
"=",
"on",
"0",
"=",
"off",
")"
] | def setLogging(self, enable):
"""
Set the logging flag to int (1=on, 0=off)
"""
self.__logging = enable | [
"def",
"setLogging",
"(",
"self",
",",
"enable",
")",
":",
"self",
".",
"__logging",
"=",
"enable"
] | https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/directnotify/Notifier.py#L227-L231 |
||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/eager/python/evaluator.py | python | Evaluator.call | (self, eval_data) | Update metrics using the output of self.model.
Note: This function is executed as a graph function in graph mode.
This means:
a) Operations on the same resource are executed in textual order.
This should make it easier to do things like add the updated
value of a variable to another, for example.
b) You don't need to worry about collecting the update ops to execute.
All update ops added to the graph by this function will be executed.
As a result, code should generally work the same way with graph or
eager execution.
Args:
eval_data: The output of self.model.eval_data() on a mini-batch of
examples. | Update metrics using the output of self.model. | [
"Update",
"metrics",
"using",
"the",
"output",
"of",
"self",
".",
"model",
"."
] | def call(self, eval_data):
"""Update metrics using the output of self.model.
Note: This function is executed as a graph function in graph mode.
This means:
a) Operations on the same resource are executed in textual order.
This should make it easier to do things like add the updated
value of a variable to another, for example.
b) You don't need to worry about collecting the update ops to execute.
All update ops added to the graph by this function will be executed.
As a result, code should generally work the same way with graph or
eager execution.
Args:
eval_data: The output of self.model.eval_data() on a mini-batch of
examples.
"""
raise NotImplementedError("Evaluators must define a call member function.") | [
"def",
"call",
"(",
"self",
",",
"eval_data",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"Evaluators must define a call member function.\"",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/eager/python/evaluator.py#L182-L199 |
||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/requests/cookies.py | python | RequestsCookieJar.values | (self) | return list(self.itervalues()) | Dict-like values() that returns a list of values of cookies from the
jar.
.. seealso:: keys() and items(). | Dict-like values() that returns a list of values of cookies from the | [
"Dict",
"-",
"like",
"values",
"()",
"that",
"returns",
"a",
"list",
"of",
"values",
"of",
"cookies",
"from",
"the"
] | def values(self):
"""Dict-like values() that returns a list of values of cookies from the
jar.
.. seealso:: keys() and items().
"""
return list(self.itervalues()) | [
"def",
"values",
"(",
"self",
")",
":",
"return",
"list",
"(",
"self",
".",
"itervalues",
"(",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/requests/cookies.py#L487-L499 |
|
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/android/loading/sandwich_prefetch.py | python | PrefetchBenchmarkBuilder._PopulateCommonPipelines | (self) | Creates necessary tasks to produce initial cache archive.
Also creates a task for producing a json file with a mapping of URLs to
subresources (urls-resources.json).
Here is the full dependency tree for the returned task:
common/patched-cache-validation.json
depends on: common/patched-cache.zip
depends on: common/original-cache.zip
depends on: common/webpages-patched.wpr
depends on: common/webpages.wpr | Creates necessary tasks to produce initial cache archive. | [
"Creates",
"necessary",
"tasks",
"to",
"produce",
"initial",
"cache",
"archive",
"."
] | def _PopulateCommonPipelines(self):
"""Creates necessary tasks to produce initial cache archive.
Also creates a task for producing a json file with a mapping of URLs to
subresources (urls-resources.json).
Here is the full dependency tree for the returned task:
common/patched-cache-validation.json
depends on: common/patched-cache.zip
depends on: common/original-cache.zip
depends on: common/webpages-patched.wpr
depends on: common/webpages.wpr
"""
self._original_headers_path = self.RebaseOutputPath(
'common/response-headers.json')
@self.RegisterTask('common/webpages-patched.wpr',
dependencies=[self._common_builder.original_wpr_task])
def BuildPatchedWpr():
shutil.copyfile(
self._common_builder.original_wpr_task.path, BuildPatchedWpr.path)
wpr_archive = wpr_backend.WprArchiveBackend(BuildPatchedWpr.path)
# Save up original response headers.
original_response_headers = {e.url: e.GetResponseHeadersDict() \
for e in wpr_archive.ListUrlEntries()}
logging.info('save up response headers for %d resources',
len(original_response_headers))
if not original_response_headers:
# TODO(gabadie): How is it possible to not even have the main resource
# in the WPR archive? Example URL can be found in:
# http://crbug.com/623966#c5
raise Exception(
'Looks like no resources were recorded in WPR during: {}'.format(
self._common_builder.original_wpr_task.name))
with open(self._original_headers_path, 'w') as file_output:
json.dump(original_response_headers, file_output)
# Patch WPR.
wpr_url_entries = wpr_archive.ListUrlEntries()
for wpr_url_entry in wpr_url_entries:
sandwich_utils.PatchWprEntryToBeCached(wpr_url_entry)
logging.info('number of patched entries: %d', len(wpr_url_entries))
wpr_archive.Persist()
@self.RegisterTask('common/original-cache.zip', [BuildPatchedWpr])
def BuildOriginalCache():
runner = self._common_builder.CreateSandwichRunner()
runner.wpr_archive_path = BuildPatchedWpr.path
runner.cache_archive_path = BuildOriginalCache.path
runner.cache_operation = sandwich_runner.CacheOperation.SAVE
runner.output_dir = BuildOriginalCache.run_path
runner.Run()
BuildOriginalCache.run_path = BuildOriginalCache.path[:-4] + '-run'
original_cache_trace_path = os.path.join(
BuildOriginalCache.run_path, '0', sandwich_runner.TRACE_FILENAME)
@self.RegisterTask('common/patched-cache.zip', [BuildOriginalCache])
def BuildPatchedCache():
_PatchCacheArchive(BuildOriginalCache.path,
original_cache_trace_path, BuildPatchedCache.path)
@self.RegisterTask('common/patched-cache-validation.json',
[BuildPatchedCache])
def ValidatePatchedCache():
cache_validation_result = _ValidateCacheArchiveContent(
original_cache_trace_path, BuildPatchedCache.path)
with open(ValidatePatchedCache.path, 'w') as output:
json.dump(cache_validation_result, output)
self._wpr_archive_path = BuildPatchedWpr.path
self._trace_from_grabbing_reference_cache = original_cache_trace_path
self._cache_path = BuildPatchedCache.path
self._cache_validation_task = ValidatePatchedCache
self._common_builder.default_final_tasks.append(ValidatePatchedCache) | [
"def",
"_PopulateCommonPipelines",
"(",
"self",
")",
":",
"self",
".",
"_original_headers_path",
"=",
"self",
".",
"RebaseOutputPath",
"(",
"'common/response-headers.json'",
")",
"@",
"self",
".",
"RegisterTask",
"(",
"'common/webpages-patched.wpr'",
",",
"dependencies",
"=",
"[",
"self",
".",
"_common_builder",
".",
"original_wpr_task",
"]",
")",
"def",
"BuildPatchedWpr",
"(",
")",
":",
"shutil",
".",
"copyfile",
"(",
"self",
".",
"_common_builder",
".",
"original_wpr_task",
".",
"path",
",",
"BuildPatchedWpr",
".",
"path",
")",
"wpr_archive",
"=",
"wpr_backend",
".",
"WprArchiveBackend",
"(",
"BuildPatchedWpr",
".",
"path",
")",
"# Save up original response headers.",
"original_response_headers",
"=",
"{",
"e",
".",
"url",
":",
"e",
".",
"GetResponseHeadersDict",
"(",
")",
"for",
"e",
"in",
"wpr_archive",
".",
"ListUrlEntries",
"(",
")",
"}",
"logging",
".",
"info",
"(",
"'save up response headers for %d resources'",
",",
"len",
"(",
"original_response_headers",
")",
")",
"if",
"not",
"original_response_headers",
":",
"# TODO(gabadie): How is it possible to not even have the main resource",
"# in the WPR archive? Example URL can be found in:",
"# http://crbug.com/623966#c5",
"raise",
"Exception",
"(",
"'Looks like no resources were recorded in WPR during: {}'",
".",
"format",
"(",
"self",
".",
"_common_builder",
".",
"original_wpr_task",
".",
"name",
")",
")",
"with",
"open",
"(",
"self",
".",
"_original_headers_path",
",",
"'w'",
")",
"as",
"file_output",
":",
"json",
".",
"dump",
"(",
"original_response_headers",
",",
"file_output",
")",
"# Patch WPR.",
"wpr_url_entries",
"=",
"wpr_archive",
".",
"ListUrlEntries",
"(",
")",
"for",
"wpr_url_entry",
"in",
"wpr_url_entries",
":",
"sandwich_utils",
".",
"PatchWprEntryToBeCached",
"(",
"wpr_url_entry",
")",
"logging",
".",
"info",
"(",
"'number of patched entries: %d'",
",",
"len",
"(",
"wpr_url_entries",
")",
")",
"wpr_archive",
".",
"Persist",
"(",
")",
"@",
"self",
".",
"RegisterTask",
"(",
"'common/original-cache.zip'",
",",
"[",
"BuildPatchedWpr",
"]",
")",
"def",
"BuildOriginalCache",
"(",
")",
":",
"runner",
"=",
"self",
".",
"_common_builder",
".",
"CreateSandwichRunner",
"(",
")",
"runner",
".",
"wpr_archive_path",
"=",
"BuildPatchedWpr",
".",
"path",
"runner",
".",
"cache_archive_path",
"=",
"BuildOriginalCache",
".",
"path",
"runner",
".",
"cache_operation",
"=",
"sandwich_runner",
".",
"CacheOperation",
".",
"SAVE",
"runner",
".",
"output_dir",
"=",
"BuildOriginalCache",
".",
"run_path",
"runner",
".",
"Run",
"(",
")",
"BuildOriginalCache",
".",
"run_path",
"=",
"BuildOriginalCache",
".",
"path",
"[",
":",
"-",
"4",
"]",
"+",
"'-run'",
"original_cache_trace_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"BuildOriginalCache",
".",
"run_path",
",",
"'0'",
",",
"sandwich_runner",
".",
"TRACE_FILENAME",
")",
"@",
"self",
".",
"RegisterTask",
"(",
"'common/patched-cache.zip'",
",",
"[",
"BuildOriginalCache",
"]",
")",
"def",
"BuildPatchedCache",
"(",
")",
":",
"_PatchCacheArchive",
"(",
"BuildOriginalCache",
".",
"path",
",",
"original_cache_trace_path",
",",
"BuildPatchedCache",
".",
"path",
")",
"@",
"self",
".",
"RegisterTask",
"(",
"'common/patched-cache-validation.json'",
",",
"[",
"BuildPatchedCache",
"]",
")",
"def",
"ValidatePatchedCache",
"(",
")",
":",
"cache_validation_result",
"=",
"_ValidateCacheArchiveContent",
"(",
"original_cache_trace_path",
",",
"BuildPatchedCache",
".",
"path",
")",
"with",
"open",
"(",
"ValidatePatchedCache",
".",
"path",
",",
"'w'",
")",
"as",
"output",
":",
"json",
".",
"dump",
"(",
"cache_validation_result",
",",
"output",
")",
"self",
".",
"_wpr_archive_path",
"=",
"BuildPatchedWpr",
".",
"path",
"self",
".",
"_trace_from_grabbing_reference_cache",
"=",
"original_cache_trace_path",
"self",
".",
"_cache_path",
"=",
"BuildPatchedCache",
".",
"path",
"self",
".",
"_cache_validation_task",
"=",
"ValidatePatchedCache",
"self",
".",
"_common_builder",
".",
"default_final_tasks",
".",
"append",
"(",
"ValidatePatchedCache",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/android/loading/sandwich_prefetch.py#L510-L585 |
||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | Canvas.find_all | (self) | return self.find('all') | Return all items. | Return all items. | [
"Return",
"all",
"items",
"."
] | def find_all(self):
"""Return all items."""
return self.find('all') | [
"def",
"find_all",
"(",
"self",
")",
":",
"return",
"self",
".",
"find",
"(",
"'all'",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py#L2297-L2299 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/arrays/period.py | python | period_array | (
data: Sequence[Optional[Period]],
freq: Optional[Union[str, Tick]] = None,
copy: bool = False,
) | return PeriodArray._from_sequence(data, dtype=dtype) | Construct a new PeriodArray from a sequence of Period scalars.
Parameters
----------
data : Sequence of Period objects
A sequence of Period objects. These are required to all have
the same ``freq.`` Missing values can be indicated by ``None``
or ``pandas.NaT``.
freq : str, Tick, or Offset
The frequency of every element of the array. This can be specified
to avoid inferring the `freq` from `data`.
copy : bool, default False
Whether to ensure a copy of the data is made.
Returns
-------
PeriodArray
See Also
--------
PeriodArray
pandas.PeriodIndex
Examples
--------
>>> period_array([pd.Period('2017', freq='A'),
... pd.Period('2018', freq='A')])
<PeriodArray>
['2017', '2018']
Length: 2, dtype: period[A-DEC]
>>> period_array([pd.Period('2017', freq='A'),
... pd.Period('2018', freq='A'),
... pd.NaT])
<PeriodArray>
['2017', '2018', 'NaT']
Length: 3, dtype: period[A-DEC]
Integers that look like years are handled
>>> period_array([2000, 2001, 2002], freq='D')
['2000-01-01', '2001-01-01', '2002-01-01']
Length: 3, dtype: period[D]
Datetime-like strings may also be passed
>>> period_array(['2000-Q1', '2000-Q2', '2000-Q3', '2000-Q4'], freq='Q')
<PeriodArray>
['2000Q1', '2000Q2', '2000Q3', '2000Q4']
Length: 4, dtype: period[Q-DEC] | Construct a new PeriodArray from a sequence of Period scalars. | [
"Construct",
"a",
"new",
"PeriodArray",
"from",
"a",
"sequence",
"of",
"Period",
"scalars",
"."
] | def period_array(
data: Sequence[Optional[Period]],
freq: Optional[Union[str, Tick]] = None,
copy: bool = False,
) -> PeriodArray:
"""
Construct a new PeriodArray from a sequence of Period scalars.
Parameters
----------
data : Sequence of Period objects
A sequence of Period objects. These are required to all have
the same ``freq.`` Missing values can be indicated by ``None``
or ``pandas.NaT``.
freq : str, Tick, or Offset
The frequency of every element of the array. This can be specified
to avoid inferring the `freq` from `data`.
copy : bool, default False
Whether to ensure a copy of the data is made.
Returns
-------
PeriodArray
See Also
--------
PeriodArray
pandas.PeriodIndex
Examples
--------
>>> period_array([pd.Period('2017', freq='A'),
... pd.Period('2018', freq='A')])
<PeriodArray>
['2017', '2018']
Length: 2, dtype: period[A-DEC]
>>> period_array([pd.Period('2017', freq='A'),
... pd.Period('2018', freq='A'),
... pd.NaT])
<PeriodArray>
['2017', '2018', 'NaT']
Length: 3, dtype: period[A-DEC]
Integers that look like years are handled
>>> period_array([2000, 2001, 2002], freq='D')
['2000-01-01', '2001-01-01', '2002-01-01']
Length: 3, dtype: period[D]
Datetime-like strings may also be passed
>>> period_array(['2000-Q1', '2000-Q2', '2000-Q3', '2000-Q4'], freq='Q')
<PeriodArray>
['2000Q1', '2000Q2', '2000Q3', '2000Q4']
Length: 4, dtype: period[Q-DEC]
"""
if is_datetime64_dtype(data):
return PeriodArray._from_datetime64(data, freq)
if isinstance(data, (ABCPeriodIndex, ABCSeries, PeriodArray)):
return PeriodArray(data, freq)
# other iterable of some kind
if not isinstance(data, (np.ndarray, list, tuple)):
data = list(data)
data = np.asarray(data)
dtype: Optional[PeriodDtype]
if freq:
dtype = PeriodDtype(freq)
else:
dtype = None
if is_float_dtype(data) and len(data) > 0:
raise TypeError("PeriodIndex does not allow floating point in construction")
data = ensure_object(data)
return PeriodArray._from_sequence(data, dtype=dtype) | [
"def",
"period_array",
"(",
"data",
":",
"Sequence",
"[",
"Optional",
"[",
"Period",
"]",
"]",
",",
"freq",
":",
"Optional",
"[",
"Union",
"[",
"str",
",",
"Tick",
"]",
"]",
"=",
"None",
",",
"copy",
":",
"bool",
"=",
"False",
",",
")",
"->",
"PeriodArray",
":",
"if",
"is_datetime64_dtype",
"(",
"data",
")",
":",
"return",
"PeriodArray",
".",
"_from_datetime64",
"(",
"data",
",",
"freq",
")",
"if",
"isinstance",
"(",
"data",
",",
"(",
"ABCPeriodIndex",
",",
"ABCSeries",
",",
"PeriodArray",
")",
")",
":",
"return",
"PeriodArray",
"(",
"data",
",",
"freq",
")",
"# other iterable of some kind",
"if",
"not",
"isinstance",
"(",
"data",
",",
"(",
"np",
".",
"ndarray",
",",
"list",
",",
"tuple",
")",
")",
":",
"data",
"=",
"list",
"(",
"data",
")",
"data",
"=",
"np",
".",
"asarray",
"(",
"data",
")",
"dtype",
":",
"Optional",
"[",
"PeriodDtype",
"]",
"if",
"freq",
":",
"dtype",
"=",
"PeriodDtype",
"(",
"freq",
")",
"else",
":",
"dtype",
"=",
"None",
"if",
"is_float_dtype",
"(",
"data",
")",
"and",
"len",
"(",
"data",
")",
">",
"0",
":",
"raise",
"TypeError",
"(",
"\"PeriodIndex does not allow floating point in construction\"",
")",
"data",
"=",
"ensure_object",
"(",
"data",
")",
"return",
"PeriodArray",
".",
"_from_sequence",
"(",
"data",
",",
"dtype",
"=",
"dtype",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/arrays/period.py#L794-L873 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/richtext.py | python | RichTextCtrl.ApplyTextEffectToSelection | (*args, **kwargs) | return _richtext.RichTextCtrl_ApplyTextEffectToSelection(*args, **kwargs) | ApplyTextEffectToSelection(self, int flags) -> bool | ApplyTextEffectToSelection(self, int flags) -> bool | [
"ApplyTextEffectToSelection",
"(",
"self",
"int",
"flags",
")",
"-",
">",
"bool"
] | def ApplyTextEffectToSelection(*args, **kwargs):
"""ApplyTextEffectToSelection(self, int flags) -> bool"""
return _richtext.RichTextCtrl_ApplyTextEffectToSelection(*args, **kwargs) | [
"def",
"ApplyTextEffectToSelection",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextCtrl_ApplyTextEffectToSelection",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/richtext.py#L3975-L3977 |
|
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Runtime/VART/vart/rnn-runner/apps/imdb_sentiment_detection/utils/hdf5_format.py | python | save_optimizer_weights_to_hdf5_group | (hdf5_group, optimizer) | Saves optimizer weights of a optimizer to a HDF5 group.
Arguments:
hdf5_group: HDF5 group.
optimizer: optimizer instance. | Saves optimizer weights of a optimizer to a HDF5 group. | [
"Saves",
"optimizer",
"weights",
"of",
"a",
"optimizer",
"to",
"a",
"HDF5",
"group",
"."
] | def save_optimizer_weights_to_hdf5_group(hdf5_group, optimizer):
"""Saves optimizer weights of a optimizer to a HDF5 group.
Arguments:
hdf5_group: HDF5 group.
optimizer: optimizer instance.
"""
symbolic_weights = getattr(optimizer, 'weights')
if symbolic_weights:
weights_group = hdf5_group.create_group('optimizer_weights')
weight_names = [str(w.name).encode('utf8') for w in symbolic_weights]
save_attributes_to_hdf5_group(weights_group, 'weight_names', weight_names)
weight_values = K.batch_get_value(symbolic_weights)
for name, val in zip(weight_names, weight_values):
param_dset = weights_group.create_dataset(
name, val.shape, dtype=val.dtype)
if not val.shape:
# scalar
param_dset[()] = val
else:
param_dset[:] = val | [
"def",
"save_optimizer_weights_to_hdf5_group",
"(",
"hdf5_group",
",",
"optimizer",
")",
":",
"symbolic_weights",
"=",
"getattr",
"(",
"optimizer",
",",
"'weights'",
")",
"if",
"symbolic_weights",
":",
"weights_group",
"=",
"hdf5_group",
".",
"create_group",
"(",
"'optimizer_weights'",
")",
"weight_names",
"=",
"[",
"str",
"(",
"w",
".",
"name",
")",
".",
"encode",
"(",
"'utf8'",
")",
"for",
"w",
"in",
"symbolic_weights",
"]",
"save_attributes_to_hdf5_group",
"(",
"weights_group",
",",
"'weight_names'",
",",
"weight_names",
")",
"weight_values",
"=",
"K",
".",
"batch_get_value",
"(",
"symbolic_weights",
")",
"for",
"name",
",",
"val",
"in",
"zip",
"(",
"weight_names",
",",
"weight_values",
")",
":",
"param_dset",
"=",
"weights_group",
".",
"create_dataset",
"(",
"name",
",",
"val",
".",
"shape",
",",
"dtype",
"=",
"val",
".",
"dtype",
")",
"if",
"not",
"val",
".",
"shape",
":",
"# scalar",
"param_dset",
"[",
"(",
")",
"]",
"=",
"val",
"else",
":",
"param_dset",
"[",
":",
"]",
"=",
"val"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Runtime/VART/vart/rnn-runner/apps/imdb_sentiment_detection/utils/hdf5_format.py#L585-L606 |
||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/linear_optimizer/python/ops/sparse_feature_column.py | python | SparseFeatureColumn.example_indices | (self) | return self._example_indices | The example indices represented as a dense tensor.
Returns:
A 1-D Tensor of int64 with shape `[N]`. | The example indices represented as a dense tensor. | [
"The",
"example",
"indices",
"represented",
"as",
"a",
"dense",
"tensor",
"."
] | def example_indices(self):
"""The example indices represented as a dense tensor.
Returns:
A 1-D Tensor of int64 with shape `[N]`.
"""
return self._example_indices | [
"def",
"example_indices",
"(",
"self",
")",
":",
"return",
"self",
".",
"_example_indices"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/linear_optimizer/python/ops/sparse_feature_column.py#L98-L104 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/extern/aui/auibook.py | python | AuiNotebook.FindNextActiveTab | (self, ctrl_idx, ctrl) | return 0 | Finds the next active tab (used mainly when :class:`AuiNotebook` has inactive/disabled
tabs in it).
:param integer `ctrl_idx`: the index of the first (most obvious) tab to check for active status;
:param `ctrl`: an instance of :class:`AuiTabCtrl`. | Finds the next active tab (used mainly when :class:`AuiNotebook` has inactive/disabled
tabs in it). | [
"Finds",
"the",
"next",
"active",
"tab",
"(",
"used",
"mainly",
"when",
":",
"class",
":",
"AuiNotebook",
"has",
"inactive",
"/",
"disabled",
"tabs",
"in",
"it",
")",
"."
] | def FindNextActiveTab(self, ctrl_idx, ctrl):
"""
Finds the next active tab (used mainly when :class:`AuiNotebook` has inactive/disabled
tabs in it).
:param integer `ctrl_idx`: the index of the first (most obvious) tab to check for active status;
:param `ctrl`: an instance of :class:`AuiTabCtrl`.
"""
if self.GetEnabled(ctrl_idx):
return ctrl_idx
for indx in xrange(ctrl_idx, ctrl.GetPageCount()):
if self.GetEnabled(indx):
return indx
for indx in xrange(ctrl_idx, -1, -1):
if self.GetEnabled(indx):
return indx
return 0 | [
"def",
"FindNextActiveTab",
"(",
"self",
",",
"ctrl_idx",
",",
"ctrl",
")",
":",
"if",
"self",
".",
"GetEnabled",
"(",
"ctrl_idx",
")",
":",
"return",
"ctrl_idx",
"for",
"indx",
"in",
"xrange",
"(",
"ctrl_idx",
",",
"ctrl",
".",
"GetPageCount",
"(",
")",
")",
":",
"if",
"self",
".",
"GetEnabled",
"(",
"indx",
")",
":",
"return",
"indx",
"for",
"indx",
"in",
"xrange",
"(",
"ctrl_idx",
",",
"-",
"1",
",",
"-",
"1",
")",
":",
"if",
"self",
".",
"GetEnabled",
"(",
"indx",
")",
":",
"return",
"indx",
"return",
"0"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/auibook.py#L3499-L3519 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/modulefinder.py | python | ModuleFinder.any_missing_maybe | (self) | return missing, maybe | Return two lists, one with modules that are certainly missing
and one with modules that *may* be missing. The latter names could
either be submodules *or* just global names in the package.
The reason it can't always be determined is that it's impossible to
tell which names are imported when "from module import *" is done
with an extension module, short of actually importing it. | Return two lists, one with modules that are certainly missing
and one with modules that *may* be missing. The latter names could
either be submodules *or* just global names in the package. | [
"Return",
"two",
"lists",
"one",
"with",
"modules",
"that",
"are",
"certainly",
"missing",
"and",
"one",
"with",
"modules",
"that",
"*",
"may",
"*",
"be",
"missing",
".",
"The",
"latter",
"names",
"could",
"either",
"be",
"submodules",
"*",
"or",
"*",
"just",
"global",
"names",
"in",
"the",
"package",
"."
] | def any_missing_maybe(self):
"""Return two lists, one with modules that are certainly missing
and one with modules that *may* be missing. The latter names could
either be submodules *or* just global names in the package.
The reason it can't always be determined is that it's impossible to
tell which names are imported when "from module import *" is done
with an extension module, short of actually importing it.
"""
missing = []
maybe = []
for name in self.badmodules:
if name in self.excludes:
continue
i = name.rfind(".")
if i < 0:
missing.append(name)
continue
subname = name[i+1:]
pkgname = name[:i]
pkg = self.modules.get(pkgname)
if pkg is not None:
if pkgname in self.badmodules[name]:
# The package tried to import this module itself and
# failed. It's definitely missing.
missing.append(name)
elif subname in pkg.globalnames:
# It's a global in the package: definitely not missing.
pass
elif pkg.starimports:
# It could be missing, but the package did an "import *"
# from a non-Python module, so we simply can't be sure.
maybe.append(name)
else:
# It's not a global in the package, the package didn't
# do funny star imports, it's very likely to be missing.
# The symbol could be inserted into the package from the
# outside, but since that's not good style we simply list
# it missing.
missing.append(name)
else:
missing.append(name)
missing.sort()
maybe.sort()
return missing, maybe | [
"def",
"any_missing_maybe",
"(",
"self",
")",
":",
"missing",
"=",
"[",
"]",
"maybe",
"=",
"[",
"]",
"for",
"name",
"in",
"self",
".",
"badmodules",
":",
"if",
"name",
"in",
"self",
".",
"excludes",
":",
"continue",
"i",
"=",
"name",
".",
"rfind",
"(",
"\".\"",
")",
"if",
"i",
"<",
"0",
":",
"missing",
".",
"append",
"(",
"name",
")",
"continue",
"subname",
"=",
"name",
"[",
"i",
"+",
"1",
":",
"]",
"pkgname",
"=",
"name",
"[",
":",
"i",
"]",
"pkg",
"=",
"self",
".",
"modules",
".",
"get",
"(",
"pkgname",
")",
"if",
"pkg",
"is",
"not",
"None",
":",
"if",
"pkgname",
"in",
"self",
".",
"badmodules",
"[",
"name",
"]",
":",
"# The package tried to import this module itself and",
"# failed. It's definitely missing.",
"missing",
".",
"append",
"(",
"name",
")",
"elif",
"subname",
"in",
"pkg",
".",
"globalnames",
":",
"# It's a global in the package: definitely not missing.",
"pass",
"elif",
"pkg",
".",
"starimports",
":",
"# It could be missing, but the package did an \"import *\"",
"# from a non-Python module, so we simply can't be sure.",
"maybe",
".",
"append",
"(",
"name",
")",
"else",
":",
"# It's not a global in the package, the package didn't",
"# do funny star imports, it's very likely to be missing.",
"# The symbol could be inserted into the package from the",
"# outside, but since that's not good style we simply list",
"# it missing.",
"missing",
".",
"append",
"(",
"name",
")",
"else",
":",
"missing",
".",
"append",
"(",
"name",
")",
"missing",
".",
"sort",
"(",
")",
"maybe",
".",
"sort",
"(",
")",
"return",
"missing",
",",
"maybe"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/modulefinder.py#L495-L539 |
|
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/maximum-binary-tree.py | python | Solution.constructMaximumBinaryTree | (self, nums) | return nodeStack[0] | :type nums: List[int]
:rtype: TreeNode | :type nums: List[int]
:rtype: TreeNode | [
":",
"type",
"nums",
":",
"List",
"[",
"int",
"]",
":",
"rtype",
":",
"TreeNode"
] | def constructMaximumBinaryTree(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
# https://github.com/kamyu104/LintCode/blob/master/C++/max-tree.cpp
nodeStack = []
for num in nums:
node = TreeNode(num)
while nodeStack and num > nodeStack[-1].val:
node.left = nodeStack.pop()
if nodeStack:
nodeStack[-1].right = node
nodeStack.append(node)
return nodeStack[0] | [
"def",
"constructMaximumBinaryTree",
"(",
"self",
",",
"nums",
")",
":",
"# https://github.com/kamyu104/LintCode/blob/master/C++/max-tree.cpp",
"nodeStack",
"=",
"[",
"]",
"for",
"num",
"in",
"nums",
":",
"node",
"=",
"TreeNode",
"(",
"num",
")",
"while",
"nodeStack",
"and",
"num",
">",
"nodeStack",
"[",
"-",
"1",
"]",
".",
"val",
":",
"node",
".",
"left",
"=",
"nodeStack",
".",
"pop",
"(",
")",
"if",
"nodeStack",
":",
"nodeStack",
"[",
"-",
"1",
"]",
".",
"right",
"=",
"node",
"nodeStack",
".",
"append",
"(",
"node",
")",
"return",
"nodeStack",
"[",
"0",
"]"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/maximum-binary-tree.py#L12-L26 |
|
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/parallel/_cost_model_context.py | python | _CostModelContext.get_costmodel_allreduce_fusion_tail_percent | (self) | return self._context_handle.get_costmodel_allreduce_fusion_tail_percent() | Get costmodel allreduce fusion tail percent.
Raises:
ValueError: If context handle is none. | Get costmodel allreduce fusion tail percent. | [
"Get",
"costmodel",
"allreduce",
"fusion",
"tail",
"percent",
"."
] | def get_costmodel_allreduce_fusion_tail_percent(self):
"""
Get costmodel allreduce fusion tail percent.
Raises:
ValueError: If context handle is none.
"""
if self._context_handle is None:
raise ValueError("Context handle is none in context!!!")
return self._context_handle.get_costmodel_allreduce_fusion_tail_percent() | [
"def",
"get_costmodel_allreduce_fusion_tail_percent",
"(",
"self",
")",
":",
"if",
"self",
".",
"_context_handle",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Context handle is none in context!!!\"",
")",
"return",
"self",
".",
"_context_handle",
".",
"get_costmodel_allreduce_fusion_tail_percent",
"(",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/parallel/_cost_model_context.py#L364-L373 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/infobar.py | python | InfoBar.SetShowHideEffects | (self, showEffect, hideEffect) | Set the effects to use when showing and hiding the bar.
Either or both of the parameters can be set to ``wx.SHOW_EFFECT_NONE`` to disable using
effects entirely.
By default, the info bar uses ``wx.SHOW_EFFECT_SLIDE_TO_BOTTOM`` effect for showing itself
and ``wx.SHOW_EFFECT_SLIDE_TO_TOP`` for hiding if it is the first element of the containing
sizer and reverse effects if it's the last one. If it is neither the first nor the last element,
no effect is used to avoid the use of an inappropriate one and this function must be called
if an effect is desired.
:param integer `showEffect`: the effect to use when showing the bar;
:param integer `hideEffect`: the effect to use when hiding the bar.
The `showEffect` and `hideEffect` parameters can take one of the following bit:
==================================== ===========================================================
`ShowEffect` Flag Description
==================================== ===========================================================
``SHOW_EFFECT_NONE`` No effect, equivalent to normal `Show()` or `Hide()` call.
``SHOW_EFFECT_ROLL_TO_LEFT`` Roll window to the left.
``SHOW_EFFECT_ROLL_TO_RIGHT`` Roll window to the right.
``SHOW_EFFECT_ROLL_TO_TOP`` Roll window to the top.
``SHOW_EFFECT_ROLL_TO_BOTTOM`` Roll window to the bottom.
``SHOW_EFFECT_SLIDE_TO_LEFT`` Slide window to the left.
``SHOW_EFFECT_SLIDE_TO_RIGHT`` Slide window to the right.
``SHOW_EFFECT_SLIDE_TO_TOP`` Slide window to the top.
``SHOW_EFFECT_SLIDE_TO_BOTTOM`` Slide window to the bottom.
``SHOW_EFFECT_BLEND`` Fade in or out effect.
``SHOW_EFFECT_EXPAND`` Expanding or collapsing effect.
==================================== =========================================================== | Set the effects to use when showing and hiding the bar. | [
"Set",
"the",
"effects",
"to",
"use",
"when",
"showing",
"and",
"hiding",
"the",
"bar",
"."
] | def SetShowHideEffects(self, showEffect, hideEffect):
"""
Set the effects to use when showing and hiding the bar.
Either or both of the parameters can be set to ``wx.SHOW_EFFECT_NONE`` to disable using
effects entirely.
By default, the info bar uses ``wx.SHOW_EFFECT_SLIDE_TO_BOTTOM`` effect for showing itself
and ``wx.SHOW_EFFECT_SLIDE_TO_TOP`` for hiding if it is the first element of the containing
sizer and reverse effects if it's the last one. If it is neither the first nor the last element,
no effect is used to avoid the use of an inappropriate one and this function must be called
if an effect is desired.
:param integer `showEffect`: the effect to use when showing the bar;
:param integer `hideEffect`: the effect to use when hiding the bar.
The `showEffect` and `hideEffect` parameters can take one of the following bit:
==================================== ===========================================================
`ShowEffect` Flag Description
==================================== ===========================================================
``SHOW_EFFECT_NONE`` No effect, equivalent to normal `Show()` or `Hide()` call.
``SHOW_EFFECT_ROLL_TO_LEFT`` Roll window to the left.
``SHOW_EFFECT_ROLL_TO_RIGHT`` Roll window to the right.
``SHOW_EFFECT_ROLL_TO_TOP`` Roll window to the top.
``SHOW_EFFECT_ROLL_TO_BOTTOM`` Roll window to the bottom.
``SHOW_EFFECT_SLIDE_TO_LEFT`` Slide window to the left.
``SHOW_EFFECT_SLIDE_TO_RIGHT`` Slide window to the right.
``SHOW_EFFECT_SLIDE_TO_TOP`` Slide window to the top.
``SHOW_EFFECT_SLIDE_TO_BOTTOM`` Slide window to the bottom.
``SHOW_EFFECT_BLEND`` Fade in or out effect.
``SHOW_EFFECT_EXPAND`` Expanding or collapsing effect.
==================================== ===========================================================
"""
self._showEffect = showEffect
self._hideEffect = hideEffect | [
"def",
"SetShowHideEffects",
"(",
"self",
",",
"showEffect",
",",
"hideEffect",
")",
":",
"self",
".",
"_showEffect",
"=",
"showEffect",
"self",
".",
"_hideEffect",
"=",
"hideEffect"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/infobar.py#L775-L812 |
||
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/resmokelib/run/__init__.py | python | TestRunner.run_tests | (self) | Run the suite and tests specified. | Run the suite and tests specified. | [
"Run",
"the",
"suite",
"and",
"tests",
"specified",
"."
] | def run_tests(self):
"""Run the suite and tests specified."""
self._resmoke_logger.info("verbatim resmoke.py invocation: %s",
" ".join([shlex.quote(arg) for arg in sys.argv]))
if config.EVERGREEN_TASK_DOC:
self._resmoke_logger.info("Evergreen task documentation:\n%s",
config.EVERGREEN_TASK_DOC)
elif config.EVERGREEN_TASK_NAME:
self._resmoke_logger.info("Evergreen task documentation is absent for this task.")
task_name = utils.get_task_name_without_suffix(config.EVERGREEN_TASK_NAME,
config.EVERGREEN_VARIANT_NAME)
self._resmoke_logger.info(
"If you are familiar with the functionality of %s task, "
"please consider adding documentation for it in %s", task_name,
os.path.join(config.CONFIG_DIR, "evg_task_doc", "evg_task_doc.yml"))
self._log_local_resmoke_invocation()
suites = None
try:
suites = self._get_suites()
self._setup_archival()
if config.SPAWN_USING == "jasper":
self._setup_jasper()
self._setup_signal_handler(suites)
for suite in suites:
self._interrupted = self._run_suite(suite)
if self._interrupted or (suite.options.fail_fast and suite.return_code != 0):
self._log_resmoke_summary(suites)
self.exit(suite.return_code)
self._log_resmoke_summary(suites)
# Exit with a nonzero code if any of the suites failed.
exit_code = max(suite.return_code for suite in suites)
self.exit(exit_code)
finally:
self._exit_archival()
if suites:
reportfile.write(suites) | [
"def",
"run_tests",
"(",
"self",
")",
":",
"self",
".",
"_resmoke_logger",
".",
"info",
"(",
"\"verbatim resmoke.py invocation: %s\"",
",",
"\" \"",
".",
"join",
"(",
"[",
"shlex",
".",
"quote",
"(",
"arg",
")",
"for",
"arg",
"in",
"sys",
".",
"argv",
"]",
")",
")",
"if",
"config",
".",
"EVERGREEN_TASK_DOC",
":",
"self",
".",
"_resmoke_logger",
".",
"info",
"(",
"\"Evergreen task documentation:\\n%s\"",
",",
"config",
".",
"EVERGREEN_TASK_DOC",
")",
"elif",
"config",
".",
"EVERGREEN_TASK_NAME",
":",
"self",
".",
"_resmoke_logger",
".",
"info",
"(",
"\"Evergreen task documentation is absent for this task.\"",
")",
"task_name",
"=",
"utils",
".",
"get_task_name_without_suffix",
"(",
"config",
".",
"EVERGREEN_TASK_NAME",
",",
"config",
".",
"EVERGREEN_VARIANT_NAME",
")",
"self",
".",
"_resmoke_logger",
".",
"info",
"(",
"\"If you are familiar with the functionality of %s task, \"",
"\"please consider adding documentation for it in %s\"",
",",
"task_name",
",",
"os",
".",
"path",
".",
"join",
"(",
"config",
".",
"CONFIG_DIR",
",",
"\"evg_task_doc\"",
",",
"\"evg_task_doc.yml\"",
")",
")",
"self",
".",
"_log_local_resmoke_invocation",
"(",
")",
"suites",
"=",
"None",
"try",
":",
"suites",
"=",
"self",
".",
"_get_suites",
"(",
")",
"self",
".",
"_setup_archival",
"(",
")",
"if",
"config",
".",
"SPAWN_USING",
"==",
"\"jasper\"",
":",
"self",
".",
"_setup_jasper",
"(",
")",
"self",
".",
"_setup_signal_handler",
"(",
"suites",
")",
"for",
"suite",
"in",
"suites",
":",
"self",
".",
"_interrupted",
"=",
"self",
".",
"_run_suite",
"(",
"suite",
")",
"if",
"self",
".",
"_interrupted",
"or",
"(",
"suite",
".",
"options",
".",
"fail_fast",
"and",
"suite",
".",
"return_code",
"!=",
"0",
")",
":",
"self",
".",
"_log_resmoke_summary",
"(",
"suites",
")",
"self",
".",
"exit",
"(",
"suite",
".",
"return_code",
")",
"self",
".",
"_log_resmoke_summary",
"(",
"suites",
")",
"# Exit with a nonzero code if any of the suites failed.",
"exit_code",
"=",
"max",
"(",
"suite",
".",
"return_code",
"for",
"suite",
"in",
"suites",
")",
"self",
".",
"exit",
"(",
"exit_code",
")",
"finally",
":",
"self",
".",
"_exit_archival",
"(",
")",
"if",
"suites",
":",
"reportfile",
".",
"write",
"(",
"suites",
")"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/resmokelib/run/__init__.py#L216-L257 |
||
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/coverage/control.py | python | coverage.__init__ | (self, data_file=None, data_suffix=None, cover_pylib=None,
auto_data=False, timid=None, branch=None, config_file=True,
source=None, omit=None, include=None) | `data_file` is the base name of the data file to use, defaulting to
".coverage". `data_suffix` is appended (with a dot) to `data_file` to
create the final file name. If `data_suffix` is simply True, then a
suffix is created with the machine and process identity included.
`cover_pylib` is a boolean determining whether Python code installed
with the Python interpreter is measured. This includes the Python
standard library and any packages installed with the interpreter.
If `auto_data` is true, then any existing data file will be read when
coverage measurement starts, and data will be saved automatically when
measurement stops.
If `timid` is true, then a slower and simpler trace function will be
used. This is important for some environments where manipulation of
tracing functions breaks the faster trace function.
If `branch` is true, then branch coverage will be measured in addition
to the usual statement coverage.
`config_file` determines what config file to read. If it is a string,
it is the name of the config file to read. If it is True, then a
standard file is read (".coveragerc"). If it is False, then no file is
read.
`source` is a list of file paths or package names. Only code located
in the trees indicated by the file paths or package names will be
measured.
`include` and `omit` are lists of filename patterns. Files that match
`include` will be measured, files that match `omit` will not. Each
will also accept a single string argument. | `data_file` is the base name of the data file to use, defaulting to
".coverage". `data_suffix` is appended (with a dot) to `data_file` to
create the final file name. If `data_suffix` is simply True, then a
suffix is created with the machine and process identity included. | [
"data_file",
"is",
"the",
"base",
"name",
"of",
"the",
"data",
"file",
"to",
"use",
"defaulting",
"to",
".",
"coverage",
".",
"data_suffix",
"is",
"appended",
"(",
"with",
"a",
"dot",
")",
"to",
"data_file",
"to",
"create",
"the",
"final",
"file",
"name",
".",
"If",
"data_suffix",
"is",
"simply",
"True",
"then",
"a",
"suffix",
"is",
"created",
"with",
"the",
"machine",
"and",
"process",
"identity",
"included",
"."
] | def __init__(self, data_file=None, data_suffix=None, cover_pylib=None,
auto_data=False, timid=None, branch=None, config_file=True,
source=None, omit=None, include=None):
"""
`data_file` is the base name of the data file to use, defaulting to
".coverage". `data_suffix` is appended (with a dot) to `data_file` to
create the final file name. If `data_suffix` is simply True, then a
suffix is created with the machine and process identity included.
`cover_pylib` is a boolean determining whether Python code installed
with the Python interpreter is measured. This includes the Python
standard library and any packages installed with the interpreter.
If `auto_data` is true, then any existing data file will be read when
coverage measurement starts, and data will be saved automatically when
measurement stops.
If `timid` is true, then a slower and simpler trace function will be
used. This is important for some environments where manipulation of
tracing functions breaks the faster trace function.
If `branch` is true, then branch coverage will be measured in addition
to the usual statement coverage.
`config_file` determines what config file to read. If it is a string,
it is the name of the config file to read. If it is True, then a
standard file is read (".coveragerc"). If it is False, then no file is
read.
`source` is a list of file paths or package names. Only code located
in the trees indicated by the file paths or package names will be
measured.
`include` and `omit` are lists of filename patterns. Files that match
`include` will be measured, files that match `omit` will not. Each
will also accept a single string argument.
"""
from coverage import __version__
# A record of all the warnings that have been issued.
self._warnings = []
# Build our configuration from a number of sources:
# 1: defaults:
self.config = CoverageConfig()
# 2: from the coveragerc file:
if config_file:
if config_file is True:
config_file = ".coveragerc"
try:
self.config.from_file(config_file)
except ValueError:
_, err, _ = sys.exc_info()
raise CoverageException(
"Couldn't read config file %s: %s" % (config_file, err)
)
# 3: from environment variables:
self.config.from_environment('COVERAGE_OPTIONS')
env_data_file = os.environ.get('COVERAGE_FILE')
if env_data_file:
self.config.data_file = env_data_file
# 4: from constructor arguments:
if isinstance(omit, string_class):
omit = [omit]
if isinstance(include, string_class):
include = [include]
self.config.from_args(
data_file=data_file, cover_pylib=cover_pylib, timid=timid,
branch=branch, parallel=bool_or_none(data_suffix),
source=source, omit=omit, include=include
)
self.auto_data = auto_data
self.atexit_registered = False
# _exclude_re is a dict mapping exclusion list names to compiled
# regexes.
self._exclude_re = {}
self._exclude_regex_stale()
self.file_locator = FileLocator()
# The source argument can be directories or package names.
self.source = []
self.source_pkgs = []
for src in self.config.source or []:
if os.path.exists(src):
self.source.append(self.file_locator.canonical_filename(src))
else:
self.source_pkgs.append(src)
self.omit = self._prep_patterns(self.config.omit)
self.include = self._prep_patterns(self.config.include)
self.collector = Collector(
self._should_trace, timid=self.config.timid,
branch=self.config.branch, warn=self._warn
)
# Suffixes are a bit tricky. We want to use the data suffix only when
# collecting data, not when combining data. So we save it as
# `self.run_suffix` now, and promote it to `self.data_suffix` if we
# find that we are collecting data later.
if data_suffix or self.config.parallel:
if not isinstance(data_suffix, string_class):
# if data_suffix=True, use .machinename.pid.random
data_suffix = True
else:
data_suffix = None
self.data_suffix = None
self.run_suffix = data_suffix
# Create the data file. We do this at construction time so that the
# data file will be written into the directory where the process
# started rather than wherever the process eventually chdir'd to.
self.data = CoverageData(
basename=self.config.data_file,
collector="coverage v%s" % __version__
)
# The dirs for files considered "installed with the interpreter".
self.pylib_dirs = []
if not self.config.cover_pylib:
# Look at where some standard modules are located. That's the
# indication for "installed with the interpreter". In some
# environments (virtualenv, for example), these modules may be
# spread across a few locations. Look at all the candidate modules
# we've imported, and take all the different ones.
for m in (atexit, os, random, socket):
if hasattr(m, "__file__"):
m_dir = self._canonical_dir(m.__file__)
if m_dir not in self.pylib_dirs:
self.pylib_dirs.append(m_dir)
# To avoid tracing the coverage code itself, we skip anything located
# where we are.
self.cover_dir = self._canonical_dir(__file__)
# The matchers for _should_trace, created when tracing starts.
self.source_match = None
self.pylib_match = self.cover_match = None
self.include_match = self.omit_match = None
# Only _harvest_data once per measurement cycle.
self._harvested = False
# Set the reporting precision.
Numbers.set_precision(self.config.precision)
# When tearing down the coverage object, modules can become None.
# Saving the modules as object attributes avoids problems, but it is
# quite ad-hoc which modules need to be saved and which references
# need to use the object attributes.
self.socket = socket
self.os = os
self.random = random | [
"def",
"__init__",
"(",
"self",
",",
"data_file",
"=",
"None",
",",
"data_suffix",
"=",
"None",
",",
"cover_pylib",
"=",
"None",
",",
"auto_data",
"=",
"False",
",",
"timid",
"=",
"None",
",",
"branch",
"=",
"None",
",",
"config_file",
"=",
"True",
",",
"source",
"=",
"None",
",",
"omit",
"=",
"None",
",",
"include",
"=",
"None",
")",
":",
"from",
"coverage",
"import",
"__version__",
"# A record of all the warnings that have been issued.",
"self",
".",
"_warnings",
"=",
"[",
"]",
"# Build our configuration from a number of sources:",
"# 1: defaults:",
"self",
".",
"config",
"=",
"CoverageConfig",
"(",
")",
"# 2: from the coveragerc file:",
"if",
"config_file",
":",
"if",
"config_file",
"is",
"True",
":",
"config_file",
"=",
"\".coveragerc\"",
"try",
":",
"self",
".",
"config",
".",
"from_file",
"(",
"config_file",
")",
"except",
"ValueError",
":",
"_",
",",
"err",
",",
"_",
"=",
"sys",
".",
"exc_info",
"(",
")",
"raise",
"CoverageException",
"(",
"\"Couldn't read config file %s: %s\"",
"%",
"(",
"config_file",
",",
"err",
")",
")",
"# 3: from environment variables:",
"self",
".",
"config",
".",
"from_environment",
"(",
"'COVERAGE_OPTIONS'",
")",
"env_data_file",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'COVERAGE_FILE'",
")",
"if",
"env_data_file",
":",
"self",
".",
"config",
".",
"data_file",
"=",
"env_data_file",
"# 4: from constructor arguments:",
"if",
"isinstance",
"(",
"omit",
",",
"string_class",
")",
":",
"omit",
"=",
"[",
"omit",
"]",
"if",
"isinstance",
"(",
"include",
",",
"string_class",
")",
":",
"include",
"=",
"[",
"include",
"]",
"self",
".",
"config",
".",
"from_args",
"(",
"data_file",
"=",
"data_file",
",",
"cover_pylib",
"=",
"cover_pylib",
",",
"timid",
"=",
"timid",
",",
"branch",
"=",
"branch",
",",
"parallel",
"=",
"bool_or_none",
"(",
"data_suffix",
")",
",",
"source",
"=",
"source",
",",
"omit",
"=",
"omit",
",",
"include",
"=",
"include",
")",
"self",
".",
"auto_data",
"=",
"auto_data",
"self",
".",
"atexit_registered",
"=",
"False",
"# _exclude_re is a dict mapping exclusion list names to compiled",
"# regexes.",
"self",
".",
"_exclude_re",
"=",
"{",
"}",
"self",
".",
"_exclude_regex_stale",
"(",
")",
"self",
".",
"file_locator",
"=",
"FileLocator",
"(",
")",
"# The source argument can be directories or package names.",
"self",
".",
"source",
"=",
"[",
"]",
"self",
".",
"source_pkgs",
"=",
"[",
"]",
"for",
"src",
"in",
"self",
".",
"config",
".",
"source",
"or",
"[",
"]",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"src",
")",
":",
"self",
".",
"source",
".",
"append",
"(",
"self",
".",
"file_locator",
".",
"canonical_filename",
"(",
"src",
")",
")",
"else",
":",
"self",
".",
"source_pkgs",
".",
"append",
"(",
"src",
")",
"self",
".",
"omit",
"=",
"self",
".",
"_prep_patterns",
"(",
"self",
".",
"config",
".",
"omit",
")",
"self",
".",
"include",
"=",
"self",
".",
"_prep_patterns",
"(",
"self",
".",
"config",
".",
"include",
")",
"self",
".",
"collector",
"=",
"Collector",
"(",
"self",
".",
"_should_trace",
",",
"timid",
"=",
"self",
".",
"config",
".",
"timid",
",",
"branch",
"=",
"self",
".",
"config",
".",
"branch",
",",
"warn",
"=",
"self",
".",
"_warn",
")",
"# Suffixes are a bit tricky. We want to use the data suffix only when",
"# collecting data, not when combining data. So we save it as",
"# `self.run_suffix` now, and promote it to `self.data_suffix` if we",
"# find that we are collecting data later.",
"if",
"data_suffix",
"or",
"self",
".",
"config",
".",
"parallel",
":",
"if",
"not",
"isinstance",
"(",
"data_suffix",
",",
"string_class",
")",
":",
"# if data_suffix=True, use .machinename.pid.random",
"data_suffix",
"=",
"True",
"else",
":",
"data_suffix",
"=",
"None",
"self",
".",
"data_suffix",
"=",
"None",
"self",
".",
"run_suffix",
"=",
"data_suffix",
"# Create the data file. We do this at construction time so that the",
"# data file will be written into the directory where the process",
"# started rather than wherever the process eventually chdir'd to.",
"self",
".",
"data",
"=",
"CoverageData",
"(",
"basename",
"=",
"self",
".",
"config",
".",
"data_file",
",",
"collector",
"=",
"\"coverage v%s\"",
"%",
"__version__",
")",
"# The dirs for files considered \"installed with the interpreter\".",
"self",
".",
"pylib_dirs",
"=",
"[",
"]",
"if",
"not",
"self",
".",
"config",
".",
"cover_pylib",
":",
"# Look at where some standard modules are located. That's the",
"# indication for \"installed with the interpreter\". In some",
"# environments (virtualenv, for example), these modules may be",
"# spread across a few locations. Look at all the candidate modules",
"# we've imported, and take all the different ones.",
"for",
"m",
"in",
"(",
"atexit",
",",
"os",
",",
"random",
",",
"socket",
")",
":",
"if",
"hasattr",
"(",
"m",
",",
"\"__file__\"",
")",
":",
"m_dir",
"=",
"self",
".",
"_canonical_dir",
"(",
"m",
".",
"__file__",
")",
"if",
"m_dir",
"not",
"in",
"self",
".",
"pylib_dirs",
":",
"self",
".",
"pylib_dirs",
".",
"append",
"(",
"m_dir",
")",
"# To avoid tracing the coverage code itself, we skip anything located",
"# where we are.",
"self",
".",
"cover_dir",
"=",
"self",
".",
"_canonical_dir",
"(",
"__file__",
")",
"# The matchers for _should_trace, created when tracing starts.",
"self",
".",
"source_match",
"=",
"None",
"self",
".",
"pylib_match",
"=",
"self",
".",
"cover_match",
"=",
"None",
"self",
".",
"include_match",
"=",
"self",
".",
"omit_match",
"=",
"None",
"# Only _harvest_data once per measurement cycle.",
"self",
".",
"_harvested",
"=",
"False",
"# Set the reporting precision.",
"Numbers",
".",
"set_precision",
"(",
"self",
".",
"config",
".",
"precision",
")",
"# When tearing down the coverage object, modules can become None.",
"# Saving the modules as object attributes avoids problems, but it is",
"# quite ad-hoc which modules need to be saved and which references",
"# need to use the object attributes.",
"self",
".",
"socket",
"=",
"socket",
"self",
".",
"os",
"=",
"os",
"self",
".",
"random",
"=",
"random"
] | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/coverage/control.py#L33-L192 |
||
nyuwireless-unipd/ns3-mmwave | 4ff9e87e8079764e04cbeccd8e85bff15ae16fb3 | utils/grid.py | python | MainWindow.__init__ | (self) | return | ! Initializer
@param self this object
@return none | ! Initializer | [
"!",
"Initializer"
] | def __init__(self):
"""! Initializer
@param self this object
@return none
"""
return | [
"def",
"__init__",
"(",
"self",
")",
":",
"return"
] | https://github.com/nyuwireless-unipd/ns3-mmwave/blob/4ff9e87e8079764e04cbeccd8e85bff15ae16fb3/utils/grid.py#L1542-L1547 |
|
twtygqyy/caffe-augmentation | c76600d247e5132fa5bd89d87bb5df458341fa84 | scripts/cpp_lint.py | python | IsBlankLine | (line) | return not line or line.isspace() | Returns true if the given line is blank.
We consider a line to be blank if the line is empty or consists of
only white spaces.
Args:
line: A line of a string.
Returns:
True, if the given line is blank. | Returns true if the given line is blank. | [
"Returns",
"true",
"if",
"the",
"given",
"line",
"is",
"blank",
"."
] | def IsBlankLine(line):
"""Returns true if the given line is blank.
We consider a line to be blank if the line is empty or consists of
only white spaces.
Args:
line: A line of a string.
Returns:
True, if the given line is blank.
"""
return not line or line.isspace() | [
"def",
"IsBlankLine",
"(",
"line",
")",
":",
"return",
"not",
"line",
"or",
"line",
".",
"isspace",
"(",
")"
] | https://github.com/twtygqyy/caffe-augmentation/blob/c76600d247e5132fa5bd89d87bb5df458341fa84/scripts/cpp_lint.py#L2373-L2385 |
|
moflow/moflow | 2dfb27c799c90c6caf1477508eca3eec616ef7d2 | bap/libtracewrap/libtrace/protobuf/python/google/protobuf/service.py | python | Service.GetRequestClass | (self, method_descriptor) | Returns the class of the request message for the specified method.
CallMethod() requires that the request is of a particular subclass of
Message. GetRequestClass() gets the default instance of this required
type.
Example:
method = service.GetDescriptor().FindMethodByName("Foo")
request = stub.GetRequestClass(method)()
request.ParseFromString(input)
service.CallMethod(method, request, callback) | Returns the class of the request message for the specified method. | [
"Returns",
"the",
"class",
"of",
"the",
"request",
"message",
"for",
"the",
"specified",
"method",
"."
] | def GetRequestClass(self, method_descriptor):
"""Returns the class of the request message for the specified method.
CallMethod() requires that the request is of a particular subclass of
Message. GetRequestClass() gets the default instance of this required
type.
Example:
method = service.GetDescriptor().FindMethodByName("Foo")
request = stub.GetRequestClass(method)()
request.ParseFromString(input)
service.CallMethod(method, request, callback)
"""
raise NotImplementedError | [
"def",
"GetRequestClass",
"(",
"self",
",",
"method_descriptor",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/moflow/moflow/blob/2dfb27c799c90c6caf1477508eca3eec616ef7d2/bap/libtracewrap/libtrace/protobuf/python/google/protobuf/service.py#L93-L106 |
||
gemrb/gemrb | 730206eed8d1dd358ca5e69a62f9e099aa22ffc6 | gemrb/GUIScripts/DualClass.py | python | DCProfsDonePress | () | return | Goes to the next applicable step.
This is either skill selection, spell selection, or nothing. | Goes to the next applicable step. | [
"Goes",
"to",
"the",
"next",
"applicable",
"step",
"."
] | def DCProfsDonePress ():
"""Goes to the next applicable step.
This is either skill selection, spell selection, or nothing."""
global NewMageSpells, NewPriestMask
# check for mage spells and thief skills
SpellTable = CommonTables.ClassSkills.GetValue (ClassName, "MAGESPELL")
ClericTable = CommonTables.ClassSkills.GetValue (ClassName, "CLERICSPELL")
DruidTable = CommonTables.ClassSkills.GetValue (ClassName, "DRUIDSPELL")
if SpellTable != "*":
LUSpellSelection.OpenSpellsWindow (pc, SpellTable, 1, 1, 0)
SpellTable = GemRB.LoadTable (SpellTable)
GemRB.SetMemorizableSpellsCount (pc, SpellTable.GetValue (0, 0), IE_SPELL_TYPE_WIZARD, 0)
NewMageSpells = 1
if ClericTable != "*":
if not GemRB.HasResource(ClericTable, RES_2DA, 1):
ClericTable = "MXSPLPRS" # iwd1 doesn't have a DRUIDSPELL column in the table
# make sure we can cast spells at this level (paladins)
ClericTable = GemRB.LoadTable (ClericTable)
if ClericTable.GetRowName (0) == "1":
NewPriestMask = 0x4000
elif DruidTable != "*":
# make sure we can cast spells at this level (rangers)
if GameCheck.HasTOB ():
DruidTable = GemRB.LoadTable (DruidTable)
if DruidTable.GetRowName (0) == "1":
NewPriestMask = 0x8000
else:
NewPriestMask = 0x8000
# open the thieves selection window
OpenSkillsWindow ()
# we can be done now
DCMainDoneButton.SetState (IE_GUI_BUTTON_ENABLED)
# close out the profs window (don't assign yet!)
if DCProfsWindow:
DCProfsWindow.Unload ()
return | [
"def",
"DCProfsDonePress",
"(",
")",
":",
"global",
"NewMageSpells",
",",
"NewPriestMask",
"# check for mage spells and thief skills",
"SpellTable",
"=",
"CommonTables",
".",
"ClassSkills",
".",
"GetValue",
"(",
"ClassName",
",",
"\"MAGESPELL\"",
")",
"ClericTable",
"=",
"CommonTables",
".",
"ClassSkills",
".",
"GetValue",
"(",
"ClassName",
",",
"\"CLERICSPELL\"",
")",
"DruidTable",
"=",
"CommonTables",
".",
"ClassSkills",
".",
"GetValue",
"(",
"ClassName",
",",
"\"DRUIDSPELL\"",
")",
"if",
"SpellTable",
"!=",
"\"*\"",
":",
"LUSpellSelection",
".",
"OpenSpellsWindow",
"(",
"pc",
",",
"SpellTable",
",",
"1",
",",
"1",
",",
"0",
")",
"SpellTable",
"=",
"GemRB",
".",
"LoadTable",
"(",
"SpellTable",
")",
"GemRB",
".",
"SetMemorizableSpellsCount",
"(",
"pc",
",",
"SpellTable",
".",
"GetValue",
"(",
"0",
",",
"0",
")",
",",
"IE_SPELL_TYPE_WIZARD",
",",
"0",
")",
"NewMageSpells",
"=",
"1",
"if",
"ClericTable",
"!=",
"\"*\"",
":",
"if",
"not",
"GemRB",
".",
"HasResource",
"(",
"ClericTable",
",",
"RES_2DA",
",",
"1",
")",
":",
"ClericTable",
"=",
"\"MXSPLPRS\"",
"# iwd1 doesn't have a DRUIDSPELL column in the table",
"# make sure we can cast spells at this level (paladins)",
"ClericTable",
"=",
"GemRB",
".",
"LoadTable",
"(",
"ClericTable",
")",
"if",
"ClericTable",
".",
"GetRowName",
"(",
"0",
")",
"==",
"\"1\"",
":",
"NewPriestMask",
"=",
"0x4000",
"elif",
"DruidTable",
"!=",
"\"*\"",
":",
"# make sure we can cast spells at this level (rangers)",
"if",
"GameCheck",
".",
"HasTOB",
"(",
")",
":",
"DruidTable",
"=",
"GemRB",
".",
"LoadTable",
"(",
"DruidTable",
")",
"if",
"DruidTable",
".",
"GetRowName",
"(",
"0",
")",
"==",
"\"1\"",
":",
"NewPriestMask",
"=",
"0x8000",
"else",
":",
"NewPriestMask",
"=",
"0x8000",
"# open the thieves selection window",
"OpenSkillsWindow",
"(",
")",
"# we can be done now",
"DCMainDoneButton",
".",
"SetState",
"(",
"IE_GUI_BUTTON_ENABLED",
")",
"# close out the profs window (don't assign yet!)",
"if",
"DCProfsWindow",
":",
"DCProfsWindow",
".",
"Unload",
"(",
")",
"return"
] | https://github.com/gemrb/gemrb/blob/730206eed8d1dd358ca5e69a62f9e099aa22ffc6/gemrb/GUIScripts/DualClass.py#L520-L561 |
|
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | third_party/numpy/files/numpy/oldnumeric/ma.py | python | MaskedArray.__nonzero__ | (self) | return bool(m is not nomask and m.any()
or d is not nomask and d.any()) | returns true if any element is non-zero or masked | returns true if any element is non-zero or masked | [
"returns",
"true",
"if",
"any",
"element",
"is",
"non",
"-",
"zero",
"or",
"masked"
] | def __nonzero__(self):
"""returns true if any element is non-zero or masked
"""
# XXX: This changes bool conversion logic from MA.
# XXX: In MA bool(a) == len(a) != 0, but in numpy
# XXX: scalars do not have len
m = self._mask
d = self._data
return bool(m is not nomask and m.any()
or d is not nomask and d.any()) | [
"def",
"__nonzero__",
"(",
"self",
")",
":",
"# XXX: This changes bool conversion logic from MA.",
"# XXX: In MA bool(a) == len(a) != 0, but in numpy",
"# XXX: scalars do not have len",
"m",
"=",
"self",
".",
"_mask",
"d",
"=",
"self",
".",
"_data",
"return",
"bool",
"(",
"m",
"is",
"not",
"nomask",
"and",
"m",
".",
"any",
"(",
")",
"or",
"d",
"is",
"not",
"nomask",
"and",
"d",
".",
"any",
"(",
")",
")"
] | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/oldnumeric/ma.py#L854-L864 |
|
Kitware/ParaView | f760af9124ff4634b23ebbeab95a4f56e0261955 | Wrapping/Python/paraview/servermanager.py | python | InputProperty.__getitem__ | (self, idx) | return OutputPort(_getPyProxy(self.SMProperty.GetProxy(idx)),\
self.SMProperty.GetOutputPortForConnection(idx)) | Returns the range [min, max) of elements. Raises an IndexError
exception if an argument is out of bounds. | Returns the range [min, max) of elements. Raises an IndexError
exception if an argument is out of bounds. | [
"Returns",
"the",
"range",
"[",
"min",
"max",
")",
"of",
"elements",
".",
"Raises",
"an",
"IndexError",
"exception",
"if",
"an",
"argument",
"is",
"out",
"of",
"bounds",
"."
] | def __getitem__(self, idx):
"""Returns the range [min, max) of elements. Raises an IndexError
exception if an argument is out of bounds."""
if isinstance(idx, slice):
indices = idx.indices(len(self))
retVal = []
for i in range(*indices):
port = None
if self.SMProperty.GetProxy(i):
port = OutputPort(_getPyProxy(self.SMProperty.GetProxy(i)),\
self.SMProperty.GetOutputPortForConnection(i))
retVal.append(port)
return retVal
elif idx >= len(self) or idx < 0:
raise IndexError
return OutputPort(_getPyProxy(self.SMProperty.GetProxy(idx)),\
self.SMProperty.GetOutputPortForConnection(idx)) | [
"def",
"__getitem__",
"(",
"self",
",",
"idx",
")",
":",
"if",
"isinstance",
"(",
"idx",
",",
"slice",
")",
":",
"indices",
"=",
"idx",
".",
"indices",
"(",
"len",
"(",
"self",
")",
")",
"retVal",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"*",
"indices",
")",
":",
"port",
"=",
"None",
"if",
"self",
".",
"SMProperty",
".",
"GetProxy",
"(",
"i",
")",
":",
"port",
"=",
"OutputPort",
"(",
"_getPyProxy",
"(",
"self",
".",
"SMProperty",
".",
"GetProxy",
"(",
"i",
")",
")",
",",
"self",
".",
"SMProperty",
".",
"GetOutputPortForConnection",
"(",
"i",
")",
")",
"retVal",
".",
"append",
"(",
"port",
")",
"return",
"retVal",
"elif",
"idx",
">=",
"len",
"(",
"self",
")",
"or",
"idx",
"<",
"0",
":",
"raise",
"IndexError",
"return",
"OutputPort",
"(",
"_getPyProxy",
"(",
"self",
".",
"SMProperty",
".",
"GetProxy",
"(",
"idx",
")",
")",
",",
"self",
".",
"SMProperty",
".",
"GetOutputPortForConnection",
"(",
"idx",
")",
")"
] | https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/Wrapping/Python/paraview/servermanager.py#L1426-L1442 |
|
apache/impala | 8ddac48f3428c86f2cbd037ced89cfb903298b12 | shell/ext-py/six-1.14.0/six.py | python | ensure_str | (s, encoding='utf-8', errors='strict') | return s | Coerce *s* to `str`.
For Python 2:
- `unicode` -> encoded to `str`
- `str` -> `str`
For Python 3:
- `str` -> `str`
- `bytes` -> decoded to `str` | Coerce *s* to `str`. | [
"Coerce",
"*",
"s",
"*",
"to",
"str",
"."
] | def ensure_str(s, encoding='utf-8', errors='strict'):
"""Coerce *s* to `str`.
For Python 2:
- `unicode` -> encoded to `str`
- `str` -> `str`
For Python 3:
- `str` -> `str`
- `bytes` -> decoded to `str`
"""
if not isinstance(s, (text_type, binary_type)):
raise TypeError("not expecting type '%s'" % type(s))
if PY2 and isinstance(s, text_type):
s = s.encode(encoding, errors)
elif PY3 and isinstance(s, binary_type):
s = s.decode(encoding, errors)
return s | [
"def",
"ensure_str",
"(",
"s",
",",
"encoding",
"=",
"'utf-8'",
",",
"errors",
"=",
"'strict'",
")",
":",
"if",
"not",
"isinstance",
"(",
"s",
",",
"(",
"text_type",
",",
"binary_type",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"not expecting type '%s'\"",
"%",
"type",
"(",
"s",
")",
")",
"if",
"PY2",
"and",
"isinstance",
"(",
"s",
",",
"text_type",
")",
":",
"s",
"=",
"s",
".",
"encode",
"(",
"encoding",
",",
"errors",
")",
"elif",
"PY3",
"and",
"isinstance",
"(",
"s",
",",
"binary_type",
")",
":",
"s",
"=",
"s",
".",
"decode",
"(",
"encoding",
",",
"errors",
")",
"return",
"s"
] | https://github.com/apache/impala/blob/8ddac48f3428c86f2cbd037ced89cfb903298b12/shell/ext-py/six-1.14.0/six.py#L901-L918 |
|
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/feature_column/feature_column_v2.py | python | NumericColumn.variable_shape | (self) | return tensor_shape.TensorShape(self.shape) | See `DenseColumn` base class. | See `DenseColumn` base class. | [
"See",
"DenseColumn",
"base",
"class",
"."
] | def variable_shape(self):
"""See `DenseColumn` base class."""
return tensor_shape.TensorShape(self.shape) | [
"def",
"variable_shape",
"(",
"self",
")",
":",
"return",
"tensor_shape",
".",
"TensorShape",
"(",
"self",
".",
"shape",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/feature_column/feature_column_v2.py#L2669-L2671 |
|
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/android/appstats.py | python | MemoryHelper.QueryMemory | (adb, pid) | return results | Queries the device for memory information about the process with a pid of
|pid|. It will query Native, Dalvik, and Pss memory of the process. It
returns a list of values: [ Native, Pss, Dalvik ]. If the process is not
found it will return [ 0, 0, 0 ]. | Queries the device for memory information about the process with a pid of
|pid|. It will query Native, Dalvik, and Pss memory of the process. It
returns a list of values: [ Native, Pss, Dalvik ]. If the process is not
found it will return [ 0, 0, 0 ]. | [
"Queries",
"the",
"device",
"for",
"memory",
"information",
"about",
"the",
"process",
"with",
"a",
"pid",
"of",
"|pid|",
".",
"It",
"will",
"query",
"Native",
"Dalvik",
"and",
"Pss",
"memory",
"of",
"the",
"process",
".",
"It",
"returns",
"a",
"list",
"of",
"values",
":",
"[",
"Native",
"Pss",
"Dalvik",
"]",
".",
"If",
"the",
"process",
"is",
"not",
"found",
"it",
"will",
"return",
"[",
"0",
"0",
"0",
"]",
"."
] | def QueryMemory(adb, pid):
"""Queries the device for memory information about the process with a pid of
|pid|. It will query Native, Dalvik, and Pss memory of the process. It
returns a list of values: [ Native, Pss, Dalvik ]. If the process is not
found it will return [ 0, 0, 0 ]."""
results = [0, 0, 0]
mem_lines = adb.RunShellCommand(['dumpsys', 'meminfo', pid])
for line in mem_lines:
match = re.split('\s+', line.strip())
# Skip data after the 'App Summary' line. This is to fix builds where
# they have more entries that might match the other conditions.
if len(match) >= 2 and match[0] == 'App' and match[1] == 'Summary':
break
result_idx = None
query_idx = None
if match[0] == 'Native' and match[1] == 'Heap':
result_idx = 0
query_idx = -2
elif match[0] == 'Dalvik' and match[1] == 'Heap':
result_idx = 2
query_idx = -2
elif match[0] == 'TOTAL':
result_idx = 1
query_idx = 1
# If we already have a result, skip it and don't overwrite the data.
if result_idx is not None and results[result_idx] != 0:
continue
if result_idx is not None and query_idx is not None:
results[result_idx] = round(float(match[query_idx]) / 1000.0, 2)
return results | [
"def",
"QueryMemory",
"(",
"adb",
",",
"pid",
")",
":",
"results",
"=",
"[",
"0",
",",
"0",
",",
"0",
"]",
"mem_lines",
"=",
"adb",
".",
"RunShellCommand",
"(",
"[",
"'dumpsys'",
",",
"'meminfo'",
",",
"pid",
"]",
")",
"for",
"line",
"in",
"mem_lines",
":",
"match",
"=",
"re",
".",
"split",
"(",
"'\\s+'",
",",
"line",
".",
"strip",
"(",
")",
")",
"# Skip data after the 'App Summary' line. This is to fix builds where",
"# they have more entries that might match the other conditions.",
"if",
"len",
"(",
"match",
")",
">=",
"2",
"and",
"match",
"[",
"0",
"]",
"==",
"'App'",
"and",
"match",
"[",
"1",
"]",
"==",
"'Summary'",
":",
"break",
"result_idx",
"=",
"None",
"query_idx",
"=",
"None",
"if",
"match",
"[",
"0",
"]",
"==",
"'Native'",
"and",
"match",
"[",
"1",
"]",
"==",
"'Heap'",
":",
"result_idx",
"=",
"0",
"query_idx",
"=",
"-",
"2",
"elif",
"match",
"[",
"0",
"]",
"==",
"'Dalvik'",
"and",
"match",
"[",
"1",
"]",
"==",
"'Heap'",
":",
"result_idx",
"=",
"2",
"query_idx",
"=",
"-",
"2",
"elif",
"match",
"[",
"0",
"]",
"==",
"'TOTAL'",
":",
"result_idx",
"=",
"1",
"query_idx",
"=",
"1",
"# If we already have a result, skip it and don't overwrite the data.",
"if",
"result_idx",
"is",
"not",
"None",
"and",
"results",
"[",
"result_idx",
"]",
"!=",
"0",
":",
"continue",
"if",
"result_idx",
"is",
"not",
"None",
"and",
"query_idx",
"is",
"not",
"None",
":",
"results",
"[",
"result_idx",
"]",
"=",
"round",
"(",
"float",
"(",
"match",
"[",
"query_idx",
"]",
")",
"/",
"1000.0",
",",
"2",
")",
"return",
"results"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/android/appstats.py#L205-L239 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_misc.py | python | DateTime.IsLeapYear | (*args, **kwargs) | return _misc_.DateTime_IsLeapYear(*args, **kwargs) | IsLeapYear(int year=Inv_Year, int cal=Gregorian) -> bool | IsLeapYear(int year=Inv_Year, int cal=Gregorian) -> bool | [
"IsLeapYear",
"(",
"int",
"year",
"=",
"Inv_Year",
"int",
"cal",
"=",
"Gregorian",
")",
"-",
">",
"bool"
] | def IsLeapYear(*args, **kwargs):
"""IsLeapYear(int year=Inv_Year, int cal=Gregorian) -> bool"""
return _misc_.DateTime_IsLeapYear(*args, **kwargs) | [
"def",
"IsLeapYear",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"DateTime_IsLeapYear",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L3702-L3704 |
|
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBWatchpoint.GetWatchAddress | (self) | return _lldb.SBWatchpoint_GetWatchAddress(self) | GetWatchAddress(SBWatchpoint self) -> lldb::addr_t | GetWatchAddress(SBWatchpoint self) -> lldb::addr_t | [
"GetWatchAddress",
"(",
"SBWatchpoint",
"self",
")",
"-",
">",
"lldb",
"::",
"addr_t"
] | def GetWatchAddress(self):
"""GetWatchAddress(SBWatchpoint self) -> lldb::addr_t"""
return _lldb.SBWatchpoint_GetWatchAddress(self) | [
"def",
"GetWatchAddress",
"(",
"self",
")",
":",
"return",
"_lldb",
".",
"SBWatchpoint_GetWatchAddress",
"(",
"self",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L15191-L15193 |
Subsets and Splits