nwo stringlengths 5 86 | sha stringlengths 40 40 | path stringlengths 4 189 | language stringclasses 1 value | identifier stringlengths 1 94 | parameters stringlengths 2 4.03k | argument_list stringclasses 1 value | return_statement stringlengths 0 11.5k | docstring stringlengths 1 33.2k | docstring_summary stringlengths 0 5.15k | docstring_tokens list | function stringlengths 34 151k | function_tokens list | url stringlengths 90 278 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/propgrid.py | python | PGProperty.SetPyClientData | (*args, **kwargs) | return _propgrid.PGProperty_SetPyClientData(*args, **kwargs) | SetPyClientData(self, PyObject clientData)
Associate the given client data. | SetPyClientData(self, PyObject clientData) | [
"SetPyClientData",
"(",
"self",
"PyObject",
"clientData",
")"
] | def SetPyClientData(*args, **kwargs):
"""
SetPyClientData(self, PyObject clientData)
Associate the given client data.
"""
return _propgrid.PGProperty_SetPyClientData(*args, **kwargs) | [
"def",
"SetPyClientData",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PGProperty_SetPyClientData",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/propgrid.py#L866-L872 | |
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | third_party/numpy/files/numpy/ma/core.py | python | put | (a, indices, values, mode='raise') | Set storage-indexed locations to corresponding values.
This function is equivalent to `MaskedArray.put`, see that method
for details.
See Also
--------
MaskedArray.put | Set storage-indexed locations to corresponding values. | [
"Set",
"storage",
"-",
"indexed",
"locations",
"to",
"corresponding",
"values",
"."
] | def put(a, indices, values, mode='raise'):
"""
Set storage-indexed locations to corresponding values.
This function is equivalent to `MaskedArray.put`, see that method
for details.
See Also
--------
MaskedArray.put
"""
# We can't use 'frommethod', the order of arguments is different
try:
return a.put(indices, values, mode=mode)
except AttributeError:
return narray(a, copy=False).put(indices, values, mode=mode) | [
"def",
"put",
"(",
"a",
",",
"indices",
",",
"values",
",",
"mode",
"=",
"'raise'",
")",
":",
"# We can't use 'frommethod', the order of arguments is different",
"try",
":",
"return",
"a",
".",
"put",
"(",
"indices",
",",
"values",
",",
"mode",
"=",
"mode",
... | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/ma/core.py#L6292-L6308 | ||
pyne/pyne | 0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3 | pyne/transmute/chainsolve.py | python | Transmuter.phi | (self, flux) | Ensures that the flux is correctly formatted. | Ensures that the flux is correctly formatted. | [
"Ensures",
"that",
"the",
"flux",
"is",
"correctly",
"formatted",
"."
] | def phi(self, flux):
"""Ensures that the flux is correctly formatted."""
flux = np.asarray(flux)
if flux.ndim == 0:
_ = np.empty(175, float)
_.fill(flux / 175.0)
flux = _
elif flux.ndim == 1 and flux.shape[0] != 175:
raise ValueError("Group structure must match EAF.")
elif flux.ndim > 1:
raise ValueError("The flux vector must be 0- or 1-dimensional.")
if not np.all(flux >= 0.0):
raise ValueError("Flux entries must be non-negative.")
for ds in self.xscache.data_sources:
ds.src_phi_g = flux
self.xscache['phi_g'] = np.array([flux.sum()])
self._phi = flux | [
"def",
"phi",
"(",
"self",
",",
"flux",
")",
":",
"flux",
"=",
"np",
".",
"asarray",
"(",
"flux",
")",
"if",
"flux",
".",
"ndim",
"==",
"0",
":",
"_",
"=",
"np",
".",
"empty",
"(",
"175",
",",
"float",
")",
"_",
".",
"fill",
"(",
"flux",
"/... | https://github.com/pyne/pyne/blob/0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3/pyne/transmute/chainsolve.py#L82-L98 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/ResourceManager/resource_manager/config.py | python | ConfigContext.join_aws_directory_path | (self, relative_path) | return os.path.join(self.aws_directory_path, relative_path) | Returns an absolute path when given a path relative to the {root}\{game}\AWS directory. | Returns an absolute path when given a path relative to the {root}\{game}\AWS directory. | [
"Returns",
"an",
"absolute",
"path",
"when",
"given",
"a",
"path",
"relative",
"to",
"the",
"{",
"root",
"}",
"\\",
"{",
"game",
"}",
"\\",
"AWS",
"directory",
"."
] | def join_aws_directory_path(self, relative_path):
"""Returns an absolute path when given a path relative to the {root}\{game}\AWS directory."""
return os.path.join(self.aws_directory_path, relative_path) | [
"def",
"join_aws_directory_path",
"(",
"self",
",",
"relative_path",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"aws_directory_path",
",",
"relative_path",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/ResourceManager/resource_manager/config.py#L441-L443 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/flatmenu.py | python | FlatMenu.GetBorderXWidth | (self) | return self._borderXWidth | Returns the menu border x-width, in pixels. | Returns the menu border x-width, in pixels. | [
"Returns",
"the",
"menu",
"border",
"x",
"-",
"width",
"in",
"pixels",
"."
] | def GetBorderXWidth(self):
""" Returns the menu border x-width, in pixels. """
return self._borderXWidth | [
"def",
"GetBorderXWidth",
"(",
"self",
")",
":",
"return",
"self",
".",
"_borderXWidth"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/flatmenu.py#L5677-L5680 | |
trilinos/Trilinos | 6168be6dd51e35e1cd681e9c4b24433e709df140 | cmake/tribits/python_utils/GeneralScriptSupport.py | python | createIndexHtmlBrowserFile | (baseDir, fileDirList) | return htmlFile | Creates an HTML browser file as a returned string. | Creates an HTML browser file as a returned string. | [
"Creates",
"an",
"HTML",
"browser",
"file",
"as",
"a",
"returned",
"string",
"."
] | def createIndexHtmlBrowserFile(baseDir, fileDirList):
"""Creates an HTML browser file as a returned string."""
htmlFile = "" \
+ "<html>\n" \
+ "<head>\n" \
+ "<title>"+baseDir+"</title>\n" \
+ "</head>\n" \
+ "<body>\n" \
+ "<b>"+baseDir+"</b>\n" \
+ createIndexHtmlBrowserList(baseDir, fileDirList) \
+ "</body>\n" \
+ "</html>\n"
return htmlFile | [
"def",
"createIndexHtmlBrowserFile",
"(",
"baseDir",
",",
"fileDirList",
")",
":",
"htmlFile",
"=",
"\"\"",
"+",
"\"<html>\\n\"",
"+",
"\"<head>\\n\"",
"+",
"\"<title>\"",
"+",
"baseDir",
"+",
"\"</title>\\n\"",
"+",
"\"</head>\\n\"",
"+",
"\"<body>\\n\"",
"+",
"\... | https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/cmake/tribits/python_utils/GeneralScriptSupport.py#L876-L888 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/prompt-toolkit/py2/prompt_toolkit/shortcuts.py | python | prompt_async | (message='', **kwargs) | return prompt(message, **kwargs) | Similar to :func:`.prompt`, but return an asyncio coroutine instead. | Similar to :func:`.prompt`, but return an asyncio coroutine instead. | [
"Similar",
"to",
":",
"func",
":",
".",
"prompt",
"but",
"return",
"an",
"asyncio",
"coroutine",
"instead",
"."
] | def prompt_async(message='', **kwargs):
"""
Similar to :func:`.prompt`, but return an asyncio coroutine instead.
"""
kwargs['return_asyncio_coroutine'] = True
return prompt(message, **kwargs) | [
"def",
"prompt_async",
"(",
"message",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'return_asyncio_coroutine'",
"]",
"=",
"True",
"return",
"prompt",
"(",
"message",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py2/prompt_toolkit/shortcuts.py#L634-L639 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/pkg_resources/_vendor/pyparsing.py | python | ParserElement.setDefaultWhitespaceChars | ( chars ) | r"""
Overrides the default whitespace chars
Example::
# default whitespace chars are space, <TAB> and newline
OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def', 'ghi', 'jkl']
# change to just treat newline as significant
ParserElement.setDefaultWhitespaceChars(" \t")
OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def'] | r"""
Overrides the default whitespace chars | [
"r",
"Overrides",
"the",
"default",
"whitespace",
"chars"
] | def setDefaultWhitespaceChars( chars ):
r"""
Overrides the default whitespace chars
Example::
# default whitespace chars are space, <TAB> and newline
OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def', 'ghi', 'jkl']
# change to just treat newline as significant
ParserElement.setDefaultWhitespaceChars(" \t")
OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def']
"""
ParserElement.DEFAULT_WHITE_CHARS = chars | [
"def",
"setDefaultWhitespaceChars",
"(",
"chars",
")",
":",
"ParserElement",
".",
"DEFAULT_WHITE_CHARS",
"=",
"chars"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pkg_resources/_vendor/pyparsing.py#L1109-L1121 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/compiler/pycodegen.py | python | CodeGenerator.initClass | (self) | This method is called once for each class | This method is called once for each class | [
"This",
"method",
"is",
"called",
"once",
"for",
"each",
"class"
] | def initClass(self):
"""This method is called once for each class""" | [
"def",
"initClass",
"(",
"self",
")",
":"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/compiler/pycodegen.py#L225-L226 | ||
naver/sling | 5671cd445a2caae0b4dd0332299e4cfede05062c | webkit/Tools/Scripts/webkitpy/thirdparty/BeautifulSoup.py | python | UnicodeDammit._detectEncoding | (self, xml_data, isHTML=False) | return xml_data, xml_encoding, sniffed_xml_encoding | Given a document, tries to detect its XML encoding. | Given a document, tries to detect its XML encoding. | [
"Given",
"a",
"document",
"tries",
"to",
"detect",
"its",
"XML",
"encoding",
"."
] | def _detectEncoding(self, xml_data, isHTML=False):
"""Given a document, tries to detect its XML encoding."""
xml_encoding = sniffed_xml_encoding = None
try:
if xml_data[:4] == '\x4c\x6f\xa7\x94':
# EBCDIC
xml_data = self._ebcdic_to_ascii(xml_data)
elif xml_data[:4] == '\x00\x3c\x00\x3f':
# UTF-16BE
sniffed_xml_encoding = 'utf-16be'
xml_data = unicode(xml_data, 'utf-16be').encode('utf-8')
elif (len(xml_data) >= 4) and (xml_data[:2] == '\xfe\xff') \
and (xml_data[2:4] != '\x00\x00'):
# UTF-16BE with BOM
sniffed_xml_encoding = 'utf-16be'
xml_data = unicode(xml_data[2:], 'utf-16be').encode('utf-8')
elif xml_data[:4] == '\x3c\x00\x3f\x00':
# UTF-16LE
sniffed_xml_encoding = 'utf-16le'
xml_data = unicode(xml_data, 'utf-16le').encode('utf-8')
elif (len(xml_data) >= 4) and (xml_data[:2] == '\xff\xfe') and \
(xml_data[2:4] != '\x00\x00'):
# UTF-16LE with BOM
sniffed_xml_encoding = 'utf-16le'
xml_data = unicode(xml_data[2:], 'utf-16le').encode('utf-8')
elif xml_data[:4] == '\x00\x00\x00\x3c':
# UTF-32BE
sniffed_xml_encoding = 'utf-32be'
xml_data = unicode(xml_data, 'utf-32be').encode('utf-8')
elif xml_data[:4] == '\x3c\x00\x00\x00':
# UTF-32LE
sniffed_xml_encoding = 'utf-32le'
xml_data = unicode(xml_data, 'utf-32le').encode('utf-8')
elif xml_data[:4] == '\x00\x00\xfe\xff':
# UTF-32BE with BOM
sniffed_xml_encoding = 'utf-32be'
xml_data = unicode(xml_data[4:], 'utf-32be').encode('utf-8')
elif xml_data[:4] == '\xff\xfe\x00\x00':
# UTF-32LE with BOM
sniffed_xml_encoding = 'utf-32le'
xml_data = unicode(xml_data[4:], 'utf-32le').encode('utf-8')
elif xml_data[:3] == '\xef\xbb\xbf':
# UTF-8 with BOM
sniffed_xml_encoding = 'utf-8'
xml_data = unicode(xml_data[3:], 'utf-8').encode('utf-8')
else:
sniffed_xml_encoding = 'ascii'
pass
except:
xml_encoding_match = None
xml_encoding_match = re.compile(
'^<\?.*encoding=[\'"](.*?)[\'"].*\?>').match(xml_data)
if not xml_encoding_match and isHTML:
regexp = re.compile('<\s*meta[^>]+charset=([^>]*?)[;\'">]', re.I)
xml_encoding_match = regexp.search(xml_data)
if xml_encoding_match is not None:
xml_encoding = xml_encoding_match.groups()[0].lower()
if isHTML:
self.declaredHTMLEncoding = xml_encoding
if sniffed_xml_encoding and \
(xml_encoding in ('iso-10646-ucs-2', 'ucs-2', 'csunicode',
'iso-10646-ucs-4', 'ucs-4', 'csucs4',
'utf-16', 'utf-32', 'utf_16', 'utf_32',
'utf16', 'u16')):
xml_encoding = sniffed_xml_encoding
return xml_data, xml_encoding, sniffed_xml_encoding | [
"def",
"_detectEncoding",
"(",
"self",
",",
"xml_data",
",",
"isHTML",
"=",
"False",
")",
":",
"xml_encoding",
"=",
"sniffed_xml_encoding",
"=",
"None",
"try",
":",
"if",
"xml_data",
"[",
":",
"4",
"]",
"==",
"'\\x4c\\x6f\\xa7\\x94'",
":",
"# EBCDIC",
"xml_d... | https://github.com/naver/sling/blob/5671cd445a2caae0b4dd0332299e4cfede05062c/webkit/Tools/Scripts/webkitpy/thirdparty/BeautifulSoup.py#L1864-L1929 | |
brave/brave-core | ceaa3de4735789d355b6fa80c21d4709e2c1d0e8 | script/lib/transifex.py | python | get_original_grd | (src_root, grd_file_path) | Obtains the Chromium GRD file for a specified Brave GRD file. | Obtains the Chromium GRD file for a specified Brave GRD file. | [
"Obtains",
"the",
"Chromium",
"GRD",
"file",
"for",
"a",
"specified",
"Brave",
"GRD",
"file",
"."
] | def get_original_grd(src_root, grd_file_path):
"""Obtains the Chromium GRD file for a specified Brave GRD file."""
# pylint: disable=fixme
# TODO: consider passing this mapping into the script from l10nUtil.js
grd_file_name = os.path.basename(grd_file_path)
if grd_file_name == 'components_brave_strings.grd':
return os.path.join(src_root, 'components',
'components_chromium_strings.grd')
elif grd_file_name == 'brave_strings.grd':
return os.path.join(src_root, 'chrome', 'app', 'chromium_strings.grd')
elif grd_file_name == 'generated_resources.grd':
return os.path.join(src_root, 'chrome', 'app',
'generated_resources.grd')
elif grd_file_name == 'android_chrome_strings.grd':
return os.path.join(src_root, 'chrome', 'browser', 'ui', 'android',
'strings', 'android_chrome_strings.grd') | [
"def",
"get_original_grd",
"(",
"src_root",
",",
"grd_file_path",
")",
":",
"# pylint: disable=fixme",
"# TODO: consider passing this mapping into the script from l10nUtil.js",
"grd_file_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"grd_file_path",
")",
"if",
"grd_f... | https://github.com/brave/brave-core/blob/ceaa3de4735789d355b6fa80c21d4709e2c1d0e8/script/lib/transifex.py#L559-L574 | ||
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/contrib/quantization/tools/quantize_graph.py | python | GraphRewriter.remove_unneeded_nodes | (self, input_graph) | return output_graph | Prunes out nodes that aren't needed for inference.
There are nodes like Identity and CheckNumerics that are only useful
during training, and can be removed in graphs that will be used for
nothing but inference. Here we identify and remove them, returning an
equivalent graph.
Args:
input_graph: Model to analyze and prune.
Returns:
A list of nodes with the unnecessary ones removed. | Prunes out nodes that aren't needed for inference. | [
"Prunes",
"out",
"nodes",
"that",
"aren",
"t",
"needed",
"for",
"inference",
"."
] | def remove_unneeded_nodes(self, input_graph):
"""Prunes out nodes that aren't needed for inference.
There are nodes like Identity and CheckNumerics that are only useful
during training, and can be removed in graphs that will be used for
nothing but inference. Here we identify and remove them, returning an
equivalent graph.
Args:
input_graph: Model to analyze and prune.
Returns:
A list of nodes with the unnecessary ones removed.
"""
types_to_remove = {"CheckNumerics": True}
input_nodes = input_graph.node
names_to_remove = {}
for node in input_nodes:
if node.op in types_to_remove:
names_to_remove[node.name] = True
nodes_after_removal = []
for node in input_nodes:
if node.name in names_to_remove:
continue
new_node = tf.NodeDef()
new_node.CopyFrom(node)
input_before_removal = node.input
del new_node.input[:]
for full_input_name in input_before_removal:
input_name = re.sub(r"^\^", "", full_input_name)
if input_name in names_to_remove:
continue
new_node.input.append(full_input_name)
nodes_after_removal.append(new_node)
types_to_splice = {"Identity": True}
names_to_splice = {}
for node in nodes_after_removal:
if node.op in types_to_splice:
# We don't want to remove nodes that have control edge inputs, because
# they might be involved in subtle dependency issues that removing them
# will jeopardize.
has_control_edge = False
for input_name in node.input:
if re.match(r"^\^", input_name):
has_control_edge = True
if not has_control_edge:
names_to_splice[node.name] = node.input[0]
nodes_after_splicing = []
for node in nodes_after_removal:
if node.name in names_to_splice:
continue
new_node = tf.NodeDef()
new_node.CopyFrom(node)
input_before_removal = node.input
del new_node.input[:]
for full_input_name in input_before_removal:
input_name = re.sub(r"^\^", "", full_input_name)
if input_name in names_to_splice:
new_node.input.append(names_to_splice[input_name])
else:
new_node.input.append(full_input_name)
nodes_after_splicing.append(new_node)
output_graph = tf.GraphDef()
output_graph.node.extend(nodes_after_splicing)
return output_graph | [
"def",
"remove_unneeded_nodes",
"(",
"self",
",",
"input_graph",
")",
":",
"types_to_remove",
"=",
"{",
"\"CheckNumerics\"",
":",
"True",
"}",
"input_nodes",
"=",
"input_graph",
".",
"node",
"names_to_remove",
"=",
"{",
"}",
"for",
"node",
"in",
"input_nodes",
... | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/quantization/tools/quantize_graph.py#L966-L1036 | |
panda3d/panda3d | 833ad89ebad58395d0af0b7ec08538e5e4308265 | direct/src/controls/DevWalker.py | python | DevWalker.handleAvatarControls | (self, task) | return Task.cont | Check on the arrow keys and update the avatar. | Check on the arrow keys and update the avatar. | [
"Check",
"on",
"the",
"arrow",
"keys",
"and",
"update",
"the",
"avatar",
"."
] | def handleAvatarControls(self, task):
"""
Check on the arrow keys and update the avatar.
"""
# get the button states:
forward = inputState.isSet("forward")
reverse = inputState.isSet("reverse")
turnLeft = inputState.isSet("turnLeft")
turnRight = inputState.isSet("turnRight")
slideLeft = inputState.isSet("slideLeft")
slideRight = inputState.isSet("slideRight")
levitateUp = inputState.isSet("levitateUp")
levitateDown = inputState.isSet("levitateDown")
run = inputState.isSet("run") and self.runMultiplier.getValue() or 1.0
# Check for Auto-Run
if base.localAvatar.getAutoRun():
forward = 1
reverse = 0
# Determine what the speeds are based on the buttons:
self.speed=(
(forward and self.avatarControlForwardSpeed or
reverse and -self.avatarControlReverseSpeed))
self.liftSpeed=(
(levitateUp and self.avatarControlForwardSpeed or
levitateDown and -self.avatarControlReverseSpeed))
self.slideSpeed=(
(slideLeft and -self.avatarControlForwardSpeed) or
(slideRight and self.avatarControlForwardSpeed))
self.rotationSpeed=(
(turnLeft and self.avatarControlRotateSpeed) or
(turnRight and -self.avatarControlRotateSpeed))
if self.wantDebugIndicator:
self.displayDebugInfo()
# Check to see if we're moving at all:
if self.speed or self.liftSpeed or self.slideSpeed or self.rotationSpeed:
# How far did we move based on the amount of time elapsed?
dt=ClockObject.getGlobalClock().getDt()
distance = dt * self.speed * run
lift = dt * self.liftSpeed * run
slideDistance = dt * self.slideSpeed * run
rotation = dt * self.rotationSpeed
# Take a step in the direction of our previous heading.
self.vel=Vec3(Vec3.forward() * distance +
Vec3.up() * lift +
Vec3.right() * slideDistance)
if self.vel != Vec3.zero():
# rotMat is the rotation matrix corresponding to
# our previous heading.
rotMat=Mat3.rotateMatNormaxis(self.avatarNodePath.getH(), Vec3.up())
step=rotMat.xform(self.vel)
self.avatarNodePath.setFluidPos(Point3(self.avatarNodePath.getPos()+step))
self.avatarNodePath.setH(self.avatarNodePath.getH()+rotation)
messenger.send("avatarMoving")
else:
self.vel.set(0.0, 0.0, 0.0)
return Task.cont | [
"def",
"handleAvatarControls",
"(",
"self",
",",
"task",
")",
":",
"# get the button states:",
"forward",
"=",
"inputState",
".",
"isSet",
"(",
"\"forward\"",
")",
"reverse",
"=",
"inputState",
".",
"isSet",
"(",
"\"reverse\"",
")",
"turnLeft",
"=",
"inputState"... | https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/controls/DevWalker.py#L104-L164 | |
NVIDIA/TensorRT | 42805f078052daad1a98bc5965974fcffaad0960 | demo/HuggingFace/NNDF/models.py | python | TorchModelFile.load_model | (self) | return load(self.fpath) | Loads the model from disk if isn't already loaded.
Does not attempt to load if given model is already loaded and instead returns original instance.
Use as_torch_model() instead to always guarantee a new instance and location on disk.
Args:
None
Returns:
torch.Model: Loaded torch model. | Loads the model from disk if isn't already loaded.
Does not attempt to load if given model is already loaded and instead returns original instance.
Use as_torch_model() instead to always guarantee a new instance and location on disk. | [
"Loads",
"the",
"model",
"from",
"disk",
"if",
"isn",
"t",
"already",
"loaded",
".",
"Does",
"not",
"attempt",
"to",
"load",
"if",
"given",
"model",
"is",
"already",
"loaded",
"and",
"instead",
"returns",
"original",
"instance",
".",
"Use",
"as_torch_model",... | def load_model(self) -> Module:
"""
Loads the model from disk if isn't already loaded.
Does not attempt to load if given model is already loaded and instead returns original instance.
Use as_torch_model() instead to always guarantee a new instance and location on disk.
Args:
None
Returns:
torch.Model: Loaded torch model.
"""
if self.is_loaded:
return self.model
return load(self.fpath) | [
"def",
"load_model",
"(",
"self",
")",
"->",
"Module",
":",
"if",
"self",
".",
"is_loaded",
":",
"return",
"self",
".",
"model",
"return",
"load",
"(",
"self",
".",
"fpath",
")"
] | https://github.com/NVIDIA/TensorRT/blob/42805f078052daad1a98bc5965974fcffaad0960/demo/HuggingFace/NNDF/models.py#L255-L270 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/gslib/boto_translation.py | python | BotoTranslation._TranslateBotoKeyTimestamp | (self, key) | Parses the timestamp from the boto key into an datetime object.
This avoids a dependency on dateutil.
Args:
key: Boto key to get timestamp from.
Returns:
datetime object if string is parsed successfully, None otherwise. | Parses the timestamp from the boto key into an datetime object. | [
"Parses",
"the",
"timestamp",
"from",
"the",
"boto",
"key",
"into",
"an",
"datetime",
"object",
"."
] | def _TranslateBotoKeyTimestamp(self, key):
"""Parses the timestamp from the boto key into an datetime object.
This avoids a dependency on dateutil.
Args:
key: Boto key to get timestamp from.
Returns:
datetime object if string is parsed successfully, None otherwise.
"""
if key.last_modified:
if '.' in key.last_modified:
key_us_timestamp = key.last_modified.rstrip('Z') + '000Z'
else:
key_us_timestamp = key.last_modified.rstrip('Z') + '.000000Z'
fmt = '%Y-%m-%dT%H:%M:%S.%fZ'
try:
return datetime.datetime.strptime(key_us_timestamp, fmt)
except ValueError:
try:
# Try alternate format
fmt = '%a, %d %b %Y %H:%M:%S %Z'
return datetime.datetime.strptime(key.last_modified, fmt)
except ValueError:
# Could not parse the time; leave updated as None.
return None | [
"def",
"_TranslateBotoKeyTimestamp",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
".",
"last_modified",
":",
"if",
"'.'",
"in",
"key",
".",
"last_modified",
":",
"key_us_timestamp",
"=",
"key",
".",
"last_modified",
".",
"rstrip",
"(",
"'Z'",
")",
"+",
... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/gslib/boto_translation.py#L1351-L1377 | ||
9miao/CrossApp | 1f5375e061bf69841eb19728598f5ae3f508d620 | tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py | python | CursorKind.is_statement | (self) | return conf.lib.clang_isStatement(self) | Test if this is a statement kind. | Test if this is a statement kind. | [
"Test",
"if",
"this",
"is",
"a",
"statement",
"kind",
"."
] | def is_statement(self):
"""Test if this is a statement kind."""
return conf.lib.clang_isStatement(self) | [
"def",
"is_statement",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_isStatement",
"(",
"self",
")"
] | https://github.com/9miao/CrossApp/blob/1f5375e061bf69841eb19728598f5ae3f508d620/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py#L531-L533 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/stc.py | python | StyledTextCtrl.SetSelAlpha | (*args, **kwargs) | return _stc.StyledTextCtrl_SetSelAlpha(*args, **kwargs) | SetSelAlpha(self, int alpha)
Set the alpha of the selection. | SetSelAlpha(self, int alpha) | [
"SetSelAlpha",
"(",
"self",
"int",
"alpha",
")"
] | def SetSelAlpha(*args, **kwargs):
"""
SetSelAlpha(self, int alpha)
Set the alpha of the selection.
"""
return _stc.StyledTextCtrl_SetSelAlpha(*args, **kwargs) | [
"def",
"SetSelAlpha",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_SetSelAlpha",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/stc.py#L2747-L2753 | |
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Tool/packaging/msi.py | python | create_feature_dict | (files) | return dict | X_MSI_FEATURE and doc FileTag's can be used to collect files in a
hierarchy. This function collects the files into this hierarchy. | X_MSI_FEATURE and doc FileTag's can be used to collect files in a
hierarchy. This function collects the files into this hierarchy. | [
"X_MSI_FEATURE",
"and",
"doc",
"FileTag",
"s",
"can",
"be",
"used",
"to",
"collect",
"files",
"in",
"a",
"hierarchy",
".",
"This",
"function",
"collects",
"the",
"files",
"into",
"this",
"hierarchy",
"."
] | def create_feature_dict(files):
""" X_MSI_FEATURE and doc FileTag's can be used to collect files in a
hierarchy. This function collects the files into this hierarchy.
"""
dict = {}
def add_to_dict( feature, file ):
if not SCons.Util.is_List( feature ):
feature = [ feature ]
for f in feature:
if f not in dict:
dict[ f ] = [ file ]
else:
dict[ f ].append( file )
for file in files:
if hasattr( file, 'PACKAGING_X_MSI_FEATURE' ):
add_to_dict(file.PACKAGING_X_MSI_FEATURE, file)
elif hasattr( file, 'PACKAGING_DOC' ):
add_to_dict( 'PACKAGING_DOC', file )
else:
add_to_dict( 'default', file )
return dict | [
"def",
"create_feature_dict",
"(",
"files",
")",
":",
"dict",
"=",
"{",
"}",
"def",
"add_to_dict",
"(",
"feature",
",",
"file",
")",
":",
"if",
"not",
"SCons",
".",
"Util",
".",
"is_List",
"(",
"feature",
")",
":",
"feature",
"=",
"[",
"feature",
"]"... | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Tool/packaging/msi.py#L127-L151 | |
BitMEX/api-connectors | 37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812 | auto-generated/python/swagger_client/models/quote.py | python | Quote.__repr__ | (self) | return self.to_str() | For `print` and `pprint` | For `print` and `pprint` | [
"For",
"print",
"and",
"pprint"
] | def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str() | [
"def",
"__repr__",
"(",
"self",
")",
":",
"return",
"self",
".",
"to_str",
"(",
")"
] | https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/quote.py#L234-L236 | |
jackaudio/jack2 | 21b293dbc37d42446141a08922cdec0d2550c6a0 | waflib/extras/xcode6.py | python | xcode.unique_buildfile | (self, buildfile) | return build_files[buildfile] | Returns a unique buildfile, possibly an existing one.
Use this after you've constructed a PBXBuildFile to make sure there is
only one PBXBuildFile for the same file in the same project. | Returns a unique buildfile, possibly an existing one.
Use this after you've constructed a PBXBuildFile to make sure there is
only one PBXBuildFile for the same file in the same project. | [
"Returns",
"a",
"unique",
"buildfile",
"possibly",
"an",
"existing",
"one",
".",
"Use",
"this",
"after",
"you",
"ve",
"constructed",
"a",
"PBXBuildFile",
"to",
"make",
"sure",
"there",
"is",
"only",
"one",
"PBXBuildFile",
"for",
"the",
"same",
"file",
"in",
... | def unique_buildfile(self, buildfile):
"""
Returns a unique buildfile, possibly an existing one.
Use this after you've constructed a PBXBuildFile to make sure there is
only one PBXBuildFile for the same file in the same project.
"""
try:
build_files = self.build_files
except AttributeError:
build_files = self.build_files = {}
if buildfile not in build_files:
build_files[buildfile] = buildfile
return build_files[buildfile] | [
"def",
"unique_buildfile",
"(",
"self",
",",
"buildfile",
")",
":",
"try",
":",
"build_files",
"=",
"self",
".",
"build_files",
"except",
"AttributeError",
":",
"build_files",
"=",
"self",
".",
"build_files",
"=",
"{",
"}",
"if",
"buildfile",
"not",
"in",
... | https://github.com/jackaudio/jack2/blob/21b293dbc37d42446141a08922cdec0d2550c6a0/waflib/extras/xcode6.py#L641-L654 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/signal/filter_design.py | python | lp2lp | (b, a, wo=1.0) | return normalize(b, a) | Transform a lowpass filter prototype to a different frequency.
Return an analog low-pass filter with cutoff frequency `wo`
from an analog low-pass filter prototype with unity cutoff frequency, in
transfer function ('ba') representation.
See Also
--------
lp2hp, lp2bp, lp2bs, bilinear
lp2lp_zpk | Transform a lowpass filter prototype to a different frequency. | [
"Transform",
"a",
"lowpass",
"filter",
"prototype",
"to",
"a",
"different",
"frequency",
"."
] | def lp2lp(b, a, wo=1.0):
"""
Transform a lowpass filter prototype to a different frequency.
Return an analog low-pass filter with cutoff frequency `wo`
from an analog low-pass filter prototype with unity cutoff frequency, in
transfer function ('ba') representation.
See Also
--------
lp2hp, lp2bp, lp2bs, bilinear
lp2lp_zpk
"""
a, b = map(atleast_1d, (a, b))
try:
wo = float(wo)
except TypeError:
wo = float(wo[0])
d = len(a)
n = len(b)
M = max((d, n))
pwo = pow(wo, numpy.arange(M - 1, -1, -1))
start1 = max((n - d, 0))
start2 = max((d - n, 0))
b = b * pwo[start1] / pwo[start2:]
a = a * pwo[start1] / pwo[start1:]
return normalize(b, a) | [
"def",
"lp2lp",
"(",
"b",
",",
"a",
",",
"wo",
"=",
"1.0",
")",
":",
"a",
",",
"b",
"=",
"map",
"(",
"atleast_1d",
",",
"(",
"a",
",",
"b",
")",
")",
"try",
":",
"wo",
"=",
"float",
"(",
"wo",
")",
"except",
"TypeError",
":",
"wo",
"=",
"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/signal/filter_design.py#L1632-L1659 | |
MegEngine/MegEngine | ce9ad07a27ec909fb8db4dd67943d24ba98fb93a | imperative/python/megengine/functional/elemwise.py | python | floor | (x) | return _elwise(x, mode=Elemwise.Mode.FLOOR) | r"""Element-wise `floor`. | r"""Element-wise `floor`. | [
"r",
"Element",
"-",
"wise",
"floor",
"."
] | def floor(x):
r"""Element-wise `floor`."""
return _elwise(x, mode=Elemwise.Mode.FLOOR) | [
"def",
"floor",
"(",
"x",
")",
":",
"return",
"_elwise",
"(",
"x",
",",
"mode",
"=",
"Elemwise",
".",
"Mode",
".",
"FLOOR",
")"
] | https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/functional/elemwise.py#L297-L299 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSVersion.py | python | _CreateVersion | (name, path, sdk_based=False) | return versions[str(name)] | Sets up MSVS project generation.
Setup is based off the GYP_MSVS_VERSION environment variable or whatever is
autodetected if GYP_MSVS_VERSION is not explicitly specified. If a version is
passed in that doesn't match a value in versions python will throw a error. | Sets up MSVS project generation. | [
"Sets",
"up",
"MSVS",
"project",
"generation",
"."
] | def _CreateVersion(name, path, sdk_based=False):
"""Sets up MSVS project generation.
Setup is based off the GYP_MSVS_VERSION environment variable or whatever is
autodetected if GYP_MSVS_VERSION is not explicitly specified. If a version is
passed in that doesn't match a value in versions python will throw a error.
"""
if path:
path = os.path.normpath(path)
versions = {
'2015': VisualStudioVersion('2015',
'Visual Studio 2015',
solution_version='12.00',
project_version='14.0',
flat_sln=False,
uses_vcxproj=True,
path=path,
sdk_based=sdk_based,
default_toolset='v140'),
'2013': VisualStudioVersion('2013',
'Visual Studio 2013',
solution_version='13.00',
project_version='12.0',
flat_sln=False,
uses_vcxproj=True,
path=path,
sdk_based=sdk_based,
default_toolset='v120'),
'2013e': VisualStudioVersion('2013e',
'Visual Studio 2013',
solution_version='13.00',
project_version='12.0',
flat_sln=True,
uses_vcxproj=True,
path=path,
sdk_based=sdk_based,
default_toolset='v120'),
'2012': VisualStudioVersion('2012',
'Visual Studio 2012',
solution_version='12.00',
project_version='4.0',
flat_sln=False,
uses_vcxproj=True,
path=path,
sdk_based=sdk_based,
default_toolset='v110'),
'2012e': VisualStudioVersion('2012e',
'Visual Studio 2012',
solution_version='12.00',
project_version='4.0',
flat_sln=True,
uses_vcxproj=True,
path=path,
sdk_based=sdk_based,
default_toolset='v110'),
'2010': VisualStudioVersion('2010',
'Visual Studio 2010',
solution_version='11.00',
project_version='4.0',
flat_sln=False,
uses_vcxproj=True,
path=path,
sdk_based=sdk_based),
'2010e': VisualStudioVersion('2010e',
'Visual C++ Express 2010',
solution_version='11.00',
project_version='4.0',
flat_sln=True,
uses_vcxproj=True,
path=path,
sdk_based=sdk_based),
'2008': VisualStudioVersion('2008',
'Visual Studio 2008',
solution_version='10.00',
project_version='9.00',
flat_sln=False,
uses_vcxproj=False,
path=path,
sdk_based=sdk_based),
'2008e': VisualStudioVersion('2008e',
'Visual Studio 2008',
solution_version='10.00',
project_version='9.00',
flat_sln=True,
uses_vcxproj=False,
path=path,
sdk_based=sdk_based),
'2005': VisualStudioVersion('2005',
'Visual Studio 2005',
solution_version='9.00',
project_version='8.00',
flat_sln=False,
uses_vcxproj=False,
path=path,
sdk_based=sdk_based),
'2005e': VisualStudioVersion('2005e',
'Visual Studio 2005',
solution_version='9.00',
project_version='8.00',
flat_sln=True,
uses_vcxproj=False,
path=path,
sdk_based=sdk_based),
}
return versions[str(name)] | [
"def",
"_CreateVersion",
"(",
"name",
",",
"path",
",",
"sdk_based",
"=",
"False",
")",
":",
"if",
"path",
":",
"path",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"path",
")",
"versions",
"=",
"{",
"'2015'",
":",
"VisualStudioVersion",
"(",
"'2015'"... | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSVersion.py#L219-L323 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/ndimage/measurements.py | python | maximum | (input, labels=None, index=None) | return _select(input, labels, index, find_max=True)[0] | Calculate the maximum of the values of an array over labeled regions.
Parameters
----------
input : array_like
Array_like of values. For each region specified by `labels`, the
maximal values of `input` over the region is computed.
labels : array_like, optional
An array of integers marking different regions over which the
maximum value of `input` is to be computed. `labels` must have the
same shape as `input`. If `labels` is not specified, the maximum
over the whole array is returned.
index : array_like, optional
A list of region labels that are taken into account for computing the
maxima. If index is None, the maximum over all elements where `labels`
is non-zero is returned.
Returns
-------
output : float or list of floats
List of maxima of `input` over the regions determined by `labels` and
whose index is in `index`. If `index` or `labels` are not specified, a
float is returned: the maximal value of `input` if `labels` is None,
and the maximal value of elements where `labels` is greater than zero
if `index` is None.
See also
--------
label, minimum, median, maximum_position, extrema, sum, mean, variance,
standard_deviation
Notes
-----
The function returns a Python list and not a Numpy array, use
`np.array` to convert the list to an array.
Examples
--------
>>> a = np.arange(16).reshape((4,4))
>>> a
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
>>> labels = np.zeros_like(a)
>>> labels[:2,:2] = 1
>>> labels[2:, 1:3] = 2
>>> labels
array([[1, 1, 0, 0],
[1, 1, 0, 0],
[0, 2, 2, 0],
[0, 2, 2, 0]])
>>> from scipy import ndimage
>>> ndimage.maximum(a)
15.0
>>> ndimage.maximum(a, labels=labels, index=[1,2])
[5.0, 14.0]
>>> ndimage.maximum(a, labels=labels)
14.0
>>> b = np.array([[1, 2, 0, 0],
... [5, 3, 0, 4],
... [0, 0, 0, 7],
... [9, 3, 0, 0]])
>>> labels, labels_nb = ndimage.label(b)
>>> labels
array([[1, 1, 0, 0],
[1, 1, 0, 2],
[0, 0, 0, 2],
[3, 3, 0, 0]])
>>> ndimage.maximum(b, labels=labels, index=np.arange(1, labels_nb + 1))
[5.0, 7.0, 9.0] | Calculate the maximum of the values of an array over labeled regions. | [
"Calculate",
"the",
"maximum",
"of",
"the",
"values",
"of",
"an",
"array",
"over",
"labeled",
"regions",
"."
] | def maximum(input, labels=None, index=None):
"""
Calculate the maximum of the values of an array over labeled regions.
Parameters
----------
input : array_like
Array_like of values. For each region specified by `labels`, the
maximal values of `input` over the region is computed.
labels : array_like, optional
An array of integers marking different regions over which the
maximum value of `input` is to be computed. `labels` must have the
same shape as `input`. If `labels` is not specified, the maximum
over the whole array is returned.
index : array_like, optional
A list of region labels that are taken into account for computing the
maxima. If index is None, the maximum over all elements where `labels`
is non-zero is returned.
Returns
-------
output : float or list of floats
List of maxima of `input` over the regions determined by `labels` and
whose index is in `index`. If `index` or `labels` are not specified, a
float is returned: the maximal value of `input` if `labels` is None,
and the maximal value of elements where `labels` is greater than zero
if `index` is None.
See also
--------
label, minimum, median, maximum_position, extrema, sum, mean, variance,
standard_deviation
Notes
-----
The function returns a Python list and not a Numpy array, use
`np.array` to convert the list to an array.
Examples
--------
>>> a = np.arange(16).reshape((4,4))
>>> a
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
>>> labels = np.zeros_like(a)
>>> labels[:2,:2] = 1
>>> labels[2:, 1:3] = 2
>>> labels
array([[1, 1, 0, 0],
[1, 1, 0, 0],
[0, 2, 2, 0],
[0, 2, 2, 0]])
>>> from scipy import ndimage
>>> ndimage.maximum(a)
15.0
>>> ndimage.maximum(a, labels=labels, index=[1,2])
[5.0, 14.0]
>>> ndimage.maximum(a, labels=labels)
14.0
>>> b = np.array([[1, 2, 0, 0],
... [5, 3, 0, 4],
... [0, 0, 0, 7],
... [9, 3, 0, 0]])
>>> labels, labels_nb = ndimage.label(b)
>>> labels
array([[1, 1, 0, 0],
[1, 1, 0, 2],
[0, 0, 0, 2],
[3, 3, 0, 0]])
>>> ndimage.maximum(b, labels=labels, index=np.arange(1, labels_nb + 1))
[5.0, 7.0, 9.0]
"""
return _select(input, labels, index, find_max=True)[0] | [
"def",
"maximum",
"(",
"input",
",",
"labels",
"=",
"None",
",",
"index",
"=",
"None",
")",
":",
"return",
"_select",
"(",
"input",
",",
"labels",
",",
"index",
",",
"find_max",
"=",
"True",
")",
"[",
"0",
"]"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/ndimage/measurements.py#L918-L994 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/debug/cli/analyzer_cli.py | python | DebugAnalyzer.list_outputs | (self, args, screen_info=None) | return output | Command handler for inputs.
Show inputs to a given node.
Args:
args: Command-line arguments, excluding the command prefix, as a list of
str.
screen_info: Optional dict input containing screen information such as
cols.
Returns:
Output text lines as a RichTextLines object. | Command handler for inputs. | [
"Command",
"handler",
"for",
"inputs",
"."
] | def list_outputs(self, args, screen_info=None):
"""Command handler for inputs.
Show inputs to a given node.
Args:
args: Command-line arguments, excluding the command prefix, as a list of
str.
screen_info: Optional dict input containing screen information such as
cols.
Returns:
Output text lines as a RichTextLines object.
"""
# Screen info not currently used by this handler. Include this line to
# mute pylint.
_ = screen_info
# TODO(cais): Use screen info to format the output lines more prettily,
# e.g., hanging indent of long node names.
parsed = self._arg_parsers["list_outputs"].parse_args(args)
output = self._list_inputs_or_outputs(
parsed.recursive,
parsed.node_name,
parsed.depth,
parsed.control,
parsed.op_type,
do_outputs=True)
node_name = debug_graphs.get_node_name(parsed.node_name)
_add_main_menu(output, node_name=node_name, enable_list_outputs=False)
return output | [
"def",
"list_outputs",
"(",
"self",
",",
"args",
",",
"screen_info",
"=",
"None",
")",
":",
"# Screen info not currently used by this handler. Include this line to",
"# mute pylint.",
"_",
"=",
"screen_info",
"# TODO(cais): Use screen info to format the output lines more prettily,"... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/debug/cli/analyzer_cli.py#L1052-L1086 | |
Ifsttar/I-Simpa | 2283385f4cac769a92e265edabb9c79cb6c42d03 | currentRelease/SystemScript/graphy/common.py | python | BaseChart.__init__ | (self) | Construct a BaseChart object. | Construct a BaseChart object. | [
"Construct",
"a",
"BaseChart",
"object",
"."
] | def __init__(self):
"""Construct a BaseChart object."""
self.data = []
self._axes = {}
for code in self._POSITION_CODES:
self._axes[code] = [Axis()]
self._legend_labels = [] # AutoLegend fills this out
self._show_legend = False # AutoLegend fills this out
# Aliases for default formatters
self.auto_color = formatters.AutoColor()
self.auto_scale = formatters.AutoScale()
self.auto_legend = formatters.AutoLegend
self.formatters = [self.auto_color, self.auto_scale, self.auto_legend]
# display is used to convert the chart into something displayable (like a
# url or img tag).
self.display = None | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"data",
"=",
"[",
"]",
"self",
".",
"_axes",
"=",
"{",
"}",
"for",
"code",
"in",
"self",
".",
"_POSITION_CODES",
":",
"self",
".",
"_axes",
"[",
"code",
"]",
"=",
"[",
"Axis",
"(",
")",
"]"... | https://github.com/Ifsttar/I-Simpa/blob/2283385f4cac769a92e265edabb9c79cb6c42d03/currentRelease/SystemScript/graphy/common.py#L234-L251 | ||
moderngl/moderngl | 32fe79927e02b0fa893b3603d677bdae39771e14 | moderngl/program_members/uniform_block.py | python | UniformBlock.binding | (self) | return self.mglo.binding | int: The binding of the uniform block. | int: The binding of the uniform block. | [
"int",
":",
"The",
"binding",
"of",
"the",
"uniform",
"block",
"."
] | def binding(self) -> int:
'''
int: The binding of the uniform block.
'''
return self.mglo.binding | [
"def",
"binding",
"(",
"self",
")",
"->",
"int",
":",
"return",
"self",
".",
"mglo",
".",
"binding"
] | https://github.com/moderngl/moderngl/blob/32fe79927e02b0fa893b3603d677bdae39771e14/moderngl/program_members/uniform_block.py#L26-L31 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py | python | Misc.option_readfile | (self, fileName, priority = None) | Read file FILENAME into the option database.
An optional second parameter gives the numeric
priority. | Read file FILENAME into the option database. | [
"Read",
"file",
"FILENAME",
"into",
"the",
"option",
"database",
"."
] | def option_readfile(self, fileName, priority = None):
"""Read file FILENAME into the option database.
An optional second parameter gives the numeric
priority."""
self.tk.call('option', 'readfile', fileName, priority) | [
"def",
"option_readfile",
"(",
"self",
",",
"fileName",
",",
"priority",
"=",
"None",
")",
":",
"self",
".",
"tk",
".",
"call",
"(",
"'option'",
",",
"'readfile'",
",",
"fileName",
",",
"priority",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py#L872-L877 | ||
llvm/llvm-project | ffa6262cb4e2a335d26416fad39a581b4f98c5f4 | lldb/examples/customization/bin-utils/binutils.py | python | utob | (debugger, command_line, result, dict) | Convert the unsigned integer to print its binary representation.
args[0] (mandatory) is the unsigned integer to be converted
args[1] (optional) is the bit width of the binary representation
args[2] (optional) if specified, turns on verbose printing | Convert the unsigned integer to print its binary representation.
args[0] (mandatory) is the unsigned integer to be converted
args[1] (optional) is the bit width of the binary representation
args[2] (optional) if specified, turns on verbose printing | [
"Convert",
"the",
"unsigned",
"integer",
"to",
"print",
"its",
"binary",
"representation",
".",
"args",
"[",
"0",
"]",
"(",
"mandatory",
")",
"is",
"the",
"unsigned",
"integer",
"to",
"be",
"converted",
"args",
"[",
"1",
"]",
"(",
"optional",
")",
"is",
... | def utob(debugger, command_line, result, dict):
"""Convert the unsigned integer to print its binary representation.
args[0] (mandatory) is the unsigned integer to be converted
args[1] (optional) is the bit width of the binary representation
args[2] (optional) if specified, turns on verbose printing"""
args = command_line.split()
try:
n = int(args[0], 0)
width = None
if len(args) > 1:
width = int(args[1], 0)
if width < 0:
width = 0
except:
print(utob.__doc__)
return
if len(args) > 2:
verbose = True
else:
verbose = False
bits = binary(n, width)
if not bits:
print("insufficient width value: %d" % width)
return
if verbose and width > 0:
pos = positions(width)
print(' ' + ' '.join(pos))
print(' %s' % str(bits)) | [
"def",
"utob",
"(",
"debugger",
",",
"command_line",
",",
"result",
",",
"dict",
")",
":",
"args",
"=",
"command_line",
".",
"split",
"(",
")",
"try",
":",
"n",
"=",
"int",
"(",
"args",
"[",
"0",
"]",
",",
"0",
")",
"width",
"=",
"None",
"if",
... | https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/lldb/examples/customization/bin-utils/binutils.py#L65-L94 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/training/checkpoint_utils.py | python | _set_variable_or_list_initializer | (variable_or_list, ckpt_file,
tensor_name) | Overrides initialization op of given variable or list of variables.
Calls `_set_checkpoint_initializer` for each variable in the given list of
variables.
Args:
variable_or_list: `tf.Variable` object or a list of `tf.Variable` objects.
ckpt_file: string, full path of the checkpoint.
tensor_name: Name of the tensor to load from the checkpoint.
Raises:
ValueError: if all objects in `variable_or_list` are not partitions of the
same large variable. | Overrides initialization op of given variable or list of variables. | [
"Overrides",
"initialization",
"op",
"of",
"given",
"variable",
"or",
"list",
"of",
"variables",
"."
] | def _set_variable_or_list_initializer(variable_or_list, ckpt_file,
tensor_name):
"""Overrides initialization op of given variable or list of variables.
Calls `_set_checkpoint_initializer` for each variable in the given list of
variables.
Args:
variable_or_list: `tf.Variable` object or a list of `tf.Variable` objects.
ckpt_file: string, full path of the checkpoint.
tensor_name: Name of the tensor to load from the checkpoint.
Raises:
ValueError: if all objects in `variable_or_list` are not partitions of the
same large variable.
"""
if isinstance(variable_or_list, (list, tuple)):
# A set of slices.
slice_name = None
for v in variable_or_list:
slice_info = v._save_slice_info # pylint:disable=protected-access
if slice_name is None:
slice_name = slice_info.full_name
elif slice_name != slice_info.full_name:
raise ValueError("Slices must all be from the same tensor: %s != %s" %
(slice_name, slice_info.full_name))
_set_checkpoint_initializer(v, ckpt_file, tensor_name, slice_info.spec)
else:
_set_checkpoint_initializer(variable_or_list, ckpt_file, tensor_name, "") | [
"def",
"_set_variable_or_list_initializer",
"(",
"variable_or_list",
",",
"ckpt_file",
",",
"tensor_name",
")",
":",
"if",
"isinstance",
"(",
"variable_or_list",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"# A set of slices.",
"slice_name",
"=",
"None",
"for",... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/training/checkpoint_utils.py#L289-L317 | ||
mysql/mysql-workbench | 2f35f9034f015cbcd22139a60e1baa2e3e8e795c | library/python/workbench/os_utils.py | python | FileUtils.remove_directory_recursive | (self, path) | Function Type : Success | Function Type : Success | [
"Function",
"Type",
":",
"Success"
] | def remove_directory_recursive(self, path):
"""
Function Type : Success
"""
try:
shutil.rmtree(path)
except (IOError, OSError) as err:
if err.errno == errno.EACCES:
raise PermissionDeniedError("Could not remove directory %s" % path)
raise err | [
"def",
"remove_directory_recursive",
"(",
"self",
",",
"path",
")",
":",
"try",
":",
"shutil",
".",
"rmtree",
"(",
"path",
")",
"except",
"(",
"IOError",
",",
"OSError",
")",
"as",
"err",
":",
"if",
"err",
".",
"errno",
"==",
"errno",
".",
"EACCES",
... | https://github.com/mysql/mysql-workbench/blob/2f35f9034f015cbcd22139a60e1baa2e3e8e795c/library/python/workbench/os_utils.py#L167-L176 | ||
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/python/ops/rnn.py | python | _infer_state_dtype | (explicit_dtype, state) | Infer the dtype of an RNN state.
Args:
explicit_dtype: explicitly declared dtype or None.
state: RNN's hidden state. Must be a Tensor or a nested iterable containing
Tensors.
Returns:
dtype: inferred dtype of hidden state.
Raises:
ValueError: if `state` has heterogeneous dtypes or is empty. | Infer the dtype of an RNN state. | [
"Infer",
"the",
"dtype",
"of",
"an",
"RNN",
"state",
"."
] | def _infer_state_dtype(explicit_dtype, state):
"""Infer the dtype of an RNN state.
Args:
explicit_dtype: explicitly declared dtype or None.
state: RNN's hidden state. Must be a Tensor or a nested iterable containing
Tensors.
Returns:
dtype: inferred dtype of hidden state.
Raises:
ValueError: if `state` has heterogeneous dtypes or is empty.
"""
if explicit_dtype is not None:
return explicit_dtype
elif nest.is_sequence(state):
inferred_dtypes = [element.dtype for element in nest.flatten(state)]
if not inferred_dtypes:
raise ValueError("Unable to infer dtype from empty state.")
all_same = all([x == inferred_dtypes[0] for x in inferred_dtypes])
if not all_same:
raise ValueError(
"State has tensors of different inferred_dtypes. Unable to infer a "
"single representative dtype.")
return inferred_dtypes[0]
else:
return state.dtype | [
"def",
"_infer_state_dtype",
"(",
"explicit_dtype",
",",
"state",
")",
":",
"if",
"explicit_dtype",
"is",
"not",
"None",
":",
"return",
"explicit_dtype",
"elif",
"nest",
".",
"is_sequence",
"(",
"state",
")",
":",
"inferred_dtypes",
"=",
"[",
"element",
".",
... | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/ops/rnn.py#L43-L70 | ||
bryanyzhu/Hidden-Two-Stream | f7f684adbdacb6df6b1cf196c3a476cd23484a0f | scripts/cpp_lint.py | python | CheckCaffeDataLayerSetUp | (filename, clean_lines, linenum, error) | Except the base classes, Caffe DataLayer should define DataLayerSetUp
instead of LayerSetUp.
The base DataLayers define common SetUp steps, the subclasses should
not override them.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Except the base classes, Caffe DataLayer should define DataLayerSetUp
instead of LayerSetUp.
The base DataLayers define common SetUp steps, the subclasses should
not override them.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | [
"Except",
"the",
"base",
"classes",
"Caffe",
"DataLayer",
"should",
"define",
"DataLayerSetUp",
"instead",
"of",
"LayerSetUp",
".",
"The",
"base",
"DataLayers",
"define",
"common",
"SetUp",
"steps",
"the",
"subclasses",
"should",
"not",
"override",
"them",
".",
... | def CheckCaffeDataLayerSetUp(filename, clean_lines, linenum, error):
"""Except the base classes, Caffe DataLayer should define DataLayerSetUp
instead of LayerSetUp.
The base DataLayers define common SetUp steps, the subclasses should
not override them.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
ix = line.find('DataLayer<Dtype>::LayerSetUp')
if ix >= 0 and (
line.find('void DataLayer<Dtype>::LayerSetUp') != -1 or
line.find('void ImageDataLayer<Dtype>::LayerSetUp') != -1 or
line.find('void MemoryDataLayer<Dtype>::LayerSetUp') != -1 or
line.find('void WindowDataLayer<Dtype>::LayerSetUp') != -1):
error(filename, linenum, 'caffe/data_layer_setup', 2,
'Except the base classes, Caffe DataLayer should define'
+ ' DataLayerSetUp instead of LayerSetUp. The base DataLayers'
+ ' define common SetUp steps, the subclasses should'
+ ' not override them.')
ix = line.find('DataLayer<Dtype>::DataLayerSetUp')
if ix >= 0 and (
line.find('void Base') == -1 and
line.find('void DataLayer<Dtype>::DataLayerSetUp') == -1 and
line.find('void ImageDataLayer<Dtype>::DataLayerSetUp') == -1 and
line.find('void MemoryDataLayer<Dtype>::DataLayerSetUp') == -1 and
line.find('void WindowDataLayer<Dtype>::DataLayerSetUp') == -1):
error(filename, linenum, 'caffe/data_layer_setup', 2,
'Except the base classes, Caffe DataLayer should define'
+ ' DataLayerSetUp instead of LayerSetUp. The base DataLayers'
+ ' define common SetUp steps, the subclasses should'
+ ' not override them.') | [
"def",
"CheckCaffeDataLayerSetUp",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"ix",
"=",
"line",
".",
"find",
"(",
"'DataLayer<Dtype>::LayerSetUp'",
")",
"if",
... | https://github.com/bryanyzhu/Hidden-Two-Stream/blob/f7f684adbdacb6df6b1cf196c3a476cd23484a0f/scripts/cpp_lint.py#L1595-L1631 | ||
cksystemsgroup/scal | fa2208a97a77d65f4e90f85fef3404c27c1f2ac2 | tools/cpplint.py | python | CheckOperatorSpacing | (filename, clean_lines, linenum, error) | Checks for horizontal spacing around operators.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Checks for horizontal spacing around operators. | [
"Checks",
"for",
"horizontal",
"spacing",
"around",
"operators",
"."
] | def CheckOperatorSpacing(filename, clean_lines, linenum, error):
"""Checks for horizontal spacing around operators.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
# Don't try to do spacing checks for operator methods. Do this by
# replacing the troublesome characters with something else,
# preserving column position for all other characters.
#
# The replacement is done repeatedly to avoid false positives from
# operators that call operators.
while True:
match = Match(r'^(.*\boperator\b)(\S+)(\s*\(.*)$', line)
if match:
line = match.group(1) + ('_' * len(match.group(2))) + match.group(3)
else:
break
# We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )".
# Otherwise not. Note we only check for non-spaces on *both* sides;
# sometimes people put non-spaces on one side when aligning ='s among
# many lines (not that this is behavior that I approve of...)
if ((Search(r'[\w.]=', line) or
Search(r'=[\w.]', line))
and not Search(r'\b(if|while|for) ', line)
# Operators taken from [lex.operators] in C++11 standard.
and not Search(r'(>=|<=|==|!=|&=|\^=|\|=|\+=|\*=|\/=|\%=)', line)
and not Search(r'operator=', line)):
error(filename, linenum, 'whitespace/operators', 4,
'Missing spaces around =')
# It's ok not to have spaces around binary operators like + - * /, but if
# there's too little whitespace, we get concerned. It's hard to tell,
# though, so we punt on this one for now. TODO.
# You should always have whitespace around binary operators.
#
# Check <= and >= first to avoid false positives with < and >, then
# check non-include lines for spacing around < and >.
#
# If the operator is followed by a comma, assume it's be used in a
# macro context and don't do any checks. This avoids false
# positives.
#
# Note that && is not included here. Those are checked separately
# in CheckRValueReference
match = Search(r'[^<>=!\s](==|!=|<=|>=|\|\|)[^<>=!\s,;\)]', line)
if match:
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around %s' % match.group(1))
elif not Match(r'#.*include', line):
# Look for < that is not surrounded by spaces. This is only
# triggered if both sides are missing spaces, even though
# technically should should flag if at least one side is missing a
# space. This is done to avoid some false positives with shifts.
match = Match(r'^(.*[^\s<])<[^\s=<,]', line)
if match:
(_, _, end_pos) = CloseExpression(
clean_lines, linenum, len(match.group(1)))
if end_pos <= -1:
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around <')
# Look for > that is not surrounded by spaces. Similar to the
# above, we only trigger if both sides are missing spaces to avoid
# false positives with shifts.
match = Match(r'^(.*[^-\s>])>[^\s=>,]', line)
if match:
(_, _, start_pos) = ReverseCloseExpression(
clean_lines, linenum, len(match.group(1)))
if start_pos <= -1:
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around >')
# We allow no-spaces around << when used like this: 10<<20, but
# not otherwise (particularly, not when used as streams)
#
# We also allow operators following an opening parenthesis, since
# those tend to be macros that deal with operators.
match = Search(r'(operator|[^\s(<])(?:L|UL|ULL|l|ul|ull)?<<([^\s,=<])', line)
if (match and not (match.group(1).isdigit() and match.group(2).isdigit()) and
not (match.group(1) == 'operator' and match.group(2) == ';')):
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around <<')
# We allow no-spaces around >> for almost anything. This is because
# C++11 allows ">>" to close nested templates, which accounts for
# most cases when ">>" is not followed by a space.
#
# We still warn on ">>" followed by alpha character, because that is
# likely due to ">>" being used for right shifts, e.g.:
# value >> alpha
#
# When ">>" is used to close templates, the alphanumeric letter that
# follows would be part of an identifier, and there should still be
# a space separating the template type and the identifier.
# type<type<type>> alpha
match = Search(r'>>[a-zA-Z_]', line)
if match:
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around >>')
# There shouldn't be space around unary operators
match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line)
if match:
error(filename, linenum, 'whitespace/operators', 4,
'Extra space for operator %s' % match.group(1)) | [
"def",
"CheckOperatorSpacing",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"# Don't try to do spacing checks for operator methods. Do this by",
"# replacing the troublesome cha... | https://github.com/cksystemsgroup/scal/blob/fa2208a97a77d65f4e90f85fef3404c27c1f2ac2/tools/cpplint.py#L3127-L3239 | ||
tensor-compiler/taco | d0654a84137169883973c40a951dfdb89883fd9c | python_bindings/pytaco/pytensor/taco_tensor.py | python | evaluate | (expr, *operands, out_format=None, dtype=None) | return tensor.from_tensor_base(tensor_base) | Evaluates the index notation expression on the input operands.
An output tensor may be optionally specified. In this case, the tensor should be given the expected output shape,
format and dtype since the out_format and dtype fields will be ignored if an output tensor is seen.
Parameters
------------
expr: str
Specifies an index expression as a string. This must be of the form ``res(i1, i2, ...) = expr``. See the
examples for a more specific example. Each object represented by a name in the string and is indexed by a
variable for each dimension.
operands: list of tensors or array_like
Specifies the input tensors OR the input and output tensor. If the length of the list is equal to N - 1 where
N is the number of terms in the input expression then it is assumed that no output tensor was specified and
taco infers the output shape and uses the out_format and dtype passed in for the output tensor. If the
length of the operands is equal to N, then the first tensor is assumed to be the output tensor and the
out_format and dtype fields are ignored.
out_format: format, optional
The storage format of the output tensor if one was not explicitly provided. If left to None and no output
tensor was provided then all modes default to dense.
dtype: datatype
The datatype of the output tensor. If left to None and no output tensor was explicitly specified then taco uses
its promotion rules and sets the output to the datatype with the highest type.
Notes
-------
This provides a convenient way to express tensor expressions. It is identical to the Index Expression syntax with
a few exceptions. There is no need to use ``t[None]`` when making expressions with scalars and square brackets are
replaced with parenthesis. For example, in python we can represent matrix multiply as
``A[i, j] = B[i, k] * C[k, j]`` while the corresponding tensor expression would be ``A(i, j) = B(i, k) * C(k, j)``.
Further, reductions in pythonic index expression notation would be expressed as ``A[None] = B[i, j]`` to sum all
the elements of a matrix while the corresponding string would be ``A = B(i, j)``.
The string parser currently only supports +, -, / and *. Thus, expressions involving other functions such as exp,
tan etc, would have to be written using the pythonic expressions.
An input tensor is recognised by the parser by a name followed by a comma separated list of index variables in
parenthesis. Thus ``A(i,j,k)`` represents an order 3 tensor with the name A. The names used in the expression are
irrelevant since taco will match the operands with the terms in the expression in the same order they appear
(which is why when specifying an output, the output tensor must appear first followed by its input).
As with index expressions, index variables appearing that are on the right hand side of the expression but not
in the result are always summed.
Examples
----------
.. doctest::
>>> import numpy as np
>>> import pytaco as pt
>>> a = np.arange(25).reshape(5, 5)
>>> t = pt.tensor([5, 5], pt.csr)
>>> for i in range(5): t.insert([i, i], a[i, i])
>>> vec = np.arange(5)
# Note that no output is specified.
# We can sum over any of the axes of the sparse tensor as follows:
>>> pt.evaluate("T(j) = A(i, j)", t).to_array() # defaults to dense vector
array([ 0., 6., 12., 18., 24.], dtype=float32)
# Specify an output
>>> result = pt.tensor([5], pt.dense)
>>> pt.evaluate("T(j) = A(i, j)", result, t).to_array()
array([ 0., 6., 12., 18., 24.], dtype=float32)
>>> result.to_array()
array([ 0., 6., 12., 18., 24.], dtype=float32)
# We can perform addition and broadcast along a given axis
>>> pt.evaluate("T(i, j) = A(i, j) + B(j)", t, vec, out_format=pt.csr).to_array()
array([[ 0., 1., 2., 3., 4.],
[ 0., 7., 2., 3., 4.],
[ 0., 1., 14., 3., 4.],
[ 0., 1., 2., 21., 4.],
[ 0., 1., 2., 3., 28.]], dtype=float32)
# Create a SpMV kernel (since t is csr)
>>> pt.evaluate("A(j) = M(i, j) * V(j)", t, vec).to_array()
array([ 0., 6., 24., 54., 96.], dtype=float32)
# Sum tensor elements, note that names used don't matter
>>> pt.evaluate("S = C(i, j)", t)[0]
60.0
Examples of reductions along with computations. Note indices that appear of the right hand side but not
on the left hand side get summed over. This means we can implement matrix multiplication as shown below:
.. doctest::
>>> from scipy.sparse import csc_matrix
>>> mat = np.arange(9).reshape(3, 3)
>>> mat2 = csc_matrix(np.triu(np.arange(6).reshape(3, 2)))
# Compute mat @ mat2 due to ordering of operands.
>>> res = pt.evaluate("T(i, j) = A(i, k) * B(k, j)", mat, mat2, out_format=pt.csr)
>>> numpy_res = np.matmul(mat, mat2.toarray())
>>> all(res == numpy_res)
True
Returns
---------
output: tensor
The tensor calculated based on the string expression passed in. Even if taco detects that an output is
specified, it will still return a reference to that tensor. | Evaluates the index notation expression on the input operands. | [
"Evaluates",
"the",
"index",
"notation",
"expression",
"on",
"the",
"input",
"operands",
"."
] | def evaluate(expr, *operands, out_format=None, dtype=None):
"""
Evaluates the index notation expression on the input operands.
An output tensor may be optionally specified. In this case, the tensor should be given the expected output shape,
format and dtype since the out_format and dtype fields will be ignored if an output tensor is seen.
Parameters
------------
expr: str
Specifies an index expression as a string. This must be of the form ``res(i1, i2, ...) = expr``. See the
examples for a more specific example. Each object represented by a name in the string and is indexed by a
variable for each dimension.
operands: list of tensors or array_like
Specifies the input tensors OR the input and output tensor. If the length of the list is equal to N - 1 where
N is the number of terms in the input expression then it is assumed that no output tensor was specified and
taco infers the output shape and uses the out_format and dtype passed in for the output tensor. If the
length of the operands is equal to N, then the first tensor is assumed to be the output tensor and the
out_format and dtype fields are ignored.
out_format: format, optional
The storage format of the output tensor if one was not explicitly provided. If left to None and no output
tensor was provided then all modes default to dense.
dtype: datatype
The datatype of the output tensor. If left to None and no output tensor was explicitly specified then taco uses
its promotion rules and sets the output to the datatype with the highest type.
Notes
-------
This provides a convenient way to express tensor expressions. It is identical to the Index Expression syntax with
a few exceptions. There is no need to use ``t[None]`` when making expressions with scalars and square brackets are
replaced with parenthesis. For example, in python we can represent matrix multiply as
``A[i, j] = B[i, k] * C[k, j]`` while the corresponding tensor expression would be ``A(i, j) = B(i, k) * C(k, j)``.
Further, reductions in pythonic index expression notation would be expressed as ``A[None] = B[i, j]`` to sum all
the elements of a matrix while the corresponding string would be ``A = B(i, j)``.
The string parser currently only supports +, -, / and *. Thus, expressions involving other functions such as exp,
tan etc, would have to be written using the pythonic expressions.
An input tensor is recognised by the parser by a name followed by a comma separated list of index variables in
parenthesis. Thus ``A(i,j,k)`` represents an order 3 tensor with the name A. The names used in the expression are
irrelevant since taco will match the operands with the terms in the expression in the same order they appear
(which is why when specifying an output, the output tensor must appear first followed by its input).
As with index expressions, index variables appearing that are on the right hand side of the expression but not
in the result are always summed.
Examples
----------
.. doctest::
>>> import numpy as np
>>> import pytaco as pt
>>> a = np.arange(25).reshape(5, 5)
>>> t = pt.tensor([5, 5], pt.csr)
>>> for i in range(5): t.insert([i, i], a[i, i])
>>> vec = np.arange(5)
# Note that no output is specified.
# We can sum over any of the axes of the sparse tensor as follows:
>>> pt.evaluate("T(j) = A(i, j)", t).to_array() # defaults to dense vector
array([ 0., 6., 12., 18., 24.], dtype=float32)
# Specify an output
>>> result = pt.tensor([5], pt.dense)
>>> pt.evaluate("T(j) = A(i, j)", result, t).to_array()
array([ 0., 6., 12., 18., 24.], dtype=float32)
>>> result.to_array()
array([ 0., 6., 12., 18., 24.], dtype=float32)
# We can perform addition and broadcast along a given axis
>>> pt.evaluate("T(i, j) = A(i, j) + B(j)", t, vec, out_format=pt.csr).to_array()
array([[ 0., 1., 2., 3., 4.],
[ 0., 7., 2., 3., 4.],
[ 0., 1., 14., 3., 4.],
[ 0., 1., 2., 21., 4.],
[ 0., 1., 2., 3., 28.]], dtype=float32)
# Create a SpMV kernel (since t is csr)
>>> pt.evaluate("A(j) = M(i, j) * V(j)", t, vec).to_array()
array([ 0., 6., 24., 54., 96.], dtype=float32)
# Sum tensor elements, note that names used don't matter
>>> pt.evaluate("S = C(i, j)", t)[0]
60.0
Examples of reductions along with computations. Note indices that appear of the right hand side but not
on the left hand side get summed over. This means we can implement matrix multiplication as shown below:
.. doctest::
>>> from scipy.sparse import csc_matrix
>>> mat = np.arange(9).reshape(3, 3)
>>> mat2 = csc_matrix(np.triu(np.arange(6).reshape(3, 2)))
# Compute mat @ mat2 due to ordering of operands.
>>> res = pt.evaluate("T(i, j) = A(i, k) * B(k, j)", mat, mat2, out_format=pt.csr)
>>> numpy_res = np.matmul(mat, mat2.toarray())
>>> all(res == numpy_res)
True
Returns
---------
output: tensor
The tensor calculated based on the string expression passed in. Even if taco detects that an output is
specified, it will still return a reference to that tensor.
"""
args = [as_tensor(t, False) for t in operands]
if len(args) == 0:
raise ValueError("Expression must have at least one operand on the LHS and one on the RHS.")
out_dtype = args[0].dtype if dtype is None else dtype
if dtype is None:
for i in range(1, len(args)):
out_dtype = _cm.max_type(out_dtype, args[i].dtype)
tensor_base = _cm._parse(expr, [t._tensor for t in args], out_format, out_dtype)
return tensor.from_tensor_base(tensor_base) | [
"def",
"evaluate",
"(",
"expr",
",",
"*",
"operands",
",",
"out_format",
"=",
"None",
",",
"dtype",
"=",
"None",
")",
":",
"args",
"=",
"[",
"as_tensor",
"(",
"t",
",",
"False",
")",
"for",
"t",
"in",
"operands",
"]",
"if",
"len",
"(",
"args",
")... | https://github.com/tensor-compiler/taco/blob/d0654a84137169883973c40a951dfdb89883fd9c/python_bindings/pytaco/pytensor/taco_tensor.py#L2824-L2949 | |
ArduPilot/ardupilot | 6e684b3496122b8158ac412b609d00004b7ac306 | Tools/Vicon/vicon_mavlink.py | python | connect_to_vicon | (ip) | connect to a vicon with given ip or hostname | connect to a vicon with given ip or hostname | [
"connect",
"to",
"a",
"vicon",
"with",
"given",
"ip",
"or",
"hostname"
] | def connect_to_vicon(ip):
'''connect to a vicon with given ip or hostname'''
global vicon
print("Opening connection to %s" % ip)
vicon.connect(ip)
print("Configuring vicon")
vicon.set_stream_mode(pyvicon.StreamMode.ClientPull)
vicon.enable_marker_data()
vicon.enable_segment_data()
vicon.enable_unlabeled_marker_data()
vicon.enable_device_data()
# wait for first subject to appear
print("waiting for vehicle...")
while True:
vicon.get_frame()
name = vicon.get_subject_name(0)
if name is not None:
break
print("Connected to subject %s" % name) | [
"def",
"connect_to_vicon",
"(",
"ip",
")",
":",
"global",
"vicon",
"print",
"(",
"\"Opening connection to %s\"",
"%",
"ip",
")",
"vicon",
".",
"connect",
"(",
"ip",
")",
"print",
"(",
"\"Configuring vicon\"",
")",
"vicon",
".",
"set_stream_mode",
"(",
"pyvicon... | https://github.com/ArduPilot/ardupilot/blob/6e684b3496122b8158ac412b609d00004b7ac306/Tools/Vicon/vicon_mavlink.py#L55-L73 | ||
rampageX/firmware-mod-kit | c94cd6aeee50d92ec5280a6dba6d74828fd3606b | src/binwalk-2.1.1/src/binwalk/core/module.py | python | Module.load | (self) | return None | Invoked at module load time.
May be overridden by the module sub-class. | Invoked at module load time.
May be overridden by the module sub-class. | [
"Invoked",
"at",
"module",
"load",
"time",
".",
"May",
"be",
"overridden",
"by",
"the",
"module",
"sub",
"-",
"class",
"."
] | def load(self):
'''
Invoked at module load time.
May be overridden by the module sub-class.
'''
return None | [
"def",
"load",
"(",
"self",
")",
":",
"return",
"None"
] | https://github.com/rampageX/firmware-mod-kit/blob/c94cd6aeee50d92ec5280a6dba6d74828fd3606b/src/binwalk-2.1.1/src/binwalk/core/module.py#L258-L263 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Runtime/VART/vart/trace/vaitrace/tracer/cuEdge.py | python | cuEdgeTracer.prepare | (self, conf: dict, debug: bool) | return optForFtrace | Handle Input Options | Handle Input Options | [
"Handle",
"Input",
"Options"
] | def prepare(self, conf: dict, debug: bool):
"Handle Input Options"
"Handle Output Options"
optForFtrace = {
"collector": {
"ftrace": {
"cuEdge": {
"name": "cuEdge",
"type": "kprobe",
"saveTo": './cuEdge.trace',
"traceList": [
["cu_start", "zocl", "zocl_hls_start",
["cu_idx=+0(%x0):u32"]],
["cu_done", "zocl", "zocl_hls_check+0x70",
["cu_idx=+0(%x20):u32"]]
]
}
}
}
}
return optForFtrace | [
"def",
"prepare",
"(",
"self",
",",
"conf",
":",
"dict",
",",
"debug",
":",
"bool",
")",
":",
"\"Handle Output Options\"",
"optForFtrace",
"=",
"{",
"\"collector\"",
":",
"{",
"\"ftrace\"",
":",
"{",
"\"cuEdge\"",
":",
"{",
"\"name\"",
":",
"\"cuEdge\"",
"... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Runtime/VART/vart/trace/vaitrace/tracer/cuEdge.py#L28-L50 | |
IfcOpenShell/IfcOpenShell | 2c2954b11a9c9d581bef03240836d4567e69ad0b | src/ifcpatch/ifcpatch/__init__.py | python | extract_docs | (
submodule_name: str,
cls_name: str,
method_name: str="__init__",
boilerplate_args : typing.Iterable[str]=None) | Extract class docstrings and method arguments
:param submodule_name: Submodule from which to extract the class
:param cls_name: Class from which to extract the docstring and method arguments
:param method_name: Class Method name from which to extract arguments
:param boilerplate_args: String iterable containing arguments that shall not be parsed | Extract class docstrings and method arguments | [
"Extract",
"class",
"docstrings",
"and",
"method",
"arguments"
] | def extract_docs(
submodule_name: str,
cls_name: str,
method_name: str="__init__",
boilerplate_args : typing.Iterable[str]=None):
"""Extract class docstrings and method arguments
:param submodule_name: Submodule from which to extract the class
:param cls_name: Class from which to extract the docstring and method arguments
:param method_name: Class Method name from which to extract arguments
:param boilerplate_args: String iterable containing arguments that shall not be parsed
"""
spec = importlib.util.spec_from_file_location(
submodule_name,
f"{os.path.dirname(inspect.getabsfile(inspect.currentframe()))}/recipes/{submodule_name}.py")
submodule = importlib.util.module_from_spec(spec)
try:
spec.loader.exec_module(submodule)
try:
return _extract_docs(getattr(submodule, cls_name), method_name, boilerplate_args)
except AttributeError as e:
print(e)
except ModuleNotFoundError as e:
print(f"Error : IFCPatch {str(submodule)} could not load because : {str(e)}") | [
"def",
"extract_docs",
"(",
"submodule_name",
":",
"str",
",",
"cls_name",
":",
"str",
",",
"method_name",
":",
"str",
"=",
"\"__init__\"",
",",
"boilerplate_args",
":",
"typing",
".",
"Iterable",
"[",
"str",
"]",
"=",
"None",
")",
":",
"spec",
"=",
"imp... | https://github.com/IfcOpenShell/IfcOpenShell/blob/2c2954b11a9c9d581bef03240836d4567e69ad0b/src/ifcpatch/ifcpatch/__init__.py#L60-L83 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/resample.py | python | PeriodIndexResampler._upsample | (self, method, limit=None, fill_value=None) | return self._wrap_result(new_obj) | Parameters
----------
method : {'backfill', 'bfill', 'pad', 'ffill'}
Method for upsampling.
limit : int, default None
Maximum size gap to fill when reindexing.
fill_value : scalar, default None
Value to use for missing values.
See Also
--------
.fillna: Fill NA/NaN values using the specified method. | Parameters
----------
method : {'backfill', 'bfill', 'pad', 'ffill'}
Method for upsampling.
limit : int, default None
Maximum size gap to fill when reindexing.
fill_value : scalar, default None
Value to use for missing values. | [
"Parameters",
"----------",
"method",
":",
"{",
"backfill",
"bfill",
"pad",
"ffill",
"}",
"Method",
"for",
"upsampling",
".",
"limit",
":",
"int",
"default",
"None",
"Maximum",
"size",
"gap",
"to",
"fill",
"when",
"reindexing",
".",
"fill_value",
":",
"scala... | def _upsample(self, method, limit=None, fill_value=None):
"""
Parameters
----------
method : {'backfill', 'bfill', 'pad', 'ffill'}
Method for upsampling.
limit : int, default None
Maximum size gap to fill when reindexing.
fill_value : scalar, default None
Value to use for missing values.
See Also
--------
.fillna: Fill NA/NaN values using the specified method.
"""
# we may need to actually resample as if we are timestamps
if self.kind == "timestamp":
return super()._upsample(method, limit=limit, fill_value=fill_value)
ax = self.ax
obj = self.obj
new_index = self.binner
# Start vs. end of period
memb = ax.asfreq(self.freq, how=self.convention)
# Get the fill indexer
indexer = memb.get_indexer(new_index, method=method, limit=limit)
new_obj = _take_new_index(
obj,
indexer,
new_index,
axis=self.axis,
)
return self._wrap_result(new_obj) | [
"def",
"_upsample",
"(",
"self",
",",
"method",
",",
"limit",
"=",
"None",
",",
"fill_value",
"=",
"None",
")",
":",
"# we may need to actually resample as if we are timestamps",
"if",
"self",
".",
"kind",
"==",
"\"timestamp\"",
":",
"return",
"super",
"(",
")",... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/resample.py#L1301-L1336 | |
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | third_party/skia/tools/copyright/main.py | python | WriteStringToFile | (string, filepath) | Writes this string out to filepath, replacing the file if it already
exists. | Writes this string out to filepath, replacing the file if it already
exists. | [
"Writes",
"this",
"string",
"out",
"to",
"filepath",
"replacing",
"the",
"file",
"if",
"it",
"already",
"exists",
"."
] | def WriteStringToFile(string, filepath):
"""Writes this string out to filepath, replacing the file if it already
exists.
"""
with open(filepath, 'w') as file_handle:
file_handle.write(string) | [
"def",
"WriteStringToFile",
"(",
"string",
",",
"filepath",
")",
":",
"with",
"open",
"(",
"filepath",
",",
"'w'",
")",
"as",
"file_handle",
":",
"file_handle",
".",
"write",
"(",
"string",
")"
] | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/skia/tools/copyright/main.py#L92-L97 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/dataset/vision/py_transforms.py | python | RandomHorizontalFlip.__call__ | (self, img) | return util.random_horizontal_flip(img, self.prob) | Call method.
Args:
img (PIL Image): Image to be horizontally flipped.
Returns:
PIL Image, randomly horizontally flipped image. | Call method. | [
"Call",
"method",
"."
] | def __call__(self, img):
"""
Call method.
Args:
img (PIL Image): Image to be horizontally flipped.
Returns:
PIL Image, randomly horizontally flipped image.
"""
return util.random_horizontal_flip(img, self.prob) | [
"def",
"__call__",
"(",
"self",
",",
"img",
")",
":",
"return",
"util",
".",
"random_horizontal_flip",
"(",
"img",
",",
"self",
".",
"prob",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/dataset/vision/py_transforms.py#L495-L505 | |
netket/netket | 0d534e54ecbf25b677ea72af6b85947979420652 | netket/utils/struct/dataclass.py | python | dataclass | (clz=None, *, init_doc=MISSING, cache_hash=False, _frozen=True) | return data_clz | Decorator creating a NetKet-flavour dataclass.
This behaves as a flax dataclass, that is a Frozen python dataclass, with a twist!
See their documentation for standard behaviour.
The new functionalities added by NetKet are:
- it is possible to define a method `__pre_init__(*args, **kwargs) ->
Tuple[Tuple,Dict]` that processes the arguments and keyword arguments provided
to the dataclass constructor. This allows to deprecate argument names and add
some logic to customize the constructors.
This function should return a tuple of the edited `(args, kwargs)`. If
inheriting from other classes it is recomended (though not mandated) to
call the same method in parent classes. The function should return arguments and
keyword arguments that will match the standard dataclass constructor.
The function can also not be called in some internal cases, so it should not be
a strict requirement to execute it.
- Cached Properties. It is possible to mark properties of a netket dataclass with
`@property_cached`. This will make the property behave as a standard property,
but it's value is cached and reset every time a dataclass is manipulated.
Cached properties can be part of the flattened pytree or not.
See :ref:`netket.utils.struct.property_cached` for more info.
Optinal Args:
init_doc: the docstring for the init method. Otherwise it's inherited
from `__pre_init__`.
cache_hash: If True the hash is computed only once and cached. Use if
the computation is expensive.
_frozen: (default True) controls whever the resulting class is frozen or not.
If it is not frozen, extra care should be taken. | Decorator creating a NetKet-flavour dataclass.
This behaves as a flax dataclass, that is a Frozen python dataclass, with a twist!
See their documentation for standard behaviour. | [
"Decorator",
"creating",
"a",
"NetKet",
"-",
"flavour",
"dataclass",
".",
"This",
"behaves",
"as",
"a",
"flax",
"dataclass",
"that",
"is",
"a",
"Frozen",
"python",
"dataclass",
"with",
"a",
"twist!",
"See",
"their",
"documentation",
"for",
"standard",
"behavio... | def dataclass(clz=None, *, init_doc=MISSING, cache_hash=False, _frozen=True):
"""
Decorator creating a NetKet-flavour dataclass.
This behaves as a flax dataclass, that is a Frozen python dataclass, with a twist!
See their documentation for standard behaviour.
The new functionalities added by NetKet are:
- it is possible to define a method `__pre_init__(*args, **kwargs) ->
Tuple[Tuple,Dict]` that processes the arguments and keyword arguments provided
to the dataclass constructor. This allows to deprecate argument names and add
some logic to customize the constructors.
This function should return a tuple of the edited `(args, kwargs)`. If
inheriting from other classes it is recomended (though not mandated) to
call the same method in parent classes. The function should return arguments and
keyword arguments that will match the standard dataclass constructor.
The function can also not be called in some internal cases, so it should not be
a strict requirement to execute it.
- Cached Properties. It is possible to mark properties of a netket dataclass with
`@property_cached`. This will make the property behave as a standard property,
but it's value is cached and reset every time a dataclass is manipulated.
Cached properties can be part of the flattened pytree or not.
See :ref:`netket.utils.struct.property_cached` for more info.
Optinal Args:
init_doc: the docstring for the init method. Otherwise it's inherited
from `__pre_init__`.
cache_hash: If True the hash is computed only once and cached. Use if
the computation is expensive.
_frozen: (default True) controls whever the resulting class is frozen or not.
If it is not frozen, extra care should be taken.
"""
if clz is None:
return partial(
dataclass, init_doc=init_doc, cache_hash=cache_hash, _frozen=_frozen
)
# get globals of the class to put generated methods in there
_globals = get_class_globals(clz)
_globals["Uninitialized"] = Uninitialized
# proces all cached properties
process_cached_properties(clz, globals=_globals)
# create the dataclass
data_clz = dataclasses.dataclass(frozen=_frozen)(clz)
purge_cache_fields(data_clz)
# attach the custom preprocessing of init arguments
attach_preprocess_init(
data_clz, globals=_globals, init_doc=init_doc, cache_hash=cache_hash
)
if cache_hash:
replace_hash_method(data_clz, globals=_globals)
# flax stuff: identify states
meta_fields = []
data_fields = []
for name, field_info in getattr(data_clz, _FIELDS, {}).items():
is_pytree_node = field_info.metadata.get("pytree_node", True)
if is_pytree_node:
data_fields.append(name)
else:
meta_fields.append(name)
# List the cache fields
cache_fields = []
for _, cp in getattr(data_clz, _CACHES, {}).items():
cache_fields.append(cp.cache_name)
# they count as struct fields
if cp.pytree_node:
data_fields.append(cp.cache_name)
# they count as meta fields
else:
meta_fields.append(cp.cache_name)
def replace(self, **updates):
"""Returns a new object replacing the specified fields with new values."""
# reset cached fields
for name in cache_fields:
updates[name] = Uninitialized
return dataclasses.replace(self, **updates, __skip_preprocess=True)
data_clz.replace = replace
# support for jax pytree flattening unflattening
def iterate_clz(x):
meta = tuple(getattr(x, name) for name in meta_fields)
data = tuple(getattr(x, name) for name in data_fields)
return data, meta
def clz_from_iterable(meta, data):
meta_args = tuple(zip(meta_fields, meta))
data_args = tuple(zip(data_fields, data))
kwargs = dict(meta_args + data_args)
return data_clz(__skip_preprocess=True, **kwargs)
jax.tree_util.register_pytree_node(data_clz, iterate_clz, clz_from_iterable)
# flax serialization
skip_serialize_fields = []
for name, field_info in data_clz.__dataclass_fields__.items():
if not field_info.metadata.get("serialize", True):
skip_serialize_fields.append(name)
def to_state_dict(x):
state_dict = {
name: serialization.to_state_dict(getattr(x, name))
for name in data_fields
if name not in skip_serialize_fields
}
return state_dict
def from_state_dict(x, state):
"""Restore the state of a data class."""
state = state.copy() # copy the state so we can pop the restored fields.
updates = {}
for name in data_fields:
if name not in skip_serialize_fields:
if name not in state:
raise ValueError(
f"Missing field {name} in state dict while restoring"
f" an instance of {clz.__name__}"
)
value = getattr(x, name)
value_state = state.pop(name)
updates[name] = serialization.from_state_dict(value, value_state)
if state:
names = ",".join(state.keys())
raise ValueError(
f'Unknown field(s) "{names}" in state dict while'
f" restoring an instance of {clz.__name__}"
)
return x.replace(**updates)
serialization.register_serialization_state(data_clz, to_state_dict, from_state_dict)
return data_clz | [
"def",
"dataclass",
"(",
"clz",
"=",
"None",
",",
"*",
",",
"init_doc",
"=",
"MISSING",
",",
"cache_hash",
"=",
"False",
",",
"_frozen",
"=",
"True",
")",
":",
"if",
"clz",
"is",
"None",
":",
"return",
"partial",
"(",
"dataclass",
",",
"init_doc",
"=... | https://github.com/netket/netket/blob/0d534e54ecbf25b677ea72af6b85947979420652/netket/utils/struct/dataclass.py#L358-L494 | |
paperManu/splash | 0cc65377fa8c1225e1a1b8b3cfa35b4fd3a71467 | tools/package_ubuntu.py | python | debuild | () | return subprocess.call("debuild -S -sa", shell=True) | Build the Debian source package
:return: Return the exit code of the command | Build the Debian source package | [
"Build",
"the",
"Debian",
"source",
"package"
] | def debuild() -> int:
"""
Build the Debian source package
:return: Return the exit code of the command
"""
return subprocess.call("debuild -S -sa", shell=True) | [
"def",
"debuild",
"(",
")",
"->",
"int",
":",
"return",
"subprocess",
".",
"call",
"(",
"\"debuild -S -sa\"",
",",
"shell",
"=",
"True",
")"
] | https://github.com/paperManu/splash/blob/0cc65377fa8c1225e1a1b8b3cfa35b4fd3a71467/tools/package_ubuntu.py#L46-L52 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/ftplib.py | python | FTP.retrlines | (self, cmd, callback = None) | return self.voidresp() | Retrieve data in line mode. A new port is created for you.
Args:
cmd: A RETR, LIST, NLST, or MLSD command.
callback: An optional single parameter callable that is called
for each line with the trailing CRLF stripped.
[default: print_line()]
Returns:
The response code. | Retrieve data in line mode. A new port is created for you. | [
"Retrieve",
"data",
"in",
"line",
"mode",
".",
"A",
"new",
"port",
"is",
"created",
"for",
"you",
"."
] | def retrlines(self, cmd, callback = None):
"""Retrieve data in line mode. A new port is created for you.
Args:
cmd: A RETR, LIST, NLST, or MLSD command.
callback: An optional single parameter callable that is called
for each line with the trailing CRLF stripped.
[default: print_line()]
Returns:
The response code.
"""
if callback is None: callback = print_line
resp = self.sendcmd('TYPE A')
conn = self.transfercmd(cmd)
fp = conn.makefile('rb')
while 1:
line = fp.readline()
if self.debugging > 2: print '*retr*', repr(line)
if not line:
break
if line[-2:] == CRLF:
line = line[:-2]
elif line[-1:] == '\n':
line = line[:-1]
callback(line)
fp.close()
conn.close()
return self.voidresp() | [
"def",
"retrlines",
"(",
"self",
",",
"cmd",
",",
"callback",
"=",
"None",
")",
":",
"if",
"callback",
"is",
"None",
":",
"callback",
"=",
"print_line",
"resp",
"=",
"self",
".",
"sendcmd",
"(",
"'TYPE A'",
")",
"conn",
"=",
"self",
".",
"transfercmd",... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/ftplib.py#L418-L446 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/drill/view/DrillView.py | python | DrillView.show_directory_manager | (self) | Open the Mantid user directories manager. | Open the Mantid user directories manager. | [
"Open",
"the",
"Mantid",
"user",
"directories",
"manager",
"."
] | def show_directory_manager(self):
"""
Open the Mantid user directories manager.
"""
manageuserdirectories.ManageUserDirectories(self).exec_() | [
"def",
"show_directory_manager",
"(",
"self",
")",
":",
"manageuserdirectories",
".",
"ManageUserDirectories",
"(",
"self",
")",
".",
"exec_",
"(",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/drill/view/DrillView.py#L429-L433 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Runtime/VART/vart/trace/vaitrace/tracer/xapm.py | python | xapmTracer.prepare | (self, option: dict, debug: bool) | return option | Handle Input Options | Handle Input Options | [
"Handle",
"Input",
"Options"
] | def prepare(self, option: dict, debug: bool):
"Handle Input Options"
xapmOption = option.get('tracer', {}).get('xapm', {})
self.interval = xapmOption.get("APM_interval", 0.01)
self.apm = APM()
"Handle Output Options"
return option | [
"def",
"prepare",
"(",
"self",
",",
"option",
":",
"dict",
",",
"debug",
":",
"bool",
")",
":",
"xapmOption",
"=",
"option",
".",
"get",
"(",
"'tracer'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'xapm'",
",",
"{",
"}",
")",
"self",
".",
"interval",
... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Runtime/VART/vart/trace/vaitrace/tracer/xapm.py#L123-L130 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/collections/__init__.py | python | OrderedDict.values | (self) | return _OrderedDictValuesView(self) | D.values() -> an object providing a view on D's values | D.values() -> an object providing a view on D's values | [
"D",
".",
"values",
"()",
"-",
">",
"an",
"object",
"providing",
"a",
"view",
"on",
"D",
"s",
"values"
] | def values(self):
"D.values() -> an object providing a view on D's values"
return _OrderedDictValuesView(self) | [
"def",
"values",
"(",
"self",
")",
":",
"return",
"_OrderedDictValuesView",
"(",
"self",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/collections/__init__.py#L234-L236 | |
domino-team/openwrt-cc | 8b181297c34d14d3ca521cc9f31430d561dbc688 | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8_inspector/third_party/jinja2/jinja2/utils.py | python | generate_lorem_ipsum | (n=5, html=True, min=20, max=100) | return Markup(u'\n'.join(u'<p>%s</p>' % escape(x) for x in result)) | Generate some lorem ipsum for the template. | Generate some lorem ipsum for the template. | [
"Generate",
"some",
"lorem",
"ipsum",
"for",
"the",
"template",
"."
] | def generate_lorem_ipsum(n=5, html=True, min=20, max=100):
"""Generate some lorem ipsum for the template."""
from jinja2.constants import LOREM_IPSUM_WORDS
from random import choice, randrange
words = LOREM_IPSUM_WORDS.split()
result = []
for _ in range(n):
next_capitalized = True
last_comma = last_fullstop = 0
word = None
last = None
p = []
# each paragraph contains out of 20 to 100 words.
for idx, _ in enumerate(range(randrange(min, max))):
while True:
word = choice(words)
if word != last:
last = word
break
if next_capitalized:
word = word.capitalize()
next_capitalized = False
# add commas
if idx - randrange(3, 8) > last_comma:
last_comma = idx
last_fullstop += 2
word += ','
# add end of sentences
if idx - randrange(10, 20) > last_fullstop:
last_comma = last_fullstop = idx
word += '.'
next_capitalized = True
p.append(word)
# ensure that the paragraph ends with a dot.
p = u' '.join(p)
if p.endswith(','):
p = p[:-1] + '.'
elif not p.endswith('.'):
p += '.'
result.append(p)
if not html:
return u'\n\n'.join(result)
return Markup(u'\n'.join(u'<p>%s</p>' % escape(x) for x in result)) | [
"def",
"generate_lorem_ipsum",
"(",
"n",
"=",
"5",
",",
"html",
"=",
"True",
",",
"min",
"=",
"20",
",",
"max",
"=",
"100",
")",
":",
"from",
"jinja2",
".",
"constants",
"import",
"LOREM_IPSUM_WORDS",
"from",
"random",
"import",
"choice",
",",
"randrange... | https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8_inspector/third_party/jinja2/jinja2/utils.py#L237-L283 | |
jackaudio/jack2 | 21b293dbc37d42446141a08922cdec0d2550c6a0 | waflib/Scripting.py | python | Dist.execute | (self) | See :py:func:`waflib.Context.Context.execute` | See :py:func:`waflib.Context.Context.execute` | [
"See",
":",
"py",
":",
"func",
":",
"waflib",
".",
"Context",
".",
"Context",
".",
"execute"
] | def execute(self):
"""
See :py:func:`waflib.Context.Context.execute`
"""
self.recurse([os.path.dirname(Context.g_module.root_path)])
self.archive() | [
"def",
"execute",
"(",
"self",
")",
":",
"self",
".",
"recurse",
"(",
"[",
"os",
".",
"path",
".",
"dirname",
"(",
"Context",
".",
"g_module",
".",
"root_path",
")",
"]",
")",
"self",
".",
"archive",
"(",
")"
] | https://github.com/jackaudio/jack2/blob/21b293dbc37d42446141a08922cdec0d2550c6a0/waflib/Scripting.py#L343-L348 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/ops/math_grad.py | python | _AngleGrad | (op, grad) | Returns -grad / (Im(x) + iRe(x)) | Returns -grad / (Im(x) + iRe(x)) | [
"Returns",
"-",
"grad",
"/",
"(",
"Im",
"(",
"x",
")",
"+",
"iRe",
"(",
"x",
"))"
] | def _AngleGrad(op, grad):
"""Returns -grad / (Im(x) + iRe(x))"""
x = op.inputs[0]
with ops.control_dependencies([grad]):
re = math_ops.real(x)
im = math_ops.imag(x)
z = math_ops.reciprocal(math_ops.complex(im, re))
zero = constant_op.constant(0, dtype=grad.dtype)
complex_grad = math_ops.complex(grad, zero)
return -complex_grad * z | [
"def",
"_AngleGrad",
"(",
"op",
",",
"grad",
")",
":",
"x",
"=",
"op",
".",
"inputs",
"[",
"0",
"]",
"with",
"ops",
".",
"control_dependencies",
"(",
"[",
"grad",
"]",
")",
":",
"re",
"=",
"math_ops",
".",
"real",
"(",
"x",
")",
"im",
"=",
"mat... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/math_grad.py#L1082-L1091 | ||
moflow/moflow | 2dfb27c799c90c6caf1477508eca3eec616ef7d2 | bap/libtracewrap/libtrace/protobuf/python/mox.py | python | Mox.CreateMock | (self, class_to_mock) | return new_mock | Create a new mock object.
Args:
# class_to_mock: the class to be mocked
class_to_mock: class
Returns:
MockObject that can be used as the class_to_mock would be. | Create a new mock object. | [
"Create",
"a",
"new",
"mock",
"object",
"."
] | def CreateMock(self, class_to_mock):
"""Create a new mock object.
Args:
# class_to_mock: the class to be mocked
class_to_mock: class
Returns:
MockObject that can be used as the class_to_mock would be.
"""
new_mock = MockObject(class_to_mock)
self._mock_objects.append(new_mock)
return new_mock | [
"def",
"CreateMock",
"(",
"self",
",",
"class_to_mock",
")",
":",
"new_mock",
"=",
"MockObject",
"(",
"class_to_mock",
")",
"self",
".",
"_mock_objects",
".",
"append",
"(",
"new_mock",
")",
"return",
"new_mock"
] | https://github.com/moflow/moflow/blob/2dfb27c799c90c6caf1477508eca3eec616ef7d2/bap/libtracewrap/libtrace/protobuf/python/mox.py#L164-L177 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/diagnostic_updater/_publisher.py | python | HeaderlessTopicDiagnostic.clear_window | (self) | Clears the frequency statistics. | Clears the frequency statistics. | [
"Clears",
"the",
"frequency",
"statistics",
"."
] | def clear_window(self):
"""Clears the frequency statistics."""
self.freq.clear() | [
"def",
"clear_window",
"(",
"self",
")",
":",
"self",
".",
"freq",
".",
"clear",
"(",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/diagnostic_updater/_publisher.py#L76-L78 | ||
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py | python | MemoizedZipManifests.load | (self, path) | return self[path].manifest | Load a manifest at path or return a suitable manifest already loaded. | Load a manifest at path or return a suitable manifest already loaded. | [
"Load",
"a",
"manifest",
"at",
"path",
"or",
"return",
"a",
"suitable",
"manifest",
"already",
"loaded",
"."
] | def load(self, path):
"""
Load a manifest at path or return a suitable manifest already loaded.
"""
path = os.path.normpath(path)
mtime = os.stat(path).st_mtime
if path not in self or self[path].mtime != mtime:
manifest = self.build(path)
self[path] = self.manifest_mod(manifest, mtime)
return self[path].manifest | [
"def",
"load",
"(",
"self",
",",
"path",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"path",
")",
"mtime",
"=",
"os",
".",
"stat",
"(",
"path",
")",
".",
"st_mtime",
"if",
"path",
"not",
"in",
"self",
"or",
"self",
"[",
"pat... | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py#L1762-L1773 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/html2.py | python | WebView.GoForward | (*args, **kwargs) | return _html2.WebView_GoForward(*args, **kwargs) | GoForward(self) | GoForward(self) | [
"GoForward",
"(",
"self",
")"
] | def GoForward(*args, **kwargs):
"""GoForward(self)"""
return _html2.WebView_GoForward(*args, **kwargs) | [
"def",
"GoForward",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_html2",
".",
"WebView_GoForward",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/html2.py#L258-L260 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/dataview.py | python | DataViewTreeStore.__init__ | (self, *args, **kwargs) | __init__(self) -> DataViewTreeStore | __init__(self) -> DataViewTreeStore | [
"__init__",
"(",
"self",
")",
"-",
">",
"DataViewTreeStore"
] | def __init__(self, *args, **kwargs):
"""__init__(self) -> DataViewTreeStore"""
_dataview.DataViewTreeStore_swiginit(self,_dataview.new_DataViewTreeStore(*args, **kwargs)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_dataview",
".",
"DataViewTreeStore_swiginit",
"(",
"self",
",",
"_dataview",
".",
"new_DataViewTreeStore",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/dataview.py#L2355-L2357 | ||
omnisci/omniscidb | b9c95f1bd602b4ffc8b0edf18bfad61031e08d86 | python/omnisci/thrift/OmniSci.py | python | Iface.set_table_epochs | (self, session, db_id, table_epochs) | Parameters:
- session
- db_id
- table_epochs | Parameters:
- session
- db_id
- table_epochs | [
"Parameters",
":",
"-",
"session",
"-",
"db_id",
"-",
"table_epochs"
] | def set_table_epochs(self, session, db_id, table_epochs):
"""
Parameters:
- session
- db_id
- table_epochs
"""
pass | [
"def",
"set_table_epochs",
"(",
"self",
",",
"session",
",",
"db_id",
",",
"table_epochs",
")",
":",
"pass"
] | https://github.com/omnisci/omniscidb/blob/b9c95f1bd602b4ffc8b0edf18bfad61031e08d86/python/omnisci/thrift/OmniSci.py#L311-L319 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/pubsub/core/topicobj.py | python | Topic.getListeners | (self) | return py2and3.keys(self.__listeners) | Get a copy of list of listeners subscribed to this topic. Safe to iterate over while listeners
get un/subscribed from this topics (such as while sending a message). | Get a copy of list of listeners subscribed to this topic. Safe to iterate over while listeners
get un/subscribed from this topics (such as while sending a message). | [
"Get",
"a",
"copy",
"of",
"list",
"of",
"listeners",
"subscribed",
"to",
"this",
"topic",
".",
"Safe",
"to",
"iterate",
"over",
"while",
"listeners",
"get",
"un",
"/",
"subscribed",
"from",
"this",
"topics",
"(",
"such",
"as",
"while",
"sending",
"a",
"m... | def getListeners(self):
"""Get a copy of list of listeners subscribed to this topic. Safe to iterate over while listeners
get un/subscribed from this topics (such as while sending a message)."""
return py2and3.keys(self.__listeners) | [
"def",
"getListeners",
"(",
"self",
")",
":",
"return",
"py2and3",
".",
"keys",
"(",
"self",
".",
"__listeners",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/pubsub/core/topicobj.py#L262-L265 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/cubecolourdialog.py | python | toscale | (x) | return x*RADIUS/255.0 | Normalize a value as a function of the radius.
:param `x`: a float value to normalize | Normalize a value as a function of the radius. | [
"Normalize",
"a",
"value",
"as",
"a",
"function",
"of",
"the",
"radius",
"."
] | def toscale(x):
"""
Normalize a value as a function of the radius.
:param `x`: a float value to normalize
"""
return x*RADIUS/255.0 | [
"def",
"toscale",
"(",
"x",
")",
":",
"return",
"x",
"*",
"RADIUS",
"/",
"255.0"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/cubecolourdialog.py#L1225-L1232 | |
pyne/pyne | 0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3 | execer.py | python | execpy | (filename, glb=None, loc=None) | A function equivalent to the Python 2.x execfile statement. | A function equivalent to the Python 2.x execfile statement. | [
"A",
"function",
"equivalent",
"to",
"the",
"Python",
"2",
".",
"x",
"execfile",
"statement",
"."
] | def execpy(filename, glb=None, loc=None):
"""A function equivalent to the Python 2.x execfile statement."""
glb = {} if glb is None else glb
with io.open(filename, 'r') as f:
src = f.read()
exec(compile(src, filename, "exec"), glb, loc) | [
"def",
"execpy",
"(",
"filename",
",",
"glb",
"=",
"None",
",",
"loc",
"=",
"None",
")",
":",
"glb",
"=",
"{",
"}",
"if",
"glb",
"is",
"None",
"else",
"glb",
"with",
"io",
".",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"f",
":",
"src",
... | https://github.com/pyne/pyne/blob/0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3/execer.py#L16-L21 | ||
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py | python | xmlDoc.relaxNGValidateFullElement | (self, ctxt, elem) | return ret | Validate a full subtree when
xmlRelaxNGValidatePushElement() returned 0 and the content
of the node has been expanded. | Validate a full subtree when
xmlRelaxNGValidatePushElement() returned 0 and the content
of the node has been expanded. | [
"Validate",
"a",
"full",
"subtree",
"when",
"xmlRelaxNGValidatePushElement",
"()",
"returned",
"0",
"and",
"the",
"content",
"of",
"the",
"node",
"has",
"been",
"expanded",
"."
] | def relaxNGValidateFullElement(self, ctxt, elem):
"""Validate a full subtree when
xmlRelaxNGValidatePushElement() returned 0 and the content
of the node has been expanded. """
if ctxt is None: ctxt__o = None
else: ctxt__o = ctxt._o
if elem is None: elem__o = None
else: elem__o = elem._o
ret = libxml2mod.xmlRelaxNGValidateFullElement(ctxt__o, self._o, elem__o)
return ret | [
"def",
"relaxNGValidateFullElement",
"(",
"self",
",",
"ctxt",
",",
"elem",
")",
":",
"if",
"ctxt",
"is",
"None",
":",
"ctxt__o",
"=",
"None",
"else",
":",
"ctxt__o",
"=",
"ctxt",
".",
"_o",
"if",
"elem",
"is",
"None",
":",
"elem__o",
"=",
"None",
"e... | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L3406-L3415 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/dataview.py | python | DataViewRenderer.SetMode | (*args, **kwargs) | return _dataview.DataViewRenderer_SetMode(*args, **kwargs) | SetMode(self, int mode) | SetMode(self, int mode) | [
"SetMode",
"(",
"self",
"int",
"mode",
")"
] | def SetMode(*args, **kwargs):
"""SetMode(self, int mode)"""
return _dataview.DataViewRenderer_SetMode(*args, **kwargs) | [
"def",
"SetMode",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewRenderer_SetMode",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/dataview.py#L1168-L1170 | |
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/random.py | python | Random.vonmisesvariate | (self, mu, kappa) | return theta | Circular data distribution.
mu is the mean angle, expressed in radians between 0 and 2*pi, and
kappa is the concentration parameter, which must be greater than or
equal to zero. If kappa is equal to zero, this distribution reduces
to a uniform random angle over the range 0 to 2*pi. | Circular data distribution. | [
"Circular",
"data",
"distribution",
"."
] | def vonmisesvariate(self, mu, kappa):
"""Circular data distribution.
mu is the mean angle, expressed in radians between 0 and 2*pi, and
kappa is the concentration parameter, which must be greater than or
equal to zero. If kappa is equal to zero, this distribution reduces
to a uniform random angle over the range 0 to 2*pi.
"""
# mu: mean angle (in radians between 0 and 2*pi)
# kappa: concentration parameter kappa (>= 0)
# if kappa = 0 generate uniform random angle
# Based upon an algorithm published in: Fisher, N.I.,
# "Statistical Analysis of Circular Data", Cambridge
# University Press, 1993.
# Thanks to Magnus Kessler for a correction to the
# implementation of step 4.
random = self.random
if kappa <= 1e-6:
return TWOPI * random()
a = 1.0 + _sqrt(1.0 + 4.0 * kappa * kappa)
b = (a - _sqrt(2.0 * a))/(2.0 * kappa)
r = (1.0 + b * b)/(2.0 * b)
while 1:
u1 = random()
z = _cos(_pi * u1)
f = (1.0 + r * z)/(r + z)
c = kappa * (r - f)
u2 = random()
if u2 < c * (2.0 - c) or u2 <= c * _exp(1.0 - c):
break
u3 = random()
if u3 > 0.5:
theta = (mu % TWOPI) + _acos(f)
else:
theta = (mu % TWOPI) - _acos(f)
return theta | [
"def",
"vonmisesvariate",
"(",
"self",
",",
"mu",
",",
"kappa",
")",
":",
"# mu: mean angle (in radians between 0 and 2*pi)",
"# kappa: concentration parameter kappa (>= 0)",
"# if kappa = 0 generate uniform random angle",
"# Based upon an algorithm published in: Fisher, N.I.,",
"# \"... | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/random.py#L434-L480 | |
neoml-lib/neoml | a0d370fba05269a1b2258cef126f77bbd2054a3e | NeoML/Python/neoml/Dnn/Lrn.py | python | Lrn.beta | (self) | return self._internal.get_beta() | Gets the beta. | Gets the beta. | [
"Gets",
"the",
"beta",
"."
] | def beta(self):
"""Gets the beta.
"""
return self._internal.get_beta() | [
"def",
"beta",
"(",
"self",
")",
":",
"return",
"self",
".",
"_internal",
".",
"get_beta",
"(",
")"
] | https://github.com/neoml-lib/neoml/blob/a0d370fba05269a1b2258cef126f77bbd2054a3e/NeoML/Python/neoml/Dnn/Lrn.py#L103-L106 | |
ideawu/ssdb-rocks | a3cbb322cafb2f493252829c608e2239df98c9ac | deps/cpy/antlr3/tree.py | python | BaseTree.setParent | (self, t) | BaseTree doesn't track parent pointers. | BaseTree doesn't track parent pointers. | [
"BaseTree",
"doesn",
"t",
"track",
"parent",
"pointers",
"."
] | def setParent(self, t):
"""BaseTree doesn't track parent pointers."""
pass | [
"def",
"setParent",
"(",
"self",
",",
"t",
")",
":",
"pass"
] | https://github.com/ideawu/ssdb-rocks/blob/a3cbb322cafb2f493252829c608e2239df98c9ac/deps/cpy/antlr3/tree.py#L861-L864 | ||
yyzybb537/libgo | 4af17b7c67643c4d54aa354dcc77963ea07847d0 | third_party/boost.context/tools/build/src/build/generators.py | python | Generator.source_types | (self) | return self.source_types_ | Returns the list of target type the generator accepts. | Returns the list of target type the generator accepts. | [
"Returns",
"the",
"list",
"of",
"target",
"type",
"the",
"generator",
"accepts",
"."
] | def source_types (self):
""" Returns the list of target type the generator accepts.
"""
return self.source_types_ | [
"def",
"source_types",
"(",
"self",
")",
":",
"return",
"self",
".",
"source_types_"
] | https://github.com/yyzybb537/libgo/blob/4af17b7c67643c4d54aa354dcc77963ea07847d0/third_party/boost.context/tools/build/src/build/generators.py#L273-L276 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/fractions.py | python | Fraction.__trunc__ | (a) | trunc(a) | trunc(a) | [
"trunc",
"(",
"a",
")"
] | def __trunc__(a):
"""trunc(a)"""
if a._numerator < 0:
return -(-a._numerator // a._denominator)
else:
return a._numerator // a._denominator | [
"def",
"__trunc__",
"(",
"a",
")",
":",
"if",
"a",
".",
"_numerator",
"<",
"0",
":",
"return",
"-",
"(",
"-",
"a",
".",
"_numerator",
"//",
"a",
".",
"_denominator",
")",
"else",
":",
"return",
"a",
".",
"_numerator",
"//",
"a",
".",
"_denominator"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/fractions.py#L501-L506 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/callwrapper.py | python | PyCallWrapper._simplified_return_type | (self) | The NPM callconv has already converted simplified optional types.
We can simply use the value type from it. | The NPM callconv has already converted simplified optional types.
We can simply use the value type from it. | [
"The",
"NPM",
"callconv",
"has",
"already",
"converted",
"simplified",
"optional",
"types",
".",
"We",
"can",
"simply",
"use",
"the",
"value",
"type",
"from",
"it",
"."
] | def _simplified_return_type(self):
"""
The NPM callconv has already converted simplified optional types.
We can simply use the value type from it.
"""
restype = self.fndesc.restype
# Optional type
if isinstance(restype, types.Optional):
return restype.type
else:
return restype | [
"def",
"_simplified_return_type",
"(",
"self",
")",
":",
"restype",
"=",
"self",
".",
"fndesc",
".",
"restype",
"# Optional type",
"if",
"isinstance",
"(",
"restype",
",",
"types",
".",
"Optional",
")",
":",
"return",
"restype",
".",
"type",
"else",
":",
"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/callwrapper.py#L199-L209 | ||
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/requests/requests/packages/urllib3/fields.py | python | RequestField.make_multipart | (self, content_disposition=None, content_type=None,
content_location=None) | Makes this request field into a multipart request field.
This method overrides "Content-Disposition", "Content-Type" and
"Content-Location" headers to the request parameter.
:param content_type:
The 'Content-Type' of the request body.
:param content_location:
The 'Content-Location' of the request body. | Makes this request field into a multipart request field. | [
"Makes",
"this",
"request",
"field",
"into",
"a",
"multipart",
"request",
"field",
"."
] | def make_multipart(self, content_disposition=None, content_type=None,
content_location=None):
"""
Makes this request field into a multipart request field.
This method overrides "Content-Disposition", "Content-Type" and
"Content-Location" headers to the request parameter.
:param content_type:
The 'Content-Type' of the request body.
:param content_location:
The 'Content-Location' of the request body.
"""
self.headers['Content-Disposition'] = content_disposition or 'form-data'
self.headers['Content-Disposition'] += '; '.join([
'', self._render_parts(
(('name', self._name), ('filename', self._filename))
)
])
self.headers['Content-Type'] = content_type
self.headers['Content-Location'] = content_location | [
"def",
"make_multipart",
"(",
"self",
",",
"content_disposition",
"=",
"None",
",",
"content_type",
"=",
"None",
",",
"content_location",
"=",
"None",
")",
":",
"self",
".",
"headers",
"[",
"'Content-Disposition'",
"]",
"=",
"content_disposition",
"or",
"'form-d... | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/requests/requests/packages/urllib3/fields.py#L156-L177 | ||
yyzybb537/libgo | 4af17b7c67643c4d54aa354dcc77963ea07847d0 | third_party/boost.context/tools/build/src/build/generators.py | python | __ensure_type | (targets) | Ensures all 'targets' have types. If this is not so, exists with
error. | Ensures all 'targets' have types. If this is not so, exists with
error. | [
"Ensures",
"all",
"targets",
"have",
"types",
".",
"If",
"this",
"is",
"not",
"so",
"exists",
"with",
"error",
"."
] | def __ensure_type (targets):
""" Ensures all 'targets' have types. If this is not so, exists with
error.
"""
assert is_iterable_typed(targets, virtual_target.VirtualTarget)
for t in targets:
if not t.type ():
get_manager().errors()("target '%s' has no type" % str (t)) | [
"def",
"__ensure_type",
"(",
"targets",
")",
":",
"assert",
"is_iterable_typed",
"(",
"targets",
",",
"virtual_target",
".",
"VirtualTarget",
")",
"for",
"t",
"in",
"targets",
":",
"if",
"not",
"t",
".",
"type",
"(",
")",
":",
"get_manager",
"(",
")",
".... | https://github.com/yyzybb537/libgo/blob/4af17b7c67643c4d54aa354dcc77963ea07847d0/third_party/boost.context/tools/build/src/build/generators.py#L985-L992 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/distribute/v1/input_lib.py | python | _SingleWorkerDatasetIterator.initialize | (self) | Initialize underlying iterator.
In eager execution, this simply recreates the underlying iterator.
In graph execution, it returns the initializer ops for the underlying
iterator.
Returns:
A list of any initializer ops that should be run. | Initialize underlying iterator. | [
"Initialize",
"underlying",
"iterator",
"."
] | def initialize(self):
"""Initialize underlying iterator.
In eager execution, this simply recreates the underlying iterator.
In graph execution, it returns the initializer ops for the underlying
iterator.
Returns:
A list of any initializer ops that should be run.
"""
if ops.executing_eagerly_outside_functions():
self._iterator._eager_reset() # pylint: disable=protected-access
return []
else:
return [self._iterator.initializer] | [
"def",
"initialize",
"(",
"self",
")",
":",
"if",
"ops",
".",
"executing_eagerly_outside_functions",
"(",
")",
":",
"self",
".",
"_iterator",
".",
"_eager_reset",
"(",
")",
"# pylint: disable=protected-access",
"return",
"[",
"]",
"else",
":",
"return",
"[",
"... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/distribute/v1/input_lib.py#L343-L357 | ||
panda3d/panda3d | 833ad89ebad58395d0af0b7ec08538e5e4308265 | direct/src/distributed/AsyncRequest.py | python | AsyncRequest.createObjectId | (self, name, className, values = None, context = None) | Create a new database object. You can get the doId from within
your self.finish() function.
This functions is different from createObject in that it does not
generate the object when the response comes back. It only tells you
the doId. This is useful on the UD where we don't really want the
object on the UD, we just want the object created and the UD wants
to send messages to it using the ID. | Create a new database object. You can get the doId from within
your self.finish() function. | [
"Create",
"a",
"new",
"database",
"object",
".",
"You",
"can",
"get",
"the",
"doId",
"from",
"within",
"your",
"self",
".",
"finish",
"()",
"function",
"."
] | def createObjectId(self, name, className, values = None, context = None):
"""
Create a new database object. You can get the doId from within
your self.finish() function.
This functions is different from createObject in that it does not
generate the object when the response comes back. It only tells you
the doId. This is useful on the UD where we don't really want the
object on the UD, we just want the object created and the UD wants
to send messages to it using the ID.
"""
assert AsyncRequest.notify.debugCall()
assert name
assert className
self.neededObjects[name] = None
if context is None:
context = self.air.allocateContext()
self.accept(
self.air.getDatabaseGenerateResponseEvent(context),
self._checkCompletion, [name, None])
self.air.requestDatabaseGenerate(className, context, values = values)
self._resetTimeoutTask() | [
"def",
"createObjectId",
"(",
"self",
",",
"name",
",",
"className",
",",
"values",
"=",
"None",
",",
"context",
"=",
"None",
")",
":",
"assert",
"AsyncRequest",
".",
"notify",
".",
"debugCall",
"(",
")",
"assert",
"name",
"assert",
"className",
"self",
... | https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/distributed/AsyncRequest.py#L174-L195 | ||
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | tools/checkperms/checkperms.py | python | ShouldCheckDirectory | (dir_path) | return repo_url == SVN_REPO_URL | Determine if we should check the content of dir_path. | Determine if we should check the content of dir_path. | [
"Determine",
"if",
"we",
"should",
"check",
"the",
"content",
"of",
"dir_path",
"."
] | def ShouldCheckDirectory(dir_path):
"""Determine if we should check the content of dir_path."""
if not IS_SVN:
return dir_path in GIT_SOURCE_DIRECTORY
repo_url = GetSvnRepositoryRoot(dir_path)
if not repo_url:
return False
return repo_url == SVN_REPO_URL | [
"def",
"ShouldCheckDirectory",
"(",
"dir_path",
")",
":",
"if",
"not",
"IS_SVN",
":",
"return",
"dir_path",
"in",
"GIT_SOURCE_DIRECTORY",
"repo_url",
"=",
"GetSvnRepositoryRoot",
"(",
"dir_path",
")",
"if",
"not",
"repo_url",
":",
"return",
"False",
"return",
"r... | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/tools/checkperms/checkperms.py#L194-L201 | |
ZhouWeikuan/DouDiZhu | 0d84ff6c0bc54dba6ae37955de9ae9307513dc99 | code/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py | python | Diagnostic.option | (self) | return conf.lib.clang_getDiagnosticOption(self, None) | The command-line option that enables this diagnostic. | The command-line option that enables this diagnostic. | [
"The",
"command",
"-",
"line",
"option",
"that",
"enables",
"this",
"diagnostic",
"."
] | def option(self):
"""The command-line option that enables this diagnostic."""
return conf.lib.clang_getDiagnosticOption(self, None) | [
"def",
"option",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_getDiagnosticOption",
"(",
"self",
",",
"None",
")"
] | https://github.com/ZhouWeikuan/DouDiZhu/blob/0d84ff6c0bc54dba6ae37955de9ae9307513dc99/code/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py#L350-L352 | |
KhronosGroup/OpenCOLLADA | 6031fa956e1da4bbdd910af3a8f9e924ef0fca7a | Externals/LibXML/python/libxml.py | python | SAXCallback.cdataBlock | (self, data) | called when CDATA section have been read, data is the string
containing the data, multiple consecutive cdataBlock() callback
are possible. | called when CDATA section have been read, data is the string
containing the data, multiple consecutive cdataBlock() callback
are possible. | [
"called",
"when",
"CDATA",
"section",
"have",
"been",
"read",
"data",
"is",
"the",
"string",
"containing",
"the",
"data",
"multiple",
"consecutive",
"cdataBlock",
"()",
"callback",
"are",
"possible",
"."
] | def cdataBlock(self, data):
"""called when CDATA section have been read, data is the string
containing the data, multiple consecutive cdataBlock() callback
are possible."""
pass | [
"def",
"cdataBlock",
"(",
"self",
",",
"data",
")",
":",
"pass"
] | https://github.com/KhronosGroup/OpenCOLLADA/blob/6031fa956e1da4bbdd910af3a8f9e924ef0fca7a/Externals/LibXML/python/libxml.py#L160-L164 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/array_analysis.py | python | ShapeEquivSet.get_shape_classes | (self, name) | return inds | Instead of the shape tuple, return tuple of int, where
each int is the corresponding class index of the size object.
Unknown shapes are given class index -1. Return empty tuple
if the input name is a scalar variable. | Instead of the shape tuple, return tuple of int, where
each int is the corresponding class index of the size object.
Unknown shapes are given class index -1. Return empty tuple
if the input name is a scalar variable. | [
"Instead",
"of",
"the",
"shape",
"tuple",
"return",
"tuple",
"of",
"int",
"where",
"each",
"int",
"is",
"the",
"corresponding",
"class",
"index",
"of",
"the",
"size",
"object",
".",
"Unknown",
"shapes",
"are",
"given",
"class",
"index",
"-",
"1",
".",
"R... | def get_shape_classes(self, name):
"""Instead of the shape tuple, return tuple of int, where
each int is the corresponding class index of the size object.
Unknown shapes are given class index -1. Return empty tuple
if the input name is a scalar variable.
"""
if isinstance(name, ir.Var):
name = name.name
typ = self.typemap[name] if name in self.typemap else None
if not (isinstance(typ, types.BaseTuple) or
isinstance(typ, types.SliceType) or
isinstance(typ, types.ArrayCompatible)):
return []
# Treat 0d arrays like scalars.
if isinstance(typ, types.ArrayCompatible) and typ.ndim == 0:
return []
names = self._get_names(name)
inds = tuple(self._get_ind(name) for name in names)
return inds | [
"def",
"get_shape_classes",
"(",
"self",
",",
"name",
")",
":",
"if",
"isinstance",
"(",
"name",
",",
"ir",
".",
"Var",
")",
":",
"name",
"=",
"name",
".",
"name",
"typ",
"=",
"self",
".",
"typemap",
"[",
"name",
"]",
"if",
"name",
"in",
"self",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/array_analysis.py#L557-L575 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/py_vulcanize/third_party/rcssmin/_setup/py2/setup.py | python | find_license | (docs) | return None | Determine license from LICENSE
:return: License text
:rtype: ``str`` | Determine license from LICENSE | [
"Determine",
"license",
"from",
"LICENSE"
] | def find_license(docs):
"""
Determine license from LICENSE
:return: License text
:rtype: ``str``
"""
filename = docs.get('meta.license', 'LICENSE').strip()
if filename and _os.path.isfile(filename):
fp = open(filename)
try:
return fp.read().rstrip()
finally:
fp.close()
return None | [
"def",
"find_license",
"(",
"docs",
")",
":",
"filename",
"=",
"docs",
".",
"get",
"(",
"'meta.license'",
",",
"'LICENSE'",
")",
".",
"strip",
"(",
")",
"if",
"filename",
"and",
"_os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
":",
"fp",
"=",... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/py_vulcanize/third_party/rcssmin/_setup/py2/setup.py#L157-L171 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/arrays/categorical.py | python | Categorical.set_ordered | (self, value, inplace=False) | Set the ordered attribute to the boolean value.
Parameters
----------
value : bool
Set whether this categorical is ordered (True) or not (False).
inplace : bool, default False
Whether or not to set the ordered attribute in-place or return
a copy of this categorical with ordered set to the value. | Set the ordered attribute to the boolean value. | [
"Set",
"the",
"ordered",
"attribute",
"to",
"the",
"boolean",
"value",
"."
] | def set_ordered(self, value, inplace=False):
"""
Set the ordered attribute to the boolean value.
Parameters
----------
value : bool
Set whether this categorical is ordered (True) or not (False).
inplace : bool, default False
Whether or not to set the ordered attribute in-place or return
a copy of this categorical with ordered set to the value.
"""
inplace = validate_bool_kwarg(inplace, "inplace")
new_dtype = CategoricalDtype(self.categories, ordered=value)
cat = self if inplace else self.copy()
NDArrayBacked.__init__(cat, cat._ndarray, new_dtype)
if not inplace:
return cat | [
"def",
"set_ordered",
"(",
"self",
",",
"value",
",",
"inplace",
"=",
"False",
")",
":",
"inplace",
"=",
"validate_bool_kwarg",
"(",
"inplace",
",",
"\"inplace\"",
")",
"new_dtype",
"=",
"CategoricalDtype",
"(",
"self",
".",
"categories",
",",
"ordered",
"="... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/arrays/categorical.py#L823-L840 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_core.py | python | MouseState.GetPosition | (*args, **kwargs) | return _core_.MouseState_GetPosition(*args, **kwargs) | GetPosition(self) -> Point | GetPosition(self) -> Point | [
"GetPosition",
"(",
"self",
")",
"-",
">",
"Point"
] | def GetPosition(*args, **kwargs):
"""GetPosition(self) -> Point"""
return _core_.MouseState_GetPosition(*args, **kwargs) | [
"def",
"GetPosition",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"MouseState_GetPosition",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L4446-L4448 | |
LunarG/VulkanSamples | 08e87dc3194cfc15e49125f71592d8acff070ce4 | scripts/update_deps.py | python | GoodRepo.PreBuild | (self) | Execute any prebuild steps from the repo root | Execute any prebuild steps from the repo root | [
"Execute",
"any",
"prebuild",
"steps",
"from",
"the",
"repo",
"root"
] | def PreBuild(self):
"""Execute any prebuild steps from the repo root"""
for p in self.prebuild:
command_output(shlex.split(p), self.repo_dir)
if platform.system() == 'Linux' or platform.system() == 'Darwin':
for p in self.prebuild_linux:
command_output(shlex.split(p), self.repo_dir)
if platform.system() == 'Windows':
for p in self.prebuild_windows:
command_output(shlex.split(p), self.repo_dir) | [
"def",
"PreBuild",
"(",
"self",
")",
":",
"for",
"p",
"in",
"self",
".",
"prebuild",
":",
"command_output",
"(",
"shlex",
".",
"split",
"(",
"p",
")",
",",
"self",
".",
"repo_dir",
")",
"if",
"platform",
".",
"system",
"(",
")",
"==",
"'Linux'",
"o... | https://github.com/LunarG/VulkanSamples/blob/08e87dc3194cfc15e49125f71592d8acff070ce4/scripts/update_deps.py#L404-L413 | ||
WeitaoVan/L-GM-loss | 598582f0631bac876b3eeb8d6c4cd1d780269e03 | scripts/cpp_lint.py | python | CheckSpacing | (filename, clean_lines, linenum, nesting_state, error) | Checks for the correctness of various spacing issues in the code.
Things we check for: spaces around operators, spaces after
if/for/while/switch, no spaces around parens in function calls, two
spaces between code and comment, don't start a block with a blank
line, don't end a function with a blank line, don't add a blank line
after public/protected/private, don't have too many blank lines in a row.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found. | Checks for the correctness of various spacing issues in the code. | [
"Checks",
"for",
"the",
"correctness",
"of",
"various",
"spacing",
"issues",
"in",
"the",
"code",
"."
] | def CheckSpacing(filename, clean_lines, linenum, nesting_state, error):
"""Checks for the correctness of various spacing issues in the code.
Things we check for: spaces around operators, spaces after
if/for/while/switch, no spaces around parens in function calls, two
spaces between code and comment, don't start a block with a blank
line, don't end a function with a blank line, don't add a blank line
after public/protected/private, don't have too many blank lines in a row.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found.
"""
# Don't use "elided" lines here, otherwise we can't check commented lines.
# Don't want to use "raw" either, because we don't want to check inside C++11
# raw strings,
raw = clean_lines.lines_without_raw_strings
line = raw[linenum]
# Before nixing comments, check if the line is blank for no good
# reason. This includes the first line after a block is opened, and
# blank lines at the end of a function (ie, right before a line like '}'
#
# Skip all the blank line checks if we are immediately inside a
# namespace body. In other words, don't issue blank line warnings
# for this block:
# namespace {
#
# }
#
# A warning about missing end of namespace comments will be issued instead.
if IsBlankLine(line) and not nesting_state.InNamespaceBody():
elided = clean_lines.elided
prev_line = elided[linenum - 1]
prevbrace = prev_line.rfind('{')
# TODO(unknown): Don't complain if line before blank line, and line after,
# both start with alnums and are indented the same amount.
# This ignores whitespace at the start of a namespace block
# because those are not usually indented.
if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1:
# OK, we have a blank line at the start of a code block. Before we
# complain, we check if it is an exception to the rule: The previous
# non-empty line has the parameters of a function header that are indented
# 4 spaces (because they did not fit in a 80 column line when placed on
# the same line as the function name). We also check for the case where
# the previous line is indented 6 spaces, which may happen when the
# initializers of a constructor do not fit into a 80 column line.
exception = False
if Match(r' {6}\w', prev_line): # Initializer list?
# We are looking for the opening column of initializer list, which
# should be indented 4 spaces to cause 6 space indentation afterwards.
search_position = linenum-2
while (search_position >= 0
and Match(r' {6}\w', elided[search_position])):
search_position -= 1
exception = (search_position >= 0
and elided[search_position][:5] == ' :')
else:
# Search for the function arguments or an initializer list. We use a
# simple heuristic here: If the line is indented 4 spaces; and we have a
# closing paren, without the opening paren, followed by an opening brace
# or colon (for initializer lists) we assume that it is the last line of
# a function header. If we have a colon indented 4 spaces, it is an
# initializer list.
exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)',
prev_line)
or Match(r' {4}:', prev_line))
if not exception:
error(filename, linenum, 'whitespace/blank_line', 2,
'Redundant blank line at the start of a code block '
'should be deleted.')
# Ignore blank lines at the end of a block in a long if-else
# chain, like this:
# if (condition1) {
# // Something followed by a blank line
#
# } else if (condition2) {
# // Something else
# }
if linenum + 1 < clean_lines.NumLines():
next_line = raw[linenum + 1]
if (next_line
and Match(r'\s*}', next_line)
and next_line.find('} else ') == -1):
error(filename, linenum, 'whitespace/blank_line', 3,
'Redundant blank line at the end of a code block '
'should be deleted.')
matched = Match(r'\s*(public|protected|private):', prev_line)
if matched:
error(filename, linenum, 'whitespace/blank_line', 3,
'Do not leave a blank line after "%s:"' % matched.group(1))
# Next, we complain if there's a comment too near the text
commentpos = line.find('//')
if commentpos != -1:
# Check if the // may be in quotes. If so, ignore it
# Comparisons made explicit for clarity -- pylint: disable=g-explicit-bool-comparison
if (line.count('"', 0, commentpos) -
line.count('\\"', 0, commentpos)) % 2 == 0: # not in quotes
# Allow one space for new scopes, two spaces otherwise:
if (not Match(r'^\s*{ //', line) and
((commentpos >= 1 and
line[commentpos-1] not in string.whitespace) or
(commentpos >= 2 and
line[commentpos-2] not in string.whitespace))):
error(filename, linenum, 'whitespace/comments', 2,
'At least two spaces is best between code and comments')
# There should always be a space between the // and the comment
commentend = commentpos + 2
if commentend < len(line) and not line[commentend] == ' ':
# but some lines are exceptions -- e.g. if they're big
# comment delimiters like:
# //----------------------------------------------------------
# or are an empty C++ style Doxygen comment, like:
# ///
# or C++ style Doxygen comments placed after the variable:
# ///< Header comment
# //!< Header comment
# or they begin with multiple slashes followed by a space:
# //////// Header comment
match = (Search(r'[=/-]{4,}\s*$', line[commentend:]) or
Search(r'^/$', line[commentend:]) or
Search(r'^!< ', line[commentend:]) or
Search(r'^/< ', line[commentend:]) or
Search(r'^/+ ', line[commentend:]))
if not match:
error(filename, linenum, 'whitespace/comments', 4,
'Should have a space between // and comment')
CheckComment(line[commentpos:], filename, linenum, error)
line = clean_lines.elided[linenum] # get rid of comments and strings
# Don't try to do spacing checks for operator methods
line = re.sub(r'operator(==|!=|<|<<|<=|>=|>>|>)\(', 'operator\(', line)
# We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )".
# Otherwise not. Note we only check for non-spaces on *both* sides;
# sometimes people put non-spaces on one side when aligning ='s among
# many lines (not that this is behavior that I approve of...)
if Search(r'[\w.]=[\w.]', line) and not Search(r'\b(if|while) ', line):
error(filename, linenum, 'whitespace/operators', 4,
'Missing spaces around =')
# It's ok not to have spaces around binary operators like + - * /, but if
# there's too little whitespace, we get concerned. It's hard to tell,
# though, so we punt on this one for now. TODO.
# You should always have whitespace around binary operators.
#
# Check <= and >= first to avoid false positives with < and >, then
# check non-include lines for spacing around < and >.
match = Search(r'[^<>=!\s](==|!=|<=|>=)[^<>=!\s]', line)
if match:
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around %s' % match.group(1))
# We allow no-spaces around << when used like this: 10<<20, but
# not otherwise (particularly, not when used as streams)
# Also ignore using ns::operator<<;
match = Search(r'(operator|\S)(?:L|UL|ULL|l|ul|ull)?<<(\S)', line)
if (match and
not (match.group(1).isdigit() and match.group(2).isdigit()) and
not (match.group(1) == 'operator' and match.group(2) == ';')):
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around <<')
elif not Match(r'#.*include', line):
# Avoid false positives on ->
reduced_line = line.replace('->', '')
# Look for < that is not surrounded by spaces. This is only
# triggered if both sides are missing spaces, even though
# technically should should flag if at least one side is missing a
# space. This is done to avoid some false positives with shifts.
match = Search(r'[^\s<]<([^\s=<].*)', reduced_line)
if (match and
not FindNextMatchingAngleBracket(clean_lines, linenum, match.group(1))):
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around <')
# Look for > that is not surrounded by spaces. Similar to the
# above, we only trigger if both sides are missing spaces to avoid
# false positives with shifts.
match = Search(r'^(.*[^\s>])>[^\s=>]', reduced_line)
if (match and
not FindPreviousMatchingAngleBracket(clean_lines, linenum,
match.group(1))):
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around >')
# We allow no-spaces around >> for almost anything. This is because
# C++11 allows ">>" to close nested templates, which accounts for
# most cases when ">>" is not followed by a space.
#
# We still warn on ">>" followed by alpha character, because that is
# likely due to ">>" being used for right shifts, e.g.:
# value >> alpha
#
# When ">>" is used to close templates, the alphanumeric letter that
# follows would be part of an identifier, and there should still be
# a space separating the template type and the identifier.
# type<type<type>> alpha
match = Search(r'>>[a-zA-Z_]', line)
if match:
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around >>')
# There shouldn't be space around unary operators
match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line)
if match:
error(filename, linenum, 'whitespace/operators', 4,
'Extra space for operator %s' % match.group(1))
# A pet peeve of mine: no spaces after an if, while, switch, or for
match = Search(r' (if\(|for\(|while\(|switch\()', line)
if match:
error(filename, linenum, 'whitespace/parens', 5,
'Missing space before ( in %s' % match.group(1))
# For if/for/while/switch, the left and right parens should be
# consistent about how many spaces are inside the parens, and
# there should either be zero or one spaces inside the parens.
# We don't want: "if ( foo)" or "if ( foo )".
# Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed.
match = Search(r'\b(if|for|while|switch)\s*'
r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$',
line)
if match:
if len(match.group(2)) != len(match.group(4)):
if not (match.group(3) == ';' and
len(match.group(2)) == 1 + len(match.group(4)) or
not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)):
error(filename, linenum, 'whitespace/parens', 5,
'Mismatching spaces inside () in %s' % match.group(1))
if len(match.group(2)) not in [0, 1]:
error(filename, linenum, 'whitespace/parens', 5,
'Should have zero or one spaces inside ( and ) in %s' %
match.group(1))
# You should always have a space after a comma (either as fn arg or operator)
#
# This does not apply when the non-space character following the
# comma is another comma, since the only time when that happens is
# for empty macro arguments.
#
# We run this check in two passes: first pass on elided lines to
# verify that lines contain missing whitespaces, second pass on raw
# lines to confirm that those missing whitespaces are not due to
# elided comments.
if Search(r',[^,\s]', line) and Search(r',[^,\s]', raw[linenum]):
error(filename, linenum, 'whitespace/comma', 3,
'Missing space after ,')
# You should always have a space after a semicolon
# except for few corner cases
# TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more
# space after ;
if Search(r';[^\s};\\)/]', line):
error(filename, linenum, 'whitespace/semicolon', 3,
'Missing space after ;')
# Next we will look for issues with function calls.
CheckSpacingForFunctionCall(filename, line, linenum, error)
# Except after an opening paren, or after another opening brace (in case of
# an initializer list, for instance), you should have spaces before your
# braces. And since you should never have braces at the beginning of a line,
# this is an easy test.
match = Match(r'^(.*[^ ({]){', line)
if match:
# Try a bit harder to check for brace initialization. This
# happens in one of the following forms:
# Constructor() : initializer_list_{} { ... }
# Constructor{}.MemberFunction()
# Type variable{};
# FunctionCall(type{}, ...);
# LastArgument(..., type{});
# LOG(INFO) << type{} << " ...";
# map_of_type[{...}] = ...;
#
# We check for the character following the closing brace, and
# silence the warning if it's one of those listed above, i.e.
# "{.;,)<]".
#
# To account for nested initializer list, we allow any number of
# closing braces up to "{;,)<". We can't simply silence the
# warning on first sight of closing brace, because that would
# cause false negatives for things that are not initializer lists.
# Silence this: But not this:
# Outer{ if (...) {
# Inner{...} if (...){ // Missing space before {
# }; }
#
# There is a false negative with this approach if people inserted
# spurious semicolons, e.g. "if (cond){};", but we will catch the
# spurious semicolon with a separate check.
(endline, endlinenum, endpos) = CloseExpression(
clean_lines, linenum, len(match.group(1)))
trailing_text = ''
if endpos > -1:
trailing_text = endline[endpos:]
for offset in xrange(endlinenum + 1,
min(endlinenum + 3, clean_lines.NumLines() - 1)):
trailing_text += clean_lines.elided[offset]
if not Match(r'^[\s}]*[{.;,)<\]]', trailing_text):
error(filename, linenum, 'whitespace/braces', 5,
'Missing space before {')
# Make sure '} else {' has spaces.
if Search(r'}else', line):
error(filename, linenum, 'whitespace/braces', 5,
'Missing space before else')
# You shouldn't have spaces before your brackets, except maybe after
# 'delete []' or 'new char * []'.
if Search(r'\w\s+\[', line) and not Search(r'delete\s+\[', line):
error(filename, linenum, 'whitespace/braces', 5,
'Extra space before [')
# You shouldn't have a space before a semicolon at the end of the line.
# There's a special case for "for" since the style guide allows space before
# the semicolon there.
if Search(r':\s*;\s*$', line):
error(filename, linenum, 'whitespace/semicolon', 5,
'Semicolon defining empty statement. Use {} instead.')
elif Search(r'^\s*;\s*$', line):
error(filename, linenum, 'whitespace/semicolon', 5,
'Line contains only semicolon. If this should be an empty statement, '
'use {} instead.')
elif (Search(r'\s+;\s*$', line) and
not Search(r'\bfor\b', line)):
error(filename, linenum, 'whitespace/semicolon', 5,
'Extra space before last semicolon. If this should be an empty '
'statement, use {} instead.')
# In range-based for, we wanted spaces before and after the colon, but
# not around "::" tokens that might appear.
if (Search('for *\(.*[^:]:[^: ]', line) or
Search('for *\(.*[^: ]:[^:]', line)):
error(filename, linenum, 'whitespace/forcolon', 2,
'Missing space around colon in range-based for loop') | [
"def",
"CheckSpacing",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"nesting_state",
",",
"error",
")",
":",
"# Don't use \"elided\" lines here, otherwise we can't check commented lines.",
"# Don't want to use \"raw\" either, because we don't want to check inside C++11",
... | https://github.com/WeitaoVan/L-GM-loss/blob/598582f0631bac876b3eeb8d6c4cd1d780269e03/scripts/cpp_lint.py#L2643-L2988 | ||
bulletphysics/bullet3 | f0f2a952e146f016096db6f85cf0c44ed75b0b9a | examples/pybullet/gym/pybullet_envs/agents/utility.py | python | initialize_variables | (sess, saver, logdir, checkpoint=None, resume=None) | Initialize or restore variables from a checkpoint if available.
Args:
sess: Session to initialize variables in.
saver: Saver to restore variables.
logdir: Directory to search for checkpoints.
checkpoint: Specify what checkpoint name to use; defaults to most recent.
resume: Whether to expect recovering a checkpoint or starting a new run.
Raises:
ValueError: If resume expected but no log directory specified.
RuntimeError: If no resume expected but a checkpoint was found. | Initialize or restore variables from a checkpoint if available. | [
"Initialize",
"or",
"restore",
"variables",
"from",
"a",
"checkpoint",
"if",
"available",
"."
] | def initialize_variables(sess, saver, logdir, checkpoint=None, resume=None):
"""Initialize or restore variables from a checkpoint if available.
Args:
sess: Session to initialize variables in.
saver: Saver to restore variables.
logdir: Directory to search for checkpoints.
checkpoint: Specify what checkpoint name to use; defaults to most recent.
resume: Whether to expect recovering a checkpoint or starting a new run.
Raises:
ValueError: If resume expected but no log directory specified.
RuntimeError: If no resume expected but a checkpoint was found.
"""
sess.run(tf.group(tf.local_variables_initializer(), tf.global_variables_initializer()))
if resume and not (logdir or checkpoint):
raise ValueError('Need to specify logdir to resume a checkpoint.')
if logdir:
state = tf.train.get_checkpoint_state(logdir)
if checkpoint:
checkpoint = os.path.join(logdir, checkpoint)
if not checkpoint and state and state.model_checkpoint_path:
checkpoint = state.model_checkpoint_path
if checkpoint and resume is False:
message = 'Found unexpected checkpoint when starting a new run.'
raise RuntimeError(message)
if checkpoint:
saver.restore(sess, checkpoint) | [
"def",
"initialize_variables",
"(",
"sess",
",",
"saver",
",",
"logdir",
",",
"checkpoint",
"=",
"None",
",",
"resume",
"=",
"None",
")",
":",
"sess",
".",
"run",
"(",
"tf",
".",
"group",
"(",
"tf",
".",
"local_variables_initializer",
"(",
")",
",",
"t... | https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/agents/utility.py#L99-L126 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/dist.py | python | check_requirements | (dist, attr, value) | Verify that install_requires is a valid requirements list | Verify that install_requires is a valid requirements list | [
"Verify",
"that",
"install_requires",
"is",
"a",
"valid",
"requirements",
"list"
] | def check_requirements(dist, attr, value):
"""Verify that install_requires is a valid requirements list"""
try:
list(pkg_resources.parse_requirements(value))
if isinstance(value, (dict, set)):
raise TypeError("Unordered types are not allowed")
except (TypeError, ValueError) as error:
tmpl = (
"{attr!r} must be a string or list of strings "
"containing valid project/version requirement specifiers; {error}"
)
raise DistutilsSetupError(tmpl.format(attr=attr, error=error)) | [
"def",
"check_requirements",
"(",
"dist",
",",
"attr",
",",
"value",
")",
":",
"try",
":",
"list",
"(",
"pkg_resources",
".",
"parse_requirements",
"(",
"value",
")",
")",
"if",
"isinstance",
"(",
"value",
",",
"(",
"dict",
",",
"set",
")",
")",
":",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/dist.py#L272-L283 | ||
VowpalWabbit/vowpal_wabbit | 866b8fa88ff85a957c7eb72065ea44518b9ba416 | python/vowpalwabbit/dftovw.py | python | Feature.__init__ | (
self,
value: Hashable,
rename_feature: Optional[str] = None,
as_type: Optional[str] = None,
) | Initialize a Feature instance.
Args:
value: The column name with the value of the feature.
rename_feature: The name to use instead of the default (which is the column name defined in the value argument).
as_type: Enforce a specific type ('numerical' or 'categorical') | Initialize a Feature instance. | [
"Initialize",
"a",
"Feature",
"instance",
"."
] | def __init__(
self,
value: Hashable,
rename_feature: Optional[str] = None,
as_type: Optional[str] = None,
):
"""
Initialize a Feature instance.
Args:
value: The column name with the value of the feature.
rename_feature: The name to use instead of the default (which is the column name defined in the value argument).
as_type: Enforce a specific type ('numerical' or 'categorical')
"""
self.value = value
self.name = _Col.make_valid_name(
rename_feature if rename_feature is not None else self.value.colname
)
if as_type is not None and as_type not in ("numerical", "categorical"):
raise ValueError(
"Argument 'as_type' can either be 'numerical' or 'categorical'"
)
else:
self.as_type = as_type | [
"def",
"__init__",
"(",
"self",
",",
"value",
":",
"Hashable",
",",
"rename_feature",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"as_type",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
")",
":",
"self",
".",
"value",
"=",
"value",
"... | https://github.com/VowpalWabbit/vowpal_wabbit/blob/866b8fa88ff85a957c7eb72065ea44518b9ba416/python/vowpalwabbit/dftovw.py#L365-L388 | ||
OpenGenus/quark | 225ad96efdfcc66cb6584a756c17eb3871e6eb62 | code/code/mathematical_algorithms/src/exponentiation_power/exponentiation_by_squaring/exponentiation_by_squaring.py | python | fast_power | (base, power) | return result | Returns the result of a^b i.e. a**b
We assume that a >= 1 and b >= 0 | Returns the result of a^b i.e. a**b
We assume that a >= 1 and b >= 0 | [
"Returns",
"the",
"result",
"of",
"a^b",
"i",
".",
"e",
".",
"a",
"**",
"b",
"We",
"assume",
"that",
"a",
">",
"=",
"1",
"and",
"b",
">",
"=",
"0"
] | def fast_power(base, power):
"""
Returns the result of a^b i.e. a**b
We assume that a >= 1 and b >= 0
"""
result = 1
while power > 0:
# If power is odd
if power % 2 == 1:
result = (result * base) % MOD
# Divide the power by 2
power = int(power / 2)
# Multiply base to itself
base = (base * base) % MOD
return result | [
"def",
"fast_power",
"(",
"base",
",",
"power",
")",
":",
"result",
"=",
"1",
"while",
"power",
">",
"0",
":",
"# If power is odd",
"if",
"power",
"%",
"2",
"==",
"1",
":",
"result",
"=",
"(",
"result",
"*",
"base",
")",
"%",
"MOD",
"# Divide the pow... | https://github.com/OpenGenus/quark/blob/225ad96efdfcc66cb6584a756c17eb3871e6eb62/code/code/mathematical_algorithms/src/exponentiation_power/exponentiation_by_squaring/exponentiation_by_squaring.py#L4-L21 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/calendar.py | python | CalendarCtrlBase.SetHoliday | (*args, **kwargs) | return _calendar.CalendarCtrlBase_SetHoliday(*args, **kwargs) | SetHoliday(self, size_t day)
Marks the specified day as being a holiday in the current month. | SetHoliday(self, size_t day) | [
"SetHoliday",
"(",
"self",
"size_t",
"day",
")"
] | def SetHoliday(*args, **kwargs):
"""
SetHoliday(self, size_t day)
Marks the specified day as being a holiday in the current month.
"""
return _calendar.CalendarCtrlBase_SetHoliday(*args, **kwargs) | [
"def",
"SetHoliday",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_calendar",
".",
"CalendarCtrlBase_SetHoliday",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/calendar.py#L387-L393 | |
lballabio/quantlib-old | 136336947ed4fea9ecc1da6edad188700e821739 | gensrc/gensrc/enumerations/enumeratedtypes.py | python | EnumeratedTypeGroup.postSerialize | (self) | Invoke any post serialization behavior that may be required. | Invoke any post serialization behavior that may be required. | [
"Invoke",
"any",
"post",
"serialization",
"behavior",
"that",
"may",
"be",
"required",
"."
] | def postSerialize(self):
"""Invoke any post serialization behavior that may be required."""
for enumeratedType in self.enumeratedTypes_.values():
enumeratedType.setType(self.type_)
enumeratedType.setConstructor(self.constructor_) | [
"def",
"postSerialize",
"(",
"self",
")",
":",
"for",
"enumeratedType",
"in",
"self",
".",
"enumeratedTypes_",
".",
"values",
"(",
")",
":",
"enumeratedType",
".",
"setType",
"(",
"self",
".",
"type_",
")",
"enumeratedType",
".",
"setConstructor",
"(",
"self... | https://github.com/lballabio/quantlib-old/blob/136336947ed4fea9ecc1da6edad188700e821739/gensrc/gensrc/enumerations/enumeratedtypes.py#L117-L121 | ||
makefile/frcnn | 8d9b9ebf8be8315ba2f374d460121b0adf1df29c | scripts/cpp_lint.py | python | FindNextMatchingAngleBracket | (clean_lines, linenum, init_suffix) | return True | Find the corresponding > to close a template.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: Current line number.
init_suffix: Remainder of the current line after the initial <.
Returns:
True if a matching bracket exists. | Find the corresponding > to close a template. | [
"Find",
"the",
"corresponding",
">",
"to",
"close",
"a",
"template",
"."
] | def FindNextMatchingAngleBracket(clean_lines, linenum, init_suffix):
"""Find the corresponding > to close a template.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: Current line number.
init_suffix: Remainder of the current line after the initial <.
Returns:
True if a matching bracket exists.
"""
line = init_suffix
nesting_stack = ['<']
while True:
# Find the next operator that can tell us whether < is used as an
# opening bracket or as a less-than operator. We only want to
# warn on the latter case.
#
# We could also check all other operators and terminate the search
# early, e.g. if we got something like this "a<b+c", the "<" is
# most likely a less-than operator, but then we will get false
# positives for default arguments and other template expressions.
match = Search(r'^[^<>(),;\[\]]*([<>(),;\[\]])(.*)$', line)
if match:
# Found an operator, update nesting stack
operator = match.group(1)
line = match.group(2)
if nesting_stack[-1] == '<':
# Expecting closing angle bracket
if operator in ('<', '(', '['):
nesting_stack.append(operator)
elif operator == '>':
nesting_stack.pop()
if not nesting_stack:
# Found matching angle bracket
return True
elif operator == ',':
# Got a comma after a bracket, this is most likely a template
# argument. We have not seen a closing angle bracket yet, but
# it's probably a few lines later if we look for it, so just
# return early here.
return True
else:
# Got some other operator.
return False
else:
# Expecting closing parenthesis or closing bracket
if operator in ('<', '(', '['):
nesting_stack.append(operator)
elif operator in (')', ']'):
# We don't bother checking for matching () or []. If we got
# something like (] or [), it would have been a syntax error.
nesting_stack.pop()
else:
# Scan the next line
linenum += 1
if linenum >= len(clean_lines.elided):
break
line = clean_lines.elided[linenum]
# Exhausted all remaining lines and still no matching angle bracket.
# Most likely the input was incomplete, otherwise we should have
# seen a semicolon and returned early.
return True | [
"def",
"FindNextMatchingAngleBracket",
"(",
"clean_lines",
",",
"linenum",
",",
"init_suffix",
")",
":",
"line",
"=",
"init_suffix",
"nesting_stack",
"=",
"[",
"'<'",
"]",
"while",
"True",
":",
"# Find the next operator that can tell us whether < is used as an",
"# openin... | https://github.com/makefile/frcnn/blob/8d9b9ebf8be8315ba2f374d460121b0adf1df29c/scripts/cpp_lint.py#L2517-L2583 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/urllib3/contrib/securetransport.py | python | _write_callback | (connection_id, data_buffer, data_length_pointer) | SecureTransport write callback. This is called by ST to request that data
actually be sent on the network. | SecureTransport write callback. This is called by ST to request that data
actually be sent on the network. | [
"SecureTransport",
"write",
"callback",
".",
"This",
"is",
"called",
"by",
"ST",
"to",
"request",
"that",
"data",
"actually",
"be",
"sent",
"on",
"the",
"network",
"."
] | def _write_callback(connection_id, data_buffer, data_length_pointer):
"""
SecureTransport write callback. This is called by ST to request that data
actually be sent on the network.
"""
wrapped_socket = None
try:
wrapped_socket = _connection_refs.get(connection_id)
if wrapped_socket is None:
return SecurityConst.errSSLInternal
base_socket = wrapped_socket.socket
bytes_to_write = data_length_pointer[0]
data = ctypes.string_at(data_buffer, bytes_to_write)
timeout = wrapped_socket.gettimeout()
error = None
sent = 0
try:
while sent < bytes_to_write:
if timeout is None or timeout >= 0:
writables = util.wait_for_write([base_socket], timeout)
if not writables:
raise socket.error(errno.EAGAIN, 'timed out')
chunk_sent = base_socket.send(data)
sent += chunk_sent
# This has some needless copying here, but I'm not sure there's
# much value in optimising this data path.
data = data[chunk_sent:]
except (socket.error) as e:
error = e.errno
if error is not None and error != errno.EAGAIN:
if error == errno.ECONNRESET:
return SecurityConst.errSSLClosedAbort
raise
data_length_pointer[0] = sent
if sent != bytes_to_write:
return SecurityConst.errSSLWouldBlock
return 0
except Exception as e:
if wrapped_socket is not None:
wrapped_socket._exception = e
return SecurityConst.errSSLInternal | [
"def",
"_write_callback",
"(",
"connection_id",
",",
"data_buffer",
",",
"data_length_pointer",
")",
":",
"wrapped_socket",
"=",
"None",
"try",
":",
"wrapped_socket",
"=",
"_connection_refs",
".",
"get",
"(",
"connection_id",
")",
"if",
"wrapped_socket",
"is",
"No... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/urllib3/contrib/securetransport.py#L238-L285 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/parenmatch.py | python | ParenMatch.create_tag_expression | (self, indices) | Highlight the entire expression | Highlight the entire expression | [
"Highlight",
"the",
"entire",
"expression"
] | def create_tag_expression(self, indices):
"""Highlight the entire expression"""
if self.text.get(indices[1]) in (')', ']', '}'):
rightindex = indices[1]+"+1c"
else:
rightindex = indices[1]
self.text.tag_add("paren", indices[0], rightindex)
self.text.tag_config("paren", self.HILITE_CONFIG) | [
"def",
"create_tag_expression",
"(",
"self",
",",
"indices",
")",
":",
"if",
"self",
".",
"text",
".",
"get",
"(",
"indices",
"[",
"1",
"]",
")",
"in",
"(",
"')'",
",",
"']'",
",",
"'}'",
")",
":",
"rightindex",
"=",
"indices",
"[",
"1",
"]",
"+"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/parenmatch.py#L134-L141 | ||
moflow/moflow | 2dfb27c799c90c6caf1477508eca3eec616ef7d2 | bap/libtracewrap/libtrace/protobuf/python/google/protobuf/internal/containers.py | python | RepeatedCompositeFieldContainer.MergeFrom | (self, other) | Appends the contents of another repeated field of the same type to this
one, copying each individual message. | Appends the contents of another repeated field of the same type to this
one, copying each individual message. | [
"Appends",
"the",
"contents",
"of",
"another",
"repeated",
"field",
"of",
"the",
"same",
"type",
"to",
"this",
"one",
"copying",
"each",
"individual",
"message",
"."
] | def MergeFrom(self, other):
"""Appends the contents of another repeated field of the same type to this
one, copying each individual message.
"""
self.extend(other._values) | [
"def",
"MergeFrom",
"(",
"self",
",",
"other",
")",
":",
"self",
".",
"extend",
"(",
"other",
".",
"_values",
")"
] | https://github.com/moflow/moflow/blob/2dfb27c799c90c6caf1477508eca3eec616ef7d2/bap/libtracewrap/libtrace/protobuf/python/google/protobuf/internal/containers.py#L237-L241 | ||
scribusproject/scribus | 41ec7c775a060912cf251682a8b1437f753f80f4 | scribus/plugins/scripter/python/scripter_runtime.py | python | mark_keep | () | mark every child of Scripter.collector to keep | mark every child of Scripter.collector to keep | [
"mark",
"every",
"child",
"of",
"Scripter",
".",
"collector",
"to",
"keep"
] | def mark_keep():
"""
mark every child of Scripter.collector to keep
"""
for child in Scripter.collector.children():
if hasattr(child, "qt"): child = child.qt
child.setProperty("keep", QVariant(True)) | [
"def",
"mark_keep",
"(",
")",
":",
"for",
"child",
"in",
"Scripter",
".",
"collector",
".",
"children",
"(",
")",
":",
"if",
"hasattr",
"(",
"child",
",",
"\"qt\"",
")",
":",
"child",
"=",
"child",
".",
"qt",
"child",
".",
"setProperty",
"(",
"\"keep... | https://github.com/scribusproject/scribus/blob/41ec7c775a060912cf251682a8b1437f753f80f4/scribus/plugins/scripter/python/scripter_runtime.py#L227-L233 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/posixpath.py | python | relpath | (path, start=None) | Return a relative version of a path | Return a relative version of a path | [
"Return",
"a",
"relative",
"version",
"of",
"a",
"path"
] | def relpath(path, start=None):
"""Return a relative version of a path"""
if not path:
raise ValueError("no path specified")
path = os.fspath(path)
if isinstance(path, bytes):
curdir = b'.'
sep = b'/'
pardir = b'..'
else:
curdir = '.'
sep = '/'
pardir = '..'
if start is None:
start = curdir
else:
start = os.fspath(start)
try:
start_list = [x for x in abspath(start).split(sep) if x]
path_list = [x for x in abspath(path).split(sep) if x]
# Work out how much of the filepath is shared by start and path.
i = len(commonprefix([start_list, path_list]))
rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
if not rel_list:
return curdir
return join(*rel_list)
except (TypeError, AttributeError, BytesWarning, DeprecationWarning):
genericpath._check_arg_types('relpath', path, start)
raise | [
"def",
"relpath",
"(",
"path",
",",
"start",
"=",
"None",
")",
":",
"if",
"not",
"path",
":",
"raise",
"ValueError",
"(",
"\"no path specified\"",
")",
"path",
"=",
"os",
".",
"fspath",
"(",
"path",
")",
"if",
"isinstance",
"(",
"path",
",",
"bytes",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/posixpath.py#L450-L483 | ||
epam/Indigo | 30e40b4b1eb9bae0207435a26cfcb81ddcc42be1 | api/python/indigo/__init__.py | python | IndigoObject.hasZCoord | (self) | return bool(
self.dispatcher._checkResult(Indigo._lib.indigoHasZCoord(self.id))
) | Molecule method returns True if the structure contains Z coordinate
Returns:
bool: True if contains Z coordinate, False otherwise | Molecule method returns True if the structure contains Z coordinate | [
"Molecule",
"method",
"returns",
"True",
"if",
"the",
"structure",
"contains",
"Z",
"coordinate"
] | def hasZCoord(self):
"""Molecule method returns True if the structure contains Z coordinate
Returns:
bool: True if contains Z coordinate, False otherwise
"""
self.dispatcher._setSessionId()
return bool(
self.dispatcher._checkResult(Indigo._lib.indigoHasZCoord(self.id))
) | [
"def",
"hasZCoord",
"(",
"self",
")",
":",
"self",
".",
"dispatcher",
".",
"_setSessionId",
"(",
")",
"return",
"bool",
"(",
"self",
".",
"dispatcher",
".",
"_checkResult",
"(",
"Indigo",
".",
"_lib",
".",
"indigoHasZCoord",
"(",
"self",
".",
"id",
")",
... | https://github.com/epam/Indigo/blob/30e40b4b1eb9bae0207435a26cfcb81ddcc42be1/api/python/indigo/__init__.py#L3219-L3228 | |
Yelp/MOE | 5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c | moe/optimal_learning/python/cpp_wrappers/domain.py | python | TensorProductDomain.dim | (self) | return len(self._domain_bounds) | Return the number of spatial dimensions. | Return the number of spatial dimensions. | [
"Return",
"the",
"number",
"of",
"spatial",
"dimensions",
"."
] | def dim(self):
"""Return the number of spatial dimensions."""
return len(self._domain_bounds) | [
"def",
"dim",
"(",
"self",
")",
":",
"return",
"len",
"(",
"self",
".",
"_domain_bounds",
")"
] | https://github.com/Yelp/MOE/blob/5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c/moe/optimal_learning/python/cpp_wrappers/domain.py#L38-L40 | |
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | .github/github_org_control/github_api.py | python | GithubOrgApi.is_org_user | (self, user) | return False | Checks that user is a member of GitHub organization | Checks that user is a member of GitHub organization | [
"Checks",
"that",
"user",
"is",
"a",
"member",
"of",
"GitHub",
"organization"
] | def is_org_user(self, user):
"""Checks that user is a member of GitHub organization"""
if is_valid_user(user):
# user.get_organization_membership(self.github_org) doesn't work with org members
# permissions, GITHUB_TOKEN must be org owner now
return self.github_org.has_in_members(user)
return False | [
"def",
"is_org_user",
"(",
"self",
",",
"user",
")",
":",
"if",
"is_valid_user",
"(",
"user",
")",
":",
"# user.get_organization_membership(self.github_org) doesn't work with org members",
"# permissions, GITHUB_TOKEN must be org owner now",
"return",
"self",
".",
"github_org",... | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/.github/github_org_control/github_api.py#L137-L143 | |
SequoiaDB/SequoiaDB | 2894ed7e5bd6fe57330afc900cf76d0ff0df9f64 | tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py | python | uCSIsTags | (code) | return ret | Check whether the character is part of Tags UCS Block | Check whether the character is part of Tags UCS Block | [
"Check",
"whether",
"the",
"character",
"is",
"part",
"of",
"Tags",
"UCS",
"Block"
] | def uCSIsTags(code):
"""Check whether the character is part of Tags UCS Block """
ret = libxml2mod.xmlUCSIsTags(code)
return ret | [
"def",
"uCSIsTags",
"(",
"code",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlUCSIsTags",
"(",
"code",
")",
"return",
"ret"
] | https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L2867-L2870 | |
apache/mesos | 97d9a4063332aae3825d78de71611657e05cf5e2 | support/cpplint.py | python | CheckForNewlineAtEOF | (filename, lines, error) | Logs an error if there is no newline char at the end of the file.
Args:
filename: The name of the current file.
lines: An array of strings, each representing a line of the file.
error: The function to call with any errors found. | Logs an error if there is no newline char at the end of the file. | [
"Logs",
"an",
"error",
"if",
"there",
"is",
"no",
"newline",
"char",
"at",
"the",
"end",
"of",
"the",
"file",
"."
] | def CheckForNewlineAtEOF(filename, lines, error):
"""Logs an error if there is no newline char at the end of the file.
Args:
filename: The name of the current file.
lines: An array of strings, each representing a line of the file.
error: The function to call with any errors found.
"""
# The array lines() was created by adding two newlines to the
# original file (go figure), then splitting on \n.
# To verify that the file ends in \n, we just have to make sure the
# last-but-two element of lines() exists and is empty.
if len(lines) < 3 or lines[-2]:
error(filename, len(lines) - 2, 'whitespace/ending_newline', 5,
'Could not find a newline character at the end of the file.') | [
"def",
"CheckForNewlineAtEOF",
"(",
"filename",
",",
"lines",
",",
"error",
")",
":",
"# The array lines() was created by adding two newlines to the",
"# original file (go figure), then splitting on \\n.",
"# To verify that the file ends in \\n, we just have to make sure the",
"# last-but-... | https://github.com/apache/mesos/blob/97d9a4063332aae3825d78de71611657e05cf5e2/support/cpplint.py#L2038-L2053 | ||
tensorflow/deepmath | b5b721f54de1d5d6a02d78f5da5995237f9995f9 | deepmath/deephol/embedding_store.py | python | TheoremEmbeddingStore.get_thm_scores_for_preceding_thms | (self,
goal_embedding,
thm_index: Optional[int] = None,
tactic_id: Optional[int] = None) | return self.predictor.batch_thm_scores(goal_embedding, thm_embeddings,
tactic_id) | Get the predicted pairwise scores in a numpy array.
For the given goal embedding (which is either the embedding of the goal term
or the embedding of the current proof state), get all the theorem scores
that preceed the given theorem in theorem list and all the local
assumptions stored in this store. The theorem parameter thm must be either
None or be in the theorem list, otherwise an assertion will fail.
Args:
goal_embedding: 1D embedding with the embedding of the given goal.
thm_index: Theorem index in the list of theorems in this store or None, in
which case all of the theorems are scored.
tactic_id: Optionally tactic that the theorem parameters will be used in.
Returns:
A 1D numpy array with the same length as the sum of the length
of preceding thms and assumptions. It is the concatenated array of the
scores for the preceding thms and assumptions in the same order given as
in the those arrays: first the theorem scores, then the assumption scores. | Get the predicted pairwise scores in a numpy array. | [
"Get",
"the",
"predicted",
"pairwise",
"scores",
"in",
"a",
"numpy",
"array",
"."
] | def get_thm_scores_for_preceding_thms(self,
goal_embedding,
thm_index: Optional[int] = None,
tactic_id: Optional[int] = None):
"""Get the predicted pairwise scores in a numpy array.
For the given goal embedding (which is either the embedding of the goal term
or the embedding of the current proof state), get all the theorem scores
that preceed the given theorem in theorem list and all the local
assumptions stored in this store. The theorem parameter thm must be either
None or be in the theorem list, otherwise an assertion will fail.
Args:
goal_embedding: 1D embedding with the embedding of the given goal.
thm_index: Theorem index in the list of theorems in this store or None, in
which case all of the theorems are scored.
tactic_id: Optionally tactic that the theorem parameters will be used in.
Returns:
A 1D numpy array with the same length as the sum of the length
of preceding thms and assumptions. It is the concatenated array of the
scores for the preceding thms and assumptions in the same order given as
in the those arrays: first the theorem scores, then the assumption scores.
"""
if thm_index is None:
thm_index = self.thm_embeddings.shape[0]
else:
assert thm_index <= self.thm_embeddings.shape[0]
assert thm_index >= 0
assert not self.assumptions
assert not self.assumption_embeddings
thm_embeddings = self.thm_embeddings[:thm_index]
assert len(thm_embeddings) == thm_index + len(self.assumptions)
return self.predictor.batch_thm_scores(goal_embedding, thm_embeddings,
tactic_id) | [
"def",
"get_thm_scores_for_preceding_thms",
"(",
"self",
",",
"goal_embedding",
",",
"thm_index",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"tactic_id",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
")",
":",
"if",
"thm_index",
"is",
"None",
":"... | https://github.com/tensorflow/deepmath/blob/b5b721f54de1d5d6a02d78f5da5995237f9995f9/deepmath/deephol/embedding_store.py#L102-L136 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_controls.py | python | ToolBarToolBase.SetDropdownMenu | (*args, **kwargs) | return _controls_.ToolBarToolBase_SetDropdownMenu(*args, **kwargs) | SetDropdownMenu(self, Menu menu) | SetDropdownMenu(self, Menu menu) | [
"SetDropdownMenu",
"(",
"self",
"Menu",
"menu",
")"
] | def SetDropdownMenu(*args, **kwargs):
"""SetDropdownMenu(self, Menu menu)"""
return _controls_.ToolBarToolBase_SetDropdownMenu(*args, **kwargs) | [
"def",
"SetDropdownMenu",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"ToolBarToolBase_SetDropdownMenu",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L3553-L3555 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.