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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/build/android/gyp/javac_output_processor.py | python | JavacOutputProcessor.Process | (self, lines) | return (self._ApplyColors(l) for l in lines) | Processes javac output.
- Applies colors to output.
- Suggests GN dep to add for 'unresolved symbol in Java import' errors. | Processes javac output. | [
"Processes",
"javac",
"output",
"."
] | def Process(self, lines):
""" Processes javac output.
- Applies colors to output.
- Suggests GN dep to add for 'unresolved symbol in Java import' errors.
"""
lines = self._ElaborateLinesForUnknownSymbol(iter(lines))
return (self._ApplyColors(l) for l in lines) | [
"def",
"Process",
"(",
"self",
",",
"lines",
")",
":",
"lines",
"=",
"self",
".",
"_ElaborateLinesForUnknownSymbol",
"(",
"iter",
"(",
"lines",
")",
")",
"return",
"(",
"self",
".",
"_ApplyColors",
"(",
"l",
")",
"for",
"l",
"in",
"lines",
")"
] | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/android/gyp/javac_output_processor.py#L76-L83 | |
WagicProject/wagic | 8e551bb287668c285a41206cf10f1a3197887ca2 | projects/mtg/tools/build/lib/pyjavaproperties-0.6/pyjavaproperties.py | python | Properties.getProperty | (self, key) | return self._props.get(key,'') | Return a property for the given key | Return a property for the given key | [
"Return",
"a",
"property",
"for",
"the",
"given",
"key"
] | def getProperty(self, key):
""" Return a property for the given key """
return self._props.get(key,'') | [
"def",
"getProperty",
"(",
"self",
",",
"key",
")",
":",
"return",
"self",
".",
"_props",
".",
"get",
"(",
"key",
",",
"''",
")"
] | https://github.com/WagicProject/wagic/blob/8e551bb287668c285a41206cf10f1a3197887ca2/projects/mtg/tools/build/lib/pyjavaproperties-0.6/pyjavaproperties.py#L249-L252 | |
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/tools/gyp/pylib/gyp/win_tool.py | python | WinTool.ExecLinkWrapper | (self, arch, use_separate_mspdbsrv, *args) | return link.returncode | Filter diagnostic output from link that looks like:
' Creating library ui.dll.lib and object ui.dll.exp'
This happens when there are exports from the dll or exe. | Filter diagnostic output from link that looks like:
' Creating library ui.dll.lib and object ui.dll.exp'
This happens when there are exports from the dll or exe. | [
"Filter",
"diagnostic",
"output",
"from",
"link",
"that",
"looks",
"like",
":",
"Creating",
"library",
"ui",
".",
"dll",
".",
"lib",
"and",
"object",
"ui",
".",
"dll",
".",
"exp",
"This",
"happens",
"when",
"there",
"are",
"exports",
"from",
"the",
"dll",
"or",
"exe",
"."
] | def ExecLinkWrapper(self, arch, use_separate_mspdbsrv, *args):
"""Filter diagnostic output from link that looks like:
' Creating library ui.dll.lib and object ui.dll.exp'
This happens when there are exports from the dll or exe.
"""
env = self._GetEnv(arch)
if use_separate_mspdbsrv == "True":
self._UseSeparateMspdbsrv(env, args)
if sys.platform == "win32":
args = list(args) # *args is a tuple by default, which is read-only.
args[0] = args[0].replace("/", "\\")
# https://docs.python.org/2/library/subprocess.html:
# "On Unix with shell=True [...] if args is a sequence, the first item
# specifies the command string, and any additional items will be treated as
# additional arguments to the shell itself. That is to say, Popen does the
# equivalent of:
# Popen(['/bin/sh', '-c', args[0], args[1], ...])"
# For that reason, since going through the shell doesn't seem necessary on
# non-Windows don't do that there.
link = subprocess.Popen(
args,
shell=sys.platform == "win32",
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
out = link.communicate()[0].decode("utf-8")
for line in out.splitlines():
if (
not line.startswith(" Creating library ")
and not line.startswith("Generating code")
and not line.startswith("Finished generating code")
):
print(line)
return link.returncode | [
"def",
"ExecLinkWrapper",
"(",
"self",
",",
"arch",
",",
"use_separate_mspdbsrv",
",",
"*",
"args",
")",
":",
"env",
"=",
"self",
".",
"_GetEnv",
"(",
"arch",
")",
"if",
"use_separate_mspdbsrv",
"==",
"\"True\"",
":",
"self",
".",
"_UseSeparateMspdbsrv",
"(",
"env",
",",
"args",
")",
"if",
"sys",
".",
"platform",
"==",
"\"win32\"",
":",
"args",
"=",
"list",
"(",
"args",
")",
"# *args is a tuple by default, which is read-only.",
"args",
"[",
"0",
"]",
"=",
"args",
"[",
"0",
"]",
".",
"replace",
"(",
"\"/\"",
",",
"\"\\\\\"",
")",
"# https://docs.python.org/2/library/subprocess.html:",
"# \"On Unix with shell=True [...] if args is a sequence, the first item",
"# specifies the command string, and any additional items will be treated as",
"# additional arguments to the shell itself. That is to say, Popen does the",
"# equivalent of:",
"# Popen(['/bin/sh', '-c', args[0], args[1], ...])\"",
"# For that reason, since going through the shell doesn't seem necessary on",
"# non-Windows don't do that there.",
"link",
"=",
"subprocess",
".",
"Popen",
"(",
"args",
",",
"shell",
"=",
"sys",
".",
"platform",
"==",
"\"win32\"",
",",
"env",
"=",
"env",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
",",
")",
"out",
"=",
"link",
".",
"communicate",
"(",
")",
"[",
"0",
"]",
".",
"decode",
"(",
"\"utf-8\"",
")",
"for",
"line",
"in",
"out",
".",
"splitlines",
"(",
")",
":",
"if",
"(",
"not",
"line",
".",
"startswith",
"(",
"\" Creating library \"",
")",
"and",
"not",
"line",
".",
"startswith",
"(",
"\"Generating code\"",
")",
"and",
"not",
"line",
".",
"startswith",
"(",
"\"Finished generating code\"",
")",
")",
":",
"print",
"(",
"line",
")",
"return",
"link",
".",
"returncode"
] | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/gyp/pylib/gyp/win_tool.py#L116-L150 | |
google/llvm-propeller | 45c226984fe8377ebfb2ad7713c680d652ba678d | lldb/third_party/Python/module/pexpect-4.6/pexpect/screen.py | python | screen.pretty | (self) | return top_bot + u'\n'.join([u'|'+line+u'|' for line in unicode(self).split(u'\n')]) + u'\n' + top_bot | This returns a copy of the screen as a unicode string with an ASCII
text box around the screen border. This is similar to
__str__/__unicode__ except that it adds a box. | This returns a copy of the screen as a unicode string with an ASCII
text box around the screen border. This is similar to
__str__/__unicode__ except that it adds a box. | [
"This",
"returns",
"a",
"copy",
"of",
"the",
"screen",
"as",
"a",
"unicode",
"string",
"with",
"an",
"ASCII",
"text",
"box",
"around",
"the",
"screen",
"border",
".",
"This",
"is",
"similar",
"to",
"__str__",
"/",
"__unicode__",
"except",
"that",
"it",
"adds",
"a",
"box",
"."
] | def pretty (self):
'''This returns a copy of the screen as a unicode string with an ASCII
text box around the screen border. This is similar to
__str__/__unicode__ except that it adds a box.'''
top_bot = u'+' + u'-'*self.cols + u'+\n'
return top_bot + u'\n'.join([u'|'+line+u'|' for line in unicode(self).split(u'\n')]) + u'\n' + top_bot | [
"def",
"pretty",
"(",
"self",
")",
":",
"top_bot",
"=",
"u'+'",
"+",
"u'-'",
"*",
"self",
".",
"cols",
"+",
"u'+\\n'",
"return",
"top_bot",
"+",
"u'\\n'",
".",
"join",
"(",
"[",
"u'|'",
"+",
"line",
"+",
"u'|'",
"for",
"line",
"in",
"unicode",
"(",
"self",
")",
".",
"split",
"(",
"u'\\n'",
")",
"]",
")",
"+",
"u'\\n'",
"+",
"top_bot"
] | https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/lldb/third_party/Python/module/pexpect-4.6/pexpect/screen.py#L138-L144 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/decimal.py | python | Context.max | (self, a, b) | return a.max(b, context=self) | max compares two values numerically and returns the maximum.
If either operand is a NaN then the general rules apply.
Otherwise, the operands are compared as though by the compare
operation. If they are numerically equal then the left-hand operand
is chosen as the result. Otherwise the maximum (closer to positive
infinity) of the two operands is chosen as the result.
>>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Decimal('3')
>>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Decimal('3')
>>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Decimal('1')
>>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
Decimal('7')
>>> ExtendedContext.max(1, 2)
Decimal('2')
>>> ExtendedContext.max(Decimal(1), 2)
Decimal('2')
>>> ExtendedContext.max(1, Decimal(2))
Decimal('2') | max compares two values numerically and returns the maximum. | [
"max",
"compares",
"two",
"values",
"numerically",
"and",
"returns",
"the",
"maximum",
"."
] | def max(self, a, b):
"""max compares two values numerically and returns the maximum.
If either operand is a NaN then the general rules apply.
Otherwise, the operands are compared as though by the compare
operation. If they are numerically equal then the left-hand operand
is chosen as the result. Otherwise the maximum (closer to positive
infinity) of the two operands is chosen as the result.
>>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Decimal('3')
>>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Decimal('3')
>>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Decimal('1')
>>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
Decimal('7')
>>> ExtendedContext.max(1, 2)
Decimal('2')
>>> ExtendedContext.max(Decimal(1), 2)
Decimal('2')
>>> ExtendedContext.max(1, Decimal(2))
Decimal('2')
"""
a = _convert_other(a, raiseit=True)
return a.max(b, context=self) | [
"def",
"max",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"a",
"=",
"_convert_other",
"(",
"a",
",",
"raiseit",
"=",
"True",
")",
"return",
"a",
".",
"max",
"(",
"b",
",",
"context",
"=",
"self",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/decimal.py#L4662-L4687 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/ops/math_ops.py | python | _SparseSegmentReductionGradShape | (op) | return [tensor_shape.TensorShape([dim0]).concatenate(input_shape[1:])] | Shape function for the SparseSegment[Mean|SqrtN]Grad ops. | Shape function for the SparseSegment[Mean|SqrtN]Grad ops. | [
"Shape",
"function",
"for",
"the",
"SparseSegment",
"[",
"Mean|SqrtN",
"]",
"Grad",
"ops",
"."
] | def _SparseSegmentReductionGradShape(op):
"""Shape function for the SparseSegment[Mean|SqrtN]Grad ops."""
input_shape = op.inputs[0].get_shape()
indices_shape = op.inputs[1].get_shape().with_rank(1)
unused_segment_ids_shape = op.inputs[2].get_shape().merge_with(indices_shape)
unused_output_dim0_shape = op.inputs[3].get_shape().merge_with(
tensor_shape.scalar())
dim0 = tensor_util.constant_value(op.inputs[3])
return [tensor_shape.TensorShape([dim0]).concatenate(input_shape[1:])] | [
"def",
"_SparseSegmentReductionGradShape",
"(",
"op",
")",
":",
"input_shape",
"=",
"op",
".",
"inputs",
"[",
"0",
"]",
".",
"get_shape",
"(",
")",
"indices_shape",
"=",
"op",
".",
"inputs",
"[",
"1",
"]",
".",
"get_shape",
"(",
")",
".",
"with_rank",
"(",
"1",
")",
"unused_segment_ids_shape",
"=",
"op",
".",
"inputs",
"[",
"2",
"]",
".",
"get_shape",
"(",
")",
".",
"merge_with",
"(",
"indices_shape",
")",
"unused_output_dim0_shape",
"=",
"op",
".",
"inputs",
"[",
"3",
"]",
".",
"get_shape",
"(",
")",
".",
"merge_with",
"(",
"tensor_shape",
".",
"scalar",
"(",
")",
")",
"dim0",
"=",
"tensor_util",
".",
"constant_value",
"(",
"op",
".",
"inputs",
"[",
"3",
"]",
")",
"return",
"[",
"tensor_shape",
".",
"TensorShape",
"(",
"[",
"dim0",
"]",
")",
".",
"concatenate",
"(",
"input_shape",
"[",
"1",
":",
"]",
")",
"]"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/math_ops.py#L1957-L1965 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/py/sliceshell.py | python | SlicesShell.execStartupScript | (self, startupScript) | Execute the user's PYTHONSTARTUP script if they have one. | Execute the user's PYTHONSTARTUP script if they have one. | [
"Execute",
"the",
"user",
"s",
"PYTHONSTARTUP",
"script",
"if",
"they",
"have",
"one",
"."
] | def execStartupScript(self, startupScript):
"""Execute the user's PYTHONSTARTUP script if they have one."""
if startupScript and os.path.isfile(startupScript):
text = 'Startup script executed: ' + startupScript
self.push('print %r; execfile(%r)' % (text, startupScript))
self.interp.startupScript = startupScript
else:
self.push('') | [
"def",
"execStartupScript",
"(",
"self",
",",
"startupScript",
")",
":",
"if",
"startupScript",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"startupScript",
")",
":",
"text",
"=",
"'Startup script executed: '",
"+",
"startupScript",
"self",
".",
"push",
"(",
"'print %r; execfile(%r)'",
"%",
"(",
"text",
",",
"startupScript",
")",
")",
"self",
".",
"interp",
".",
"startupScript",
"=",
"startupScript",
"else",
":",
"self",
".",
"push",
"(",
"''",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/py/sliceshell.py#L996-L1003 | ||
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/linter/base.py | python | LinterBase.get_lint_cmd_args | (self, file_name) | Get the command to run a linter. | Get the command to run a linter. | [
"Get",
"the",
"command",
"to",
"run",
"a",
"linter",
"."
] | def get_lint_cmd_args(self, file_name):
# type: (str) -> List[str]
"""Get the command to run a linter."""
pass | [
"def",
"get_lint_cmd_args",
"(",
"self",
",",
"file_name",
")",
":",
"# type: (str) -> List[str]",
"pass"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/linter/base.py#L24-L27 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/mixins/rubberband.py | python | RubberBand.__mouseMoved | (self, x, y) | Called when the mouse moved without any buttons pressed
or dragging being done. | Called when the mouse moved without any buttons pressed
or dragging being done. | [
"Called",
"when",
"the",
"mouse",
"moved",
"without",
"any",
"buttons",
"pressed",
"or",
"dragging",
"being",
"done",
"."
] | def __mouseMoved(self, x, y):
"""
Called when the mouse moved without any buttons pressed
or dragging being done.
"""
# Are we on the bounding box?
if pointOnBox(x, y, self.currentBox, thickness=self.__THICKNESS):
position = getCursorPosition(x, y, self.currentBox, thickness=self.__THICKNESS)
cursor = [
wx.CURSOR_SIZENWSE,
wx.CURSOR_SIZENS,
wx.CURSOR_SIZENESW,
wx.CURSOR_SIZEWE,
wx.CURSOR_SIZENWSE,
wx.CURSOR_SIZENS,
wx.CURSOR_SIZENESW,
wx.CURSOR_SIZEWE
] [position]
self.__setCursor(cursor)
elif pointInBox(x, y, self.currentBox):
self.__setCursor(wx.CURSOR_HAND)
else:
self.__setCursor() | [
"def",
"__mouseMoved",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"# Are we on the bounding box?",
"if",
"pointOnBox",
"(",
"x",
",",
"y",
",",
"self",
".",
"currentBox",
",",
"thickness",
"=",
"self",
".",
"__THICKNESS",
")",
":",
"position",
"=",
"getCursorPosition",
"(",
"x",
",",
"y",
",",
"self",
".",
"currentBox",
",",
"thickness",
"=",
"self",
".",
"__THICKNESS",
")",
"cursor",
"=",
"[",
"wx",
".",
"CURSOR_SIZENWSE",
",",
"wx",
".",
"CURSOR_SIZENS",
",",
"wx",
".",
"CURSOR_SIZENESW",
",",
"wx",
".",
"CURSOR_SIZEWE",
",",
"wx",
".",
"CURSOR_SIZENWSE",
",",
"wx",
".",
"CURSOR_SIZENS",
",",
"wx",
".",
"CURSOR_SIZENESW",
",",
"wx",
".",
"CURSOR_SIZEWE",
"]",
"[",
"position",
"]",
"self",
".",
"__setCursor",
"(",
"cursor",
")",
"elif",
"pointInBox",
"(",
"x",
",",
"y",
",",
"self",
".",
"currentBox",
")",
":",
"self",
".",
"__setCursor",
"(",
"wx",
".",
"CURSOR_HAND",
")",
"else",
":",
"self",
".",
"__setCursor",
"(",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/mixins/rubberband.py#L275-L297 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/python-gflags/gflags.py | python | _WriteSimpleXMLElement | (outfile, name, value, indent) | Writes a simple XML element.
Args:
outfile: File object we write the XML element to.
name: A string, the name of XML element.
value: A Python object, whose string representation will be used
as the value of the XML element.
indent: A string, prepended to each line of generated output. | Writes a simple XML element. | [
"Writes",
"a",
"simple",
"XML",
"element",
"."
] | def _WriteSimpleXMLElement(outfile, name, value, indent):
"""Writes a simple XML element.
Args:
outfile: File object we write the XML element to.
name: A string, the name of XML element.
value: A Python object, whose string representation will be used
as the value of the XML element.
indent: A string, prepended to each line of generated output.
"""
value_str = _StrOrUnicode(value)
if isinstance(value, bool):
# Display boolean values as the C++ flag library does: no caps.
value_str = value_str.lower()
safe_value_str = _MakeXMLSafe(value_str)
outfile.write('%s<%s>%s</%s>\n' % (indent, name, safe_value_str, name)) | [
"def",
"_WriteSimpleXMLElement",
"(",
"outfile",
",",
"name",
",",
"value",
",",
"indent",
")",
":",
"value_str",
"=",
"_StrOrUnicode",
"(",
"value",
")",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"# Display boolean values as the C++ flag library does: no caps.",
"value_str",
"=",
"value_str",
".",
"lower",
"(",
")",
"safe_value_str",
"=",
"_MakeXMLSafe",
"(",
"value_str",
")",
"outfile",
".",
"write",
"(",
"'%s<%s>%s</%s>\\n'",
"%",
"(",
"indent",
",",
"name",
",",
"safe_value_str",
",",
"name",
")",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/python-gflags/gflags.py#L1789-L1804 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/ribbon/page.py | python | RibbonPage.DoSetSize | (self, x, y, width, height, sizeFlags=wx.SIZE_AUTO) | Sets the size of the window in pixels.
:param integer `x`: required `x` position in pixels, or ``wx.DefaultCoord`` to
indicate that the existing value should be used;
:param integer `y`: required `y` position in pixels, or ``wx.DefaultCoord`` to
indicate that the existing value should be used;
:param integer `width`: required width in pixels, or ``wx.DefaultCoord`` to
indicate that the existing value should be used;
:param integer `height`: required height in pixels, or ``wx.DefaultCoord`` to
indicate that the existing value should be used;
:param integer `sizeFlags`: indicates the interpretation of other parameters.
It is a bit list of the following:
* ``wx.SIZE_AUTO_WIDTH``: a ``wx.DefaultCoord`` width value is taken to indicate a
wxPython-supplied default width.
* ``wx.SIZE_AUTO_HEIGHT``: a ``wx.DefaultCoord`` height value is taken to indicate a
wxPython-supplied default height.
* ``wx.SIZE_AUTO``: ``wx.DefaultCoord`` size values are taken to indicate a wxPython-supplied
default size.
* ``wx.SIZE_USE_EXISTING``: existing dimensions should be used if ``wx.DefaultCoord`` values are supplied.
* ``wx.SIZE_ALLOW_MINUS_ONE``: allow negative dimensions (i.e. value of ``wx.DefaultCoord``)
to be interpreted as real dimensions, not default values.
* ``wx.SIZE_FORCE``: normally, if the position and the size of the window are already
the same as the parameters of this function, nothing is done. but with this flag a window
resize may be forced even in this case (supported in wx 2.6.2 and later and only implemented
for MSW and ignored elsewhere currently). | Sets the size of the window in pixels. | [
"Sets",
"the",
"size",
"of",
"the",
"window",
"in",
"pixels",
"."
] | def DoSetSize(self, x, y, width, height, sizeFlags=wx.SIZE_AUTO):
"""
Sets the size of the window in pixels.
:param integer `x`: required `x` position in pixels, or ``wx.DefaultCoord`` to
indicate that the existing value should be used;
:param integer `y`: required `y` position in pixels, or ``wx.DefaultCoord`` to
indicate that the existing value should be used;
:param integer `width`: required width in pixels, or ``wx.DefaultCoord`` to
indicate that the existing value should be used;
:param integer `height`: required height in pixels, or ``wx.DefaultCoord`` to
indicate that the existing value should be used;
:param integer `sizeFlags`: indicates the interpretation of other parameters.
It is a bit list of the following:
* ``wx.SIZE_AUTO_WIDTH``: a ``wx.DefaultCoord`` width value is taken to indicate a
wxPython-supplied default width.
* ``wx.SIZE_AUTO_HEIGHT``: a ``wx.DefaultCoord`` height value is taken to indicate a
wxPython-supplied default height.
* ``wx.SIZE_AUTO``: ``wx.DefaultCoord`` size values are taken to indicate a wxPython-supplied
default size.
* ``wx.SIZE_USE_EXISTING``: existing dimensions should be used if ``wx.DefaultCoord`` values are supplied.
* ``wx.SIZE_ALLOW_MINUS_ONE``: allow negative dimensions (i.e. value of ``wx.DefaultCoord``)
to be interpreted as real dimensions, not default values.
* ``wx.SIZE_FORCE``: normally, if the position and the size of the window are already
the same as the parameters of this function, nothing is done. but with this flag a window
resize may be forced even in this case (supported in wx 2.6.2 and later and only implemented
for MSW and ignored elsewhere currently).
"""
# When a resize triggers the scroll buttons to become visible, the page is resized.
# This resize from within a resize event can cause (MSW) wxWidgets some confusion,
# and report the 1st size to the 2nd size event. Hence the most recent size is
# remembered internally and used in Layout() where appropiate.
if self.GetMajorAxis() == wx.HORIZONTAL:
self._size_in_major_axis_for_children = width
if self._scroll_buttons_visible:
if self._scroll_left_btn:
self._size_in_major_axis_for_children += self._scroll_left_btn.GetSize().GetWidth()
if self._scroll_right_btn:
self._size_in_major_axis_for_children += self._scroll_right_btn.GetSize().GetWidth()
else:
self._size_in_major_axis_for_children = height
if self._scroll_buttons_visible:
if self._scroll_left_btn:
self._size_in_major_axis_for_children += self._scroll_left_btn.GetSize().GetHeight()
if self._scroll_right_btn:
self._size_in_major_axis_for_children += self._scroll_right_btn.GetSize().GetHeight()
RibbonControl.DoSetSize(self, x, y, width, height, sizeFlags) | [
"def",
"DoSetSize",
"(",
"self",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
",",
"sizeFlags",
"=",
"wx",
".",
"SIZE_AUTO",
")",
":",
"# When a resize triggers the scroll buttons to become visible, the page is resized.",
"# This resize from within a resize event can cause (MSW) wxWidgets some confusion,",
"# and report the 1st size to the 2nd size event. Hence the most recent size is",
"# remembered internally and used in Layout() where appropiate.",
"if",
"self",
".",
"GetMajorAxis",
"(",
")",
"==",
"wx",
".",
"HORIZONTAL",
":",
"self",
".",
"_size_in_major_axis_for_children",
"=",
"width",
"if",
"self",
".",
"_scroll_buttons_visible",
":",
"if",
"self",
".",
"_scroll_left_btn",
":",
"self",
".",
"_size_in_major_axis_for_children",
"+=",
"self",
".",
"_scroll_left_btn",
".",
"GetSize",
"(",
")",
".",
"GetWidth",
"(",
")",
"if",
"self",
".",
"_scroll_right_btn",
":",
"self",
".",
"_size_in_major_axis_for_children",
"+=",
"self",
".",
"_scroll_right_btn",
".",
"GetSize",
"(",
")",
".",
"GetWidth",
"(",
")",
"else",
":",
"self",
".",
"_size_in_major_axis_for_children",
"=",
"height",
"if",
"self",
".",
"_scroll_buttons_visible",
":",
"if",
"self",
".",
"_scroll_left_btn",
":",
"self",
".",
"_size_in_major_axis_for_children",
"+=",
"self",
".",
"_scroll_left_btn",
".",
"GetSize",
"(",
")",
".",
"GetHeight",
"(",
")",
"if",
"self",
".",
"_scroll_right_btn",
":",
"self",
".",
"_size_in_major_axis_for_children",
"+=",
"self",
".",
"_scroll_right_btn",
".",
"GetSize",
"(",
")",
".",
"GetHeight",
"(",
")",
"RibbonControl",
".",
"DoSetSize",
"(",
"self",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
",",
"sizeFlags",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ribbon/page.py#L374-L427 | ||
ablab/quast | 5f6709528129a6ad266a6b24ef3f40b88f0fe04b | quast_libs/site_packages/jsontemplate/jsontemplate.py | python | _Section.__init__ | (self, section_name=None) | Args:
section_name: name given as an argument to the section
token_type: The token type that created this section (e.g.
PREDICATE_TOKEN) | Args:
section_name: name given as an argument to the section
token_type: The token type that created this section (e.g.
PREDICATE_TOKEN) | [
"Args",
":",
"section_name",
":",
"name",
"given",
"as",
"an",
"argument",
"to",
"the",
"section",
"token_type",
":",
"The",
"token",
"type",
"that",
"created",
"this",
"section",
"(",
"e",
".",
"g",
".",
"PREDICATE_TOKEN",
")"
] | def __init__(self, section_name=None):
"""
Args:
section_name: name given as an argument to the section
token_type: The token type that created this section (e.g.
PREDICATE_TOKEN)
"""
_AbstractSection.__init__(self)
self.section_name = section_name
# Clauses is just a string and a list of statements.
self.statements = {'default': self.current_clause} | [
"def",
"__init__",
"(",
"self",
",",
"section_name",
"=",
"None",
")",
":",
"_AbstractSection",
".",
"__init__",
"(",
"self",
")",
"self",
".",
"section_name",
"=",
"section_name",
"# Clauses is just a string and a list of statements.",
"self",
".",
"statements",
"=",
"{",
"'default'",
":",
"self",
".",
"current_clause",
"}"
] | https://github.com/ablab/quast/blob/5f6709528129a6ad266a6b24ef3f40b88f0fe04b/quast_libs/site_packages/jsontemplate/jsontemplate.py#L377-L388 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/math/optimize.py | python | OptimizationProblemBuilder.addFeasibilityTest | (self,f,weight=None) | Adds an additional feasibility test. | Adds an additional feasibility test. | [
"Adds",
"an",
"additional",
"feasibility",
"test",
"."
] | def addFeasibilityTest(self,f,weight=None):
"""Adds an additional feasibility test."""
if isinstance(f,symbolic.Function):
return self.addFeasibilityTest(self.context.bindFunction(f,self.optimizationVariables),weight)
else:
assert isinstance(f,symbolic.Expression)
self.objectives.append(OptimizationObjective(f,'feas',weight))
return self.objectives[-1] | [
"def",
"addFeasibilityTest",
"(",
"self",
",",
"f",
",",
"weight",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"f",
",",
"symbolic",
".",
"Function",
")",
":",
"return",
"self",
".",
"addFeasibilityTest",
"(",
"self",
".",
"context",
".",
"bindFunction",
"(",
"f",
",",
"self",
".",
"optimizationVariables",
")",
",",
"weight",
")",
"else",
":",
"assert",
"isinstance",
"(",
"f",
",",
"symbolic",
".",
"Expression",
")",
"self",
".",
"objectives",
".",
"append",
"(",
"OptimizationObjective",
"(",
"f",
",",
"'feas'",
",",
"weight",
")",
")",
"return",
"self",
".",
"objectives",
"[",
"-",
"1",
"]"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/math/optimize.py#L838-L845 | ||
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/ros/rosunit/src/rosunit/junitxml.py | python | TestCaseResult._description | (self) | @return: description of testcase result
@rtype: str | [] | def _description(self):
"""
@return: description of testcase result
@rtype: str
"""
if self.passed:
return "[%s][passed]\n"%self.name
else:
return self._failure_description()+\
self._error_description() | [
"def",
"_description",
"(",
"self",
")",
":",
"if",
"self",
".",
"passed",
":",
"return",
"\"[%s][passed]\\n\"",
"%",
"self",
".",
"name",
"else",
":",
"return",
"self",
".",
"_failure_description",
"(",
")",
"+",
"self",
".",
"_error_description",
"(",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros/rosunit/src/rosunit/junitxml.py#L147-L156 | |||
panda3d/panda3d | 833ad89ebad58395d0af0b7ec08538e5e4308265 | direct/src/actor/Actor.py | python | Actor.loadAnims | (self, anims, partName="modelRoot", lodName="lodRoot") | loadAnims(self, string:string{}, string='modelRoot',
string='lodRoot')
Actor anim loader. Takes an optional partName (defaults to
'modelRoot' for non-multipart actors) and lodName (defaults
to 'lodRoot' for non-LOD actors) and dict of corresponding
anims in the form animName:animPath{} | loadAnims(self, string:string{}, string='modelRoot',
string='lodRoot')
Actor anim loader. Takes an optional partName (defaults to
'modelRoot' for non-multipart actors) and lodName (defaults
to 'lodRoot' for non-LOD actors) and dict of corresponding
anims in the form animName:animPath{} | [
"loadAnims",
"(",
"self",
"string",
":",
"string",
"{}",
"string",
"=",
"modelRoot",
"string",
"=",
"lodRoot",
")",
"Actor",
"anim",
"loader",
".",
"Takes",
"an",
"optional",
"partName",
"(",
"defaults",
"to",
"modelRoot",
"for",
"non",
"-",
"multipart",
"actors",
")",
"and",
"lodName",
"(",
"defaults",
"to",
"lodRoot",
"for",
"non",
"-",
"LOD",
"actors",
")",
"and",
"dict",
"of",
"corresponding",
"anims",
"in",
"the",
"form",
"animName",
":",
"animPath",
"{}"
] | def loadAnims(self, anims, partName="modelRoot", lodName="lodRoot"):
"""loadAnims(self, string:string{}, string='modelRoot',
string='lodRoot')
Actor anim loader. Takes an optional partName (defaults to
'modelRoot' for non-multipart actors) and lodName (defaults
to 'lodRoot' for non-LOD actors) and dict of corresponding
anims in the form animName:animPath{}
"""
reload = True
if self.mergeLODBundles:
lodNames = ['common']
elif lodName == 'all':
reload = False
lodNames = list(map(str, sorted(self.switches.keys())))
else:
lodNames = [lodName]
assert Actor.notify.debug("in loadAnims: %s, part: %s, lod: %s" %
(anims, partName, lodNames[0]))
firstLoad = True
if not reload:
if lodNames[0] in self.__animControlDict and \
partName in self.__animControlDict[lodNames[0]]:
firstLoad = False
for lName in lodNames:
if firstLoad:
self.__animControlDict.setdefault(lName, {})
self.__animControlDict[lName].setdefault(partName, {})
for animName, filename in anims.items():
# make sure this lod is in anim control dict
for lName in lodNames:
if firstLoad:
self.__animControlDict[lName][partName][animName] = Actor.AnimDef()
if isinstance(filename, NodePath):
# We were given a pre-load anim bundle, not a filename.
assert not filename.isEmpty()
if filename.node().isOfType(AnimBundleNode.getClassType()):
animBundleNP = filename
else:
animBundleNP = filename.find('**/+AnimBundleNode')
assert not animBundleNP.isEmpty()
self.__animControlDict[lName][partName][animName].animBundle = animBundleNP.node().getBundle()
else:
# We were given a filename that must be loaded.
# Store the filename only; we will load and bind
# it (and produce an AnimControl) when it is
# played.
self.__animControlDict[lName][partName][animName].filename = filename | [
"def",
"loadAnims",
"(",
"self",
",",
"anims",
",",
"partName",
"=",
"\"modelRoot\"",
",",
"lodName",
"=",
"\"lodRoot\"",
")",
":",
"reload",
"=",
"True",
"if",
"self",
".",
"mergeLODBundles",
":",
"lodNames",
"=",
"[",
"'common'",
"]",
"elif",
"lodName",
"==",
"'all'",
":",
"reload",
"=",
"False",
"lodNames",
"=",
"list",
"(",
"map",
"(",
"str",
",",
"sorted",
"(",
"self",
".",
"switches",
".",
"keys",
"(",
")",
")",
")",
")",
"else",
":",
"lodNames",
"=",
"[",
"lodName",
"]",
"assert",
"Actor",
".",
"notify",
".",
"debug",
"(",
"\"in loadAnims: %s, part: %s, lod: %s\"",
"%",
"(",
"anims",
",",
"partName",
",",
"lodNames",
"[",
"0",
"]",
")",
")",
"firstLoad",
"=",
"True",
"if",
"not",
"reload",
":",
"if",
"lodNames",
"[",
"0",
"]",
"in",
"self",
".",
"__animControlDict",
"and",
"partName",
"in",
"self",
".",
"__animControlDict",
"[",
"lodNames",
"[",
"0",
"]",
"]",
":",
"firstLoad",
"=",
"False",
"for",
"lName",
"in",
"lodNames",
":",
"if",
"firstLoad",
":",
"self",
".",
"__animControlDict",
".",
"setdefault",
"(",
"lName",
",",
"{",
"}",
")",
"self",
".",
"__animControlDict",
"[",
"lName",
"]",
".",
"setdefault",
"(",
"partName",
",",
"{",
"}",
")",
"for",
"animName",
",",
"filename",
"in",
"anims",
".",
"items",
"(",
")",
":",
"# make sure this lod is in anim control dict",
"for",
"lName",
"in",
"lodNames",
":",
"if",
"firstLoad",
":",
"self",
".",
"__animControlDict",
"[",
"lName",
"]",
"[",
"partName",
"]",
"[",
"animName",
"]",
"=",
"Actor",
".",
"AnimDef",
"(",
")",
"if",
"isinstance",
"(",
"filename",
",",
"NodePath",
")",
":",
"# We were given a pre-load anim bundle, not a filename.",
"assert",
"not",
"filename",
".",
"isEmpty",
"(",
")",
"if",
"filename",
".",
"node",
"(",
")",
".",
"isOfType",
"(",
"AnimBundleNode",
".",
"getClassType",
"(",
")",
")",
":",
"animBundleNP",
"=",
"filename",
"else",
":",
"animBundleNP",
"=",
"filename",
".",
"find",
"(",
"'**/+AnimBundleNode'",
")",
"assert",
"not",
"animBundleNP",
".",
"isEmpty",
"(",
")",
"self",
".",
"__animControlDict",
"[",
"lName",
"]",
"[",
"partName",
"]",
"[",
"animName",
"]",
".",
"animBundle",
"=",
"animBundleNP",
".",
"node",
"(",
")",
".",
"getBundle",
"(",
")",
"else",
":",
"# We were given a filename that must be loaded.",
"# Store the filename only; we will load and bind",
"# it (and produce an AnimControl) when it is",
"# played.",
"self",
".",
"__animControlDict",
"[",
"lName",
"]",
"[",
"partName",
"]",
"[",
"animName",
"]",
".",
"filename",
"=",
"filename"
] | https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/actor/Actor.py#L2122-L2174 | ||
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py | python | _FixPaths | (paths) | return [_FixPath(i) for i in paths] | Fix each of the paths of the list. | Fix each of the paths of the list. | [
"Fix",
"each",
"of",
"the",
"paths",
"of",
"the",
"list",
"."
] | def _FixPaths(paths):
"""Fix each of the paths of the list."""
return [_FixPath(i) for i in paths] | [
"def",
"_FixPaths",
"(",
"paths",
")",
":",
"return",
"[",
"_FixPath",
"(",
"i",
")",
"for",
"i",
"in",
"paths",
"]"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py#L174-L176 | |
openthread/openthread | 9fcdbed9c526c70f1556d1ed84099c1535c7cd32 | tools/otci/otci/otci.py | python | OTCI.set_child_supervision_interval | (self, val: int) | Set the Child Supervision Interval value.
This command can only be used with FTD devices. | Set the Child Supervision Interval value.
This command can only be used with FTD devices. | [
"Set",
"the",
"Child",
"Supervision",
"Interval",
"value",
".",
"This",
"command",
"can",
"only",
"be",
"used",
"with",
"FTD",
"devices",
"."
] | def set_child_supervision_interval(self, val: int):
"""Set the Child Supervision Interval value.
This command can only be used with FTD devices.
"""
self.execute_command(f'childsupervision interval {val}') | [
"def",
"set_child_supervision_interval",
"(",
"self",
",",
"val",
":",
"int",
")",
":",
"self",
".",
"execute_command",
"(",
"f'childsupervision interval {val}'",
")"
] | https://github.com/openthread/openthread/blob/9fcdbed9c526c70f1556d1ed84099c1535c7cd32/tools/otci/otci/otci.py#L1271-L1275 | ||
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/vision/transforms/functional_tensor.py | python | resize | (img, size, interpolation='bilinear', data_format='CHW') | return img.squeeze(0) | Resizes the image to given size
Args:
input (paddle.Tensor): Image to be resized.
size (int|list|tuple): Target size of input data, with (height, width) shape.
interpolation (int|str, optional): Interpolation method. when use paddle backend,
support method are as following:
- "nearest"
- "bilinear"
- "bicubic"
- "trilinear"
- "area"
- "linear"
data_format (str, optional): paddle.Tensor format
- 'CHW'
- 'HWC'
Returns:
paddle.Tensor: Resized image. | Resizes the image to given size | [
"Resizes",
"the",
"image",
"to",
"given",
"size"
] | def resize(img, size, interpolation='bilinear', data_format='CHW'):
"""
Resizes the image to given size
Args:
input (paddle.Tensor): Image to be resized.
size (int|list|tuple): Target size of input data, with (height, width) shape.
interpolation (int|str, optional): Interpolation method. when use paddle backend,
support method are as following:
- "nearest"
- "bilinear"
- "bicubic"
- "trilinear"
- "area"
- "linear"
data_format (str, optional): paddle.Tensor format
- 'CHW'
- 'HWC'
Returns:
paddle.Tensor: Resized image.
"""
_assert_image_tensor(img, data_format)
if not (isinstance(size, int) or
(isinstance(size, (tuple, list)) and len(size) == 2)):
raise TypeError('Got inappropriate size arg: {}'.format(size))
if isinstance(size, int):
w, h = _get_image_size(img, data_format)
if (w <= h and w == size) or (h <= w and h == size):
return img
if w < h:
ow = size
oh = int(size * h / w)
else:
oh = size
ow = int(size * w / h)
else:
oh, ow = size
img = img.unsqueeze(0)
img = F.interpolate(
img,
size=(oh, ow),
mode=interpolation.lower(),
data_format='N' + data_format.upper())
return img.squeeze(0) | [
"def",
"resize",
"(",
"img",
",",
"size",
",",
"interpolation",
"=",
"'bilinear'",
",",
"data_format",
"=",
"'CHW'",
")",
":",
"_assert_image_tensor",
"(",
"img",
",",
"data_format",
")",
"if",
"not",
"(",
"isinstance",
"(",
"size",
",",
"int",
")",
"or",
"(",
"isinstance",
"(",
"size",
",",
"(",
"tuple",
",",
"list",
")",
")",
"and",
"len",
"(",
"size",
")",
"==",
"2",
")",
")",
":",
"raise",
"TypeError",
"(",
"'Got inappropriate size arg: {}'",
".",
"format",
"(",
"size",
")",
")",
"if",
"isinstance",
"(",
"size",
",",
"int",
")",
":",
"w",
",",
"h",
"=",
"_get_image_size",
"(",
"img",
",",
"data_format",
")",
"if",
"(",
"w",
"<=",
"h",
"and",
"w",
"==",
"size",
")",
"or",
"(",
"h",
"<=",
"w",
"and",
"h",
"==",
"size",
")",
":",
"return",
"img",
"if",
"w",
"<",
"h",
":",
"ow",
"=",
"size",
"oh",
"=",
"int",
"(",
"size",
"*",
"h",
"/",
"w",
")",
"else",
":",
"oh",
"=",
"size",
"ow",
"=",
"int",
"(",
"size",
"*",
"w",
"/",
"h",
")",
"else",
":",
"oh",
",",
"ow",
"=",
"size",
"img",
"=",
"img",
".",
"unsqueeze",
"(",
"0",
")",
"img",
"=",
"F",
".",
"interpolate",
"(",
"img",
",",
"size",
"=",
"(",
"oh",
",",
"ow",
")",
",",
"mode",
"=",
"interpolation",
".",
"lower",
"(",
")",
",",
"data_format",
"=",
"'N'",
"+",
"data_format",
".",
"upper",
"(",
")",
")",
"return",
"img",
".",
"squeeze",
"(",
"0",
")"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/vision/transforms/functional_tensor.py#L468-L516 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/syntax/synextreg.py | python | GetFileExtensions | () | return extreg.GetAllExtensions() | Gets a sorted list of all file extensions the editor is configured
to handle.
@return: all registered file extensions | Gets a sorted list of all file extensions the editor is configured
to handle.
@return: all registered file extensions | [
"Gets",
"a",
"sorted",
"list",
"of",
"all",
"file",
"extensions",
"the",
"editor",
"is",
"configured",
"to",
"handle",
".",
"@return",
":",
"all",
"registered",
"file",
"extensions"
] | def GetFileExtensions():
"""Gets a sorted list of all file extensions the editor is configured
to handle.
@return: all registered file extensions
"""
extreg = ExtensionRegister()
return extreg.GetAllExtensions() | [
"def",
"GetFileExtensions",
"(",
")",
":",
"extreg",
"=",
"ExtensionRegister",
"(",
")",
"return",
"extreg",
".",
"GetAllExtensions",
"(",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/syntax/synextreg.py#L576-L583 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | deps/src/libxml2-2.9.1/python/libxml2.py | python | xmlDoc.ID | (self, ID) | return __tmp | Search the attribute declaring the given ID | Search the attribute declaring the given ID | [
"Search",
"the",
"attribute",
"declaring",
"the",
"given",
"ID"
] | def ID(self, ID):
"""Search the attribute declaring the given ID """
ret = libxml2mod.xmlGetID(self._o, ID)
if ret is None:raise treeError('xmlGetID() failed')
__tmp = xmlAttr(_obj=ret)
return __tmp | [
"def",
"ID",
"(",
"self",
",",
"ID",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlGetID",
"(",
"self",
".",
"_o",
",",
"ID",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlGetID() failed'",
")",
"__tmp",
"=",
"xmlAttr",
"(",
"_obj",
"=",
"ret",
")",
"return",
"__tmp"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2.py#L4593-L4598 | |
openalpr/openalpr | 736ab0e608cf9b20d92f36a873bb1152240daa98 | src/bindings/python/openalpr/openalpr.py | python | Alpr.recognize_file | (self, file_path) | return response_obj | This causes OpenALPR to attempt to recognize an image by opening a file on
disk.
:param file_path: The path to the image that will be analyzed
:return: An OpenALPR analysis in the form of a response dictionary | This causes OpenALPR to attempt to recognize an image by opening a file on
disk. | [
"This",
"causes",
"OpenALPR",
"to",
"attempt",
"to",
"recognize",
"an",
"image",
"by",
"opening",
"a",
"file",
"on",
"disk",
"."
] | def recognize_file(self, file_path):
"""
This causes OpenALPR to attempt to recognize an image by opening a file on
disk.
:param file_path: The path to the image that will be analyzed
:return: An OpenALPR analysis in the form of a response dictionary
"""
file_path = _convert_to_charp(file_path)
ptr = self._recognize_file_func(self.alpr_pointer, file_path)
json_data = ctypes.cast(ptr, ctypes.c_char_p).value
json_data = _convert_from_charp(json_data)
response_obj = json.loads(json_data)
self._free_json_mem_func(ctypes.c_void_p(ptr))
return response_obj | [
"def",
"recognize_file",
"(",
"self",
",",
"file_path",
")",
":",
"file_path",
"=",
"_convert_to_charp",
"(",
"file_path",
")",
"ptr",
"=",
"self",
".",
"_recognize_file_func",
"(",
"self",
".",
"alpr_pointer",
",",
"file_path",
")",
"json_data",
"=",
"ctypes",
".",
"cast",
"(",
"ptr",
",",
"ctypes",
".",
"c_char_p",
")",
".",
"value",
"json_data",
"=",
"_convert_from_charp",
"(",
"json_data",
")",
"response_obj",
"=",
"json",
".",
"loads",
"(",
"json_data",
")",
"self",
".",
"_free_json_mem_func",
"(",
"ctypes",
".",
"c_void_p",
"(",
"ptr",
")",
")",
"return",
"response_obj"
] | https://github.com/openalpr/openalpr/blob/736ab0e608cf9b20d92f36a873bb1152240daa98/src/bindings/python/openalpr/openalpr.py#L140-L154 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/debug/lib/debug_data.py | python | DebugDumpDir.nodes | (self, device_name=None) | Get a list of all nodes from the partition graphs.
Args:
device_name: (`str`) name of device. If None, all nodes from all available
devices will be included.
Returns:
All nodes' names, as a list of str.
Raises:
LookupError: If no partition graphs have been loaded.
ValueError: If specified node name does not exist. | Get a list of all nodes from the partition graphs. | [
"Get",
"a",
"list",
"of",
"all",
"nodes",
"from",
"the",
"partition",
"graphs",
"."
] | def nodes(self, device_name=None):
"""Get a list of all nodes from the partition graphs.
Args:
device_name: (`str`) name of device. If None, all nodes from all available
devices will be included.
Returns:
All nodes' names, as a list of str.
Raises:
LookupError: If no partition graphs have been loaded.
ValueError: If specified node name does not exist.
"""
if self._partition_graphs is None:
raise LookupError("No partition graphs have been loaded.")
if device_name is None:
nodes = []
for device_name in self._node_inputs:
nodes.extend(self._node_inputs[device_name].keys())
return nodes
else:
if device_name not in self._node_inputs:
raise ValueError("Invalid device name: %s" % device_name)
return self._node_inputs[device_name].keys() | [
"def",
"nodes",
"(",
"self",
",",
"device_name",
"=",
"None",
")",
":",
"if",
"self",
".",
"_partition_graphs",
"is",
"None",
":",
"raise",
"LookupError",
"(",
"\"No partition graphs have been loaded.\"",
")",
"if",
"device_name",
"is",
"None",
":",
"nodes",
"=",
"[",
"]",
"for",
"device_name",
"in",
"self",
".",
"_node_inputs",
":",
"nodes",
".",
"extend",
"(",
"self",
".",
"_node_inputs",
"[",
"device_name",
"]",
".",
"keys",
"(",
")",
")",
"return",
"nodes",
"else",
":",
"if",
"device_name",
"not",
"in",
"self",
".",
"_node_inputs",
":",
"raise",
"ValueError",
"(",
"\"Invalid device name: %s\"",
"%",
"device_name",
")",
"return",
"self",
".",
"_node_inputs",
"[",
"device_name",
"]",
".",
"keys",
"(",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/debug/lib/debug_data.py#L1367-L1391 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/imaplib.py | python | IMAP4.send | (self, data) | Send data to remote. | Send data to remote. | [
"Send",
"data",
"to",
"remote",
"."
] | def send(self, data):
"""Send data to remote."""
self.sock.sendall(data) | [
"def",
"send",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"sock",
".",
"sendall",
"(",
"data",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/imaplib.py#L316-L318 | ||
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/src/third_party/wiredtiger/src/docs/tools/doxypy.py | python | Doxypy.startCommentSearch | (self, match) | Starts a new comment search.
Saves the triggering line, resets the current comment and saves
the current indentation. | Starts a new comment search.
Saves the triggering line, resets the current comment and saves
the current indentation. | [
"Starts",
"a",
"new",
"comment",
"search",
".",
"Saves",
"the",
"triggering",
"line",
"resets",
"the",
"current",
"comment",
"and",
"saves",
"the",
"current",
"indentation",
"."
] | def startCommentSearch(self, match):
"""Starts a new comment search.
Saves the triggering line, resets the current comment and saves
the current indentation.
"""
if options.debug:
print >>sys.stderr, "# CALLBACK: startCommentSearch"
self.defclass = [self.fsm.current_input]
self.comment = []
self.indent = match.group(1) | [
"def",
"startCommentSearch",
"(",
"self",
",",
"match",
")",
":",
"if",
"options",
".",
"debug",
":",
"print",
">>",
"sys",
".",
"stderr",
",",
"\"# CALLBACK: startCommentSearch\"",
"self",
".",
"defclass",
"=",
"[",
"self",
".",
"fsm",
".",
"current_input",
"]",
"self",
".",
"comment",
"=",
"[",
"]",
"self",
".",
"indent",
"=",
"match",
".",
"group",
"(",
"1",
")"
] | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/wiredtiger/src/docs/tools/doxypy.py#L235-L245 | ||
FEniCS/dolfinx | 3dfdf038cccdb70962865b58a63bf29c2e55ec6e | python/dolfinx/pkgconfig.py | python | parse | (package) | return result | Return a dict containing compile-time definitions | Return a dict containing compile-time definitions | [
"Return",
"a",
"dict",
"containing",
"compile",
"-",
"time",
"definitions"
] | def parse(package):
"Return a dict containing compile-time definitions"
parse_map = {
'-D': 'define_macros',
'-I': 'include_dirs',
'-L': 'library_dirs',
'-l': 'libraries'
}
result = {x: [] for x in parse_map.values()}
# Execute the query to pkg-config and clean the result.
out = _pkgconfig_query(package + ' --cflags --libs')[1]
out = out.replace('\\"', '')
# Iterate through each token in the output.
for token in out.split():
key = parse_map.get(token[:2])
if key:
t = token[2:].strip()
result[key].append(t)
return result | [
"def",
"parse",
"(",
"package",
")",
":",
"parse_map",
"=",
"{",
"'-D'",
":",
"'define_macros'",
",",
"'-I'",
":",
"'include_dirs'",
",",
"'-L'",
":",
"'library_dirs'",
",",
"'-l'",
":",
"'libraries'",
"}",
"result",
"=",
"{",
"x",
":",
"[",
"]",
"for",
"x",
"in",
"parse_map",
".",
"values",
"(",
")",
"}",
"# Execute the query to pkg-config and clean the result.",
"out",
"=",
"_pkgconfig_query",
"(",
"package",
"+",
"' --cflags --libs'",
")",
"[",
"1",
"]",
"out",
"=",
"out",
".",
"replace",
"(",
"'\\\\\"'",
",",
"''",
")",
"# Iterate through each token in the output.",
"for",
"token",
"in",
"out",
".",
"split",
"(",
")",
":",
"key",
"=",
"parse_map",
".",
"get",
"(",
"token",
"[",
":",
"2",
"]",
")",
"if",
"key",
":",
"t",
"=",
"token",
"[",
"2",
":",
"]",
".",
"strip",
"(",
")",
"result",
"[",
"key",
"]",
".",
"append",
"(",
"t",
")",
"return",
"result"
] | https://github.com/FEniCS/dolfinx/blob/3dfdf038cccdb70962865b58a63bf29c2e55ec6e/python/dolfinx/pkgconfig.py#L32-L54 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/email/message.py | python | Message.get_payload | (self, i=None, decode=False) | return payload | Return a reference to the payload.
The payload will either be a list object or a string. If you mutate
the list object, you modify the message's payload in place. Optional
i returns that index into the payload.
Optional decode is a flag indicating whether the payload should be
decoded or not, according to the Content-Transfer-Encoding header
(default is False).
When True and the message is not a multipart, the payload will be
decoded if this header's value is `quoted-printable' or `base64'. If
some other encoding is used, or the header is missing, or if the
payload has bogus data (i.e. bogus base64 or uuencoded data), the
payload is returned as-is.
If the message is a multipart and the decode flag is True, then None
is returned. | Return a reference to the payload. | [
"Return",
"a",
"reference",
"to",
"the",
"payload",
"."
] | def get_payload(self, i=None, decode=False):
"""Return a reference to the payload.
The payload will either be a list object or a string. If you mutate
the list object, you modify the message's payload in place. Optional
i returns that index into the payload.
Optional decode is a flag indicating whether the payload should be
decoded or not, according to the Content-Transfer-Encoding header
(default is False).
When True and the message is not a multipart, the payload will be
decoded if this header's value is `quoted-printable' or `base64'. If
some other encoding is used, or the header is missing, or if the
payload has bogus data (i.e. bogus base64 or uuencoded data), the
payload is returned as-is.
If the message is a multipart and the decode flag is True, then None
is returned.
"""
if i is None:
payload = self._payload
elif not isinstance(self._payload, list):
raise TypeError('Expected list, got %s' % type(self._payload))
else:
payload = self._payload[i]
if decode:
if self.is_multipart():
return None
cte = self.get('content-transfer-encoding', '').lower()
if cte == 'quoted-printable':
return utils._qdecode(payload)
elif cte == 'base64':
try:
return utils._bdecode(payload)
except binascii.Error:
# Incorrect padding
return payload
elif cte in ('x-uuencode', 'uuencode', 'uue', 'x-uue'):
sfp = StringIO()
try:
uu.decode(StringIO(payload+'\n'), sfp, quiet=True)
payload = sfp.getvalue()
except uu.Error:
# Some decoding problem
return payload
# Everything else, including encodings with 8bit or 7bit are returned
# unchanged.
return payload | [
"def",
"get_payload",
"(",
"self",
",",
"i",
"=",
"None",
",",
"decode",
"=",
"False",
")",
":",
"if",
"i",
"is",
"None",
":",
"payload",
"=",
"self",
".",
"_payload",
"elif",
"not",
"isinstance",
"(",
"self",
".",
"_payload",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"'Expected list, got %s'",
"%",
"type",
"(",
"self",
".",
"_payload",
")",
")",
"else",
":",
"payload",
"=",
"self",
".",
"_payload",
"[",
"i",
"]",
"if",
"decode",
":",
"if",
"self",
".",
"is_multipart",
"(",
")",
":",
"return",
"None",
"cte",
"=",
"self",
".",
"get",
"(",
"'content-transfer-encoding'",
",",
"''",
")",
".",
"lower",
"(",
")",
"if",
"cte",
"==",
"'quoted-printable'",
":",
"return",
"utils",
".",
"_qdecode",
"(",
"payload",
")",
"elif",
"cte",
"==",
"'base64'",
":",
"try",
":",
"return",
"utils",
".",
"_bdecode",
"(",
"payload",
")",
"except",
"binascii",
".",
"Error",
":",
"# Incorrect padding",
"return",
"payload",
"elif",
"cte",
"in",
"(",
"'x-uuencode'",
",",
"'uuencode'",
",",
"'uue'",
",",
"'x-uue'",
")",
":",
"sfp",
"=",
"StringIO",
"(",
")",
"try",
":",
"uu",
".",
"decode",
"(",
"StringIO",
"(",
"payload",
"+",
"'\\n'",
")",
",",
"sfp",
",",
"quiet",
"=",
"True",
")",
"payload",
"=",
"sfp",
".",
"getvalue",
"(",
")",
"except",
"uu",
".",
"Error",
":",
"# Some decoding problem",
"return",
"payload",
"# Everything else, including encodings with 8bit or 7bit are returned",
"# unchanged.",
"return",
"payload"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/email/message.py#L168-L216 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/eager/context.py | python | _ContextSwitchStack.pop | (self) | Pop the stack. | Pop the stack. | [
"Pop",
"the",
"stack",
"."
] | def pop(self):
"""Pop the stack."""
self.stack.pop() | [
"def",
"pop",
"(",
"self",
")",
":",
"self",
".",
"stack",
".",
"pop",
"(",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/eager/context.py#L234-L237 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/richtext.py | python | RichTextBuffer.InitStandardHandlers | (*args, **kwargs) | return _richtext.RichTextBuffer_InitStandardHandlers(*args, **kwargs) | InitStandardHandlers() | InitStandardHandlers() | [
"InitStandardHandlers",
"()"
] | def InitStandardHandlers(*args, **kwargs):
"""InitStandardHandlers()"""
return _richtext.RichTextBuffer_InitStandardHandlers(*args, **kwargs) | [
"def",
"InitStandardHandlers",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextBuffer_InitStandardHandlers",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/richtext.py#L2600-L2602 | |
microsoft/CNTK | e9396480025b9ca457d26b6f33dd07c474c6aa04 | bindings/python/cntk/ops/__init__.py | python | space_to_depth | (operand, block_size, name='') | return space_to_depth(operand, block_size, name) | Rearranges elements in the input tensor from the spatial dimensions to the depth dimension.
This is the reverse transformation of depth_to_space. This operation is useful for implementing
and testing sub-pixel convolution that is part of models for image super-resolution (see [1]).
It rearranges elements of an input tensor of shape (C, H, W) to a tensor of shape (C*b*b, H/b, W/b),
where b is the `block_size`, by rearranging non-overlapping spatial blocks of size `block_size` x `block_size`
into the depth/channel dimension at each location.
Example:
>>> np.random.seed(3)
>>> x = np.random.randint(low=0, high=100, size=(1, 4, 6)).astype(np.float32)
>>> a = C.input_variable((1, 4, 6))
>>> s2d_op = C.space_to_depth(a, block_size=2)
>>> s2d_op.eval({a:x})
array([[[[ 24., 56., 0.],
[ 96., 44., 39.]],
<BLANKLINE>
[[ 3., 72., 21.],
[ 20., 93., 14.]],
<BLANKLINE>
[[ 19., 41., 21.],
[ 26., 90., 66.]],
<BLANKLINE>
[[ 74., 10., 38.],
[ 81., 22., 2.]]]], dtype=float32)
Args:
operand: Input tensor, with dimensions :math:`[C \\times H \\times W]`.
block_size (int): Integer value. This defines the size of the spatial block whose elements
are moved to the depth dimension. Size of spatial dimensions (H, W) in the input tensor
must be divisible by math:`block_size`
name (str, optional): the name of the Function instance in the network
Returns:
:class:`~cntk.ops.functions.Function`
See also:
[1] W. Shi et. al. `: Real-Time Single Image and Video Super-Resolution Using an Efficient Sub-Pixel Convolutional Neural Network <https://arxiv.org/abs/1609.05158>`_. | Rearranges elements in the input tensor from the spatial dimensions to the depth dimension. | [
"Rearranges",
"elements",
"in",
"the",
"input",
"tensor",
"from",
"the",
"spatial",
"dimensions",
"to",
"the",
"depth",
"dimension",
"."
] | def space_to_depth(operand, block_size, name=''):
'''
Rearranges elements in the input tensor from the spatial dimensions to the depth dimension.
This is the reverse transformation of depth_to_space. This operation is useful for implementing
and testing sub-pixel convolution that is part of models for image super-resolution (see [1]).
It rearranges elements of an input tensor of shape (C, H, W) to a tensor of shape (C*b*b, H/b, W/b),
where b is the `block_size`, by rearranging non-overlapping spatial blocks of size `block_size` x `block_size`
into the depth/channel dimension at each location.
Example:
>>> np.random.seed(3)
>>> x = np.random.randint(low=0, high=100, size=(1, 4, 6)).astype(np.float32)
>>> a = C.input_variable((1, 4, 6))
>>> s2d_op = C.space_to_depth(a, block_size=2)
>>> s2d_op.eval({a:x})
array([[[[ 24., 56., 0.],
[ 96., 44., 39.]],
<BLANKLINE>
[[ 3., 72., 21.],
[ 20., 93., 14.]],
<BLANKLINE>
[[ 19., 41., 21.],
[ 26., 90., 66.]],
<BLANKLINE>
[[ 74., 10., 38.],
[ 81., 22., 2.]]]], dtype=float32)
Args:
operand: Input tensor, with dimensions :math:`[C \\times H \\times W]`.
block_size (int): Integer value. This defines the size of the spatial block whose elements
are moved to the depth dimension. Size of spatial dimensions (H, W) in the input tensor
must be divisible by math:`block_size`
name (str, optional): the name of the Function instance in the network
Returns:
:class:`~cntk.ops.functions.Function`
See also:
[1] W. Shi et. al. `: Real-Time Single Image and Video Super-Resolution Using an Efficient Sub-Pixel Convolutional Neural Network <https://arxiv.org/abs/1609.05158>`_.
'''
from cntk.cntk_py import space_to_depth
operand = sanitize_input(operand, get_data_type(operand))
if not float(block_size).is_integer():
raise ValueError('block_size must be an integer.')
return space_to_depth(operand, block_size, name) | [
"def",
"space_to_depth",
"(",
"operand",
",",
"block_size",
",",
"name",
"=",
"''",
")",
":",
"from",
"cntk",
".",
"cntk_py",
"import",
"space_to_depth",
"operand",
"=",
"sanitize_input",
"(",
"operand",
",",
"get_data_type",
"(",
"operand",
")",
")",
"if",
"not",
"float",
"(",
"block_size",
")",
".",
"is_integer",
"(",
")",
":",
"raise",
"ValueError",
"(",
"'block_size must be an integer.'",
")",
"return",
"space_to_depth",
"(",
"operand",
",",
"block_size",
",",
"name",
")"
] | https://github.com/microsoft/CNTK/blob/e9396480025b9ca457d26b6f33dd07c474c6aa04/bindings/python/cntk/ops/__init__.py#L4031-L4075 | |
rodeofx/OpenWalter | 6116fbe3f04f1146c854afbfbdbe944feaee647e | walter/common/walterWidgets/walterBaseTreeView.py | python | BaseModel.rowCount | (self, parent=QtCore.QModelIndex()) | return item.childCount() | The number of rows under the given parent. | The number of rows under the given parent. | [
"The",
"number",
"of",
"rows",
"under",
"the",
"given",
"parent",
"."
] | def rowCount(self, parent=QtCore.QModelIndex()):
"""The number of rows under the given parent."""
if parent.column() > 0:
return 0
if not parent.isValid():
item = self.rootItem
else:
item = parent.internalPointer()
if not item:
return 0
return item.childCount() | [
"def",
"rowCount",
"(",
"self",
",",
"parent",
"=",
"QtCore",
".",
"QModelIndex",
"(",
")",
")",
":",
"if",
"parent",
".",
"column",
"(",
")",
">",
"0",
":",
"return",
"0",
"if",
"not",
"parent",
".",
"isValid",
"(",
")",
":",
"item",
"=",
"self",
".",
"rootItem",
"else",
":",
"item",
"=",
"parent",
".",
"internalPointer",
"(",
")",
"if",
"not",
"item",
":",
"return",
"0",
"return",
"item",
".",
"childCount",
"(",
")"
] | https://github.com/rodeofx/OpenWalter/blob/6116fbe3f04f1146c854afbfbdbe944feaee647e/walter/common/walterWidgets/walterBaseTreeView.py#L134-L146 | |
Samsung/veles | 95ed733c2e49bc011ad98ccf2416ecec23fbf352 | veles/external/freetype/__init__.py | python | Face.load_char | (self, char, flags=FT_LOAD_RENDER) | A function used to load a single glyph into the glyph slot of a face
object, according to its character code.
:param char: The glyph's character code, according to the current
charmap used in the face.
:param flags: A flag indicating what to load for this glyph. The
FT_LOAD_XXX constants can be used to control the glyph
loading process (e.g., whether the outline should be
scaled, whether to load bitmaps or not, whether to hint
the outline, etc).
**Note**:
This function simply calls FT_Get_Char_Index and FT_Load_Glyph. | A function used to load a single glyph into the glyph slot of a face
object, according to its character code. | [
"A",
"function",
"used",
"to",
"load",
"a",
"single",
"glyph",
"into",
"the",
"glyph",
"slot",
"of",
"a",
"face",
"object",
"according",
"to",
"its",
"character",
"code",
"."
] | def load_char(self, char, flags=FT_LOAD_RENDER):
'''
A function used to load a single glyph into the glyph slot of a face
object, according to its character code.
:param char: The glyph's character code, according to the current
charmap used in the face.
:param flags: A flag indicating what to load for this glyph. The
FT_LOAD_XXX constants can be used to control the glyph
loading process (e.g., whether the outline should be
scaled, whether to load bitmaps or not, whether to hint
the outline, etc).
**Note**:
This function simply calls FT_Get_Char_Index and FT_Load_Glyph.
'''
if len(char) == 1:
char = ord(char)
error = FT_Load_Char(self._FT_Face, char, flags)
if error: raise FT_Exception(error) | [
"def",
"load_char",
"(",
"self",
",",
"char",
",",
"flags",
"=",
"FT_LOAD_RENDER",
")",
":",
"if",
"len",
"(",
"char",
")",
"==",
"1",
":",
"char",
"=",
"ord",
"(",
"char",
")",
"error",
"=",
"FT_Load_Char",
"(",
"self",
".",
"_FT_Face",
",",
"char",
",",
"flags",
")",
"if",
"error",
":",
"raise",
"FT_Exception",
"(",
"error",
")"
] | https://github.com/Samsung/veles/blob/95ed733c2e49bc011ad98ccf2416ecec23fbf352/veles/external/freetype/__init__.py#L1283-L1305 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/ragged/ragged_concat_ops.py | python | stack | (values, axis=0, name=None) | Stacks a list of rank-`R` tensors into one rank-`(R+1)` `RaggedTensor`.
Given a list of tensors or ragged tensors with the same rank `R`
(`R >= axis`), returns a rank-`R+1` `RaggedTensor` `result` such that
`result[i0...iaxis]` is `[value[i0...iaxis] for value in values]`.
#### Example:
```python
>>> t1 = tf.ragged.constant([[1, 2], [3, 4, 5]])
>>> t2 = tf.ragged.constant([[6], [7, 8, 9]])
>>> tf.ragged.stack([t1, t2], axis=0)
[[[1, 2], [3, 4, 5]], [[6], [7, 9, 0]]]
>>> tf.ragged.stack([t1, t2], axis=1)
[[[1, 2], [6]], [[3, 4, 5], [7, 8, 9]]]
```
Args:
values: A list of `tf.Tensor` or `tf.RaggedTensor`. May not be empty. All
`values` must have the same rank and the same dtype; but unlike
`tf.stack`, they can have arbitrary dimension sizes.
axis: A python integer, indicating the dimension along which to stack.
(Note: Unlike `tf.stack`, the `axis` parameter must be statically known.)
Negative values are supported only if the rank of at least one
`values` value is statically known.
name: A name prefix for the returned tensor (optional).
Returns:
A `RaggedTensor` with rank `R+1`.
`result.ragged_rank=1+max(axis, max(rt.ragged_rank for rt in values]))`.
Raises:
ValueError: If `values` is empty, if `axis` is out of bounds or if
the input tensors have different ranks. | Stacks a list of rank-`R` tensors into one rank-`(R+1)` `RaggedTensor`. | [
"Stacks",
"a",
"list",
"of",
"rank",
"-",
"R",
"tensors",
"into",
"one",
"rank",
"-",
"(",
"R",
"+",
"1",
")",
"RaggedTensor",
"."
] | def stack(values, axis=0, name=None):
"""Stacks a list of rank-`R` tensors into one rank-`(R+1)` `RaggedTensor`.
Given a list of tensors or ragged tensors with the same rank `R`
(`R >= axis`), returns a rank-`R+1` `RaggedTensor` `result` such that
`result[i0...iaxis]` is `[value[i0...iaxis] for value in values]`.
#### Example:
```python
>>> t1 = tf.ragged.constant([[1, 2], [3, 4, 5]])
>>> t2 = tf.ragged.constant([[6], [7, 8, 9]])
>>> tf.ragged.stack([t1, t2], axis=0)
[[[1, 2], [3, 4, 5]], [[6], [7, 9, 0]]]
>>> tf.ragged.stack([t1, t2], axis=1)
[[[1, 2], [6]], [[3, 4, 5], [7, 8, 9]]]
```
Args:
values: A list of `tf.Tensor` or `tf.RaggedTensor`. May not be empty. All
`values` must have the same rank and the same dtype; but unlike
`tf.stack`, they can have arbitrary dimension sizes.
axis: A python integer, indicating the dimension along which to stack.
(Note: Unlike `tf.stack`, the `axis` parameter must be statically known.)
Negative values are supported only if the rank of at least one
`values` value is statically known.
name: A name prefix for the returned tensor (optional).
Returns:
A `RaggedTensor` with rank `R+1`.
`result.ragged_rank=1+max(axis, max(rt.ragged_rank for rt in values]))`.
Raises:
ValueError: If `values` is empty, if `axis` is out of bounds or if
the input tensors have different ranks.
"""
if not isinstance(values, (list, tuple)):
values = [values]
with ops.name_scope(name, 'RaggedConcat', values):
return _ragged_stack_concat_helper(values, axis, stack_values=True) | [
"def",
"stack",
"(",
"values",
",",
"axis",
"=",
"0",
",",
"name",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"values",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"values",
"=",
"[",
"values",
"]",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"'RaggedConcat'",
",",
"values",
")",
":",
"return",
"_ragged_stack_concat_helper",
"(",
"values",
",",
"axis",
",",
"stack_values",
"=",
"True",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/ragged/ragged_concat_ops.py#L75-L113 | ||
mapsme/omim | 1892903b63f2c85b16ed4966d21fe76aba06b9ba | 3party/freetype/src/tools/docmaker/content.py | python | DocBlock.get_markup | ( self, tag_name ) | return None | Return the DocMarkup corresponding to a given tag in a block. | Return the DocMarkup corresponding to a given tag in a block. | [
"Return",
"the",
"DocMarkup",
"corresponding",
"to",
"a",
"given",
"tag",
"in",
"a",
"block",
"."
] | def get_markup( self, tag_name ):
"""Return the DocMarkup corresponding to a given tag in a block."""
for m in self.markups:
if m.tag == string.lower( tag_name ):
return m
return None | [
"def",
"get_markup",
"(",
"self",
",",
"tag_name",
")",
":",
"for",
"m",
"in",
"self",
".",
"markups",
":",
"if",
"m",
".",
"tag",
"==",
"string",
".",
"lower",
"(",
"tag_name",
")",
":",
"return",
"m",
"return",
"None"
] | https://github.com/mapsme/omim/blob/1892903b63f2c85b16ed4966d21fe76aba06b9ba/3party/freetype/src/tools/docmaker/content.py#L598-L603 | |
faasm/faasm | b3bc196d887adbd0bb9802bcb93323543bad59cb | faasmcli/faasmcli/tasks/redis.py | python | clear_queue | (ctx, local=False, docker=False, knative=True) | Clear the message queue in Redis | Clear the message queue in Redis | [
"Clear",
"the",
"message",
"queue",
"in",
"Redis"
] | def clear_queue(ctx, local=False, docker=False, knative=True):
"""
Clear the message queue in Redis
"""
_do_redis_command("flushall", local, docker, knative) | [
"def",
"clear_queue",
"(",
"ctx",
",",
"local",
"=",
"False",
",",
"docker",
"=",
"False",
",",
"knative",
"=",
"True",
")",
":",
"_do_redis_command",
"(",
"\"flushall\"",
",",
"local",
",",
"docker",
",",
"knative",
")"
] | https://github.com/faasm/faasm/blob/b3bc196d887adbd0bb9802bcb93323543bad59cb/faasmcli/faasmcli/tasks/redis.py#L36-L40 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqt/mantidqt/widgets/samplelogs/presenter.py | python | SampleLogs.log_changed | (self) | Update interface aspects | Update interface aspects | [
"Update",
"interface",
"aspects"
] | def log_changed(self):
"""Update interface aspects
"""
#determine if any of the logs might support filtering
are_any_logs_filtered = False
for row in self.view.get_selected_row_indexes():
if self.model.get_is_log_filtered(self.view.get_row_log_name(row)):
are_any_logs_filtered = True
break
self.view.set_log_controls(are_any_logs_filtered) | [
"def",
"log_changed",
"(",
"self",
")",
":",
"#determine if any of the logs might support filtering",
"are_any_logs_filtered",
"=",
"False",
"for",
"row",
"in",
"self",
".",
"view",
".",
"get_selected_row_indexes",
"(",
")",
":",
"if",
"self",
".",
"model",
".",
"get_is_log_filtered",
"(",
"self",
".",
"view",
".",
"get_row_log_name",
"(",
"row",
")",
")",
":",
"are_any_logs_filtered",
"=",
"True",
"break",
"self",
".",
"view",
".",
"set_log_controls",
"(",
"are_any_logs_filtered",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/widgets/samplelogs/presenter.py#L45-L54 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/signal/waveforms.py | python | gausspulse | (t, fc=1000, bw=0.5, bwr=-6, tpr=-60, retquad=False,
retenv=False) | Return a Gaussian modulated sinusoid:
``exp(-a t^2) exp(1j*2*pi*fc*t).``
If `retquad` is True, then return the real and imaginary parts
(in-phase and quadrature).
If `retenv` is True, then return the envelope (unmodulated signal).
Otherwise, return the real part of the modulated sinusoid.
Parameters
----------
t : ndarray or the string 'cutoff'
Input array.
fc : int, optional
Center frequency (e.g. Hz). Default is 1000.
bw : float, optional
Fractional bandwidth in frequency domain of pulse (e.g. Hz).
Default is 0.5.
bwr : float, optional
Reference level at which fractional bandwidth is calculated (dB).
Default is -6.
tpr : float, optional
If `t` is 'cutoff', then the function returns the cutoff
time for when the pulse amplitude falls below `tpr` (in dB).
Default is -60.
retquad : bool, optional
If True, return the quadrature (imaginary) as well as the real part
of the signal. Default is False.
retenv : bool, optional
If True, return the envelope of the signal. Default is False.
Returns
-------
yI : ndarray
Real part of signal. Always returned.
yQ : ndarray
Imaginary part of signal. Only returned if `retquad` is True.
yenv : ndarray
Envelope of signal. Only returned if `retenv` is True.
See Also
--------
scipy.signal.morlet
Examples
--------
Plot real component, imaginary component, and envelope for a 5 Hz pulse,
sampled at 100 Hz for 2 seconds:
>>> from scipy import signal
>>> import matplotlib.pyplot as plt
>>> t = np.linspace(-1, 1, 2 * 100, endpoint=False)
>>> i, q, e = signal.gausspulse(t, fc=5, retquad=True, retenv=True)
>>> plt.plot(t, i, t, q, t, e, '--') | Return a Gaussian modulated sinusoid: | [
"Return",
"a",
"Gaussian",
"modulated",
"sinusoid",
":"
] | def gausspulse(t, fc=1000, bw=0.5, bwr=-6, tpr=-60, retquad=False,
retenv=False):
"""
Return a Gaussian modulated sinusoid:
``exp(-a t^2) exp(1j*2*pi*fc*t).``
If `retquad` is True, then return the real and imaginary parts
(in-phase and quadrature).
If `retenv` is True, then return the envelope (unmodulated signal).
Otherwise, return the real part of the modulated sinusoid.
Parameters
----------
t : ndarray or the string 'cutoff'
Input array.
fc : int, optional
Center frequency (e.g. Hz). Default is 1000.
bw : float, optional
Fractional bandwidth in frequency domain of pulse (e.g. Hz).
Default is 0.5.
bwr : float, optional
Reference level at which fractional bandwidth is calculated (dB).
Default is -6.
tpr : float, optional
If `t` is 'cutoff', then the function returns the cutoff
time for when the pulse amplitude falls below `tpr` (in dB).
Default is -60.
retquad : bool, optional
If True, return the quadrature (imaginary) as well as the real part
of the signal. Default is False.
retenv : bool, optional
If True, return the envelope of the signal. Default is False.
Returns
-------
yI : ndarray
Real part of signal. Always returned.
yQ : ndarray
Imaginary part of signal. Only returned if `retquad` is True.
yenv : ndarray
Envelope of signal. Only returned if `retenv` is True.
See Also
--------
scipy.signal.morlet
Examples
--------
Plot real component, imaginary component, and envelope for a 5 Hz pulse,
sampled at 100 Hz for 2 seconds:
>>> from scipy import signal
>>> import matplotlib.pyplot as plt
>>> t = np.linspace(-1, 1, 2 * 100, endpoint=False)
>>> i, q, e = signal.gausspulse(t, fc=5, retquad=True, retenv=True)
>>> plt.plot(t, i, t, q, t, e, '--')
"""
if fc < 0:
raise ValueError("Center frequency (fc=%.2f) must be >=0." % fc)
if bw <= 0:
raise ValueError("Fractional bandwidth (bw=%.2f) must be > 0." % bw)
if bwr >= 0:
raise ValueError("Reference level for bandwidth (bwr=%.2f) must "
"be < 0 dB" % bwr)
# exp(-a t^2) <-> sqrt(pi/a) exp(-pi^2/a * f^2) = g(f)
ref = pow(10.0, bwr / 20.0)
# fdel = fc*bw/2: g(fdel) = ref --- solve this for a
#
# pi^2/a * fc^2 * bw^2 /4=-log(ref)
a = -(pi * fc * bw) ** 2 / (4.0 * log(ref))
if isinstance(t, string_types):
if t == 'cutoff': # compute cut_off point
# Solve exp(-a tc**2) = tref for tc
# tc = sqrt(-log(tref) / a) where tref = 10^(tpr/20)
if tpr >= 0:
raise ValueError("Reference level for time cutoff must "
"be < 0 dB")
tref = pow(10.0, tpr / 20.0)
return sqrt(-log(tref) / a)
else:
raise ValueError("If `t` is a string, it must be 'cutoff'")
yenv = exp(-a * t * t)
yI = yenv * cos(2 * pi * fc * t)
yQ = yenv * sin(2 * pi * fc * t)
if not retquad and not retenv:
return yI
if not retquad and retenv:
return yI, yenv
if retquad and not retenv:
return yI, yQ
if retquad and retenv:
return yI, yQ, yenv | [
"def",
"gausspulse",
"(",
"t",
",",
"fc",
"=",
"1000",
",",
"bw",
"=",
"0.5",
",",
"bwr",
"=",
"-",
"6",
",",
"tpr",
"=",
"-",
"60",
",",
"retquad",
"=",
"False",
",",
"retenv",
"=",
"False",
")",
":",
"if",
"fc",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"Center frequency (fc=%.2f) must be >=0.\"",
"%",
"fc",
")",
"if",
"bw",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"\"Fractional bandwidth (bw=%.2f) must be > 0.\"",
"%",
"bw",
")",
"if",
"bwr",
">=",
"0",
":",
"raise",
"ValueError",
"(",
"\"Reference level for bandwidth (bwr=%.2f) must \"",
"\"be < 0 dB\"",
"%",
"bwr",
")",
"# exp(-a t^2) <-> sqrt(pi/a) exp(-pi^2/a * f^2) = g(f)",
"ref",
"=",
"pow",
"(",
"10.0",
",",
"bwr",
"/",
"20.0",
")",
"# fdel = fc*bw/2: g(fdel) = ref --- solve this for a",
"#",
"# pi^2/a * fc^2 * bw^2 /4=-log(ref)",
"a",
"=",
"-",
"(",
"pi",
"*",
"fc",
"*",
"bw",
")",
"**",
"2",
"/",
"(",
"4.0",
"*",
"log",
"(",
"ref",
")",
")",
"if",
"isinstance",
"(",
"t",
",",
"string_types",
")",
":",
"if",
"t",
"==",
"'cutoff'",
":",
"# compute cut_off point",
"# Solve exp(-a tc**2) = tref for tc",
"# tc = sqrt(-log(tref) / a) where tref = 10^(tpr/20)",
"if",
"tpr",
">=",
"0",
":",
"raise",
"ValueError",
"(",
"\"Reference level for time cutoff must \"",
"\"be < 0 dB\"",
")",
"tref",
"=",
"pow",
"(",
"10.0",
",",
"tpr",
"/",
"20.0",
")",
"return",
"sqrt",
"(",
"-",
"log",
"(",
"tref",
")",
"/",
"a",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"If `t` is a string, it must be 'cutoff'\"",
")",
"yenv",
"=",
"exp",
"(",
"-",
"a",
"*",
"t",
"*",
"t",
")",
"yI",
"=",
"yenv",
"*",
"cos",
"(",
"2",
"*",
"pi",
"*",
"fc",
"*",
"t",
")",
"yQ",
"=",
"yenv",
"*",
"sin",
"(",
"2",
"*",
"pi",
"*",
"fc",
"*",
"t",
")",
"if",
"not",
"retquad",
"and",
"not",
"retenv",
":",
"return",
"yI",
"if",
"not",
"retquad",
"and",
"retenv",
":",
"return",
"yI",
",",
"yenv",
"if",
"retquad",
"and",
"not",
"retenv",
":",
"return",
"yI",
",",
"yQ",
"if",
"retquad",
"and",
"retenv",
":",
"return",
"yI",
",",
"yQ",
",",
"yenv"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/signal/waveforms.py#L165-L262 | ||
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/MooseDocs/extensions/reveal.py | python | RevealExtension._getNodeIDs | (root) | return keys | Return all 'ids' in a node tree. | Return all 'ids' in a node tree. | [
"Return",
"all",
"ids",
"in",
"a",
"node",
"tree",
"."
] | def _getNodeIDs(root):
"""Return all 'ids' in a node tree."""
keys = []
id_ = root.get('id', None)
if id_:
keys.append(id_)
for node in moosetree.iterate(root, method=moosetree.IterMethod.PRE_ORDER):
id_ = node.get('id', None)
if id_:
keys.append(id_)
return keys | [
"def",
"_getNodeIDs",
"(",
"root",
")",
":",
"keys",
"=",
"[",
"]",
"id_",
"=",
"root",
".",
"get",
"(",
"'id'",
",",
"None",
")",
"if",
"id_",
":",
"keys",
".",
"append",
"(",
"id_",
")",
"for",
"node",
"in",
"moosetree",
".",
"iterate",
"(",
"root",
",",
"method",
"=",
"moosetree",
".",
"IterMethod",
".",
"PRE_ORDER",
")",
":",
"id_",
"=",
"node",
".",
"get",
"(",
"'id'",
",",
"None",
")",
"if",
"id_",
":",
"keys",
".",
"append",
"(",
"id_",
")",
"return",
"keys"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/MooseDocs/extensions/reveal.py#L119-L131 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/logging/handlers.py | python | QueueHandler.enqueue | (self, record) | Enqueue a record.
The base implementation uses put_nowait. You may want to override
this method if you want to use blocking, timeouts or custom queue
implementations. | Enqueue a record. | [
"Enqueue",
"a",
"record",
"."
] | def enqueue(self, record):
"""
Enqueue a record.
The base implementation uses put_nowait. You may want to override
this method if you want to use blocking, timeouts or custom queue
implementations.
"""
self.queue.put_nowait(record) | [
"def",
"enqueue",
"(",
"self",
",",
"record",
")",
":",
"self",
".",
"queue",
".",
"put_nowait",
"(",
"record",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/logging/handlers.py#L1351-L1359 | ||
moderngl/moderngl | 32fe79927e02b0fa893b3603d677bdae39771e14 | moderngl/program_members/varying.py | python | Varying.number | (self) | return self._number | int: The number of the varying. | int: The number of the varying. | [
"int",
":",
"The",
"number",
"of",
"the",
"varying",
"."
] | def number(self) -> int:
'''
int: The number of the varying.
'''
return self._number | [
"def",
"number",
"(",
"self",
")",
"->",
"int",
":",
"return",
"self",
".",
"_number"
] | https://github.com/moderngl/moderngl/blob/32fe79927e02b0fa893b3603d677bdae39771e14/moderngl/program_members/varying.py#L26-L31 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/directconnect/layer1.py | python | DirectConnectConnection.describe_connections_on_interconnect | (self, interconnect_id) | return self.make_request(action='DescribeConnectionsOnInterconnect',
body=json.dumps(params)) | Return a list of connections that have been provisioned on the
given interconnect.
:type interconnect_id: string
:param interconnect_id: ID of the interconnect on which a list of
connection is provisioned.
Example: dxcon-abc123
Default: None | Return a list of connections that have been provisioned on the
given interconnect. | [
"Return",
"a",
"list",
"of",
"connections",
"that",
"have",
"been",
"provisioned",
"on",
"the",
"given",
"interconnect",
"."
] | def describe_connections_on_interconnect(self, interconnect_id):
"""
Return a list of connections that have been provisioned on the
given interconnect.
:type interconnect_id: string
:param interconnect_id: ID of the interconnect on which a list of
connection is provisioned.
Example: dxcon-abc123
Default: None
"""
params = {'interconnectId': interconnect_id, }
return self.make_request(action='DescribeConnectionsOnInterconnect',
body=json.dumps(params)) | [
"def",
"describe_connections_on_interconnect",
"(",
"self",
",",
"interconnect_id",
")",
":",
"params",
"=",
"{",
"'interconnectId'",
":",
"interconnect_id",
",",
"}",
"return",
"self",
".",
"make_request",
"(",
"action",
"=",
"'DescribeConnectionsOnInterconnect'",
",",
"body",
"=",
"json",
".",
"dumps",
"(",
"params",
")",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/directconnect/layer1.py#L506-L521 | |
brave/brave-core | ceaa3de4735789d355b6fa80c21d4709e2c1d0e8 | build/ios/mojom/mojom_objc_generator.py | python | Generator._ObjCEnumFormatter | (self, value) | return UnderToCamel(name) | Formats uppercased, k-prefixed & snake case to upper camel case | Formats uppercased, k-prefixed & snake case to upper camel case | [
"Formats",
"uppercased",
"k",
"-",
"prefixed",
"&",
"snake",
"case",
"to",
"upper",
"camel",
"case"
] | def _ObjCEnumFormatter(self, value):
""" Formats uppercased, k-prefixed & snake case to upper camel case """
name = value
if len(value) >= 2 and value[0] == "k" and value[1].isupper():
# k-prefixed
name = value[1:]
return UnderToCamel(name) | [
"def",
"_ObjCEnumFormatter",
"(",
"self",
",",
"value",
")",
":",
"name",
"=",
"value",
"if",
"len",
"(",
"value",
")",
">=",
"2",
"and",
"value",
"[",
"0",
"]",
"==",
"\"k\"",
"and",
"value",
"[",
"1",
"]",
".",
"isupper",
"(",
")",
":",
"# k-prefixed",
"name",
"=",
"value",
"[",
"1",
":",
"]",
"return",
"UnderToCamel",
"(",
"name",
")"
] | https://github.com/brave/brave-core/blob/ceaa3de4735789d355b6fa80c21d4709e2c1d0e8/build/ios/mojom/mojom_objc_generator.py#L476-L482 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/plotting/_matplotlib/style.py | python | _is_single_string_color | (color: Color) | Check if `color` is a single string color.
Examples of single string colors:
- 'r'
- 'g'
- 'red'
- 'green'
- 'C3'
- 'firebrick'
Parameters
----------
color : Color
Color string or sequence of floats.
Returns
-------
bool
True if `color` looks like a valid color.
False otherwise. | Check if `color` is a single string color. | [
"Check",
"if",
"color",
"is",
"a",
"single",
"string",
"color",
"."
] | def _is_single_string_color(color: Color) -> bool:
"""Check if `color` is a single string color.
Examples of single string colors:
- 'r'
- 'g'
- 'red'
- 'green'
- 'C3'
- 'firebrick'
Parameters
----------
color : Color
Color string or sequence of floats.
Returns
-------
bool
True if `color` looks like a valid color.
False otherwise.
"""
conv = matplotlib.colors.ColorConverter()
try:
conv.to_rgba(color)
except ValueError:
return False
else:
return True | [
"def",
"_is_single_string_color",
"(",
"color",
":",
"Color",
")",
"->",
"bool",
":",
"conv",
"=",
"matplotlib",
".",
"colors",
".",
"ColorConverter",
"(",
")",
"try",
":",
"conv",
".",
"to_rgba",
"(",
"color",
")",
"except",
"ValueError",
":",
"return",
"False",
"else",
":",
"return",
"True"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/plotting/_matplotlib/style.py#L247-L275 | ||
neoml-lib/neoml | a0d370fba05269a1b2258cef126f77bbd2054a3e | NeoML/Python/neoml/DifferentialEvolution.py | python | BaseTraits.mutate | (self, base, left, right, fluctuation, min_value, max_value) | Performs mutation for the differential evolution algorithm.
:param base: a member of the original population.
:type base: any type
:param left: another member of the original population.
:type left: any type
:param right: another member of the original population.
:type right: any type
:param fluctuation: the coefficient for mutation.
:type fluctuation: any type
:param min_value: the lower bound for the mutated value.
:type min_value: any type
:param max_value: the upper bound for the mutated value.
:type max_value: any type | Performs mutation for the differential evolution algorithm. | [
"Performs",
"mutation",
"for",
"the",
"differential",
"evolution",
"algorithm",
"."
] | def mutate(self, base, left, right, fluctuation, min_value, max_value):
"""Performs mutation for the differential evolution algorithm.
:param base: a member of the original population.
:type base: any type
:param left: another member of the original population.
:type left: any type
:param right: another member of the original population.
:type right: any type
:param fluctuation: the coefficient for mutation.
:type fluctuation: any type
:param min_value: the lower bound for the mutated value.
:type min_value: any type
:param max_value: the upper bound for the mutated value.
:type max_value: any type
""" | [
"def",
"mutate",
"(",
"self",
",",
"base",
",",
"left",
",",
"right",
",",
"fluctuation",
",",
"min_value",
",",
"max_value",
")",
":"
] | https://github.com/neoml-lib/neoml/blob/a0d370fba05269a1b2258cef126f77bbd2054a3e/NeoML/Python/neoml/DifferentialEvolution.py#L49-L69 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/Diffraction/isis_powder/hrpd.py | python | HRPD._mask_prompt_pulses | (self, ws) | HRPD has a long flight path from the moderator resulting
in sharp peaks from the proton pulse that maintain their
sharp resolution. Here we mask these pulses out that occur
at 20ms intervals.
:param ws: The workspace containing the pulses. It is
masked in place. | HRPD has a long flight path from the moderator resulting
in sharp peaks from the proton pulse that maintain their
sharp resolution. Here we mask these pulses out that occur
at 20ms intervals. | [
"HRPD",
"has",
"a",
"long",
"flight",
"path",
"from",
"the",
"moderator",
"resulting",
"in",
"sharp",
"peaks",
"from",
"the",
"proton",
"pulse",
"that",
"maintain",
"their",
"sharp",
"resolution",
".",
"Here",
"we",
"mask",
"these",
"pulses",
"out",
"that",
"occur",
"at",
"20ms",
"intervals",
"."
] | def _mask_prompt_pulses(self, ws):
"""
HRPD has a long flight path from the moderator resulting
in sharp peaks from the proton pulse that maintain their
sharp resolution. Here we mask these pulses out that occur
at 20ms intervals.
:param ws: The workspace containing the pulses. It is
masked in place.
"""
# The number of pulse can vary depending on the data range
# Compute number of pulses that occur at each 20ms interval.
x_data = ws.readX(0)
pulse_min = int(round(x_data[0]) / PROMPT_PULSE_INTERVAL) + 1
pulse_max = int(round(x_data[-1]) / PROMPT_PULSE_INTERVAL) + 1
for i in range(pulse_min, pulse_max):
centre = PROMPT_PULSE_INTERVAL * float(i)
mantid.MaskBins(InputWorkspace=ws, OutputWorkspace=ws,
XMin=centre - PROMPT_PULSE_LEFT_WIDTH,
XMax=centre + PROMPT_PULSE_RIGHT_WIDTH) | [
"def",
"_mask_prompt_pulses",
"(",
"self",
",",
"ws",
")",
":",
"# The number of pulse can vary depending on the data range",
"# Compute number of pulses that occur at each 20ms interval.",
"x_data",
"=",
"ws",
".",
"readX",
"(",
"0",
")",
"pulse_min",
"=",
"int",
"(",
"round",
"(",
"x_data",
"[",
"0",
"]",
")",
"/",
"PROMPT_PULSE_INTERVAL",
")",
"+",
"1",
"pulse_max",
"=",
"int",
"(",
"round",
"(",
"x_data",
"[",
"-",
"1",
"]",
")",
"/",
"PROMPT_PULSE_INTERVAL",
")",
"+",
"1",
"for",
"i",
"in",
"range",
"(",
"pulse_min",
",",
"pulse_max",
")",
":",
"centre",
"=",
"PROMPT_PULSE_INTERVAL",
"*",
"float",
"(",
"i",
")",
"mantid",
".",
"MaskBins",
"(",
"InputWorkspace",
"=",
"ws",
",",
"OutputWorkspace",
"=",
"ws",
",",
"XMin",
"=",
"centre",
"-",
"PROMPT_PULSE_LEFT_WIDTH",
",",
"XMax",
"=",
"centre",
"+",
"PROMPT_PULSE_RIGHT_WIDTH",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/Diffraction/isis_powder/hrpd.py#L161-L180 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_gdi.py | python | Pen.GetDashCount | (*args, **kwargs) | return _gdi_.Pen_GetDashCount(*args, **kwargs) | GetDashCount(self) -> int | GetDashCount(self) -> int | [
"GetDashCount",
"(",
"self",
")",
"-",
">",
"int"
] | def GetDashCount(*args, **kwargs):
"""GetDashCount(self) -> int"""
return _gdi_.Pen_GetDashCount(*args, **kwargs) | [
"def",
"GetDashCount",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"Pen_GetDashCount",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L463-L465 | |
MegEngine/MegEngine | ce9ad07a27ec909fb8db4dd67943d24ba98fb93a | imperative/python/megengine/distributed/server.py | python | Client.set_is_grad | (self, key, is_grad) | r"""Mark send/recv need gradiants by key.
Args:
key: key to match send/recv op.
is_grad: whether this op need grad. | r"""Mark send/recv need gradiants by key. | [
"r",
"Mark",
"send",
"/",
"recv",
"need",
"gradiants",
"by",
"key",
"."
] | def set_is_grad(self, key, is_grad):
r"""Mark send/recv need gradiants by key.
Args:
key: key to match send/recv op.
is_grad: whether this op need grad.
"""
self.proxy.set_is_grad(key, is_grad) | [
"def",
"set_is_grad",
"(",
"self",
",",
"key",
",",
"is_grad",
")",
":",
"self",
".",
"proxy",
".",
"set_is_grad",
"(",
"key",
",",
"is_grad",
")"
] | https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/distributed/server.py#L236-L243 | ||
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBBreakpointList.Clear | (self) | return _lldb.SBBreakpointList_Clear(self) | Clear(SBBreakpointList self) | Clear(SBBreakpointList self) | [
"Clear",
"(",
"SBBreakpointList",
"self",
")"
] | def Clear(self):
"""Clear(SBBreakpointList self)"""
return _lldb.SBBreakpointList_Clear(self) | [
"def",
"Clear",
"(",
"self",
")",
":",
"return",
"_lldb",
".",
"SBBreakpointList_Clear",
"(",
"self",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L1926-L1928 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_misc.py | python | Display.IsOk | (*args, **kwargs) | return _misc_.Display_IsOk(*args, **kwargs) | IsOk(self) -> bool
Return true if the object was initialized successfully | IsOk(self) -> bool | [
"IsOk",
"(",
"self",
")",
"-",
">",
"bool"
] | def IsOk(*args, **kwargs):
"""
IsOk(self) -> bool
Return true if the object was initialized successfully
"""
return _misc_.Display_IsOk(*args, **kwargs) | [
"def",
"IsOk",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"Display_IsOk",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L6121-L6127 | |
PixarAnimationStudios/USD | faed18ce62c8736b02413635b584a2f637156bad | pxr/usdImaging/usdviewq/selectionDataModel.py | python | SelectionDataModel.addComputedPropPath | (self, primPath, propName) | Add a computed property to the selection. | Add a computed property to the selection. | [
"Add",
"a",
"computed",
"property",
"to",
"the",
"selection",
"."
] | def addComputedPropPath(self, primPath, propName):
"""Add a computed property to the selection."""
primPath = self._ensureValidPrimPath(primPath)
self._validateComputedPropName(propName)
self._computedPropSelection.addPropPath(primPath, propName)
self._computedPropSelectionChanged() | [
"def",
"addComputedPropPath",
"(",
"self",
",",
"primPath",
",",
"propName",
")",
":",
"primPath",
"=",
"self",
".",
"_ensureValidPrimPath",
"(",
"primPath",
")",
"self",
".",
"_validateComputedPropName",
"(",
"propName",
")",
"self",
".",
"_computedPropSelection",
".",
"addPropPath",
"(",
"primPath",
",",
"propName",
")",
"self",
".",
"_computedPropSelectionChanged",
"(",
")"
] | https://github.com/PixarAnimationStudios/USD/blob/faed18ce62c8736b02413635b584a2f637156bad/pxr/usdImaging/usdviewq/selectionDataModel.py#L973-L980 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/dateutil/tz/win.py | python | valuestodict | (key) | return dout | Convert a registry key's values to a dictionary. | Convert a registry key's values to a dictionary. | [
"Convert",
"a",
"registry",
"key",
"s",
"values",
"to",
"a",
"dictionary",
"."
] | def valuestodict(key):
"""Convert a registry key's values to a dictionary."""
dout = {}
size = winreg.QueryInfoKey(key)[1]
tz_res = None
for i in range(size):
key_name, value, dtype = winreg.EnumValue(key, i)
if dtype == winreg.REG_DWORD or dtype == winreg.REG_DWORD_LITTLE_ENDIAN:
# If it's a DWORD (32-bit integer), it's stored as unsigned - convert
# that to a proper signed integer
if value & (1 << 31):
value = value - (1 << 32)
elif dtype == winreg.REG_SZ:
# If it's a reference to the tzres DLL, load the actual string
if value.startswith('@tzres'):
tz_res = tz_res or tzres()
value = tz_res.name_from_string(value)
value = value.rstrip('\x00') # Remove trailing nulls
dout[key_name] = value
return dout | [
"def",
"valuestodict",
"(",
"key",
")",
":",
"dout",
"=",
"{",
"}",
"size",
"=",
"winreg",
".",
"QueryInfoKey",
"(",
"key",
")",
"[",
"1",
"]",
"tz_res",
"=",
"None",
"for",
"i",
"in",
"range",
"(",
"size",
")",
":",
"key_name",
",",
"value",
",",
"dtype",
"=",
"winreg",
".",
"EnumValue",
"(",
"key",
",",
"i",
")",
"if",
"dtype",
"==",
"winreg",
".",
"REG_DWORD",
"or",
"dtype",
"==",
"winreg",
".",
"REG_DWORD_LITTLE_ENDIAN",
":",
"# If it's a DWORD (32-bit integer), it's stored as unsigned - convert",
"# that to a proper signed integer",
"if",
"value",
"&",
"(",
"1",
"<<",
"31",
")",
":",
"value",
"=",
"value",
"-",
"(",
"1",
"<<",
"32",
")",
"elif",
"dtype",
"==",
"winreg",
".",
"REG_SZ",
":",
"# If it's a reference to the tzres DLL, load the actual string",
"if",
"value",
".",
"startswith",
"(",
"'@tzres'",
")",
":",
"tz_res",
"=",
"tz_res",
"or",
"tzres",
"(",
")",
"value",
"=",
"tz_res",
".",
"name_from_string",
"(",
"value",
")",
"value",
"=",
"value",
".",
"rstrip",
"(",
"'\\x00'",
")",
"# Remove trailing nulls",
"dout",
"[",
"key_name",
"]",
"=",
"value",
"return",
"dout"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/dateutil/tz/win.py#L347-L370 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/mailbox.py | python | _mboxMMDFMessage.remove_flag | (self, flag) | Unset the given string flag(s) without changing others. | Unset the given string flag(s) without changing others. | [
"Unset",
"the",
"given",
"string",
"flag",
"(",
"s",
")",
"without",
"changing",
"others",
"."
] | def remove_flag(self, flag):
"""Unset the given string flag(s) without changing others."""
if 'Status' in self or 'X-Status' in self:
self.set_flags(''.join(set(self.get_flags()) - set(flag))) | [
"def",
"remove_flag",
"(",
"self",
",",
"flag",
")",
":",
"if",
"'Status'",
"in",
"self",
"or",
"'X-Status'",
"in",
"self",
":",
"self",
".",
"set_flags",
"(",
"''",
".",
"join",
"(",
"set",
"(",
"self",
".",
"get_flags",
"(",
")",
")",
"-",
"set",
"(",
"flag",
")",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/mailbox.py#L1691-L1694 | ||
facebookarchive/LogDevice | ce7726050edc49a1e15d9160e81c890736b779e2 | logdevice/ops/ldshell/autoload/commands/status.py | python | status | (
format="tabular",
sort="node_id",
nodes=None,
hosts=None,
hostnames=None,
extended=False,
force: bool = False,
) | Next gen status command using the Thrift interfaces | Next gen status command using the Thrift interfaces | [
"Next",
"gen",
"status",
"command",
"using",
"the",
"Thrift",
"interfaces"
] | async def status(
format="tabular",
sort="node_id",
nodes=None,
hosts=None,
hostnames=None,
extended=False,
force: bool = False,
):
"""
Next gen status command using the Thrift interfaces
"""
hostnames = set(chain.from_iterable((hostnames or [], hosts or [])))
await additional_validation() # pyre-ignore
start = datetime.datetime.now()
await run_status(
nodes=nodes,
hostnames=hostnames,
extended=extended,
formatter=FORMATTERS[format],
force=force,
sort=sort,
)
stop = datetime.datetime.now()
duration = int((stop - start).total_seconds() * 1000)
print(f"Took {duration}ms", file=sys.stderr) | [
"async",
"def",
"status",
"(",
"format",
"=",
"\"tabular\"",
",",
"sort",
"=",
"\"node_id\"",
",",
"nodes",
"=",
"None",
",",
"hosts",
"=",
"None",
",",
"hostnames",
"=",
"None",
",",
"extended",
"=",
"False",
",",
"force",
":",
"bool",
"=",
"False",
",",
")",
":",
"hostnames",
"=",
"set",
"(",
"chain",
".",
"from_iterable",
"(",
"(",
"hostnames",
"or",
"[",
"]",
",",
"hosts",
"or",
"[",
"]",
")",
")",
")",
"await",
"additional_validation",
"(",
")",
"# pyre-ignore",
"start",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"await",
"run_status",
"(",
"nodes",
"=",
"nodes",
",",
"hostnames",
"=",
"hostnames",
",",
"extended",
"=",
"extended",
",",
"formatter",
"=",
"FORMATTERS",
"[",
"format",
"]",
",",
"force",
"=",
"force",
",",
"sort",
"=",
"sort",
",",
")",
"stop",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"duration",
"=",
"int",
"(",
"(",
"stop",
"-",
"start",
")",
".",
"total_seconds",
"(",
")",
"*",
"1000",
")",
"print",
"(",
"f\"Took {duration}ms\"",
",",
"file",
"=",
"sys",
".",
"stderr",
")"
] | https://github.com/facebookarchive/LogDevice/blob/ce7726050edc49a1e15d9160e81c890736b779e2/logdevice/ops/ldshell/autoload/commands/status.py#L505-L534 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/stc.py | python | StyledTextEvent.GetLParam | (*args, **kwargs) | return _stc.StyledTextEvent_GetLParam(*args, **kwargs) | GetLParam(self) -> int | GetLParam(self) -> int | [
"GetLParam",
"(",
"self",
")",
"-",
">",
"int"
] | def GetLParam(*args, **kwargs):
"""GetLParam(self) -> int"""
return _stc.StyledTextEvent_GetLParam(*args, **kwargs) | [
"def",
"GetLParam",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextEvent_GetLParam",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/stc.py#L7174-L7176 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/flatmenu.py | python | FlatMenuButton.GetTimerId | (self) | return self._timerID | Returns the timer object identifier. | Returns the timer object identifier. | [
"Returns",
"the",
"timer",
"object",
"identifier",
"."
] | def GetTimerId(self):
""" Returns the timer object identifier. """
return self._timerID | [
"def",
"GetTimerId",
"(",
"self",
")",
":",
"return",
"self",
".",
"_timerID"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/flatmenu.py#L4070-L4073 | |
JumpingYang001/webrtc | c03d6e965e1f54aeadd670e491eabe5fdb8db968 | tools_webrtc/clang_tidy.py | python | ValidateCC | (filepath) | We can only analyze .cc files. Provide explicit message about that. | We can only analyze .cc files. Provide explicit message about that. | [
"We",
"can",
"only",
"analyze",
".",
"cc",
"files",
".",
"Provide",
"explicit",
"message",
"about",
"that",
"."
] | def ValidateCC(filepath):
"""We can only analyze .cc files. Provide explicit message about that."""
if filepath.endswith('.cc'):
return filepath
msg = ('%s not supported.\n'
'For now, we can only analyze translation units (.cc files).' %
filepath)
raise argparse.ArgumentTypeError(msg) | [
"def",
"ValidateCC",
"(",
"filepath",
")",
":",
"if",
"filepath",
".",
"endswith",
"(",
"'.cc'",
")",
":",
"return",
"filepath",
"msg",
"=",
"(",
"'%s not supported.\\n'",
"'For now, we can only analyze translation units (.cc files).'",
"%",
"filepath",
")",
"raise",
"argparse",
".",
"ArgumentTypeError",
"(",
"msg",
")"
] | https://github.com/JumpingYang001/webrtc/blob/c03d6e965e1f54aeadd670e491eabe5fdb8db968/tools_webrtc/clang_tidy.py#L70-L77 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/Util/number.py | python | bytes_to_long | (s) | return acc | Convert a byte string to a long integer (big endian).
In Python 3.2+, use the native method instead::
>>> int.from_bytes(s, 'big')
For instance::
>>> int.from_bytes(b'\x00P', 'big')
80
This is (essentially) the inverse of :func:`long_to_bytes`. | Convert a byte string to a long integer (big endian). | [
"Convert",
"a",
"byte",
"string",
"to",
"a",
"long",
"integer",
"(",
"big",
"endian",
")",
"."
] | def bytes_to_long(s):
"""Convert a byte string to a long integer (big endian).
In Python 3.2+, use the native method instead::
>>> int.from_bytes(s, 'big')
For instance::
>>> int.from_bytes(b'\x00P', 'big')
80
This is (essentially) the inverse of :func:`long_to_bytes`.
"""
acc = 0
unpack = struct.unpack
# Up to Python 2.7.4, struct.unpack can't work with bytearrays nor
# memoryviews
if sys.version_info[0:3] < (2, 7, 4):
if isinstance(s, bytearray):
s = bytes(s)
elif isinstance(s, _memoryview):
s = s.tobytes()
length = len(s)
if length % 4:
extra = (4 - length % 4)
s = b'\x00' * extra + s
length = length + extra
for i in range(0, length, 4):
acc = (acc << 32) + unpack('>I', s[i:i+4])[0]
return acc | [
"def",
"bytes_to_long",
"(",
"s",
")",
":",
"acc",
"=",
"0",
"unpack",
"=",
"struct",
".",
"unpack",
"# Up to Python 2.7.4, struct.unpack can't work with bytearrays nor",
"# memoryviews",
"if",
"sys",
".",
"version_info",
"[",
"0",
":",
"3",
"]",
"<",
"(",
"2",
",",
"7",
",",
"4",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"bytearray",
")",
":",
"s",
"=",
"bytes",
"(",
"s",
")",
"elif",
"isinstance",
"(",
"s",
",",
"_memoryview",
")",
":",
"s",
"=",
"s",
".",
"tobytes",
"(",
")",
"length",
"=",
"len",
"(",
"s",
")",
"if",
"length",
"%",
"4",
":",
"extra",
"=",
"(",
"4",
"-",
"length",
"%",
"4",
")",
"s",
"=",
"b'\\x00'",
"*",
"extra",
"+",
"s",
"length",
"=",
"length",
"+",
"extra",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"length",
",",
"4",
")",
":",
"acc",
"=",
"(",
"acc",
"<<",
"32",
")",
"+",
"unpack",
"(",
"'>I'",
",",
"s",
"[",
"i",
":",
"i",
"+",
"4",
"]",
")",
"[",
"0",
"]",
"return",
"acc"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/Util/number.py#L416-L449 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/ops/control_flow_ops.py | python | GradLoopState.outer_grad_state | (self) | return self._outer_grad_state | The grad loop state for outer loop. | The grad loop state for outer loop. | [
"The",
"grad",
"loop",
"state",
"for",
"outer",
"loop",
"."
] | def outer_grad_state(self):
"""The grad loop state for outer loop."""
return self._outer_grad_state | [
"def",
"outer_grad_state",
"(",
"self",
")",
":",
"return",
"self",
".",
"_outer_grad_state"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/control_flow_ops.py#L561-L563 | |
s9xie/hed | 94fb22f10cbfec8d84fbc0642b224022014b6bd6 | scripts/cpp_lint.py | python | ReplaceAll | (pattern, rep, s) | return _regexp_compile_cache[pattern].sub(rep, s) | Replaces instances of pattern in a string with a replacement.
The compiled regex is kept in a cache shared by Match and Search.
Args:
pattern: regex pattern
rep: replacement text
s: search string
Returns:
string with replacements made (or original string if no replacements) | Replaces instances of pattern in a string with a replacement. | [
"Replaces",
"instances",
"of",
"pattern",
"in",
"a",
"string",
"with",
"a",
"replacement",
"."
] | def ReplaceAll(pattern, rep, s):
"""Replaces instances of pattern in a string with a replacement.
The compiled regex is kept in a cache shared by Match and Search.
Args:
pattern: regex pattern
rep: replacement text
s: search string
Returns:
string with replacements made (or original string if no replacements)
"""
if pattern not in _regexp_compile_cache:
_regexp_compile_cache[pattern] = sre_compile.compile(pattern)
return _regexp_compile_cache[pattern].sub(rep, s) | [
"def",
"ReplaceAll",
"(",
"pattern",
",",
"rep",
",",
"s",
")",
":",
"if",
"pattern",
"not",
"in",
"_regexp_compile_cache",
":",
"_regexp_compile_cache",
"[",
"pattern",
"]",
"=",
"sre_compile",
".",
"compile",
"(",
"pattern",
")",
"return",
"_regexp_compile_cache",
"[",
"pattern",
"]",
".",
"sub",
"(",
"rep",
",",
"s",
")"
] | https://github.com/s9xie/hed/blob/94fb22f10cbfec8d84fbc0642b224022014b6bd6/scripts/cpp_lint.py#L525-L540 | |
protocolbuffers/protobuf | b5ab0b7a18b7336c60130f4ddb2d97c51792f896 | python/google/protobuf/internal/_parameterized.py | python | _ParameterDecorator | (naming_type, testcases) | return _Apply | Implementation of the parameterization decorators.
Args:
naming_type: The naming type.
testcases: Testcase parameters.
Returns:
A function for modifying the decorated object. | Implementation of the parameterization decorators. | [
"Implementation",
"of",
"the",
"parameterization",
"decorators",
"."
] | def _ParameterDecorator(naming_type, testcases):
"""Implementation of the parameterization decorators.
Args:
naming_type: The naming type.
testcases: Testcase parameters.
Returns:
A function for modifying the decorated object.
"""
def _Apply(obj):
if isinstance(obj, type):
_ModifyClass(
obj,
list(testcases) if not isinstance(testcases, collections_abc.Sequence)
else testcases,
naming_type)
return obj
else:
return _ParameterizedTestIter(obj, testcases, naming_type)
if _IsSingletonList(testcases):
assert _NonStringIterable(testcases[0]), (
'Single parameter argument must be a non-string iterable')
testcases = testcases[0]
return _Apply | [
"def",
"_ParameterDecorator",
"(",
"naming_type",
",",
"testcases",
")",
":",
"def",
"_Apply",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"type",
")",
":",
"_ModifyClass",
"(",
"obj",
",",
"list",
"(",
"testcases",
")",
"if",
"not",
"isinstance",
"(",
"testcases",
",",
"collections_abc",
".",
"Sequence",
")",
"else",
"testcases",
",",
"naming_type",
")",
"return",
"obj",
"else",
":",
"return",
"_ParameterizedTestIter",
"(",
"obj",
",",
"testcases",
",",
"naming_type",
")",
"if",
"_IsSingletonList",
"(",
"testcases",
")",
":",
"assert",
"_NonStringIterable",
"(",
"testcases",
"[",
"0",
"]",
")",
",",
"(",
"'Single parameter argument must be a non-string iterable'",
")",
"testcases",
"=",
"testcases",
"[",
"0",
"]",
"return",
"_Apply"
] | https://github.com/protocolbuffers/protobuf/blob/b5ab0b7a18b7336c60130f4ddb2d97c51792f896/python/google/protobuf/internal/_parameterized.py#L281-L307 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/ops/math_ops.py | python | reduce_mean | (input_tensor,
axis=None,
keep_dims=False,
name=None,
reduction_indices=None) | return gen_math_ops._mean(
input_tensor,
_ReductionDims(input_tensor, axis, reduction_indices),
keep_dims,
name=name) | Computes the mean of elements across dimensions of a tensor.
Reduces `input_tensor` along the dimensions given in `axis`.
Unless `keep_dims` is true, the rank of the tensor is reduced by 1 for each
entry in `axis`. If `keep_dims` is true, the reduced dimensions
are retained with length 1.
If `axis` has no entries, all dimensions are reduced, and a
tensor with a single element is returned.
For example:
```python
x = tf.constant([[1., 1.], [2., 2.]])
tf.reduce_mean(x) # 1.5
tf.reduce_mean(x, 0) # [1.5, 1.5]
tf.reduce_mean(x, 1) # [1., 2.]
```
Args:
input_tensor: The tensor to reduce. Should have numeric type.
axis: The dimensions to reduce. If `None` (the default),
reduces all dimensions. Must be in the range
`[-rank(input_tensor), rank(input_tensor))`.
keep_dims: If true, retains reduced dimensions with length 1.
name: A name for the operation (optional).
reduction_indices: The old (deprecated) name for axis.
Returns:
The reduced tensor.
@compatibility(numpy)
Equivalent to np.mean
@end_compatibility | Computes the mean of elements across dimensions of a tensor. | [
"Computes",
"the",
"mean",
"of",
"elements",
"across",
"dimensions",
"of",
"a",
"tensor",
"."
] | def reduce_mean(input_tensor,
axis=None,
keep_dims=False,
name=None,
reduction_indices=None):
"""Computes the mean of elements across dimensions of a tensor.
Reduces `input_tensor` along the dimensions given in `axis`.
Unless `keep_dims` is true, the rank of the tensor is reduced by 1 for each
entry in `axis`. If `keep_dims` is true, the reduced dimensions
are retained with length 1.
If `axis` has no entries, all dimensions are reduced, and a
tensor with a single element is returned.
For example:
```python
x = tf.constant([[1., 1.], [2., 2.]])
tf.reduce_mean(x) # 1.5
tf.reduce_mean(x, 0) # [1.5, 1.5]
tf.reduce_mean(x, 1) # [1., 2.]
```
Args:
input_tensor: The tensor to reduce. Should have numeric type.
axis: The dimensions to reduce. If `None` (the default),
reduces all dimensions. Must be in the range
`[-rank(input_tensor), rank(input_tensor))`.
keep_dims: If true, retains reduced dimensions with length 1.
name: A name for the operation (optional).
reduction_indices: The old (deprecated) name for axis.
Returns:
The reduced tensor.
@compatibility(numpy)
Equivalent to np.mean
@end_compatibility
"""
return gen_math_ops._mean(
input_tensor,
_ReductionDims(input_tensor, axis, reduction_indices),
keep_dims,
name=name) | [
"def",
"reduce_mean",
"(",
"input_tensor",
",",
"axis",
"=",
"None",
",",
"keep_dims",
"=",
"False",
",",
"name",
"=",
"None",
",",
"reduction_indices",
"=",
"None",
")",
":",
"return",
"gen_math_ops",
".",
"_mean",
"(",
"input_tensor",
",",
"_ReductionDims",
"(",
"input_tensor",
",",
"axis",
",",
"reduction_indices",
")",
",",
"keep_dims",
",",
"name",
"=",
"name",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/math_ops.py#L1373-L1417 | |
apache/parquet-cpp | 642da055adf009652689b20e68a198cffb857651 | build-support/cpplint.py | python | _FunctionState.Begin | (self, function_name) | Start analyzing function body.
Args:
function_name: The name of the function being tracked. | Start analyzing function body. | [
"Start",
"analyzing",
"function",
"body",
"."
] | def Begin(self, function_name):
"""Start analyzing function body.
Args:
function_name: The name of the function being tracked.
"""
self.in_a_function = True
self.lines_in_function = 0
self.current_function = function_name | [
"def",
"Begin",
"(",
"self",
",",
"function_name",
")",
":",
"self",
".",
"in_a_function",
"=",
"True",
"self",
".",
"lines_in_function",
"=",
"0",
"self",
".",
"current_function",
"=",
"function_name"
] | https://github.com/apache/parquet-cpp/blob/642da055adf009652689b20e68a198cffb857651/build-support/cpplint.py#L924-L932 | ||
microsoft/onnxruntime | f92e47e95b13a240e37caf7b36577983544f98fc | orttraining/orttraining/python/training/checkpoint.py | python | _aggregate_over_ranks | (ordered_paths, ranks, sharded_states_original_dims = None, mode = _AGGREGATION_MODE.Zero, partial_aggregation = False, pytorch_format=True) | return _to_pytorch_format(state_dict) if pytorch_format else state_dict | Aggregate checkpoint files over set of ranks and return a single state dictionary
Args:
ordered_paths: list of paths in the order in which they must be aggregated
ranks: list of ranks that are to be aggregated
sharded_states_original_dims: dict containing the original dims for sharded states that are persisted over
multiple calls to _aggregate_over_ranks()
mode: mode of aggregation: Zero or Megatron
partial_aggregation: boolean flag to indicate whether to produce a partially
aggregated state which can be further aggregated over
pytorch_format: boolean flag to select either ONNX Runtime or PyTorch state schema of the returned state_dict
Returns:
state_dict that can be loaded into an ORTTrainer or into a PyTorch model | Aggregate checkpoint files over set of ranks and return a single state dictionary | [
"Aggregate",
"checkpoint",
"files",
"over",
"set",
"of",
"ranks",
"and",
"return",
"a",
"single",
"state",
"dictionary"
] | def _aggregate_over_ranks(ordered_paths, ranks, sharded_states_original_dims = None, mode = _AGGREGATION_MODE.Zero, partial_aggregation = False, pytorch_format=True):
"""Aggregate checkpoint files over set of ranks and return a single state dictionary
Args:
ordered_paths: list of paths in the order in which they must be aggregated
ranks: list of ranks that are to be aggregated
sharded_states_original_dims: dict containing the original dims for sharded states that are persisted over
multiple calls to _aggregate_over_ranks()
mode: mode of aggregation: Zero or Megatron
partial_aggregation: boolean flag to indicate whether to produce a partially
aggregated state which can be further aggregated over
pytorch_format: boolean flag to select either ONNX Runtime or PyTorch state schema of the returned state_dict
Returns:
state_dict that can be loaded into an ORTTrainer or into a PyTorch model
"""
state_dict = {}
if sharded_states_original_dims is None:
sharded_states_original_dims = dict()
world_rank = _utils.state_dict_trainer_options_world_rank_key()
mixed_precision = _utils.state_dict_trainer_options_mixed_precision_key()
zero_stage = _utils.state_dict_trainer_options_zero_stage_key()
world_size = _utils.state_dict_trainer_options_world_size_key()
optimizer_name = _utils.state_dict_trainer_options_optimizer_name_key()
loaded_mixed_precision = None
loaded_world_size = None
loaded_zero_stage = None
loaded_optimizer_name = None
for i, path in enumerate(ordered_paths):
rank_state_dict = _checkpoint_storage.load(path)
assert _utils.state_dict_partition_info_key() in rank_state_dict, "Missing information: partition_info"
assert _utils.state_dict_trainer_options_key() in rank_state_dict, "Missing information: trainer_options"
assert ranks[i] == rank_state_dict[_utils.state_dict_trainer_options_key()][world_rank], \
"Unexpected rank in file at path {}. Expected {}, got {}".\
format(path, rank, rank_state_dict[_utils.state_dict_trainer_options_key()][world_rank])
if loaded_mixed_precision is None:
loaded_mixed_precision = rank_state_dict[_utils.state_dict_trainer_options_key()][mixed_precision]
else:
assert loaded_mixed_precision == rank_state_dict[_utils.state_dict_trainer_options_key()][mixed_precision], \
"Mixed precision state mismatch among checkpoint files. File: {}".format(path)
if loaded_world_size is None:
loaded_world_size = rank_state_dict[_utils.state_dict_trainer_options_key()][world_size]
else:
assert loaded_world_size == rank_state_dict[_utils.state_dict_trainer_options_key()][world_size], \
"World size state mismatch among checkpoint files. File: {}".format(path)
if loaded_zero_stage is None:
loaded_zero_stage = rank_state_dict[_utils.state_dict_trainer_options_key()][zero_stage]
else:
assert loaded_zero_stage == rank_state_dict[_utils.state_dict_trainer_options_key()][zero_stage], \
"Zero stage mismatch among checkpoint files. File: {}".format(path)
if loaded_optimizer_name is None:
loaded_optimizer_name = rank_state_dict[_utils.state_dict_trainer_options_key()][optimizer_name]
else:
assert loaded_optimizer_name == rank_state_dict[_utils.state_dict_trainer_options_key()][optimizer_name], \
"Optimizer name mismatch among checkpoint files. File: {}".format(path)
# aggregate all model states
_aggregate_model_states(rank_state_dict, sharded_states_original_dims, state_dict, loaded_mixed_precision, mode)
if not pytorch_format:
# aggregate all optimizer states if pytorch_format is False
_aggregate_optimizer_states(rank_state_dict, sharded_states_original_dims, state_dict, mode)
# for D+H aggregation scenario, the first pass of aggregation(partial aggregation) is over D groups
# to aggregate over Zero, and another pass to aggregate Megatron partitioned
# states. Preserve the relevant partition info only for weights that are megatron partitioned for
# a partial aggregation call
if partial_aggregation:
_aggregate_megatron_partition_info(rank_state_dict, state_dict)
# entry for trainer_options in the state_dict to perform other sanity checks
if _utils.state_dict_trainer_options_key() not in state_dict:
_aggregate_trainer_options(rank_state_dict, state_dict, partial_aggregation)
# entry for user_dict in the state_dict if not already present
if _utils.state_dict_user_dict_key() not in state_dict and \
_utils.state_dict_user_dict_key() in rank_state_dict:
state_dict[_utils.state_dict_user_dict_key()] = rank_state_dict[_utils.state_dict_user_dict_key()]
# for a partial aggregation scenario, we might not have the entire tensor aggregated yet, thus skip reshape
if not partial_aggregation:
# reshape all the sharded tensors based on the original dimensions stored in sharded_states_original_dims
_reshape_states(sharded_states_original_dims, state_dict, loaded_mixed_precision)
# return a flat structure for PyTorch model in case pytorch_format is True
# else return the hierarchical structure for ORTTrainer
return _to_pytorch_format(state_dict) if pytorch_format else state_dict | [
"def",
"_aggregate_over_ranks",
"(",
"ordered_paths",
",",
"ranks",
",",
"sharded_states_original_dims",
"=",
"None",
",",
"mode",
"=",
"_AGGREGATION_MODE",
".",
"Zero",
",",
"partial_aggregation",
"=",
"False",
",",
"pytorch_format",
"=",
"True",
")",
":",
"state_dict",
"=",
"{",
"}",
"if",
"sharded_states_original_dims",
"is",
"None",
":",
"sharded_states_original_dims",
"=",
"dict",
"(",
")",
"world_rank",
"=",
"_utils",
".",
"state_dict_trainer_options_world_rank_key",
"(",
")",
"mixed_precision",
"=",
"_utils",
".",
"state_dict_trainer_options_mixed_precision_key",
"(",
")",
"zero_stage",
"=",
"_utils",
".",
"state_dict_trainer_options_zero_stage_key",
"(",
")",
"world_size",
"=",
"_utils",
".",
"state_dict_trainer_options_world_size_key",
"(",
")",
"optimizer_name",
"=",
"_utils",
".",
"state_dict_trainer_options_optimizer_name_key",
"(",
")",
"loaded_mixed_precision",
"=",
"None",
"loaded_world_size",
"=",
"None",
"loaded_zero_stage",
"=",
"None",
"loaded_optimizer_name",
"=",
"None",
"for",
"i",
",",
"path",
"in",
"enumerate",
"(",
"ordered_paths",
")",
":",
"rank_state_dict",
"=",
"_checkpoint_storage",
".",
"load",
"(",
"path",
")",
"assert",
"_utils",
".",
"state_dict_partition_info_key",
"(",
")",
"in",
"rank_state_dict",
",",
"\"Missing information: partition_info\"",
"assert",
"_utils",
".",
"state_dict_trainer_options_key",
"(",
")",
"in",
"rank_state_dict",
",",
"\"Missing information: trainer_options\"",
"assert",
"ranks",
"[",
"i",
"]",
"==",
"rank_state_dict",
"[",
"_utils",
".",
"state_dict_trainer_options_key",
"(",
")",
"]",
"[",
"world_rank",
"]",
",",
"\"Unexpected rank in file at path {}. Expected {}, got {}\"",
".",
"format",
"(",
"path",
",",
"rank",
",",
"rank_state_dict",
"[",
"_utils",
".",
"state_dict_trainer_options_key",
"(",
")",
"]",
"[",
"world_rank",
"]",
")",
"if",
"loaded_mixed_precision",
"is",
"None",
":",
"loaded_mixed_precision",
"=",
"rank_state_dict",
"[",
"_utils",
".",
"state_dict_trainer_options_key",
"(",
")",
"]",
"[",
"mixed_precision",
"]",
"else",
":",
"assert",
"loaded_mixed_precision",
"==",
"rank_state_dict",
"[",
"_utils",
".",
"state_dict_trainer_options_key",
"(",
")",
"]",
"[",
"mixed_precision",
"]",
",",
"\"Mixed precision state mismatch among checkpoint files. File: {}\"",
".",
"format",
"(",
"path",
")",
"if",
"loaded_world_size",
"is",
"None",
":",
"loaded_world_size",
"=",
"rank_state_dict",
"[",
"_utils",
".",
"state_dict_trainer_options_key",
"(",
")",
"]",
"[",
"world_size",
"]",
"else",
":",
"assert",
"loaded_world_size",
"==",
"rank_state_dict",
"[",
"_utils",
".",
"state_dict_trainer_options_key",
"(",
")",
"]",
"[",
"world_size",
"]",
",",
"\"World size state mismatch among checkpoint files. File: {}\"",
".",
"format",
"(",
"path",
")",
"if",
"loaded_zero_stage",
"is",
"None",
":",
"loaded_zero_stage",
"=",
"rank_state_dict",
"[",
"_utils",
".",
"state_dict_trainer_options_key",
"(",
")",
"]",
"[",
"zero_stage",
"]",
"else",
":",
"assert",
"loaded_zero_stage",
"==",
"rank_state_dict",
"[",
"_utils",
".",
"state_dict_trainer_options_key",
"(",
")",
"]",
"[",
"zero_stage",
"]",
",",
"\"Zero stage mismatch among checkpoint files. File: {}\"",
".",
"format",
"(",
"path",
")",
"if",
"loaded_optimizer_name",
"is",
"None",
":",
"loaded_optimizer_name",
"=",
"rank_state_dict",
"[",
"_utils",
".",
"state_dict_trainer_options_key",
"(",
")",
"]",
"[",
"optimizer_name",
"]",
"else",
":",
"assert",
"loaded_optimizer_name",
"==",
"rank_state_dict",
"[",
"_utils",
".",
"state_dict_trainer_options_key",
"(",
")",
"]",
"[",
"optimizer_name",
"]",
",",
"\"Optimizer name mismatch among checkpoint files. File: {}\"",
".",
"format",
"(",
"path",
")",
"# aggregate all model states",
"_aggregate_model_states",
"(",
"rank_state_dict",
",",
"sharded_states_original_dims",
",",
"state_dict",
",",
"loaded_mixed_precision",
",",
"mode",
")",
"if",
"not",
"pytorch_format",
":",
"# aggregate all optimizer states if pytorch_format is False",
"_aggregate_optimizer_states",
"(",
"rank_state_dict",
",",
"sharded_states_original_dims",
",",
"state_dict",
",",
"mode",
")",
"# for D+H aggregation scenario, the first pass of aggregation(partial aggregation) is over D groups ",
"# to aggregate over Zero, and another pass to aggregate Megatron partitioned",
"# states. Preserve the relevant partition info only for weights that are megatron partitioned for ",
"# a partial aggregation call",
"if",
"partial_aggregation",
":",
"_aggregate_megatron_partition_info",
"(",
"rank_state_dict",
",",
"state_dict",
")",
"# entry for trainer_options in the state_dict to perform other sanity checks",
"if",
"_utils",
".",
"state_dict_trainer_options_key",
"(",
")",
"not",
"in",
"state_dict",
":",
"_aggregate_trainer_options",
"(",
"rank_state_dict",
",",
"state_dict",
",",
"partial_aggregation",
")",
"# entry for user_dict in the state_dict if not already present",
"if",
"_utils",
".",
"state_dict_user_dict_key",
"(",
")",
"not",
"in",
"state_dict",
"and",
"_utils",
".",
"state_dict_user_dict_key",
"(",
")",
"in",
"rank_state_dict",
":",
"state_dict",
"[",
"_utils",
".",
"state_dict_user_dict_key",
"(",
")",
"]",
"=",
"rank_state_dict",
"[",
"_utils",
".",
"state_dict_user_dict_key",
"(",
")",
"]",
"# for a partial aggregation scenario, we might not have the entire tensor aggregated yet, thus skip reshape",
"if",
"not",
"partial_aggregation",
":",
"# reshape all the sharded tensors based on the original dimensions stored in sharded_states_original_dims",
"_reshape_states",
"(",
"sharded_states_original_dims",
",",
"state_dict",
",",
"loaded_mixed_precision",
")",
"# return a flat structure for PyTorch model in case pytorch_format is True",
"# else return the hierarchical structure for ORTTrainer",
"return",
"_to_pytorch_format",
"(",
"state_dict",
")",
"if",
"pytorch_format",
"else",
"state_dict"
] | https://github.com/microsoft/onnxruntime/blob/f92e47e95b13a240e37caf7b36577983544f98fc/orttraining/orttraining/python/training/checkpoint.py#L321-L409 | |
anestisb/oatdump_plus | ba858c1596598f0d9ae79c14d08c708cecc50af3 | tools/cpplint.py | python | CheckMakePairUsesDeduction | (filename, clean_lines, linenum, error) | Check that make_pair's template arguments are deduced.
G++ 4.6 in C++0x mode fails badly if make_pair's template arguments are
specified explicitly, and such use isn't intended in any case.
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. | Check that make_pair's template arguments are deduced. | [
"Check",
"that",
"make_pair",
"s",
"template",
"arguments",
"are",
"deduced",
"."
] | def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error):
"""Check that make_pair's template arguments are deduced.
G++ 4.6 in C++0x mode fails badly if make_pair's template arguments are
specified explicitly, and such use isn't intended in any case.
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.
"""
raw = clean_lines.raw_lines
line = raw[linenum]
match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line)
if match:
error(filename, linenum, 'build/explicit_make_pair',
4, # 4 = high confidence
'For C++11-compatibility, omit template arguments from make_pair'
' OR use pair directly OR if appropriate, construct a pair directly') | [
"def",
"CheckMakePairUsesDeduction",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"raw",
"=",
"clean_lines",
".",
"raw_lines",
"line",
"=",
"raw",
"[",
"linenum",
"]",
"match",
"=",
"_RE_PATTERN_EXPLICIT_MAKEPAIR",
".",
"search",
"(",
"line",
")",
"if",
"match",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/explicit_make_pair'",
",",
"4",
",",
"# 4 = high confidence",
"'For C++11-compatibility, omit template arguments from make_pair'",
"' OR use pair directly OR if appropriate, construct a pair directly'",
")"
] | https://github.com/anestisb/oatdump_plus/blob/ba858c1596598f0d9ae79c14d08c708cecc50af3/tools/cpplint.py#L3796-L3815 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/sets.py | python | ImmutableSet.__init__ | (self, iterable=None) | Construct an immutable set from an optional iterable. | Construct an immutable set from an optional iterable. | [
"Construct",
"an",
"immutable",
"set",
"from",
"an",
"optional",
"iterable",
"."
] | def __init__(self, iterable=None):
"""Construct an immutable set from an optional iterable."""
self._hashcode = None
self._data = {}
if iterable is not None:
self._update(iterable) | [
"def",
"__init__",
"(",
"self",
",",
"iterable",
"=",
"None",
")",
":",
"self",
".",
"_hashcode",
"=",
"None",
"self",
".",
"_data",
"=",
"{",
"}",
"if",
"iterable",
"is",
"not",
"None",
":",
"self",
".",
"_update",
"(",
"iterable",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/sets.py#L385-L390 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/strings/accessor.py | python | StringMethods.repeat | (self, repeats) | return self._wrap_result(result) | Duplicate each string in the Series or Index.
Parameters
----------
repeats : int or sequence of int
Same value for all (int) or different value per (sequence).
Returns
-------
Series or Index of object
Series or Index of repeated string objects specified by
input parameter repeats.
Examples
--------
>>> s = pd.Series(['a', 'b', 'c'])
>>> s
0 a
1 b
2 c
dtype: object
Single int repeats string in Series
>>> s.str.repeat(repeats=2)
0 aa
1 bb
2 cc
dtype: object
Sequence of int repeats corresponding string in Series
>>> s.str.repeat(repeats=[1, 2, 3])
0 a
1 bb
2 ccc
dtype: object | Duplicate each string in the Series or Index. | [
"Duplicate",
"each",
"string",
"in",
"the",
"Series",
"or",
"Index",
"."
] | def repeat(self, repeats):
"""
Duplicate each string in the Series or Index.
Parameters
----------
repeats : int or sequence of int
Same value for all (int) or different value per (sequence).
Returns
-------
Series or Index of object
Series or Index of repeated string objects specified by
input parameter repeats.
Examples
--------
>>> s = pd.Series(['a', 'b', 'c'])
>>> s
0 a
1 b
2 c
dtype: object
Single int repeats string in Series
>>> s.str.repeat(repeats=2)
0 aa
1 bb
2 cc
dtype: object
Sequence of int repeats corresponding string in Series
>>> s.str.repeat(repeats=[1, 2, 3])
0 a
1 bb
2 ccc
dtype: object
"""
result = self._data.array._str_repeat(repeats)
return self._wrap_result(result) | [
"def",
"repeat",
"(",
"self",
",",
"repeats",
")",
":",
"result",
"=",
"self",
".",
"_data",
".",
"array",
".",
"_str_repeat",
"(",
"repeats",
")",
"return",
"self",
".",
"_wrap_result",
"(",
"result",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/strings/accessor.py#L1407-L1448 | |
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | TIntIntVV.GetDat | (self, *args) | return _snap.TIntIntVV_GetDat(self, *args) | GetDat(TIntIntVV self, TIntV Val) -> TIntV
Parameters:
Val: TVec< TInt,int > const & | GetDat(TIntIntVV self, TIntV Val) -> TIntV | [
"GetDat",
"(",
"TIntIntVV",
"self",
"TIntV",
"Val",
")",
"-",
">",
"TIntV"
] | def GetDat(self, *args):
"""
GetDat(TIntIntVV self, TIntV Val) -> TIntV
Parameters:
Val: TVec< TInt,int > const &
"""
return _snap.TIntIntVV_GetDat(self, *args) | [
"def",
"GetDat",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_snap",
".",
"TIntIntVV_GetDat",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L17343-L17351 | |
MegEngine/MegEngine | ce9ad07a27ec909fb8db4dd67943d24ba98fb93a | imperative/python/megengine/traced_module/traced_module.py | python | NodeFilter.node_id | (self, node_id: List[int]) | return NodeFilterNodeId(self, node_id) | r"""Filter Nodes by their ``id``.
See :meth:`~.InternalGraph.get_node_by_id` for details. | r"""Filter Nodes by their ``id``.
See :meth:`~.InternalGraph.get_node_by_id` for details. | [
"r",
"Filter",
"Nodes",
"by",
"their",
"id",
".",
"See",
":",
"meth",
":",
"~",
".",
"InternalGraph",
".",
"get_node_by_id",
"for",
"details",
"."
] | def node_id(self, node_id: List[int]):
r"""Filter Nodes by their ``id``.
See :meth:`~.InternalGraph.get_node_by_id` for details.
"""
return NodeFilterNodeId(self, node_id) | [
"def",
"node_id",
"(",
"self",
",",
"node_id",
":",
"List",
"[",
"int",
"]",
")",
":",
"return",
"NodeFilterNodeId",
"(",
"self",
",",
"node_id",
")"
] | https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/traced_module/traced_module.py#L1828-L1832 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/model/trajectory.py | python | HermiteTrajectory.extractDofs | (self,dofs) | return self.constructor([t for t in self.times],[[m[j] for j in dofs] + [m[n+j] for j in dofs] for m in self.milestones]) | Returns a trajectory just over the given DOFs.
Args:
dofs (list of int): the (primary) indices to extract. Each entry
must be < len(milestones[0])/2.
Returns:
HermiteTrajectory: a copy of this trajectory but only over the
given DOFs. | Returns a trajectory just over the given DOFs. | [
"Returns",
"a",
"trajectory",
"just",
"over",
"the",
"given",
"DOFs",
"."
] | def extractDofs(self,dofs):
"""Returns a trajectory just over the given DOFs.
Args:
dofs (list of int): the (primary) indices to extract. Each entry
must be < len(milestones[0])/2.
Returns:
HermiteTrajectory: a copy of this trajectory but only over the
given DOFs.
"""
if len(self.times)==0:
return self.constructor()
n = len(self.milestones[0])//2
for d in dofs:
if abs(d) >= n:
raise ValueError("Invalid dof")
return self.constructor([t for t in self.times],[[m[j] for j in dofs] + [m[n+j] for j in dofs] for m in self.milestones]) | [
"def",
"extractDofs",
"(",
"self",
",",
"dofs",
")",
":",
"if",
"len",
"(",
"self",
".",
"times",
")",
"==",
"0",
":",
"return",
"self",
".",
"constructor",
"(",
")",
"n",
"=",
"len",
"(",
"self",
".",
"milestones",
"[",
"0",
"]",
")",
"//",
"2",
"for",
"d",
"in",
"dofs",
":",
"if",
"abs",
"(",
"d",
")",
">=",
"n",
":",
"raise",
"ValueError",
"(",
"\"Invalid dof\"",
")",
"return",
"self",
".",
"constructor",
"(",
"[",
"t",
"for",
"t",
"in",
"self",
".",
"times",
"]",
",",
"[",
"[",
"m",
"[",
"j",
"]",
"for",
"j",
"in",
"dofs",
"]",
"+",
"[",
"m",
"[",
"n",
"+",
"j",
"]",
"for",
"j",
"in",
"dofs",
"]",
"for",
"m",
"in",
"self",
".",
"milestones",
"]",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/model/trajectory.py#L1017-L1034 | |
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/third_party/Python/module/pexpect-2.4/pexpect.py | python | ExceptionPexpect.__filter_not_pexpect | (self, trace_list_item) | This returns True if list item 0 the string 'pexpect.py' in it. | This returns True if list item 0 the string 'pexpect.py' in it. | [
"This",
"returns",
"True",
"if",
"list",
"item",
"0",
"the",
"string",
"pexpect",
".",
"py",
"in",
"it",
"."
] | def __filter_not_pexpect(self, trace_list_item):
"""This returns True if list item 0 the string 'pexpect.py' in it. """
if trace_list_item[0].find('pexpect.py') == -1:
return True
else:
return False | [
"def",
"__filter_not_pexpect",
"(",
"self",
",",
"trace_list_item",
")",
":",
"if",
"trace_list_item",
"[",
"0",
"]",
".",
"find",
"(",
"'pexpect.py'",
")",
"==",
"-",
"1",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/third_party/Python/module/pexpect-2.4/pexpect.py#L122-L128 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/telemetry/internal/browser/browser.py | python | Browser.Foreground | (self) | return self._browser_backend.Foreground() | Ensure the browser application is moved to the foreground. | Ensure the browser application is moved to the foreground. | [
"Ensure",
"the",
"browser",
"application",
"is",
"moved",
"to",
"the",
"foreground",
"."
] | def Foreground(self):
"""Ensure the browser application is moved to the foreground."""
return self._browser_backend.Foreground() | [
"def",
"Foreground",
"(",
"self",
")",
":",
"return",
"self",
".",
"_browser_backend",
".",
"Foreground",
"(",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/internal/browser/browser.py#L268-L270 | |
apple/swift | 469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893 | utils/bug_reducer/bug_reducer/swift_tools.py | python | SwiftTools.sil_passpipeline_dumper | (self) | return self._get_tool('sil-passpipeline-dumper') | Return the path to sil-passpipeline-dumper in the specified swift build
directory. Throws a runtime error if the tool does not exist | Return the path to sil-passpipeline-dumper in the specified swift build
directory. Throws a runtime error if the tool does not exist | [
"Return",
"the",
"path",
"to",
"sil",
"-",
"passpipeline",
"-",
"dumper",
"in",
"the",
"specified",
"swift",
"build",
"directory",
".",
"Throws",
"a",
"runtime",
"error",
"if",
"the",
"tool",
"does",
"not",
"exist"
] | def sil_passpipeline_dumper(self):
"""Return the path to sil-passpipeline-dumper in the specified swift build
directory. Throws a runtime error if the tool does not exist
"""
return self._get_tool('sil-passpipeline-dumper') | [
"def",
"sil_passpipeline_dumper",
"(",
"self",
")",
":",
"return",
"self",
".",
"_get_tool",
"(",
"'sil-passpipeline-dumper'",
")"
] | https://github.com/apple/swift/blob/469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893/utils/bug_reducer/bug_reducer/swift_tools.py#L68-L73 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/metrics/pairwise.py | python | _precompute_metric_params | (X, Y, metric=None, **kwds) | return {} | Precompute data-derived metric parameters if not provided | Precompute data-derived metric parameters if not provided | [
"Precompute",
"data",
"-",
"derived",
"metric",
"parameters",
"if",
"not",
"provided"
] | def _precompute_metric_params(X, Y, metric=None, **kwds):
"""Precompute data-derived metric parameters if not provided
"""
if metric == "seuclidean" and 'V' not in kwds:
if X is Y:
V = np.var(X, axis=0, ddof=1)
else:
V = np.var(np.vstack([X, Y]), axis=0, ddof=1)
return {'V': V}
if metric == "mahalanobis" and 'VI' not in kwds:
if X is Y:
VI = np.linalg.inv(np.cov(X.T)).T
else:
VI = np.linalg.inv(np.cov(np.vstack([X, Y]).T)).T
return {'VI': VI}
return {} | [
"def",
"_precompute_metric_params",
"(",
"X",
",",
"Y",
",",
"metric",
"=",
"None",
",",
"*",
"*",
"kwds",
")",
":",
"if",
"metric",
"==",
"\"seuclidean\"",
"and",
"'V'",
"not",
"in",
"kwds",
":",
"if",
"X",
"is",
"Y",
":",
"V",
"=",
"np",
".",
"var",
"(",
"X",
",",
"axis",
"=",
"0",
",",
"ddof",
"=",
"1",
")",
"else",
":",
"V",
"=",
"np",
".",
"var",
"(",
"np",
".",
"vstack",
"(",
"[",
"X",
",",
"Y",
"]",
")",
",",
"axis",
"=",
"0",
",",
"ddof",
"=",
"1",
")",
"return",
"{",
"'V'",
":",
"V",
"}",
"if",
"metric",
"==",
"\"mahalanobis\"",
"and",
"'VI'",
"not",
"in",
"kwds",
":",
"if",
"X",
"is",
"Y",
":",
"VI",
"=",
"np",
".",
"linalg",
".",
"inv",
"(",
"np",
".",
"cov",
"(",
"X",
".",
"T",
")",
")",
".",
"T",
"else",
":",
"VI",
"=",
"np",
".",
"linalg",
".",
"inv",
"(",
"np",
".",
"cov",
"(",
"np",
".",
"vstack",
"(",
"[",
"X",
",",
"Y",
"]",
")",
".",
"T",
")",
")",
".",
"T",
"return",
"{",
"'VI'",
":",
"VI",
"}",
"return",
"{",
"}"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/metrics/pairwise.py#L1429-L1444 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/propgrid.py | python | PropertyGrid.DedicateKey | (*args, **kwargs) | return _propgrid.PropertyGrid_DedicateKey(*args, **kwargs) | DedicateKey(self, int keycode) | DedicateKey(self, int keycode) | [
"DedicateKey",
"(",
"self",
"int",
"keycode",
")"
] | def DedicateKey(*args, **kwargs):
"""DedicateKey(self, int keycode)"""
return _propgrid.PropertyGrid_DedicateKey(*args, **kwargs) | [
"def",
"DedicateKey",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PropertyGrid_DedicateKey",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L1986-L1988 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/build/waf-1.7.13/waflib/Task.py | python | compile_fun | (line, shell=False) | Parse a string expression such as "${CC} ${SRC} -o ${TGT}" and return a pair containing:
* the function created (compiled) for use as :py:meth:`waflib.Task.TaskBase.run`
* the list of variables that imply a dependency from self.env
for example::
from waflib.Task import compile_fun
compile_fun('cxx', '${CXX} -o ${TGT[0]} ${SRC} -I ${SRC[0].parent.bldpath()}')
def build(bld):
bld(source='wscript', rule='echo "foo\\${SRC[0].name}\\bar"')
The env variables (CXX, ..) on the task must not hold dicts (order)
The reserved keywords *TGT* and *SRC* represent the task input and output nodes | Parse a string expression such as "${CC} ${SRC} -o ${TGT}" and return a pair containing: | [
"Parse",
"a",
"string",
"expression",
"such",
"as",
"$",
"{",
"CC",
"}",
"$",
"{",
"SRC",
"}",
"-",
"o",
"$",
"{",
"TGT",
"}",
"and",
"return",
"a",
"pair",
"containing",
":"
] | def compile_fun(line, shell=False):
"""
Parse a string expression such as "${CC} ${SRC} -o ${TGT}" and return a pair containing:
* the function created (compiled) for use as :py:meth:`waflib.Task.TaskBase.run`
* the list of variables that imply a dependency from self.env
for example::
from waflib.Task import compile_fun
compile_fun('cxx', '${CXX} -o ${TGT[0]} ${SRC} -I ${SRC[0].parent.bldpath()}')
def build(bld):
bld(source='wscript', rule='echo "foo\\${SRC[0].name}\\bar"')
The env variables (CXX, ..) on the task must not hold dicts (order)
The reserved keywords *TGT* and *SRC* represent the task input and output nodes
"""
if line.find('<') > 0 or line.find('>') > 0 or line.find('&&') > 0:
shell = True
if shell:
return compile_fun_shell(line)
else:
return compile_fun_noshell(line) | [
"def",
"compile_fun",
"(",
"line",
",",
"shell",
"=",
"False",
")",
":",
"if",
"line",
".",
"find",
"(",
"'<'",
")",
">",
"0",
"or",
"line",
".",
"find",
"(",
"'>'",
")",
">",
"0",
"or",
"line",
".",
"find",
"(",
"'&&'",
")",
">",
"0",
":",
"shell",
"=",
"True",
"if",
"shell",
":",
"return",
"compile_fun_shell",
"(",
"line",
")",
"else",
":",
"return",
"compile_fun_noshell",
"(",
"line",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/Task.py#L1215-L1240 | ||
facebook/fboss | 60063db1df37c2ec0e7dcd0955c54885ea9bf7f0 | fboss/py/fboss/cli/commands/port.py | python | PortStatusDetailCmd._print_transceiver_details | (self, tid) | Print details about transceiver | Print details about transceiver | [
"Print",
"details",
"about",
"transceiver"
] | def _print_transceiver_details(self, tid): # noqa
"""Print details about transceiver"""
info = self._info_resp.get(tid)
ch_to_port = self._t_to_p[tid]
if not info or info.present is False:
self._print_transceiver_ports(ch_to_port.values(), info)
return
print("Transceiver: {:>2}".format(info.port))
if info.identifier:
print(
"Optics type: {}".format(
transceiver_ttypes.TransceiverModuleIdentifier._VALUES_TO_NAMES[
info.identifier
]
)
)
if info.vendor:
self._print_vendor_details(info)
if info.cable:
self._print_cable_details(info)
if info.settings:
self._print_settings_details(info)
if info.sensor or (info.thresholds and self._verbose) or info.channels:
print("Monitoring Information:")
if info.sensor:
print(
" {:<15} {:0.4} {:<4} {:0.4}".format(
"Temperature", info.sensor.temp.value, "Vcc", info.sensor.vcc.value
)
)
if self._verbose and info.thresholds:
self._print_thresholds(info.thresholds)
if self._verbose and info.sensor:
if info.sensor.temp.flags and info.sensor.vcc.flags:
self._print_sensor_flags(info.sensor)
for channel in info.channels:
port = ch_to_port.get(channel.channel, None)
if port:
attrs = utils.get_status_strs(self._status_resp[port], None)
print(
" Channel: {} Port: {:>2} Status: {:<8} Link: {:<4}".format(
channel.channel,
port,
attrs["admin_status"],
attrs["link_status"],
)
)
else:
# This is a channel for a port we weren't asked to display.
#
# (It would probably be nicer to clean up the CLI syntax so it
# is a bit less ambiguous about what we should do here when we
# were only asked to display info for some ports in a given
# transceiver.)
print(" Channel: {}".format(channel.channel))
self._print_port_channel(channel)
# If we didn't print any channel info, print something useful
if not info.channels:
self._print_transceiver_ports(ch_to_port.values(), info) | [
"def",
"_print_transceiver_details",
"(",
"self",
",",
"tid",
")",
":",
"# noqa",
"info",
"=",
"self",
".",
"_info_resp",
".",
"get",
"(",
"tid",
")",
"ch_to_port",
"=",
"self",
".",
"_t_to_p",
"[",
"tid",
"]",
"if",
"not",
"info",
"or",
"info",
".",
"present",
"is",
"False",
":",
"self",
".",
"_print_transceiver_ports",
"(",
"ch_to_port",
".",
"values",
"(",
")",
",",
"info",
")",
"return",
"print",
"(",
"\"Transceiver: {:>2}\"",
".",
"format",
"(",
"info",
".",
"port",
")",
")",
"if",
"info",
".",
"identifier",
":",
"print",
"(",
"\"Optics type: {}\"",
".",
"format",
"(",
"transceiver_ttypes",
".",
"TransceiverModuleIdentifier",
".",
"_VALUES_TO_NAMES",
"[",
"info",
".",
"identifier",
"]",
")",
")",
"if",
"info",
".",
"vendor",
":",
"self",
".",
"_print_vendor_details",
"(",
"info",
")",
"if",
"info",
".",
"cable",
":",
"self",
".",
"_print_cable_details",
"(",
"info",
")",
"if",
"info",
".",
"settings",
":",
"self",
".",
"_print_settings_details",
"(",
"info",
")",
"if",
"info",
".",
"sensor",
"or",
"(",
"info",
".",
"thresholds",
"and",
"self",
".",
"_verbose",
")",
"or",
"info",
".",
"channels",
":",
"print",
"(",
"\"Monitoring Information:\"",
")",
"if",
"info",
".",
"sensor",
":",
"print",
"(",
"\" {:<15} {:0.4} {:<4} {:0.4}\"",
".",
"format",
"(",
"\"Temperature\"",
",",
"info",
".",
"sensor",
".",
"temp",
".",
"value",
",",
"\"Vcc\"",
",",
"info",
".",
"sensor",
".",
"vcc",
".",
"value",
")",
")",
"if",
"self",
".",
"_verbose",
"and",
"info",
".",
"thresholds",
":",
"self",
".",
"_print_thresholds",
"(",
"info",
".",
"thresholds",
")",
"if",
"self",
".",
"_verbose",
"and",
"info",
".",
"sensor",
":",
"if",
"info",
".",
"sensor",
".",
"temp",
".",
"flags",
"and",
"info",
".",
"sensor",
".",
"vcc",
".",
"flags",
":",
"self",
".",
"_print_sensor_flags",
"(",
"info",
".",
"sensor",
")",
"for",
"channel",
"in",
"info",
".",
"channels",
":",
"port",
"=",
"ch_to_port",
".",
"get",
"(",
"channel",
".",
"channel",
",",
"None",
")",
"if",
"port",
":",
"attrs",
"=",
"utils",
".",
"get_status_strs",
"(",
"self",
".",
"_status_resp",
"[",
"port",
"]",
",",
"None",
")",
"print",
"(",
"\" Channel: {} Port: {:>2} Status: {:<8} Link: {:<4}\"",
".",
"format",
"(",
"channel",
".",
"channel",
",",
"port",
",",
"attrs",
"[",
"\"admin_status\"",
"]",
",",
"attrs",
"[",
"\"link_status\"",
"]",
",",
")",
")",
"else",
":",
"# This is a channel for a port we weren't asked to display.",
"#",
"# (It would probably be nicer to clean up the CLI syntax so it",
"# is a bit less ambiguous about what we should do here when we",
"# were only asked to display info for some ports in a given",
"# transceiver.)",
"print",
"(",
"\" Channel: {}\"",
".",
"format",
"(",
"channel",
".",
"channel",
")",
")",
"self",
".",
"_print_port_channel",
"(",
"channel",
")",
"# If we didn't print any channel info, print something useful",
"if",
"not",
"info",
".",
"channels",
":",
"self",
".",
"_print_transceiver_ports",
"(",
"ch_to_port",
".",
"values",
"(",
")",
",",
"info",
")"
] | https://github.com/facebook/fboss/blob/60063db1df37c2ec0e7dcd0955c54885ea9bf7f0/fboss/py/fboss/cli/commands/port.py#L923-L993 | ||
microsoft/checkedc-clang | a173fefde5d7877b7750e7ce96dd08cf18baebf2 | clang/bindings/python/clang/cindex.py | python | Token.spelling | (self) | return conf.lib.clang_getTokenSpelling(self._tu, self) | The spelling of this token.
This is the textual representation of the token in source. | The spelling of this token. | [
"The",
"spelling",
"of",
"this",
"token",
"."
] | def spelling(self):
"""The spelling of this token.
This is the textual representation of the token in source.
"""
return conf.lib.clang_getTokenSpelling(self._tu, self) | [
"def",
"spelling",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_getTokenSpelling",
"(",
"self",
".",
"_tu",
",",
"self",
")"
] | https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/clang/bindings/python/clang/cindex.py#L3287-L3292 | |
rrwick/Unicycler | 96ffea71e3a78d63ade19d6124946773e65cf129 | ez_setup.py | python | _parse_args | () | return options | Parse the command line for options. | Parse the command line for options. | [
"Parse",
"the",
"command",
"line",
"for",
"options",
"."
] | def _parse_args():
"""Parse the command line for options."""
parser = optparse.OptionParser()
parser.add_option(
'--user', dest='user_install', action='store_true', default=False,
help='install in user site package')
parser.add_option(
'--download-base', dest='download_base', metavar="URL",
default=DEFAULT_URL,
help='alternative URL from where to download the setuptools package')
parser.add_option(
'--insecure', dest='downloader_factory', action='store_const',
const=lambda: download_file_insecure, default=get_best_downloader,
help='Use internal, non-validating downloader'
)
parser.add_option(
'--version', help="Specify which version to download",
default=DEFAULT_VERSION,
)
parser.add_option(
'--to-dir',
help="Directory to save (and re-use) package",
default=DEFAULT_SAVE_DIR,
)
options, args = parser.parse_args()
# positional arguments are ignored
return options | [
"def",
"_parse_args",
"(",
")",
":",
"parser",
"=",
"optparse",
".",
"OptionParser",
"(",
")",
"parser",
".",
"add_option",
"(",
"'--user'",
",",
"dest",
"=",
"'user_install'",
",",
"action",
"=",
"'store_true'",
",",
"default",
"=",
"False",
",",
"help",
"=",
"'install in user site package'",
")",
"parser",
".",
"add_option",
"(",
"'--download-base'",
",",
"dest",
"=",
"'download_base'",
",",
"metavar",
"=",
"\"URL\"",
",",
"default",
"=",
"DEFAULT_URL",
",",
"help",
"=",
"'alternative URL from where to download the setuptools package'",
")",
"parser",
".",
"add_option",
"(",
"'--insecure'",
",",
"dest",
"=",
"'downloader_factory'",
",",
"action",
"=",
"'store_const'",
",",
"const",
"=",
"lambda",
":",
"download_file_insecure",
",",
"default",
"=",
"get_best_downloader",
",",
"help",
"=",
"'Use internal, non-validating downloader'",
")",
"parser",
".",
"add_option",
"(",
"'--version'",
",",
"help",
"=",
"\"Specify which version to download\"",
",",
"default",
"=",
"DEFAULT_VERSION",
",",
")",
"parser",
".",
"add_option",
"(",
"'--to-dir'",
",",
"help",
"=",
"\"Directory to save (and re-use) package\"",
",",
"default",
"=",
"DEFAULT_SAVE_DIR",
",",
")",
"options",
",",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"# positional arguments are ignored",
"return",
"options"
] | https://github.com/rrwick/Unicycler/blob/96ffea71e3a78d63ade19d6124946773e65cf129/ez_setup.py#L368-L394 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/stc.py | python | StyledTextCtrl.GetRectangularSelectionCaretVirtualSpace | (*args, **kwargs) | return _stc.StyledTextCtrl_GetRectangularSelectionCaretVirtualSpace(*args, **kwargs) | GetRectangularSelectionCaretVirtualSpace(self) -> int | GetRectangularSelectionCaretVirtualSpace(self) -> int | [
"GetRectangularSelectionCaretVirtualSpace",
"(",
"self",
")",
"-",
">",
"int"
] | def GetRectangularSelectionCaretVirtualSpace(*args, **kwargs):
"""GetRectangularSelectionCaretVirtualSpace(self) -> int"""
return _stc.StyledTextCtrl_GetRectangularSelectionCaretVirtualSpace(*args, **kwargs) | [
"def",
"GetRectangularSelectionCaretVirtualSpace",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_GetRectangularSelectionCaretVirtualSpace",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L6228-L6230 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/auto_bisect/fetch_build.py | python | Unzip | (file_path, output_dir, verbose=True) | Extracts a zip archive's contents into the given output directory.
This was based on ExtractZip from build/scripts/common/chromium_utils.py.
Args:
file_path: Path of the zip file to extract.
output_dir: Path to the destination directory.
verbose: Whether to print out what is being extracted.
Raises:
IOError: The unzip command had a non-zero exit code.
RuntimeError: Failed to create the output directory. | Extracts a zip archive's contents into the given output directory. | [
"Extracts",
"a",
"zip",
"archive",
"s",
"contents",
"into",
"the",
"given",
"output",
"directory",
"."
] | def Unzip(file_path, output_dir, verbose=True):
"""Extracts a zip archive's contents into the given output directory.
This was based on ExtractZip from build/scripts/common/chromium_utils.py.
Args:
file_path: Path of the zip file to extract.
output_dir: Path to the destination directory.
verbose: Whether to print out what is being extracted.
Raises:
IOError: The unzip command had a non-zero exit code.
RuntimeError: Failed to create the output directory.
"""
_MakeDirectory(output_dir)
# On Linux and Mac, we use the unzip command because it handles links and
# file permissions bits, so achieving this behavior is easier than with
# ZipInfo options.
#
# The Mac Version of unzip unfortunately does not support Zip64, whereas
# the python module does, so we have to fall back to the python zip module
# on Mac if the file size is greater than 4GB.
mac_zip_size_limit = 2 ** 32 # 4GB
if (bisect_utils.IsLinuxHost() or
(bisect_utils.IsMacHost()
and os.path.getsize(file_path) < mac_zip_size_limit)):
unzip_command = ['unzip', '-o']
_UnzipUsingCommand(unzip_command, file_path, output_dir)
return
# On Windows, try to use 7z if it is installed, otherwise fall back to the
# Python zipfile module. If 7z is not installed, then this may fail if the
# zip file is larger than 512MB.
sevenzip_path = r'C:\Program Files\7-Zip\7z.exe'
if bisect_utils.IsWindowsHost() and os.path.exists(sevenzip_path):
unzip_command = [sevenzip_path, 'x', '-y']
_UnzipUsingCommand(unzip_command, file_path, output_dir)
return
_UnzipUsingZipFile(file_path, output_dir, verbose) | [
"def",
"Unzip",
"(",
"file_path",
",",
"output_dir",
",",
"verbose",
"=",
"True",
")",
":",
"_MakeDirectory",
"(",
"output_dir",
")",
"# On Linux and Mac, we use the unzip command because it handles links and",
"# file permissions bits, so achieving this behavior is easier than with",
"# ZipInfo options.",
"#",
"# The Mac Version of unzip unfortunately does not support Zip64, whereas",
"# the python module does, so we have to fall back to the python zip module",
"# on Mac if the file size is greater than 4GB.",
"mac_zip_size_limit",
"=",
"2",
"**",
"32",
"# 4GB",
"if",
"(",
"bisect_utils",
".",
"IsLinuxHost",
"(",
")",
"or",
"(",
"bisect_utils",
".",
"IsMacHost",
"(",
")",
"and",
"os",
".",
"path",
".",
"getsize",
"(",
"file_path",
")",
"<",
"mac_zip_size_limit",
")",
")",
":",
"unzip_command",
"=",
"[",
"'unzip'",
",",
"'-o'",
"]",
"_UnzipUsingCommand",
"(",
"unzip_command",
",",
"file_path",
",",
"output_dir",
")",
"return",
"# On Windows, try to use 7z if it is installed, otherwise fall back to the",
"# Python zipfile module. If 7z is not installed, then this may fail if the",
"# zip file is larger than 512MB.",
"sevenzip_path",
"=",
"r'C:\\Program Files\\7-Zip\\7z.exe'",
"if",
"bisect_utils",
".",
"IsWindowsHost",
"(",
")",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"sevenzip_path",
")",
":",
"unzip_command",
"=",
"[",
"sevenzip_path",
",",
"'x'",
",",
"'-y'",
"]",
"_UnzipUsingCommand",
"(",
"unzip_command",
",",
"file_path",
",",
"output_dir",
")",
"return",
"_UnzipUsingZipFile",
"(",
"file_path",
",",
"output_dir",
",",
"verbose",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/auto_bisect/fetch_build.py#L385-L425 | ||
emscripten-core/emscripten | 0d413d3c5af8b28349682496edc14656f5700c2f | third_party/ply/example/ansic/cparse.py | python | p_declaration_list_2 | (t) | declaration_list : declaration_list declaration | declaration_list : declaration_list declaration | [
"declaration_list",
":",
"declaration_list",
"declaration"
] | def p_declaration_list_2(t):
'declaration_list : declaration_list declaration '
pass | [
"def",
"p_declaration_list_2",
"(",
"t",
")",
":",
"pass"
] | https://github.com/emscripten-core/emscripten/blob/0d413d3c5af8b28349682496edc14656f5700c2f/third_party/ply/example/ansic/cparse.py#L68-L70 | ||
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/contrib/graph_editor/util.py | python | get_generating_ops | (ts) | return [t.op for t in ts] | Return all the generating ops of the tensors in ts.
Args:
ts: a list of tf.Tensor
Returns:
A list of all the generating tf.Operation of the tensors in ts.
Raises:
TypeError: if ts cannot be converted to a list of tf.Tensor. | Return all the generating ops of the tensors in ts. | [
"Return",
"all",
"the",
"generating",
"ops",
"of",
"the",
"tensors",
"in",
"ts",
"."
] | def get_generating_ops(ts):
"""Return all the generating ops of the tensors in ts.
Args:
ts: a list of tf.Tensor
Returns:
A list of all the generating tf.Operation of the tensors in ts.
Raises:
TypeError: if ts cannot be converted to a list of tf.Tensor.
"""
ts = make_list_of_t(ts, allow_graph=False)
return [t.op for t in ts] | [
"def",
"get_generating_ops",
"(",
"ts",
")",
":",
"ts",
"=",
"make_list_of_t",
"(",
"ts",
",",
"allow_graph",
"=",
"False",
")",
"return",
"[",
"t",
".",
"op",
"for",
"t",
"in",
"ts",
"]"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/graph_editor/util.py#L199-L210 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/nn/cell.py | python | Cell._recompute_slice_activation | (self, slice_activation=False) | Slice the cell output which would remains in memory. | Slice the cell output which would remains in memory. | [
"Slice",
"the",
"cell",
"output",
"which",
"would",
"remains",
"in",
"memory",
"."
] | def _recompute_slice_activation(self, slice_activation=False):
"""
Slice the cell output which would remains in memory.
"""
for _, value in self._primitives.items():
if value:
value.add_prim_attr("slice_activation", slice_activation)
for cell in self.cells():
cell._recompute_slice_activation(slice_activation) | [
"def",
"_recompute_slice_activation",
"(",
"self",
",",
"slice_activation",
"=",
"False",
")",
":",
"for",
"_",
",",
"value",
"in",
"self",
".",
"_primitives",
".",
"items",
"(",
")",
":",
"if",
"value",
":",
"value",
".",
"add_prim_attr",
"(",
"\"slice_activation\"",
",",
"slice_activation",
")",
"for",
"cell",
"in",
"self",
".",
"cells",
"(",
")",
":",
"cell",
".",
"_recompute_slice_activation",
"(",
"slice_activation",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/cell.py#L1549-L1557 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/dateutil/dateutil/rrule.py | python | rrule.__str__ | (self) | return '\n'.join(output) | Output a string that would generate this RRULE if passed to rrulestr.
This is mostly compatible with RFC5545, except for the
dateutil-specific extension BYEASTER. | Output a string that would generate this RRULE if passed to rrulestr.
This is mostly compatible with RFC5545, except for the
dateutil-specific extension BYEASTER. | [
"Output",
"a",
"string",
"that",
"would",
"generate",
"this",
"RRULE",
"if",
"passed",
"to",
"rrulestr",
".",
"This",
"is",
"mostly",
"compatible",
"with",
"RFC5545",
"except",
"for",
"the",
"dateutil",
"-",
"specific",
"extension",
"BYEASTER",
"."
] | def __str__(self):
"""
Output a string that would generate this RRULE if passed to rrulestr.
This is mostly compatible with RFC5545, except for the
dateutil-specific extension BYEASTER.
"""
output = []
h, m, s = [None] * 3
if self._dtstart:
output.append(self._dtstart.strftime('DTSTART:%Y%m%dT%H%M%S'))
h, m, s = self._dtstart.timetuple()[3:6]
parts = ['FREQ=' + FREQNAMES[self._freq]]
if self._interval != 1:
parts.append('INTERVAL=' + str(self._interval))
if self._wkst:
parts.append('WKST=' + repr(weekday(self._wkst))[0:2])
if self._count is not None:
parts.append('COUNT=' + str(self._count))
if self._until:
parts.append(self._until.strftime('UNTIL=%Y%m%dT%H%M%S'))
if self._original_rule.get('byweekday') is not None:
# The str() method on weekday objects doesn't generate
# RFC5545-compliant strings, so we should modify that.
original_rule = dict(self._original_rule)
wday_strings = []
for wday in original_rule['byweekday']:
if wday.n:
wday_strings.append('{n:+d}{wday}'.format(
n=wday.n,
wday=repr(wday)[0:2]))
else:
wday_strings.append(repr(wday))
original_rule['byweekday'] = wday_strings
else:
original_rule = self._original_rule
partfmt = '{name}={vals}'
for name, key in [('BYSETPOS', 'bysetpos'),
('BYMONTH', 'bymonth'),
('BYMONTHDAY', 'bymonthday'),
('BYYEARDAY', 'byyearday'),
('BYWEEKNO', 'byweekno'),
('BYDAY', 'byweekday'),
('BYHOUR', 'byhour'),
('BYMINUTE', 'byminute'),
('BYSECOND', 'bysecond'),
('BYEASTER', 'byeaster')]:
value = original_rule.get(key)
if value:
parts.append(partfmt.format(name=name, vals=(','.join(str(v)
for v in value))))
output.append('RRULE:' + ';'.join(parts))
return '\n'.join(output) | [
"def",
"__str__",
"(",
"self",
")",
":",
"output",
"=",
"[",
"]",
"h",
",",
"m",
",",
"s",
"=",
"[",
"None",
"]",
"*",
"3",
"if",
"self",
".",
"_dtstart",
":",
"output",
".",
"append",
"(",
"self",
".",
"_dtstart",
".",
"strftime",
"(",
"'DTSTART:%Y%m%dT%H%M%S'",
")",
")",
"h",
",",
"m",
",",
"s",
"=",
"self",
".",
"_dtstart",
".",
"timetuple",
"(",
")",
"[",
"3",
":",
"6",
"]",
"parts",
"=",
"[",
"'FREQ='",
"+",
"FREQNAMES",
"[",
"self",
".",
"_freq",
"]",
"]",
"if",
"self",
".",
"_interval",
"!=",
"1",
":",
"parts",
".",
"append",
"(",
"'INTERVAL='",
"+",
"str",
"(",
"self",
".",
"_interval",
")",
")",
"if",
"self",
".",
"_wkst",
":",
"parts",
".",
"append",
"(",
"'WKST='",
"+",
"repr",
"(",
"weekday",
"(",
"self",
".",
"_wkst",
")",
")",
"[",
"0",
":",
"2",
"]",
")",
"if",
"self",
".",
"_count",
"is",
"not",
"None",
":",
"parts",
".",
"append",
"(",
"'COUNT='",
"+",
"str",
"(",
"self",
".",
"_count",
")",
")",
"if",
"self",
".",
"_until",
":",
"parts",
".",
"append",
"(",
"self",
".",
"_until",
".",
"strftime",
"(",
"'UNTIL=%Y%m%dT%H%M%S'",
")",
")",
"if",
"self",
".",
"_original_rule",
".",
"get",
"(",
"'byweekday'",
")",
"is",
"not",
"None",
":",
"# The str() method on weekday objects doesn't generate",
"# RFC5545-compliant strings, so we should modify that.",
"original_rule",
"=",
"dict",
"(",
"self",
".",
"_original_rule",
")",
"wday_strings",
"=",
"[",
"]",
"for",
"wday",
"in",
"original_rule",
"[",
"'byweekday'",
"]",
":",
"if",
"wday",
".",
"n",
":",
"wday_strings",
".",
"append",
"(",
"'{n:+d}{wday}'",
".",
"format",
"(",
"n",
"=",
"wday",
".",
"n",
",",
"wday",
"=",
"repr",
"(",
"wday",
")",
"[",
"0",
":",
"2",
"]",
")",
")",
"else",
":",
"wday_strings",
".",
"append",
"(",
"repr",
"(",
"wday",
")",
")",
"original_rule",
"[",
"'byweekday'",
"]",
"=",
"wday_strings",
"else",
":",
"original_rule",
"=",
"self",
".",
"_original_rule",
"partfmt",
"=",
"'{name}={vals}'",
"for",
"name",
",",
"key",
"in",
"[",
"(",
"'BYSETPOS'",
",",
"'bysetpos'",
")",
",",
"(",
"'BYMONTH'",
",",
"'bymonth'",
")",
",",
"(",
"'BYMONTHDAY'",
",",
"'bymonthday'",
")",
",",
"(",
"'BYYEARDAY'",
",",
"'byyearday'",
")",
",",
"(",
"'BYWEEKNO'",
",",
"'byweekno'",
")",
",",
"(",
"'BYDAY'",
",",
"'byweekday'",
")",
",",
"(",
"'BYHOUR'",
",",
"'byhour'",
")",
",",
"(",
"'BYMINUTE'",
",",
"'byminute'",
")",
",",
"(",
"'BYSECOND'",
",",
"'bysecond'",
")",
",",
"(",
"'BYEASTER'",
",",
"'byeaster'",
")",
"]",
":",
"value",
"=",
"original_rule",
".",
"get",
"(",
"key",
")",
"if",
"value",
":",
"parts",
".",
"append",
"(",
"partfmt",
".",
"format",
"(",
"name",
"=",
"name",
",",
"vals",
"=",
"(",
"','",
".",
"join",
"(",
"str",
"(",
"v",
")",
"for",
"v",
"in",
"value",
")",
")",
")",
")",
"output",
".",
"append",
"(",
"'RRULE:'",
"+",
"';'",
".",
"join",
"(",
"parts",
")",
")",
"return",
"'\\n'",
".",
"join",
"(",
"output",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/dateutil/dateutil/rrule.py#L700-L760 | |
peteanderson80/Matterport3DSimulator | 589d091b111333f9e9f9d6cfd021b2eb68435925 | tasks/R2R/agent.py | python | Seq2SeqAgent.load | (self, encoder_path, decoder_path) | Loads parameters (but not training state) | Loads parameters (but not training state) | [
"Loads",
"parameters",
"(",
"but",
"not",
"training",
"state",
")"
] | def load(self, encoder_path, decoder_path):
''' Loads parameters (but not training state) '''
self.encoder.load_state_dict(torch.load(encoder_path))
self.decoder.load_state_dict(torch.load(decoder_path)) | [
"def",
"load",
"(",
"self",
",",
"encoder_path",
",",
"decoder_path",
")",
":",
"self",
".",
"encoder",
".",
"load_state_dict",
"(",
"torch",
".",
"load",
"(",
"encoder_path",
")",
")",
"self",
".",
"decoder",
".",
"load_state_dict",
"(",
"torch",
".",
"load",
"(",
"decoder_path",
")",
")"
] | https://github.com/peteanderson80/Matterport3DSimulator/blob/589d091b111333f9e9f9d6cfd021b2eb68435925/tasks/R2R/agent.py#L317-L320 | ||
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/python/framework/ops.py | python | Graph.get_all_collection_keys | (self) | Returns a list of collections used in this graph. | Returns a list of collections used in this graph. | [
"Returns",
"a",
"list",
"of",
"collections",
"used",
"in",
"this",
"graph",
"."
] | def get_all_collection_keys(self):
"""Returns a list of collections used in this graph."""
with self._lock:
return [x for x in self._collections if isinstance(x, six.string_types)] | [
"def",
"get_all_collection_keys",
"(",
"self",
")",
":",
"with",
"self",
".",
"_lock",
":",
"return",
"[",
"x",
"for",
"x",
"in",
"self",
".",
"_collections",
"if",
"isinstance",
"(",
"x",
",",
"six",
".",
"string_types",
")",
"]"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/framework/ops.py#L2686-L2689 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | Framework/PythonInterface/plugins/algorithms/MRGetTheta.py | python | MRGetTheta.PyExec | (self) | return | Main execution body | Main execution body | [
"Main",
"execution",
"body"
] | def PyExec(self):
""" Main execution body """
_w=self.getProperty("Workspace").value
angle_offset = self.getProperty("AngleOffset").value
dirpix_overwrite = self.getProperty("DirectPixelOverwrite").value
dangle0_overwrite = self.getProperty("DAngle0Overwrite").value
use_sangle = self.getProperty("UseSANGLE").value
if use_sangle:
theta = self.read_log(_w, 'SANGLE', target_units='rad', assumed_units='deg')
else:
dangle = self.read_log(_w, 'DANGLE', target_units='rad', assumed_units='deg')
if dangle0_overwrite == Property.EMPTY_DBL:
dangle0 = self.read_log(_w, 'DANGLE0', target_units='rad', assumed_units='deg')
else:
dangle0 = dangle0_overwrite * math.pi / 180.0
det_distance = self.read_log(_w, 'SampleDetDis', target_units='m', assumed_units='mm')
if dirpix_overwrite == Property.EMPTY_DBL:
direct_beam_pix = _w.getRun()['DIRPIX'].getStatistics().mean
else:
direct_beam_pix = dirpix_overwrite
ref_pix = self.getProperty("SpecularPixel").value
if ref_pix == 0.:
ref_pix = direct_beam_pix
# Get pixel size from instrument properties
if _w.getInstrument().hasParameter("pixel-width"):
pixel_width = float(_w.getInstrument().getNumberParameter("pixel-width")[0]) / 1000.0
else:
mantid.simpleapi.logger.warning("Not pixel width found in instrument, assuming 0.7 mm.")
pixel_width = 0.0007
theta = (dangle - dangle0) / 2.0 + ((direct_beam_pix - ref_pix) * pixel_width) / (2.0 * det_distance)
self.setProperty("Theta", abs(theta) + angle_offset)
return | [
"def",
"PyExec",
"(",
"self",
")",
":",
"_w",
"=",
"self",
".",
"getProperty",
"(",
"\"Workspace\"",
")",
".",
"value",
"angle_offset",
"=",
"self",
".",
"getProperty",
"(",
"\"AngleOffset\"",
")",
".",
"value",
"dirpix_overwrite",
"=",
"self",
".",
"getProperty",
"(",
"\"DirectPixelOverwrite\"",
")",
".",
"value",
"dangle0_overwrite",
"=",
"self",
".",
"getProperty",
"(",
"\"DAngle0Overwrite\"",
")",
".",
"value",
"use_sangle",
"=",
"self",
".",
"getProperty",
"(",
"\"UseSANGLE\"",
")",
".",
"value",
"if",
"use_sangle",
":",
"theta",
"=",
"self",
".",
"read_log",
"(",
"_w",
",",
"'SANGLE'",
",",
"target_units",
"=",
"'rad'",
",",
"assumed_units",
"=",
"'deg'",
")",
"else",
":",
"dangle",
"=",
"self",
".",
"read_log",
"(",
"_w",
",",
"'DANGLE'",
",",
"target_units",
"=",
"'rad'",
",",
"assumed_units",
"=",
"'deg'",
")",
"if",
"dangle0_overwrite",
"==",
"Property",
".",
"EMPTY_DBL",
":",
"dangle0",
"=",
"self",
".",
"read_log",
"(",
"_w",
",",
"'DANGLE0'",
",",
"target_units",
"=",
"'rad'",
",",
"assumed_units",
"=",
"'deg'",
")",
"else",
":",
"dangle0",
"=",
"dangle0_overwrite",
"*",
"math",
".",
"pi",
"/",
"180.0",
"det_distance",
"=",
"self",
".",
"read_log",
"(",
"_w",
",",
"'SampleDetDis'",
",",
"target_units",
"=",
"'m'",
",",
"assumed_units",
"=",
"'mm'",
")",
"if",
"dirpix_overwrite",
"==",
"Property",
".",
"EMPTY_DBL",
":",
"direct_beam_pix",
"=",
"_w",
".",
"getRun",
"(",
")",
"[",
"'DIRPIX'",
"]",
".",
"getStatistics",
"(",
")",
".",
"mean",
"else",
":",
"direct_beam_pix",
"=",
"dirpix_overwrite",
"ref_pix",
"=",
"self",
".",
"getProperty",
"(",
"\"SpecularPixel\"",
")",
".",
"value",
"if",
"ref_pix",
"==",
"0.",
":",
"ref_pix",
"=",
"direct_beam_pix",
"# Get pixel size from instrument properties",
"if",
"_w",
".",
"getInstrument",
"(",
")",
".",
"hasParameter",
"(",
"\"pixel-width\"",
")",
":",
"pixel_width",
"=",
"float",
"(",
"_w",
".",
"getInstrument",
"(",
")",
".",
"getNumberParameter",
"(",
"\"pixel-width\"",
")",
"[",
"0",
"]",
")",
"/",
"1000.0",
"else",
":",
"mantid",
".",
"simpleapi",
".",
"logger",
".",
"warning",
"(",
"\"Not pixel width found in instrument, assuming 0.7 mm.\"",
")",
"pixel_width",
"=",
"0.0007",
"theta",
"=",
"(",
"dangle",
"-",
"dangle0",
")",
"/",
"2.0",
"+",
"(",
"(",
"direct_beam_pix",
"-",
"ref_pix",
")",
"*",
"pixel_width",
")",
"/",
"(",
"2.0",
"*",
"det_distance",
")",
"self",
".",
"setProperty",
"(",
"\"Theta\"",
",",
"abs",
"(",
"theta",
")",
"+",
"angle_offset",
")",
"return"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/MRGetTheta.py#L40-L76 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/mhlib.py | python | MH.__repr__ | (self) | return 'MH(%r, %r)' % (self.path, self.profile) | String representation. | String representation. | [
"String",
"representation",
"."
] | def __repr__(self):
"""String representation."""
return 'MH(%r, %r)' % (self.path, self.profile) | [
"def",
"__repr__",
"(",
"self",
")",
":",
"return",
"'MH(%r, %r)'",
"%",
"(",
"self",
".",
"path",
",",
"self",
".",
"profile",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/mhlib.py#L114-L116 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/error_interpolation.py | python | interpolate | (error_message, graph) | return "".join(
itertools.chain(*six.moves.zip_longest(seps, subs, fillvalue=""))) | Interpolates an error message.
The error message can contain tags of the form `{{type name}}` which will be
replaced. For example: "{{node <name>}}" would get expanded to:
"node <name>(defined at <path>)".
Args:
error_message: A string to interpolate.
graph: ops.Graph object containing all nodes referenced in the error
message.
Returns:
The string with tags of the form {{type name}} interpolated. | Interpolates an error message. | [
"Interpolates",
"an",
"error",
"message",
"."
] | def interpolate(error_message, graph):
"""Interpolates an error message.
The error message can contain tags of the form `{{type name}}` which will be
replaced. For example: "{{node <name>}}" would get expanded to:
"node <name>(defined at <path>)".
Args:
error_message: A string to interpolate.
graph: ops.Graph object containing all nodes referenced in the error
message.
Returns:
The string with tags of the form {{type name}} interpolated.
"""
seps, tags = parse_message(error_message)
subs = []
end_msg = collections.defaultdict(list)
tagged_ops = []
for t in tags:
try:
op = graph.get_operation_by_name(t.name)
except KeyError:
op = None
if op is None:
tagged_ops.append(None)
else:
tagged_ops.append([op] + _sources_for_node(op, graph))
common_prefix = traceback_files_common_prefix(tagged_ops)
for tag, ops in zip(tags, tagged_ops):
msg = "{{%s %s}}" % (tag.type, tag.name)
if ops is not None:
if tag.type == "node":
msg, source_msg = _build_error_message(ops[0], ops[1:], common_prefix)
if source_msg:
end_msg["source_nodes"].append(source_msg)
elif tag.type == "colocation_node":
field_dict = compute_field_dict(ops[0], common_prefix)
msg = "node %s%s placed on device %s " % (
ops[0].name, field_dict["defined_at"], field_dict["devices"])
end_msg["colocations"].append(field_dict["devs_and_colocs"])
if tag.type == "function_node":
msg = ""
subs.append(msg)
if "source_nodes" in end_msg:
subs.append("\n\nErrors may have originated from an input operation.")
subs.append("\n".join(end_msg["source_nodes"]))
end_msg.pop("source_nodes", None)
for k, messages in end_msg.items():
subs.append("Additional information about %s:" % k)
subs.append("\n".join(messages))
return "".join(
itertools.chain(*six.moves.zip_longest(seps, subs, fillvalue=""))) | [
"def",
"interpolate",
"(",
"error_message",
",",
"graph",
")",
":",
"seps",
",",
"tags",
"=",
"parse_message",
"(",
"error_message",
")",
"subs",
"=",
"[",
"]",
"end_msg",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"tagged_ops",
"=",
"[",
"]",
"for",
"t",
"in",
"tags",
":",
"try",
":",
"op",
"=",
"graph",
".",
"get_operation_by_name",
"(",
"t",
".",
"name",
")",
"except",
"KeyError",
":",
"op",
"=",
"None",
"if",
"op",
"is",
"None",
":",
"tagged_ops",
".",
"append",
"(",
"None",
")",
"else",
":",
"tagged_ops",
".",
"append",
"(",
"[",
"op",
"]",
"+",
"_sources_for_node",
"(",
"op",
",",
"graph",
")",
")",
"common_prefix",
"=",
"traceback_files_common_prefix",
"(",
"tagged_ops",
")",
"for",
"tag",
",",
"ops",
"in",
"zip",
"(",
"tags",
",",
"tagged_ops",
")",
":",
"msg",
"=",
"\"{{%s %s}}\"",
"%",
"(",
"tag",
".",
"type",
",",
"tag",
".",
"name",
")",
"if",
"ops",
"is",
"not",
"None",
":",
"if",
"tag",
".",
"type",
"==",
"\"node\"",
":",
"msg",
",",
"source_msg",
"=",
"_build_error_message",
"(",
"ops",
"[",
"0",
"]",
",",
"ops",
"[",
"1",
":",
"]",
",",
"common_prefix",
")",
"if",
"source_msg",
":",
"end_msg",
"[",
"\"source_nodes\"",
"]",
".",
"append",
"(",
"source_msg",
")",
"elif",
"tag",
".",
"type",
"==",
"\"colocation_node\"",
":",
"field_dict",
"=",
"compute_field_dict",
"(",
"ops",
"[",
"0",
"]",
",",
"common_prefix",
")",
"msg",
"=",
"\"node %s%s placed on device %s \"",
"%",
"(",
"ops",
"[",
"0",
"]",
".",
"name",
",",
"field_dict",
"[",
"\"defined_at\"",
"]",
",",
"field_dict",
"[",
"\"devices\"",
"]",
")",
"end_msg",
"[",
"\"colocations\"",
"]",
".",
"append",
"(",
"field_dict",
"[",
"\"devs_and_colocs\"",
"]",
")",
"if",
"tag",
".",
"type",
"==",
"\"function_node\"",
":",
"msg",
"=",
"\"\"",
"subs",
".",
"append",
"(",
"msg",
")",
"if",
"\"source_nodes\"",
"in",
"end_msg",
":",
"subs",
".",
"append",
"(",
"\"\\n\\nErrors may have originated from an input operation.\"",
")",
"subs",
".",
"append",
"(",
"\"\\n\"",
".",
"join",
"(",
"end_msg",
"[",
"\"source_nodes\"",
"]",
")",
")",
"end_msg",
".",
"pop",
"(",
"\"source_nodes\"",
",",
"None",
")",
"for",
"k",
",",
"messages",
"in",
"end_msg",
".",
"items",
"(",
")",
":",
"subs",
".",
"append",
"(",
"\"Additional information about %s:\"",
"%",
"k",
")",
"subs",
".",
"append",
"(",
"\"\\n\"",
".",
"join",
"(",
"messages",
")",
")",
"return",
"\"\"",
".",
"join",
"(",
"itertools",
".",
"chain",
"(",
"*",
"six",
".",
"moves",
".",
"zip_longest",
"(",
"seps",
",",
"subs",
",",
"fillvalue",
"=",
"\"\"",
")",
")",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/error_interpolation.py#L424-L480 | |
GeometryCollective/boundary-first-flattening | 8250e5a0e85980ec50b5e8aa8f49dd6519f915cd | deps/nanogui/ext/pybind11/tools/clang/cindex.py | python | TranslationUnit.spelling | (self) | return conf.lib.clang_getTranslationUnitSpelling(self) | Get the original translation unit source file name. | Get the original translation unit source file name. | [
"Get",
"the",
"original",
"translation",
"unit",
"source",
"file",
"name",
"."
] | def spelling(self):
"""Get the original translation unit source file name."""
return conf.lib.clang_getTranslationUnitSpelling(self) | [
"def",
"spelling",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_getTranslationUnitSpelling",
"(",
"self",
")"
] | https://github.com/GeometryCollective/boundary-first-flattening/blob/8250e5a0e85980ec50b5e8aa8f49dd6519f915cd/deps/nanogui/ext/pybind11/tools/clang/cindex.py#L2456-L2458 | |
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | syzygy/build/variable_expansion.py | python | _GetVar | (vars, key_match) | return value | Looks up a variable (in the first group of the RE match |key_match|) and
returns its value. If the variable has a prefix specifying encoding then the
encodings are first applied before returning the value. | Looks up a variable (in the first group of the RE match |key_match|) and
returns its value. If the variable has a prefix specifying encoding then the
encodings are first applied before returning the value. | [
"Looks",
"up",
"a",
"variable",
"(",
"in",
"the",
"first",
"group",
"of",
"the",
"RE",
"match",
"|key_match|",
")",
"and",
"returns",
"its",
"value",
".",
"If",
"the",
"variable",
"has",
"a",
"prefix",
"specifying",
"encoding",
"then",
"the",
"encodings",
"are",
"first",
"applied",
"before",
"returning",
"the",
"value",
"."
] | def _GetVar(vars, key_match):
"""Looks up a variable (in the first group of the RE match |key_match|) and
returns its value. If the variable has a prefix specifying encoding then the
encodings are first applied before returning the value.
"""
# Get the key.
key = key_match.group(1)
# Extract the encoding if one is specified.
enc = ''
m = re.match('^([^:]+):(.*)$', key)
if m:
enc = m.group(1).lower()
key = m.group(2)
# Raise an error for keys that don't exist.
if key not in vars:
raise Error('The value "%s" is not defined.' % key)
# Get the value and apply any encodings.
value = vars[key]
if 'a' in enc: # Absolute path encoding.
_LOGGER.info('Converting "%s" to absolute path.', key)
value = os.path.abspath(value)
if 'c' in enc: # C-style escaping.
_LOGGER.info('C-escaping "%s" value.', key)
value = json.dumps(value)[1:-1]
return value | [
"def",
"_GetVar",
"(",
"vars",
",",
"key_match",
")",
":",
"# Get the key.",
"key",
"=",
"key_match",
".",
"group",
"(",
"1",
")",
"# Extract the encoding if one is specified.",
"enc",
"=",
"''",
"m",
"=",
"re",
".",
"match",
"(",
"'^([^:]+):(.*)$'",
",",
"key",
")",
"if",
"m",
":",
"enc",
"=",
"m",
".",
"group",
"(",
"1",
")",
".",
"lower",
"(",
")",
"key",
"=",
"m",
".",
"group",
"(",
"2",
")",
"# Raise an error for keys that don't exist.",
"if",
"key",
"not",
"in",
"vars",
":",
"raise",
"Error",
"(",
"'The value \"%s\" is not defined.'",
"%",
"key",
")",
"# Get the value and apply any encodings.",
"value",
"=",
"vars",
"[",
"key",
"]",
"if",
"'a'",
"in",
"enc",
":",
"# Absolute path encoding.",
"_LOGGER",
".",
"info",
"(",
"'Converting \"%s\" to absolute path.'",
",",
"key",
")",
"value",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"value",
")",
"if",
"'c'",
"in",
"enc",
":",
"# C-style escaping.",
"_LOGGER",
".",
"info",
"(",
"'C-escaping \"%s\" value.'",
",",
"key",
")",
"value",
"=",
"json",
".",
"dumps",
"(",
"value",
")",
"[",
"1",
":",
"-",
"1",
"]",
"return",
"value"
] | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/syzygy/build/variable_expansion.py#L86-L115 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/nn/quantized/modules/conv.py | python | _ConvNd.get_qconv | (cls, mod, activation_post_process, weight_post_process=None) | r"""Creates a qconv object and returns it. | r"""Creates a qconv object and returns it. | [
"r",
"Creates",
"a",
"qconv",
"object",
"and",
"returns",
"it",
"."
] | def get_qconv(cls, mod, activation_post_process, weight_post_process=None):
r"""Creates a qconv object and returns it.
"""
if weight_post_process is None:
weight_post_process = mod.qconfig.weight()
weight_post_process(mod.weight)
assert weight_post_process.dtype == torch.qint8, \
'Weight observer must have a dtype of qint8'
qweight = _quantize_weight(mod.weight.float(), weight_post_process)
# the __init__ call used is the one from derived classes and not the one from _ConvNd
qconv = cls(mod.in_channels, mod.out_channels, mod.kernel_size,
mod.stride, mod.padding, mod.dilation, mod.groups,
mod.bias is not None, mod.padding_mode)
qconv.set_weight_bias(qweight, mod.bias)
if activation_post_process is None or activation_post_process.dtype == torch.float:
return qconv # dynamic quantization doesn't need scale/zero_point
else:
act_scale, act_zp = activation_post_process.calculate_qparams()
qconv.scale = float(act_scale)
qconv.zero_point = int(act_zp)
return qconv | [
"def",
"get_qconv",
"(",
"cls",
",",
"mod",
",",
"activation_post_process",
",",
"weight_post_process",
"=",
"None",
")",
":",
"if",
"weight_post_process",
"is",
"None",
":",
"weight_post_process",
"=",
"mod",
".",
"qconfig",
".",
"weight",
"(",
")",
"weight_post_process",
"(",
"mod",
".",
"weight",
")",
"assert",
"weight_post_process",
".",
"dtype",
"==",
"torch",
".",
"qint8",
",",
"'Weight observer must have a dtype of qint8'",
"qweight",
"=",
"_quantize_weight",
"(",
"mod",
".",
"weight",
".",
"float",
"(",
")",
",",
"weight_post_process",
")",
"# the __init__ call used is the one from derived classes and not the one from _ConvNd",
"qconv",
"=",
"cls",
"(",
"mod",
".",
"in_channels",
",",
"mod",
".",
"out_channels",
",",
"mod",
".",
"kernel_size",
",",
"mod",
".",
"stride",
",",
"mod",
".",
"padding",
",",
"mod",
".",
"dilation",
",",
"mod",
".",
"groups",
",",
"mod",
".",
"bias",
"is",
"not",
"None",
",",
"mod",
".",
"padding_mode",
")",
"qconv",
".",
"set_weight_bias",
"(",
"qweight",
",",
"mod",
".",
"bias",
")",
"if",
"activation_post_process",
"is",
"None",
"or",
"activation_post_process",
".",
"dtype",
"==",
"torch",
".",
"float",
":",
"return",
"qconv",
"# dynamic quantization doesn't need scale/zero_point",
"else",
":",
"act_scale",
",",
"act_zp",
"=",
"activation_post_process",
".",
"calculate_qparams",
"(",
")",
"qconv",
".",
"scale",
"=",
"float",
"(",
"act_scale",
")",
"qconv",
".",
"zero_point",
"=",
"int",
"(",
"act_zp",
")",
"return",
"qconv"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/nn/quantized/modules/conv.py#L192-L212 | ||
macchina-io/macchina.io | ef24ba0e18379c3dd48fb84e6dbf991101cb8db0 | platform/JS/V8/tools/gyp/pylib/gyp/msvs_emulation.py | python | MsvsSettings._HasExplicitRuleForExtension | (self, spec, extension) | return False | Determine if there's an explicit rule for a particular extension. | Determine if there's an explicit rule for a particular extension. | [
"Determine",
"if",
"there",
"s",
"an",
"explicit",
"rule",
"for",
"a",
"particular",
"extension",
"."
] | def _HasExplicitRuleForExtension(self, spec, extension):
"""Determine if there's an explicit rule for a particular extension."""
for rule in spec.get('rules', []):
if rule['extension'] == extension:
return True
return False | [
"def",
"_HasExplicitRuleForExtension",
"(",
"self",
",",
"spec",
",",
"extension",
")",
":",
"for",
"rule",
"in",
"spec",
".",
"get",
"(",
"'rules'",
",",
"[",
"]",
")",
":",
"if",
"rule",
"[",
"'extension'",
"]",
"==",
"extension",
":",
"return",
"True",
"return",
"False"
] | https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/tools/gyp/pylib/gyp/msvs_emulation.py#L829-L834 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/asyncio/tasks.py | python | wait | (fs, *, loop=None, timeout=None, return_when=ALL_COMPLETED) | return await _wait(fs, timeout, return_when, loop) | Wait for the Futures and coroutines given by fs to complete.
The sequence futures must not be empty.
Coroutines will be wrapped in Tasks.
Returns two sets of Future: (done, pending).
Usage:
done, pending = await asyncio.wait(fs)
Note: This does not raise TimeoutError! Futures that aren't done
when the timeout occurs are returned in the second set. | Wait for the Futures and coroutines given by fs to complete. | [
"Wait",
"for",
"the",
"Futures",
"and",
"coroutines",
"given",
"by",
"fs",
"to",
"complete",
"."
] | async def wait(fs, *, loop=None, timeout=None, return_when=ALL_COMPLETED):
"""Wait for the Futures and coroutines given by fs to complete.
The sequence futures must not be empty.
Coroutines will be wrapped in Tasks.
Returns two sets of Future: (done, pending).
Usage:
done, pending = await asyncio.wait(fs)
Note: This does not raise TimeoutError! Futures that aren't done
when the timeout occurs are returned in the second set.
"""
if futures.isfuture(fs) or coroutines.iscoroutine(fs):
raise TypeError(f"expect a list of futures, not {type(fs).__name__}")
if not fs:
raise ValueError('Set of coroutines/Futures is empty.')
if return_when not in (FIRST_COMPLETED, FIRST_EXCEPTION, ALL_COMPLETED):
raise ValueError(f'Invalid return_when value: {return_when}')
if loop is None:
loop = events.get_event_loop()
fs = {ensure_future(f, loop=loop) for f in set(fs)}
return await _wait(fs, timeout, return_when, loop) | [
"async",
"def",
"wait",
"(",
"fs",
",",
"*",
",",
"loop",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"return_when",
"=",
"ALL_COMPLETED",
")",
":",
"if",
"futures",
".",
"isfuture",
"(",
"fs",
")",
"or",
"coroutines",
".",
"iscoroutine",
"(",
"fs",
")",
":",
"raise",
"TypeError",
"(",
"f\"expect a list of futures, not {type(fs).__name__}\"",
")",
"if",
"not",
"fs",
":",
"raise",
"ValueError",
"(",
"'Set of coroutines/Futures is empty.'",
")",
"if",
"return_when",
"not",
"in",
"(",
"FIRST_COMPLETED",
",",
"FIRST_EXCEPTION",
",",
"ALL_COMPLETED",
")",
":",
"raise",
"ValueError",
"(",
"f'Invalid return_when value: {return_when}'",
")",
"if",
"loop",
"is",
"None",
":",
"loop",
"=",
"events",
".",
"get_event_loop",
"(",
")",
"fs",
"=",
"{",
"ensure_future",
"(",
"f",
",",
"loop",
"=",
"loop",
")",
"for",
"f",
"in",
"set",
"(",
"fs",
")",
"}",
"return",
"await",
"_wait",
"(",
"fs",
",",
"timeout",
",",
"return_when",
",",
"loop",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/asyncio/tasks.py#L361-L389 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/psutil/__init__.py | python | virtual_memory | () | return ret | Return statistics about system memory usage as a namedtuple
including the following fields, expressed in bytes:
- total:
total physical memory available.
- available:
the memory that can be given instantly to processes without the
system going into swap.
This is calculated by summing different memory values depending
on the platform and it is supposed to be used to monitor actual
memory usage in a cross platform fashion.
- percent:
the percentage usage calculated as (total - available) / total * 100
- used:
memory used, calculated differently depending on the platform and
designed for informational purposes only:
macOS: active + wired
BSD: active + wired + cached
Linux: total - free
- free:
memory not being used at all (zeroed) that is readily available;
note that this doesn't reflect the actual memory available
(use 'available' instead)
Platform-specific fields:
- active (UNIX):
memory currently in use or very recently used, and so it is in RAM.
- inactive (UNIX):
memory that is marked as not used.
- buffers (BSD, Linux):
cache for things like file system metadata.
- cached (BSD, macOS):
cache for various things.
- wired (macOS, BSD):
memory that is marked to always stay in RAM. It is never moved to disk.
- shared (BSD):
memory that may be simultaneously accessed by multiple processes.
The sum of 'used' and 'available' does not necessarily equal total.
On Windows 'available' and 'free' are the same. | Return statistics about system memory usage as a namedtuple
including the following fields, expressed in bytes: | [
"Return",
"statistics",
"about",
"system",
"memory",
"usage",
"as",
"a",
"namedtuple",
"including",
"the",
"following",
"fields",
"expressed",
"in",
"bytes",
":"
] | def virtual_memory():
"""Return statistics about system memory usage as a namedtuple
including the following fields, expressed in bytes:
- total:
total physical memory available.
- available:
the memory that can be given instantly to processes without the
system going into swap.
This is calculated by summing different memory values depending
on the platform and it is supposed to be used to monitor actual
memory usage in a cross platform fashion.
- percent:
the percentage usage calculated as (total - available) / total * 100
- used:
memory used, calculated differently depending on the platform and
designed for informational purposes only:
macOS: active + wired
BSD: active + wired + cached
Linux: total - free
- free:
memory not being used at all (zeroed) that is readily available;
note that this doesn't reflect the actual memory available
(use 'available' instead)
Platform-specific fields:
- active (UNIX):
memory currently in use or very recently used, and so it is in RAM.
- inactive (UNIX):
memory that is marked as not used.
- buffers (BSD, Linux):
cache for things like file system metadata.
- cached (BSD, macOS):
cache for various things.
- wired (macOS, BSD):
memory that is marked to always stay in RAM. It is never moved to disk.
- shared (BSD):
memory that may be simultaneously accessed by multiple processes.
The sum of 'used' and 'available' does not necessarily equal total.
On Windows 'available' and 'free' are the same.
"""
global _TOTAL_PHYMEM
ret = _psplatform.virtual_memory()
# cached for later use in Process.memory_percent()
_TOTAL_PHYMEM = ret.total
return ret | [
"def",
"virtual_memory",
"(",
")",
":",
"global",
"_TOTAL_PHYMEM",
"ret",
"=",
"_psplatform",
".",
"virtual_memory",
"(",
")",
"# cached for later use in Process.memory_percent()",
"_TOTAL_PHYMEM",
"=",
"ret",
".",
"total",
"return",
"ret"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/psutil/__init__.py#L1928-L1984 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/ops/control_flow_ops.py | python | _Enter | (data, frame_name, is_constant=False, parallel_iterations=10,
use_ref=True, use_input_shape=True, name=None) | Creates or finds a child frame, and makes `data` available to it.
The unique `frame_name` is used by the `Executor` to identify frames. If
`is_constant` is true, `data` is a constant in the child frame; otherwise
it may be changed in the child frame. At most `parallel_iterations`
iterations are run in parallel in the child frame.
Args:
data: The tensor to be made available to the child frame.
frame_name: The name of the child frame.
is_constant: If true, the output is constant within the child frame.
parallel_iterations: The number of iterations allowed to run in parallel.
use_ref: If true, use ref_enter if data is of ref type.
name: A name for this operation (optional).
Returns:
The same tensor as `data`. | Creates or finds a child frame, and makes `data` available to it. | [
"Creates",
"or",
"finds",
"a",
"child",
"frame",
"and",
"makes",
"data",
"available",
"to",
"it",
"."
] | def _Enter(data, frame_name, is_constant=False, parallel_iterations=10,
use_ref=True, use_input_shape=True, name=None):
"""Creates or finds a child frame, and makes `data` available to it.
The unique `frame_name` is used by the `Executor` to identify frames. If
`is_constant` is true, `data` is a constant in the child frame; otherwise
it may be changed in the child frame. At most `parallel_iterations`
iterations are run in parallel in the child frame.
Args:
data: The tensor to be made available to the child frame.
frame_name: The name of the child frame.
is_constant: If true, the output is constant within the child frame.
parallel_iterations: The number of iterations allowed to run in parallel.
use_ref: If true, use ref_enter if data is of ref type.
name: A name for this operation (optional).
Returns:
The same tensor as `data`.
"""
data = ops.internal_convert_to_tensor_or_indexed_slices(data, as_ref=True)
if isinstance(data, ops.Tensor):
if data.dtype._is_ref_dtype and use_ref: # pylint: disable=protected-access
result = ref_enter(data, frame_name, is_constant, parallel_iterations,
name=name)
else:
result = enter(data, frame_name, is_constant, parallel_iterations,
name=name)
if use_input_shape:
result.set_shape(data.get_shape())
return result
else:
if not isinstance(data, (ops.IndexedSlices, sparse_tensor.SparseTensor)):
raise TypeError("Type %s not supported" % type(data))
values = _Enter(data.values, frame_name, is_constant,
parallel_iterations=parallel_iterations,
use_input_shape=use_input_shape, name=name)
indices = enter(data.indices, frame_name, is_constant,
parallel_iterations, name="indices")
if use_input_shape:
indices.set_shape(data.indices.get_shape())
if isinstance(data, ops.IndexedSlices):
dense_shape = data.dense_shape
if dense_shape is not None:
dense_shape = enter(dense_shape, frame_name, is_constant,
parallel_iterations, name="dense_shape")
if use_input_shape:
dense_shape.set_shape(data.dense_shape.get_shape())
return ops.IndexedSlices(values, indices, dense_shape)
else:
dense_shape = enter(data.dense_shape, frame_name, is_constant,
parallel_iterations, name="dense_shape")
if use_input_shape:
dense_shape.set_shape(data.dense_shape.get_shape())
return sparse_tensor.SparseTensor(indices, values, dense_shape) | [
"def",
"_Enter",
"(",
"data",
",",
"frame_name",
",",
"is_constant",
"=",
"False",
",",
"parallel_iterations",
"=",
"10",
",",
"use_ref",
"=",
"True",
",",
"use_input_shape",
"=",
"True",
",",
"name",
"=",
"None",
")",
":",
"data",
"=",
"ops",
".",
"internal_convert_to_tensor_or_indexed_slices",
"(",
"data",
",",
"as_ref",
"=",
"True",
")",
"if",
"isinstance",
"(",
"data",
",",
"ops",
".",
"Tensor",
")",
":",
"if",
"data",
".",
"dtype",
".",
"_is_ref_dtype",
"and",
"use_ref",
":",
"# pylint: disable=protected-access",
"result",
"=",
"ref_enter",
"(",
"data",
",",
"frame_name",
",",
"is_constant",
",",
"parallel_iterations",
",",
"name",
"=",
"name",
")",
"else",
":",
"result",
"=",
"enter",
"(",
"data",
",",
"frame_name",
",",
"is_constant",
",",
"parallel_iterations",
",",
"name",
"=",
"name",
")",
"if",
"use_input_shape",
":",
"result",
".",
"set_shape",
"(",
"data",
".",
"get_shape",
"(",
")",
")",
"return",
"result",
"else",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"(",
"ops",
".",
"IndexedSlices",
",",
"sparse_tensor",
".",
"SparseTensor",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"Type %s not supported\"",
"%",
"type",
"(",
"data",
")",
")",
"values",
"=",
"_Enter",
"(",
"data",
".",
"values",
",",
"frame_name",
",",
"is_constant",
",",
"parallel_iterations",
"=",
"parallel_iterations",
",",
"use_input_shape",
"=",
"use_input_shape",
",",
"name",
"=",
"name",
")",
"indices",
"=",
"enter",
"(",
"data",
".",
"indices",
",",
"frame_name",
",",
"is_constant",
",",
"parallel_iterations",
",",
"name",
"=",
"\"indices\"",
")",
"if",
"use_input_shape",
":",
"indices",
".",
"set_shape",
"(",
"data",
".",
"indices",
".",
"get_shape",
"(",
")",
")",
"if",
"isinstance",
"(",
"data",
",",
"ops",
".",
"IndexedSlices",
")",
":",
"dense_shape",
"=",
"data",
".",
"dense_shape",
"if",
"dense_shape",
"is",
"not",
"None",
":",
"dense_shape",
"=",
"enter",
"(",
"dense_shape",
",",
"frame_name",
",",
"is_constant",
",",
"parallel_iterations",
",",
"name",
"=",
"\"dense_shape\"",
")",
"if",
"use_input_shape",
":",
"dense_shape",
".",
"set_shape",
"(",
"data",
".",
"dense_shape",
".",
"get_shape",
"(",
")",
")",
"return",
"ops",
".",
"IndexedSlices",
"(",
"values",
",",
"indices",
",",
"dense_shape",
")",
"else",
":",
"dense_shape",
"=",
"enter",
"(",
"data",
".",
"dense_shape",
",",
"frame_name",
",",
"is_constant",
",",
"parallel_iterations",
",",
"name",
"=",
"\"dense_shape\"",
")",
"if",
"use_input_shape",
":",
"dense_shape",
".",
"set_shape",
"(",
"data",
".",
"dense_shape",
".",
"get_shape",
"(",
")",
")",
"return",
"sparse_tensor",
".",
"SparseTensor",
"(",
"indices",
",",
"values",
",",
"dense_shape",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/control_flow_ops.py#L188-L242 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_misc.py | python | GetStockLabel | (*args, **kwargs) | return _misc_.GetStockLabel(*args, **kwargs) | GetStockLabel(int id, long flags=STOCK_WITH_MNEMONIC) -> String | GetStockLabel(int id, long flags=STOCK_WITH_MNEMONIC) -> String | [
"GetStockLabel",
"(",
"int",
"id",
"long",
"flags",
"=",
"STOCK_WITH_MNEMONIC",
")",
"-",
">",
"String"
] | def GetStockLabel(*args, **kwargs):
"""GetStockLabel(int id, long flags=STOCK_WITH_MNEMONIC) -> String"""
return _misc_.GetStockLabel(*args, **kwargs) | [
"def",
"GetStockLabel",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"GetStockLabel",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L307-L309 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/ops/nn_ops.py | python | erosion2d | (value, kernel, strides, rates, padding, name=None) | Computes the grayscale erosion of 4-D `value` and 3-D `kernel` tensors.
The `value` tensor has shape `[batch, in_height, in_width, depth]` and the
`kernel` tensor has shape `[kernel_height, kernel_width, depth]`, i.e.,
each input channel is processed independently of the others with its own
structuring function. The `output` tensor has shape
`[batch, out_height, out_width, depth]`. The spatial dimensions of the
output tensor depend on the `padding` algorithm. We currently only support the
default "NHWC" `data_format`.
In detail, the grayscale morphological 2-D erosion is given by:
output[b, y, x, c] =
min_{dy, dx} value[b,
strides[1] * y - rates[1] * dy,
strides[2] * x - rates[2] * dx,
c] -
kernel[dy, dx, c]
Duality: The erosion of `value` by the `kernel` is equal to the negation of
the dilation of `-value` by the reflected `kernel`.
Args:
value: A `Tensor`. 4-D with shape `[batch, in_height, in_width, depth]`.
kernel: A `Tensor`. Must have the same type as `value`.
3-D with shape `[kernel_height, kernel_width, depth]`.
strides: A list of `ints` that has length `>= 4`.
1-D of length 4. The stride of the sliding window for each dimension of
the input tensor. Must be: `[1, stride_height, stride_width, 1]`.
rates: A list of `ints` that has length `>= 4`.
1-D of length 4. The input stride for atrous morphological dilation.
Must be: `[1, rate_height, rate_width, 1]`.
padding: A `string` from: `"SAME", "VALID"`.
The type of padding algorithm to use.
name: A name for the operation (optional). If not specified "erosion2d"
is used.
Returns:
A `Tensor`. Has the same type as `value`.
4-D with shape `[batch, out_height, out_width, depth]`.
Raises:
ValueError: If the `value` depth does not match `kernel`' shape, or if
padding is other than `'VALID'` or `'SAME'`. | Computes the grayscale erosion of 4-D `value` and 3-D `kernel` tensors. | [
"Computes",
"the",
"grayscale",
"erosion",
"of",
"4",
"-",
"D",
"value",
"and",
"3",
"-",
"D",
"kernel",
"tensors",
"."
] | def erosion2d(value, kernel, strides, rates, padding, name=None):
"""Computes the grayscale erosion of 4-D `value` and 3-D `kernel` tensors.
The `value` tensor has shape `[batch, in_height, in_width, depth]` and the
`kernel` tensor has shape `[kernel_height, kernel_width, depth]`, i.e.,
each input channel is processed independently of the others with its own
structuring function. The `output` tensor has shape
`[batch, out_height, out_width, depth]`. The spatial dimensions of the
output tensor depend on the `padding` algorithm. We currently only support the
default "NHWC" `data_format`.
In detail, the grayscale morphological 2-D erosion is given by:
output[b, y, x, c] =
min_{dy, dx} value[b,
strides[1] * y - rates[1] * dy,
strides[2] * x - rates[2] * dx,
c] -
kernel[dy, dx, c]
Duality: The erosion of `value` by the `kernel` is equal to the negation of
the dilation of `-value` by the reflected `kernel`.
Args:
value: A `Tensor`. 4-D with shape `[batch, in_height, in_width, depth]`.
kernel: A `Tensor`. Must have the same type as `value`.
3-D with shape `[kernel_height, kernel_width, depth]`.
strides: A list of `ints` that has length `>= 4`.
1-D of length 4. The stride of the sliding window for each dimension of
the input tensor. Must be: `[1, stride_height, stride_width, 1]`.
rates: A list of `ints` that has length `>= 4`.
1-D of length 4. The input stride for atrous morphological dilation.
Must be: `[1, rate_height, rate_width, 1]`.
padding: A `string` from: `"SAME", "VALID"`.
The type of padding algorithm to use.
name: A name for the operation (optional). If not specified "erosion2d"
is used.
Returns:
A `Tensor`. Has the same type as `value`.
4-D with shape `[batch, out_height, out_width, depth]`.
Raises:
ValueError: If the `value` depth does not match `kernel`' shape, or if
padding is other than `'VALID'` or `'SAME'`.
"""
with ops.name_scope(name, "erosion2d", [value, kernel]) as name:
# Reduce erosion to dilation by duality.
return math_ops.neg(gen_nn_ops.dilation2d(input=math_ops.neg(value),
filter=array_ops.reverse(
kernel, [True, True, False]),
strides=strides,
rates=rates,
padding=padding,
name=name)) | [
"def",
"erosion2d",
"(",
"value",
",",
"kernel",
",",
"strides",
",",
"rates",
",",
"padding",
",",
"name",
"=",
"None",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"\"erosion2d\"",
",",
"[",
"value",
",",
"kernel",
"]",
")",
"as",
"name",
":",
"# Reduce erosion to dilation by duality.",
"return",
"math_ops",
".",
"neg",
"(",
"gen_nn_ops",
".",
"dilation2d",
"(",
"input",
"=",
"math_ops",
".",
"neg",
"(",
"value",
")",
",",
"filter",
"=",
"array_ops",
".",
"reverse",
"(",
"kernel",
",",
"[",
"True",
",",
"True",
",",
"False",
"]",
")",
",",
"strides",
"=",
"strides",
",",
"rates",
"=",
"rates",
",",
"padding",
"=",
"padding",
",",
"name",
"=",
"name",
")",
")"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/ops/nn_ops.py#L1872-L1926 | ||
cvxpy/cvxpy | 5165b4fb750dfd237de8659383ef24b4b2e33aaf | cvxpy/expressions/expression.py | python | Expression.is_psd | (self) | return False | Is the expression a positive semidefinite matrix? | Is the expression a positive semidefinite matrix? | [
"Is",
"the",
"expression",
"a",
"positive",
"semidefinite",
"matrix?"
] | def is_psd(self) -> bool:
"""Is the expression a positive semidefinite matrix?
"""
# Default to False.
return False | [
"def",
"is_psd",
"(",
"self",
")",
"->",
"bool",
":",
"# Default to False.",
"return",
"False"
] | https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/expressions/expression.py#L296-L300 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | Framework/PythonInterface/mantid/kernel/environment.py | python | is_64bit | () | Returns True if the current platform is 64-bit | Returns True if the current platform is 64-bit | [
"Returns",
"True",
"if",
"the",
"current",
"platform",
"is",
"64",
"-",
"bit"
] | def is_64bit():
"""
Returns True if the current platform is 64-bit
"""
if is_mac():
# See Python documentation on platform module for why this is different
return _sys.maxsize > 2**32
else:
bits = _platform.architecture()[0]
return bits == '64bit' | [
"def",
"is_64bit",
"(",
")",
":",
"if",
"is_mac",
"(",
")",
":",
"# See Python documentation on platform module for why this is different",
"return",
"_sys",
".",
"maxsize",
">",
"2",
"**",
"32",
"else",
":",
"bits",
"=",
"_platform",
".",
"architecture",
"(",
")",
"[",
"0",
"]",
"return",
"bits",
"==",
"'64bit'"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/mantid/kernel/environment.py#L52-L61 | ||
microsoft/CNTK | e9396480025b9ca457d26b6f33dd07c474c6aa04 | bindings/python/cntk/ops/functions.py | python | Function.find_all_with_name | (self, name, depth=0) | return graph.find_all_with_name(self, name, depth) | Returns a list of primitive function with ``name`` in the graph
starting from this node. Throws an exception if ``name`` occurs
multiple times. If you expect only one function to be returned, use
:func:`find_by_name`.
Example:
>>> a = C.input_variable(shape=1, name='i')
>>> b = C.input_variable(shape=1, name='i')
>>> c = C.plus(a, b, name='c')
>>> len(c.find_all_with_name('i'))
2
>>> c.find_all_with_name('z')
[]
Args:
name (str): names to look for
depth (int, default 0): how deep into the block hierarchy the DFS
algorithm should go into. Set to -1 for infinite depth.
Returns:
list of :class:`Function` objects matching ``name``
See also:
:func:`find_by_name` | Returns a list of primitive function with ``name`` in the graph
starting from this node. Throws an exception if ``name`` occurs
multiple times. If you expect only one function to be returned, use
:func:`find_by_name`. | [
"Returns",
"a",
"list",
"of",
"primitive",
"function",
"with",
"name",
"in",
"the",
"graph",
"starting",
"from",
"this",
"node",
".",
"Throws",
"an",
"exception",
"if",
"name",
"occurs",
"multiple",
"times",
".",
"If",
"you",
"expect",
"only",
"one",
"function",
"to",
"be",
"returned",
"use",
":",
"func",
":",
"find_by_name",
"."
] | def find_all_with_name(self, name, depth=0):
'''
Returns a list of primitive function with ``name`` in the graph
starting from this node. Throws an exception if ``name`` occurs
multiple times. If you expect only one function to be returned, use
:func:`find_by_name`.
Example:
>>> a = C.input_variable(shape=1, name='i')
>>> b = C.input_variable(shape=1, name='i')
>>> c = C.plus(a, b, name='c')
>>> len(c.find_all_with_name('i'))
2
>>> c.find_all_with_name('z')
[]
Args:
name (str): names to look for
depth (int, default 0): how deep into the block hierarchy the DFS
algorithm should go into. Set to -1 for infinite depth.
Returns:
list of :class:`Function` objects matching ``name``
See also:
:func:`find_by_name`
'''
from cntk.logging import graph
return graph.find_all_with_name(self, name, depth) | [
"def",
"find_all_with_name",
"(",
"self",
",",
"name",
",",
"depth",
"=",
"0",
")",
":",
"from",
"cntk",
".",
"logging",
"import",
"graph",
"return",
"graph",
".",
"find_all_with_name",
"(",
"self",
",",
"name",
",",
"depth",
")"
] | https://github.com/microsoft/CNTK/blob/e9396480025b9ca457d26b6f33dd07c474c6aa04/bindings/python/cntk/ops/functions.py#L1230-L1258 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.