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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
microsoft/checkedc-clang | a173fefde5d7877b7750e7ce96dd08cf18baebf2 | lldb/utils/lui/lldbutil.py | python | ChildVisitingFormatter.__init__ | (self, indent_child=2) | Default indentation of 2 SPC's for the children. | Default indentation of 2 SPC's for the children. | [
"Default",
"indentation",
"of",
"2",
"SPC",
"s",
"for",
"the",
"children",
"."
] | def __init__(self, indent_child=2):
"""Default indentation of 2 SPC's for the children."""
self.cindent = indent_child | [
"def",
"__init__",
"(",
"self",
",",
"indent_child",
"=",
"2",
")",
":",
"self",
".",
"cindent",
"=",
"indent_child"
] | https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/lldb/utils/lui/lldbutil.py#L989-L991 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/py_vulcanize/third_party/rjsmin/_setup/py2/ext.py | python | ConfTest.__del__ | (self) | Destruction | Destruction | [
"Destruction"
] | def __del__(self):
""" Destruction """
self.destroy() | [
"def",
"__del__",
"(",
"self",
")",
":",
"self",
".",
"destroy",
"(",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/py_vulcanize/third_party/rjsmin/_setup/py2/ext.py#L193-L195 | ||
letscontrolit/ESPEasy | acb2c9e695d6f61d8d67adf0fe4037c08d4baedd | lib/IRremoteESP8266/tools/auto_analyse_raw_data.py | python | dump_constants | (message, defines, name="", output=sys.stdout) | Dump the key constants and generate the C++ #defines. | Dump the key constants and generate the C++ #defines. | [
"Dump",
"the",
"key",
"constants",
"and",
"generate",
"the",
"C",
"++",
"#defines",
"."
] | def dump_constants(message, defines, name="", output=sys.stdout):
"""Dump the key constants and generate the C++ #defines."""
ldr_mark = None
hdr_mark = 0
hdr_space = 0
if message.ldr_mark is not None:
ldr_mark = avg_list(message.mark_buckets[message.ldr_mark])
if message.hdr_mark != 0:
hdr_mark = avg_list(message.mark_buckets[message.hdr_mark])
bit_mark = avg_list(message.mark_buckets[message.bit_mark])
if message.hdr_space is not None:
hdr_space = avg_list(message.space_buckets[message.hdr_space])
one_space = avg_list(message.space_buckets[message.one_space])
zero_space = avg_list(message.space_buckets[message.zero_space])
output.write("Guessing key value:\n"
f"k{name}HdrMark = {hdr_mark}\n"
f"k{name}HdrSpace = {hdr_space}\n"
f"k{name}BitMark = {bit_mark}\n"
f"k{name}OneSpace = {one_space}\n"
f"k{name}ZeroSpace = {zero_space}\n")
defines.append(f"const uint16_t k{name}HdrMark = {hdr_mark};")
defines.append(f"const uint16_t k{name}BitMark = {bit_mark};")
defines.append(f"const uint16_t k{name}HdrSpace = {hdr_space};")
defines.append(f"const uint16_t k{name}OneSpace = {one_space};")
defines.append(f"const uint16_t k{name}ZeroSpace = {zero_space};")
if ldr_mark:
output.write(f"k{name}LdrMark = {ldr_mark}\n")
defines.append(f"const uint16_t k{name}LdrMark = {ldr_mark};")
avg_gaps = [avg_list(message.space_buckets[x]) for x in message.gaps]
if len(message.gaps) == 1:
output.write(f"k{name}SpaceGap = {avg_gaps[0]}\n")
defines.append(f"const uint16_t k{name}SpaceGap = {avg_gaps[0]};")
else:
count = 0
for gap in avg_gaps:
# We probably (still) have a gap in the protocol.
count = count + 1
output.write(f"k{name}SpaceGap{count} = {gap}\n")
defines.append(f"const uint16_t k{name}SpaceGap{count} = {gap};")
defines.append(f"const uint16_t k{name}Freq = 38000; "
"// Hz. (Guessing the most common frequency.)") | [
"def",
"dump_constants",
"(",
"message",
",",
"defines",
",",
"name",
"=",
"\"\"",
",",
"output",
"=",
"sys",
".",
"stdout",
")",
":",
"ldr_mark",
"=",
"None",
"hdr_mark",
"=",
"0",
"hdr_space",
"=",
"0",
"if",
"message",
".",
"ldr_mark",
"is",
"not",
... | https://github.com/letscontrolit/ESPEasy/blob/acb2c9e695d6f61d8d67adf0fe4037c08d4baedd/lib/IRremoteESP8266/tools/auto_analyse_raw_data.py#L315-L357 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/req/req_uninstall.py | python | UninstallPathSet.rollback | (self) | Rollback the changes previously made by remove(). | Rollback the changes previously made by remove(). | [
"Rollback",
"the",
"changes",
"previously",
"made",
"by",
"remove",
"()",
"."
] | def rollback(self):
# type: () -> None
"""Rollback the changes previously made by remove()."""
if not self._moved_paths.can_rollback:
logger.error(
"Can't roll back %s; was not uninstalled",
self.dist.project_name,
)
return
logger.info('Rolling back uninstall of %s', self.dist.project_name)
self._moved_paths.rollback()
for pth in self.pth.values():
pth.rollback() | [
"def",
"rollback",
"(",
"self",
")",
":",
"# type: () -> None",
"if",
"not",
"self",
".",
"_moved_paths",
".",
"can_rollback",
":",
"logger",
".",
"error",
"(",
"\"Can't roll back %s; was not uninstalled\"",
",",
"self",
".",
"dist",
".",
"project_name",
",",
")... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/req/req_uninstall.py#L877-L901 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/WebOb/webob/cookies.py | python | Base64Serializer.loads | (self, bstruct) | return self.serializer.loads(cstruct) | Given a ``bstruct`` (a bytestring), verify the signature and then
deserialize and return the deserialized value.
A ``ValueError`` will be raised if the signature fails to validate. | Given a ``bstruct`` (a bytestring), verify the signature and then
deserialize and return the deserialized value. | [
"Given",
"a",
"bstruct",
"(",
"a",
"bytestring",
")",
"verify",
"the",
"signature",
"and",
"then",
"deserialize",
"and",
"return",
"the",
"deserialized",
"value",
"."
] | def loads(self, bstruct):
"""
Given a ``bstruct`` (a bytestring), verify the signature and then
deserialize and return the deserialized value.
A ``ValueError`` will be raised if the signature fails to validate.
"""
try:
cstruct = base64.urlsafe_b64decode(bytes_(bstruct))
except (binascii.Error, TypeError) as e:
raise ValueError('Badly formed base64 data: %s' % e)
return self.serializer.loads(cstruct) | [
"def",
"loads",
"(",
"self",
",",
"bstruct",
")",
":",
"try",
":",
"cstruct",
"=",
"base64",
".",
"urlsafe_b64decode",
"(",
"bytes_",
"(",
"bstruct",
")",
")",
"except",
"(",
"binascii",
".",
"Error",
",",
"TypeError",
")",
"as",
"e",
":",
"raise",
"... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/WebOb/webob/cookies.py#L498-L510 | |
GeometryCollective/boundary-first-flattening | 8250e5a0e85980ec50b5e8aa8f49dd6519f915cd | deps/nanogui/docs/exhale.py | python | kindAsBreatheDirective | (kind) | return directive | Returns the appropriate breathe restructured text directive for the specified kind.
The output for a given kind is as follows:
+-------------+--------------------+
| Input Kind | Output Directive |
+=============+====================+
| "class" | "doxygenclass" |
+-------------+--------------------+
| "define" | "doxygendefine" |
+-------------+--------------------+
| "enum" | "doxygenenum" |
+-------------+--------------------+
| "enumvalue" | "doxygenenumvalue" |
+-------------+--------------------+
| "file" | "doxygenfile" |
+-------------+--------------------+
| "function" | "doxygenfunction" |
+-------------+--------------------+
| "group" | "doxygengroup" |
+-------------+--------------------+
| "namespace" | "doxygennamespace" |
+-------------+--------------------+
| "struct" | "doxygenstruct" |
+-------------+--------------------+
| "typedef" | "doxygentypedef" |
+-------------+--------------------+
| "union" | "doxygenunion" |
+-------------+--------------------+
| "variable" | "doxygenvariable" |
+-------------+--------------------+
The following breathe kinds are ignored:
- "autodoxygenfile"
- "doxygenindex"
- "autodoxygenindex"
Note also that although a return value is generated, neither "enumvalue" nor
"group" are actually used.
:Parameters:
``kind`` (str)
The kind of the breathe compound / ExhaleNode object (same values).
:Return (str):
The directive to be used for the given ``kind``. The empty string is returned
for both unrecognized and ignored input values. | Returns the appropriate breathe restructured text directive for the specified kind.
The output for a given kind is as follows: | [
"Returns",
"the",
"appropriate",
"breathe",
"restructured",
"text",
"directive",
"for",
"the",
"specified",
"kind",
".",
"The",
"output",
"for",
"a",
"given",
"kind",
"is",
"as",
"follows",
":"
] | def kindAsBreatheDirective(kind):
'''
Returns the appropriate breathe restructured text directive for the specified kind.
The output for a given kind is as follows:
+-------------+--------------------+
| Input Kind | Output Directive |
+=============+====================+
| "class" | "doxygenclass" |
+-------------+--------------------+
| "define" | "doxygendefine" |
+-------------+--------------------+
| "enum" | "doxygenenum" |
+-------------+--------------------+
| "enumvalue" | "doxygenenumvalue" |
+-------------+--------------------+
| "file" | "doxygenfile" |
+-------------+--------------------+
| "function" | "doxygenfunction" |
+-------------+--------------------+
| "group" | "doxygengroup" |
+-------------+--------------------+
| "namespace" | "doxygennamespace" |
+-------------+--------------------+
| "struct" | "doxygenstruct" |
+-------------+--------------------+
| "typedef" | "doxygentypedef" |
+-------------+--------------------+
| "union" | "doxygenunion" |
+-------------+--------------------+
| "variable" | "doxygenvariable" |
+-------------+--------------------+
The following breathe kinds are ignored:
- "autodoxygenfile"
- "doxygenindex"
- "autodoxygenindex"
Note also that although a return value is generated, neither "enumvalue" nor
"group" are actually used.
:Parameters:
``kind`` (str)
The kind of the breathe compound / ExhaleNode object (same values).
:Return (str):
The directive to be used for the given ``kind``. The empty string is returned
for both unrecognized and ignored input values.
'''
if kind == "class":
directive = "doxygenclass"
elif kind == "struct":
directive = "doxygenstruct"
elif kind == "function":
directive = "doxygenfunction"
elif kind == "enum":
directive = "doxygenenum"
elif kind == "enumvalue":# unused
directive = "doxygenenumvalue"
elif kind == "namespace":
directive = "doxygennamespace"
elif kind == "define":
directive = "doxygendefine"
elif kind == "typedef":
directive = "doxygentypedef"
elif kind == "variable":
directive = "doxygenvariable"
elif kind == "file":
directive = "doxygenfile"
elif kind == "union":
directive = "doxygenunion"
elif kind == "group":# unused
directive = "doxygengroup"
else:
directive = ""
return directive | [
"def",
"kindAsBreatheDirective",
"(",
"kind",
")",
":",
"if",
"kind",
"==",
"\"class\"",
":",
"directive",
"=",
"\"doxygenclass\"",
"elif",
"kind",
"==",
"\"struct\"",
":",
"directive",
"=",
"\"doxygenstruct\"",
"elif",
"kind",
"==",
"\"function\"",
":",
"direct... | https://github.com/GeometryCollective/boundary-first-flattening/blob/8250e5a0e85980ec50b5e8aa8f49dd6519f915cd/deps/nanogui/docs/exhale.py#L457-L533 | |
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBModule.FindFunctions | (self, *args) | return _lldb.SBModule_FindFunctions(self, *args) | FindFunctions(SBModule self, char const * name, uint32_t name_type_mask) -> SBSymbolContextList
FindFunctions(SBModule self, char const * name) -> SBSymbolContextList
Find functions by name.
@param[in] name
The name of the function we are looking for.
@param[in] name_type_mask
A logical OR of one or more FunctionNameType enum bits that
indicate what kind of names should be used when doing the
lookup. Bits include fully qualified names, base names,
C++ methods, or ObjC selectors.
See FunctionNameType for more details.
@return
A symbol context list that gets filled in with all of the
matches. | FindFunctions(SBModule self, char const * name, uint32_t name_type_mask) -> SBSymbolContextList
FindFunctions(SBModule self, char const * name) -> SBSymbolContextList | [
"FindFunctions",
"(",
"SBModule",
"self",
"char",
"const",
"*",
"name",
"uint32_t",
"name_type_mask",
")",
"-",
">",
"SBSymbolContextList",
"FindFunctions",
"(",
"SBModule",
"self",
"char",
"const",
"*",
"name",
")",
"-",
">",
"SBSymbolContextList"
] | def FindFunctions(self, *args):
"""
FindFunctions(SBModule self, char const * name, uint32_t name_type_mask) -> SBSymbolContextList
FindFunctions(SBModule self, char const * name) -> SBSymbolContextList
Find functions by name.
@param[in] name
The name of the function we are looking for.
@param[in] name_type_mask
A logical OR of one or more FunctionNameType enum bits that
indicate what kind of names should be used when doing the
lookup. Bits include fully qualified names, base names,
C++ methods, or ObjC selectors.
See FunctionNameType for more details.
@return
A symbol context list that gets filled in with all of the
matches.
"""
return _lldb.SBModule_FindFunctions(self, *args) | [
"def",
"FindFunctions",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_lldb",
".",
"SBModule_FindFunctions",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L7338-L7360 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/operator.py | python | length_hint | (obj, default=0) | return val | Return an estimate of the number of items in obj.
This is useful for presizing containers when building from an iterable.
If the object supports len(), the result will be exact. Otherwise, it may
over- or under-estimate by an arbitrary amount. The result will be an
integer >= 0. | Return an estimate of the number of items in obj.
This is useful for presizing containers when building from an iterable. | [
"Return",
"an",
"estimate",
"of",
"the",
"number",
"of",
"items",
"in",
"obj",
".",
"This",
"is",
"useful",
"for",
"presizing",
"containers",
"when",
"building",
"from",
"an",
"iterable",
"."
] | def length_hint(obj, default=0):
"""
Return an estimate of the number of items in obj.
This is useful for presizing containers when building from an iterable.
If the object supports len(), the result will be exact. Otherwise, it may
over- or under-estimate by an arbitrary amount. The result will be an
integer >= 0.
"""
if not isinstance(default, int):
msg = ("'%s' object cannot be interpreted as an integer" %
type(default).__name__)
raise TypeError(msg)
try:
return len(obj)
except TypeError:
pass
try:
hint = type(obj).__length_hint__
except AttributeError:
return default
try:
val = hint(obj)
except TypeError:
return default
if val is NotImplemented:
return default
if not isinstance(val, int):
msg = ('__length_hint__ must be integer, not %s' %
type(val).__name__)
raise TypeError(msg)
if val < 0:
msg = '__length_hint__() should return >= 0'
raise ValueError(msg)
return val | [
"def",
"length_hint",
"(",
"obj",
",",
"default",
"=",
"0",
")",
":",
"if",
"not",
"isinstance",
"(",
"default",
",",
"int",
")",
":",
"msg",
"=",
"(",
"\"'%s' object cannot be interpreted as an integer\"",
"%",
"type",
"(",
"default",
")",
".",
"__name__",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/operator.py#L185-L222 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/tensorboard/backend/handler.py | python | TensorboardHandler._send_json_response | (self, obj, code=200) | Writes out the given object as JSON using the given HTTP status code.
This also replaces special float values with stringified versions.
Args:
obj: The object to respond with.
code: The numeric HTTP status code to use. | Writes out the given object as JSON using the given HTTP status code. | [
"Writes",
"out",
"the",
"given",
"object",
"as",
"JSON",
"using",
"the",
"given",
"HTTP",
"status",
"code",
"."
] | def _send_json_response(self, obj, code=200):
"""Writes out the given object as JSON using the given HTTP status code.
This also replaces special float values with stringified versions.
Args:
obj: The object to respond with.
code: The numeric HTTP status code to use.
"""
content = json.dumps(json_util.WrapSpecialFloats(obj))
self._respond(content, 'application/json', code) | [
"def",
"_send_json_response",
"(",
"self",
",",
"obj",
",",
"code",
"=",
"200",
")",
":",
"content",
"=",
"json",
".",
"dumps",
"(",
"json_util",
".",
"WrapSpecialFloats",
"(",
"obj",
")",
")",
"self",
".",
"_respond",
"(",
"content",
",",
"'application/... | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/tensorboard/backend/handler.py#L225-L235 | ||
scummvm/scummvm | 9c039d027e7ffb9d83ae2e274147e2daf8d57ce2 | devtools/dumper-companion.py | python | decode_macjapanese | (text: ByteString) | return res | Decode Mac Japanse
Mac OS Japanese
https://en.wikipedia.org/wiki/Shift_JIS#MacJapanese
https://www.unicode.org/Public/MAPPINGS/VENDORS/APPLE/JAPANESE.TXT | Decode Mac Japanse | [
"Decode",
"Mac",
"Japanse"
] | def decode_macjapanese(text: ByteString) -> str:
"""
Decode Mac Japanse
Mac OS Japanese
https://en.wikipedia.org/wiki/Shift_JIS#MacJapanese
https://www.unicode.org/Public/MAPPINGS/VENDORS/APPLE/JAPANESE.TXT
"""
res = ""
i_text = iter(text)
hi = next(i_text, None)
while hi:
if hi <= 0x7F: # ASCII
res += chr(hi)
elif hi == 0x80: # reverse solidus
res += "\u005C"
elif (0x81 <= hi <= 0x9F) or (0xE0 <= hi <= 0xFC): # two-byte sequence
lo = next(i_text, None)
if lo is None:
print(f"WARNING: Mac Japanese sequence missing second byte 0x{hi:02x}")
return text.decode('mac-roman')
hi_key = f'{hi:02x}'
lo_key = lo - 0x40
if lo_key < 0:
print(f"WARNING: second byte out of range 0x{lo:02x}")
return text.decode('mac-roman')
elif decode_map.get(hi_key) is None or decode_map[hi_key][lo_key] is None:
print(f"WARNING: No mapping for MacJapanese sequence 0x{hi_key}{lo:02x}")
return text.decode('mac-roman')
assert_tmp = decode_map[hi_key][lo_key]
assert assert_tmp # mypy assert
res += assert_tmp
elif hi == 0xA0: # no-break space
res += "\u00A0"
elif 0xA1 <= hi <= 0xDF: # Katakana
res += chr(hi - 0xA1 + 0xFF61)
elif hi == 0xFD: # copyright sign
res += "\u00A9"
elif hi == 0xFE: # trade mark sign
res += "\u2122"
elif hi == 0xFF: # halfwidth horizontal ellipsis
res += "\u2026\uF87F"
else:
raise Exception(f"No mapping for MacJapanese sequence 0x{hi:02x}")
hi = next(i_text, None)
return res | [
"def",
"decode_macjapanese",
"(",
"text",
":",
"ByteString",
")",
"->",
"str",
":",
"res",
"=",
"\"\"",
"i_text",
"=",
"iter",
"(",
"text",
")",
"hi",
"=",
"next",
"(",
"i_text",
",",
"None",
")",
"while",
"hi",
":",
"if",
"hi",
"<=",
"0x7F",
":",
... | https://github.com/scummvm/scummvm/blob/9c039d027e7ffb9d83ae2e274147e2daf8d57ce2/devtools/dumper-companion.py#L87-L132 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/xml/sax/_exceptions.py | python | SAXParseException.getSystemId | (self) | return self._systemId | Get the system identifier of the entity where the exception occurred. | Get the system identifier of the entity where the exception occurred. | [
"Get",
"the",
"system",
"identifier",
"of",
"the",
"entity",
"where",
"the",
"exception",
"occurred",
"."
] | def getSystemId(self):
"Get the system identifier of the entity where the exception occurred."
return self._systemId | [
"def",
"getSystemId",
"(",
"self",
")",
":",
"return",
"self",
".",
"_systemId"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/xml/sax/_exceptions.py#L85-L87 | |
HeYijia/PL-VIO | ddec7f3995cae0c90ba216861ad7cd784e7004cf | sim_data_pub/Myimg2bag/img2bag_Mars_imu.py | python | ReadIMU | (filename) | return timestamp,imu_data | return IMU data and timestamp of IMU | return IMU data and timestamp of IMU | [
"return",
"IMU",
"data",
"and",
"timestamp",
"of",
"IMU"
] | def ReadIMU(filename):
'''return IMU data and timestamp of IMU'''
file = open(filename,'r')
all = file.readlines()
timestamp = []
imu_data = []
for f in all:
line = f.rstrip('\n').split(' ')
timestamp.append(line[0])
imu_data.append(line[1:])
return timestamp,imu_data | [
"def",
"ReadIMU",
"(",
"filename",
")",
":",
"file",
"=",
"open",
"(",
"filename",
",",
"'r'",
")",
"all",
"=",
"file",
".",
"readlines",
"(",
")",
"timestamp",
"=",
"[",
"]",
"imu_data",
"=",
"[",
"]",
"for",
"f",
"in",
"all",
":",
"line",
"=",
... | https://github.com/HeYijia/PL-VIO/blob/ddec7f3995cae0c90ba216861ad7cd784e7004cf/sim_data_pub/Myimg2bag/img2bag_Mars_imu.py#L38-L48 | |
gemrb/gemrb | 730206eed8d1dd358ca5e69a62f9e099aa22ffc6 | gemrb/GUIScripts/Actor.py | python | Actor.LevelDiffs | (self) | return [(next-current) for current,next in zip(self.Levels(),
self.NextLevels())] | Returns the differences between the current and next classes. | Returns the differences between the current and next classes. | [
"Returns",
"the",
"differences",
"between",
"the",
"current",
"and",
"next",
"classes",
"."
] | def LevelDiffs (self):
"""Returns the differences between the current and next classes."""
return [(next-current) for current,next in zip(self.Levels(),
self.NextLevels())] | [
"def",
"LevelDiffs",
"(",
"self",
")",
":",
"return",
"[",
"(",
"next",
"-",
"current",
")",
"for",
"current",
",",
"next",
"in",
"zip",
"(",
"self",
".",
"Levels",
"(",
")",
",",
"self",
".",
"NextLevels",
"(",
")",
")",
"]"
] | https://github.com/gemrb/gemrb/blob/730206eed8d1dd358ca5e69a62f9e099aa22ffc6/gemrb/GUIScripts/Actor.py#L142-L145 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/robotsim.py | python | Geometry3D.getBBTight | (self) | return _robotsim.Geometry3D_getBBTight(self) | r"""
Computes a tighter axis-aligned bounding box of the object than
:meth:`Geometry3D.getBB`. Worst case O(n) time. | r"""
Computes a tighter axis-aligned bounding box of the object than
:meth:`Geometry3D.getBB`. Worst case O(n) time. | [
"r",
"Computes",
"a",
"tighter",
"axis",
"-",
"aligned",
"bounding",
"box",
"of",
"the",
"object",
"than",
":",
"meth",
":",
"Geometry3D",
".",
"getBB",
".",
"Worst",
"case",
"O",
"(",
"n",
")",
"time",
"."
] | def getBBTight(self) ->None:
r"""
Computes a tighter axis-aligned bounding box of the object than
:meth:`Geometry3D.getBB`. Worst case O(n) time.
"""
return _robotsim.Geometry3D_getBBTight(self) | [
"def",
"getBBTight",
"(",
"self",
")",
"->",
"None",
":",
"return",
"_robotsim",
".",
"Geometry3D_getBBTight",
"(",
"self",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/robotsim.py#L2337-L2343 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/distutils/dist.py | python | Distribution.parse_command_line | (self) | return True | Parse the setup script's command line, taken from the
'script_args' instance attribute (which defaults to 'sys.argv[1:]'
-- see 'setup()' in core.py). This list is first processed for
"global options" -- options that set attributes of the Distribution
instance. Then, it is alternately scanned for Distutils commands
and options for that command. Each new command terminates the
options for the previous command. The allowed options for a
command are determined by the 'user_options' attribute of the
command class -- thus, we have to be able to load command classes
in order to parse the command line. Any error in that 'options'
attribute raises DistutilsGetoptError; any error on the
command-line raises DistutilsArgError. If no Distutils commands
were found on the command line, raises DistutilsArgError. Return
true if command-line was successfully parsed and we should carry
on with executing commands; false if no errors but we shouldn't
execute commands (currently, this only happens if user asks for
help). | Parse the setup script's command line, taken from the
'script_args' instance attribute (which defaults to 'sys.argv[1:]'
-- see 'setup()' in core.py). This list is first processed for
"global options" -- options that set attributes of the Distribution
instance. Then, it is alternately scanned for Distutils commands
and options for that command. Each new command terminates the
options for the previous command. The allowed options for a
command are determined by the 'user_options' attribute of the
command class -- thus, we have to be able to load command classes
in order to parse the command line. Any error in that 'options'
attribute raises DistutilsGetoptError; any error on the
command-line raises DistutilsArgError. If no Distutils commands
were found on the command line, raises DistutilsArgError. Return
true if command-line was successfully parsed and we should carry
on with executing commands; false if no errors but we shouldn't
execute commands (currently, this only happens if user asks for
help). | [
"Parse",
"the",
"setup",
"script",
"s",
"command",
"line",
"taken",
"from",
"the",
"script_args",
"instance",
"attribute",
"(",
"which",
"defaults",
"to",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"--",
"see",
"setup",
"()",
"in",
"core",
".",
"py",
")",... | def parse_command_line(self):
"""Parse the setup script's command line, taken from the
'script_args' instance attribute (which defaults to 'sys.argv[1:]'
-- see 'setup()' in core.py). This list is first processed for
"global options" -- options that set attributes of the Distribution
instance. Then, it is alternately scanned for Distutils commands
and options for that command. Each new command terminates the
options for the previous command. The allowed options for a
command are determined by the 'user_options' attribute of the
command class -- thus, we have to be able to load command classes
in order to parse the command line. Any error in that 'options'
attribute raises DistutilsGetoptError; any error on the
command-line raises DistutilsArgError. If no Distutils commands
were found on the command line, raises DistutilsArgError. Return
true if command-line was successfully parsed and we should carry
on with executing commands; false if no errors but we shouldn't
execute commands (currently, this only happens if user asks for
help).
"""
#
# We now have enough information to show the Macintosh dialog
# that allows the user to interactively specify the "command line".
#
toplevel_options = self._get_toplevel_options()
# We have to parse the command line a bit at a time -- global
# options, then the first command, then its options, and so on --
# because each command will be handled by a different class, and
# the options that are valid for a particular class aren't known
# until we have loaded the command class, which doesn't happen
# until we know what the command is.
self.commands = []
parser = FancyGetopt(toplevel_options + self.display_options)
parser.set_negative_aliases(self.negative_opt)
parser.set_aliases({'licence': 'license'})
args = parser.getopt(args=self.script_args, object=self)
option_order = parser.get_option_order()
log.set_verbosity(self.verbose)
# for display options we return immediately
if self.handle_display_options(option_order):
return
while args:
args = self._parse_command_opts(parser, args)
if args is None: # user asked for help (and got it)
return
# Handle the cases of --help as a "global" option, ie.
# "setup.py --help" and "setup.py --help command ...". For the
# former, we show global options (--verbose, --dry-run, etc.)
# and display-only options (--name, --version, etc.); for the
# latter, we omit the display-only options and show help for
# each command listed on the command line.
if self.help:
self._show_help(parser,
display_options=len(self.commands) == 0,
commands=self.commands)
return
# Oops, no commands found -- an end-user error
if not self.commands:
raise DistutilsArgError("no commands supplied")
# All is well: return true
return True | [
"def",
"parse_command_line",
"(",
"self",
")",
":",
"#",
"# We now have enough information to show the Macintosh dialog",
"# that allows the user to interactively specify the \"command line\".",
"#",
"toplevel_options",
"=",
"self",
".",
"_get_toplevel_options",
"(",
")",
"# We hav... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/distutils/dist.py#L439-L504 | |
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | TPM2_ChangePPS_REQUEST.fromTpm | (buf) | return buf.createObj(TPM2_ChangePPS_REQUEST) | Returns new TPM2_ChangePPS_REQUEST object constructed from its
marshaled representation in the given TpmBuffer buffer | Returns new TPM2_ChangePPS_REQUEST object constructed from its
marshaled representation in the given TpmBuffer buffer | [
"Returns",
"new",
"TPM2_ChangePPS_REQUEST",
"object",
"constructed",
"from",
"its",
"marshaled",
"representation",
"in",
"the",
"given",
"TpmBuffer",
"buffer"
] | def fromTpm(buf):
""" Returns new TPM2_ChangePPS_REQUEST object constructed from its
marshaled representation in the given TpmBuffer buffer
"""
return buf.createObj(TPM2_ChangePPS_REQUEST) | [
"def",
"fromTpm",
"(",
"buf",
")",
":",
"return",
"buf",
".",
"createObj",
"(",
"TPM2_ChangePPS_REQUEST",
")"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L15485-L15489 | |
microsoft/ELL | a1d6bacc37a14879cc025d9be2ba40b1a0632315 | tools/utilities/pythonlibs/vision/tiled_image.py | python | TiledImage.__init__ | (self, num_images=2, output_shape=(600, 800)) | Helper class to create a tiled image out of many smaller images.
The class calculates how many horizontal and vertical blocks are needed to fit the requested number of images
and fills in unused blocks as blank. For example, to fit 4 images, the number of tiles is 2x2, to fit 5 images,
the number of tiles is 3x2, with the last tile being blank.
num_images - the maximum number of images that need to be composed into the tiled image. Note that the
actual number of tiles is equal to or larger than this number.
output_shape - a tuple contaiing rows and columns of the output image. The output tiled image
is a composition of sub images. | Helper class to create a tiled image out of many smaller images.
The class calculates how many horizontal and vertical blocks are needed to fit the requested number of images
and fills in unused blocks as blank. For example, to fit 4 images, the number of tiles is 2x2, to fit 5 images,
the number of tiles is 3x2, with the last tile being blank.
num_images - the maximum number of images that need to be composed into the tiled image. Note that the
actual number of tiles is equal to or larger than this number.
output_shape - a tuple contaiing rows and columns of the output image. The output tiled image
is a composition of sub images. | [
"Helper",
"class",
"to",
"create",
"a",
"tiled",
"image",
"out",
"of",
"many",
"smaller",
"images",
".",
"The",
"class",
"calculates",
"how",
"many",
"horizontal",
"and",
"vertical",
"blocks",
"are",
"needed",
"to",
"fit",
"the",
"requested",
"number",
"of",... | def __init__(self, num_images=2, output_shape=(600, 800)):
""" Helper class to create a tiled image out of many smaller images.
The class calculates how many horizontal and vertical blocks are needed to fit the requested number of images
and fills in unused blocks as blank. For example, to fit 4 images, the number of tiles is 2x2, to fit 5 images,
the number of tiles is 3x2, with the last tile being blank.
num_images - the maximum number of images that need to be composed into the tiled image. Note that the
actual number of tiles is equal to or larger than this number.
output_shape - a tuple contaiing rows and columns of the output image. The output tiled image
is a composition of sub images.
"""
self.composed_image_shape = self.get_composed_image_shape(num_images)
self.number_of_tiles = self.composed_image_shape[0] * self.composed_image_shape[1]
self.output_height_and_width = output_shape
self.images = None
self.window_name = 'ELL side by side'
cv2.namedWindow(self.window_name, cv2.WINDOW_NORMAL) # Ensure the window is resizable
# The aspect ratio of the composed image is now self.composed_image_shape[0] : self.composed_image_shape[1]
# Adjust the height of the window to account for this, else images will look distorted
height = int(output_shape[0] * (self.composed_image_shape[0] / self.composed_image_shape[1]))
cv2.resizeWindow(self.window_name, output_shape[1], height) | [
"def",
"__init__",
"(",
"self",
",",
"num_images",
"=",
"2",
",",
"output_shape",
"=",
"(",
"600",
",",
"800",
")",
")",
":",
"self",
".",
"composed_image_shape",
"=",
"self",
".",
"get_composed_image_shape",
"(",
"num_images",
")",
"self",
".",
"number_of... | https://github.com/microsoft/ELL/blob/a1d6bacc37a14879cc025d9be2ba40b1a0632315/tools/utilities/pythonlibs/vision/tiled_image.py#L18-L37 | ||
Vipermdl/OCR_detection_IC15 | 8eebd353d6fac97f5832a138d7af3bd3071670db | data_loader/datautils.py | python | rectangle_from_parallelogram | (poly) | fit a rectangle from a parallelogram
:param poly:
:return: | fit a rectangle from a parallelogram
:param poly:
:return: | [
"fit",
"a",
"rectangle",
"from",
"a",
"parallelogram",
":",
"param",
"poly",
":",
":",
"return",
":"
] | def rectangle_from_parallelogram(poly):
'''
fit a rectangle from a parallelogram
:param poly:
:return:
'''
p0, p1, p2, p3 = poly
angle_p0 = np.arccos(np.dot(p1 - p0, p3 - p0) / (np.linalg.norm(p0 - p1) * np.linalg.norm(p3 - p0)))
if angle_p0 < 0.5 * np.pi:
if np.linalg.norm(p0 - p1) > np.linalg.norm(p0 - p3):
# p0 and p2
## p0
p2p3 = fit_line([p2[0], p3[0]], [p2[1], p3[1]])
p2p3_verticle = line_verticle(p2p3, p0)
new_p3 = line_cross_point(p2p3, p2p3_verticle)
## p2
p0p1 = fit_line([p0[0], p1[0]], [p0[1], p1[1]])
p0p1_verticle = line_verticle(p0p1, p2)
new_p1 = line_cross_point(p0p1, p0p1_verticle)
return np.array([p0, new_p1, p2, new_p3], dtype = np.float32)
else:
p1p2 = fit_line([p1[0], p2[0]], [p1[1], p2[1]])
p1p2_verticle = line_verticle(p1p2, p0)
new_p1 = line_cross_point(p1p2, p1p2_verticle)
p0p3 = fit_line([p0[0], p3[0]], [p0[1], p3[1]])
p0p3_verticle = line_verticle(p0p3, p2)
new_p3 = line_cross_point(p0p3, p0p3_verticle)
return np.array([p0, new_p1, p2, new_p3], dtype = np.float32)
else:
if np.linalg.norm(p0 - p1) > np.linalg.norm(p0 - p3):
# p1 and p3
## p1
p2p3 = fit_line([p2[0], p3[0]], [p2[1], p3[1]])
p2p3_verticle = line_verticle(p2p3, p1)
new_p2 = line_cross_point(p2p3, p2p3_verticle)
## p3
p0p1 = fit_line([p0[0], p1[0]], [p0[1], p1[1]])
p0p1_verticle = line_verticle(p0p1, p3)
new_p0 = line_cross_point(p0p1, p0p1_verticle)
return np.array([new_p0, p1, new_p2, p3], dtype = np.float32)
else:
p0p3 = fit_line([p0[0], p3[0]], [p0[1], p3[1]])
p0p3_verticle = line_verticle(p0p3, p1)
new_p0 = line_cross_point(p0p3, p0p3_verticle)
p1p2 = fit_line([p1[0], p2[0]], [p1[1], p2[1]])
p1p2_verticle = line_verticle(p1p2, p3)
new_p2 = line_cross_point(p1p2, p1p2_verticle)
return np.array([new_p0, p1, new_p2, p3], dtype = np.float32) | [
"def",
"rectangle_from_parallelogram",
"(",
"poly",
")",
":",
"p0",
",",
"p1",
",",
"p2",
",",
"p3",
"=",
"poly",
"angle_p0",
"=",
"np",
".",
"arccos",
"(",
"np",
".",
"dot",
"(",
"p1",
"-",
"p0",
",",
"p3",
"-",
"p0",
")",
"/",
"(",
"np",
".",... | https://github.com/Vipermdl/OCR_detection_IC15/blob/8eebd353d6fac97f5832a138d7af3bd3071670db/data_loader/datautils.py#L276-L331 | ||
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/distributed/_shard/sharded_tensor/_ops/embedding_bag.py | python | _handle_row_wise_sharding | (
input,
world_size,
weight,
local_shard,
offsets,
per_sample_weights,
mode,
max_norm,
norm_type,
padding_idx,
rank,
pg,
) | return gathered_output | Entry-point function to handle the logic of row-wise sharding of weight
for embeddingBag. (Detailed explanations of the logic can be found in
the comment for sharded_embedding_bag.)
Args:
input: list of ID used for lookup and aggregation.
world_size: number of ranks.
weight: shareded weight tensor.
local_shard: row-wise shared local weight used for lookup.
offsets: list of start positions of each bag for 1D input.
per_sample_weights: weights for weighted sum mode.
mode: aggregation method of each bag.
max_norm: If given, each embedding vector with norm larger
than max_norm is renormalized to have norm max_norm.
Note: this will modify weight in-place.
norm_type: The p in the p-norm to compute for the max_norm option.
padding_idx: If specified, the entries at padding_idx do
not contribute to the gradient; therefore, the embedding
vector at padding_idx is not updated during training,
i.e. it remains as a fixed “pad”.
Note that the embedding vector at padding_idx is
excluded from the reduction.
rank: # of cuda process.
pg: process group.
Returns:
gathered_output: final result of lookup and aggregation. | Entry-point function to handle the logic of row-wise sharding of weight
for embeddingBag. (Detailed explanations of the logic can be found in
the comment for sharded_embedding_bag.) | [
"Entry",
"-",
"point",
"function",
"to",
"handle",
"the",
"logic",
"of",
"row",
"-",
"wise",
"sharding",
"of",
"weight",
"for",
"embeddingBag",
".",
"(",
"Detailed",
"explanations",
"of",
"the",
"logic",
"can",
"be",
"found",
"in",
"the",
"comment",
"for",... | def _handle_row_wise_sharding(
input,
world_size,
weight,
local_shard,
offsets,
per_sample_weights,
mode,
max_norm,
norm_type,
padding_idx,
rank,
pg,
):
"""
Entry-point function to handle the logic of row-wise sharding of weight
for embeddingBag. (Detailed explanations of the logic can be found in
the comment for sharded_embedding_bag.)
Args:
input: list of ID used for lookup and aggregation.
world_size: number of ranks.
weight: shareded weight tensor.
local_shard: row-wise shared local weight used for lookup.
offsets: list of start positions of each bag for 1D input.
per_sample_weights: weights for weighted sum mode.
mode: aggregation method of each bag.
max_norm: If given, each embedding vector with norm larger
than max_norm is renormalized to have norm max_norm.
Note: this will modify weight in-place.
norm_type: The p in the p-norm to compute for the max_norm option.
padding_idx: If specified, the entries at padding_idx do
not contribute to the gradient; therefore, the embedding
vector at padding_idx is not updated during training,
i.e. it remains as a fixed “pad”.
Note that the embedding vector at padding_idx is
excluded from the reduction.
rank: # of cuda process.
pg: process group.
Returns:
gathered_output: final result of lookup and aggregation.
"""
# We sort each interval defined by offset. If 2D, each interval is a row.
input_size = input.size()
(
input_split_sorted_list,
input_split_sorted_indices,
split_sizes_1d,
split_sizes_1d_with_padding,
) = _input_split_sort(input, offsets, padding_idx)
# Within each interval of the sorted list, we first need to distribute
# each ID to different bucket(rank) and also ensure the rearrangement
# has been done in case the placement idx not equal to rank.
# We then perform some simple stats on each interval for the next step
# If user specifies per_sample_weights we need to rearrange them
# to be sync with IDs and then distribute them to each rank
(
input_combined,
input_combined_split_sizes,
offsets_rearrange_list,
offsets_rearrange_sizes,
per_sample_weights,
sharded_dim_size_max,
padding_idx,
) = _sorted_input_distribute_prepare(
input_split_sorted_list,
input_split_sorted_indices,
world_size,
input,
weight,
per_sample_weights,
rank,
padding_idx,
)
# Send ID/offsets/per_sample_weights to different bucket(rank).
(
gathered_input,
output_offsets_tensor_list,
output_split_sizes,
gathered_per_sample_weights,
) = _distribute_input(
input_combined,
input_combined_split_sizes,
offsets_rearrange_list,
offsets_rearrange_sizes,
sharded_dim_size_max,
world_size,
input,
per_sample_weights,
pg,
)
# Perform the embedding bag look-up and aggregation
results = []
for i, inp in enumerate(gathered_input):
per_sample_weights = (
gathered_per_sample_weights[i]
if gathered_per_sample_weights is not None
else None
)
# If input is None, passing in max_norm causes
# errors in CUDA.
if max_norm is not None and inp.size(0) == 0:
max_norm = None
# Perform local embedding look up and aggregation.
result = torch.nn.functional.embedding_bag(
inp,
local_shard,
offsets=output_offsets_tensor_list[i],
mode=mode if mode != "mean" else "sum",
per_sample_weights=per_sample_weights,
max_norm=max_norm,
norm_type=norm_type,
padding_idx=padding_idx,
)
if mode != "max":
results.append(result)
# For max case, it there is no look-up from some ranks
# it will return all zero for that. For that case, we need
# to set the row to neg inf; otherwise, in the final
# aggregation negative values will be rounded up to zero.
elif inp.size(0) == 0:
result[:] = -float("Inf")
results.append(result)
else:
for idx, current_offset in enumerate(output_offsets_tensor_list[i]):
next_offset = current_offset
if idx == len(output_offsets_tensor_list[i]) - 1:
next_offset = output_split_sizes[i]
else:
next_offset = output_offsets_tensor_list[i][idx + 1]
# When there is no interval in the current rank or all IDs
# are equal to padding_idx, we then need to ensure they
# don't contribute to the final result.
if (current_offset == next_offset) or (
padding_idx is not None
and not torch.any(
torch.ne(inp[current_offset:next_offset], padding_idx)
)
):
result[idx] = -float("Inf")
results.append(result)
# Gather all the aggregated results appropriately by using reduce_scatter.
row_size = input.size(0) if len(input_size) > 1 else len(split_sizes_1d)
gathered_output = torch.empty(row_size, weight.size(1), device=input.device)
op = ReduceOp.SUM if mode != "max" else ReduceOp.MAX
dist.reduce_scatter(gathered_output, results, op=op, group=pg)
# For Mean, we cannot do the division until very end because the sum of means
# not equal to the mean of sum. (Divisor is different)
if mode == "mean":
split_sizes_1d_tensor = torch.tensor(
split_sizes_1d_with_padding, dtype=torch.float, device=input.device
)
# Make sure divisor is not zero.
split_sizes_1d_tensor[split_sizes_1d_tensor == 0.0] = 1.0
return (
torch.div(gathered_output.t().contiguous(), split_sizes_1d_tensor)
.t()
.contiguous()
)
# Return the appropriate local result.
return gathered_output | [
"def",
"_handle_row_wise_sharding",
"(",
"input",
",",
"world_size",
",",
"weight",
",",
"local_shard",
",",
"offsets",
",",
"per_sample_weights",
",",
"mode",
",",
"max_norm",
",",
"norm_type",
",",
"padding_idx",
",",
"rank",
",",
"pg",
",",
")",
":",
"# W... | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/distributed/_shard/sharded_tensor/_ops/embedding_bag.py#L337-L505 | |
swift/swift | 12d031cf8177fdec0137f9aa7e2912fa23c4416b | 3rdParty/SCons/scons-3.0.1/engine/SCons/Tool/msginit.py | python | exists | (env) | Check if the tool exists | Check if the tool exists | [
"Check",
"if",
"the",
"tool",
"exists"
] | def exists(env):
""" Check if the tool exists """
from SCons.Tool.GettextCommon import _msginit_exists
try:
return _msginit_exists(env)
except:
return False | [
"def",
"exists",
"(",
"env",
")",
":",
"from",
"SCons",
".",
"Tool",
".",
"GettextCommon",
"import",
"_msginit_exists",
"try",
":",
"return",
"_msginit_exists",
"(",
"env",
")",
"except",
":",
"return",
"False"
] | https://github.com/swift/swift/blob/12d031cf8177fdec0137f9aa7e2912fa23c4416b/3rdParty/SCons/scons-3.0.1/engine/SCons/Tool/msginit.py#L107-L113 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/summary/summary_iterator.py | python | SummaryWriter.add_summary | (self, summary, global_step=None) | Adds a `Summary` protocol buffer to the event file.
This method wraps the provided summary in an `Event` protocol buffer
and adds it to the event file.
You can pass the result of evaluating any summary op, using
@{tf.Session.run} or
@{tf.Tensor.eval}, to this
function. Alternatively, you can pass a `tf.Summary` protocol
buffer that you populate with your own data. The latter is
commonly done to report evaluation results in event files.
Args:
summary: A `Summary` protocol buffer, optionally serialized as a string.
global_step: Number. Optional global step value to record with the
summary. | Adds a `Summary` protocol buffer to the event file. | [
"Adds",
"a",
"Summary",
"protocol",
"buffer",
"to",
"the",
"event",
"file",
"."
] | def add_summary(self, summary, global_step=None):
"""Adds a `Summary` protocol buffer to the event file.
This method wraps the provided summary in an `Event` protocol buffer
and adds it to the event file.
You can pass the result of evaluating any summary op, using
@{tf.Session.run} or
@{tf.Tensor.eval}, to this
function. Alternatively, you can pass a `tf.Summary` protocol
buffer that you populate with your own data. The latter is
commonly done to report evaluation results in event files.
Args:
summary: A `Summary` protocol buffer, optionally serialized as a string.
global_step: Number. Optional global step value to record with the
summary.
"""
if isinstance(summary, bytes):
summ = summary_pb2.Summary()
summ.ParseFromString(summary)
summary = summ
event = event_pb2.Event(wall_time=time.time(), summary=summary)
if global_step is not None:
event.step = int(global_step)
self.add_event(event) | [
"def",
"add_summary",
"(",
"self",
",",
"summary",
",",
"global_step",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"summary",
",",
"bytes",
")",
":",
"summ",
"=",
"summary_pb2",
".",
"Summary",
"(",
")",
"summ",
".",
"ParseFromString",
"(",
"summary"... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/summary/summary_iterator.py#L120-L145 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/third_party/mlir/utils/spirv/gen_spirv_dialect.py | python | gen_opcode | (instructions) | return opcode_str + '\n\n' + enum_attr | Generates the TableGen definition to map opname to opcode
Returns:
- A string containing the TableGen SPV_OpCode definition | Generates the TableGen definition to map opname to opcode | [
"Generates",
"the",
"TableGen",
"definition",
"to",
"map",
"opname",
"to",
"opcode"
] | def gen_opcode(instructions):
""" Generates the TableGen definition to map opname to opcode
Returns:
- A string containing the TableGen SPV_OpCode definition
"""
max_len = max([len(inst['opname']) for inst in instructions])
def_fmt_str = 'def SPV_OC_{name} {colon:>{offset}} '\
'I32EnumAttrCase<"{name}", {value}>;'
opcode_defs = [
def_fmt_str.format(
name=inst['opname'],
value=inst['opcode'],
colon=':',
offset=(max_len + 1 - len(inst['opname']))) for inst in instructions
]
opcode_str = '\n'.join(opcode_defs)
decl_fmt_str = 'SPV_OC_{name}'
opcode_list = [
decl_fmt_str.format(name=inst['opname']) for inst in instructions
]
opcode_list = split_list_into_sublists(opcode_list, 6)
opcode_list = [
'{:6}'.format('') + ', '.join(sublist) for sublist in opcode_list
]
opcode_list = ',\n'.join(opcode_list)
enum_attr = 'def SPV_OpcodeAttr :\n'\
' I32EnumAttr<"{name}", "valid SPIR-V instructions", [\n'\
'{lst}\n'\
' ]> {{\n'\
' let returnType = "::mlir::spirv::{name}";\n'\
' let convertFromStorage = '\
'"static_cast<::mlir::spirv::{name}>($_self.getInt())";\n'\
' let cppNamespace = "::mlir::spirv";\n}}'.format(
name='Opcode', lst=opcode_list)
return opcode_str + '\n\n' + enum_attr | [
"def",
"gen_opcode",
"(",
"instructions",
")",
":",
"max_len",
"=",
"max",
"(",
"[",
"len",
"(",
"inst",
"[",
"'opname'",
"]",
")",
"for",
"inst",
"in",
"instructions",
"]",
")",
"def_fmt_str",
"=",
"'def SPV_OC_{name} {colon:>{offset}} '",
"'I32EnumAttrCase<\"{... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/third_party/mlir/utils/spirv/gen_spirv_dialect.py#L186-L223 | |
twtygqyy/caffe-augmentation | c76600d247e5132fa5bd89d87bb5df458341fa84 | scripts/cpp_lint.py | python | CleanseComments | (line) | return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line) | Removes //-comments and single-line C-style /* */ comments.
Args:
line: A line of C++ source.
Returns:
The line with single-line comments removed. | Removes //-comments and single-line C-style /* */ comments. | [
"Removes",
"//",
"-",
"comments",
"and",
"single",
"-",
"line",
"C",
"-",
"style",
"/",
"*",
"*",
"/",
"comments",
"."
] | def CleanseComments(line):
"""Removes //-comments and single-line C-style /* */ comments.
Args:
line: A line of C++ source.
Returns:
The line with single-line comments removed.
"""
commentpos = line.find('//')
if commentpos != -1 and not IsCppString(line[:commentpos]):
line = line[:commentpos].rstrip()
# get rid of /* ... */
return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line) | [
"def",
"CleanseComments",
"(",
"line",
")",
":",
"commentpos",
"=",
"line",
".",
"find",
"(",
"'//'",
")",
"if",
"commentpos",
"!=",
"-",
"1",
"and",
"not",
"IsCppString",
"(",
"line",
"[",
":",
"commentpos",
"]",
")",
":",
"line",
"=",
"line",
"[",
... | https://github.com/twtygqyy/caffe-augmentation/blob/c76600d247e5132fa5bd89d87bb5df458341fa84/scripts/cpp_lint.py#L1171-L1184 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/util/nest.py | python | flatten_with_joined_string_paths | (structure, separator="/",
expand_composites=False) | return list(zip(flat_string_paths,
flatten(structure, expand_composites=expand_composites))) | Returns a list of (string path, atom) tuples.
The order of tuples produced matches that of `nest.flatten`. This allows you
to flatten a nested structure while keeping information about where in the
structure each atom was located. See `nest.yield_flat_paths`
for more information.
Args:
structure: the nested structure to flatten.
separator: string to separate levels of hierarchy in the results, defaults
to '/'.
expand_composites: If true, then composite tensors such as
`tf.sparse.SparseTensor` and `tf.RaggedTensor` are expanded into their
component tensors.
Returns:
A list of (string, atom) tuples. | Returns a list of (string path, atom) tuples. | [
"Returns",
"a",
"list",
"of",
"(",
"string",
"path",
"atom",
")",
"tuples",
"."
] | def flatten_with_joined_string_paths(structure, separator="/",
expand_composites=False):
"""Returns a list of (string path, atom) tuples.
The order of tuples produced matches that of `nest.flatten`. This allows you
to flatten a nested structure while keeping information about where in the
structure each atom was located. See `nest.yield_flat_paths`
for more information.
Args:
structure: the nested structure to flatten.
separator: string to separate levels of hierarchy in the results, defaults
to '/'.
expand_composites: If true, then composite tensors such as
`tf.sparse.SparseTensor` and `tf.RaggedTensor` are expanded into their
component tensors.
Returns:
A list of (string, atom) tuples.
"""
flat_paths = yield_flat_paths(structure, expand_composites=expand_composites)
def stringify_and_join(path_elements):
return separator.join(str(path_element) for path_element in path_elements)
flat_string_paths = (stringify_and_join(path) for path in flat_paths)
return list(zip(flat_string_paths,
flatten(structure, expand_composites=expand_composites))) | [
"def",
"flatten_with_joined_string_paths",
"(",
"structure",
",",
"separator",
"=",
"\"/\"",
",",
"expand_composites",
"=",
"False",
")",
":",
"flat_paths",
"=",
"yield_flat_paths",
"(",
"structure",
",",
"expand_composites",
"=",
"expand_composites",
")",
"def",
"s... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/util/nest.py#L1648-L1674 | |
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | tools/mo/openvino/tools/mo/utils/versions_checker.py | python | parse_and_filter_versions_list | (required_fw_versions, version_list, env_setup) | return version_list | Please do not add parameter type annotations (param:type).
Because we import this file while checking Python version.
Python 2.x will fail with no clear message on type annotations.
Parsing requirements versions for a dependency and filtering out requirements that
satisfy environment setup such as python version.
if environment version (python_version, etc.) is satisfied
:param required_fw_versions: String with fw versions from requirements file
:param version_list: List for append
:param env_setup: a dictionary with environment setup
:return: list of tuples of strings like (name_of_module, sign, version)
Examples of required_fw_versions:
'tensorflow>=1.15.2,<2.0; python_version < "3.8"'
'tensorflow>=2.0'
Returned object is:
[('tensorflow', '>=', '1.2.0'), ('networkx', '==', '2.1'), ('numpy', None, None)] | Please do not add parameter type annotations (param:type).
Because we import this file while checking Python version.
Python 2.x will fail with no clear message on type annotations. | [
"Please",
"do",
"not",
"add",
"parameter",
"type",
"annotations",
"(",
"param",
":",
"type",
")",
".",
"Because",
"we",
"import",
"this",
"file",
"while",
"checking",
"Python",
"version",
".",
"Python",
"2",
".",
"x",
"will",
"fail",
"with",
"no",
"clear... | def parse_and_filter_versions_list(required_fw_versions, version_list, env_setup):
"""
Please do not add parameter type annotations (param:type).
Because we import this file while checking Python version.
Python 2.x will fail with no clear message on type annotations.
Parsing requirements versions for a dependency and filtering out requirements that
satisfy environment setup such as python version.
if environment version (python_version, etc.) is satisfied
:param required_fw_versions: String with fw versions from requirements file
:param version_list: List for append
:param env_setup: a dictionary with environment setup
:return: list of tuples of strings like (name_of_module, sign, version)
Examples of required_fw_versions:
'tensorflow>=1.15.2,<2.0; python_version < "3.8"'
'tensorflow>=2.0'
Returned object is:
[('tensorflow', '>=', '1.2.0'), ('networkx', '==', '2.1'), ('numpy', None, None)]
"""
line = required_fw_versions.strip('\n')
line = line.strip(' ')
if line == '':
return version_list
split_requirement = line.split(";")
# check environment marker
if len(split_requirement) > 1:
env_req = split_requirement[1]
if any([x in split_requirement[1] for x in [' and ', ' or ']]):
log.error("The version checker doesn't support environment marker combination and it will be ignored: {}"
"".format(split_requirement[1]), extra={'is_warning': True})
return version_list
split_env_req = re.split(r"==|>=|<=|>|<|~=|!=", env_req)
split_env_req = [l.strip(',') for l in split_env_req]
env_marker = split_env_req[0].strip(' ')
if env_marker == 'python_version' and env_marker in env_setup:
installed_python_version = env_setup['python_version']
env_req_version_list = []
split_required_versions = re.split(r",", env_req)
for i, l in enumerate(split_required_versions):
for comparison in ['==', '>=', '<=', '<', '>', '~=']:
if comparison in l:
required_version = split_env_req[i + 1].strip(' ').replace("'", "").replace('"', '')
env_req_version_list.append((env_marker, comparison, required_version))
break
not_satisfied_list = []
for name, key, required_version in env_req_version_list:
version_check(name, installed_python_version, required_version,
key, not_satisfied_list)
if len(not_satisfied_list) > 0:
# this python_version requirement is not satisfied to required environment
# and requirement for a dependency will be skipped
return version_list
elif env_marker == 'sys_platform' and env_marker in env_setup:
split_env_req[1] = split_env_req[1].strip(' ').replace("'", "").replace('"', '')
if '==' in env_req:
if env_setup['sys_platform'] != split_env_req[1]:
# this sys_platform requirement is not satisfied to required environment
# and requirement for a dependency will be skipped
return version_list
elif '!=' in env_req:
if env_setup['sys_platform'] == split_env_req[1]:
# this sys_platform requirement is not satisfied to required environment
# and requirement for a dependency will be skipped
return version_list
else:
log.error("Error during platform version check, line: {}".format(line))
else:
log.error("{} is unsupported environment marker and it will be ignored".format(env_marker),
extra={'is_warning': True})
# parse a requirement for a dependency
requirement = split_requirement[0]
split_versions_by_conditions = re.split(r"==|>=|<=|>|<|~=", requirement)
split_versions_by_conditions = [l.strip(',').strip(' ') for l in split_versions_by_conditions]
if len(split_versions_by_conditions) == 0:
return version_list
if len(split_versions_by_conditions) == 1:
version_list.append((split_versions_by_conditions[0], None, None))
else:
split_required_versions= re.split(r",", requirement)
for i, l in enumerate(split_required_versions):
for comparison in ['==', '>=', '<=', '<', '>', '~=']:
if comparison in l:
version_list.append((split_versions_by_conditions[0], comparison, split_versions_by_conditions[i + 1]))
break
return version_list | [
"def",
"parse_and_filter_versions_list",
"(",
"required_fw_versions",
",",
"version_list",
",",
"env_setup",
")",
":",
"line",
"=",
"required_fw_versions",
".",
"strip",
"(",
"'\\n'",
")",
"line",
"=",
"line",
".",
"strip",
"(",
"' '",
")",
"if",
"line",
"==",... | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/mo/openvino/tools/mo/utils/versions_checker.py#L45-L135 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/gaussian_process/kernels.py | python | Sum.diag | (self, X) | return self.k1.diag(X) + self.k2.diag(X) | Returns the diagonal of the kernel k(X, X).
The result of this method is identical to np.diag(self(X)); however,
it can be evaluated more efficiently since only the diagonal is
evaluated.
Parameters
----------
X : array, shape (n_samples_X, n_features)
Left argument of the returned kernel k(X, Y)
Returns
-------
K_diag : array, shape (n_samples_X,)
Diagonal of kernel k(X, X) | Returns the diagonal of the kernel k(X, X). | [
"Returns",
"the",
"diagonal",
"of",
"the",
"kernel",
"k",
"(",
"X",
"X",
")",
"."
] | def diag(self, X):
"""Returns the diagonal of the kernel k(X, X).
The result of this method is identical to np.diag(self(X)); however,
it can be evaluated more efficiently since only the diagonal is
evaluated.
Parameters
----------
X : array, shape (n_samples_X, n_features)
Left argument of the returned kernel k(X, Y)
Returns
-------
K_diag : array, shape (n_samples_X,)
Diagonal of kernel k(X, X)
"""
return self.k1.diag(X) + self.k2.diag(X) | [
"def",
"diag",
"(",
"self",
",",
"X",
")",
":",
"return",
"self",
".",
"k1",
".",
"diag",
"(",
"X",
")",
"+",
"self",
".",
"k2",
".",
"diag",
"(",
"X",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/gaussian_process/kernels.py#L685-L702 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/ttk.py | python | Panedwindow.sashpos | (self, index, newpos=None) | return self.tk.call(self._w, "sashpos", index, newpos) | If newpos is specified, sets the position of sash number index.
May adjust the positions of adjacent sashes to ensure that
positions are monotonically increasing. Sash positions are further
constrained to be between 0 and the total size of the widget.
Returns the new position of sash number index. | If newpos is specified, sets the position of sash number index. | [
"If",
"newpos",
"is",
"specified",
"sets",
"the",
"position",
"of",
"sash",
"number",
"index",
"."
] | def sashpos(self, index, newpos=None):
"""If newpos is specified, sets the position of sash number index.
May adjust the positions of adjacent sashes to ensure that
positions are monotonically increasing. Sash positions are further
constrained to be between 0 and the total size of the widget.
Returns the new position of sash number index."""
return self.tk.call(self._w, "sashpos", index, newpos) | [
"def",
"sashpos",
"(",
"self",
",",
"index",
",",
"newpos",
"=",
"None",
")",
":",
"return",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_w",
",",
"\"sashpos\"",
",",
"index",
",",
"newpos",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/ttk.py#L976-L984 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Arch/ArchSchedule.py | python | ArchScheduleTaskPanel.add | (self) | Adds a new row below the last one | Adds a new row below the last one | [
"Adds",
"a",
"new",
"row",
"below",
"the",
"last",
"one"
] | def add(self):
"""Adds a new row below the last one"""
self.form.list.insertRow(self.form.list.currentRow()+1) | [
"def",
"add",
"(",
"self",
")",
":",
"self",
".",
"form",
".",
"list",
".",
"insertRow",
"(",
"self",
".",
"form",
".",
"list",
".",
"currentRow",
"(",
")",
"+",
"1",
")"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Arch/ArchSchedule.py#L480-L484 | ||
bingwin/MicroChat | 81d9a71a212c1cbca5bba497ec42659a7d25dccf | mars/lint/cpplint.py | python | GetLineWidth | (line) | Determines the width of the line in column positions.
Args:
line: A string, which may be a Unicode string.
Returns:
The width of the line in column positions, accounting for Unicode
combining characters and wide characters. | Determines the width of the line in column positions. | [
"Determines",
"the",
"width",
"of",
"the",
"line",
"in",
"column",
"positions",
"."
] | def GetLineWidth(line):
"""Determines the width of the line in column positions.
Args:
line: A string, which may be a Unicode string.
Returns:
The width of the line in column positions, accounting for Unicode
combining characters and wide characters.
"""
if isinstance(line, unicode):
width = 0
for uc in unicodedata.normalize('NFC', line):
if unicodedata.east_asian_width(uc) in ('W', 'F'):
width += 2
elif not unicodedata.combining(uc):
width += 1
return width
else:
return len(line) | [
"def",
"GetLineWidth",
"(",
"line",
")",
":",
"if",
"isinstance",
"(",
"line",
",",
"unicode",
")",
":",
"width",
"=",
"0",
"for",
"uc",
"in",
"unicodedata",
".",
"normalize",
"(",
"'NFC'",
",",
"line",
")",
":",
"if",
"unicodedata",
".",
"east_asian_w... | https://github.com/bingwin/MicroChat/blob/81d9a71a212c1cbca5bba497ec42659a7d25dccf/mars/lint/cpplint.py#L4356-L4375 | ||
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/models/rnn/translate/translate.py | python | create_model | (session, forward_only) | return model | Create translation model and initialize or load parameters in session. | Create translation model and initialize or load parameters in session. | [
"Create",
"translation",
"model",
"and",
"initialize",
"or",
"load",
"parameters",
"in",
"session",
"."
] | def create_model(session, forward_only):
"""Create translation model and initialize or load parameters in session."""
dtype = tf.float16 if FLAGS.use_fp16 else tf.float32
model = seq2seq_model.Seq2SeqModel(
FLAGS.en_vocab_size,
FLAGS.fr_vocab_size,
_buckets,
FLAGS.size,
FLAGS.num_layers,
FLAGS.max_gradient_norm,
FLAGS.batch_size,
FLAGS.learning_rate,
FLAGS.learning_rate_decay_factor,
forward_only=forward_only,
dtype=dtype)
ckpt = tf.train.get_checkpoint_state(FLAGS.train_dir)
if ckpt and tf.gfile.Exists(ckpt.model_checkpoint_path):
print("Reading model parameters from %s" % ckpt.model_checkpoint_path)
model.saver.restore(session, ckpt.model_checkpoint_path)
else:
print("Created model with fresh parameters.")
session.run(tf.initialize_all_variables())
return model | [
"def",
"create_model",
"(",
"session",
",",
"forward_only",
")",
":",
"dtype",
"=",
"tf",
".",
"float16",
"if",
"FLAGS",
".",
"use_fp16",
"else",
"tf",
".",
"float32",
"model",
"=",
"seq2seq_model",
".",
"Seq2SeqModel",
"(",
"FLAGS",
".",
"en_vocab_size",
... | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/models/rnn/translate/translate.py#L117-L139 | |
quarnster/boxeebox-xbmc | 7209547d3d247a4082de956f4d9a765086d96985 | tools/EventClients/lib/python/xbmcclient.py | python | PacketHELO.__init__ | (self, devicename=None, icon_type=ICON_NONE, icon_file=None) | Keyword arguments:
devicename -- the string that identifies the client
icon_type -- one of ICON_NONE, ICON_JPEG, ICON_PNG, ICON_GIF
icon_file -- location of icon file with respect to current working
directory if icon_type is not ICON_NONE | Keyword arguments:
devicename -- the string that identifies the client
icon_type -- one of ICON_NONE, ICON_JPEG, ICON_PNG, ICON_GIF
icon_file -- location of icon file with respect to current working
directory if icon_type is not ICON_NONE | [
"Keyword",
"arguments",
":",
"devicename",
"--",
"the",
"string",
"that",
"identifies",
"the",
"client",
"icon_type",
"--",
"one",
"of",
"ICON_NONE",
"ICON_JPEG",
"ICON_PNG",
"ICON_GIF",
"icon_file",
"--",
"location",
"of",
"icon",
"file",
"with",
"respect",
"to... | def __init__(self, devicename=None, icon_type=ICON_NONE, icon_file=None):
"""
Keyword arguments:
devicename -- the string that identifies the client
icon_type -- one of ICON_NONE, ICON_JPEG, ICON_PNG, ICON_GIF
icon_file -- location of icon file with respect to current working
directory if icon_type is not ICON_NONE
"""
Packet.__init__(self)
self.packettype = PT_HELO
self.icontype = icon_type
self.set_payload ( format_string(devicename)[0:128] )
self.append_payload( chr (icon_type) )
self.append_payload( format_uint16 (0) ) # port no
self.append_payload( format_uint32 (0) ) # reserved1
self.append_payload( format_uint32 (0) ) # reserved2
if icon_type != ICON_NONE and icon_file:
self.append_payload( file(icon_file).read() ) | [
"def",
"__init__",
"(",
"self",
",",
"devicename",
"=",
"None",
",",
"icon_type",
"=",
"ICON_NONE",
",",
"icon_file",
"=",
"None",
")",
":",
"Packet",
".",
"__init__",
"(",
"self",
")",
"self",
".",
"packettype",
"=",
"PT_HELO",
"self",
".",
"icontype",
... | https://github.com/quarnster/boxeebox-xbmc/blob/7209547d3d247a4082de956f4d9a765086d96985/tools/EventClients/lib/python/xbmcclient.py#L265-L282 | ||
devpack/android-python27 | d42dd67565e104cf7b0b50eb473f615db3e69901 | python-build-with-qt/sip-4.11.2/siputils.py | python | SIPModuleMakefile.finalise | (self) | Finalise the macros for a SIP generated module Makefile. | Finalise the macros for a SIP generated module Makefile. | [
"Finalise",
"the",
"macros",
"for",
"a",
"SIP",
"generated",
"module",
"Makefile",
"."
] | def finalise(self):
"""Finalise the macros for a SIP generated module Makefile.
"""
if self._prot_is_public:
self.DEFINES.append('SIP_PROTECTED_IS_PUBLIC')
self.DEFINES.append('protected=public')
self.INCDIR.append(self.config.sip_inc_dir)
ModuleMakefile.finalise(self) | [
"def",
"finalise",
"(",
"self",
")",
":",
"if",
"self",
".",
"_prot_is_public",
":",
"self",
".",
"DEFINES",
".",
"append",
"(",
"'SIP_PROTECTED_IS_PUBLIC'",
")",
"self",
".",
"DEFINES",
".",
"append",
"(",
"'protected=public'",
")",
"self",
".",
"INCDIR",
... | https://github.com/devpack/android-python27/blob/d42dd67565e104cf7b0b50eb473f615db3e69901/python-build-with-qt/sip-4.11.2/siputils.py#L1665-L1674 | ||
yshshrm/Data-Structures-And-Algorithms-Hacktoberfest18 | ce2807facfb817d1303d2ac9f1b2d90955e29a18 | python/algorithms/linear_hashing.py | python | LinearHashing.insert | (self, value, print_status=0) | return True | :param value: value to be inserted
:param print_status: set to 1 if
:return: | [] | def insert(self, value, print_status=0):
"""
:param value: value to be inserted
:param print_status: set to 1 if
:return:
"""
self.set_index_counter_if()
if self.threshold_outbound:
# buffer to be extend
self.buffer[len(self.buffer)] = []
buffer_index = self.hash_function(value)
self.buffer[buffer_index] = self.buffer.setdefault(buffer_index, []) + [value]
# bucket to be split
bucket_to_split = self.buffer[self.index_counter]
self.buffer[self.index_counter] = []
for data in bucket_to_split:
buffer_idx = self.hash_function(data, flag=1)
self.buffer[buffer_idx] = self.buffer.setdefault(buffer_idx, []) + [data]
self.index_counter += 1
else:
buffer_index = self.hash_function(value)
# self.buffer[buffer_index].append(value)
self.buffer[buffer_index] = self.buffer.setdefault(buffer_index, []) + [value]
self.total_data += 1
if print_status:
print(self.buffer)
print("INDEX: {}\nCURRENT PHASE: {} \t PREVIOUS PHASE: {}".format(self.index_counter, self.current_phase, self.previous_phase))
return True | [
"def",
"insert",
"(",
"self",
",",
"value",
",",
"print_status",
"=",
"0",
")",
":",
"self",
".",
"set_index_counter_if",
"(",
")",
"if",
"self",
".",
"threshold_outbound",
":",
"# buffer to be extend",
"self",
".",
"buffer",
"[",
"len",
"(",
"self",
".",
... | https://github.com/yshshrm/Data-Structures-And-Algorithms-Hacktoberfest18/blob/ce2807facfb817d1303d2ac9f1b2d90955e29a18/python/algorithms/linear_hashing.py#L54-L84 | ||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/contrib/learn/python/learn/monitors.py | python | BaseMonitor.epoch_begin | (self, epoch) | Begin epoch.
Args:
epoch: `int`, the epoch number.
Raises:
ValueError: if we've already begun an epoch, or `epoch` < 0. | Begin epoch. | [
"Begin",
"epoch",
"."
] | def epoch_begin(self, epoch):
"""Begin epoch.
Args:
epoch: `int`, the epoch number.
Raises:
ValueError: if we've already begun an epoch, or `epoch` < 0.
"""
if self._current_epoch is not None:
raise ValueError("epoch_begin called twice without epoch_end.")
if epoch < 0:
raise ValueError("Invalid epoch %s." % epoch)
self._current_epoch = epoch | [
"def",
"epoch_begin",
"(",
"self",
",",
"epoch",
")",
":",
"if",
"self",
".",
"_current_epoch",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"\"epoch_begin called twice without epoch_end.\"",
")",
"if",
"epoch",
"<",
"0",
":",
"raise",
"ValueError",
"... | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/learn/python/learn/monitors.py#L168-L181 | ||
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py | python | newText | (content) | return xmlNode(_obj=ret) | Creation of a new text node. | Creation of a new text node. | [
"Creation",
"of",
"a",
"new",
"text",
"node",
"."
] | def newText(content):
"""Creation of a new text node. """
ret = libxml2mod.xmlNewText(content)
if ret is None:raise treeError('xmlNewText() failed')
return xmlNode(_obj=ret) | [
"def",
"newText",
"(",
"content",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlNewText",
"(",
"content",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlNewText() failed'",
")",
"return",
"xmlNode",
"(",
"_obj",
"=",
"ret",
")"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L910-L914 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/metrics_impl.py | python | recall_at_top_k | (labels,
predictions_idx,
k=None,
class_id=None,
weights=None,
metrics_collections=None,
updates_collections=None,
name=None) | Computes recall@k of top-k predictions with respect to sparse labels.
Differs from `recall_at_k` in that predictions must be in the form of top `k`
class indices, whereas `recall_at_k` expects logits. Refer to `recall_at_k`
for more details.
Args:
labels: `int64` `Tensor` or `SparseTensor` with shape
[D1, ... DN, num_labels] or [D1, ... DN], where the latter implies
num_labels=1. N >= 1 and num_labels is the number of target classes for
the associated prediction. Commonly, N=1 and `labels` has shape
[batch_size, num_labels]. [D1, ... DN] must match `predictions`. Values
should be in range [0, num_classes), where num_classes is the last
dimension of `predictions`. Values outside this range always count
towards `false_negative_at_<k>`.
predictions_idx: Integer `Tensor` with shape [D1, ... DN, k] where N >= 1.
Commonly, N=1 and predictions has shape [batch size, k]. The final
dimension contains the top `k` predicted class indices. [D1, ... DN] must
match `labels`.
k: Integer, k for @k metric. Only used for the default op name.
class_id: Integer class ID for which we want binary metrics. This should be
in range [0, num_classes), where num_classes is the last dimension of
`predictions`. If class_id is outside this range, the method returns NAN.
weights: `Tensor` whose rank is either 0, or n-1, where n is the rank of
`labels`. If the latter, it must be broadcastable to `labels` (i.e., all
dimensions must be either `1`, or the same as the corresponding `labels`
dimension).
metrics_collections: An optional list of collections that values should
be added to.
updates_collections: An optional list of collections that updates should
be added to.
name: Name of new update operation, and namespace for other dependent ops.
Returns:
recall: Scalar `float64` `Tensor` with the value of `true_positives` divided
by the sum of `true_positives` and `false_negatives`.
update_op: `Operation` that increments `true_positives` and
`false_negatives` variables appropriately, and whose value matches
`recall`.
Raises:
ValueError: If `weights` is not `None` and its shape doesn't match
`predictions`, or if either `metrics_collections` or `updates_collections`
are not a list or tuple. | Computes recall@k of top-k predictions with respect to sparse labels. | [
"Computes",
"recall@k",
"of",
"top",
"-",
"k",
"predictions",
"with",
"respect",
"to",
"sparse",
"labels",
"."
] | def recall_at_top_k(labels,
predictions_idx,
k=None,
class_id=None,
weights=None,
metrics_collections=None,
updates_collections=None,
name=None):
"""Computes recall@k of top-k predictions with respect to sparse labels.
Differs from `recall_at_k` in that predictions must be in the form of top `k`
class indices, whereas `recall_at_k` expects logits. Refer to `recall_at_k`
for more details.
Args:
labels: `int64` `Tensor` or `SparseTensor` with shape
[D1, ... DN, num_labels] or [D1, ... DN], where the latter implies
num_labels=1. N >= 1 and num_labels is the number of target classes for
the associated prediction. Commonly, N=1 and `labels` has shape
[batch_size, num_labels]. [D1, ... DN] must match `predictions`. Values
should be in range [0, num_classes), where num_classes is the last
dimension of `predictions`. Values outside this range always count
towards `false_negative_at_<k>`.
predictions_idx: Integer `Tensor` with shape [D1, ... DN, k] where N >= 1.
Commonly, N=1 and predictions has shape [batch size, k]. The final
dimension contains the top `k` predicted class indices. [D1, ... DN] must
match `labels`.
k: Integer, k for @k metric. Only used for the default op name.
class_id: Integer class ID for which we want binary metrics. This should be
in range [0, num_classes), where num_classes is the last dimension of
`predictions`. If class_id is outside this range, the method returns NAN.
weights: `Tensor` whose rank is either 0, or n-1, where n is the rank of
`labels`. If the latter, it must be broadcastable to `labels` (i.e., all
dimensions must be either `1`, or the same as the corresponding `labels`
dimension).
metrics_collections: An optional list of collections that values should
be added to.
updates_collections: An optional list of collections that updates should
be added to.
name: Name of new update operation, and namespace for other dependent ops.
Returns:
recall: Scalar `float64` `Tensor` with the value of `true_positives` divided
by the sum of `true_positives` and `false_negatives`.
update_op: `Operation` that increments `true_positives` and
`false_negatives` variables appropriately, and whose value matches
`recall`.
Raises:
ValueError: If `weights` is not `None` and its shape doesn't match
`predictions`, or if either `metrics_collections` or `updates_collections`
are not a list or tuple.
"""
with ops.name_scope(name, _at_k_name('recall', k, class_id=class_id),
(predictions_idx, labels, weights)) as scope:
labels = _maybe_expand_labels(labels, predictions_idx)
top_k_idx = math_ops.cast(predictions_idx, dtypes.int64)
tp, tp_update = _streaming_sparse_true_positive_at_k(
predictions_idx=top_k_idx,
labels=labels,
k=k,
class_id=class_id,
weights=weights)
fn, fn_update = _streaming_sparse_false_negative_at_k(
predictions_idx=top_k_idx,
labels=labels,
k=k,
class_id=class_id,
weights=weights)
def compute_recall(_, tp, fn):
return math_ops.divide(tp, math_ops.add(tp, fn), name=scope)
metric = _aggregate_across_replicas(
metrics_collections, compute_recall, tp, fn)
update = math_ops.divide(
tp_update, math_ops.add(tp_update, fn_update), name='update')
if updates_collections:
ops.add_to_collections(updates_collections, update)
return metric, update | [
"def",
"recall_at_top_k",
"(",
"labels",
",",
"predictions_idx",
",",
"k",
"=",
"None",
",",
"class_id",
"=",
"None",
",",
"weights",
"=",
"None",
",",
"metrics_collections",
"=",
"None",
",",
"updates_collections",
"=",
"None",
",",
"name",
"=",
"None",
"... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/metrics_impl.py#L2754-L2834 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/psutil/_pswindows.py | python | Process._proc_info | (self) | return ret | Return multiple information about this process as a
raw tuple. | Return multiple information about this process as a
raw tuple. | [
"Return",
"multiple",
"information",
"about",
"this",
"process",
"as",
"a",
"raw",
"tuple",
"."
] | def _proc_info(self):
"""Return multiple information about this process as a
raw tuple.
"""
ret = cext.proc_info(self.pid)
assert len(ret) == len(pinfo_map)
return ret | [
"def",
"_proc_info",
"(",
"self",
")",
":",
"ret",
"=",
"cext",
".",
"proc_info",
"(",
"self",
".",
"pid",
")",
"assert",
"len",
"(",
"ret",
")",
"==",
"len",
"(",
"pinfo_map",
")",
"return",
"ret"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/psutil/_pswindows.py#L732-L738 | |
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | tutorials/darcy_thermo_mech/step07_adaptivity/problems/step7abc.py | python | frames | () | Render frames | Render frames | [
"Render",
"frames"
] | def frames():
"""Render frames"""
camera = vtk.vtkCamera()
camera.SetViewUp(0.0000000000, 1.0000000000, 0.0000000000)
camera.SetPosition(0.1520000000, 0.0128500000, 0.1198046424)
camera.SetFocalPoint(0.1520000000, 0.0128500000, 0.0000000000)
reader_a = chigger.exodus.ExodusReader('step7a_coarse_out.e')
reader_b = chigger.exodus.ExodusReader('step7b_fine_out.e')
reader_c = chigger.exodus.ExodusReader('step7c_adapt_out.e')
temp_a = chigger.exodus.ExodusResult(reader_a, camera=camera, variable='temperature',
viewport=[0,0,0.9,0.333],
edges=True, edge_color=EDGE_COLOR,
range=[300, 350], cmap='viridis')
temp_b = chigger.exodus.ExodusResult(reader_b, camera=camera, variable='temperature',
viewport=[0,0.333,0.9,0.666],
edges=True, edge_color=EDGE_COLOR,
range=[300, 350], cmap='viridis')
temp_c = chigger.exodus.ExodusResult(reader_c, camera=camera, variable='temperature',
viewport=[0,0.666,0.9,1],
edges=True, edge_color=EDGE_COLOR,
range=[300, 350], cmap='viridis')
cbar = chigger.exodus.ExodusColorBar(temp_a,
viewport=[0.9,0,1,1],
length=0.8,
width=0.3,
colorbar_origin=[0.1, 0.1])
cbar.setOptions('primary', title='Temperature (K)', font_size=28, font_color=[0,0,0])
time = chigger.annotations.TextAnnotation(position=[0.45,0.3], font_size=48, text_color=[0,0,0],
viewport=[0,0,1,1],
justification='center')
window = chigger.RenderWindow(temp_a, temp_b, temp_c, cbar, time, size=[1920, 1080],
background=[1,1,1],
motion_factor=0.24)
for i, t in enumerate(reader_a.getTimes()):
reader_a.setOptions(timestep=i)
reader_b.setOptions(timestep=i)
reader_c.setOptions(timestep=i)
time.setOptions(text='Time = {:.1f} sec.'.format(t))
filename = 'output/step07abc_{:05d}.png'.format(i)
window.write(filename)
window.start() | [
"def",
"frames",
"(",
")",
":",
"camera",
"=",
"vtk",
".",
"vtkCamera",
"(",
")",
"camera",
".",
"SetViewUp",
"(",
"0.0000000000",
",",
"1.0000000000",
",",
"0.0000000000",
")",
"camera",
".",
"SetPosition",
"(",
"0.1520000000",
",",
"0.0128500000",
",",
"... | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/tutorials/darcy_thermo_mech/step07_adaptivity/problems/step7abc.py#L18-L66 | ||
bulletphysics/bullet3 | f0f2a952e146f016096db6f85cf0c44ed75b0b9a | examples/pybullet/gym/pybullet_envs/minitaur/envs/minitaur_four_leg_stand_env.py | python | MinitaurFourLegStandEnv._get_observation | (self) | return self._observation | Get the true observations of this environment.
It includes the roll, pitch, roll dot, pitch dot of the base, and the motor
angles.
Returns:
The observation list. | Get the true observations of this environment. | [
"Get",
"the",
"true",
"observations",
"of",
"this",
"environment",
"."
] | def _get_observation(self):
"""Get the true observations of this environment.
It includes the roll, pitch, roll dot, pitch dot of the base, and the motor
angles.
Returns:
The observation list.
"""
roll, pitch, _ = self.minitaur.GetBaseRollPitchYaw()
observation = [roll, pitch]
if self._use_angular_velocity_in_observation:
roll_rate, pitch_rate, _ = self.minitaur.GetBaseRollPitchYawRate()
observation.extend([roll_rate, pitch_rate])
if self._use_motor_angle_in_observation:
observation.extend(self.minitaur.GetMotorAngles().tolist())
self._observation = np.array(observation)
return self._observation | [
"def",
"_get_observation",
"(",
"self",
")",
":",
"roll",
",",
"pitch",
",",
"_",
"=",
"self",
".",
"minitaur",
".",
"GetBaseRollPitchYaw",
"(",
")",
"observation",
"=",
"[",
"roll",
",",
"pitch",
"]",
"if",
"self",
".",
"_use_angular_velocity_in_observation... | https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/minitaur/envs/minitaur_four_leg_stand_env.py#L268-L285 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/req/req_file.py | python | parse_requirements | (
filename, # type: str
session, # type: PipSession
finder=None, # type: Optional[PackageFinder]
options=None, # type: Optional[optparse.Values]
constraint=False, # type: bool
) | Parse a requirements file and yield ParsedRequirement instances.
:param filename: Path or url of requirements file.
:param session: PipSession instance.
:param finder: Instance of pip.index.PackageFinder.
:param options: cli options.
:param constraint: If true, parsing a constraint file rather than
requirements file. | Parse a requirements file and yield ParsedRequirement instances. | [
"Parse",
"a",
"requirements",
"file",
"and",
"yield",
"ParsedRequirement",
"instances",
"."
] | def parse_requirements(
filename, # type: str
session, # type: PipSession
finder=None, # type: Optional[PackageFinder]
options=None, # type: Optional[optparse.Values]
constraint=False, # type: bool
):
# type: (...) -> Iterator[ParsedRequirement]
"""Parse a requirements file and yield ParsedRequirement instances.
:param filename: Path or url of requirements file.
:param session: PipSession instance.
:param finder: Instance of pip.index.PackageFinder.
:param options: cli options.
:param constraint: If true, parsing a constraint file rather than
requirements file.
"""
line_parser = get_line_parser(finder)
parser = RequirementsFileParser(session, line_parser)
for parsed_line in parser.parse(filename, constraint):
parsed_req = handle_line(
parsed_line,
options=options,
finder=finder,
session=session
)
if parsed_req is not None:
yield parsed_req | [
"def",
"parse_requirements",
"(",
"filename",
",",
"# type: str",
"session",
",",
"# type: PipSession",
"finder",
"=",
"None",
",",
"# type: Optional[PackageFinder]",
"options",
"=",
"None",
",",
"# type: Optional[optparse.Values]",
"constraint",
"=",
"False",
",",
"# t... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/req/req_file.py#L253-L309 | ||
bryanyzhu/Hidden-Two-Stream | f7f684adbdacb6df6b1cf196c3a476cd23484a0f | scripts/cpp_lint.py | python | CheckForNonStandardConstructs | (filename, clean_lines, linenum,
nesting_state, error) | r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
Complain about several constructs which gcc-2 accepts, but which are
not standard C++. Warning about these in lint is one way to ease the
transition to new compilers.
- put storage class first (e.g. "static const" instead of "const static").
- "%lld" instead of %qd" in printf-type functions.
- "%1$d" is non-standard in printf-type functions.
- "\%" is an undefined character escape sequence.
- text after #endif is not allowed.
- invalid inner-style forward declaration.
- >? and <? operators, and their >?= and <?= cousins.
Additionally, check for constructor/destructor style violations and reference
members, as it is very convenient to do so while checking for
gcc-2 compliance.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message | r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2. | [
"r",
"Logs",
"an",
"error",
"if",
"we",
"see",
"certain",
"non",
"-",
"ANSI",
"constructs",
"ignored",
"by",
"gcc",
"-",
"2",
"."
] | def CheckForNonStandardConstructs(filename, clean_lines, linenum,
nesting_state, error):
r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
Complain about several constructs which gcc-2 accepts, but which are
not standard C++. Warning about these in lint is one way to ease the
transition to new compilers.
- put storage class first (e.g. "static const" instead of "const static").
- "%lld" instead of %qd" in printf-type functions.
- "%1$d" is non-standard in printf-type functions.
- "\%" is an undefined character escape sequence.
- text after #endif is not allowed.
- invalid inner-style forward declaration.
- >? and <? operators, and their >?= and <?= cousins.
Additionally, check for constructor/destructor style violations and reference
members, as it is very convenient to do so while checking for
gcc-2 compliance.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
"""
# Remove comments from the line, but leave in strings for now.
line = clean_lines.lines[linenum]
if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line):
error(filename, linenum, 'runtime/printf_format', 3,
'%q in format strings is deprecated. Use %ll instead.')
if Search(r'printf\s*\(.*".*%\d+\$', line):
error(filename, linenum, 'runtime/printf_format', 2,
'%N$ formats are unconventional. Try rewriting to avoid them.')
# Remove escaped backslashes before looking for undefined escapes.
line = line.replace('\\\\', '')
if Search(r'("|\').*\\(%|\[|\(|{)', line):
error(filename, linenum, 'build/printf_format', 3,
'%, [, (, and { are undefined character escapes. Unescape them.')
# For the rest, work with both comments and strings removed.
line = clean_lines.elided[linenum]
if Search(r'\b(const|volatile|void|char|short|int|long'
r'|float|double|signed|unsigned'
r'|schar|u?int8|u?int16|u?int32|u?int64)'
r'\s+(register|static|extern|typedef)\b',
line):
error(filename, linenum, 'build/storage_class', 5,
'Storage class (static, extern, typedef, etc) should be first.')
if Match(r'\s*#\s*endif\s*[^/\s]+', line):
error(filename, linenum, 'build/endif_comment', 5,
'Uncommented text after #endif is non-standard. Use a comment.')
if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line):
error(filename, linenum, 'build/forward_decl', 5,
'Inner-style forward declarations are invalid. Remove this line.')
if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?',
line):
error(filename, linenum, 'build/deprecated', 3,
'>? and <? (max and min) operators are non-standard and deprecated.')
if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line):
# TODO(unknown): Could it be expanded safely to arbitrary references,
# without triggering too many false positives? The first
# attempt triggered 5 warnings for mostly benign code in the regtest, hence
# the restriction.
# Here's the original regexp, for the reference:
# type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?'
# r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;'
error(filename, linenum, 'runtime/member_string_references', 2,
'const string& members are dangerous. It is much better to use '
'alternatives, such as pointers or simple constants.')
# Everything else in this function operates on class declarations.
# Return early if the top of the nesting stack is not a class, or if
# the class head is not completed yet.
classinfo = nesting_state.InnermostClass()
if not classinfo or not classinfo.seen_open_brace:
return
# The class may have been declared with namespace or classname qualifiers.
# The constructor and destructor will not have those qualifiers.
base_classname = classinfo.name.split('::')[-1]
# Look for single-argument constructors that aren't marked explicit.
# Technically a valid construct, but against style.
args = Match(r'\s+(?:inline\s+)?%s\s*\(([^,()]+)\)'
% re.escape(base_classname),
line)
if (args and
args.group(1) != 'void' and
not Match(r'(const\s+)?%s(\s+const)?\s*(?:<\w+>\s*)?&'
% re.escape(base_classname), args.group(1).strip())):
error(filename, linenum, 'runtime/explicit', 5,
'Single-argument constructors should be marked explicit.') | [
"def",
"CheckForNonStandardConstructs",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"nesting_state",
",",
"error",
")",
":",
"# Remove comments from the line, but leave in strings for now.",
"line",
"=",
"clean_lines",
".",
"lines",
"[",
"linenum",
"]",
"i... | https://github.com/bryanyzhu/Hidden-Two-Stream/blob/f7f684adbdacb6df6b1cf196c3a476cd23484a0f/scripts/cpp_lint.py#L2194-L2298 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/ntpath.py | python | dirname | (p) | return split(p)[0] | Returns the directory component of a pathname | Returns the directory component of a pathname | [
"Returns",
"the",
"directory",
"component",
"of",
"a",
"pathname"
] | def dirname(p):
"""Returns the directory component of a pathname"""
return split(p)[0] | [
"def",
"dirname",
"(",
"p",
")",
":",
"return",
"split",
"(",
"p",
")",
"[",
"0",
"]"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/ntpath.py#L203-L205 | |
hpi-xnor/BMXNet | ed0b201da6667887222b8e4b5f997c4f6b61943d | python/mxnet/gluon/block.py | python | HybridBlock.forward | (self, x, *args) | Defines the forward computation. Arguments can be either
:py:class:`NDArray` or :py:class:`Symbol`. | Defines the forward computation. Arguments can be either
:py:class:`NDArray` or :py:class:`Symbol`. | [
"Defines",
"the",
"forward",
"computation",
".",
"Arguments",
"can",
"be",
"either",
":",
"py",
":",
"class",
":",
"NDArray",
"or",
":",
"py",
":",
"class",
":",
"Symbol",
"."
] | def forward(self, x, *args):
"""Defines the forward computation. Arguments can be either
:py:class:`NDArray` or :py:class:`Symbol`."""
if isinstance(x, NDArray):
with x.context as ctx:
try:
if self._active:
return self._call_cached_op(x, *args)
params = {i: j.data(ctx) for i, j in self._reg_params.items()}
except DeferredInitializationError:
self._finish_deferred_init(self._active, x, *args)
if self._active:
return self._call_cached_op(x, *args)
params = {i: j.data(ctx) for i, j in self._reg_params.items()}
return self.hybrid_forward(ndarray, x, *args, **params)
assert isinstance(x, Symbol), \
"HybridBlock requires the first argument to forward be either " \
"Symbol or NDArray, but got %s"%type(x)
params = {i: j.var() for i, j in self._reg_params.items()}
with self.name_scope():
return self.hybrid_forward(symbol, x, *args, **params) | [
"def",
"forward",
"(",
"self",
",",
"x",
",",
"*",
"args",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"NDArray",
")",
":",
"with",
"x",
".",
"context",
"as",
"ctx",
":",
"try",
":",
"if",
"self",
".",
"_active",
":",
"return",
"self",
".",
"_... | https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/gluon/block.py#L499-L521 | ||
mapnik/mapnik | f3da900c355e1d15059c4a91b00203dcc9d9f0ef | scons/scons-local-4.1.0/SCons/Tool/docbook/__init__.py | python | DocbookHtmlhelp | (env, target, source=None, *args, **kw) | return result | A pseudo-Builder, providing a Docbook toolchain for HTMLHELP output. | A pseudo-Builder, providing a Docbook toolchain for HTMLHELP output. | [
"A",
"pseudo",
"-",
"Builder",
"providing",
"a",
"Docbook",
"toolchain",
"for",
"HTMLHELP",
"output",
"."
] | def DocbookHtmlhelp(env, target, source=None, *args, **kw):
"""
A pseudo-Builder, providing a Docbook toolchain for HTMLHELP output.
"""
# Init target/source
if not SCons.Util.is_List(target):
target = [target]
if not source:
source = target
target = ['index.html']
elif not SCons.Util.is_List(source):
source = [source]
# Init XSL stylesheet
__init_xsl_stylesheet(kw, env, '$DOCBOOK_DEFAULT_XSL_HTMLHELP', ['htmlhelp','htmlhelp.xsl'])
# Setup builder
__builder = __select_builder(__lxml_noresult_builder, __xsltproc_nobase_builder)
# Detect base dir
base_dir = kw.get('base_dir', '')
if base_dir:
__create_output_dir(base_dir)
# Create targets
result = []
r = __builder.__call__(env, __ensure_suffix(str(target[0]), '.html'), source[0], **kw)
env.Depends(r, kw['DOCBOOK_XSL'])
result.extend(r)
# Add supporting files for cleanup
env.Clean(r, ['toc.hhc', 'htmlhelp.hhp', 'index.hhk'] +
glob.glob(os.path.join(base_dir, '[ar|bk|ch]*.html')))
return result | [
"def",
"DocbookHtmlhelp",
"(",
"env",
",",
"target",
",",
"source",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"# Init target/source",
"if",
"not",
"SCons",
".",
"Util",
".",
"is_List",
"(",
"target",
")",
":",
"target",
"=",
"[",
... | https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Tool/docbook/__init__.py#L555-L588 | |
msitt/blpapi-python | bebcf43668c9e5f5467b1f685f9baebbfc45bc87 | src/blpapi/constant.py | python | Constant.status | (self) | return internals.blpapi_Constant_status(self.__handle) | Returns:
int: Status of this :class:`Constant`.
The possible return values are enumerated in :class:`SchemaStatus`. | Returns:
int: Status of this :class:`Constant`. | [
"Returns",
":",
"int",
":",
"Status",
"of",
"this",
":",
"class",
":",
"Constant",
"."
] | def status(self):
"""
Returns:
int: Status of this :class:`Constant`.
The possible return values are enumerated in :class:`SchemaStatus`.
"""
return internals.blpapi_Constant_status(self.__handle) | [
"def",
"status",
"(",
"self",
")",
":",
"return",
"internals",
".",
"blpapi_Constant_status",
"(",
"self",
".",
"__handle",
")"
] | https://github.com/msitt/blpapi-python/blob/bebcf43668c9e5f5467b1f685f9baebbfc45bc87/src/blpapi/constant.py#L68-L75 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | samples/doodle/doodle.py | python | DoodleWindow.OnPaint | (self, event) | Called when the window is exposed. | Called when the window is exposed. | [
"Called",
"when",
"the",
"window",
"is",
"exposed",
"."
] | def OnPaint(self, event):
"""
Called when the window is exposed.
"""
# Create a buffered paint DC. It will create the real
# wx.PaintDC and then blit the bitmap to it when dc is
# deleted. Since we don't need to draw anything else
# here that's all there is to it.
dc = wx.BufferedPaintDC(self, self.buffer) | [
"def",
"OnPaint",
"(",
"self",
",",
"event",
")",
":",
"# Create a buffered paint DC. It will create the real",
"# wx.PaintDC and then blit the bitmap to it when dc is",
"# deleted. Since we don't need to draw anything else",
"# here that's all there is to it.",
"dc",
"=",
"wx",
".",... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/samples/doodle/doodle.py#L204-L212 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/nn/cell.py | python | Cell._set_mixed_precision_type_recursive | (self, mixed_type) | Set mixed precision type to each cell | Set mixed precision type to each cell | [
"Set",
"mixed",
"precision",
"type",
"to",
"each",
"cell"
] | def _set_mixed_precision_type_recursive(self, mixed_type):
"""Set mixed precision type to each cell"""
Cell_.set_mixed_precision_type(self, mixed_type)
for cell in self.cells():
cell._set_mixed_precision_type_recursive(mixed_type) | [
"def",
"_set_mixed_precision_type_recursive",
"(",
"self",
",",
"mixed_type",
")",
":",
"Cell_",
".",
"set_mixed_precision_type",
"(",
"self",
",",
"mixed_type",
")",
"for",
"cell",
"in",
"self",
".",
"cells",
"(",
")",
":",
"cell",
".",
"_set_mixed_precision_ty... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/cell.py#L1317-L1321 | ||
sdhash/sdhash | b9eff63e4e5867e910f41fd69032bbb1c94a2a5e | sdhash-ui/cherrypy/process/plugins.py | python | SignalHandler.subscribe | (self) | Subscribe self.handlers to signals. | Subscribe self.handlers to signals. | [
"Subscribe",
"self",
".",
"handlers",
"to",
"signals",
"."
] | def subscribe(self):
"""Subscribe self.handlers to signals."""
for sig, func in self.handlers.items():
try:
self.set_handler(sig, func)
except ValueError:
pass | [
"def",
"subscribe",
"(",
"self",
")",
":",
"for",
"sig",
",",
"func",
"in",
"self",
".",
"handlers",
".",
"items",
"(",
")",
":",
"try",
":",
"self",
".",
"set_handler",
"(",
"sig",
",",
"func",
")",
"except",
"ValueError",
":",
"pass"
] | https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-ui/cherrypy/process/plugins.py#L115-L121 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/stc.py | python | StyledTextCtrl.SetWhitespaceBackground | (*args, **kwargs) | return _stc.StyledTextCtrl_SetWhitespaceBackground(*args, **kwargs) | SetWhitespaceBackground(self, bool useSetting, Colour back)
Set the background colour of all whitespace and whether to use this setting. | SetWhitespaceBackground(self, bool useSetting, Colour back) | [
"SetWhitespaceBackground",
"(",
"self",
"bool",
"useSetting",
"Colour",
"back",
")"
] | def SetWhitespaceBackground(*args, **kwargs):
"""
SetWhitespaceBackground(self, bool useSetting, Colour back)
Set the background colour of all whitespace and whether to use this setting.
"""
return _stc.StyledTextCtrl_SetWhitespaceBackground(*args, **kwargs) | [
"def",
"SetWhitespaceBackground",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_SetWhitespaceBackground",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/stc.py#L2921-L2927 | |
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py | python | xmlAttr.removeProp | (self) | return ret | Unlink and free one attribute, all the content is freed too
Note this doesn't work for namespace definition attributes | Unlink and free one attribute, all the content is freed too
Note this doesn't work for namespace definition attributes | [
"Unlink",
"and",
"free",
"one",
"attribute",
"all",
"the",
"content",
"is",
"freed",
"too",
"Note",
"this",
"doesn",
"t",
"work",
"for",
"namespace",
"definition",
"attributes"
] | def removeProp(self):
"""Unlink and free one attribute, all the content is freed too
Note this doesn't work for namespace definition attributes """
ret = libxml2mod.xmlRemoveProp(self._o)
return ret | [
"def",
"removeProp",
"(",
"self",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlRemoveProp",
"(",
"self",
".",
"_o",
")",
"return",
"ret"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L4828-L4832 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/email/_header_value_parser.py | python | get_extended_attrtext | (value) | return attrtext, value | attrtext = 1*(any non-ATTRIBUTE_ENDS character plus '%')
This is a special parsing routine so that we get a value that
includes % escapes as a single string (which we decode as a single
string later). | attrtext = 1*(any non-ATTRIBUTE_ENDS character plus '%') | [
"attrtext",
"=",
"1",
"*",
"(",
"any",
"non",
"-",
"ATTRIBUTE_ENDS",
"character",
"plus",
"%",
")"
] | def get_extended_attrtext(value):
"""attrtext = 1*(any non-ATTRIBUTE_ENDS character plus '%')
This is a special parsing routine so that we get a value that
includes % escapes as a single string (which we decode as a single
string later).
"""
m = _non_extended_attribute_end_matcher(value)
if not m:
raise errors.HeaderParseError(
"expected extended attrtext but found {!r}".format(value))
attrtext = m.group()
value = value[len(attrtext):]
attrtext = ValueTerminal(attrtext, 'extended-attrtext')
_validate_xtext(attrtext)
return attrtext, value | [
"def",
"get_extended_attrtext",
"(",
"value",
")",
":",
"m",
"=",
"_non_extended_attribute_end_matcher",
"(",
"value",
")",
"if",
"not",
"m",
":",
"raise",
"errors",
".",
"HeaderParseError",
"(",
"\"expected extended attrtext but found {!r}\"",
".",
"format",
"(",
"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/email/_header_value_parser.py#L2319-L2335 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/hypertreelist.py | python | EditCtrl.AcceptChanges | (self) | Accepts/refuses the changes made by the user. | Accepts/refuses the changes made by the user. | [
"Accepts",
"/",
"refuses",
"the",
"changes",
"made",
"by",
"the",
"user",
"."
] | def AcceptChanges(self):
"""Accepts/refuses the changes made by the user."""
value = self.GetValue()
if value == self._startValue:
# nothing changed, always accept
# when an item remains unchanged, the owner
# needs to be notified that the user decided
# not to change the tree item label, and that
# the edit has been cancelled
self._owner.OnCancelEdit()
return True
else:
return self._owner.OnAcceptEdit(value) | [
"def",
"AcceptChanges",
"(",
"self",
")",
":",
"value",
"=",
"self",
".",
"GetValue",
"(",
")",
"if",
"value",
"==",
"self",
".",
"_startValue",
":",
"# nothing changed, always accept",
"# when an item remains unchanged, the owner",
"# needs to be notified that the user d... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/hypertreelist.py#L1896-L1910 | ||
tensorflow/deepmath | b5b721f54de1d5d6a02d78f5da5995237f9995f9 | deepmath/deephol/utilities/proof_checker_lib.py | python | proof_log_as_dict | (log: deephol_pb2.ProofLog
) | return d | Turns proof log into a dictionary. | Turns proof log into a dictionary. | [
"Turns",
"proof",
"log",
"into",
"a",
"dictionary",
"."
] | def proof_log_as_dict(log: deephol_pb2.ProofLog
) -> Dict[int, deephol_pb2.ProofNode]:
"""Turns proof log into a dictionary."""
d = {}
for node in log.nodes:
fingerprint = theorem_fingerprint.Fingerprint(node.goal)
if fingerprint in d:
raise ValueError('Duplicate subgoal in fingerprint. Ignoring')
d[fingerprint] = node
return d | [
"def",
"proof_log_as_dict",
"(",
"log",
":",
"deephol_pb2",
".",
"ProofLog",
")",
"->",
"Dict",
"[",
"int",
",",
"deephol_pb2",
".",
"ProofNode",
"]",
":",
"d",
"=",
"{",
"}",
"for",
"node",
"in",
"log",
".",
"nodes",
":",
"fingerprint",
"=",
"theorem_... | https://github.com/tensorflow/deepmath/blob/b5b721f54de1d5d6a02d78f5da5995237f9995f9/deepmath/deephol/utilities/proof_checker_lib.py#L76-L85 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py | python | LineWriter.writestring | (self, string) | Write a string | Write a string | [
"Write",
"a",
"string"
] | def writestring(self, string):
"Write a string"
if not self.file:
self.file = codecs.open(self.filename, 'w', "utf-8")
if self.file == sys.stdout and sys.version_info < (3,0):
string = string.encode('utf-8')
self.file.write(string) | [
"def",
"writestring",
"(",
"self",
",",
"string",
")",
":",
"if",
"not",
"self",
".",
"file",
":",
"self",
".",
"file",
"=",
"codecs",
".",
"open",
"(",
"self",
".",
"filename",
",",
"'w'",
",",
"\"utf-8\"",
")",
"if",
"self",
".",
"file",
"==",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py#L1799-L1805 | ||
bareos/bareos | 56a10bb368b0a81e977bb51304033fe49d59efb0 | core/src/plugins/filed/python/mariabackup/BareosFdPluginMariabackup.py | python | BareosFdMariabackup.create_file | (self, restorepkt) | return bRC_OK | On restore we create a subdirectory for the first base backup and each incremental backup.
Because mariabackup expects an empty directory, we create a tree starting with jobId/ of restore job | On restore we create a subdirectory for the first base backup and each incremental backup.
Because mariabackup expects an empty directory, we create a tree starting with jobId/ of restore job | [
"On",
"restore",
"we",
"create",
"a",
"subdirectory",
"for",
"the",
"first",
"base",
"backup",
"and",
"each",
"incremental",
"backup",
".",
"Because",
"mariabackup",
"expects",
"an",
"empty",
"directory",
"we",
"create",
"a",
"tree",
"starting",
"with",
"jobId... | def create_file(self, restorepkt):
"""
On restore we create a subdirectory for the first base backup and each incremental backup.
Because mariabackup expects an empty directory, we create a tree starting with jobId/ of restore job
"""
FNAME = restorepkt.ofname
DebugMessage(100, "create file with %s called\n" % FNAME)
self.writeDir = "%s/%d/" % (os.path.dirname(FNAME), self.jobId)
# FNAME contains originating jobId after last .
origJobId = int(FNAME.rpartition(".")[-1])
if origJobId in self.rop_data:
rop_from_lsn = int(self.rop_data[origJobId]["from_lsn"])
rop_to_lsn = int(self.rop_data[origJobId]["to_lsn"])
self.writeDir += "/%020d_" % rop_from_lsn
self.writeDir += "%020d_" % rop_to_lsn
self.writeDir += "%010d" % origJobId
else:
JobMessage(
M_ERROR,
"No lsn information found in restore object for file %s from job %d\n"
% (FNAME, origJobId),
)
# Create restore directory, if not existent
if not os.path.exists(self.writeDir):
bareosfd.DebugMessage(
200,
"Directory %s does not exist, creating it now\n" % self.writeDir,
)
os.makedirs(self.writeDir)
# Mariabackup requires empty directory
if os.listdir(self.writeDir):
JobMessage(
M_FATAL,
"Restore with xbstream needs empty directory: %s\n" % self.writeDir,
)
return bRC_Error
self.restorecommand += self.writeDir
DebugMessage(
100,
'Restore using xbstream to extract files with "%s"\n' % self.restorecommand,
)
restorepkt.create_status = CF_EXTRACT
return bRC_OK | [
"def",
"create_file",
"(",
"self",
",",
"restorepkt",
")",
":",
"FNAME",
"=",
"restorepkt",
".",
"ofname",
"DebugMessage",
"(",
"100",
",",
"\"create file with %s called\\n\"",
"%",
"FNAME",
")",
"self",
".",
"writeDir",
"=",
"\"%s/%d/\"",
"%",
"(",
"os",
".... | https://github.com/bareos/bareos/blob/56a10bb368b0a81e977bb51304033fe49d59efb0/core/src/plugins/filed/python/mariabackup/BareosFdPluginMariabackup.py#L135-L178 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/_pydecimal.py | python | Decimal.__rsub__ | (self, other, context=None) | return other.__sub__(self, context=context) | Return other - self | Return other - self | [
"Return",
"other",
"-",
"self"
] | def __rsub__(self, other, context=None):
"""Return other - self"""
other = _convert_other(other)
if other is NotImplemented:
return other
return other.__sub__(self, context=context) | [
"def",
"__rsub__",
"(",
"self",
",",
"other",
",",
"context",
"=",
"None",
")",
":",
"other",
"=",
"_convert_other",
"(",
"other",
")",
"if",
"other",
"is",
"NotImplemented",
":",
"return",
"other",
"return",
"other",
".",
"__sub__",
"(",
"self",
",",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/_pydecimal.py#L1259-L1265 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/keras/_impl/keras/backend.py | python | switch | (condition, then_expression, else_expression) | return x | Switches between two operations depending on a scalar value.
Note that both `then_expression` and `else_expression`
should be symbolic tensors of the *same shape*.
Arguments:
condition: scalar tensor (`int` or `bool`).
then_expression: either a tensor, or a callable that returns a tensor.
else_expression: either a tensor, or a callable that returns a tensor.
Returns:
The selected tensor. | Switches between two operations depending on a scalar value. | [
"Switches",
"between",
"two",
"operations",
"depending",
"on",
"a",
"scalar",
"value",
"."
] | def switch(condition, then_expression, else_expression):
"""Switches between two operations depending on a scalar value.
Note that both `then_expression` and `else_expression`
should be symbolic tensors of the *same shape*.
Arguments:
condition: scalar tensor (`int` or `bool`).
then_expression: either a tensor, or a callable that returns a tensor.
else_expression: either a tensor, or a callable that returns a tensor.
Returns:
The selected tensor.
"""
if condition.dtype != dtypes_module.bool:
condition = math_ops.cast(condition, 'bool')
if not callable(then_expression):
def then_expression_fn():
return then_expression
else:
then_expression_fn = then_expression
if not callable(else_expression):
def else_expression_fn():
return else_expression
else:
else_expression_fn = else_expression
x = control_flow_ops.cond(condition, then_expression_fn, else_expression_fn)
return x | [
"def",
"switch",
"(",
"condition",
",",
"then_expression",
",",
"else_expression",
")",
":",
"if",
"condition",
".",
"dtype",
"!=",
"dtypes_module",
".",
"bool",
":",
"condition",
"=",
"math_ops",
".",
"cast",
"(",
"condition",
",",
"'bool'",
")",
"if",
"n... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/keras/_impl/keras/backend.py#L2769-L2798 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/stats/morestats.py | python | bayes_mvs | (data, alpha=0.90) | return m_res, v_res, s_res | r"""
Bayesian confidence intervals for the mean, var, and std.
Parameters
----------
data : array_like
Input data, if multi-dimensional it is flattened to 1-D by `bayes_mvs`.
Requires 2 or more data points.
alpha : float, optional
Probability that the returned confidence interval contains
the true parameter.
Returns
-------
mean_cntr, var_cntr, std_cntr : tuple
The three results are for the mean, variance and standard deviation,
respectively. Each result is a tuple of the form::
(center, (lower, upper))
with `center` the mean of the conditional pdf of the value given the
data, and `(lower, upper)` a confidence interval, centered on the
median, containing the estimate to a probability ``alpha``.
See Also
--------
mvsdist
Notes
-----
Each tuple of mean, variance, and standard deviation estimates represent
the (center, (lower, upper)) with center the mean of the conditional pdf
of the value given the data and (lower, upper) is a confidence interval
centered on the median, containing the estimate to a probability
``alpha``.
Converts data to 1-D and assumes all data has the same mean and variance.
Uses Jeffrey's prior for variance and std.
Equivalent to ``tuple((x.mean(), x.interval(alpha)) for x in mvsdist(dat))``
References
----------
T.E. Oliphant, "A Bayesian perspective on estimating mean, variance, and
standard-deviation from data", http://scholarsarchive.byu.edu/facpub/278,
2006.
Examples
--------
First a basic example to demonstrate the outputs:
>>> from scipy import stats
>>> data = [6, 9, 12, 7, 8, 8, 13]
>>> mean, var, std = stats.bayes_mvs(data)
>>> mean
Mean(statistic=9.0, minmax=(7.1036502226125329, 10.896349777387467))
>>> var
Variance(statistic=10.0, minmax=(3.176724206..., 24.45910382...))
>>> std
Std_dev(statistic=2.9724954732045084, minmax=(1.7823367265645143, 4.9456146050146295))
Now we generate some normally distributed random data, and get estimates of
mean and standard deviation with 95% confidence intervals for those
estimates:
>>> n_samples = 100000
>>> data = stats.norm.rvs(size=n_samples)
>>> res_mean, res_var, res_std = stats.bayes_mvs(data, alpha=0.95)
>>> import matplotlib.pyplot as plt
>>> fig = plt.figure()
>>> ax = fig.add_subplot(111)
>>> ax.hist(data, bins=100, normed=True, label='Histogram of data')
>>> ax.vlines(res_mean.statistic, 0, 0.5, colors='r', label='Estimated mean')
>>> ax.axvspan(res_mean.minmax[0],res_mean.minmax[1], facecolor='r',
... alpha=0.2, label=r'Estimated mean (95% limits)')
>>> ax.vlines(res_std.statistic, 0, 0.5, colors='g', label='Estimated scale')
>>> ax.axvspan(res_std.minmax[0],res_std.minmax[1], facecolor='g', alpha=0.2,
... label=r'Estimated scale (95% limits)')
>>> ax.legend(fontsize=10)
>>> ax.set_xlim([-4, 4])
>>> ax.set_ylim([0, 0.5])
>>> plt.show() | r"""
Bayesian confidence intervals for the mean, var, and std. | [
"r",
"Bayesian",
"confidence",
"intervals",
"for",
"the",
"mean",
"var",
"and",
"std",
"."
] | def bayes_mvs(data, alpha=0.90):
r"""
Bayesian confidence intervals for the mean, var, and std.
Parameters
----------
data : array_like
Input data, if multi-dimensional it is flattened to 1-D by `bayes_mvs`.
Requires 2 or more data points.
alpha : float, optional
Probability that the returned confidence interval contains
the true parameter.
Returns
-------
mean_cntr, var_cntr, std_cntr : tuple
The three results are for the mean, variance and standard deviation,
respectively. Each result is a tuple of the form::
(center, (lower, upper))
with `center` the mean of the conditional pdf of the value given the
data, and `(lower, upper)` a confidence interval, centered on the
median, containing the estimate to a probability ``alpha``.
See Also
--------
mvsdist
Notes
-----
Each tuple of mean, variance, and standard deviation estimates represent
the (center, (lower, upper)) with center the mean of the conditional pdf
of the value given the data and (lower, upper) is a confidence interval
centered on the median, containing the estimate to a probability
``alpha``.
Converts data to 1-D and assumes all data has the same mean and variance.
Uses Jeffrey's prior for variance and std.
Equivalent to ``tuple((x.mean(), x.interval(alpha)) for x in mvsdist(dat))``
References
----------
T.E. Oliphant, "A Bayesian perspective on estimating mean, variance, and
standard-deviation from data", http://scholarsarchive.byu.edu/facpub/278,
2006.
Examples
--------
First a basic example to demonstrate the outputs:
>>> from scipy import stats
>>> data = [6, 9, 12, 7, 8, 8, 13]
>>> mean, var, std = stats.bayes_mvs(data)
>>> mean
Mean(statistic=9.0, minmax=(7.1036502226125329, 10.896349777387467))
>>> var
Variance(statistic=10.0, minmax=(3.176724206..., 24.45910382...))
>>> std
Std_dev(statistic=2.9724954732045084, minmax=(1.7823367265645143, 4.9456146050146295))
Now we generate some normally distributed random data, and get estimates of
mean and standard deviation with 95% confidence intervals for those
estimates:
>>> n_samples = 100000
>>> data = stats.norm.rvs(size=n_samples)
>>> res_mean, res_var, res_std = stats.bayes_mvs(data, alpha=0.95)
>>> import matplotlib.pyplot as plt
>>> fig = plt.figure()
>>> ax = fig.add_subplot(111)
>>> ax.hist(data, bins=100, normed=True, label='Histogram of data')
>>> ax.vlines(res_mean.statistic, 0, 0.5, colors='r', label='Estimated mean')
>>> ax.axvspan(res_mean.minmax[0],res_mean.minmax[1], facecolor='r',
... alpha=0.2, label=r'Estimated mean (95% limits)')
>>> ax.vlines(res_std.statistic, 0, 0.5, colors='g', label='Estimated scale')
>>> ax.axvspan(res_std.minmax[0],res_std.minmax[1], facecolor='g', alpha=0.2,
... label=r'Estimated scale (95% limits)')
>>> ax.legend(fontsize=10)
>>> ax.set_xlim([-4, 4])
>>> ax.set_ylim([0, 0.5])
>>> plt.show()
"""
m, v, s = mvsdist(data)
if alpha >= 1 or alpha <= 0:
raise ValueError("0 < alpha < 1 is required, but alpha=%s was given."
% alpha)
m_res = Mean(m.mean(), m.interval(alpha))
v_res = Variance(v.mean(), v.interval(alpha))
s_res = Std_dev(s.mean(), s.interval(alpha))
return m_res, v_res, s_res | [
"def",
"bayes_mvs",
"(",
"data",
",",
"alpha",
"=",
"0.90",
")",
":",
"m",
",",
"v",
",",
"s",
"=",
"mvsdist",
"(",
"data",
")",
"if",
"alpha",
">=",
"1",
"or",
"alpha",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"\"0 < alpha < 1 is required, but alph... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/stats/morestats.py#L43-L139 | |
domino-team/openwrt-cc | 8b181297c34d14d3ca521cc9f31430d561dbc688 | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py | python | PBXProject.RootGroupForPath | (self, path) | return (self.SourceGroup(), True) | Returns a PBXGroup child of this object to which path should be added.
This method is intended to choose between SourceGroup and
IntermediatesGroup on the basis of whether path is present in a source
directory or an intermediates directory. For the purposes of this
determination, any path located within a derived file directory such as
PROJECT_DERIVED_FILE_DIR is treated as being in an intermediates
directory.
The returned value is a two-element tuple. The first element is the
PBXGroup, and the second element specifies whether that group should be
organized hierarchically (True) or as a single flat list (False). | Returns a PBXGroup child of this object to which path should be added. | [
"Returns",
"a",
"PBXGroup",
"child",
"of",
"this",
"object",
"to",
"which",
"path",
"should",
"be",
"added",
"."
] | def RootGroupForPath(self, path):
"""Returns a PBXGroup child of this object to which path should be added.
This method is intended to choose between SourceGroup and
IntermediatesGroup on the basis of whether path is present in a source
directory or an intermediates directory. For the purposes of this
determination, any path located within a derived file directory such as
PROJECT_DERIVED_FILE_DIR is treated as being in an intermediates
directory.
The returned value is a two-element tuple. The first element is the
PBXGroup, and the second element specifies whether that group should be
organized hierarchically (True) or as a single flat list (False).
"""
# TODO(mark): make this a class variable and bind to self on call?
# Also, this list is nowhere near exhaustive.
# INTERMEDIATE_DIR and SHARED_INTERMEDIATE_DIR are used by
# gyp.generator.xcode. There should probably be some way for that module
# to push the names in, rather than having to hard-code them here.
source_tree_groups = {
'DERIVED_FILE_DIR': (self.IntermediatesGroup, True),
'INTERMEDIATE_DIR': (self.IntermediatesGroup, True),
'PROJECT_DERIVED_FILE_DIR': (self.IntermediatesGroup, True),
'SHARED_INTERMEDIATE_DIR': (self.IntermediatesGroup, True),
}
(source_tree, path) = SourceTreeAndPathFromPath(path)
if source_tree != None and source_tree in source_tree_groups:
(group_func, hierarchical) = source_tree_groups[source_tree]
group = group_func()
return (group, hierarchical)
# TODO(mark): make additional choices based on file extension.
return (self.SourceGroup(), True) | [
"def",
"RootGroupForPath",
"(",
"self",
",",
"path",
")",
":",
"# TODO(mark): make this a class variable and bind to self on call?",
"# Also, this list is nowhere near exhaustive.",
"# INTERMEDIATE_DIR and SHARED_INTERMEDIATE_DIR are used by",
"# gyp.generator.xcode. There should probably be ... | https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py#L2584-L2619 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_misc.py | python | ClipboardLocker.__init__ | (self, *args, **kwargs) | __init__(self, Clipboard clipboard=None) -> ClipboardLocker
A helpful class for opening the clipboard and automatically
closing it when the locker is destroyed. | __init__(self, Clipboard clipboard=None) -> ClipboardLocker | [
"__init__",
"(",
"self",
"Clipboard",
"clipboard",
"=",
"None",
")",
"-",
">",
"ClipboardLocker"
] | def __init__(self, *args, **kwargs):
"""
__init__(self, Clipboard clipboard=None) -> ClipboardLocker
A helpful class for opening the clipboard and automatically
closing it when the locker is destroyed.
"""
_misc_.ClipboardLocker_swiginit(self,_misc_.new_ClipboardLocker(*args, **kwargs)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_misc_",
".",
"ClipboardLocker_swiginit",
"(",
"self",
",",
"_misc_",
".",
"new_ClipboardLocker",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L5955-L5962 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_gdi.py | python | NativePixelData.__init__ | (self, *args) | __init__(self, Bitmap bmp) -> NativePixelData
__init__(self, Bitmap bmp, Rect rect) -> NativePixelData
__init__(self, Bitmap bmp, Point pt, Size sz) -> NativePixelData | __init__(self, Bitmap bmp) -> NativePixelData
__init__(self, Bitmap bmp, Rect rect) -> NativePixelData
__init__(self, Bitmap bmp, Point pt, Size sz) -> NativePixelData | [
"__init__",
"(",
"self",
"Bitmap",
"bmp",
")",
"-",
">",
"NativePixelData",
"__init__",
"(",
"self",
"Bitmap",
"bmp",
"Rect",
"rect",
")",
"-",
">",
"NativePixelData",
"__init__",
"(",
"self",
"Bitmap",
"bmp",
"Point",
"pt",
"Size",
"sz",
")",
"-",
">",
... | def __init__(self, *args):
"""
__init__(self, Bitmap bmp) -> NativePixelData
__init__(self, Bitmap bmp, Rect rect) -> NativePixelData
__init__(self, Bitmap bmp, Point pt, Size sz) -> NativePixelData
"""
_gdi_.NativePixelData_swiginit(self,_gdi_.new_NativePixelData(*args)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
")",
":",
"_gdi_",
".",
"NativePixelData_swiginit",
"(",
"self",
",",
"_gdi_",
".",
"new_NativePixelData",
"(",
"*",
"args",
")",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L1017-L1023 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/train/summary/_summary_adapter.py | python | _fill_image_summary | (tag: str, np_value, summary_image, input_format='NCHW') | return True | Package the image summary.
Args:
tag (str): Summary tag describe.
np_value (Type): Summary data type.
summary_image (Tensor): The tensor of summary.
input_format (str): Data sort order index. Default: 'NCHW'.
Returns:
Summary, return image summary content. | Package the image summary. | [
"Package",
"the",
"image",
"summary",
"."
] | def _fill_image_summary(tag: str, np_value, summary_image, input_format='NCHW'):
"""
Package the image summary.
Args:
tag (str): Summary tag describe.
np_value (Type): Summary data type.
summary_image (Tensor): The tensor of summary.
input_format (str): Data sort order index. Default: 'NCHW'.
Returns:
Summary, return image summary content.
"""
logger.debug(f"Set({tag}) the image summary value")
if np_value.ndim != 4 or np_value.shape[1] not in (1, 3):
logger.error(f"The value is not Image, tag = {tag}, ndim = {np_value.ndim}, shape={np_value.shape}")
return False
if np_value.ndim != len(input_format):
logger.error(
f"The tensor with dim({np_value.ndim}) can't convert the format({input_format}) because dim not same")
return False
if 0 in np_value.shape:
logger.error(
f"The tensor with shape({np_value.shape}) is not a valid image because the shape contains zero.")
return False
# convert the tensor format
tensor = _convert_image_format(np_value, input_format)
# convert the tensor dtype
# Do not assume that user passes in values in [0, 255], use data type to detect
scale_factor = 1
if tensor.dtype == np.uint8:
scale_factor = 1
elif np.max(tensor) <= 1 and np.min(tensor) >= 0:
scale_factor = 255
tensor = tensor.astype(np.float32)
tensor = (tensor * scale_factor).astype(np.uint8)
# create the image summary
height, width, channel, image_string = _make_image(tensor)
summary_image.height = height
summary_image.width = width
summary_image.colorspace = channel
summary_image.encoded_image = image_string
return True | [
"def",
"_fill_image_summary",
"(",
"tag",
":",
"str",
",",
"np_value",
",",
"summary_image",
",",
"input_format",
"=",
"'NCHW'",
")",
":",
"logger",
".",
"debug",
"(",
"f\"Set({tag}) the image summary value\"",
")",
"if",
"np_value",
".",
"ndim",
"!=",
"4",
"o... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/train/summary/_summary_adapter.py#L342-L389 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Draft/importDXF.py | python | drawCircle | (circle, forceShape=False) | return None | Return a Part shape (Circle, Edge) from a DXF circle.
Parameters
----------
circle : drawing.entities
The DXF object of type `'circle'`. The `'circle'` object is different
from an `'arc'` because the circle forms a full circumference.
forceShape : bool, optional
It defaults to `False`. If it is `True` it will try to produce
a `Part.Edge`, otherwise it tries to produce a `Draft Circle`.
Returns
-------
Part::Part2DObject or Part::TopoShape ('Edge')
The returned object is normally a `Draft Circle` with no face,
if the global variables `dxfCreateDraft` or `dxfCreateSketch` are set,
and `forceShape` is `False`.
Otherwise it produces a `Part.Edge`.
It returns `None` if it fails producing a shape.
See also
--------
drawArc, drawBlock
To do
-----
Use local variables, not global variables. | Return a Part shape (Circle, Edge) from a DXF circle. | [
"Return",
"a",
"Part",
"shape",
"(",
"Circle",
"Edge",
")",
"from",
"a",
"DXF",
"circle",
"."
] | def drawCircle(circle, forceShape=False):
"""Return a Part shape (Circle, Edge) from a DXF circle.
Parameters
----------
circle : drawing.entities
The DXF object of type `'circle'`. The `'circle'` object is different
from an `'arc'` because the circle forms a full circumference.
forceShape : bool, optional
It defaults to `False`. If it is `True` it will try to produce
a `Part.Edge`, otherwise it tries to produce a `Draft Circle`.
Returns
-------
Part::Part2DObject or Part::TopoShape ('Edge')
The returned object is normally a `Draft Circle` with no face,
if the global variables `dxfCreateDraft` or `dxfCreateSketch` are set,
and `forceShape` is `False`.
Otherwise it produces a `Part.Edge`.
It returns `None` if it fails producing a shape.
See also
--------
drawArc, drawBlock
To do
-----
Use local variables, not global variables.
"""
v = vec(circle.loc)
curve = Part.Circle()
curve.Radius = vec(circle.radius)
curve.Center = v
try:
if (dxfCreateDraft or dxfCreateSketch) and (not forceShape):
pl = placementFromDXFOCS(circle)
return Draft.makeCircle(circle.radius, pl)
else:
return curve.toShape()
except Part.OCCError:
warn(circle)
return None | [
"def",
"drawCircle",
"(",
"circle",
",",
"forceShape",
"=",
"False",
")",
":",
"v",
"=",
"vec",
"(",
"circle",
".",
"loc",
")",
"curve",
"=",
"Part",
".",
"Circle",
"(",
")",
"curve",
".",
"Radius",
"=",
"vec",
"(",
"circle",
".",
"radius",
")",
... | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/importDXF.py#L1061-L1104 | |
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | third_party/Python/module/pexpect-4.6/pexpect/FSM.py | python | FSM.add_transition_any | (self, state, action=None, next_state=None) | This adds a transition that associates:
(current_state) --> (action, next_state)
That is, any input symbol will match the current state.
The process() method checks the "any" state associations after it first
checks for an exact match of (input_symbol, current_state).
The action may be set to None in which case the process() method will
ignore the action and only set the next_state. The next_state may be
set to None in which case the current state will be unchanged. | This adds a transition that associates: | [
"This",
"adds",
"a",
"transition",
"that",
"associates",
":"
] | def add_transition_any (self, state, action=None, next_state=None):
'''This adds a transition that associates:
(current_state) --> (action, next_state)
That is, any input symbol will match the current state.
The process() method checks the "any" state associations after it first
checks for an exact match of (input_symbol, current_state).
The action may be set to None in which case the process() method will
ignore the action and only set the next_state. The next_state may be
set to None in which case the current state will be unchanged. '''
if next_state is None:
next_state = state
self.state_transitions_any [state] = (action, next_state) | [
"def",
"add_transition_any",
"(",
"self",
",",
"state",
",",
"action",
"=",
"None",
",",
"next_state",
"=",
"None",
")",
":",
"if",
"next_state",
"is",
"None",
":",
"next_state",
"=",
"state",
"self",
".",
"state_transitions_any",
"[",
"state",
"]",
"=",
... | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/third_party/Python/module/pexpect-4.6/pexpect/FSM.py#L164-L180 | ||
sailing-pmls/pmls-caffe | 49e98bced9c6d5af7cd701d18ab235b5fd0e4b3a | scripts/cpp_lint.py | python | _IncludeState.CheckNextIncludeOrder | (self, header_type) | return '' | Returns a non-empty error message if the next header is out of order.
This function also updates the internal state to be ready to check
the next include.
Args:
header_type: One of the _XXX_HEADER constants defined above.
Returns:
The empty string if the header is in the right order, or an
error message describing what's wrong. | Returns a non-empty error message if the next header is out of order. | [
"Returns",
"a",
"non",
"-",
"empty",
"error",
"message",
"if",
"the",
"next",
"header",
"is",
"out",
"of",
"order",
"."
] | def CheckNextIncludeOrder(self, header_type):
"""Returns a non-empty error message if the next header is out of order.
This function also updates the internal state to be ready to check
the next include.
Args:
header_type: One of the _XXX_HEADER constants defined above.
Returns:
The empty string if the header is in the right order, or an
error message describing what's wrong.
"""
error_message = ('Found %s after %s' %
(self._TYPE_NAMES[header_type],
self._SECTION_NAMES[self._section]))
last_section = self._section
if header_type == _C_SYS_HEADER:
if self._section <= self._C_SECTION:
self._section = self._C_SECTION
else:
self._last_header = ''
return error_message
elif header_type == _CPP_SYS_HEADER:
if self._section <= self._CPP_SECTION:
self._section = self._CPP_SECTION
else:
self._last_header = ''
return error_message
elif header_type == _LIKELY_MY_HEADER:
if self._section <= self._MY_H_SECTION:
self._section = self._MY_H_SECTION
else:
self._section = self._OTHER_H_SECTION
elif header_type == _POSSIBLE_MY_HEADER:
if self._section <= self._MY_H_SECTION:
self._section = self._MY_H_SECTION
else:
# This will always be the fallback because we're not sure
# enough that the header is associated with this file.
self._section = self._OTHER_H_SECTION
else:
assert header_type == _OTHER_HEADER
self._section = self._OTHER_H_SECTION
if last_section != self._section:
self._last_header = ''
return '' | [
"def",
"CheckNextIncludeOrder",
"(",
"self",
",",
"header_type",
")",
":",
"error_message",
"=",
"(",
"'Found %s after %s'",
"%",
"(",
"self",
".",
"_TYPE_NAMES",
"[",
"header_type",
"]",
",",
"self",
".",
"_SECTION_NAMES",
"[",
"self",
".",
"_section",
"]",
... | https://github.com/sailing-pmls/pmls-caffe/blob/49e98bced9c6d5af7cd701d18ab235b5fd0e4b3a/scripts/cpp_lint.py#L633-L684 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/tools/inspector_protocol/jinja2/environment.py | python | Template.make_module_async | (self, vars=None, shared=False, locals=None) | As template module creation can invoke template code for
asynchronous exections this method must be used instead of the
normal :meth:`make_module` one. Likewise the module attribute
becomes unavailable in async mode. | As template module creation can invoke template code for
asynchronous exections this method must be used instead of the
normal :meth:`make_module` one. Likewise the module attribute
becomes unavailable in async mode. | [
"As",
"template",
"module",
"creation",
"can",
"invoke",
"template",
"code",
"for",
"asynchronous",
"exections",
"this",
"method",
"must",
"be",
"used",
"instead",
"of",
"the",
"normal",
":",
"meth",
":",
"make_module",
"one",
".",
"Likewise",
"the",
"module",... | def make_module_async(self, vars=None, shared=False, locals=None):
"""As template module creation can invoke template code for
asynchronous exections this method must be used instead of the
normal :meth:`make_module` one. Likewise the module attribute
becomes unavailable in async mode.
"""
# see asyncsupport for the actual implementation
raise NotImplementedError('This feature is not available for this '
'version of Python') | [
"def",
"make_module_async",
"(",
"self",
",",
"vars",
"=",
"None",
",",
"shared",
"=",
"False",
",",
"locals",
"=",
"None",
")",
":",
"# see asyncsupport for the actual implementation",
"raise",
"NotImplementedError",
"(",
"'This feature is not available for this '",
"'... | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/inspector_protocol/jinja2/environment.py#L1075-L1083 | ||
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Defaults.py | python | _stripixes | (prefix, itms, suffix, stripprefixes, stripsuffixes, env, c=None) | return c(prefix, stripped, suffix, env) | This is a wrapper around _concat()/_concat_ixes() that checks for
the existence of prefixes or suffixes on list items and strips them
where it finds them. This is used by tools (like the GNU linker)
that need to turn something like 'libfoo.a' into '-lfoo'. | This is a wrapper around _concat()/_concat_ixes() that checks for
the existence of prefixes or suffixes on list items and strips them
where it finds them. This is used by tools (like the GNU linker)
that need to turn something like 'libfoo.a' into '-lfoo'. | [
"This",
"is",
"a",
"wrapper",
"around",
"_concat",
"()",
"/",
"_concat_ixes",
"()",
"that",
"checks",
"for",
"the",
"existence",
"of",
"prefixes",
"or",
"suffixes",
"on",
"list",
"items",
"and",
"strips",
"them",
"where",
"it",
"finds",
"them",
".",
"This"... | def _stripixes(prefix, itms, suffix, stripprefixes, stripsuffixes, env, c=None):
"""
This is a wrapper around _concat()/_concat_ixes() that checks for
the existence of prefixes or suffixes on list items and strips them
where it finds them. This is used by tools (like the GNU linker)
that need to turn something like 'libfoo.a' into '-lfoo'.
"""
if not itms:
return itms
if not callable(c):
env_c = env['_concat']
if env_c != _concat and callable(env_c):
# There's a custom _concat() method in the construction
# environment, and we've allowed people to set that in
# the past (see test/custom-concat.py), so preserve the
# backwards compatibility.
c = env_c
else:
c = _concat_ixes
stripprefixes = list(map(env.subst, SCons.Util.flatten(stripprefixes)))
stripsuffixes = list(map(env.subst, SCons.Util.flatten(stripsuffixes)))
stripped = []
for l in SCons.PathList.PathList(itms).subst_path(env, None, None):
if isinstance(l, SCons.Node.FS.File):
stripped.append(l)
continue
if not SCons.Util.is_String(l):
l = str(l)
for stripprefix in stripprefixes:
lsp = len(stripprefix)
if l[:lsp] == stripprefix:
l = l[lsp:]
# Do not strip more than one prefix
break
for stripsuffix in stripsuffixes:
lss = len(stripsuffix)
if l[-lss:] == stripsuffix:
l = l[:-lss]
# Do not strip more than one suffix
break
stripped.append(l)
return c(prefix, stripped, suffix, env) | [
"def",
"_stripixes",
"(",
"prefix",
",",
"itms",
",",
"suffix",
",",
"stripprefixes",
",",
"stripsuffixes",
",",
"env",
",",
"c",
"=",
"None",
")",
":",
"if",
"not",
"itms",
":",
"return",
"itms",
"if",
"not",
"callable",
"(",
"c",
")",
":",
"env_c",... | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Defaults.py#L401-L451 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/computation/scope.py | python | _get_pretty_string | (obj) | return sio.getvalue() | Return a prettier version of obj.
Parameters
----------
obj : object
Object to pretty print
Returns
-------
str
Pretty print object repr | Return a prettier version of obj. | [
"Return",
"a",
"prettier",
"version",
"of",
"obj",
"."
] | def _get_pretty_string(obj) -> str:
"""
Return a prettier version of obj.
Parameters
----------
obj : object
Object to pretty print
Returns
-------
str
Pretty print object repr
"""
sio = StringIO()
pprint.pprint(obj, stream=sio)
return sio.getvalue() | [
"def",
"_get_pretty_string",
"(",
"obj",
")",
"->",
"str",
":",
"sio",
"=",
"StringIO",
"(",
")",
"pprint",
".",
"pprint",
"(",
"obj",
",",
"stream",
"=",
"sio",
")",
"return",
"sio",
".",
"getvalue",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/computation/scope.py#L67-L83 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/ops/array_ops.py | python | ones | (shape, dtype=dtypes.float32, name=None) | return output | Creates a tensor with all elements set to 1.
This operation returns a tensor of type `dtype` with shape `shape` and all
elements set to 1.
For example:
```python
tf.ones([2, 3], int32) ==> [[1, 1, 1], [1, 1, 1]]
```
Args:
shape: Either a list of integers, or a 1-D `Tensor` of type `int32`.
dtype: The type of an element in the resulting `Tensor`.
name: A name for the operation (optional).
Returns:
A `Tensor` with all elements set to 1. | Creates a tensor with all elements set to 1. | [
"Creates",
"a",
"tensor",
"with",
"all",
"elements",
"set",
"to",
"1",
"."
] | def ones(shape, dtype=dtypes.float32, name=None):
"""Creates a tensor with all elements set to 1.
This operation returns a tensor of type `dtype` with shape `shape` and all
elements set to 1.
For example:
```python
tf.ones([2, 3], int32) ==> [[1, 1, 1], [1, 1, 1]]
```
Args:
shape: Either a list of integers, or a 1-D `Tensor` of type `int32`.
dtype: The type of an element in the resulting `Tensor`.
name: A name for the operation (optional).
Returns:
A `Tensor` with all elements set to 1.
"""
with ops.op_scope([shape], name, "ones") as name:
try:
shape = tensor_shape.as_shape(shape)
output = constant(1, shape=shape, dtype=dtype, name=name)
except (TypeError, ValueError):
shape = ops.convert_to_tensor(shape, dtype=dtypes.int32, name="shape")
output = fill(shape, constant(1, dtype=dtype), name=name)
assert output.dtype.base_dtype == dtypes.as_dtype(dtype).base_dtype
return output | [
"def",
"ones",
"(",
"shape",
",",
"dtype",
"=",
"dtypes",
".",
"float32",
",",
"name",
"=",
"None",
")",
":",
"with",
"ops",
".",
"op_scope",
"(",
"[",
"shape",
"]",
",",
"name",
",",
"\"ones\"",
")",
"as",
"name",
":",
"try",
":",
"shape",
"=",
... | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/array_ops.py#L1143-L1171 | |
giuspen/cherrytree | 84712f206478fcf9acf30174009ad28c648c6344 | pygtk2/modules/core.py | python | CherryTree.dialog_preferences | (self, *args) | Opens the Preferences Dialog | Opens the Preferences Dialog | [
"Opens",
"the",
"Preferences",
"Dialog"
] | def dialog_preferences(self, *args):
"""Opens the Preferences Dialog"""
self.combobox_country_lang_init()
self.combobox_style_scheme_init()
if self.spell_check_init: self.combobox_spell_check_lang_init()
config.dialog_preferences(self)
config.config_file_save(self) | [
"def",
"dialog_preferences",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"combobox_country_lang_init",
"(",
")",
"self",
".",
"combobox_style_scheme_init",
"(",
")",
"if",
"self",
".",
"spell_check_init",
":",
"self",
".",
"combobox_spell_check_lang_init... | https://github.com/giuspen/cherrytree/blob/84712f206478fcf9acf30174009ad28c648c6344/pygtk2/modules/core.py#L1340-L1346 | ||
domino-team/openwrt-cc | 8b181297c34d14d3ca521cc9f31430d561dbc688 | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py | python | _FilterActionsFromExcluded | (excluded_sources, actions_to_add) | return [s for s in excluded_sources if s not in must_keep] | Take inputs with actions attached out of the list of exclusions.
Arguments:
excluded_sources: list of source files not to be built.
actions_to_add: dict of actions keyed on source file they're attached to.
Returns:
excluded_sources with files that have actions attached removed. | Take inputs with actions attached out of the list of exclusions. | [
"Take",
"inputs",
"with",
"actions",
"attached",
"out",
"of",
"the",
"list",
"of",
"exclusions",
"."
] | def _FilterActionsFromExcluded(excluded_sources, actions_to_add):
"""Take inputs with actions attached out of the list of exclusions.
Arguments:
excluded_sources: list of source files not to be built.
actions_to_add: dict of actions keyed on source file they're attached to.
Returns:
excluded_sources with files that have actions attached removed.
"""
must_keep = OrderedSet(_FixPaths(actions_to_add.keys()))
return [s for s in excluded_sources if s not in must_keep] | [
"def",
"_FilterActionsFromExcluded",
"(",
"excluded_sources",
",",
"actions_to_add",
")",
":",
"must_keep",
"=",
"OrderedSet",
"(",
"_FixPaths",
"(",
"actions_to_add",
".",
"keys",
"(",
")",
")",
")",
"return",
"[",
"s",
"for",
"s",
"in",
"excluded_sources",
"... | https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py#L848-L858 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/receptive_field/python/util/receptive_field.py | python | _conv_kernel_size | (node, name_to_order_node) | return kernel_size_x, kernel_size_y | Computes kernel size given a TF convolution or pooling node.
Args:
node: Tensorflow node (NodeDef proto).
name_to_order_node: Map from name to {order, node}. Output of
graph_compute_order.get_compute_order().
Returns:
kernel_size_x: Kernel size for horizontal direction (integer).
kernel_size_y: Kernel size for vertical direction (integer).
Raises:
ValueError: If the weight layer node is invalid. | Computes kernel size given a TF convolution or pooling node. | [
"Computes",
"kernel",
"size",
"given",
"a",
"TF",
"convolution",
"or",
"pooling",
"node",
"."
] | def _conv_kernel_size(node, name_to_order_node):
"""Computes kernel size given a TF convolution or pooling node.
Args:
node: Tensorflow node (NodeDef proto).
name_to_order_node: Map from name to {order, node}. Output of
graph_compute_order.get_compute_order().
Returns:
kernel_size_x: Kernel size for horizontal direction (integer).
kernel_size_y: Kernel size for vertical direction (integer).
Raises:
ValueError: If the weight layer node is invalid.
"""
weights_layer_read_name = node.input[1]
if not weights_layer_read_name.endswith("/read"):
raise ValueError(
"Weight layer's name input to conv layer does not end with '/read'")
weights_layer_param_name = weights_layer_read_name[:-5]
weights_node = name_to_order_node[weights_layer_param_name].node
if weights_node.op != "VariableV2":
raise ValueError("Weight layer is not of type VariableV2")
shape = weights_node.attr["shape"]
logging.vlog(4, "weight shape = %s", shape)
kernel_size_y = shape.shape.dim[0].size
kernel_size_x = shape.shape.dim[1].size
return kernel_size_x, kernel_size_y | [
"def",
"_conv_kernel_size",
"(",
"node",
",",
"name_to_order_node",
")",
":",
"weights_layer_read_name",
"=",
"node",
".",
"input",
"[",
"1",
"]",
"if",
"not",
"weights_layer_read_name",
".",
"endswith",
"(",
"\"/read\"",
")",
":",
"raise",
"ValueError",
"(",
... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/receptive_field/python/util/receptive_field.py#L62-L89 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/feature_column/feature_column_v2.py | python | VocabularyListCategoricalColumn._transform_input_tensor | (self, input_tensor, state_manager=None) | return table.lookup(input_tensor) | Creates a lookup table for the vocabulary list. | Creates a lookup table for the vocabulary list. | [
"Creates",
"a",
"lookup",
"table",
"for",
"the",
"vocabulary",
"list",
"."
] | def _transform_input_tensor(self, input_tensor, state_manager=None):
"""Creates a lookup table for the vocabulary list."""
if self.dtype.is_integer != input_tensor.dtype.is_integer:
raise ValueError(
'Column dtype and SparseTensors dtype must be compatible. '
'key: {}, column dtype: {}, tensor dtype: {}'.format(
self.key, self.dtype, input_tensor.dtype))
fc_utils.assert_string_or_int(
input_tensor.dtype,
prefix='column_name: {} input_tensor'.format(self.key))
key_dtype = self.dtype
if input_tensor.dtype.is_integer:
# `index_table_from_tensor` requires 64-bit integer keys.
key_dtype = dtypes.int64
input_tensor = math_ops.cast(input_tensor, dtypes.int64)
name = '{}_lookup'.format(self.key)
if state_manager is None or not state_manager.has_resource(self, name):
with ops.init_scope():
table = lookup_ops.index_table_from_tensor(
vocabulary_list=tuple(self.vocabulary_list),
default_value=self.default_value,
num_oov_buckets=self.num_oov_buckets,
dtype=key_dtype,
name=name)
if state_manager is not None:
state_manager.add_resource(self, name, table)
else:
# Reuse the table from the previous run.
table = state_manager.get_resource(self, name)
return table.lookup(input_tensor) | [
"def",
"_transform_input_tensor",
"(",
"self",
",",
"input_tensor",
",",
"state_manager",
"=",
"None",
")",
":",
"if",
"self",
".",
"dtype",
".",
"is_integer",
"!=",
"input_tensor",
".",
"dtype",
".",
"is_integer",
":",
"raise",
"ValueError",
"(",
"'Column dty... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/feature_column/feature_column_v2.py#L3663-L3695 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/decimal.py | python | Context._raise_error | (self, condition, explanation = None, *args) | Handles an error
If the flag is in _ignored_flags, returns the default response.
Otherwise, it sets the flag, then, if the corresponding
trap_enabler is set, it reraises the exception. Otherwise, it returns
the default value after setting the flag. | Handles an error | [
"Handles",
"an",
"error"
] | def _raise_error(self, condition, explanation = None, *args):
"""Handles an error
If the flag is in _ignored_flags, returns the default response.
Otherwise, it sets the flag, then, if the corresponding
trap_enabler is set, it reraises the exception. Otherwise, it returns
the default value after setting the flag.
"""
error = _condition_map.get(condition, condition)
if error in self._ignored_flags:
# Don't touch the flag
return error().handle(self, *args)
self.flags[error] = 1
if not self.traps[error]:
# The errors define how to handle themselves.
return condition().handle(self, *args)
# Errors should only be risked on copies of the context
# self._ignored_flags = []
raise error(explanation) | [
"def",
"_raise_error",
"(",
"self",
",",
"condition",
",",
"explanation",
"=",
"None",
",",
"*",
"args",
")",
":",
"error",
"=",
"_condition_map",
".",
"get",
"(",
"condition",
",",
"condition",
")",
"if",
"error",
"in",
"self",
".",
"_ignored_flags",
":... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/decimal.py#L3852-L3872 | ||
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py | python | parserCtxt.parsePEReference | (self) | parse PEReference declarations The entity content is
handled directly by pushing it's content as a new input
stream. [69] PEReference ::= '%' Name ';' [ WFC: No
Recursion ] A parsed entity must not contain a recursive
reference to itself, either directly or indirectly. [ WFC:
Entity Declared ] In a document without any DTD, a document
with only an internal DTD subset which contains no
parameter entity references, or a document with
"standalone='yes'", ... ... The declaration of a parameter
entity must precede any reference to it... [ VC: Entity
Declared ] In a document with an external subset or
external parameter entities with "standalone='no'", ...
... The declaration of a parameter entity must precede any
reference to it... [ WFC: In DTD ] Parameter-entity
references may only appear in the DTD. NOTE: misleading but
this is handled. | parse PEReference declarations The entity content is
handled directly by pushing it's content as a new input
stream. [69] PEReference ::= '%' Name ';' [ WFC: No
Recursion ] A parsed entity must not contain a recursive
reference to itself, either directly or indirectly. [ WFC:
Entity Declared ] In a document without any DTD, a document
with only an internal DTD subset which contains no
parameter entity references, or a document with
"standalone='yes'", ... ... The declaration of a parameter
entity must precede any reference to it... [ VC: Entity
Declared ] In a document with an external subset or
external parameter entities with "standalone='no'", ...
... The declaration of a parameter entity must precede any
reference to it... [ WFC: In DTD ] Parameter-entity
references may only appear in the DTD. NOTE: misleading but
this is handled. | [
"parse",
"PEReference",
"declarations",
"The",
"entity",
"content",
"is",
"handled",
"directly",
"by",
"pushing",
"it",
"s",
"content",
"as",
"a",
"new",
"input",
"stream",
".",
"[",
"69",
"]",
"PEReference",
"::",
"=",
"%",
"Name",
";",
"[",
"WFC",
":",... | def parsePEReference(self):
"""parse PEReference declarations The entity content is
handled directly by pushing it's content as a new input
stream. [69] PEReference ::= '%' Name ';' [ WFC: No
Recursion ] A parsed entity must not contain a recursive
reference to itself, either directly or indirectly. [ WFC:
Entity Declared ] In a document without any DTD, a document
with only an internal DTD subset which contains no
parameter entity references, or a document with
"standalone='yes'", ... ... The declaration of a parameter
entity must precede any reference to it... [ VC: Entity
Declared ] In a document with an external subset or
external parameter entities with "standalone='no'", ...
... The declaration of a parameter entity must precede any
reference to it... [ WFC: In DTD ] Parameter-entity
references may only appear in the DTD. NOTE: misleading but
this is handled. """
libxml2mod.xmlParsePEReference(self._o) | [
"def",
"parsePEReference",
"(",
"self",
")",
":",
"libxml2mod",
".",
"xmlParsePEReference",
"(",
"self",
".",
"_o",
")"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L4588-L4605 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/requests/adapters.py | python | HTTPAdapter.proxy_headers | (self, proxy) | return headers | Returns a dictionary of the headers to add to any request sent
through a proxy. This works with urllib3 magic to ensure that they are
correctly sent to the proxy, rather than in a tunnelled request if
CONNECT is being used.
This should not be called from user code, and is only exposed for use
when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param proxy: The url of the proxy being used for this request.
:rtype: dict | Returns a dictionary of the headers to add to any request sent
through a proxy. This works with urllib3 magic to ensure that they are
correctly sent to the proxy, rather than in a tunnelled request if
CONNECT is being used. | [
"Returns",
"a",
"dictionary",
"of",
"the",
"headers",
"to",
"add",
"to",
"any",
"request",
"sent",
"through",
"a",
"proxy",
".",
"This",
"works",
"with",
"urllib3",
"magic",
"to",
"ensure",
"that",
"they",
"are",
"correctly",
"sent",
"to",
"the",
"proxy",
... | def proxy_headers(self, proxy):
"""Returns a dictionary of the headers to add to any request sent
through a proxy. This works with urllib3 magic to ensure that they are
correctly sent to the proxy, rather than in a tunnelled request if
CONNECT is being used.
This should not be called from user code, and is only exposed for use
when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param proxy: The url of the proxy being used for this request.
:rtype: dict
"""
headers = {}
username, password = get_auth_from_url(proxy)
if username:
headers['Proxy-Authorization'] = _basic_auth_str(username,
password)
return headers | [
"def",
"proxy_headers",
"(",
"self",
",",
"proxy",
")",
":",
"headers",
"=",
"{",
"}",
"username",
",",
"password",
"=",
"get_auth_from_url",
"(",
"proxy",
")",
"if",
"username",
":",
"headers",
"[",
"'Proxy-Authorization'",
"]",
"=",
"_basic_auth_str",
"(",... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/requests/adapters.py#L372-L392 | |
gnuradio/gnuradio | 09c3c4fa4bfb1a02caac74cb5334dfe065391e3b | grc/core/utils/backports/chainmap.py | python | ChainMap.__init__ | (self, *maps) | Initialize a ChainMap by setting *maps* to the given mappings.
If no mappings are provided, a single empty dictionary is used. | Initialize a ChainMap by setting *maps* to the given mappings.
If no mappings are provided, a single empty dictionary is used. | [
"Initialize",
"a",
"ChainMap",
"by",
"setting",
"*",
"maps",
"*",
"to",
"the",
"given",
"mappings",
".",
"If",
"no",
"mappings",
"are",
"provided",
"a",
"single",
"empty",
"dictionary",
"is",
"used",
"."
] | def __init__(self, *maps):
"""Initialize a ChainMap by setting *maps* to the given mappings.
If no mappings are provided, a single empty dictionary is used.
"""
self.maps = list(maps) or [{}] | [
"def",
"__init__",
"(",
"self",
",",
"*",
"maps",
")",
":",
"self",
".",
"maps",
"=",
"list",
"(",
"maps",
")",
"or",
"[",
"{",
"}",
"]"
] | https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/grc/core/utils/backports/chainmap.py#L20-L25 | ||
grpc/grpc | 27bc6fe7797e43298dc931b96dc57322d0852a9f | src/python/grpcio/grpc/framework/interfaces/base/utilities.py | python | completion | (terminal_metadata, code, message) | return _Completion(terminal_metadata, code, message) | Creates a base.Completion aggregating the given operation values.
Args:
terminal_metadata: A terminal metadata value for an operaton.
code: A code value for an operation.
message: A message value for an operation.
Returns:
A base.Completion aggregating the given operation values. | Creates a base.Completion aggregating the given operation values. | [
"Creates",
"a",
"base",
".",
"Completion",
"aggregating",
"the",
"given",
"operation",
"values",
"."
] | def completion(terminal_metadata, code, message):
"""Creates a base.Completion aggregating the given operation values.
Args:
terminal_metadata: A terminal metadata value for an operaton.
code: A code value for an operation.
message: A message value for an operation.
Returns:
A base.Completion aggregating the given operation values.
"""
return _Completion(terminal_metadata, code, message) | [
"def",
"completion",
"(",
"terminal_metadata",
",",
"code",
",",
"message",
")",
":",
"return",
"_Completion",
"(",
"terminal_metadata",
",",
"code",
",",
"message",
")"
] | https://github.com/grpc/grpc/blob/27bc6fe7797e43298dc931b96dc57322d0852a9f/src/python/grpcio/grpc/framework/interfaces/base/utilities.py#L45-L56 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/ntpath.py | python | _abspath_fallback | (path) | return normpath(path) | Return the absolute version of a path as a fallback function in case
`nt._getfullpathname` is not available or raises OSError. See bpo-31047 for
more. | Return the absolute version of a path as a fallback function in case
`nt._getfullpathname` is not available or raises OSError. See bpo-31047 for
more. | [
"Return",
"the",
"absolute",
"version",
"of",
"a",
"path",
"as",
"a",
"fallback",
"function",
"in",
"case",
"nt",
".",
"_getfullpathname",
"is",
"not",
"available",
"or",
"raises",
"OSError",
".",
"See",
"bpo",
"-",
"31047",
"for",
"more",
"."
] | def _abspath_fallback(path):
"""Return the absolute version of a path as a fallback function in case
`nt._getfullpathname` is not available or raises OSError. See bpo-31047 for
more.
"""
path = os.fspath(path)
if not isabs(path):
if isinstance(path, bytes):
cwd = os.getcwdb()
else:
cwd = os.getcwd()
path = join(cwd, path)
return normpath(path) | [
"def",
"_abspath_fallback",
"(",
"path",
")",
":",
"path",
"=",
"os",
".",
"fspath",
"(",
"path",
")",
"if",
"not",
"isabs",
"(",
"path",
")",
":",
"if",
"isinstance",
"(",
"path",
",",
"bytes",
")",
":",
"cwd",
"=",
"os",
".",
"getcwdb",
"(",
")... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/ntpath.py#L500-L514 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | third_party/tlslite/tlslite/TLSConnection.py | python | TLSConnection.handshakeClientUnknown | (self, srpCallback=None, certCallback=None,
session=None, settings=None, checker=None,
async=False) | Perform a to-be-determined type of handshake in the role of client.
This function performs an SSL or TLS handshake. If the server
requests client certificate authentication, the
certCallback will be invoked and should return a (certChain,
privateKey) pair. If the callback returns None, the library
will attempt to proceed without client authentication. The
server may or may not allow this.
If the server requests SRP authentication, the srpCallback
will be invoked and should return a (username, password) pair.
If the callback returns None, the local implementation will
signal a user_canceled error alert.
After the handshake completes, the client can inspect the
connection's session attribute to determine what type of
authentication was performed.
Like any handshake function, this can be called on a closed
TLS connection, or on a TLS connection that is already open.
If called on an open connection it performs a re-handshake.
If the function completes without raising an exception, the
TLS connection will be open and available for data transfer.
If an exception is raised, the connection will have been
automatically closed (if it was ever open).
@type srpCallback: callable
@param srpCallback: The callback to be used if the server
requests SRP authentication. If None, the client will not
offer support for SRP ciphersuites.
@type certCallback: callable
@param certCallback: The callback to be used if the server
requests client certificate authentication.
@type session: L{tlslite.Session.Session}
@param session: A TLS session to attempt to resume. If the
resumption does not succeed, a full handshake will be
performed.
@type settings: L{tlslite.HandshakeSettings.HandshakeSettings}
@param settings: Various settings which can be used to control
the ciphersuites, certificate types, and SSL/TLS versions
offered by the client.
@type checker: L{tlslite.Checker.Checker}
@param checker: A Checker instance. This instance will be
invoked to examine the other party's authentication
credentials, if the handshake completes succesfully.
@type async: bool
@param async: If False, this function will block until the
handshake is completed. If True, this function will return a
generator. Successive invocations of the generator will
return 0 if it is waiting to read from the socket, 1 if it is
waiting to write to the socket, or will raise StopIteration if
the handshake operation is completed.
@rtype: None or an iterable
@return: If 'async' is True, a generator object will be
returned.
@raise socket.error: If a socket error occurs.
@raise tlslite.errors.TLSAbruptCloseError: If the socket is closed
without a preceding alert.
@raise tlslite.errors.TLSAlert: If a TLS alert is signalled.
@raise tlslite.errors.TLSAuthenticationError: If the checker
doesn't like the other party's authentication credentials. | Perform a to-be-determined type of handshake in the role of client. | [
"Perform",
"a",
"to",
"-",
"be",
"-",
"determined",
"type",
"of",
"handshake",
"in",
"the",
"role",
"of",
"client",
"."
] | def handshakeClientUnknown(self, srpCallback=None, certCallback=None,
session=None, settings=None, checker=None,
async=False):
"""Perform a to-be-determined type of handshake in the role of client.
This function performs an SSL or TLS handshake. If the server
requests client certificate authentication, the
certCallback will be invoked and should return a (certChain,
privateKey) pair. If the callback returns None, the library
will attempt to proceed without client authentication. The
server may or may not allow this.
If the server requests SRP authentication, the srpCallback
will be invoked and should return a (username, password) pair.
If the callback returns None, the local implementation will
signal a user_canceled error alert.
After the handshake completes, the client can inspect the
connection's session attribute to determine what type of
authentication was performed.
Like any handshake function, this can be called on a closed
TLS connection, or on a TLS connection that is already open.
If called on an open connection it performs a re-handshake.
If the function completes without raising an exception, the
TLS connection will be open and available for data transfer.
If an exception is raised, the connection will have been
automatically closed (if it was ever open).
@type srpCallback: callable
@param srpCallback: The callback to be used if the server
requests SRP authentication. If None, the client will not
offer support for SRP ciphersuites.
@type certCallback: callable
@param certCallback: The callback to be used if the server
requests client certificate authentication.
@type session: L{tlslite.Session.Session}
@param session: A TLS session to attempt to resume. If the
resumption does not succeed, a full handshake will be
performed.
@type settings: L{tlslite.HandshakeSettings.HandshakeSettings}
@param settings: Various settings which can be used to control
the ciphersuites, certificate types, and SSL/TLS versions
offered by the client.
@type checker: L{tlslite.Checker.Checker}
@param checker: A Checker instance. This instance will be
invoked to examine the other party's authentication
credentials, if the handshake completes succesfully.
@type async: bool
@param async: If False, this function will block until the
handshake is completed. If True, this function will return a
generator. Successive invocations of the generator will
return 0 if it is waiting to read from the socket, 1 if it is
waiting to write to the socket, or will raise StopIteration if
the handshake operation is completed.
@rtype: None or an iterable
@return: If 'async' is True, a generator object will be
returned.
@raise socket.error: If a socket error occurs.
@raise tlslite.errors.TLSAbruptCloseError: If the socket is closed
without a preceding alert.
@raise tlslite.errors.TLSAlert: If a TLS alert is signalled.
@raise tlslite.errors.TLSAuthenticationError: If the checker
doesn't like the other party's authentication credentials.
"""
handshaker = self._handshakeClientAsync(unknownParams=(srpCallback,
certCallback), session=session, settings=settings,
checker=checker)
if async:
return handshaker
for result in handshaker:
pass | [
"def",
"handshakeClientUnknown",
"(",
"self",
",",
"srpCallback",
"=",
"None",
",",
"certCallback",
"=",
"None",
",",
"session",
"=",
"None",
",",
"settings",
"=",
"None",
",",
"checker",
"=",
"None",
",",
"async",
"=",
"False",
")",
":",
"handshaker",
"... | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/tlslite/tlslite/TLSConnection.py#L210-L290 | ||
NVIDIA/TensorRT | 42805f078052daad1a98bc5965974fcffaad0960 | samples/python/uff_ssd/model.py | python | parse_commandline_arguments | () | return args | Parses command line arguments and adjusts internal data structures. | Parses command line arguments and adjusts internal data structures. | [
"Parses",
"command",
"line",
"arguments",
"and",
"adjusts",
"internal",
"data",
"structures",
"."
] | def parse_commandline_arguments():
"""Parses command line arguments and adjusts internal data structures."""
# Define script command line arguments
parser = argparse.ArgumentParser(description='Run object detection inference on input image.')
parser.add_argument('-w', '--workspace_dir',
help='sample workspace directory')
parser.add_argument('-d', '--data',
help="Specify the data directory where it is saved in. $TRT_DATA_DIR will be overwritten by this argument.")
args, _ = parser.parse_known_args()
data_dir = os.environ.get('TRT_DATA_DIR', None) if args.data is None else args.data
if data_dir is None:
raise ValueError("Data directory must be specified by either `-d $DATA` or environment variable $TRT_DATA_DIR.")
PATHS.set_data_dir_path(data_dir)
# Set workspace dir path if passed by user
if args.workspace_dir:
PATHS.set_workspace_dir_path(args.workspace_dir)
try:
os.makedirs(PATHS.get_workspace_dir_path())
except:
pass
# Verify Paths after adjustments. This also exits script if verification fails
PATHS.verify_all_paths()
return args | [
"def",
"parse_commandline_arguments",
"(",
")",
":",
"# Define script command line arguments",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Run object detection inference on input image.'",
")",
"parser",
".",
"add_argument",
"(",
"'-w'",
","... | https://github.com/NVIDIA/TensorRT/blob/42805f078052daad1a98bc5965974fcffaad0960/samples/python/uff_ssd/model.py#L26-L55 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_misc.py | python | SystemOptions.__init__ | (self, *args, **kwargs) | __init__(self) -> SystemOptions | __init__(self) -> SystemOptions | [
"__init__",
"(",
"self",
")",
"-",
">",
"SystemOptions"
] | def __init__(self, *args, **kwargs):
"""__init__(self) -> SystemOptions"""
_misc_.SystemOptions_swiginit(self,_misc_.new_SystemOptions(*args, **kwargs)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_misc_",
".",
"SystemOptions_swiginit",
"(",
"self",
",",
"_misc_",
".",
"new_SystemOptions",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L218-L220 | ||
gnuradio/gnuradio | 09c3c4fa4bfb1a02caac74cb5334dfe065391e3b | grc/core/FlowGraph.py | python | FlowGraph.new_block | (self, block_id, **kwargs) | return block | Get a new block of the specified key.
Add the block to the list of elements.
Args:
block_id: the block key
Returns:
the new block or None if not found | Get a new block of the specified key.
Add the block to the list of elements. | [
"Get",
"a",
"new",
"block",
"of",
"the",
"specified",
"key",
".",
"Add",
"the",
"block",
"to",
"the",
"list",
"of",
"elements",
"."
] | def new_block(self, block_id, **kwargs):
"""
Get a new block of the specified key.
Add the block to the list of elements.
Args:
block_id: the block key
Returns:
the new block or None if not found
"""
if block_id == 'options':
return self.options_block
try:
block = self.parent_platform.make_block(self, block_id, **kwargs)
self.blocks.append(block)
except KeyError:
block = None
return block | [
"def",
"new_block",
"(",
"self",
",",
"block_id",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"block_id",
"==",
"'options'",
":",
"return",
"self",
".",
"options_block",
"try",
":",
"block",
"=",
"self",
".",
"parent_platform",
".",
"make_block",
"(",
"self... | https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/grc/core/FlowGraph.py#L314-L332 | |
llvm/llvm-project | ffa6262cb4e2a335d26416fad39a581b4f98c5f4 | lldb/third_party/Python/module/pexpect-4.6/pexpect/spawnbase.py | python | SpawnBase.readline | (self, size=-1) | This reads and returns one entire line. The newline at the end of
line is returned as part of the string, unless the file ends without a
newline. An empty string is returned if EOF is encountered immediately.
This looks for a newline as a CR/LF pair (\\r\\n) even on UNIX because
this is what the pseudotty device returns. So contrary to what you may
expect you will receive newlines as \\r\\n.
If the size argument is 0 then an empty string is returned. In all
other cases the size argument is ignored, which is not standard
behavior for a file-like object. | This reads and returns one entire line. The newline at the end of
line is returned as part of the string, unless the file ends without a
newline. An empty string is returned if EOF is encountered immediately.
This looks for a newline as a CR/LF pair (\\r\\n) even on UNIX because
this is what the pseudotty device returns. So contrary to what you may
expect you will receive newlines as \\r\\n. | [
"This",
"reads",
"and",
"returns",
"one",
"entire",
"line",
".",
"The",
"newline",
"at",
"the",
"end",
"of",
"line",
"is",
"returned",
"as",
"part",
"of",
"the",
"string",
"unless",
"the",
"file",
"ends",
"without",
"a",
"newline",
".",
"An",
"empty",
... | def readline(self, size=-1):
'''This reads and returns one entire line. The newline at the end of
line is returned as part of the string, unless the file ends without a
newline. An empty string is returned if EOF is encountered immediately.
This looks for a newline as a CR/LF pair (\\r\\n) even on UNIX because
this is what the pseudotty device returns. So contrary to what you may
expect you will receive newlines as \\r\\n.
If the size argument is 0 then an empty string is returned. In all
other cases the size argument is ignored, which is not standard
behavior for a file-like object. '''
if size == 0:
return self.string_type()
# delimiter default is EOF
index = self.expect([self.crlf, self.delimiter])
if index == 0:
return self.before + self.crlf
else:
return self.before | [
"def",
"readline",
"(",
"self",
",",
"size",
"=",
"-",
"1",
")",
":",
"if",
"size",
"==",
"0",
":",
"return",
"self",
".",
"string_type",
"(",
")",
"# delimiter default is EOF",
"index",
"=",
"self",
".",
"expect",
"(",
"[",
"self",
".",
"crlf",
",",... | https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/lldb/third_party/Python/module/pexpect-4.6/pexpect/spawnbase.py#L459-L478 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/chunk.py | python | Chunk.seek | (self, pos, whence=0) | Seek to specified position into the chunk.
Default position is 0 (start of chunk).
If the file is not seekable, this will result in an error. | Seek to specified position into the chunk.
Default position is 0 (start of chunk).
If the file is not seekable, this will result in an error. | [
"Seek",
"to",
"specified",
"position",
"into",
"the",
"chunk",
".",
"Default",
"position",
"is",
"0",
"(",
"start",
"of",
"chunk",
")",
".",
"If",
"the",
"file",
"is",
"not",
"seekable",
"this",
"will",
"result",
"in",
"an",
"error",
"."
] | def seek(self, pos, whence=0):
"""Seek to specified position into the chunk.
Default position is 0 (start of chunk).
If the file is not seekable, this will result in an error.
"""
if self.closed:
raise ValueError("I/O operation on closed file")
if not self.seekable:
raise OSError("cannot seek")
if whence == 1:
pos = pos + self.size_read
elif whence == 2:
pos = pos + self.chunksize
if pos < 0 or pos > self.chunksize:
raise RuntimeError
self.file.seek(self.offset + pos, 0)
self.size_read = pos | [
"def",
"seek",
"(",
"self",
",",
"pos",
",",
"whence",
"=",
"0",
")",
":",
"if",
"self",
".",
"closed",
":",
"raise",
"ValueError",
"(",
"\"I/O operation on closed file\"",
")",
"if",
"not",
"self",
".",
"seekable",
":",
"raise",
"OSError",
"(",
"\"canno... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/chunk.py#L98-L115 | ||
cvxpy/cvxpy | 5165b4fb750dfd237de8659383ef24b4b2e33aaf | cvxpy/atoms/atom.py | python | Atom.is_convex | (self) | Is the expression convex? | Is the expression convex? | [
"Is",
"the",
"expression",
"convex?"
] | def is_convex(self) -> bool:
"""Is the expression convex?
"""
# Applies DCP composition rule.
if self.is_constant():
return True
elif self.is_atom_convex():
for idx, arg in enumerate(self.args):
if not (arg.is_affine() or
(arg.is_convex() and self.is_incr(idx)) or
(arg.is_concave() and self.is_decr(idx))):
return False
return True
else:
return False | [
"def",
"is_convex",
"(",
"self",
")",
"->",
"bool",
":",
"# Applies DCP composition rule.",
"if",
"self",
".",
"is_constant",
"(",
")",
":",
"return",
"True",
"elif",
"self",
".",
"is_atom_convex",
"(",
")",
":",
"for",
"idx",
",",
"arg",
"in",
"enumerate"... | https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/atoms/atom.py#L170-L184 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/base64.py | python | main | () | Small main program | Small main program | [
"Small",
"main",
"program"
] | def main():
"""Small main program"""
import sys, getopt
try:
opts, args = getopt.getopt(sys.argv[1:], 'deut')
except getopt.error as msg:
sys.stdout = sys.stderr
print(msg)
print("""usage: %s [-d|-e|-u|-t] [file|-]
-d, -u: decode
-e: encode (default)
-t: encode and decode string 'Aladdin:open sesame'"""%sys.argv[0])
sys.exit(2)
func = encode
for o, a in opts:
if o == '-e': func = encode
if o == '-d': func = decode
if o == '-u': func = decode
if o == '-t': test(); return
if args and args[0] != '-':
with open(args[0], 'rb') as f:
func(f, sys.stdout.buffer)
else:
func(sys.stdin.buffer, sys.stdout.buffer) | [
"def",
"main",
"(",
")",
":",
"import",
"sys",
",",
"getopt",
"try",
":",
"opts",
",",
"args",
"=",
"getopt",
".",
"getopt",
"(",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
",",
"'deut'",
")",
"except",
"getopt",
".",
"error",
"as",
"msg",
":",
"s... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/base64.py#L542-L565 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/odr/odrpack.py | python | Model.__getattr__ | (self, attr) | Dispatch attribute access to the metadata. | Dispatch attribute access to the metadata. | [
"Dispatch",
"attribute",
"access",
"to",
"the",
"metadata",
"."
] | def __getattr__(self, attr):
""" Dispatch attribute access to the metadata.
"""
if attr in self.meta:
return self.meta[attr]
else:
raise AttributeError("'%s' not in metadata" % attr) | [
"def",
"__getattr__",
"(",
"self",
",",
"attr",
")",
":",
"if",
"attr",
"in",
"self",
".",
"meta",
":",
"return",
"self",
".",
"meta",
"[",
"attr",
"]",
"else",
":",
"raise",
"AttributeError",
"(",
"\"'%s' not in metadata\"",
"%",
"attr",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/odr/odrpack.py#L535-L542 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/imaplib.py | python | IMAP4.xatom | (self, name, *args) | return self._simple_command(name, *args) | Allow simple extension commands
notified by server in CAPABILITY response.
Assumes command is legal in current state.
(typ, [data]) = <instance>.xatom(name, arg, ...)
Returns response appropriate to extension command `name'. | Allow simple extension commands
notified by server in CAPABILITY response. | [
"Allow",
"simple",
"extension",
"commands",
"notified",
"by",
"server",
"in",
"CAPABILITY",
"response",
"."
] | def xatom(self, name, *args):
"""Allow simple extension commands
notified by server in CAPABILITY response.
Assumes command is legal in current state.
(typ, [data]) = <instance>.xatom(name, arg, ...)
Returns response appropriate to extension command `name'.
"""
name = name.upper()
#if not name in self.capabilities: # Let the server decide!
# raise self.error('unknown extension command: %s' % name)
if not name in Commands:
Commands[name] = (self.state,)
return self._simple_command(name, *args) | [
"def",
"xatom",
"(",
"self",
",",
"name",
",",
"*",
"args",
")",
":",
"name",
"=",
"name",
".",
"upper",
"(",
")",
"#if not name in self.capabilities: # Let the server decide!",
"# raise self.error('unknown extension command: %s' % name)",
"if",
"not",
"name",
"... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/imaplib.py#L776-L791 | |
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/uuid.py | python | _ipconfig_getnode | () | Get the hardware address on Windows by running ipconfig.exe. | Get the hardware address on Windows by running ipconfig.exe. | [
"Get",
"the",
"hardware",
"address",
"on",
"Windows",
"by",
"running",
"ipconfig",
".",
"exe",
"."
] | def _ipconfig_getnode():
"""Get the hardware address on Windows by running ipconfig.exe."""
import os, re
dirs = ['', r'c:\windows\system32', r'c:\winnt\system32']
try:
import ctypes
buffer = ctypes.create_string_buffer(300)
ctypes.windll.kernel32.GetSystemDirectoryA(buffer, 300)
dirs.insert(0, buffer.value.decode('mbcs'))
except:
pass
for dir in dirs:
try:
pipe = os.popen(os.path.join(dir, 'ipconfig') + ' /all')
except IOError:
continue
for line in pipe:
value = line.split(':')[-1].strip().lower()
if re.match('([0-9a-f][0-9a-f]-){5}[0-9a-f][0-9a-f]', value):
return int(value.replace('-', ''), 16) | [
"def",
"_ipconfig_getnode",
"(",
")",
":",
"import",
"os",
",",
"re",
"dirs",
"=",
"[",
"''",
",",
"r'c:\\windows\\system32'",
",",
"r'c:\\winnt\\system32'",
"]",
"try",
":",
"import",
"ctypes",
"buffer",
"=",
"ctypes",
".",
"create_string_buffer",
"(",
"300",... | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/uuid.py#L340-L359 | ||
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/symbol/symbol.py | python | Symbol.arcsin | (self, *args, **kwargs) | return op.arcsin(self, *args, **kwargs) | Convenience fluent method for :py:func:`arcsin`.
The arguments are the same as for :py:func:`arcsin`, with
this array as data. | Convenience fluent method for :py:func:`arcsin`. | [
"Convenience",
"fluent",
"method",
"for",
":",
"py",
":",
"func",
":",
"arcsin",
"."
] | def arcsin(self, *args, **kwargs):
"""Convenience fluent method for :py:func:`arcsin`.
The arguments are the same as for :py:func:`arcsin`, with
this array as data.
"""
return op.arcsin(self, *args, **kwargs) | [
"def",
"arcsin",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"op",
".",
"arcsin",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/symbol/symbol.py#L2389-L2395 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/code_coverage/croc.py | python | CoveredFile.UpdateCoverage | (self) | Updates the coverage summary based on covered lines. | Updates the coverage summary based on covered lines. | [
"Updates",
"the",
"coverage",
"summary",
"based",
"on",
"covered",
"lines",
"."
] | def UpdateCoverage(self):
"""Updates the coverage summary based on covered lines."""
exe = instr = cov = 0
for l in self.lines.itervalues():
exe += 1
if l is not None:
instr += 1
if l == 1:
cov += 1
# Add stats that always exist
self.stats = CoverageStats(lines_executable=exe,
lines_instrumented=instr,
lines_covered=cov,
files_executable=1)
# Add conditional stats
if cov:
self.stats['files_covered'] = 1
if instr or self.in_lcov:
self.stats['files_instrumented'] = 1 | [
"def",
"UpdateCoverage",
"(",
"self",
")",
":",
"exe",
"=",
"instr",
"=",
"cov",
"=",
"0",
"for",
"l",
"in",
"self",
".",
"lines",
".",
"itervalues",
"(",
")",
":",
"exe",
"+=",
"1",
"if",
"l",
"is",
"not",
"None",
":",
"instr",
"+=",
"1",
"if"... | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/code_coverage/croc.py#L83-L103 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/core/getlimits.py | python | _get_machar | (ftype) | return _discovered_machar(ftype) | Get MachAr instance or MachAr-like instance
Get parameters for floating point type, by first trying signatures of
various known floating point types, then, if none match, attempting to
identify parameters by analysis.
Parameters
----------
ftype : class
Numpy floating point type class (e.g. ``np.float64``)
Returns
-------
ma_like : instance of :class:`MachAr` or :class:`MachArLike`
Object giving floating point parameters for `ftype`.
Warns
-----
UserWarning
If the binary signature of the float type is not in the dictionary of
known float types. | Get MachAr instance or MachAr-like instance | [
"Get",
"MachAr",
"instance",
"or",
"MachAr",
"-",
"like",
"instance"
] | def _get_machar(ftype):
""" Get MachAr instance or MachAr-like instance
Get parameters for floating point type, by first trying signatures of
various known floating point types, then, if none match, attempting to
identify parameters by analysis.
Parameters
----------
ftype : class
Numpy floating point type class (e.g. ``np.float64``)
Returns
-------
ma_like : instance of :class:`MachAr` or :class:`MachArLike`
Object giving floating point parameters for `ftype`.
Warns
-----
UserWarning
If the binary signature of the float type is not in the dictionary of
known float types.
"""
params = _MACHAR_PARAMS.get(ftype)
if params is None:
raise ValueError(repr(ftype))
# Detect known / suspected types
key = ftype('-0.1').newbyteorder('<').tobytes()
ma_like = _KNOWN_TYPES.get(key)
# Could be 80 bit == 10 byte extended precision, where last bytes can be
# random garbage. Try comparing first 10 bytes to pattern.
if ma_like is None and ftype == ntypes.longdouble:
ma_like = _KNOWN_TYPES.get(key[:10])
if ma_like is not None:
return ma_like
# Fall back to parameter discovery
warnings.warn(
'Signature {} for {} does not match any known type: '
'falling back to type probe function'.format(key, ftype),
UserWarning, stacklevel=2)
return _discovered_machar(ftype) | [
"def",
"_get_machar",
"(",
"ftype",
")",
":",
"params",
"=",
"_MACHAR_PARAMS",
".",
"get",
"(",
"ftype",
")",
"if",
"params",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"repr",
"(",
"ftype",
")",
")",
"# Detect known / suspected types",
"key",
"=",
"ft... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/core/getlimits.py#L239-L279 | |
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | Alignment/MuonAlignment/python/svgfig.py | python | XAxis.SVG | (self, trans=None) | return LineAxis.SVG(self, trans) | Apply the transformation "trans" and return an SVG object. | Apply the transformation "trans" and return an SVG object. | [
"Apply",
"the",
"transformation",
"trans",
"and",
"return",
"an",
"SVG",
"object",
"."
] | def SVG(self, trans=None):
"""Apply the transformation "trans" and return an SVG object."""
self.y1 = self.aty
self.y2 = self.aty
return LineAxis.SVG(self, trans) | [
"def",
"SVG",
"(",
"self",
",",
"trans",
"=",
"None",
")",
":",
"self",
".",
"y1",
"=",
"self",
".",
"aty",
"self",
".",
"y2",
"=",
"self",
".",
"aty",
"return",
"LineAxis",
".",
"SVG",
"(",
"self",
",",
"trans",
")"
] | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Alignment/MuonAlignment/python/svgfig.py#L2983-L2987 | |
ablab/spades | 3a754192b88540524ce6fb69eef5ea9273a38465 | assembler/ext/src/python_libs/pyyaml3/__init__.py | python | safe_dump | (data, stream=None, **kwds) | return dump_all([data], stream, Dumper=SafeDumper, **kwds) | Serialize a Python object into a YAML stream.
Produce only basic YAML tags.
If stream is None, return the produced string instead. | Serialize a Python object into a YAML stream.
Produce only basic YAML tags.
If stream is None, return the produced string instead. | [
"Serialize",
"a",
"Python",
"object",
"into",
"a",
"YAML",
"stream",
".",
"Produce",
"only",
"basic",
"YAML",
"tags",
".",
"If",
"stream",
"is",
"None",
"return",
"the",
"produced",
"string",
"instead",
"."
] | def safe_dump(data, stream=None, **kwds):
"""
Serialize a Python object into a YAML stream.
Produce only basic YAML tags.
If stream is None, return the produced string instead.
"""
return dump_all([data], stream, Dumper=SafeDumper, **kwds) | [
"def",
"safe_dump",
"(",
"data",
",",
"stream",
"=",
"None",
",",
"*",
"*",
"kwds",
")",
":",
"return",
"dump_all",
"(",
"[",
"data",
"]",
",",
"stream",
",",
"Dumper",
"=",
"SafeDumper",
",",
"*",
"*",
"kwds",
")"
] | https://github.com/ablab/spades/blob/3a754192b88540524ce6fb69eef5ea9273a38465/assembler/ext/src/python_libs/pyyaml3/__init__.py#L210-L216 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/grid.py | python | GridCellFloatRenderer.GetFormat | (*args, **kwargs) | return _grid.GridCellFloatRenderer_GetFormat(*args, **kwargs) | GetFormat(self) -> int | GetFormat(self) -> int | [
"GetFormat",
"(",
"self",
")",
"-",
">",
"int"
] | def GetFormat(*args, **kwargs):
"""GetFormat(self) -> int"""
return _grid.GridCellFloatRenderer_GetFormat(*args, **kwargs) | [
"def",
"GetFormat",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"GridCellFloatRenderer_GetFormat",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/grid.py#L203-L205 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/richtext.py | python | RichTextCtrl.IsSelectionUnderlined | (*args, **kwargs) | return _richtext.RichTextCtrl_IsSelectionUnderlined(*args, **kwargs) | IsSelectionUnderlined(self) -> bool
Is all of the selection underlined? | IsSelectionUnderlined(self) -> bool | [
"IsSelectionUnderlined",
"(",
"self",
")",
"-",
">",
"bool"
] | def IsSelectionUnderlined(*args, **kwargs):
"""
IsSelectionUnderlined(self) -> bool
Is all of the selection underlined?
"""
return _richtext.RichTextCtrl_IsSelectionUnderlined(*args, **kwargs) | [
"def",
"IsSelectionUnderlined",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextCtrl_IsSelectionUnderlined",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L3935-L3941 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/pickle.py | python | Pickler.__init__ | (self, file, protocol=None) | This takes a file-like object for writing a pickle data stream.
The optional protocol argument tells the pickler to use the
given protocol; supported protocols are 0, 1, 2. The default
protocol is 0, to be backwards compatible. (Protocol 0 is the
only protocol that can be written to a file opened in text
mode and read back successfully. When using a protocol higher
than 0, make sure the file is opened in binary mode, both when
pickling and unpickling.)
Protocol 1 is more efficient than protocol 0; protocol 2 is
more efficient than protocol 1.
Specifying a negative protocol version selects the highest
protocol version supported. The higher the protocol used, the
more recent the version of Python needed to read the pickle
produced.
The file parameter must have a write() method that accepts a single
string argument. It can thus be an open file object, a StringIO
object, or any other custom object that meets this interface. | This takes a file-like object for writing a pickle data stream. | [
"This",
"takes",
"a",
"file",
"-",
"like",
"object",
"for",
"writing",
"a",
"pickle",
"data",
"stream",
"."
] | def __init__(self, file, protocol=None):
"""This takes a file-like object for writing a pickle data stream.
The optional protocol argument tells the pickler to use the
given protocol; supported protocols are 0, 1, 2. The default
protocol is 0, to be backwards compatible. (Protocol 0 is the
only protocol that can be written to a file opened in text
mode and read back successfully. When using a protocol higher
than 0, make sure the file is opened in binary mode, both when
pickling and unpickling.)
Protocol 1 is more efficient than protocol 0; protocol 2 is
more efficient than protocol 1.
Specifying a negative protocol version selects the highest
protocol version supported. The higher the protocol used, the
more recent the version of Python needed to read the pickle
produced.
The file parameter must have a write() method that accepts a single
string argument. It can thus be an open file object, a StringIO
object, or any other custom object that meets this interface.
"""
if protocol is None:
protocol = 0
if protocol < 0:
protocol = HIGHEST_PROTOCOL
elif not 0 <= protocol <= HIGHEST_PROTOCOL:
raise ValueError("pickle protocol must be <= %d" % HIGHEST_PROTOCOL)
self.write = file.write
self.memo = {}
self.proto = int(protocol)
self.bin = protocol >= 1
self.fast = 0 | [
"def",
"__init__",
"(",
"self",
",",
"file",
",",
"protocol",
"=",
"None",
")",
":",
"if",
"protocol",
"is",
"None",
":",
"protocol",
"=",
"0",
"if",
"protocol",
"<",
"0",
":",
"protocol",
"=",
"HIGHEST_PROTOCOL",
"elif",
"not",
"0",
"<=",
"protocol",
... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/pickle.py#L173-L207 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/ops.py | python | prepend_name_scope | (name, import_scope) | Prepends name scope to a name.
Args:
name: A `string` name.
import_scope: Optional `string`. Name scope to add.
Returns:
Name with name scope added, or the original name if import_scope
is None. | Prepends name scope to a name. | [
"Prepends",
"name",
"scope",
"to",
"a",
"name",
"."
] | def prepend_name_scope(name, import_scope):
"""Prepends name scope to a name.
Args:
name: A `string` name.
import_scope: Optional `string`. Name scope to add.
Returns:
Name with name scope added, or the original name if import_scope
is None.
"""
if import_scope:
if import_scope[-1] == "/":
import_scope = import_scope[:-1]
try:
str_to_replace = r"([\^]|loc:@|^)(.*)"
return re.sub(str_to_replace, r"\1" + import_scope + r"/\2",
compat.as_str(name))
except TypeError as e:
# If the name is not of a type we can process, simply return it.
logging.warning(e)
return name
else:
return name | [
"def",
"prepend_name_scope",
"(",
"name",
",",
"import_scope",
")",
":",
"if",
"import_scope",
":",
"if",
"import_scope",
"[",
"-",
"1",
"]",
"==",
"\"/\"",
":",
"import_scope",
"=",
"import_scope",
"[",
":",
"-",
"1",
"]",
"try",
":",
"str_to_replace",
... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/ops.py#L6482-L6506 | ||
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/python/turicreate/data_structures/sarray.py | python | SArray.argmin | (self) | return sf_out["minimum_x1"][0] | Get the index of the minimum numeric value in SArray.
Returns None on an empty SArray. Raises an exception if called on an
SArray with non-numeric type.
Returns
-------
out : int
index of the minimum value of SArray
See Also
--------
argmax
Examples
--------
>>> turicreate.SArray([14, 62, 83, 72, 77, 96, 5, 25, 69, 66]).argmin() | Get the index of the minimum numeric value in SArray. | [
"Get",
"the",
"index",
"of",
"the",
"minimum",
"numeric",
"value",
"in",
"SArray",
"."
] | def argmin(self):
"""
Get the index of the minimum numeric value in SArray.
Returns None on an empty SArray. Raises an exception if called on an
SArray with non-numeric type.
Returns
-------
out : int
index of the minimum value of SArray
See Also
--------
argmax
Examples
--------
>>> turicreate.SArray([14, 62, 83, 72, 77, 96, 5, 25, 69, 66]).argmin()
"""
from .sframe import SFrame as _SFrame
if len(self) == 0:
return None
if not any([isinstance(self[0], i) for i in [int, float, long]]):
raise TypeError("SArray must be of type 'int', 'long', or 'float'.")
sf = _SFrame(self).add_row_number()
sf_out = sf.groupby(
key_column_names=[],
operations={"minimum_x1": _aggregate.ARGMIN("X1", "id")},
)
return sf_out["minimum_x1"][0] | [
"def",
"argmin",
"(",
"self",
")",
":",
"from",
".",
"sframe",
"import",
"SFrame",
"as",
"_SFrame",
"if",
"len",
"(",
"self",
")",
"==",
"0",
":",
"return",
"None",
"if",
"not",
"any",
"(",
"[",
"isinstance",
"(",
"self",
"[",
"0",
"]",
",",
"i",... | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/data_structures/sarray.py#L2223-L2256 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.