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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | Misc.winfo_server | (self) | return self.tk.call('winfo', 'server', self._w) | Return information of the X-Server of the screen of this widget in
the form "XmajorRminor vendor vendorVersion". | Return information of the X-Server of the screen of this widget in
the form "XmajorRminor vendor vendorVersion". | [
"Return",
"information",
"of",
"the",
"X",
"-",
"Server",
"of",
"the",
"screen",
"of",
"this",
"widget",
"in",
"the",
"form",
"XmajorRminor",
"vendor",
"vendorVersion",
"."
] | def winfo_server(self):
"""Return information of the X-Server of the screen of this widget in
the form "XmajorRminor vendor vendorVersion"."""
return self.tk.call('winfo', 'server', self._w) | [
"def",
"winfo_server",
"(",
"self",
")",
":",
"return",
"self",
".",
"tk",
".",
"call",
"(",
"'winfo'",
",",
"'server'",
",",
"self",
".",
"_w",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py#L886-L889 | |
echronos/echronos | c996f1d2c8af6c6536205eb319c1bf1d4d84569c | external_tools/ply_info/example/ansic/cparse.py | python | p_parameter_type_list_opt_1 | (t) | parameter_type_list_opt : empty | parameter_type_list_opt : empty | [
"parameter_type_list_opt",
":",
"empty"
] | def p_parameter_type_list_opt_1(t):
'parameter_type_list_opt : empty'
pass | [
"def",
"p_parameter_type_list_opt_1",
"(",
"t",
")",
":",
"pass"
] | https://github.com/echronos/echronos/blob/c996f1d2c8af6c6536205eb319c1bf1d4d84569c/external_tools/ply_info/example/ansic/cparse.py#L443-L445 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py | python | Misc.winfo_vrootx | (self) | return self.tk.getint(
self.tk.call('winfo', 'vrootx', self._w)) | Return the x offset of the virtual root relative to the root
window of the screen of this widget. | Return the x offset of the virtual root relative to the root
window of the screen of this widget. | [
"Return",
"the",
"x",
"offset",
"of",
"the",
"virtual",
"root",
"relative",
"to",
"the",
"root",
"window",
"of",
"the",
"screen",
"of",
"this",
"widget",
"."
] | def winfo_vrootx(self):
"""Return the x offset of the virtual root relative to the root
window of the screen of this widget."""
return self.tk.getint(
self.tk.call('winfo', 'vrootx', self._w)) | [
"def",
"winfo_vrootx",
"(",
"self",
")",
":",
"return",
"self",
".",
"tk",
".",
"getint",
"(",
"self",
".",
"tk",
".",
"call",
"(",
"'winfo'",
",",
"'vrootx'",
",",
"self",
".",
"_w",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py#L1151-L1155 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/mailbox.py | python | MaildirMessage.get_date | (self) | return self._date | Return delivery date of message, in seconds since the epoch. | Return delivery date of message, in seconds since the epoch. | [
"Return",
"delivery",
"date",
"of",
"message",
"in",
"seconds",
"since",
"the",
"epoch",
"."
] | def get_date(self):
"""Return delivery date of message, in seconds since the epoch."""
return self._date | [
"def",
"get_date",
"(",
"self",
")",
":",
"return",
"self",
".",
"_date"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/mailbox.py#L1569-L1571 | |
nvdla/sw | 79538ba1b52b040a4a4645f630e457fa01839e90 | umd/external/protobuf-2.6/python/google/protobuf/descriptor.py | python | MakeDescriptor | (desc_proto, package='', build_file_if_cpp=True) | return Descriptor(desc_proto.name, desc_name, None, None, fields,
nested_types.values(), enum_types.values(), []) | Make a protobuf Descriptor given a DescriptorProto protobuf.
Handles nested descriptors. Note that this is limited to the scope of defining
a message inside of another message. Composite fields can currently only be
resolved if the message is defined in the same scope as the field.
Args:
desc_proto: The descriptor_pb2.DescriptorProto protobuf message.
package: Optional package name for the new message Descriptor (string).
build_file_if_cpp: Update the C++ descriptor pool if api matches.
Set to False on recursion, so no duplicates are created.
Returns:
A Descriptor for protobuf messages. | Make a protobuf Descriptor given a DescriptorProto protobuf. | [
"Make",
"a",
"protobuf",
"Descriptor",
"given",
"a",
"DescriptorProto",
"protobuf",
"."
] | def MakeDescriptor(desc_proto, package='', build_file_if_cpp=True):
"""Make a protobuf Descriptor given a DescriptorProto protobuf.
Handles nested descriptors. Note that this is limited to the scope of defining
a message inside of another message. Composite fields can currently only be
resolved if the message is defined in the same scope as the field.
Args:
desc_proto: The descriptor_pb2.DescriptorProto protobuf message.
package: Optional package name for the new message Descriptor (string).
build_file_if_cpp: Update the C++ descriptor pool if api matches.
Set to False on recursion, so no duplicates are created.
Returns:
A Descriptor for protobuf messages.
"""
if api_implementation.Type() == 'cpp' and build_file_if_cpp:
# The C++ implementation requires all descriptors to be backed by the same
# definition in the C++ descriptor pool. To do this, we build a
# FileDescriptorProto with the same definition as this descriptor and build
# it into the pool.
from google.protobuf import descriptor_pb2
file_descriptor_proto = descriptor_pb2.FileDescriptorProto()
file_descriptor_proto.message_type.add().MergeFrom(desc_proto)
# Generate a random name for this proto file to prevent conflicts with
# any imported ones. We need to specify a file name so BuildFile accepts
# our FileDescriptorProto, but it is not important what that file name
# is actually set to.
proto_name = str(uuid.uuid4())
if package:
file_descriptor_proto.name = os.path.join(package.replace('.', '/'),
proto_name + '.proto')
file_descriptor_proto.package = package
else:
file_descriptor_proto.name = proto_name + '.proto'
if api_implementation.Version() == 2:
# pylint: disable=protected-access
_message.Message._BuildFile(file_descriptor_proto.SerializeToString())
# pylint: enable=protected-access
else:
cpp_message.BuildFile(file_descriptor_proto.SerializeToString())
full_message_name = [desc_proto.name]
if package: full_message_name.insert(0, package)
# Create Descriptors for enum types
enum_types = {}
for enum_proto in desc_proto.enum_type:
full_name = '.'.join(full_message_name + [enum_proto.name])
enum_desc = EnumDescriptor(
enum_proto.name, full_name, None, [
EnumValueDescriptor(enum_val.name, ii, enum_val.number)
for ii, enum_val in enumerate(enum_proto.value)])
enum_types[full_name] = enum_desc
# Create Descriptors for nested types
nested_types = {}
for nested_proto in desc_proto.nested_type:
full_name = '.'.join(full_message_name + [nested_proto.name])
# Nested types are just those defined inside of the message, not all types
# used by fields in the message, so no loops are possible here.
nested_desc = MakeDescriptor(nested_proto,
package='.'.join(full_message_name),
build_file_if_cpp=False)
nested_types[full_name] = nested_desc
fields = []
for field_proto in desc_proto.field:
full_name = '.'.join(full_message_name + [field_proto.name])
enum_desc = None
nested_desc = None
if field_proto.HasField('type_name'):
type_name = field_proto.type_name
full_type_name = '.'.join(full_message_name +
[type_name[type_name.rfind('.')+1:]])
if full_type_name in nested_types:
nested_desc = nested_types[full_type_name]
elif full_type_name in enum_types:
enum_desc = enum_types[full_type_name]
# Else type_name references a non-local type, which isn't implemented
field = FieldDescriptor(
field_proto.name, full_name, field_proto.number - 1,
field_proto.number, field_proto.type,
FieldDescriptor.ProtoTypeToCppProtoType(field_proto.type),
field_proto.label, None, nested_desc, enum_desc, None, False, None,
has_default_value=False)
fields.append(field)
desc_name = '.'.join(full_message_name)
return Descriptor(desc_proto.name, desc_name, None, None, fields,
nested_types.values(), enum_types.values(), []) | [
"def",
"MakeDescriptor",
"(",
"desc_proto",
",",
"package",
"=",
"''",
",",
"build_file_if_cpp",
"=",
"True",
")",
":",
"if",
"api_implementation",
".",
"Type",
"(",
")",
"==",
"'cpp'",
"and",
"build_file_if_cpp",
":",
"# The C++ implementation requires all descript... | https://github.com/nvdla/sw/blob/79538ba1b52b040a4a4645f630e457fa01839e90/umd/external/protobuf-2.6/python/google/protobuf/descriptor.py#L757-L849 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_misc.py | python | GetPowerType | (*args) | return _misc_.GetPowerType(*args) | GetPowerType() -> int
return the current system power state: online or offline | GetPowerType() -> int | [
"GetPowerType",
"()",
"-",
">",
"int"
] | def GetPowerType(*args):
"""
GetPowerType() -> int
return the current system power state: online or offline
"""
return _misc_.GetPowerType(*args) | [
"def",
"GetPowerType",
"(",
"*",
"args",
")",
":",
"return",
"_misc_",
".",
"GetPowerType",
"(",
"*",
"args",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L6525-L6531 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/speedmeter.py | python | SpeedMeter.SetHandStyle | (self, style=None) | Sets the style for the hand (arrow indicator).
:param `style`: by specifying "Hand", :class:`SpeedMeter` will draw a polygon
that simulates the car speed control indicator. Using "Arrow" will force
:class:`SpeedMeter` to draw a simple arrow. If defaulted to ``None``, "Hand" will
be used. | Sets the style for the hand (arrow indicator). | [
"Sets",
"the",
"style",
"for",
"the",
"hand",
"(",
"arrow",
"indicator",
")",
"."
] | def SetHandStyle(self, style=None):
"""
Sets the style for the hand (arrow indicator).
:param `style`: by specifying "Hand", :class:`SpeedMeter` will draw a polygon
that simulates the car speed control indicator. Using "Arrow" will force
:class:`SpeedMeter` to draw a simple arrow. If defaulted to ``None``, "Hand" will
be used.
"""
if style is None:
style = "Hand"
if style not in ["Hand", "Arrow"]:
raise Exception('\nERROR: Hand Style Parameter Should Be One Of "Hand" Or "Arrow".')
return
self._handstyle = style | [
"def",
"SetHandStyle",
"(",
"self",
",",
"style",
"=",
"None",
")",
":",
"if",
"style",
"is",
"None",
":",
"style",
"=",
"\"Hand\"",
"if",
"style",
"not",
"in",
"[",
"\"Hand\"",
",",
"\"Arrow\"",
"]",
":",
"raise",
"Exception",
"(",
"'\\nERROR: Hand Styl... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/speedmeter.py#L1635-L1652 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/apitools/apitools/gen/message_registry.py | python | MessageRegistry.WriteFile | (self, printer) | Write the messages file to out. | Write the messages file to out. | [
"Write",
"the",
"messages",
"file",
"to",
"out",
"."
] | def WriteFile(self, printer):
"""Write the messages file to out."""
self.Validate()
extended_descriptor.WritePythonFile(
self.__file_descriptor, self.__package, self.__client_info.version,
printer) | [
"def",
"WriteFile",
"(",
"self",
",",
"printer",
")",
":",
"self",
".",
"Validate",
"(",
")",
"extended_descriptor",
".",
"WritePythonFile",
"(",
"self",
".",
"__file_descriptor",
",",
"self",
".",
"__package",
",",
"self",
".",
"__client_info",
".",
"versio... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/apitools/apitools/gen/message_registry.py#L103-L108 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/src/motionplanning.py | python | CSpaceInterface.enableAdaptiveQueries | (self, enabled=True) | return _motionplanning.CSpaceInterface_enableAdaptiveQueries(self, enabled) | enableAdaptiveQueries(CSpaceInterface self, bool enabled=True)
enableAdaptiveQueries(CSpaceInterface self)
Call this to enable adaptive queries. (It has a small overhead.) | enableAdaptiveQueries(CSpaceInterface self, bool enabled=True)
enableAdaptiveQueries(CSpaceInterface self) | [
"enableAdaptiveQueries",
"(",
"CSpaceInterface",
"self",
"bool",
"enabled",
"=",
"True",
")",
"enableAdaptiveQueries",
"(",
"CSpaceInterface",
"self",
")"
] | def enableAdaptiveQueries(self, enabled=True):
"""
enableAdaptiveQueries(CSpaceInterface self, bool enabled=True)
enableAdaptiveQueries(CSpaceInterface self)
Call this to enable adaptive queries. (It has a small overhead.)
"""
return _motionplanning.CSpaceInterface_enableAdaptiveQueries(self, enabled) | [
"def",
"enableAdaptiveQueries",
"(",
"self",
",",
"enabled",
"=",
"True",
")",
":",
"return",
"_motionplanning",
".",
"CSpaceInterface_enableAdaptiveQueries",
"(",
"self",
",",
"enabled",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/src/motionplanning.py#L569-L579 | |
apple/swift | 469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893 | utils/GYBUnicodeDataUtils.py | python | UnicodeTrieGenerator.__init__ | (self) | Create a trie generator with default parameters. | Create a trie generator with default parameters. | [
"Create",
"a",
"trie",
"generator",
"with",
"default",
"parameters",
"."
] | def __init__(self):
"""Create a trie generator with default parameters."""
pass | [
"def",
"__init__",
"(",
"self",
")",
":",
"pass"
] | https://github.com/apple/swift/blob/469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893/utils/GYBUnicodeDataUtils.py#L241-L243 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/pty.py | python | openpty | () | return master_fd, slave_fd | openpty() -> (master_fd, slave_fd)
Open a pty master/slave pair, using os.openpty() if possible. | openpty() -> (master_fd, slave_fd)
Open a pty master/slave pair, using os.openpty() if possible. | [
"openpty",
"()",
"-",
">",
"(",
"master_fd",
"slave_fd",
")",
"Open",
"a",
"pty",
"master",
"/",
"slave",
"pair",
"using",
"os",
".",
"openpty",
"()",
"if",
"possible",
"."
] | def openpty():
"""openpty() -> (master_fd, slave_fd)
Open a pty master/slave pair, using os.openpty() if possible."""
try:
return os.openpty()
except (AttributeError, OSError):
pass
master_fd, slave_name = _open_terminal()
slave_fd = slave_open(slave_name)
return master_fd, slave_fd | [
"def",
"openpty",
"(",
")",
":",
"try",
":",
"return",
"os",
".",
"openpty",
"(",
")",
"except",
"(",
"AttributeError",
",",
"OSError",
")",
":",
"pass",
"master_fd",
",",
"slave_name",
"=",
"_open_terminal",
"(",
")",
"slave_fd",
"=",
"slave_open",
"(",... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/pty.py#L21-L31 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/contrib/distributions/python/ops/shape.py | python | _ShapeUtil.batch_ndims | (self) | return self._batch_ndims | Returns number of dimensions corresponding to non-identical draws. | Returns number of dimensions corresponding to non-identical draws. | [
"Returns",
"number",
"of",
"dimensions",
"corresponding",
"to",
"non",
"-",
"identical",
"draws",
"."
] | def batch_ndims(self):
"""Returns number of dimensions corresponding to non-identical draws."""
return self._batch_ndims | [
"def",
"batch_ndims",
"(",
"self",
")",
":",
"return",
"self",
".",
"_batch_ndims"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/shape.py#L157-L159 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distlib/version.py | python | _suggest_semantic_version | (s) | return result | Try to suggest a semantic form for a version for which
_suggest_normalized_version couldn't come up with anything. | [] | def _suggest_semantic_version(s):
"""
Try to suggest a semantic form for a version for which
_suggest_normalized_version couldn't come up with anything.
"""
result = s.strip().lower()
for pat, repl in _REPLACEMENTS:
result = pat.sub(repl, result)
if not result:
result = '0.0.0'
# Now look for numeric prefix, and separate it out from
# the rest.
#import pdb; pdb.set_trace()
m = _NUMERIC_PREFIX.match(result)
if not m:
prefix = '0.0.0'
suffix = result
else:
prefix = m.groups()[0].split('.')
prefix = [int(i) for i in prefix]
while len(prefix) < 3:
prefix.append(0)
if len(prefix) == 3:
suffix = result[m.end():]
else:
suffix = '.'.join([str(i) for i in prefix[3:]]) + result[m.end():]
prefix = prefix[:3]
prefix = '.'.join([str(i) for i in prefix])
suffix = suffix.strip()
if suffix:
#import pdb; pdb.set_trace()
# massage the suffix.
for pat, repl in _SUFFIX_REPLACEMENTS:
suffix = pat.sub(repl, suffix)
if not suffix:
result = prefix
else:
sep = '-' if 'dev' in suffix else '+'
result = prefix + sep + suffix
if not is_semver(result):
result = None
return result | [
"def",
"_suggest_semantic_version",
"(",
"s",
")",
":",
"result",
"=",
"s",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"for",
"pat",
",",
"repl",
"in",
"_REPLACEMENTS",
":",
"result",
"=",
"pat",
".",
"sub",
"(",
"repl",
",",
"result",
")",
"i... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distlib/version.py#L811-L897 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_misc.py | python | Joystick.HasZ | (*args, **kwargs) | return _misc_.Joystick_HasZ(*args, **kwargs) | HasZ(self) -> bool | HasZ(self) -> bool | [
"HasZ",
"(",
"self",
")",
"-",
">",
"bool"
] | def HasZ(*args, **kwargs):
"""HasZ(self) -> bool"""
return _misc_.Joystick_HasZ(*args, **kwargs) | [
"def",
"HasZ",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"Joystick_HasZ",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L2262-L2264 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/findertools.py | python | movetotrash | (path) | move the object to the trash | move the object to the trash | [
"move",
"the",
"object",
"to",
"the",
"trash"
] | def movetotrash(path):
"""move the object to the trash"""
fss = Carbon.File.FSSpec(path)
trashfolder = Carbon.Folder.FSFindFolder(fss.as_tuple()[0], 'trsh', 0)
move(path, trashfolder) | [
"def",
"movetotrash",
"(",
"path",
")",
":",
"fss",
"=",
"Carbon",
".",
"File",
".",
"FSSpec",
"(",
"path",
")",
"trashfolder",
"=",
"Carbon",
".",
"Folder",
".",
"FSFindFolder",
"(",
"fss",
".",
"as_tuple",
"(",
")",
"[",
"0",
"]",
",",
"'trsh'",
... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/findertools.py#L683-L687 | ||
deepmind/reverb | ef3c8f0be1b720a741d2dee335e15e44668c291a | reverb/server.py | python | Server.__init__ | (self,
tables: Optional[Sequence[Table]] = None,
port: Optional[int] = None,
checkpointer: Optional[checkpointers.CheckpointerBase] = None) | Constructor of Server serving the ReverbService.
Args:
tables: A sequence of tables to host on the server.
port: The port number to serve the gRPC-service on. If `None` (default)
then a port is automatically picked and assigned.
checkpointer: Checkpointer used for storing/loading checkpoints. If None
(default) then `checkpointers.default_checkpointer` is used to
construct the checkpointer.
Raises:
ValueError: If tables is empty.
ValueError: If multiple Table in tables share names. | Constructor of Server serving the ReverbService. | [
"Constructor",
"of",
"Server",
"serving",
"the",
"ReverbService",
"."
] | def __init__(self,
tables: Optional[Sequence[Table]] = None,
port: Optional[int] = None,
checkpointer: Optional[checkpointers.CheckpointerBase] = None):
"""Constructor of Server serving the ReverbService.
Args:
tables: A sequence of tables to host on the server.
port: The port number to serve the gRPC-service on. If `None` (default)
then a port is automatically picked and assigned.
checkpointer: Checkpointer used for storing/loading checkpoints. If None
(default) then `checkpointers.default_checkpointer` is used to
construct the checkpointer.
Raises:
ValueError: If tables is empty.
ValueError: If multiple Table in tables share names.
"""
if not tables:
raise ValueError('At least one table must be provided')
names = collections.Counter(table.name for table in tables)
duplicates = [name for name, count in names.items() if count > 1]
if duplicates:
raise ValueError('Multiple items in tables have the same name: {}'.format(
', '.join(duplicates)))
if port is None:
port = portpicker.pick_unused_port()
if checkpointer is None:
checkpointer = checkpointers.default_checkpointer()
self._server = pybind.Server([table.internal_table for table in tables],
port, checkpointer.internal_checkpointer())
self._port = port | [
"def",
"__init__",
"(",
"self",
",",
"tables",
":",
"Optional",
"[",
"Sequence",
"[",
"Table",
"]",
"]",
"=",
"None",
",",
"port",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"checkpointer",
":",
"Optional",
"[",
"checkpointers",
".",
"Checkpoi... | https://github.com/deepmind/reverb/blob/ef3c8f0be1b720a741d2dee335e15e44668c291a/reverb/server.py#L253-L287 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/stc.py | python | StyledTextCtrl.SetKeysUnicode | (*args, **kwargs) | return _stc.StyledTextCtrl_SetKeysUnicode(*args, **kwargs) | SetKeysUnicode(self, bool keysUnicode)
Always interpret keyboard input as Unicode | SetKeysUnicode(self, bool keysUnicode) | [
"SetKeysUnicode",
"(",
"self",
"bool",
"keysUnicode",
")"
] | def SetKeysUnicode(*args, **kwargs):
"""
SetKeysUnicode(self, bool keysUnicode)
Always interpret keyboard input as Unicode
"""
return _stc.StyledTextCtrl_SetKeysUnicode(*args, **kwargs) | [
"def",
"SetKeysUnicode",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_SetKeysUnicode",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L5759-L5765 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/stc.py | python | StyledTextCtrl.SetAdditionalSelBackground | (*args, **kwargs) | return _stc.StyledTextCtrl_SetAdditionalSelBackground(*args, **kwargs) | SetAdditionalSelBackground(self, Colour back)
Set the background colour of additional selections.
Must have previously called SetSelBack with non-zero first argument for this to have an effect. | SetAdditionalSelBackground(self, Colour back) | [
"SetAdditionalSelBackground",
"(",
"self",
"Colour",
"back",
")"
] | def SetAdditionalSelBackground(*args, **kwargs):
"""
SetAdditionalSelBackground(self, Colour back)
Set the background colour of additional selections.
Must have previously called SetSelBack with non-zero first argument for this to have an effect.
"""
return _stc.StyledTextCtrl_SetAdditionalSelBackground(*args, **kwargs) | [
"def",
"SetAdditionalSelBackground",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_SetAdditionalSelBackground",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L6276-L6283 | |
quantOS-org/DataCore | e2ef9bd2c22ee9e2845675b6435a14fa607f3551 | mdlink/deps/windows/protobuf-2.5.0/python/google/protobuf/internal/encoder.py | python | MessageSizer | (field_number, is_repeated, is_packed) | Returns a sizer for a message field. | Returns a sizer for a message field. | [
"Returns",
"a",
"sizer",
"for",
"a",
"message",
"field",
"."
] | def MessageSizer(field_number, is_repeated, is_packed):
"""Returns a sizer for a message field."""
tag_size = _TagSize(field_number)
local_VarintSize = _VarintSize
assert not is_packed
if is_repeated:
def RepeatedFieldSize(value):
result = tag_size * len(value)
for element in value:
l = element.ByteSize()
result += local_VarintSize(l) + l
return result
return RepeatedFieldSize
else:
def FieldSize(value):
l = value.ByteSize()
return tag_size + local_VarintSize(l) + l
return FieldSize | [
"def",
"MessageSizer",
"(",
"field_number",
",",
"is_repeated",
",",
"is_packed",
")",
":",
"tag_size",
"=",
"_TagSize",
"(",
"field_number",
")",
"local_VarintSize",
"=",
"_VarintSize",
"assert",
"not",
"is_packed",
"if",
"is_repeated",
":",
"def",
"RepeatedField... | https://github.com/quantOS-org/DataCore/blob/e2ef9bd2c22ee9e2845675b6435a14fa607f3551/mdlink/deps/windows/protobuf-2.5.0/python/google/protobuf/internal/encoder.py#L289-L307 | ||
microsoft/checkedc-clang | a173fefde5d7877b7750e7ce96dd08cf18baebf2 | clang/bindings/python/clang/cindex.py | python | TokenKind.__init__ | (self, value, name) | Create a new TokenKind instance from a numeric value and a name. | Create a new TokenKind instance from a numeric value and a name. | [
"Create",
"a",
"new",
"TokenKind",
"instance",
"from",
"a",
"numeric",
"value",
"and",
"a",
"name",
"."
] | def __init__(self, value, name):
"""Create a new TokenKind instance from a numeric value and a name."""
self.value = value
self.name = name | [
"def",
"__init__",
"(",
"self",
",",
"value",
",",
"name",
")",
":",
"self",
".",
"value",
"=",
"value",
"self",
".",
"name",
"=",
"name"
] | https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/clang/bindings/python/clang/cindex.py#L578-L581 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/linalg_grad.py | python | _MatrixTriangularSolveGrad | (op, grad) | return grad_a, grad_b | Gradient for MatrixTriangularSolve. | Gradient for MatrixTriangularSolve. | [
"Gradient",
"for",
"MatrixTriangularSolve",
"."
] | def _MatrixTriangularSolveGrad(op, grad):
"""Gradient for MatrixTriangularSolve."""
a = op.inputs[0]
b = op.inputs[1]
adjoint_a = op.get_attr("adjoint")
lower_a = op.get_attr("lower")
c = op.outputs[0]
grad_b = linalg_ops.matrix_triangular_solve(
a, grad, lower=lower_a, adjoint=not adjoint_a)
if adjoint_a:
grad_a = -math_ops.matmul(c, grad_b, adjoint_b=True) # pylint: disable=invalid-unary-operand-type
else:
grad_a = -math_ops.matmul(grad_b, c, adjoint_b=True) # pylint: disable=invalid-unary-operand-type
if lower_a:
grad_a = array_ops.matrix_band_part(grad_a, -1, 0)
else:
grad_a = array_ops.matrix_band_part(grad_a, 0, -1)
# If the static batch shapes are equal, we don't need to unbroadcast.
if (a.shape.is_fully_defined() and b.shape.is_fully_defined() and
a.shape[:-2] == b.shape[:-2]):
return grad_a, grad_b
a_shape = array_ops.shape(a)
b_shape = array_ops.shape(b)
ra, rb = array_ops.broadcast_gradient_args(a_shape[:-2], b_shape[:-2])
grad_a = array_ops.reshape(math_ops.reduce_sum(grad_a, axis=ra), a_shape)
grad_b = array_ops.reshape(math_ops.reduce_sum(grad_b, axis=rb), b_shape)
return grad_a, grad_b | [
"def",
"_MatrixTriangularSolveGrad",
"(",
"op",
",",
"grad",
")",
":",
"a",
"=",
"op",
".",
"inputs",
"[",
"0",
"]",
"b",
"=",
"op",
".",
"inputs",
"[",
"1",
"]",
"adjoint_a",
"=",
"op",
".",
"get_attr",
"(",
"\"adjoint\"",
")",
"lower_a",
"=",
"op... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/linalg_grad.py#L680-L706 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py3/setuptools/msvc.py | python | EnvironmentInfo.SdkSetup | (self) | return [join(self.si.WindowsSdkDir, 'Setup')] | Microsoft Windows SDK Setup.
Return
------
list of str
paths | Microsoft Windows SDK Setup. | [
"Microsoft",
"Windows",
"SDK",
"Setup",
"."
] | def SdkSetup(self):
"""
Microsoft Windows SDK Setup.
Return
------
list of str
paths
"""
if self.vs_ver > 9.0:
return []
return [join(self.si.WindowsSdkDir, 'Setup')] | [
"def",
"SdkSetup",
"(",
"self",
")",
":",
"if",
"self",
".",
"vs_ver",
">",
"9.0",
":",
"return",
"[",
"]",
"return",
"[",
"join",
"(",
"self",
".",
"si",
".",
"WindowsSdkDir",
",",
"'Setup'",
")",
"]"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/msvc.py#L1498-L1510 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/distutils/ccompiler.py | python | CCompiler.define_macro | (self, name, value=None) | Define a preprocessor macro for all compilations driven by this
compiler object. The optional parameter 'value' should be a
string; if it is not supplied, then the macro will be defined
without an explicit value and the exact outcome depends on the
compiler used (XXX true? does ANSI say anything about this?) | Define a preprocessor macro for all compilations driven by this
compiler object. The optional parameter 'value' should be a
string; if it is not supplied, then the macro will be defined
without an explicit value and the exact outcome depends on the
compiler used (XXX true? does ANSI say anything about this?) | [
"Define",
"a",
"preprocessor",
"macro",
"for",
"all",
"compilations",
"driven",
"by",
"this",
"compiler",
"object",
".",
"The",
"optional",
"parameter",
"value",
"should",
"be",
"a",
"string",
";",
"if",
"it",
"is",
"not",
"supplied",
"then",
"the",
"macro",... | def define_macro(self, name, value=None):
"""Define a preprocessor macro for all compilations driven by this
compiler object. The optional parameter 'value' should be a
string; if it is not supplied, then the macro will be defined
without an explicit value and the exact outcome depends on the
compiler used (XXX true? does ANSI say anything about this?)
"""
# Delete from the list of macro definitions/undefinitions if
# already there (so that this one will take precedence).
i = self._find_macro (name)
if i is not None:
del self.macros[i]
defn = (name, value)
self.macros.append (defn) | [
"def",
"define_macro",
"(",
"self",
",",
"name",
",",
"value",
"=",
"None",
")",
":",
"# Delete from the list of macro definitions/undefinitions if",
"# already there (so that this one will take precedence).",
"i",
"=",
"self",
".",
"_find_macro",
"(",
"name",
")",
"if",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/distutils/ccompiler.py#L201-L215 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/third_party/pyserial/serial/serialutil.py | python | SerialBase.getSettingsDict | (self) | return dict([(key, getattr(self, '_'+key)) for key in self._SETTINGS]) | Get current port settings as a dictionary. For use with
applySettingsDict | Get current port settings as a dictionary. For use with
applySettingsDict | [
"Get",
"current",
"port",
"settings",
"as",
"a",
"dictionary",
".",
"For",
"use",
"with",
"applySettingsDict"
] | def getSettingsDict(self):
"""Get current port settings as a dictionary. For use with
applySettingsDict"""
return dict([(key, getattr(self, '_'+key)) for key in self._SETTINGS]) | [
"def",
"getSettingsDict",
"(",
"self",
")",
":",
"return",
"dict",
"(",
"[",
"(",
"key",
",",
"getattr",
"(",
"self",
",",
"'_'",
"+",
"key",
")",
")",
"for",
"key",
"in",
"self",
".",
"_SETTINGS",
"]",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/pyserial/serial/serialutil.py#L491-L494 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/model_selection/_search.py | python | ParameterGrid.__len__ | (self) | return sum(product(len(v) for v in p.values()) if p else 1
for p in self.param_grid) | Number of points on the grid. | Number of points on the grid. | [
"Number",
"of",
"points",
"on",
"the",
"grid",
"."
] | def __len__(self):
"""Number of points on the grid."""
# Product function that can handle iterables (np.product can't).
product = partial(reduce, operator.mul)
return sum(product(len(v) for v in p.values()) if p else 1
for p in self.param_grid) | [
"def",
"__len__",
"(",
"self",
")",
":",
"# Product function that can handle iterables (np.product can't).",
"product",
"=",
"partial",
"(",
"reduce",
",",
"operator",
".",
"mul",
")",
"return",
"sum",
"(",
"product",
"(",
"len",
"(",
"v",
")",
"for",
"v",
"in... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/model_selection/_search.py#L133-L138 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/debug/cli/analyzer_cli.py | python | DebugAnalyzer._tensor_list_column_heads | (self, parsed, max_timestamp_width,
max_dump_size_width, max_op_type_width) | return debugger_cli_common.RichTextLines([row], font_attr_segs=attr_segs) | Generate a line containing the column heads of the tensor list.
Args:
parsed: Parsed arguments (by argparse) of the list_tensors command.
max_timestamp_width: (int) maximum width of the timestamp column.
max_dump_size_width: (int) maximum width of the dump size column.
max_op_type_width: (int) maximum width of the op type column.
Returns:
A RichTextLines object. | Generate a line containing the column heads of the tensor list. | [
"Generate",
"a",
"line",
"containing",
"the",
"column",
"heads",
"of",
"the",
"tensor",
"list",
"."
] | def _tensor_list_column_heads(self, parsed, max_timestamp_width,
max_dump_size_width, max_op_type_width):
"""Generate a line containing the column heads of the tensor list.
Args:
parsed: Parsed arguments (by argparse) of the list_tensors command.
max_timestamp_width: (int) maximum width of the timestamp column.
max_dump_size_width: (int) maximum width of the dump size column.
max_op_type_width: (int) maximum width of the op type column.
Returns:
A RichTextLines object.
"""
base_command = "list_tensors"
if parsed.tensor_filter:
base_command += " -f %s" % parsed.tensor_filter
if parsed.op_type_filter:
base_command += " -t %s" % parsed.op_type_filter
if parsed.node_name_filter:
base_command += " -n %s" % parsed.node_name_filter
attr_segs = {0: []}
row = self._TIMESTAMP_COLUMN_HEAD
command = "%s -s %s" % (base_command, SORT_TENSORS_BY_TIMESTAMP)
if parsed.sort_by == SORT_TENSORS_BY_TIMESTAMP and not parsed.reverse:
command += " -r"
attr_segs[0].append(
(0, len(row), [debugger_cli_common.MenuItem(None, command), "bold"]))
row += " " * (max_timestamp_width - len(row))
prev_len = len(row)
row += self._DUMP_SIZE_COLUMN_HEAD
command = "%s -s %s" % (base_command, SORT_TENSORS_BY_DUMP_SIZE)
if parsed.sort_by == SORT_TENSORS_BY_DUMP_SIZE and not parsed.reverse:
command += " -r"
attr_segs[0].append((prev_len, len(row),
[debugger_cli_common.MenuItem(None, command), "bold"]))
row += " " * (max_dump_size_width + max_timestamp_width - len(row))
prev_len = len(row)
row += self._OP_TYPE_COLUMN_HEAD
command = "%s -s %s" % (base_command, SORT_TENSORS_BY_OP_TYPE)
if parsed.sort_by == SORT_TENSORS_BY_OP_TYPE and not parsed.reverse:
command += " -r"
attr_segs[0].append((prev_len, len(row),
[debugger_cli_common.MenuItem(None, command), "bold"]))
row += " " * (
max_op_type_width + max_dump_size_width + max_timestamp_width - len(row)
)
prev_len = len(row)
row += self._TENSOR_NAME_COLUMN_HEAD
command = "%s -s %s" % (base_command, SORT_TENSORS_BY_TENSOR_NAME)
if parsed.sort_by == SORT_TENSORS_BY_TENSOR_NAME and not parsed.reverse:
command += " -r"
attr_segs[0].append((prev_len, len(row),
[debugger_cli_common.MenuItem("", command), "bold"]))
row += " " * (
max_op_type_width + max_dump_size_width + max_timestamp_width - len(row)
)
return debugger_cli_common.RichTextLines([row], font_attr_segs=attr_segs) | [
"def",
"_tensor_list_column_heads",
"(",
"self",
",",
"parsed",
",",
"max_timestamp_width",
",",
"max_dump_size_width",
",",
"max_op_type_width",
")",
":",
"base_command",
"=",
"\"list_tensors\"",
"if",
"parsed",
".",
"tensor_filter",
":",
"base_command",
"+=",
"\" -f... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/debug/cli/analyzer_cli.py#L671-L733 | |
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/resmokelib/powercycle/setup/__init__.py | python | SetUpEC2Instance.execute | (self) | :return: None. | :return: None. | [
":",
"return",
":",
"None",
"."
] | def execute(self) -> None: # pylint: disable=too-many-instance-attributes, too-many-locals, too-many-statements
""":return: None."""
default_retry_count = 2
retry_count = int(self.expansions.get("set_up_retry_count", default_retry_count))
# First operation -
# Create remote_dir.
group_cmd = f"id -Gn {self.user}"
_, group = self._call(group_cmd)
group = group.split(" ")[0]
user_group = f"{self.user}:{group}"
remote_dir = powercycle_constants.REMOTE_DIR
db_path = powercycle_constants.DB_PATH
set_permission_stmt = "chmod -R 777"
if self.is_windows():
set_permission_stmt = "setfacl -s user::rwx,group::rwx,other::rwx"
cmds = f"{self.sudo} mkdir -p {remote_dir}; {self.sudo} chown -R {user_group} {remote_dir}; {set_permission_stmt} {remote_dir}; ls -ld {remote_dir}"
cmds = f"{cmds}; {self.sudo} mkdir -p {db_path}; {self.sudo} chown -R {user_group} {db_path}; {set_permission_stmt} {db_path}; ls -ld {db_path}"
self.remote_op.operation(SSHOperation.SHELL, cmds, retry=True, retry_count=retry_count)
# Second operation -
# Copy buildscripts and mongoDB executables to the remote host.
files = ["etc", "buildscripts", "dist-test/bin"]
shared_libs = "dist-test/lib"
if os.path.isdir(shared_libs):
files.append(shared_libs)
self.remote_op.operation(SSHOperation.COPY_TO, files, remote_dir, retry=True,
retry_count=retry_count)
# Third operation -
# Set up virtualenv on remote.
venv = powercycle_constants.VIRTUALENV_DIR
python = "/opt/mongodbtoolchain/v3/bin/python3" if "python" not in self.expansions else self.expansions[
"python"]
cmds = f"python_loc=$(which {python})"
cmds = f"{cmds}; remote_dir={remote_dir}"
cmds = f"{cmds}; if [ \"Windows_NT\" = \"$OS\" ]; then python_loc=$(cygpath -w $python_loc); remote_dir=$(cygpath -w $remote_dir); fi"
cmds = f"{cmds}; virtualenv --python $python_loc --system-site-packages {venv}"
cmds = f"{cmds}; activate=$(find {venv} -name 'activate')"
cmds = f"{cmds}; . $activate"
cmds = f"{cmds}; pip3 install -r $remote_dir/etc/pip/powercycle-requirements.txt"
self.remote_op.operation(SSHOperation.SHELL, cmds, retry=True, retry_count=retry_count)
# Operation below that enables core dumps is commented out since it causes failures on Ubuntu 18.04.
# It might be a race condition, so `nohup reboot` command is likely a culprit here.
# Fourth operation -
# Enable core dumps on non-Windows remote hosts.
# The core pattern must specify a director, since mongod --fork will chdir("/")
# and cannot generate a core dump there (see SERVER-21635).
# We need to reboot the host for the core limits to take effect.
# if not self.is_windows():
# core_pattern = f"{remote_dir}/dump_%e.%p.core"
# sysctl_conf = "/etc/sysctl.conf"
# cmds = "ulimit -a"
# cmds = f"{cmds}; echo \"{self.user} - core unlimited\" | {self.sudo} tee -a /etc/security/limits.conf"
# cmds = f"{cmds}; if [ -f {sysctl_conf} ]"
# cmds = f"{cmds}; then grep ^kernel.core_pattern {sysctl_conf}"
# cmds = f"{cmds}; if [ $? -eq 0 ]"
# cmds = f"{cmds}; then {self.sudo} sed -i \"s,kernel.core_pattern=.*,kernel.core_pattern={core_pattern},\" {sysctl_conf}"
# cmds = f"{cmds}; else echo \"kernel.core_pattern={core_pattern}\" | {self.sudo} tee -a {sysctl_conf}"
# cmds = f"{cmds}; fi"
# cmds = f"{cmds}; else echo Cannot change the core pattern and no core dumps will be generated."
# cmds = f"{cmds}; fi"
# # The following line for restarting the machine is based on
# # https://unix.stackexchange.com/a/349558 in order to ensure the ssh client gets a
# # response from the remote machine before it restarts.
# cmds = f"{cmds}; nohup {self.sudo} reboot &>/dev/null & exit"
# self.remote_op.operation(SSHOperation.SHELL, cmds, retry=True, retry_count=retry_count)
# Fifth operation -
# Print the ulimit & kernel.core_pattern
# if not self.is_windows():
# # Always exit successfully, as this is just informational.
# cmds = "uptime"
# cmds = f"{cmds}; ulimit -a"
# cmds = f"{cmds}; if [ -f /sbin/sysctl ]"
# cmds = f"{cmds}; then /sbin/sysctl kernel.core_pattern"
# cmds = f"{cmds}; fi"
#
# self.remote_op.operation(SSHOperation.SHELL, cmds, retry=True, retry_count=retry_count)
# Sixth operation -
# Set up curator to collect system & process stats on remote.
variant = "windows-64" if self.is_windows() else "linux-32"
curator_hash = "b0c3c0fc68bce26d9572796d6bed3af4a298e30e"
curator_url = f"https://s3.amazonaws.com/boxes.10gen.com/build/curator/curator-dist-{variant}-{curator_hash}.tar.gz"
cmds = f"curl -s {curator_url} | tar -xzv"
monitor_system_file = powercycle_constants.MONITOR_SYSTEM_FILE
monitor_proc_file = powercycle_constants.MONITOR_PROC_FILE
if self.is_windows():
# Since curator runs as SYSTEM user, ensure the output files can be accessed.
cmds = f"{cmds}; touch {monitor_system_file}; chmod 777 {monitor_system_file}"
cmds = f"{cmds}; cygrunsrv --install curator_sys --path curator --chdir $HOME --args 'stat system --file {monitor_system_file}'"
cmds = f"{cmds}; touch {monitor_proc_file}; chmod 777 {monitor_proc_file}"
cmds = f"{cmds}; cygrunsrv --install curator_proc --path curator --chdir $HOME --args 'stat process-all --file {monitor_proc_file}'"
cmds = f"{cmds}; cygrunsrv --start curator_sys"
cmds = f"{cmds}; cygrunsrv --start curator_proc"
else:
cmds = f"{cmds}; touch {monitor_system_file} {monitor_proc_file}"
cmds = f"{cmds}; cmd=\"@reboot cd $HOME && {self.sudo} ./curator stat system >> {monitor_system_file}\""
cmds = f"{cmds}; (crontab -l ; echo \"$cmd\") | crontab -"
cmds = f"{cmds}; cmd=\"@reboot cd $HOME && $sudo ./curator stat process-all >> {monitor_proc_file}\""
cmds = f"{cmds}; (crontab -l ; echo \"$cmd\") | crontab -"
cmds = f"{cmds}; crontab -l"
cmds = f"{cmds}; {{ {self.sudo} $HOME/curator stat system --file {monitor_system_file} > /dev/null 2>&1 & {self.sudo} $HOME/curator stat process-all --file {monitor_proc_file} > /dev/null 2>&1 & }} & disown"
self.remote_op.operation(SSHOperation.SHELL, cmds, retry=True, retry_count=retry_count)
# Seventh operation -
# Install NotMyFault, used to crash Windows.
if self.is_windows():
windows_crash_zip = powercycle_constants.WINDOWS_CRASH_ZIP
windows_crash_dl = powercycle_constants.WINDOWS_CRASH_DL
windows_crash_dir = powercycle_constants.WINDOWS_CRASH_DIR
cmds = f"curl -s -o {windows_crash_zip} {windows_crash_dl}"
cmds = f"{cmds}; unzip -q {windows_crash_zip} -d {windows_crash_dir}"
cmds = f"{cmds}; chmod +x {windows_crash_dir}/*.exe"
self.remote_op.operation(SSHOperation.SHELL, cmds, retry=True, retry_count=retry_count) | [
"def",
"execute",
"(",
"self",
")",
"->",
"None",
":",
"# pylint: disable=too-many-instance-attributes, too-many-locals, too-many-statements",
"default_retry_count",
"=",
"2",
"retry_count",
"=",
"int",
"(",
"self",
".",
"expansions",
".",
"get",
"(",
"\"set_up_retry_coun... | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/resmokelib/powercycle/setup/__init__.py#L15-L142 | ||
kushview/Element | 1cc16380caa2ab79461246ba758b9de1f46db2a5 | waflib/Utils.py | python | get_process | () | Returns a process object that can execute commands as sub-processes
:rtype: subprocess.Popen | Returns a process object that can execute commands as sub-processes | [
"Returns",
"a",
"process",
"object",
"that",
"can",
"execute",
"commands",
"as",
"sub",
"-",
"processes"
] | def get_process():
"""
Returns a process object that can execute commands as sub-processes
:rtype: subprocess.Popen
"""
try:
return process_pool.pop()
except IndexError:
filepath = os.path.dirname(os.path.abspath(__file__)) + os.sep + 'processor.py'
cmd = [sys.executable, '-c', readf(filepath)]
return subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, bufsize=0, close_fds=not is_win32) | [
"def",
"get_process",
"(",
")",
":",
"try",
":",
"return",
"process_pool",
".",
"pop",
"(",
")",
"except",
"IndexError",
":",
"filepath",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
")",
"+",
... | https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/Utils.py#L880-L891 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/ttk.py | python | Notebook.select | (self, tab_id=None) | return self.tk.call(self._w, "select", tab_id) | Selects the specified tab.
The associated child window will be displayed, and the
previously-selected window (if different) is unmapped. If tab_id
is omitted, returns the widget name of the currently selected
pane. | Selects the specified tab. | [
"Selects",
"the",
"specified",
"tab",
"."
] | def select(self, tab_id=None):
"""Selects the specified tab.
The associated child window will be displayed, and the
previously-selected window (if different) is unmapped. If tab_id
is omitted, returns the widget name of the currently selected
pane."""
return self.tk.call(self._w, "select", tab_id) | [
"def",
"select",
"(",
"self",
",",
"tab_id",
"=",
"None",
")",
":",
"return",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_w",
",",
"\"select\"",
",",
"tab_id",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/ttk.py#L885-L892 | |
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBModule.GetAddressByteSize | (self) | return _lldb.SBModule_GetAddressByteSize(self) | GetAddressByteSize(SBModule self) -> uint32_t | GetAddressByteSize(SBModule self) -> uint32_t | [
"GetAddressByteSize",
"(",
"SBModule",
"self",
")",
"-",
">",
"uint32_t"
] | def GetAddressByteSize(self):
"""GetAddressByteSize(SBModule self) -> uint32_t"""
return _lldb.SBModule_GetAddressByteSize(self) | [
"def",
"GetAddressByteSize",
"(",
"self",
")",
":",
"return",
"_lldb",
".",
"SBModule_GetAddressByteSize",
"(",
"self",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L7453-L7455 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | tools/site_compare/command_line.py | python | Command.GetHelpString | (self, width=80) | return "\n".join([arg.GetHelpString(width) for arg in sorted_args]) | Returns a list of help strings for all this command's arguments. | Returns a list of help strings for all this command's arguments. | [
"Returns",
"a",
"list",
"of",
"help",
"strings",
"for",
"all",
"this",
"command",
"s",
"arguments",
"."
] | def GetHelpString(self, width=80):
"""Returns a list of help strings for all this command's arguments."""
sorted_args = self.args[:]
sorted_args.sort(self.SortArgs())
return "\n".join([arg.GetHelpString(width) for arg in sorted_args]) | [
"def",
"GetHelpString",
"(",
"self",
",",
"width",
"=",
"80",
")",
":",
"sorted_args",
"=",
"self",
".",
"args",
"[",
":",
"]",
"sorted_args",
".",
"sort",
"(",
"self",
".",
"SortArgs",
"(",
")",
")",
"return",
"\"\\n\"",
".",
"join",
"(",
"[",
"ar... | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/tools/site_compare/command_line.py#L486-L491 | |
trailofbits/llvm-sanitizer-tutorial | d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99 | llvm/utils/benchmark/mingw.py | python | unpack | (archive, location, log = EmptyLogger()) | Unpacks a mingw-builds archive | Unpacks a mingw-builds archive | [
"Unpacks",
"a",
"mingw",
"-",
"builds",
"archive"
] | def unpack(archive, location, log = EmptyLogger()):
'''
Unpacks a mingw-builds archive
'''
sevenzip = find_7zip(log)
log.info('unpacking %s', os.path.basename(archive))
cmd = [sevenzip, 'x', archive, '-o' + location, '-y']
log.debug(' - %r', cmd)
with open(os.devnull, 'w') as devnull:
subprocess.check_call(cmd, stdout = devnull) | [
"def",
"unpack",
"(",
"archive",
",",
"location",
",",
"log",
"=",
"EmptyLogger",
"(",
")",
")",
":",
"sevenzip",
"=",
"find_7zip",
"(",
"log",
")",
"log",
".",
"info",
"(",
"'unpacking %s'",
",",
"os",
".",
"path",
".",
"basename",
"(",
"archive",
"... | https://github.com/trailofbits/llvm-sanitizer-tutorial/blob/d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99/llvm/utils/benchmark/mingw.py#L114-L123 | ||
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/wpt/wpt/tools/wptserve/wptserve/response.py | python | Response.write_status_headers | (self) | Write out the status line and headers for the response | Write out the status line and headers for the response | [
"Write",
"out",
"the",
"status",
"line",
"and",
"headers",
"for",
"the",
"response"
] | def write_status_headers(self):
"""Write out the status line and headers for the response"""
self.writer.write_status(*self.status)
for item in self.headers:
self.writer.write_header(*item)
self.writer.end_headers() | [
"def",
"write_status_headers",
"(",
"self",
")",
":",
"self",
".",
"writer",
".",
"write_status",
"(",
"*",
"self",
".",
"status",
")",
"for",
"item",
"in",
"self",
".",
"headers",
":",
"self",
".",
"writer",
".",
"write_header",
"(",
"*",
"item",
")",... | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/wpt/wpt/tools/wptserve/wptserve/response.py#L187-L192 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/joblib/joblib/_store_backends.py | python | StoreBackendMixin._concurrency_safe_write | (self, to_write, filename, write_func) | Writes an object into a file in a concurrency-safe way. | Writes an object into a file in a concurrency-safe way. | [
"Writes",
"an",
"object",
"into",
"a",
"file",
"in",
"a",
"concurrency",
"-",
"safe",
"way",
"."
] | def _concurrency_safe_write(self, to_write, filename, write_func):
"""Writes an object into a file in a concurrency-safe way."""
temporary_filename = concurrency_safe_write(to_write,
filename, write_func)
self._move_item(temporary_filename, filename) | [
"def",
"_concurrency_safe_write",
"(",
"self",
",",
"to_write",
",",
"filename",
",",
"write_func",
")",
":",
"temporary_filename",
"=",
"concurrency_safe_write",
"(",
"to_write",
",",
"filename",
",",
"write_func",
")",
"self",
".",
"_move_item",
"(",
"temporary_... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/joblib/joblib/_store_backends.py#L323-L327 | ||
msracver/Deep-Image-Analogy | 632b9287b42552e32dad64922967c8c9ec7fc4d3 | scripts/cpp_lint.py | python | CheckIncludeLine | (filename, clean_lines, linenum, include_state, error) | Check rules that are applicable to #include lines.
Strings on #include lines are NOT removed from elided line, to make
certain tasks easier. However, to prevent false positives, checks
applicable to #include lines in CheckLanguage must be put here.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
include_state: An _IncludeState instance in which the headers are inserted.
error: The function to call with any errors found. | Check rules that are applicable to #include lines. | [
"Check",
"rules",
"that",
"are",
"applicable",
"to",
"#include",
"lines",
"."
] | def CheckIncludeLine(filename, clean_lines, linenum, include_state, error):
"""Check rules that are applicable to #include lines.
Strings on #include lines are NOT removed from elided line, to make
certain tasks easier. However, to prevent false positives, checks
applicable to #include lines in CheckLanguage must be put here.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
include_state: An _IncludeState instance in which the headers are inserted.
error: The function to call with any errors found.
"""
fileinfo = FileInfo(filename)
line = clean_lines.lines[linenum]
# "include" should use the new style "foo/bar.h" instead of just "bar.h"
if _RE_PATTERN_INCLUDE_NEW_STYLE.search(line):
error(filename, linenum, 'build/include_dir', 4,
'Include the directory when naming .h files')
# we shouldn't include a file more than once. actually, there are a
# handful of instances where doing so is okay, but in general it's
# not.
match = _RE_PATTERN_INCLUDE.search(line)
if match:
include = match.group(2)
is_system = (match.group(1) == '<')
if include in include_state:
error(filename, linenum, 'build/include', 4,
'"%s" already included at %s:%s' %
(include, filename, include_state[include]))
else:
include_state[include] = linenum
# We want to ensure that headers appear in the right order:
# 1) for foo.cc, foo.h (preferred location)
# 2) c system files
# 3) cpp system files
# 4) for foo.cc, foo.h (deprecated location)
# 5) other google headers
#
# We classify each include statement as one of those 5 types
# using a number of techniques. The include_state object keeps
# track of the highest type seen, and complains if we see a
# lower type after that.
error_message = include_state.CheckNextIncludeOrder(
_ClassifyInclude(fileinfo, include, is_system))
if error_message:
error(filename, linenum, 'build/include_order', 4,
'%s. Should be: %s.h, c system, c++ system, other.' %
(error_message, fileinfo.BaseName()))
canonical_include = include_state.CanonicalizeAlphabeticalOrder(include)
if not include_state.IsInAlphabeticalOrder(
clean_lines, linenum, canonical_include):
error(filename, linenum, 'build/include_alpha', 4,
'Include "%s" not in alphabetical order' % include)
include_state.SetLastHeader(canonical_include)
# Look for any of the stream classes that are part of standard C++.
match = _RE_PATTERN_INCLUDE.match(line)
if match:
include = match.group(2)
if Match(r'(f|ind|io|i|o|parse|pf|stdio|str|)?stream$', include):
# Many unit tests use cout, so we exempt them.
if not _IsTestFilename(filename):
error(filename, linenum, 'readability/streams', 3,
'Streams are highly discouraged.') | [
"def",
"CheckIncludeLine",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"include_state",
",",
"error",
")",
":",
"fileinfo",
"=",
"FileInfo",
"(",
"filename",
")",
"line",
"=",
"clean_lines",
".",
"lines",
"[",
"linenum",
"]",
"# \"include\" shoul... | https://github.com/msracver/Deep-Image-Analogy/blob/632b9287b42552e32dad64922967c8c9ec7fc4d3/scripts/cpp_lint.py#L3680-L3749 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/richtext.py | python | TextAttrBorders.CollectCommonAttributes | (*args, **kwargs) | return _richtext.TextAttrBorders_CollectCommonAttributes(*args, **kwargs) | CollectCommonAttributes(self, TextAttrBorders attr, TextAttrBorders clashingAttr,
TextAttrBorders absentAttr) | CollectCommonAttributes(self, TextAttrBorders attr, TextAttrBorders clashingAttr,
TextAttrBorders absentAttr) | [
"CollectCommonAttributes",
"(",
"self",
"TextAttrBorders",
"attr",
"TextAttrBorders",
"clashingAttr",
"TextAttrBorders",
"absentAttr",
")"
] | def CollectCommonAttributes(*args, **kwargs):
"""
CollectCommonAttributes(self, TextAttrBorders attr, TextAttrBorders clashingAttr,
TextAttrBorders absentAttr)
"""
return _richtext.TextAttrBorders_CollectCommonAttributes(*args, **kwargs) | [
"def",
"CollectCommonAttributes",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"TextAttrBorders_CollectCommonAttributes",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/richtext.py#L473-L478 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py3/setuptools/_vendor/more_itertools/more.py | python | collapse | (iterable, base_type=None, levels=None) | Flatten an iterable with multiple levels of nesting (e.g., a list of
lists of tuples) into non-iterable types.
>>> iterable = [(1, 2), ([3, 4], [[5], [6]])]
>>> list(collapse(iterable))
[1, 2, 3, 4, 5, 6]
Binary and text strings are not considered iterable and
will not be collapsed.
To avoid collapsing other types, specify *base_type*:
>>> iterable = ['ab', ('cd', 'ef'), ['gh', 'ij']]
>>> list(collapse(iterable, base_type=tuple))
['ab', ('cd', 'ef'), 'gh', 'ij']
Specify *levels* to stop flattening after a certain level:
>>> iterable = [('a', ['b']), ('c', ['d'])]
>>> list(collapse(iterable)) # Fully flattened
['a', 'b', 'c', 'd']
>>> list(collapse(iterable, levels=1)) # Only one level flattened
['a', ['b'], 'c', ['d']] | Flatten an iterable with multiple levels of nesting (e.g., a list of
lists of tuples) into non-iterable types. | [
"Flatten",
"an",
"iterable",
"with",
"multiple",
"levels",
"of",
"nesting",
"(",
"e",
".",
"g",
".",
"a",
"list",
"of",
"lists",
"of",
"tuples",
")",
"into",
"non",
"-",
"iterable",
"types",
"."
] | def collapse(iterable, base_type=None, levels=None):
"""Flatten an iterable with multiple levels of nesting (e.g., a list of
lists of tuples) into non-iterable types.
>>> iterable = [(1, 2), ([3, 4], [[5], [6]])]
>>> list(collapse(iterable))
[1, 2, 3, 4, 5, 6]
Binary and text strings are not considered iterable and
will not be collapsed.
To avoid collapsing other types, specify *base_type*:
>>> iterable = ['ab', ('cd', 'ef'), ['gh', 'ij']]
>>> list(collapse(iterable, base_type=tuple))
['ab', ('cd', 'ef'), 'gh', 'ij']
Specify *levels* to stop flattening after a certain level:
>>> iterable = [('a', ['b']), ('c', ['d'])]
>>> list(collapse(iterable)) # Fully flattened
['a', 'b', 'c', 'd']
>>> list(collapse(iterable, levels=1)) # Only one level flattened
['a', ['b'], 'c', ['d']]
"""
def walk(node, level):
if (
((levels is not None) and (level > levels))
or isinstance(node, (str, bytes))
or ((base_type is not None) and isinstance(node, base_type))
):
yield node
return
try:
tree = iter(node)
except TypeError:
yield node
return
else:
for child in tree:
yield from walk(child, level + 1)
yield from walk(iterable, 0) | [
"def",
"collapse",
"(",
"iterable",
",",
"base_type",
"=",
"None",
",",
"levels",
"=",
"None",
")",
":",
"def",
"walk",
"(",
"node",
",",
"level",
")",
":",
"if",
"(",
"(",
"(",
"levels",
"is",
"not",
"None",
")",
"and",
"(",
"level",
">",
"level... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/_vendor/more_itertools/more.py#L1020-L1065 | ||
nmslib/nmslib | 5acedb651c277af8d99fa75def9f8b2590bd9512 | benchmark/eval.py | python | compute_neighbors | (dist_type, data, queries, K) | Compute neighbors for a given distance.
:param dist_type: the type of the distance
:param data: data
:param queries: queries
:param K: the number of neighbors
:return: an output in the shape <#of queries> X min(K, <# of data points>) | Compute neighbors for a given distance. | [
"Compute",
"neighbors",
"for",
"a",
"given",
"distance",
"."
] | def compute_neighbors(dist_type, data, queries, K):
"""Compute neighbors for a given distance.
:param dist_type: the type of the distance
:param data: data
:param queries: queries
:param K: the number of neighbors
:return: an output in the shape <#of queries> X min(K, <# of data points>)
"""
dist_type = dist_type.lower()
if dist_type in SKLEARN_MAP:
sindx = NearestNeighbors(n_neighbors=K, metric=SKLEARN_MAP[dist_type], algorithm='brute', n_jobs=-1)
sindx.fit(data)
return sindx.kneighbors(queries, return_distance=False)
elif dist_type.startswith('l') and len(dist_type) > 1 and to_int(dist_type[1:]) > 0:
sindx = NearestNeighbors(n_neighbors=K, metric='minkowski', p=to_int(dist_type[1:]), algorithm='brute', n_jobs=-1)
sindx.fit(data)
return sindx.kneighbors(queries, return_distance=False)
elif dist_type == DIST_INNER_PROD:
return compute_neighbors_batched(data, queries, K, inner_prod_neighbor_dists, DIST_COMPUTE_BATCH_SIZE)
elif dist_type == DIST_KL_DIV:
return compute_neighbors_batched(data, queries, K, kldiv_neighbor_dists, DIST_COMPUTE_BATCH_SIZE)
else:
raise Exception(f'Unsupported distance: {dist_type}') | [
"def",
"compute_neighbors",
"(",
"dist_type",
",",
"data",
",",
"queries",
",",
"K",
")",
":",
"dist_type",
"=",
"dist_type",
".",
"lower",
"(",
")",
"if",
"dist_type",
"in",
"SKLEARN_MAP",
":",
"sindx",
"=",
"NearestNeighbors",
"(",
"n_neighbors",
"=",
"K... | https://github.com/nmslib/nmslib/blob/5acedb651c277af8d99fa75def9f8b2590bd9512/benchmark/eval.py#L136-L166 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/distlib/version.py | python | VersionScheme.is_valid_constraint_list | (self, s) | return self.is_valid_matcher('dummy_name (%s)' % s) | Used for processing some metadata fields | Used for processing some metadata fields | [
"Used",
"for",
"processing",
"some",
"metadata",
"fields"
] | def is_valid_constraint_list(self, s):
"""
Used for processing some metadata fields
"""
return self.is_valid_matcher('dummy_name (%s)' % s) | [
"def",
"is_valid_constraint_list",
"(",
"self",
",",
"s",
")",
":",
"return",
"self",
".",
"is_valid_matcher",
"(",
"'dummy_name (%s)'",
"%",
"s",
")"
] | 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/distlib/version.py#L709-L713 | |
gimli-org/gimli | 17aa2160de9b15ababd9ef99e89b1bc3277bbb23 | pygimli/physics/em/fdem.py | python | FDEM.invBlock | (self, xpos=0, nlay=2, noise=1.0, show=True,
stmod=30., lam=1000., lBound=0., uBound=0., verbose=False) | return self.model1d | Create and return Gimli inversion instance for block inversion.
Parameters
----------
xpos : array
position vector
nLay : int
Number of layers of the model to be determined OR
vector of layer numbers OR forward operator
noise : float
Absolute data err in percent
stmod : float or pg.Vector
Starting model
lam : float
Global regularization parameter lambda.
lBound : float
Lower boundary for the model
uBound : float
Upper boundary for the model. 0 means no upper booundary
verbose : bool
Be verbose | Create and return Gimli inversion instance for block inversion. | [
"Create",
"and",
"return",
"Gimli",
"inversion",
"instance",
"for",
"block",
"inversion",
"."
] | def invBlock(self, xpos=0, nlay=2, noise=1.0, show=True,
stmod=30., lam=1000., lBound=0., uBound=0., verbose=False):
"""Create and return Gimli inversion instance for block inversion.
Parameters
----------
xpos : array
position vector
nLay : int
Number of layers of the model to be determined OR
vector of layer numbers OR forward operator
noise : float
Absolute data err in percent
stmod : float or pg.Vector
Starting model
lam : float
Global regularization parameter lambda.
lBound : float
Lower boundary for the model
uBound : float
Upper boundary for the model. 0 means no upper booundary
verbose : bool
Be verbose
"""
self.transThk = pg.trans.TransLog()
self.transRes = pg.trans.TransLogLU(lBound, uBound)
self.transData = pg.trans.Trans()
# EM forward operator
if isinstance(nlay, pg.core.FDEM1dModelling):
self.fop = nlay
else:
self.fop = self.FOP(nlay)
data = self.datavec(xpos)
self.fop.region(0).setTransModel(self.transThk)
self.fop.region(1).setTransModel(self.transRes)
if isinstance(noise, float):
noiseVec = pg.Vector(len(data), noise)
else:
noiseVec = pg.asvector(noise)
# independent EM inversion
self.inv = pg.core.Inversion(data, self.fop, self.transData, verbose)
if isinstance(stmod, float): # real model given
model = pg.Vector(nlay * 2 - 1, stmod)
model[0] = 2.
else:
if len(stmod) == nlay * 2 - 1:
model = stmod
else:
model = pg.Vector(nlay * 2 - 1, 30.)
self.inv.setAbsoluteError(noiseVec)
self.inv.setLambda(lam)
self.inv.setMarquardtScheme(0.8)
self.inv.setDeltaPhiAbortPercent(0.5)
self.inv.setModel(model)
# self.inv.setReferenceModel(model)
self.model1d = self.inv.run()
if show:
self.plotData(response=self.inv.response())
return self.model1d | [
"def",
"invBlock",
"(",
"self",
",",
"xpos",
"=",
"0",
",",
"nlay",
"=",
"2",
",",
"noise",
"=",
"1.0",
",",
"show",
"=",
"True",
",",
"stmod",
"=",
"30.",
",",
"lam",
"=",
"1000.",
",",
"lBound",
"=",
"0.",
",",
"uBound",
"=",
"0.",
",",
"ve... | https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/physics/em/fdem.py#L424-L495 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/pkg_resources/_vendor/pyparsing.py | python | ParserElement.parseWithTabs | ( self ) | return self | Overrides default behavior to expand C{<TAB>}s to spaces before parsing the input string.
Must be called before C{parseString} when the input grammar contains elements that
match C{<TAB>} characters. | Overrides default behavior to expand C{<TAB>}s to spaces before parsing the input string.
Must be called before C{parseString} when the input grammar contains elements that
match C{<TAB>} characters. | [
"Overrides",
"default",
"behavior",
"to",
"expand",
"C",
"{",
"<TAB",
">",
"}",
"s",
"to",
"spaces",
"before",
"parsing",
"the",
"input",
"string",
".",
"Must",
"be",
"called",
"before",
"C",
"{",
"parseString",
"}",
"when",
"the",
"input",
"grammar",
"c... | def parseWithTabs( self ):
"""
Overrides default behavior to expand C{<TAB>}s to spaces before parsing the input string.
Must be called before C{parseString} when the input grammar contains elements that
match C{<TAB>} characters.
"""
self.keepTabs = True
return self | [
"def",
"parseWithTabs",
"(",
"self",
")",
":",
"self",
".",
"keepTabs",
"=",
"True",
"return",
"self"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/pkg_resources/_vendor/pyparsing.py#L2029-L2036 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/distutils/command/bdist_rpm.py | python | bdist_rpm._make_spec_file | (self) | return spec_file | Generate the text of an RPM spec file and return it as a
list of strings (one per line). | Generate the text of an RPM spec file and return it as a
list of strings (one per line). | [
"Generate",
"the",
"text",
"of",
"an",
"RPM",
"spec",
"file",
"and",
"return",
"it",
"as",
"a",
"list",
"of",
"strings",
"(",
"one",
"per",
"line",
")",
"."
] | def _make_spec_file(self):
"""Generate the text of an RPM spec file and return it as a
list of strings (one per line).
"""
# definitions and headers
spec_file = [
'%define name ' + self.distribution.get_name(),
'%define version ' + self.distribution.get_version().replace('-','_'),
'%define unmangled_version ' + self.distribution.get_version(),
'%define release ' + self.release.replace('-','_'),
'',
'Summary: ' + self.distribution.get_description(),
]
# Workaround for #14443 which affects some RPM based systems such as
# RHEL6 (and probably derivatives)
vendor_hook = subprocess.getoutput('rpm --eval %{__os_install_post}')
# Generate a potential replacement value for __os_install_post (whilst
# normalizing the whitespace to simplify the test for whether the
# invocation of brp-python-bytecompile passes in __python):
vendor_hook = '\n'.join([' %s \\' % line.strip()
for line in vendor_hook.splitlines()])
problem = "brp-python-bytecompile \\\n"
fixed = "brp-python-bytecompile %{__python} \\\n"
fixed_hook = vendor_hook.replace(problem, fixed)
if fixed_hook != vendor_hook:
spec_file.append('# Workaround for http://bugs.python.org/issue14443')
spec_file.append('%define __os_install_post ' + fixed_hook + '\n')
# put locale summaries into spec file
# XXX not supported for now (hard to put a dictionary
# in a config file -- arg!)
#for locale in self.summaries.keys():
# spec_file.append('Summary(%s): %s' % (locale,
# self.summaries[locale]))
spec_file.extend([
'Name: %{name}',
'Version: %{version}',
'Release: %{release}',])
# XXX yuck! this filename is available from the "sdist" command,
# but only after it has run: and we create the spec file before
# running "sdist", in case of --spec-only.
if self.use_bzip2:
spec_file.append('Source0: %{name}-%{unmangled_version}.tar.bz2')
else:
spec_file.append('Source0: %{name}-%{unmangled_version}.tar.gz')
spec_file.extend([
'License: ' + self.distribution.get_license(),
'Group: ' + self.group,
'BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-buildroot',
'Prefix: %{_prefix}', ])
if not self.force_arch:
# noarch if no extension modules
if not self.distribution.has_ext_modules():
spec_file.append('BuildArch: noarch')
else:
spec_file.append( 'BuildArch: %s' % self.force_arch )
for field in ('Vendor',
'Packager',
'Provides',
'Requires',
'Conflicts',
'Obsoletes',
):
val = getattr(self, field.lower())
if isinstance(val, list):
spec_file.append('%s: %s' % (field, ' '.join(val)))
elif val is not None:
spec_file.append('%s: %s' % (field, val))
if self.distribution.get_url() != 'UNKNOWN':
spec_file.append('Url: ' + self.distribution.get_url())
if self.distribution_name:
spec_file.append('Distribution: ' + self.distribution_name)
if self.build_requires:
spec_file.append('BuildRequires: ' +
' '.join(self.build_requires))
if self.icon:
spec_file.append('Icon: ' + os.path.basename(self.icon))
if self.no_autoreq:
spec_file.append('AutoReq: 0')
spec_file.extend([
'',
'%description',
self.distribution.get_long_description()
])
# put locale descriptions into spec file
# XXX again, suppressed because config file syntax doesn't
# easily support this ;-(
#for locale in self.descriptions.keys():
# spec_file.extend([
# '',
# '%description -l ' + locale,
# self.descriptions[locale],
# ])
# rpm scripts
# figure out default build script
def_setup_call = "%s %s" % (self.python,os.path.basename(sys.argv[0]))
def_build = "%s build" % def_setup_call
if self.use_rpm_opt_flags:
def_build = 'env CFLAGS="$RPM_OPT_FLAGS" ' + def_build
# insert contents of files
# XXX this is kind of misleading: user-supplied options are files
# that we open and interpolate into the spec file, but the defaults
# are just text that we drop in as-is. Hmmm.
install_cmd = ('%s install -O1 --root=$RPM_BUILD_ROOT '
'--record=INSTALLED_FILES') % def_setup_call
script_options = [
('prep', 'prep_script', "%setup -n %{name}-%{unmangled_version}"),
('build', 'build_script', def_build),
('install', 'install_script', install_cmd),
('clean', 'clean_script', "rm -rf $RPM_BUILD_ROOT"),
('verifyscript', 'verify_script', None),
('pre', 'pre_install', None),
('post', 'post_install', None),
('preun', 'pre_uninstall', None),
('postun', 'post_uninstall', None),
]
for (rpm_opt, attr, default) in script_options:
# Insert contents of file referred to, if no file is referred to
# use 'default' as contents of script
val = getattr(self, attr)
if val or default:
spec_file.extend([
'',
'%' + rpm_opt,])
if val:
spec_file.extend(open(val, 'r').read().split('\n'))
else:
spec_file.append(default)
# files section
spec_file.extend([
'',
'%files -f INSTALLED_FILES',
'%defattr(-,root,root)',
])
if self.doc_files:
spec_file.append('%doc ' + ' '.join(self.doc_files))
if self.changelog:
spec_file.extend([
'',
'%changelog',])
spec_file.extend(self.changelog)
return spec_file | [
"def",
"_make_spec_file",
"(",
"self",
")",
":",
"# definitions and headers",
"spec_file",
"=",
"[",
"'%define name '",
"+",
"self",
".",
"distribution",
".",
"get_name",
"(",
")",
",",
"'%define version '",
"+",
"self",
".",
"distribution",
".",
"get_version",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/distutils/command/bdist_rpm.py#L395-L561 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/mapreduce/mapreduce/records.py | python | _mask_crc | (crc) | return (((crc >> 15) | (crc << 17)) + _CRC_MASK_DELTA) & 0xFFFFFFFFL | Mask crc.
Args:
crc: integer crc.
Returns:
masked integer crc. | Mask crc. | [
"Mask",
"crc",
"."
] | def _mask_crc(crc):
"""Mask crc.
Args:
crc: integer crc.
Returns:
masked integer crc.
"""
return (((crc >> 15) | (crc << 17)) + _CRC_MASK_DELTA) & 0xFFFFFFFFL | [
"def",
"_mask_crc",
"(",
"crc",
")",
":",
"return",
"(",
"(",
"(",
"crc",
">>",
"15",
")",
"|",
"(",
"crc",
"<<",
"17",
")",
")",
"+",
"_CRC_MASK_DELTA",
")",
"&",
"0xFFFFFFFFL"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/mapreduce/mapreduce/records.py#L111-L119 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/core/dtypes/inference.py | python | is_nested_list_like | (obj) | return (is_list_like(obj) and hasattr(obj, '__len__') and
len(obj) > 0 and all(is_list_like(item) for item in obj)) | Check if the object is list-like, and that all of its elements
are also list-like.
.. versionadded:: 0.20.0
Parameters
----------
obj : The object to check
Returns
-------
is_list_like : bool
Whether `obj` has list-like properties.
Examples
--------
>>> is_nested_list_like([[1, 2, 3]])
True
>>> is_nested_list_like([{1, 2, 3}, {1, 2, 3}])
True
>>> is_nested_list_like(["foo"])
False
>>> is_nested_list_like([])
False
>>> is_nested_list_like([[1, 2, 3], 1])
False
Notes
-----
This won't reliably detect whether a consumable iterator (e. g.
a generator) is a nested-list-like without consuming the iterator.
To avoid consuming it, we always return False if the outer container
doesn't define `__len__`.
See Also
--------
is_list_like | Check if the object is list-like, and that all of its elements
are also list-like. | [
"Check",
"if",
"the",
"object",
"is",
"list",
"-",
"like",
"and",
"that",
"all",
"of",
"its",
"elements",
"are",
"also",
"list",
"-",
"like",
"."
] | def is_nested_list_like(obj):
"""
Check if the object is list-like, and that all of its elements
are also list-like.
.. versionadded:: 0.20.0
Parameters
----------
obj : The object to check
Returns
-------
is_list_like : bool
Whether `obj` has list-like properties.
Examples
--------
>>> is_nested_list_like([[1, 2, 3]])
True
>>> is_nested_list_like([{1, 2, 3}, {1, 2, 3}])
True
>>> is_nested_list_like(["foo"])
False
>>> is_nested_list_like([])
False
>>> is_nested_list_like([[1, 2, 3], 1])
False
Notes
-----
This won't reliably detect whether a consumable iterator (e. g.
a generator) is a nested-list-like without consuming the iterator.
To avoid consuming it, we always return False if the outer container
doesn't define `__len__`.
See Also
--------
is_list_like
"""
return (is_list_like(obj) and hasattr(obj, '__len__') and
len(obj) > 0 and all(is_list_like(item) for item in obj)) | [
"def",
"is_nested_list_like",
"(",
"obj",
")",
":",
"return",
"(",
"is_list_like",
"(",
"obj",
")",
"and",
"hasattr",
"(",
"obj",
",",
"'__len__'",
")",
"and",
"len",
"(",
"obj",
")",
">",
"0",
"and",
"all",
"(",
"is_list_like",
"(",
"item",
")",
"fo... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/dtypes/inference.py#L337-L378 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/io/sas/sas_xport.py | python | _parse_date | (datestr) | Given a date in xport format, return Python date. | Given a date in xport format, return Python date. | [
"Given",
"a",
"date",
"in",
"xport",
"format",
"return",
"Python",
"date",
"."
] | def _parse_date(datestr):
""" Given a date in xport format, return Python date. """
try:
# e.g. "16FEB11:10:07:55"
return datetime.strptime(datestr, "%d%b%y:%H:%M:%S")
except ValueError:
return pd.NaT | [
"def",
"_parse_date",
"(",
"datestr",
")",
":",
"try",
":",
"# e.g. \"16FEB11:10:07:55\"",
"return",
"datetime",
".",
"strptime",
"(",
"datestr",
",",
"\"%d%b%y:%H:%M:%S\"",
")",
"except",
"ValueError",
":",
"return",
"pd",
".",
"NaT"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/io/sas/sas_xport.py#L120-L126 | ||
psi4/psi4 | be533f7f426b6ccc263904e55122899b16663395 | psi4/driver/qcdb/qchem.py | python | psi4_list | () | return sorted(procedures['energy'].keys()) | Return an array of Psi4 methods with energies. | Return an array of Psi4 methods with energies. | [
"Return",
"an",
"array",
"of",
"Psi4",
"methods",
"with",
"energies",
"."
] | def psi4_list():
"""Return an array of Psi4 methods with energies.
"""
return sorted(procedures['energy'].keys()) | [
"def",
"psi4_list",
"(",
")",
":",
"return",
"sorted",
"(",
"procedures",
"[",
"'energy'",
"]",
".",
"keys",
"(",
")",
")"
] | https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/qcdb/qchem.py#L477-L481 | |
envoyproxy/envoy | 65541accdafe255e72310b4298d646e091da2d80 | configs/configgen.py | python | generate_config | (template_path, template, output_file, **context) | Generate a final config file based on a template and some context. | Generate a final config file based on a template and some context. | [
"Generate",
"a",
"final",
"config",
"file",
"based",
"on",
"a",
"template",
"and",
"some",
"context",
"."
] | def generate_config(template_path, template, output_file, **context):
""" Generate a final config file based on a template and some context. """
env = jinja2.Environment(
loader=jinja2.FileSystemLoader(template_path, followlinks=True),
undefined=jinja2.StrictUndefined)
raw_output = env.get_template(template).render(**context)
with open(output_file, 'w') as fh:
fh.write(raw_output) | [
"def",
"generate_config",
"(",
"template_path",
",",
"template",
",",
"output_file",
",",
"*",
"*",
"context",
")",
":",
"env",
"=",
"jinja2",
".",
"Environment",
"(",
"loader",
"=",
"jinja2",
".",
"FileSystemLoader",
"(",
"template_path",
",",
"followlinks",
... | https://github.com/envoyproxy/envoy/blob/65541accdafe255e72310b4298d646e091da2d80/configs/configgen.py#L97-L104 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/re2/lib/codereview/codereview.py | python | VersionControlSystem.GenerateDiff | (self, args) | Return the current diff as a string.
Args:
args: Extra arguments to pass to the diff command. | Return the current diff as a string. | [
"Return",
"the",
"current",
"diff",
"as",
"a",
"string",
"."
] | def GenerateDiff(self, args):
"""Return the current diff as a string.
Args:
args: Extra arguments to pass to the diff command.
"""
raise NotImplementedError(
"abstract method -- subclass %s must override" % self.__class__) | [
"def",
"GenerateDiff",
"(",
"self",
",",
"args",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"abstract method -- subclass %s must override\"",
"%",
"self",
".",
"__class__",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/re2/lib/codereview/codereview.py#L3169-L3176 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/func_graph.py | python | FuncGraph.capture | (self, tensor, name=None) | return tensor | Captures `tensor` if it's external to this graph.
If `tensor` is from a different graph, returns a placeholder for it.
`tensor` and the placeholder will appear in self.captures, and the
placeholder will appear in self.inputs. Multiple calls to this method with
the same `tensor` argument will return the same placeholder. If `tensor` is
from this graph, returns `tensor`.
Args:
tensor: Tensor. May be from this FuncGraph or a different graph.
name: Optional name if a placeholder is created.
Returns:
Tensor from this FuncGraph.
Raises:
InaccessibleTensorError: if any tensors are accessed in a manner that
bypasses the mechanisms required for the data dependencies to be correctly
wired. | Captures `tensor` if it's external to this graph. | [
"Captures",
"tensor",
"if",
"it",
"s",
"external",
"to",
"this",
"graph",
"."
] | def capture(self, tensor, name=None):
"""Captures `tensor` if it's external to this graph.
If `tensor` is from a different graph, returns a placeholder for it.
`tensor` and the placeholder will appear in self.captures, and the
placeholder will appear in self.inputs. Multiple calls to this method with
the same `tensor` argument will return the same placeholder. If `tensor` is
from this graph, returns `tensor`.
Args:
tensor: Tensor. May be from this FuncGraph or a different graph.
name: Optional name if a placeholder is created.
Returns:
Tensor from this FuncGraph.
Raises:
InaccessibleTensorError: if any tensors are accessed in a manner that
bypasses the mechanisms required for the data dependencies to be correctly
wired.
"""
# Note: _forward_func_graph is currently only set when building the gradient
# graph graph of a defun call. If the backwards graph tries to capture
# tensors those will be captured first in the forward graph. This
# makes sure that any tensor needed by a custom_gradient is correctly
# captured.
if (getattr(tensor, "graph", None) is not self and
hasattr(self, "_forward_func_graph") and
isinstance(self._forward_func_graph, FuncGraph)):
tensor = self._forward_func_graph.capture(tensor)
if isinstance(tensor, ops.EagerTensor):
if name is None:
name = str(ops.uid())
# Small EagerTensors are captured with Const ops
if (tensor.dtype in dtypes.TF_VALUE_DTYPES and
np.prod(tensor.shape) <= _EAGER_CONST_THRESHOLD):
return self.capture_eager_tensor(tensor, name)
# Large EagerTensors and resources are captured with Placeholder ops
return self._capture_helper(tensor, name)
if tensor.graph is not self:
if name is None:
name = tensor.op.name
inner_graph = tensor.graph
while inner_graph is not None and isinstance(inner_graph, FuncGraph):
if inner_graph is self:
raise errors.InaccessibleTensorError(
"The tensor '%s' cannot be accessed here: it is defined"
" in another function or code block. Use return values,"
" explicit Python locals or TensorFlow collections to access"
" it. Defined in: %s; accessed from: %s.\n"
% (tensor, tensor.graph, self))
inner_graph = inner_graph.outer_graph
return self._capture_helper(tensor, name)
return tensor | [
"def",
"capture",
"(",
"self",
",",
"tensor",
",",
"name",
"=",
"None",
")",
":",
"# Note: _forward_func_graph is currently only set when building the gradient",
"# graph graph of a defun call. If the backwards graph tries to capture",
"# tensors those will be captured first in the forwa... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/func_graph.py#L550-L606 | |
SpenceKonde/megaTinyCore | 1c4a70b18a149fe6bcb551dfa6db11ca50b8997b | megaavr/tools/libs/pymcuprog/nvm.py | python | NvmAccessProvider._log_incomplete_stack | (self, device_stack) | Used to tell the user this device stack is not completed yet
:param device_stack: User friendly name of target stack | Used to tell the user this device stack is not completed yet | [
"Used",
"to",
"tell",
"the",
"user",
"this",
"device",
"stack",
"is",
"not",
"completed",
"yet"
] | def _log_incomplete_stack(self, device_stack):
"""
Used to tell the user this device stack is not completed yet
:param device_stack: User friendly name of target stack
"""
self.logger.warning("")
self.logger.warning("%s stack is in Alpha state", device_stack)
self.logger.warning("Expect some features to be missing")
self.logger.warning("") | [
"def",
"_log_incomplete_stack",
"(",
"self",
",",
"device_stack",
")",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"\"\"",
")",
"self",
".",
"logger",
".",
"warning",
"(",
"\"%s stack is in Alpha state\"",
",",
"device_stack",
")",
"self",
".",
"logger",
... | https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/pymcuprog/nvm.py#L73-L82 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/stats/_multivariate.py | python | multivariate_normal_gen.rvs | (self, mean=None, cov=1, size=1, random_state=None) | return _squeeze_output(out) | Draw random samples from a multivariate normal distribution.
Parameters
----------
%(_mvn_doc_default_callparams)s
size : integer, optional
Number of samples to draw (default 1).
%(_doc_random_state)s
Returns
-------
rvs : ndarray or scalar
Random variates of size (`size`, `N`), where `N` is the
dimension of the random variable.
Notes
-----
%(_mvn_doc_callparams_note)s | Draw random samples from a multivariate normal distribution. | [
"Draw",
"random",
"samples",
"from",
"a",
"multivariate",
"normal",
"distribution",
"."
] | def rvs(self, mean=None, cov=1, size=1, random_state=None):
"""
Draw random samples from a multivariate normal distribution.
Parameters
----------
%(_mvn_doc_default_callparams)s
size : integer, optional
Number of samples to draw (default 1).
%(_doc_random_state)s
Returns
-------
rvs : ndarray or scalar
Random variates of size (`size`, `N`), where `N` is the
dimension of the random variable.
Notes
-----
%(_mvn_doc_callparams_note)s
"""
dim, mean, cov = self._process_parameters(None, mean, cov)
random_state = self._get_random_state(random_state)
out = random_state.multivariate_normal(mean, cov, size)
return _squeeze_output(out) | [
"def",
"rvs",
"(",
"self",
",",
"mean",
"=",
"None",
",",
"cov",
"=",
"1",
",",
"size",
"=",
"1",
",",
"random_state",
"=",
"None",
")",
":",
"dim",
",",
"mean",
",",
"cov",
"=",
"self",
".",
"_process_parameters",
"(",
"None",
",",
"mean",
",",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/stats/_multivariate.py#L635-L661 | |
SequoiaDB/SequoiaDB | 2894ed7e5bd6fe57330afc900cf76d0ff0df9f64 | tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py | python | uCSIsControlPictures | (code) | return ret | Check whether the character is part of ControlPictures UCS
Block | Check whether the character is part of ControlPictures UCS
Block | [
"Check",
"whether",
"the",
"character",
"is",
"part",
"of",
"ControlPictures",
"UCS",
"Block"
] | def uCSIsControlPictures(code):
"""Check whether the character is part of ControlPictures UCS
Block """
ret = libxml2mod.xmlUCSIsControlPictures(code)
return ret | [
"def",
"uCSIsControlPictures",
"(",
"code",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlUCSIsControlPictures",
"(",
"code",
")",
"return",
"ret"
] | https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L2405-L2409 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_gdi.py | python | NativeFontInfo.GetPointSize | (*args, **kwargs) | return _gdi_.NativeFontInfo_GetPointSize(*args, **kwargs) | GetPointSize(self) -> int | GetPointSize(self) -> int | [
"GetPointSize",
"(",
"self",
")",
"-",
">",
"int"
] | def GetPointSize(*args, **kwargs):
"""GetPointSize(self) -> int"""
return _gdi_.NativeFontInfo_GetPointSize(*args, **kwargs) | [
"def",
"GetPointSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"NativeFontInfo_GetPointSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L1877-L1879 | |
KratosMultiphysics/Kratos | 0000833054ed0503424eb28205d6508d9ca6cbbc | applications/RomApplication/python_scripts/convection_diffusion_analysis_rom.py | python | ConvectionDiffusionAnalysisROM.ModifyAfterSolverInitialize | (self) | Here is where the ROM_BASIS is imposed to each node | Here is where the ROM_BASIS is imposed to each node | [
"Here",
"is",
"where",
"the",
"ROM_BASIS",
"is",
"imposed",
"to",
"each",
"node"
] | def ModifyAfterSolverInitialize(self):
"""Here is where the ROM_BASIS is imposed to each node"""
super().ModifyAfterSolverInitialize()
computing_model_part = self._solver.GetComputingModelPart()
with open('RomParameters.json') as f:
data = json.load(f)
nodal_dofs = len(data["rom_settings"]["nodal_unknowns"])
nodal_modes = data["nodal_modes"]
counter = 0
rom_dofs= self.project_parameters["solver_settings"]["rom_settings"]["number_of_rom_dofs"].GetInt()
for node in computing_model_part.Nodes:
aux = KratosMultiphysics.Matrix(nodal_dofs, rom_dofs)
for j in range(nodal_dofs):
Counter=str(node.Id)
for i in range(rom_dofs):
aux[j,i] = nodal_modes[Counter][j][i]
node.SetValue(romapp.ROM_BASIS, aux ) # ROM basis
counter+=1 | [
"def",
"ModifyAfterSolverInitialize",
"(",
"self",
")",
":",
"super",
"(",
")",
".",
"ModifyAfterSolverInitialize",
"(",
")",
"computing_model_part",
"=",
"self",
".",
"_solver",
".",
"GetComputingModelPart",
"(",
")",
"with",
"open",
"(",
"'RomParameters.json'",
... | https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/RomApplication/python_scripts/convection_diffusion_analysis_rom.py#L28-L45 | ||
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | RewrapResponse.__init__ | (self, outDuplicate = None, outSymSeed = None) | This command allows the TPM to serve in the role as a Duplication
Authority. If proper authorization for use of the oldParent is provided,
then an HMAC key and a symmetric key are recovered from inSymSeed and
used to integrity check and decrypt inDuplicate. A new protection seed
value is generated according to the methods appropriate for newParent
and the blob is re-encrypted and a new integrity value is computed. The
re-encrypted blob is returned in outDuplicate and the symmetric key
returned in outSymKey.
Attributes:
outDuplicate (TPM2B_PRIVATE): An object encrypted using symmetric
key derived from outSymSeed
outSymSeed (bytes): Seed for a symmetric key protected by newParent
asymmetric key | This command allows the TPM to serve in the role as a Duplication
Authority. If proper authorization for use of the oldParent is provided,
then an HMAC key and a symmetric key are recovered from inSymSeed and
used to integrity check and decrypt inDuplicate. A new protection seed
value is generated according to the methods appropriate for newParent
and the blob is re-encrypted and a new integrity value is computed. The
re-encrypted blob is returned in outDuplicate and the symmetric key
returned in outSymKey. | [
"This",
"command",
"allows",
"the",
"TPM",
"to",
"serve",
"in",
"the",
"role",
"as",
"a",
"Duplication",
"Authority",
".",
"If",
"proper",
"authorization",
"for",
"use",
"of",
"the",
"oldParent",
"is",
"provided",
"then",
"an",
"HMAC",
"key",
"and",
"a",
... | def __init__(self, outDuplicate = None, outSymSeed = None):
""" This command allows the TPM to serve in the role as a Duplication
Authority. If proper authorization for use of the oldParent is provided,
then an HMAC key and a symmetric key are recovered from inSymSeed and
used to integrity check and decrypt inDuplicate. A new protection seed
value is generated according to the methods appropriate for newParent
and the blob is re-encrypted and a new integrity value is computed. The
re-encrypted blob is returned in outDuplicate and the symmetric key
returned in outSymKey.
Attributes:
outDuplicate (TPM2B_PRIVATE): An object encrypted using symmetric
key derived from outSymSeed
outSymSeed (bytes): Seed for a symmetric key protected by newParent
asymmetric key
"""
self.outDuplicate = outDuplicate
self.outSymSeed = outSymSeed | [
"def",
"__init__",
"(",
"self",
",",
"outDuplicate",
"=",
"None",
",",
"outSymSeed",
"=",
"None",
")",
":",
"self",
".",
"outDuplicate",
"=",
"outDuplicate",
"self",
".",
"outSymSeed",
"=",
"outSymSeed"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L10443-L10460 | ||
PrincetonUniversity/athena-public-version | 9c266692b9423743d8e23509b3ab266a232a92d2 | tst/style/cpplint.py | python | _SetVerboseLevel | (level) | return _cpplint_state.SetVerboseLevel(level) | Sets the module's verbosity, and returns the previous setting. | Sets the module's verbosity, and returns the previous setting. | [
"Sets",
"the",
"module",
"s",
"verbosity",
"and",
"returns",
"the",
"previous",
"setting",
"."
] | def _SetVerboseLevel(level):
"""Sets the module's verbosity, and returns the previous setting."""
return _cpplint_state.SetVerboseLevel(level) | [
"def",
"_SetVerboseLevel",
"(",
"level",
")",
":",
"return",
"_cpplint_state",
".",
"SetVerboseLevel",
"(",
"level",
")"
] | https://github.com/PrincetonUniversity/athena-public-version/blob/9c266692b9423743d8e23509b3ab266a232a92d2/tst/style/cpplint.py#L1195-L1197 | |
libornovax/master_thesis_code | 6eca474ed3cae673afde010caef338cf7349f839 | scripts/data/shared/classes.py | python | BB2D.height | (self) | return float(self.ymax - self.ymin) | Height of the bounding box. | Height of the bounding box. | [
"Height",
"of",
"the",
"bounding",
"box",
"."
] | def height(self):
"""
Height of the bounding box.
"""
return float(self.ymax - self.ymin) | [
"def",
"height",
"(",
"self",
")",
":",
"return",
"float",
"(",
"self",
".",
"ymax",
"-",
"self",
".",
"ymin",
")"
] | https://github.com/libornovax/master_thesis_code/blob/6eca474ed3cae673afde010caef338cf7349f839/scripts/data/shared/classes.py#L81-L85 | |
BertaBescos/DynaSLAM | 8f894a8b9d63c0a608fd871d63c10796491b9312 | src/python/model.py | python | load_image_gt | (dataset, config, image_id, augment=False,
use_mini_mask=False) | return image, image_meta, class_ids, bbox, mask | Load and return ground truth data for an image (image, mask, bounding boxes).
augment: If true, apply random image augmentation. Currently, only
horizontal flipping is offered.
use_mini_mask: If False, returns full-size masks that are the same height
and width as the original image. These can be big, for example
1024x1024x100 (for 100 instances). Mini masks are smaller, typically,
224x224 and are generated by extracting the bounding box of the
object and resizing it to MINI_MASK_SHAPE.
Returns:
image: [height, width, 3]
shape: the original shape of the image before resizing and cropping.
class_ids: [instance_count] Integer class IDs
bbox: [instance_count, (y1, x1, y2, x2)]
mask: [height, width, instance_count]. The height and width are those
of the image unless use_mini_mask is True, in which case they are
defined in MINI_MASK_SHAPE. | Load and return ground truth data for an image (image, mask, bounding boxes). | [
"Load",
"and",
"return",
"ground",
"truth",
"data",
"for",
"an",
"image",
"(",
"image",
"mask",
"bounding",
"boxes",
")",
"."
] | def load_image_gt(dataset, config, image_id, augment=False,
use_mini_mask=False):
"""Load and return ground truth data for an image (image, mask, bounding boxes).
augment: If true, apply random image augmentation. Currently, only
horizontal flipping is offered.
use_mini_mask: If False, returns full-size masks that are the same height
and width as the original image. These can be big, for example
1024x1024x100 (for 100 instances). Mini masks are smaller, typically,
224x224 and are generated by extracting the bounding box of the
object and resizing it to MINI_MASK_SHAPE.
Returns:
image: [height, width, 3]
shape: the original shape of the image before resizing and cropping.
class_ids: [instance_count] Integer class IDs
bbox: [instance_count, (y1, x1, y2, x2)]
mask: [height, width, instance_count]. The height and width are those
of the image unless use_mini_mask is True, in which case they are
defined in MINI_MASK_SHAPE.
"""
# Load image and mask
image = dataset.load_image(image_id)
mask, class_ids = dataset.load_mask(image_id)
shape = image.shape
image, window, scale, padding = utils.resize_image(
image,
min_dim=config.IMAGE_MIN_DIM,
max_dim=config.IMAGE_MAX_DIM,
padding=config.IMAGE_PADDING)
mask = utils.resize_mask(mask, scale, padding)
# Random horizontal flips.
if augment:
if random.randint(0, 1):
image = np.fliplr(image)
mask = np.fliplr(mask)
# Bounding boxes. Note that some boxes might be all zeros
# if the corresponding mask got cropped out.
# bbox: [num_instances, (y1, x1, y2, x2)]
bbox = utils.extract_bboxes(mask)
# Active classes
# Different datasets have different classes, so track the
# classes supported in the dataset of this image.
active_class_ids = np.zeros([dataset.num_classes], dtype=np.int32)
source_class_ids = dataset.source_class_ids[dataset.image_info[image_id]["source"]]
active_class_ids[source_class_ids] = 1
# Resize masks to smaller size to reduce memory usage
if use_mini_mask:
mask = utils.minimize_mask(bbox, mask, config.MINI_MASK_SHAPE)
# Image meta data
image_meta = compose_image_meta(image_id, shape, window, active_class_ids)
return image, image_meta, class_ids, bbox, mask | [
"def",
"load_image_gt",
"(",
"dataset",
",",
"config",
",",
"image_id",
",",
"augment",
"=",
"False",
",",
"use_mini_mask",
"=",
"False",
")",
":",
"# Load image and mask",
"image",
"=",
"dataset",
".",
"load_image",
"(",
"image_id",
")",
"mask",
",",
"class... | https://github.com/BertaBescos/DynaSLAM/blob/8f894a8b9d63c0a608fd871d63c10796491b9312/src/python/model.py#L1108-L1165 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py3/pkg_resources/__init__.py | python | ResourceManager.resource_listdir | (self, package_or_requirement, resource_name) | return get_provider(package_or_requirement).resource_listdir(
resource_name
) | List the contents of the named resource directory | List the contents of the named resource directory | [
"List",
"the",
"contents",
"of",
"the",
"named",
"resource",
"directory"
] | def resource_listdir(self, package_or_requirement, resource_name):
"""List the contents of the named resource directory"""
return get_provider(package_or_requirement).resource_listdir(
resource_name
) | [
"def",
"resource_listdir",
"(",
"self",
",",
"package_or_requirement",
",",
"resource_name",
")",
":",
"return",
"get_provider",
"(",
"package_or_requirement",
")",
".",
"resource_listdir",
"(",
"resource_name",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/pkg_resources/__init__.py#L1151-L1155 | |
rdkit/rdkit | ede860ae316d12d8568daf5ee800921c3389c84e | rdkit/ML/Neural/NetNode.py | python | NetNode.SetWeights | (self, weights) | Sets the weight list
**Arguments**
- weights: a list of values which are to be used as weights
**Note**
If this _NetNode_ already has _inputNodes_ and _weights_ is a different length,
this will bomb out with an assertion. | Sets the weight list | [
"Sets",
"the",
"weight",
"list"
] | def SetWeights(self, weights):
""" Sets the weight list
**Arguments**
- weights: a list of values which are to be used as weights
**Note**
If this _NetNode_ already has _inputNodes_ and _weights_ is a different length,
this will bomb out with an assertion.
"""
if self.inputNodes:
assert len(weights) == len(self.inputNodes),\
'lengths of weights and nodes do not match'
self.weights = numpy.array(weights) | [
"def",
"SetWeights",
"(",
"self",
",",
"weights",
")",
":",
"if",
"self",
".",
"inputNodes",
":",
"assert",
"len",
"(",
"weights",
")",
"==",
"len",
"(",
"self",
".",
"inputNodes",
")",
",",
"'lengths of weights and nodes do not match'",
"self",
".",
"weight... | https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/ML/Neural/NetNode.py#L84-L100 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/closure_linter/closure_linter/indentation.py | python | IndentationRules._Add | (self, token_info) | Adds the given token info to the stack.
Args:
token_info: The token information to add. | Adds the given token info to the stack. | [
"Adds",
"the",
"given",
"token",
"info",
"to",
"the",
"stack",
"."
] | def _Add(self, token_info):
"""Adds the given token info to the stack.
Args:
token_info: The token information to add.
"""
if self._stack and self._stack[-1].token == token_info.token:
# Don't add the same token twice.
return
if token_info.is_block or token_info.token.type == Type.START_PAREN:
token_info.overridden_by = self._GoogScopeOrNone(token_info.token)
index = 1
while index <= len(self._stack):
stack_info = self._stack[-index]
stack_token = stack_info.token
if stack_info.line_number == token_info.line_number:
# In general, tokens only override each other when they are on
# the same line.
stack_info.overridden_by = token_info
if (token_info.token.type == Type.START_BLOCK and
(stack_token.IsAssignment() or
stack_token.type in (Type.IDENTIFIER, Type.START_PAREN))):
# Multi-line blocks have lasting overrides, as in:
# callFn({
# a: 10
# },
# 30);
close_block = token_info.token.metadata.context.end_token
stack_info.is_permanent_override = \
close_block.line_number != token_info.token.line_number
elif (token_info.token.type == Type.START_BLOCK and
token_info.token.metadata.context.type == Context.BLOCK and
(stack_token.IsAssignment() or
stack_token.type == Type.IDENTIFIER)):
# When starting a function block, the override can transcend lines.
# For example
# long.long.name = function(
# a) {
# In this case the { and the = are on different lines. But the
# override should still apply.
stack_info.overridden_by = token_info
stack_info.is_permanent_override = True
else:
break
index += 1
self._stack.append(token_info) | [
"def",
"_Add",
"(",
"self",
",",
"token_info",
")",
":",
"if",
"self",
".",
"_stack",
"and",
"self",
".",
"_stack",
"[",
"-",
"1",
"]",
".",
"token",
"==",
"token_info",
".",
"token",
":",
"# Don't add the same token twice.",
"return",
"if",
"token_info",
... | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/closure_linter/closure_linter/indentation.py#L471-L519 | ||
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | third_party/numpy/files/numpy/ma/extras.py | python | issequence | (seq) | return False | Is seq a sequence (ndarray, list or tuple)? | Is seq a sequence (ndarray, list or tuple)? | [
"Is",
"seq",
"a",
"sequence",
"(",
"ndarray",
"list",
"or",
"tuple",
")",
"?"
] | def issequence(seq):
"""Is seq a sequence (ndarray, list or tuple)?"""
if isinstance(seq, (ndarray, tuple, list)):
return True
return False | [
"def",
"issequence",
"(",
"seq",
")",
":",
"if",
"isinstance",
"(",
"seq",
",",
"(",
"ndarray",
",",
"tuple",
",",
"list",
")",
")",
":",
"return",
"True",
"return",
"False"
] | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/ma/extras.py#L53-L57 | |
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/wsgiref/handlers.py | python | BaseHandler.handle_error | (self) | Log current error, and send error output to client if possible | Log current error, and send error output to client if possible | [
"Log",
"current",
"error",
"and",
"send",
"error",
"output",
"to",
"client",
"if",
"possible"
] | def handle_error(self):
"""Log current error, and send error output to client if possible"""
self.log_exception(sys.exc_info())
if not self.headers_sent:
self.result = self.error_output(self.environ, self.start_response)
self.finish_response() | [
"def",
"handle_error",
"(",
"self",
")",
":",
"self",
".",
"log_exception",
"(",
"sys",
".",
"exc_info",
"(",
")",
")",
"if",
"not",
"self",
".",
"headers_sent",
":",
"self",
".",
"result",
"=",
"self",
".",
"error_output",
"(",
"self",
".",
"environ",... | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/wsgiref/handlers.py#L305-L310 | ||
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/tools/jinja2/lexer.py | python | Lexer.wrap | (self, stream, name=None, filename=None) | This is called with the stream as returned by `tokenize` and wraps
every token in a :class:`Token` and converts the value. | This is called with the stream as returned by `tokenize` and wraps
every token in a :class:`Token` and converts the value. | [
"This",
"is",
"called",
"with",
"the",
"stream",
"as",
"returned",
"by",
"tokenize",
"and",
"wraps",
"every",
"token",
"in",
"a",
":",
"class",
":",
"Token",
"and",
"converts",
"the",
"value",
"."
] | def wrap(self, stream, name=None, filename=None):
"""This is called with the stream as returned by `tokenize` and wraps
every token in a :class:`Token` and converts the value.
"""
for lineno, token, value in stream:
if token in ignored_tokens:
continue
elif token == 'linestatement_begin':
token = 'block_begin'
elif token == 'linestatement_end':
token = 'block_end'
# we are not interested in those tokens in the parser
elif token in ('raw_begin', 'raw_end'):
continue
elif token == 'data':
value = self._normalize_newlines(value)
elif token == 'keyword':
token = value
elif token == 'name':
value = str(value)
if check_ident and not value.isidentifier():
raise TemplateSyntaxError(
'Invalid character in identifier',
lineno, name, filename)
elif token == 'string':
# try to unescape string
try:
value = self._normalize_newlines(value[1:-1]) \
.encode('ascii', 'backslashreplace') \
.decode('unicode-escape')
except Exception as e:
msg = str(e).split(':')[-1].strip()
raise TemplateSyntaxError(msg, lineno, name, filename)
elif token == 'integer':
value = int(value)
elif token == 'float':
value = float(value)
elif token == 'operator':
token = operators[value]
yield Token(lineno, token, value) | [
"def",
"wrap",
"(",
"self",
",",
"stream",
",",
"name",
"=",
"None",
",",
"filename",
"=",
"None",
")",
":",
"for",
"lineno",
",",
"token",
",",
"value",
"in",
"stream",
":",
"if",
"token",
"in",
"ignored_tokens",
":",
"continue",
"elif",
"token",
"=... | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/jinja2/lexer.py#L558-L597 | ||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/contrib/session_bundle/exporter.py | python | gfile_copy_callback | (files_to_copy, export_dir_path) | Callback to copy files using `gfile.Copy` to an export directory.
This method is used as the default `assets_callback` in `Exporter.init` to
copy assets from the `assets_collection`. It can also be invoked directly to
copy additional supplementary files into the export directory (in which case
it is not a callback).
Args:
files_to_copy: A dictionary that maps original file paths to desired
basename in the export directory.
export_dir_path: Directory to copy the files to. | Callback to copy files using `gfile.Copy` to an export directory. | [
"Callback",
"to",
"copy",
"files",
"using",
"gfile",
".",
"Copy",
"to",
"an",
"export",
"directory",
"."
] | def gfile_copy_callback(files_to_copy, export_dir_path):
"""Callback to copy files using `gfile.Copy` to an export directory.
This method is used as the default `assets_callback` in `Exporter.init` to
copy assets from the `assets_collection`. It can also be invoked directly to
copy additional supplementary files into the export directory (in which case
it is not a callback).
Args:
files_to_copy: A dictionary that maps original file paths to desired
basename in the export directory.
export_dir_path: Directory to copy the files to.
"""
logging.info("Write assest into: %s using gfile_copy.", export_dir_path)
gfile.MakeDirs(export_dir_path)
for source_filepath, basename in files_to_copy.items():
new_path = os.path.join(
compat.as_bytes(export_dir_path), compat.as_bytes(basename))
logging.info("Copying asset %s to path %s.", source_filepath, new_path)
if gfile.Exists(new_path):
# Guard against being restarted while copying assets, and the file
# existing and being in an unknown state.
# TODO(b/28676216): Do some file checks before deleting.
logging.info("Removing file %s.", new_path)
gfile.Remove(new_path)
gfile.Copy(source_filepath, new_path) | [
"def",
"gfile_copy_callback",
"(",
"files_to_copy",
",",
"export_dir_path",
")",
":",
"logging",
".",
"info",
"(",
"\"Write assest into: %s using gfile_copy.\"",
",",
"export_dir_path",
")",
"gfile",
".",
"MakeDirs",
"(",
"export_dir_path",
")",
"for",
"source_filepath"... | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/session_bundle/exporter.py#L42-L68 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_misc.py | python | DisplayDepth | (*args) | return _misc_.DisplayDepth(*args) | DisplayDepth() -> int | DisplayDepth() -> int | [
"DisplayDepth",
"()",
"-",
">",
"int"
] | def DisplayDepth(*args):
"""DisplayDepth() -> int"""
return _misc_.DisplayDepth(*args) | [
"def",
"DisplayDepth",
"(",
"*",
"args",
")",
":",
"return",
"_misc_",
".",
"DisplayDepth",
"(",
"*",
"args",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L505-L507 | |
asLody/whale | 6a661b27cc4cf83b7b5a3b02451597ee1ac7f264 | whale/cpplint.py | python | _CppLintState.SetFilters | (self, filters) | Sets the error-message filters.
These filters are applied when deciding whether to emit a given
error message.
Args:
filters: A string of comma-separated filters (eg "+whitespace/indent").
Each filter should start with + or -; else we die.
Raises:
ValueError: The comma-separated filters did not all start with '+' or '-'.
E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter" | Sets the error-message filters. | [
"Sets",
"the",
"error",
"-",
"message",
"filters",
"."
] | def SetFilters(self, filters):
"""Sets the error-message filters.
These filters are applied when deciding whether to emit a given
error message.
Args:
filters: A string of comma-separated filters (eg "+whitespace/indent").
Each filter should start with + or -; else we die.
Raises:
ValueError: The comma-separated filters did not all start with '+' or '-'.
E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter"
"""
# Default filters always have less priority than the flag ones.
self.filters = _DEFAULT_FILTERS[:]
self.AddFilters(filters) | [
"def",
"SetFilters",
"(",
"self",
",",
"filters",
")",
":",
"# Default filters always have less priority than the flag ones.",
"self",
".",
"filters",
"=",
"_DEFAULT_FILTERS",
"[",
":",
"]",
"self",
".",
"AddFilters",
"(",
"filters",
")"
] | https://github.com/asLody/whale/blob/6a661b27cc4cf83b7b5a3b02451597ee1ac7f264/whale/cpplint.py#L901-L917 | ||
mamedev/mame | 02cd26d37ee11191f3e311e19e805d872cb1e3a4 | scripts/build/png.py | python | Image.__init__ | (self, rows, info) | .. note ::
The constructor is not public. Please do not call it. | .. note ::
The constructor is not public. Please do not call it. | [
"..",
"note",
"::",
"The",
"constructor",
"is",
"not",
"public",
".",
"Please",
"do",
"not",
"call",
"it",
"."
] | def __init__(self, rows, info):
"""
.. note ::
The constructor is not public. Please do not call it.
"""
self.rows = rows
self.info = info | [
"def",
"__init__",
"(",
"self",
",",
"rows",
",",
"info",
")",
":",
"self",
".",
"rows",
"=",
"rows",
"self",
".",
"info",
"=",
"info"
] | https://github.com/mamedev/mame/blob/02cd26d37ee11191f3e311e19e805d872cb1e3a4/scripts/build/png.py#L1303-L1311 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/Inelastic/Direct/PropertyManager.py | python | PropertyManager.__getattr__ | (self,name) | Overloaded get method, disallowing non-existing properties being get but allowing
a property been called with different names specified in substitution dictionary. | Overloaded get method, disallowing non-existing properties being get but allowing
a property been called with different names specified in substitution dictionary. | [
"Overloaded",
"get",
"method",
"disallowing",
"non",
"-",
"existing",
"properties",
"being",
"get",
"but",
"allowing",
"a",
"property",
"been",
"called",
"with",
"different",
"names",
"specified",
"in",
"substitution",
"dictionary",
"."
] | def __getattr__(self,name):
""" Overloaded get method, disallowing non-existing properties being get but allowing
a property been called with different names specified in substitution dictionary.
"""
if name in self.__subst_dict:
name = self.__subst_dict[name]
return getattr(self,name)
#end
if name in self.__descriptors:
# This can only happen only if descriptor is called through synonims dictionary
# This to work, all descriptors should define getter to return self on Null instance.
descr=getattr(PropertyManager,name)
return descr.__get__(self,name)
else:
return prop_helpers.gen_getter(self.__dict__,name) | [
"def",
"__getattr__",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"in",
"self",
".",
"__subst_dict",
":",
"name",
"=",
"self",
".",
"__subst_dict",
"[",
"name",
"]",
"return",
"getattr",
"(",
"self",
",",
"name",
")",
"#end",
"if",
"name",
"in"... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/Inelastic/Direct/PropertyManager.py#L191-L207 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/distutils/dep_util.py | python | newer_pairwise | (sources, targets) | return n_sources, n_targets | Walk two filename lists in parallel, testing if each source is newer
than its corresponding target. Return a pair of lists (sources,
targets) where source is newer than target, according to the semantics
of 'newer()'. | Walk two filename lists in parallel, testing if each source is newer
than its corresponding target. Return a pair of lists (sources,
targets) where source is newer than target, according to the semantics
of 'newer()'. | [
"Walk",
"two",
"filename",
"lists",
"in",
"parallel",
"testing",
"if",
"each",
"source",
"is",
"newer",
"than",
"its",
"corresponding",
"target",
".",
"Return",
"a",
"pair",
"of",
"lists",
"(",
"sources",
"targets",
")",
"where",
"source",
"is",
"newer",
"... | def newer_pairwise(sources, targets):
"""Walk two filename lists in parallel, testing if each source is newer
than its corresponding target. Return a pair of lists (sources,
targets) where source is newer than target, according to the semantics
of 'newer()'.
"""
if len(sources) != len(targets):
raise ValueError, "'sources' and 'targets' must be same length"
# build a pair of lists (sources, targets) where source is newer
n_sources = []
n_targets = []
for source, target in zip(sources, targets):
if newer(source, target):
n_sources.append(source)
n_targets.append(target)
return n_sources, n_targets | [
"def",
"newer_pairwise",
"(",
"sources",
",",
"targets",
")",
":",
"if",
"len",
"(",
"sources",
")",
"!=",
"len",
"(",
"targets",
")",
":",
"raise",
"ValueError",
",",
"\"'sources' and 'targets' must be same length\"",
"# build a pair of lists (sources, targets) where ... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/distutils/dep_util.py#L33-L50 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | DLG_SZE | (win, size_width, height=None) | Convenience function for converting a Size or (w,h) in
dialog units to pixel units. | Convenience function for converting a Size or (w,h) in
dialog units to pixel units. | [
"Convenience",
"function",
"for",
"converting",
"a",
"Size",
"or",
"(",
"w",
"h",
")",
"in",
"dialog",
"units",
"to",
"pixel",
"units",
"."
] | def DLG_SZE(win, size_width, height=None):
"""
Convenience function for converting a Size or (w,h) in
dialog units to pixel units.
"""
if height is None:
return win.ConvertDialogSizeToPixels(size_width)
else:
return win.ConvertDialogSizeToPixels(wx.Size(size_width, height)) | [
"def",
"DLG_SZE",
"(",
"win",
",",
"size_width",
",",
"height",
"=",
"None",
")",
":",
"if",
"height",
"is",
"None",
":",
"return",
"win",
".",
"ConvertDialogSizeToPixels",
"(",
"size_width",
")",
"else",
":",
"return",
"win",
".",
"ConvertDialogSizeToPixels... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L11791-L11799 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_misc.py | python | Joystick.IsOk | (*args, **kwargs) | return _misc_.Joystick_IsOk(*args, **kwargs) | IsOk(self) -> bool | IsOk(self) -> bool | [
"IsOk",
"(",
"self",
")",
"-",
">",
"bool"
] | def IsOk(*args, **kwargs):
"""IsOk(self) -> bool"""
return _misc_.Joystick_IsOk(*args, **kwargs) | [
"def",
"IsOk",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"Joystick_IsOk",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L2166-L2168 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/layers/python/layers/initializers.py | python | variance_scaling_initializer | (factor=2.0, mode='FAN_IN', uniform=False,
seed=None, dtype=dtypes.float32) | return _initializer | Returns an initializer that generates tensors without scaling variance.
When initializing a deep network, it is in principle advantageous to keep
the scale of the input variance constant, so it does not explode or diminish
by reaching the final layer. This initializer use the following formula:
if mode='FAN_IN': # Count only number of input connections.
n = fan_in
elif mode='FAN_OUT': # Count only number of output connections.
n = fan_out
elif mode='FAN_AVG': # Average number of inputs and output connections.
n = (fan_in + fan_out)/2.0
truncated_normal(shape, 0.0, stddev=sqrt(factor / n))
To get http://arxiv.org/pdf/1502.01852v1.pdf use (Default):
- factor=2.0 mode='FAN_IN' uniform=False
To get http://arxiv.org/abs/1408.5093 use:
- factor=1.0 mode='FAN_IN' uniform=True
To get http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf use:
- factor=1.0 mode='FAN_AVG' uniform=True.
To get xavier_initializer use either:
- factor=1.0 mode='FAN_AVG' uniform=True.
- factor=1.0 mode='FAN_AVG' uniform=False.
Args:
factor: Float. A multiplicative factor.
mode: String. 'FAN_IN', 'FAN_OUT', 'FAN_AVG'.
uniform: Whether to use uniform or normal distributed random initialization.
seed: A Python integer. Used to create random seeds. See
[`set_random_seed`](../../api_docs/python/constant_op.md#set_random_seed)
for behavior.
dtype: The data type. Only floating point types are supported.
Returns:
An initializer that generates tensors with unit variance.
Raises:
ValueError: if `dtype` is not a floating point type.
TypeError: if `mode` is not in ['FAN_IN', 'FAN_OUT', 'FAN_AVG']. | Returns an initializer that generates tensors without scaling variance. | [
"Returns",
"an",
"initializer",
"that",
"generates",
"tensors",
"without",
"scaling",
"variance",
"."
] | def variance_scaling_initializer(factor=2.0, mode='FAN_IN', uniform=False,
seed=None, dtype=dtypes.float32):
"""Returns an initializer that generates tensors without scaling variance.
When initializing a deep network, it is in principle advantageous to keep
the scale of the input variance constant, so it does not explode or diminish
by reaching the final layer. This initializer use the following formula:
if mode='FAN_IN': # Count only number of input connections.
n = fan_in
elif mode='FAN_OUT': # Count only number of output connections.
n = fan_out
elif mode='FAN_AVG': # Average number of inputs and output connections.
n = (fan_in + fan_out)/2.0
truncated_normal(shape, 0.0, stddev=sqrt(factor / n))
To get http://arxiv.org/pdf/1502.01852v1.pdf use (Default):
- factor=2.0 mode='FAN_IN' uniform=False
To get http://arxiv.org/abs/1408.5093 use:
- factor=1.0 mode='FAN_IN' uniform=True
To get http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf use:
- factor=1.0 mode='FAN_AVG' uniform=True.
To get xavier_initializer use either:
- factor=1.0 mode='FAN_AVG' uniform=True.
- factor=1.0 mode='FAN_AVG' uniform=False.
Args:
factor: Float. A multiplicative factor.
mode: String. 'FAN_IN', 'FAN_OUT', 'FAN_AVG'.
uniform: Whether to use uniform or normal distributed random initialization.
seed: A Python integer. Used to create random seeds. See
[`set_random_seed`](../../api_docs/python/constant_op.md#set_random_seed)
for behavior.
dtype: The data type. Only floating point types are supported.
Returns:
An initializer that generates tensors with unit variance.
Raises:
ValueError: if `dtype` is not a floating point type.
TypeError: if `mode` is not in ['FAN_IN', 'FAN_OUT', 'FAN_AVG'].
"""
if not dtype.is_floating:
raise TypeError('Cannot create initializer for non-floating point type.')
if mode not in ['FAN_IN', 'FAN_OUT', 'FAN_AVG']:
raise TypeError('Unknow mode %s [FAN_IN, FAN_OUT, FAN_AVG]', mode)
def _initializer(shape, dtype=dtype):
"""Initializer function."""
if not dtype.is_floating:
raise TypeError('Cannot create initializer for non-floating point type.')
# Estimating fan_in and fan_out is not possible to do perfectly, but we try.
# This is the right thing for matrix multiply and convolutions.
fan_in = float(shape[-2])
fan_out = float(shape[-1])
for dim in shape[:-2]:
fan_in *= float(dim)
fan_out *= float(dim)
if mode == 'FAN_IN':
# Count only number of input connections.
n = fan_in
elif mode == 'FAN_OUT':
# Count only number of output connections.
n = fan_out
elif mode == 'FAN_AVG':
# Average number of inputs and output connections.
n = (fan_in + fan_out) / 2.0
if uniform:
# To get stddev = math.sqrt(factor / n) need to adjust for uniform.
limit = math.sqrt(3.0 * factor / n)
return random_ops.random_uniform(shape, -limit, limit,
dtype, seed=seed)
else:
# To get stddev = math.sqrt(factor / n) need to adjust for truncated.
trunc_stddev = math.sqrt(1.3 * factor / n)
return random_ops.truncated_normal(shape, 0.0, trunc_stddev, dtype,
seed=seed)
return _initializer | [
"def",
"variance_scaling_initializer",
"(",
"factor",
"=",
"2.0",
",",
"mode",
"=",
"'FAN_IN'",
",",
"uniform",
"=",
"False",
",",
"seed",
"=",
"None",
",",
"dtype",
"=",
"dtypes",
".",
"float32",
")",
":",
"if",
"not",
"dtype",
".",
"is_floating",
":",
... | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/layers/python/layers/initializers.py#L62-L139 | |
rdiankov/openrave | d1a23023fd4b58f077d2ca949ceaf1b91f3f13d7 | python/ikfast_sympy0_6.py | python | IKFastSolver.forwardKinematicsChain | (self, chainlinks, chainjoints) | return Links, jointvars | The first and last matrices returned are always non-symbolic | The first and last matrices returned are always non-symbolic | [
"The",
"first",
"and",
"last",
"matrices",
"returned",
"are",
"always",
"non",
"-",
"symbolic"
] | def forwardKinematicsChain(self, chainlinks, chainjoints):
"""The first and last matrices returned are always non-symbolic
"""
with self.kinbody:
assert(len(chainjoints)+1==len(chainlinks))
Links = []
Tright = eye(4)
jointvars = []
jointinds = []
for i,joint in enumerate(chainjoints):
if len(joint.GetName()) == 0:
raise self.CannotSolveError('chain %s:%s contains a joint with no name!'%(chainlinks[0].GetName(),chainlinks[-1].GetName()))
if chainjoints[i].GetHierarchyParentLink() == chainlinks[i]:
TLeftjoint = self.numpyMatrixToSympy(joint.GetInternalHierarchyLeftTransform())
TRightjoint = self.numpyMatrixToSympy(joint.GetInternalHierarchyRightTransform())
axissign = S.One
else:
TLeftjoint = self.affineInverse(self.numpyMatrixToSympy(joint.GetInternalHierarchyRightTransform()))
TRightjoint = self.affineInverse(self.numpyMatrixToSympy(joint.GetInternalHierarchyLeftTransform()))
axissign = -S.One
#print i,TLeftjoint,TRightjoint
if joint.IsStatic():
Tright = self.affineSimplify(Tright * TLeftjoint * TRightjoint)
else:
Tjoints = []
for iaxis in range(joint.GetDOF()):
if joint.GetDOFIndex() >= 0:
var = Symbol(self.axismapinv[joint.GetDOFIndex()])
cosvar = cos(var)
sinvar = sin(var)
jointvars.append(var)
elif joint.IsMimic(iaxis):
# get the mimic equation
var = joint.GetMimicEquation(iaxis)
# this needs to be reduced!
cosvar = cos(var)
sinvar = sin(var)
else:
raise ValueError('cannot solve for mechanism when a non-mimic passive joint %s is in chain'%str(joint))
Tj = eye(4)
jaxis = axissign*self.numpyVectorToSympy(joint.GetInternalHierarchyAxis(iaxis))
if joint.IsRevolute(iaxis):
Tj[0:3,0:3] = self.rodrigues2(jaxis,cosvar,sinvar)
elif joint.IsPrismatic(iaxis):
Tj[0:3,3] = jaxis*(var)
else:
raise ValueError('failed to process joint %s'%joint.GetName())
Tjoints.append(Tj)
if axisAngleFromRotationMatrix is not None:
axisangle = axisAngleFromRotationMatrix(numpy.array(numpy.array(Tright * TLeftjoint),numpy.float64))
angle = sqrt(axisangle[0]**2+axisangle[1]**2+axisangle[2]**2)
axisangle /= angle
log.debug('rotation angle of Links[%d]: %f, axis=[%f,%f,%f]', len(Links), (angle*180/pi).evalf(),axisangle[0],axisangle[1],axisangle[2])
Links.append(Tright * TLeftjoint)
for Tj in Tjoints:
jointinds.append(len(Links))
Links.append(Tj)
Tright = TRightjoint
Links.append(Tright)
# before returning the final links, try to push as much translation components
# outwards to both ends. Sometimes these components can get in the way of detecting
# intersecting axes
if len(jointinds) > 0:
iright = jointinds[-1]
Ttrans = eye(4)
Ttrans[0:3,3] = Links[iright-1][0:3,0:3].transpose() * Links[iright-1][0:3,3]
Trot_with_trans = Ttrans * Links[iright]
separated_trans = Trot_with_trans[0:3,0:3].transpose() * Trot_with_trans[0:3,3]
for j in range(0,3):
if separated_trans[j].has_any_symbols(*jointvars):
Ttrans[j,3] = Rational(0)
else:
Ttrans[j,3] = separated_trans[j]
Links[iright+1] = Ttrans * Links[iright+1]
Links[iright-1] = Links[iright-1] * self.affineInverse(Ttrans)
log.info("moved translation %s to right end",Ttrans[0:3,3].transpose())
if len(jointinds) > 1:
ileft = jointinds[0]
separated_trans = Links[ileft][0:3,0:3] * Links[ileft+1][0:3,3]
Ttrans = eye(4)
for j in range(0,3):
if not separated_trans[j].has_any_symbols(*jointvars):
Ttrans[j,3] = separated_trans[j]
Links[ileft-1] = Links[ileft-1] * Ttrans
Links[ileft+1] = self.affineInverse(Ttrans) * Links[ileft+1]
log.info("moved translation %s to left end",Ttrans[0:3,3].transpose())
if len(jointinds) > 3: # last 3 axes always have to be intersecting, move the translation of the first axis to the left
ileft = jointinds[-3]
separated_trans = Links[ileft][0:3,0:3] * Links[ileft+1][0:3,3]
Ttrans = eye(4)
for j in range(0,3):
if not separated_trans[j].has_any_symbols(*jointvars):
Ttrans[j,3] = separated_trans[j]
Links[ileft-1] = Links[ileft-1] * Ttrans
Links[ileft+1] = self.affineInverse(Ttrans) * Links[ileft+1]
log.info("moved translation on intersecting axis %s to left",Ttrans[0:3,3].transpose())
return Links, jointvars | [
"def",
"forwardKinematicsChain",
"(",
"self",
",",
"chainlinks",
",",
"chainjoints",
")",
":",
"with",
"self",
".",
"kinbody",
":",
"assert",
"(",
"len",
"(",
"chainjoints",
")",
"+",
"1",
"==",
"len",
"(",
"chainlinks",
")",
")",
"Links",
"=",
"[",
"]... | https://github.com/rdiankov/openrave/blob/d1a23023fd4b58f077d2ca949ceaf1b91f3f13d7/python/ikfast_sympy0_6.py#L1193-L1297 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/html.py | python | HtmlCellEvent.SetLinkClicked | (*args, **kwargs) | return _html.HtmlCellEvent_SetLinkClicked(*args, **kwargs) | SetLinkClicked(self, bool linkclicked) | SetLinkClicked(self, bool linkclicked) | [
"SetLinkClicked",
"(",
"self",
"bool",
"linkclicked",
")"
] | def SetLinkClicked(*args, **kwargs):
"""SetLinkClicked(self, bool linkclicked)"""
return _html.HtmlCellEvent_SetLinkClicked(*args, **kwargs) | [
"def",
"SetLinkClicked",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_html",
".",
"HtmlCellEvent_SetLinkClicked",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/html.py#L1702-L1704 | |
1989Ryan/Semantic_SLAM | 0284b3f832ca431c494f9c134fe46c40ec86ee38 | Third_Part/PSPNet_Keras_tensorflow/layers_builder.py | python | ResNet | (inp, layers) | return res | Modify_stride --Used only once in first 3_1 convolutions block.
changes stride of first convolution from 1 -> 2 | Modify_stride --Used only once in first 3_1 convolutions block.
changes stride of first convolution from 1 -> 2 | [
"Modify_stride",
"--",
"Used",
"only",
"once",
"in",
"first",
"3_1",
"convolutions",
"block",
".",
"changes",
"stride",
"of",
"first",
"convolution",
"from",
"1",
"-",
">",
"2"
] | def ResNet(inp, layers):
# Names for the first couple layers of model
names = ["conv1_1_3x3_s2",
"conv1_1_3x3_s2_bn",
"conv1_2_3x3",
"conv1_2_3x3_bn",
"conv1_3_3x3",
"conv1_3_3x3_bn"]
# Short branch(only start of network)
cnv1 = Conv2D(64, (3, 3), strides=(2, 2), padding='same', name=names[0],
use_bias=False)(inp) # "conv1_1_3x3_s2"
bn1 = BN(name=names[1])(cnv1) # "conv1_1_3x3_s2/bn"
relu1 = Activation('relu')(bn1) # "conv1_1_3x3_s2/relu"
cnv1 = Conv2D(64, (3, 3), strides=(1, 1), padding='same', name=names[2],
use_bias=False)(relu1) # "conv1_2_3x3"
bn1 = BN(name=names[3])(cnv1) # "conv1_2_3x3/bn"
relu1 = Activation('relu')(bn1) # "conv1_2_3x3/relu"
cnv1 = Conv2D(128, (3, 3), strides=(1, 1), padding='same', name=names[4],
use_bias=False)(relu1) # "conv1_3_3x3"
bn1 = BN(name=names[5])(cnv1) # "conv1_3_3x3/bn"
relu1 = Activation('relu')(bn1) # "conv1_3_3x3/relu"
res = MaxPooling2D(pool_size=(3, 3), padding='same',
strides=(2, 2))(relu1) # "pool1_3x3_s2"
# ---Residual layers(body of network)
"""
Modify_stride --Used only once in first 3_1 convolutions block.
changes stride of first convolution from 1 -> 2
"""
# 2_1- 2_3
res = residual_short(res, 1, pad=1, lvl=2, sub_lvl=1)
for i in range(2):
res = residual_empty(res, 1, pad=1, lvl=2, sub_lvl=i + 2)
# 3_1 - 3_3
res = residual_short(res, 2, pad=1, lvl=3, sub_lvl=1, modify_stride=True)
for i in range(3):
res = residual_empty(res, 2, pad=1, lvl=3, sub_lvl=i + 2)
if layers is 50:
# 4_1 - 4_6
res = residual_short(res, 4, pad=2, lvl=4, sub_lvl=1)
for i in range(5):
res = residual_empty(res, 4, pad=2, lvl=4, sub_lvl=i + 2)
elif layers is 101:
# 4_1 - 4_23
res = residual_short(res, 4, pad=2, lvl=4, sub_lvl=1)
for i in range(22):
res = residual_empty(res, 4, pad=2, lvl=4, sub_lvl=i + 2)
else:
print("This ResNet is not implemented")
# 5_1 - 5_3
res = residual_short(res, 8, pad=4, lvl=5, sub_lvl=1)
for i in range(2):
res = residual_empty(res, 8, pad=4, lvl=5, sub_lvl=i + 2)
res = Activation('relu')(res)
return res | [
"def",
"ResNet",
"(",
"inp",
",",
"layers",
")",
":",
"# Names for the first couple layers of model",
"names",
"=",
"[",
"\"conv1_1_3x3_s2\"",
",",
"\"conv1_1_3x3_s2_bn\"",
",",
"\"conv1_2_3x3\"",
",",
"\"conv1_2_3x3_bn\"",
",",
"\"conv1_3_3x3\"",
",",
"\"conv1_3_3x3_bn\"... | https://github.com/1989Ryan/Semantic_SLAM/blob/0284b3f832ca431c494f9c134fe46c40ec86ee38/Third_Part/PSPNet_Keras_tensorflow/layers_builder.py#L127-L191 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/applications/workbench/workbench/widgets/plotselector/view.py | python | PlotNameWidget.toggle_visibility | (self) | Calls the presenter to hide the selected plot | Calls the presenter to hide the selected plot | [
"Calls",
"the",
"presenter",
"to",
"hide",
"the",
"selected",
"plot"
] | def toggle_visibility(self):
"""
Calls the presenter to hide the selected plot
"""
self.presenter.toggle_plot_visibility(self.plot_number) | [
"def",
"toggle_visibility",
"(",
"self",
")",
":",
"self",
".",
"presenter",
".",
"toggle_plot_visibility",
"(",
"self",
".",
"plot_number",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/applications/workbench/workbench/widgets/plotselector/view.py#L724-L728 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/dataset/audio/validators.py | python | check_biquad_noise | (noise) | Wrapper method to check the parameters of noise. | Wrapper method to check the parameters of noise. | [
"Wrapper",
"method",
"to",
"check",
"the",
"parameters",
"of",
"noise",
"."
] | def check_biquad_noise(noise):
"""Wrapper method to check the parameters of noise."""
type_check(noise, (bool,), "noise") | [
"def",
"check_biquad_noise",
"(",
"noise",
")",
":",
"type_check",
"(",
"noise",
",",
"(",
"bool",
",",
")",
",",
"\"noise\"",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/dataset/audio/validators.py#L71-L73 | ||
weichengkuo/DeepBox | c4f8c065b6a51cf296540cc453a44f0519aaacc9 | caffe-fast-rcnn/scripts/cpp_lint.py | python | _BlockInfo.CheckEnd | (self, filename, clean_lines, linenum, error) | Run checks that applies to text after the closing brace.
This is mostly used for checking end of namespace comments.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Run checks that applies to text after the closing brace. | [
"Run",
"checks",
"that",
"applies",
"to",
"text",
"after",
"the",
"closing",
"brace",
"."
] | def CheckEnd(self, filename, clean_lines, linenum, error):
"""Run checks that applies to text after the closing brace.
This is mostly used for checking end of namespace comments.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
pass | [
"def",
"CheckEnd",
"(",
"self",
",",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"pass"
] | https://github.com/weichengkuo/DeepBox/blob/c4f8c065b6a51cf296540cc453a44f0519aaacc9/caffe-fast-rcnn/scripts/cpp_lint.py#L1778-L1789 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/mailbox.py | python | MH.get_bytes | (self, key) | Return a bytes representation or raise a KeyError. | Return a bytes representation or raise a KeyError. | [
"Return",
"a",
"bytes",
"representation",
"or",
"raise",
"a",
"KeyError",
"."
] | def get_bytes(self, key):
"""Return a bytes representation or raise a KeyError."""
try:
if self._locked:
f = open(os.path.join(self._path, str(key)), 'rb+')
else:
f = open(os.path.join(self._path, str(key)), 'rb')
except OSError as e:
if e.errno == errno.ENOENT:
raise KeyError('No message with key: %s' % key)
else:
raise
with f:
if self._locked:
_lock_file(f)
try:
return f.read().replace(linesep, b'\n')
finally:
if self._locked:
_unlock_file(f) | [
"def",
"get_bytes",
"(",
"self",
",",
"key",
")",
":",
"try",
":",
"if",
"self",
".",
"_locked",
":",
"f",
"=",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_path",
",",
"str",
"(",
"key",
")",
")",
",",
"'rb+'",
")",
"else... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/mailbox.py#L1047-L1066 | ||
Samsung/veles | 95ed733c2e49bc011ad98ccf2416ecec23fbf352 | veles/server.py | python | VelesProtocol._checkQuery | (self, msg) | return True | Respond to possible informational requests. | Respond to possible informational requests. | [
"Respond",
"to",
"possible",
"informational",
"requests",
"."
] | def _checkQuery(self, msg):
"""Respond to possible informational requests.
"""
query = msg.get('query')
if query is None:
return False
self._not_a_slave = True
checksum = msg.get('workflow')
if checksum is None:
self._sendError("Workflow checksum was not specified")
return True
valid_checksum = self.host.workflow.checksum
if checksum != valid_checksum:
self._sendError("Workflow checksum mismatch: mine is %s" %
valid_checksum)
return True
responders = {"nodes": lambda _: self.sendLine(self.host.active_nodes),
"endpoints":
lambda _: self.sendLine(self.host.zmq_endpoints)}
responder = responders.get(query)
self.info(self.nodes)
if responder is None:
self._sendError("%s query is not supported" % query)
else:
self.info("Fulfilled query \"%s\"", query)
responder(msg)
return True | [
"def",
"_checkQuery",
"(",
"self",
",",
"msg",
")",
":",
"query",
"=",
"msg",
".",
"get",
"(",
"'query'",
")",
"if",
"query",
"is",
"None",
":",
"return",
"False",
"self",
".",
"_not_a_slave",
"=",
"True",
"checksum",
"=",
"msg",
".",
"get",
"(",
"... | https://github.com/Samsung/veles/blob/95ed733c2e49bc011ad98ccf2416ecec23fbf352/veles/server.py#L450-L476 | |
generalized-intelligence/GAAS | 29ab17d3e8a4ba18edef3a57c36d8db6329fac73 | deprecated/algorithms/sfm/OpenSfM/opensfm/dataset.py | python | DataSet._camera_models_overrides_file | (self) | return os.path.join(self.data_path, 'camera_models_overrides.json') | Path to the camera model overrides file. | Path to the camera model overrides file. | [
"Path",
"to",
"the",
"camera",
"model",
"overrides",
"file",
"."
] | def _camera_models_overrides_file(self):
"""Path to the camera model overrides file."""
return os.path.join(self.data_path, 'camera_models_overrides.json') | [
"def",
"_camera_models_overrides_file",
"(",
"self",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"data_path",
",",
"'camera_models_overrides.json'",
")"
] | https://github.com/generalized-intelligence/GAAS/blob/29ab17d3e8a4ba18edef3a57c36d8db6329fac73/deprecated/algorithms/sfm/OpenSfM/opensfm/dataset.py#L650-L652 | |
acbull/Unbiased_LambdaMart | 7c39abe5caa18ca07df2d23c2db392916d92956c | Unbias_LightGBM/python-package/lightgbm/sklearn.py | python | LGBMModel.best_score_ | (self) | return self._best_score | Get the best score of fitted model. | Get the best score of fitted model. | [
"Get",
"the",
"best",
"score",
"of",
"fitted",
"model",
"."
] | def best_score_(self):
"""Get the best score of fitted model."""
if self._n_features is None:
raise LGBMNotFittedError('No best_score found. Need to call fit beforehand.')
return self._best_score | [
"def",
"best_score_",
"(",
"self",
")",
":",
"if",
"self",
".",
"_n_features",
"is",
"None",
":",
"raise",
"LGBMNotFittedError",
"(",
"'No best_score found. Need to call fit beforehand.'",
")",
"return",
"self",
".",
"_best_score"
] | https://github.com/acbull/Unbiased_LambdaMart/blob/7c39abe5caa18ca07df2d23c2db392916d92956c/Unbias_LightGBM/python-package/lightgbm/sklearn.py#L567-L571 | |
rbgirshick/caffe-fast-rcnn | 28a579eaf0668850705598b3075b8969f22226d9 | scripts/cpp_lint.py | python | FindNextMultiLineCommentEnd | (lines, lineix) | return len(lines) | We are inside a comment, find the end marker. | We are inside a comment, find the end marker. | [
"We",
"are",
"inside",
"a",
"comment",
"find",
"the",
"end",
"marker",
"."
] | def FindNextMultiLineCommentEnd(lines, lineix):
"""We are inside a comment, find the end marker."""
while lineix < len(lines):
if lines[lineix].strip().endswith('*/'):
return lineix
lineix += 1
return len(lines) | [
"def",
"FindNextMultiLineCommentEnd",
"(",
"lines",
",",
"lineix",
")",
":",
"while",
"lineix",
"<",
"len",
"(",
"lines",
")",
":",
"if",
"lines",
"[",
"lineix",
"]",
".",
"strip",
"(",
")",
".",
"endswith",
"(",
"'*/'",
")",
":",
"return",
"lineix",
... | https://github.com/rbgirshick/caffe-fast-rcnn/blob/28a579eaf0668850705598b3075b8969f22226d9/scripts/cpp_lint.py#L1134-L1140 | |
facebook/fbthrift | fb9c8562aba04c4fd9b17716eb5d970cc88a75bb | build/fbcode_builder/getdeps/envfuncs.py | python | add_path_entry | (env, name, item, append=True, separator=os.pathsep) | Cause `item` to be added to the path style env var named
`name` held in the `env` dict. `append` specifies whether
the item is added to the end (the default) or should be
prepended if `name` already exists. | Cause `item` to be added to the path style env var named
`name` held in the `env` dict. `append` specifies whether
the item is added to the end (the default) or should be
prepended if `name` already exists. | [
"Cause",
"item",
"to",
"be",
"added",
"to",
"the",
"path",
"style",
"env",
"var",
"named",
"name",
"held",
"in",
"the",
"env",
"dict",
".",
"append",
"specifies",
"whether",
"the",
"item",
"is",
"added",
"to",
"the",
"end",
"(",
"the",
"default",
")",
... | def add_path_entry(env, name, item, append=True, separator=os.pathsep):
"""Cause `item` to be added to the path style env var named
`name` held in the `env` dict. `append` specifies whether
the item is added to the end (the default) or should be
prepended if `name` already exists."""
val = env.get(name, "")
if len(val) > 0:
val = val.split(separator)
else:
val = []
if append:
val.append(item)
else:
val.insert(0, item)
env.set(name, separator.join(val)) | [
"def",
"add_path_entry",
"(",
"env",
",",
"name",
",",
"item",
",",
"append",
"=",
"True",
",",
"separator",
"=",
"os",
".",
"pathsep",
")",
":",
"val",
"=",
"env",
".",
"get",
"(",
"name",
",",
"\"\"",
")",
"if",
"len",
"(",
"val",
")",
">",
"... | https://github.com/facebook/fbthrift/blob/fb9c8562aba04c4fd9b17716eb5d970cc88a75bb/build/fbcode_builder/getdeps/envfuncs.py#L121-L135 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/ttk.py | python | Treeview.column | (self, column, option=None, **kw) | return _val_or_dict(self.tk, kw, self._w, "column", column) | Query or modify the options for the specified column.
If kw is not given, returns a dict of the column option values. If
option is specified then the value for that option is returned.
Otherwise, sets the options to the corresponding values. | Query or modify the options for the specified column. | [
"Query",
"or",
"modify",
"the",
"options",
"for",
"the",
"specified",
"column",
"."
] | def column(self, column, option=None, **kw):
"""Query or modify the options for the specified column.
If kw is not given, returns a dict of the column option values. If
option is specified then the value for that option is returned.
Otherwise, sets the options to the corresponding values."""
if option is not None:
kw[option] = None
return _val_or_dict(self.tk, kw, self._w, "column", column) | [
"def",
"column",
"(",
"self",
",",
"column",
",",
"option",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"if",
"option",
"is",
"not",
"None",
":",
"kw",
"[",
"option",
"]",
"=",
"None",
"return",
"_val_or_dict",
"(",
"self",
".",
"tk",
",",
"kw",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/ttk.py#L1239-L1247 | |
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/contributed/sumopy/agilepy/lib_wx/objpanel.py | python | ChecklistWidgetContainer.set_widgetvalue | (self, val) | Sets value for valuewidget.
Depends on attribute type and hence widgettype.
To be overwritten. | Sets value for valuewidget.
Depends on attribute type and hence widgettype.
To be overwritten. | [
"Sets",
"value",
"for",
"valuewidget",
".",
"Depends",
"on",
"attribute",
"type",
"and",
"hence",
"widgettype",
".",
"To",
"be",
"overwritten",
"."
] | def set_widgetvalue(self, val):
"""
Sets value for valuewidget.
Depends on attribute type and hence widgettype.
To be overwritten.
"""
if self._attrconf.is_writable():
self.set_checkbox(self.valuewidget, val)
else:
self.valuewidget.SetValue(str(val)) | [
"def",
"set_widgetvalue",
"(",
"self",
",",
"val",
")",
":",
"if",
"self",
".",
"_attrconf",
".",
"is_writable",
"(",
")",
":",
"self",
".",
"set_checkbox",
"(",
"self",
".",
"valuewidget",
",",
"val",
")",
"else",
":",
"self",
".",
"valuewidget",
".",... | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/agilepy/lib_wx/objpanel.py#L1002-L1011 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/email/charset.py | python | Charset.header_encode_lines | (self, string, maxlengths) | return lines | Header-encode a string by converting it first to bytes.
This is similar to `header_encode()` except that the string is fit
into maximum line lengths as given by the argument.
:param string: A unicode string for the header. It must be possible
to encode this string to bytes using the character set's
output codec.
:param maxlengths: Maximum line length iterator. Each element
returned from this iterator will provide the next maximum line
length. This parameter is used as an argument to built-in next()
and should never be exhausted. The maximum line lengths should
not count the RFC 2047 chrome. These line lengths are only a
hint; the splitter does the best it can.
:return: Lines of encoded strings, each with RFC 2047 chrome. | Header-encode a string by converting it first to bytes. | [
"Header",
"-",
"encode",
"a",
"string",
"by",
"converting",
"it",
"first",
"to",
"bytes",
"."
] | def header_encode_lines(self, string, maxlengths):
"""Header-encode a string by converting it first to bytes.
This is similar to `header_encode()` except that the string is fit
into maximum line lengths as given by the argument.
:param string: A unicode string for the header. It must be possible
to encode this string to bytes using the character set's
output codec.
:param maxlengths: Maximum line length iterator. Each element
returned from this iterator will provide the next maximum line
length. This parameter is used as an argument to built-in next()
and should never be exhausted. The maximum line lengths should
not count the RFC 2047 chrome. These line lengths are only a
hint; the splitter does the best it can.
:return: Lines of encoded strings, each with RFC 2047 chrome.
"""
# See which encoding we should use.
codec = self.output_codec or 'us-ascii'
header_bytes = _encode(string, codec)
encoder_module = self._get_encoder(header_bytes)
encoder = partial(encoder_module.header_encode, charset=codec)
# Calculate the number of characters that the RFC 2047 chrome will
# contribute to each line.
charset = self.get_output_charset()
extra = len(charset) + RFC2047_CHROME_LEN
# Now comes the hard part. We must encode bytes but we can't split on
# bytes because some character sets are variable length and each
# encoded word must stand on its own. So the problem is you have to
# encode to bytes to figure out this word's length, but you must split
# on characters. This causes two problems: first, we don't know how
# many octets a specific substring of unicode characters will get
# encoded to, and second, we don't know how many ASCII characters
# those octets will get encoded to. Unless we try it. Which seems
# inefficient. In the interest of being correct rather than fast (and
# in the hope that there will be few encoded headers in any such
# message), brute force it. :(
lines = []
current_line = []
maxlen = next(maxlengths) - extra
for character in string:
current_line.append(character)
this_line = EMPTYSTRING.join(current_line)
length = encoder_module.header_length(_encode(this_line, charset))
if length > maxlen:
# This last character doesn't fit so pop it off.
current_line.pop()
# Does nothing fit on the first line?
if not lines and not current_line:
lines.append(None)
else:
separator = (' ' if lines else '')
joined_line = EMPTYSTRING.join(current_line)
header_bytes = _encode(joined_line, codec)
lines.append(encoder(header_bytes))
current_line = [character]
maxlen = next(maxlengths) - extra
joined_line = EMPTYSTRING.join(current_line)
header_bytes = _encode(joined_line, codec)
lines.append(encoder(header_bytes))
return lines | [
"def",
"header_encode_lines",
"(",
"self",
",",
"string",
",",
"maxlengths",
")",
":",
"# See which encoding we should use.",
"codec",
"=",
"self",
".",
"output_codec",
"or",
"'us-ascii'",
"header_bytes",
"=",
"_encode",
"(",
"string",
",",
"codec",
")",
"encoder_... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/email/charset.py#L298-L358 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/sparse/linalg/interface.py | python | LinearOperator._init_dtype | (self) | Called from subclasses at the end of the __init__ routine. | Called from subclasses at the end of the __init__ routine. | [
"Called",
"from",
"subclasses",
"at",
"the",
"end",
"of",
"the",
"__init__",
"routine",
"."
] | def _init_dtype(self):
"""Called from subclasses at the end of the __init__ routine.
"""
if self.dtype is None:
v = np.zeros(self.shape[-1])
self.dtype = np.asarray(self.matvec(v)).dtype | [
"def",
"_init_dtype",
"(",
"self",
")",
":",
"if",
"self",
".",
"dtype",
"is",
"None",
":",
"v",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"shape",
"[",
"-",
"1",
"]",
")",
"self",
".",
"dtype",
"=",
"np",
".",
"asarray",
"(",
"self",
".",
"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/sparse/linalg/interface.py#L163-L168 | ||
apache/arrow | af33dd1157eb8d7d9bfac25ebf61445b793b7943 | python/pyarrow/util.py | python | product | (seq) | return functools.reduce(lambda a, b: a*b, seq, 1) | Return a product of sequence items. | Return a product of sequence items. | [
"Return",
"a",
"product",
"of",
"sequence",
"items",
"."
] | def product(seq):
"""
Return a product of sequence items.
"""
return functools.reduce(lambda a, b: a*b, seq, 1) | [
"def",
"product",
"(",
"seq",
")",
":",
"return",
"functools",
".",
"reduce",
"(",
"lambda",
"a",
",",
"b",
":",
"a",
"*",
"b",
",",
"seq",
",",
"1",
")"
] | https://github.com/apache/arrow/blob/af33dd1157eb8d7d9bfac25ebf61445b793b7943/python/pyarrow/util.py#L95-L99 | |
sonyxperiadev/WebGL | 0299b38196f78c6d5f74bcf6fa312a3daee6de60 | Tools/Scripts/webkitpy/style/checkers/cpp.py | python | check_switch_indentation | (clean_lines, line_number, error) | Looks for indentation errors inside of switch statements.
Args:
clean_lines: A CleansedLines instance containing the file.
line_number: The number of the line to check.
error: The function to call with any errors found. | Looks for indentation errors inside of switch statements. | [
"Looks",
"for",
"indentation",
"errors",
"inside",
"of",
"switch",
"statements",
"."
] | def check_switch_indentation(clean_lines, line_number, error):
"""Looks for indentation errors inside of switch statements.
Args:
clean_lines: A CleansedLines instance containing the file.
line_number: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[line_number] # Get rid of comments and strings.
switch_match = match(r'(?P<switch_indentation>\s*)switch\s*\(.+\)\s*{\s*$', line)
if not switch_match:
return
switch_indentation = switch_match.group('switch_indentation')
inner_indentation = switch_indentation + ' ' * 4
line_offset = 0
encountered_nested_switch = False
for current_line in clean_lines.elided[line_number + 1:]:
line_offset += 1
# Skip not only empty lines but also those with preprocessor directives.
if current_line.strip() == '' or current_line.startswith('#'):
continue
if match(r'\s*switch\s*\(.+\)\s*{\s*$', current_line):
# Complexity alarm - another switch statement nested inside the one
# that we're currently testing. We'll need to track the extent of
# that inner switch if the upcoming label tests are still supposed
# to work correctly. Let's not do that; instead, we'll finish
# checking this line, and then leave it like that. Assuming the
# indentation is done consistently (even if incorrectly), this will
# still catch all indentation issues in practice.
encountered_nested_switch = True
current_indentation_match = match(r'(?P<indentation>\s*)(?P<remaining_line>.*)$', current_line);
current_indentation = current_indentation_match.group('indentation')
remaining_line = current_indentation_match.group('remaining_line')
# End the check at the end of the switch statement.
if remaining_line.startswith('}') and current_indentation == switch_indentation:
break
# Case and default branches should not be indented. The regexp also
# catches single-line cases like "default: break;" but does not trigger
# on stuff like "Document::Foo();".
elif match(r'(default|case\s+.*)\s*:([^:].*)?$', remaining_line):
if current_indentation != switch_indentation:
error(line_number + line_offset, 'whitespace/indent', 4,
'A case label should not be indented, but line up with its switch statement.')
# Don't throw an error for multiple badly indented labels,
# one should be enough to figure out the problem.
break
# We ignore goto labels at the very beginning of a line.
elif match(r'\w+\s*:\s*$', remaining_line):
continue
# It's not a goto label, so check if it's indented at least as far as
# the switch statement plus one more level of indentation.
elif not current_indentation.startswith(inner_indentation):
error(line_number + line_offset, 'whitespace/indent', 4,
'Non-label code inside switch statements should be indented.')
# Don't throw an error for multiple badly indented statements,
# one should be enough to figure out the problem.
break
if encountered_nested_switch:
break | [
"def",
"check_switch_indentation",
"(",
"clean_lines",
",",
"line_number",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"line_number",
"]",
"# Get rid of comments and strings.",
"switch_match",
"=",
"match",
"(",
"r'(?P<switch_indentation>\\s*... | https://github.com/sonyxperiadev/WebGL/blob/0299b38196f78c6d5f74bcf6fa312a3daee6de60/Tools/Scripts/webkitpy/style/checkers/cpp.py#L2029-L2096 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | contrib/gizmos/osx_carbon/gizmos.py | python | TreeListCtrl.GetColumn | (*args, **kwargs) | return _gizmos.TreeListCtrl_GetColumn(*args, **kwargs) | GetColumn(self, int column) -> TreeListColumnInfo | GetColumn(self, int column) -> TreeListColumnInfo | [
"GetColumn",
"(",
"self",
"int",
"column",
")",
"-",
">",
"TreeListColumnInfo"
] | def GetColumn(*args, **kwargs):
"""GetColumn(self, int column) -> TreeListColumnInfo"""
return _gizmos.TreeListCtrl_GetColumn(*args, **kwargs) | [
"def",
"GetColumn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gizmos",
".",
"TreeListCtrl_GetColumn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/gizmos/osx_carbon/gizmos.py#L598-L600 | |
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py | python | valuePop | (ctxt) | return ret | Pops the top XPath object from the value stack | Pops the top XPath object from the value stack | [
"Pops",
"the",
"top",
"XPath",
"object",
"from",
"the",
"value",
"stack"
] | def valuePop(ctxt):
"""Pops the top XPath object from the value stack """
if ctxt is None: ctxt__o = None
else: ctxt__o = ctxt._o
ret = libxml2mod.valuePop(ctxt__o)
return ret | [
"def",
"valuePop",
"(",
"ctxt",
")",
":",
"if",
"ctxt",
"is",
"None",
":",
"ctxt__o",
"=",
"None",
"else",
":",
"ctxt__o",
"=",
"ctxt",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"valuePop",
"(",
"ctxt__o",
")",
"return",
"ret"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L3010-L3015 | |
Kitware/ParaView | f760af9124ff4634b23ebbeab95a4f56e0261955 | Plugins/pvblot/blotish.py | python | solid | () | Sets the view to solid mesh mode, which paints each element using a
different color for each element block. | Sets the view to solid mesh mode, which paints each element using a
different color for each element block. | [
"Sets",
"the",
"view",
"to",
"solid",
"mesh",
"mode",
"which",
"paints",
"each",
"element",
"using",
"a",
"different",
"color",
"for",
"each",
"element",
"block",
"."
] | def solid():
"""
Sets the view to solid mesh mode, which paints each element using a
different color for each element block.
"""
print " Solid mesh plot"
print
state.resetPipeline()
state.msurface = 1
todraw = _updateMeshRender()
paraview.simple.SetDisplayProperties(todraw,
ColorAttributeType=state._block_id_field,
ColorArrayName=state._block_id_variable,
LookupTable=state.blockLookupTable)
_finish_plot_change() | [
"def",
"solid",
"(",
")",
":",
"print",
"\" Solid mesh plot\"",
"print",
"state",
".",
"resetPipeline",
"(",
")",
"state",
".",
"msurface",
"=",
"1",
"todraw",
"=",
"_updateMeshRender",
"(",
")",
"paraview",
".",
"simple",
".",
"SetDisplayProperties",
"(",
"... | https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/Plugins/pvblot/blotish.py#L684-L698 | ||
bareos/bareos | 56a10bb368b0a81e977bb51304033fe49d59efb0 | restapi/bareos_restapi/__init__.py | python | read_fileset_by_name | (
*,
response: Response,
current_user: User = Depends(get_current_user),
filesets_name: str = Path(..., title="fileset name to look for"),
verbose: Optional[bareosBool] = Query("yes", title="Verbose output"),
) | return show_configuration_items(
response=response,
current_user=current_user,
itemType="filesets",
byName=filesets_name,
verbose=verbose,
) | Read all jobdef resources. Built on console command _show filesets_.
Needs at least Bareos Version >= 20.0.0 | Read all jobdef resources. Built on console command _show filesets_. | [
"Read",
"all",
"jobdef",
"resources",
".",
"Built",
"on",
"console",
"command",
"_show",
"filesets_",
"."
] | def read_fileset_by_name(
*,
response: Response,
current_user: User = Depends(get_current_user),
filesets_name: str = Path(..., title="fileset name to look for"),
verbose: Optional[bareosBool] = Query("yes", title="Verbose output"),
):
"""
Read all jobdef resources. Built on console command _show filesets_.
Needs at least Bareos Version >= 20.0.0
"""
return show_configuration_items(
response=response,
current_user=current_user,
itemType="filesets",
byName=filesets_name,
verbose=verbose,
) | [
"def",
"read_fileset_by_name",
"(",
"*",
",",
"response",
":",
"Response",
",",
"current_user",
":",
"User",
"=",
"Depends",
"(",
"get_current_user",
")",
",",
"filesets_name",
":",
"str",
"=",
"Path",
"(",
"...",
",",
"title",
"=",
"\"fileset name to look for... | https://github.com/bareos/bareos/blob/56a10bb368b0a81e977bb51304033fe49d59efb0/restapi/bareos_restapi/__init__.py#L613-L631 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_core.py | python | ImageHandler.SetExtension | (*args, **kwargs) | return _core_.ImageHandler_SetExtension(*args, **kwargs) | SetExtension(self, String extension) | SetExtension(self, String extension) | [
"SetExtension",
"(",
"self",
"String",
"extension",
")"
] | def SetExtension(*args, **kwargs):
"""SetExtension(self, String extension)"""
return _core_.ImageHandler_SetExtension(*args, **kwargs) | [
"def",
"SetExtension",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"ImageHandler_SetExtension",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L2652-L2654 | |
ceph/ceph | 959663007321a369c83218414a29bd9dbc8bda3a | qa/tasks/rgw_logsocket.py | python | _config_user | (s3tests_conf, section, user) | return s3tests._config_user(s3tests_conf, section, user) | Run s3tests user config function | Run s3tests user config function | [
"Run",
"s3tests",
"user",
"config",
"function"
] | def _config_user(s3tests_conf, section, user):
"""
Run s3tests user config function
"""
return s3tests._config_user(s3tests_conf, section, user) | [
"def",
"_config_user",
"(",
"s3tests_conf",
",",
"section",
",",
"user",
")",
":",
"return",
"s3tests",
".",
"_config_user",
"(",
"s3tests_conf",
",",
"section",
",",
"user",
")"
] | https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/qa/tasks/rgw_logsocket.py#L23-L27 | |
lammps/lammps | b75c3065430a75b1b5543a10e10f46d9b4c91913 | tools/i-pi/ipi/inputs/thermostats.py | python | InputThermo.fetch | (self) | return thermo | Creates a thermostat object.
Returns:
A thermostat object of the appropriate type and with the appropriate
parameters given the attributes of the InputThermo object.
Raises:
TypeError: Raised if the thermostat type is not a recognized option. | Creates a thermostat object. | [
"Creates",
"a",
"thermostat",
"object",
"."
] | def fetch(self):
"""Creates a thermostat object.
Returns:
A thermostat object of the appropriate type and with the appropriate
parameters given the attributes of the InputThermo object.
Raises:
TypeError: Raised if the thermostat type is not a recognized option.
"""
super(InputThermo,self).fetch()
if self.mode.fetch() == "langevin":
thermo = ThermoLangevin(tau=self.tau.fetch())
elif self.mode.fetch() == "svr":
thermo = ThermoSVR(tau=self.tau.fetch())
elif self.mode.fetch() == "pile_l":
thermo = ThermoPILE_L(tau=self.tau.fetch(), scale=self.pile_scale.fetch())
elif self.mode.fetch() == "pile_g":
thermo = ThermoPILE_G(tau=self.tau.fetch(), scale=self.pile_scale.fetch())
elif self.mode.fetch() == "gle":
rC = self.C.fetch()
if len(rC) == 0:
rC = None
thermo = ThermoGLE(A=self.A.fetch(),C=rC)
thermo.s = self.s.fetch()
elif self.mode.fetch() == "nm_gle":
rC = self.C.fetch()
if len(rC) == 0:
rC = None
thermo = ThermoNMGLE(A=self.A.fetch(),C=rC)
thermo.s = self.s.fetch()
elif self.mode.fetch() == "nm_gle_g":
rC = self.C.fetch()
if len(rC) == 0:
rC = None
thermo = ThermoNMGLEG(A=self.A.fetch(),C=rC, tau=self.tau.fetch())
thermo.s = self.s.fetch()
elif self.mode.fetch() == "" :
thermo=Thermostat()
else:
raise TypeError("Invalid thermostat mode " + self.mode.fetch())
thermo.ethermo = self.ethermo.fetch()
return thermo | [
"def",
"fetch",
"(",
"self",
")",
":",
"super",
"(",
"InputThermo",
",",
"self",
")",
".",
"fetch",
"(",
")",
"if",
"self",
".",
"mode",
".",
"fetch",
"(",
")",
"==",
"\"langevin\"",
":",
"thermo",
"=",
"ThermoLangevin",
"(",
"tau",
"=",
"self",
".... | https://github.com/lammps/lammps/blob/b75c3065430a75b1b5543a10e10f46d9b4c91913/tools/i-pi/ipi/inputs/thermostats.py#L139-L184 | |
wenwei202/caffe | f54a74abaf6951d8485cbdcfa1d74a4c37839466 | scripts/cpp_lint.py | python | CleanseRawStrings | (raw_lines) | return lines_without_raw_strings | Removes C++11 raw strings from lines.
Before:
static const char kData[] = R"(
multi-line string
)";
After:
static const char kData[] = ""
(replaced by blank line)
"";
Args:
raw_lines: list of raw lines.
Returns:
list of lines with C++11 raw strings replaced by empty strings. | Removes C++11 raw strings from lines. | [
"Removes",
"C",
"++",
"11",
"raw",
"strings",
"from",
"lines",
"."
] | def CleanseRawStrings(raw_lines):
"""Removes C++11 raw strings from lines.
Before:
static const char kData[] = R"(
multi-line string
)";
After:
static const char kData[] = ""
(replaced by blank line)
"";
Args:
raw_lines: list of raw lines.
Returns:
list of lines with C++11 raw strings replaced by empty strings.
"""
delimiter = None
lines_without_raw_strings = []
for line in raw_lines:
if delimiter:
# Inside a raw string, look for the end
end = line.find(delimiter)
if end >= 0:
# Found the end of the string, match leading space for this
# line and resume copying the original lines, and also insert
# a "" on the last line.
leading_space = Match(r'^(\s*)\S', line)
line = leading_space.group(1) + '""' + line[end + len(delimiter):]
delimiter = None
else:
# Haven't found the end yet, append a blank line.
line = ''
else:
# Look for beginning of a raw string.
# See 2.14.15 [lex.string] for syntax.
matched = Match(r'^(.*)\b(?:R|u8R|uR|UR|LR)"([^\s\\()]*)\((.*)$', line)
if matched:
delimiter = ')' + matched.group(2) + '"'
end = matched.group(3).find(delimiter)
if end >= 0:
# Raw string ended on same line
line = (matched.group(1) + '""' +
matched.group(3)[end + len(delimiter):])
delimiter = None
else:
# Start of a multi-line raw string
line = matched.group(1) + '""'
lines_without_raw_strings.append(line)
# TODO(unknown): if delimiter is not None here, we might want to
# emit a warning for unterminated string.
return lines_without_raw_strings | [
"def",
"CleanseRawStrings",
"(",
"raw_lines",
")",
":",
"delimiter",
"=",
"None",
"lines_without_raw_strings",
"=",
"[",
"]",
"for",
"line",
"in",
"raw_lines",
":",
"if",
"delimiter",
":",
"# Inside a raw string, look for the end",
"end",
"=",
"line",
".",
"find",... | https://github.com/wenwei202/caffe/blob/f54a74abaf6951d8485cbdcfa1d74a4c37839466/scripts/cpp_lint.py#L1062-L1120 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/framework/tensor_shape.py | python | TensorShape.ndims | (self) | Returns the rank of this shape, or None if it is unspecified. | Returns the rank of this shape, or None if it is unspecified. | [
"Returns",
"the",
"rank",
"of",
"this",
"shape",
"or",
"None",
"if",
"it",
"is",
"unspecified",
"."
] | def ndims(self):
"""Returns the rank of this shape, or None if it is unspecified."""
if self._dims is None:
return None
else:
return len(self._dims) | [
"def",
"ndims",
"(",
"self",
")",
":",
"if",
"self",
".",
"_dims",
"is",
"None",
":",
"return",
"None",
"else",
":",
"return",
"len",
"(",
"self",
".",
"_dims",
")"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/framework/tensor_shape.py#L468-L473 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.