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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
falkTX/Carla | 74a1ae82c90db85f20550ddcdc8a927b8fb7e414 | source/modules/lilv/lilv-0.24.0/bindings/python/lilv.py | python | Plugin.is_replaced | (self) | return plugin_is_replaced(self.plugin) | Return true iff `plugin` has been replaced by another plugin.
The plugin will still be usable, but hosts should hide them from their
user interfaces to prevent users from using deprecated plugins. | Return true iff `plugin` has been replaced by another plugin. | [
"Return",
"true",
"iff",
"plugin",
"has",
"been",
"replaced",
"by",
"another",
"plugin",
"."
] | def is_replaced(self):
"""Return true iff `plugin` has been replaced by another plugin.
The plugin will still be usable, but hosts should hide them from their
user interfaces to prevent users from using deprecated plugins.
"""
return plugin_is_replaced(self.plugin) | [
"def",
"is_replaced",
"(",
"self",
")",
":",
"return",
"plugin_is_replaced",
"(",
"self",
".",
"plugin",
")"
] | https://github.com/falkTX/Carla/blob/74a1ae82c90db85f20550ddcdc8a927b8fb7e414/source/modules/lilv/lilv-0.24.0/bindings/python/lilv.py#L496-L502 | |
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | TPMS_SCHEME_ECSCHNORR.__init__ | (self, hashAlg = TPM_ALG_ID.NULL) | Most of the ECC signature schemes only require a hash algorithm to
complete the definition and can be typed as TPMS_SCHEME_HASH. Anonymous
algorithms also require a count value so they are typed to be
TPMS_SCHEME_ECDAA.
Attributes:
hashAlg (TPM_ALG_ID): The hash algorithm used to digest the message | Most of the ECC signature schemes only require a hash algorithm to
complete the definition and can be typed as TPMS_SCHEME_HASH. Anonymous
algorithms also require a count value so they are typed to be
TPMS_SCHEME_ECDAA. | [
"Most",
"of",
"the",
"ECC",
"signature",
"schemes",
"only",
"require",
"a",
"hash",
"algorithm",
"to",
"complete",
"the",
"definition",
"and",
"can",
"be",
"typed",
"as",
"TPMS_SCHEME_HASH",
".",
"Anonymous",
"algorithms",
"also",
"require",
"a",
"count",
"val... | def __init__(self, hashAlg = TPM_ALG_ID.NULL):
""" Most of the ECC signature schemes only require a hash algorithm to
complete the definition and can be typed as TPMS_SCHEME_HASH. Anonymous
algorithms also require a count value so they are typed to be
TPMS_SCHEME_ECDAA.
Attributes:
hashAlg (TPM_ALG_ID): The hash algorithm used to digest the message
"""
super(TPMS_SCHEME_ECSCHNORR, self).__init__(hashAlg) | [
"def",
"__init__",
"(",
"self",
",",
"hashAlg",
"=",
"TPM_ALG_ID",
".",
"NULL",
")",
":",
"super",
"(",
"TPMS_SCHEME_ECSCHNORR",
",",
"self",
")",
".",
"__init__",
"(",
"hashAlg",
")"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L17767-L17776 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | Window.SetSize | (*args, **kwargs) | return _core_.Window_SetSize(*args, **kwargs) | SetSize(self, Size size)
Sets the size of the window in pixels. | SetSize(self, Size size) | [
"SetSize",
"(",
"self",
"Size",
"size",
")"
] | def SetSize(*args, **kwargs):
"""
SetSize(self, Size size)
Sets the size of the window in pixels.
"""
return _core_.Window_SetSize(*args, **kwargs) | [
"def",
"SetSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Window_SetSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L9328-L9334 | |
omnisci/omniscidb | b9c95f1bd602b4ffc8b0edf18bfad61031e08d86 | python/omnisci/thrift/OmniSci.py | python | Iface.unshare_dashboards | (self, session, dashboard_ids, groups, permissions) | Parameters:
- session
- dashboard_ids
- groups
- permissions | Parameters:
- session
- dashboard_ids
- groups
- permissions | [
"Parameters",
":",
"-",
"session",
"-",
"dashboard_ids",
"-",
"groups",
"-",
"permissions"
] | def unshare_dashboards(self, session, dashboard_ids, groups, permissions):
"""
Parameters:
- session
- dashboard_ids
- groups
- permissions
"""
pass | [
"def",
"unshare_dashboards",
"(",
"self",
",",
"session",
",",
"dashboard_ids",
",",
"groups",
",",
"permissions",
")",
":",
"pass"
] | https://github.com/omnisci/omniscidb/blob/b9c95f1bd602b4ffc8b0edf18bfad61031e08d86/python/omnisci/thrift/OmniSci.py#L574-L583 | ||
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/build/fuchsia/runner_exceptions.py | python | IsStdoutBlocking | () | return not nonblocking | Returns True if sys.stdout is blocking or False if non-blocking.
sys.stdout should always be blocking. Non-blocking is associated with
intermittent IOErrors (crbug.com/1080858). | Returns True if sys.stdout is blocking or False if non-blocking. | [
"Returns",
"True",
"if",
"sys",
".",
"stdout",
"is",
"blocking",
"or",
"False",
"if",
"non",
"-",
"blocking",
"."
] | def IsStdoutBlocking():
"""Returns True if sys.stdout is blocking or False if non-blocking.
sys.stdout should always be blocking. Non-blocking is associated with
intermittent IOErrors (crbug.com/1080858).
"""
nonblocking = fcntl.fcntl(sys.stdout, fcntl.F_GETFL) & os.O_NONBLOCK
return not nonblocking | [
"def",
"IsStdoutBlocking",
"(",
")",
":",
"nonblocking",
"=",
"fcntl",
".",
"fcntl",
"(",
"sys",
".",
"stdout",
",",
"fcntl",
".",
"F_GETFL",
")",
"&",
"os",
".",
"O_NONBLOCK",
"return",
"not",
"nonblocking"
] | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/fuchsia/runner_exceptions.py#L27-L35 | |
apple/swift | 469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893 | utils/swift_build_support/swift_build_support/products/foundation.py | python | Foundation.product_source_name | (cls) | return "swift-corelibs-foundation" | product_source_name() -> str
The name of the source code directory of this product. | product_source_name() -> str | [
"product_source_name",
"()",
"-",
">",
"str"
] | def product_source_name(cls):
"""product_source_name() -> str
The name of the source code directory of this product.
"""
return "swift-corelibs-foundation" | [
"def",
"product_source_name",
"(",
"cls",
")",
":",
"return",
"\"swift-corelibs-foundation\""
] | https://github.com/apple/swift/blob/469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893/utils/swift_build_support/swift_build_support/products/foundation.py#L40-L45 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_misc.py | python | TimeSpan_Second | (*args) | return _misc_.TimeSpan_Second(*args) | TimeSpan_Second() -> TimeSpan | TimeSpan_Second() -> TimeSpan | [
"TimeSpan_Second",
"()",
"-",
">",
"TimeSpan"
] | def TimeSpan_Second(*args):
"""TimeSpan_Second() -> TimeSpan"""
return _misc_.TimeSpan_Second(*args) | [
"def",
"TimeSpan_Second",
"(",
"*",
"args",
")",
":",
"return",
"_misc_",
".",
"TimeSpan_Second",
"(",
"*",
"args",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L4568-L4570 | |
wenwei202/caffe | f54a74abaf6951d8485cbdcfa1d74a4c37839466 | scripts/cpp_lint.py | python | _NestingState.Update | (self, filename, clean_lines, linenum, error) | Update nesting state with current line.
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. | Update nesting state with current line. | [
"Update",
"nesting",
"state",
"with",
"current",
"line",
"."
] | def Update(self, filename, clean_lines, linenum, error):
"""Update nesting state with current line.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
# Update pp_stack first
self.UpdatePreprocessor(line)
# Count parentheses. This is to avoid adding struct arguments to
# the nesting stack.
if self.stack:
inner_block = self.stack[-1]
depth_change = line.count('(') - line.count(')')
inner_block.open_parentheses += depth_change
# Also check if we are starting or ending an inline assembly block.
if inner_block.inline_asm in (_NO_ASM, _END_ASM):
if (depth_change != 0 and
inner_block.open_parentheses == 1 and
_MATCH_ASM.match(line)):
# Enter assembly block
inner_block.inline_asm = _INSIDE_ASM
else:
# Not entering assembly block. If previous line was _END_ASM,
# we will now shift to _NO_ASM state.
inner_block.inline_asm = _NO_ASM
elif (inner_block.inline_asm == _INSIDE_ASM and
inner_block.open_parentheses == 0):
# Exit assembly block
inner_block.inline_asm = _END_ASM
# Consume namespace declaration at the beginning of the line. Do
# this in a loop so that we catch same line declarations like this:
# namespace proto2 { namespace bridge { class MessageSet; } }
while True:
# Match start of namespace. The "\b\s*" below catches namespace
# declarations even if it weren't followed by a whitespace, this
# is so that we don't confuse our namespace checker. The
# missing spaces will be flagged by CheckSpacing.
namespace_decl_match = Match(r'^\s*namespace\b\s*([:\w]+)?(.*)$', line)
if not namespace_decl_match:
break
new_namespace = _NamespaceInfo(namespace_decl_match.group(1), linenum)
self.stack.append(new_namespace)
line = namespace_decl_match.group(2)
if line.find('{') != -1:
new_namespace.seen_open_brace = True
line = line[line.find('{') + 1:]
# Look for a class declaration in whatever is left of the line
# after parsing namespaces. The regexp accounts for decorated classes
# such as in:
# class LOCKABLE API Object {
# };
#
# Templates with class arguments may confuse the parser, for example:
# template <class T
# class Comparator = less<T>,
# class Vector = vector<T> >
# class HeapQueue {
#
# Because this parser has no nesting state about templates, by the
# time it saw "class Comparator", it may think that it's a new class.
# Nested templates have a similar problem:
# template <
# typename ExportedType,
# typename TupleType,
# template <typename, typename> class ImplTemplate>
#
# To avoid these cases, we ignore classes that are followed by '=' or '>'
class_decl_match = Match(
r'\s*(template\s*<[\w\s<>,:]*>\s*)?'
r'(class|struct)\s+([A-Z_]+\s+)*(\w+(?:::\w+)*)'
r'(([^=>]|<[^<>]*>|<[^<>]*<[^<>]*>\s*>)*)$', line)
if (class_decl_match and
(not self.stack or self.stack[-1].open_parentheses == 0)):
self.stack.append(_ClassInfo(
class_decl_match.group(4), class_decl_match.group(2),
clean_lines, linenum))
line = class_decl_match.group(5)
# If we have not yet seen the opening brace for the innermost block,
# run checks here.
if not self.SeenOpenBrace():
self.stack[-1].CheckBegin(filename, clean_lines, linenum, error)
# Update access control if we are inside a class/struct
if self.stack and isinstance(self.stack[-1], _ClassInfo):
classinfo = self.stack[-1]
access_match = Match(
r'^(.*)\b(public|private|protected|signals)(\s+(?:slots\s*)?)?'
r':(?:[^:]|$)',
line)
if access_match:
classinfo.access = access_match.group(2)
# Check that access keywords are indented +1 space. Skip this
# check if the keywords are not preceded by whitespaces.
indent = access_match.group(1)
if (len(indent) != classinfo.class_indent + 1 and
Match(r'^\s*$', indent)):
if classinfo.is_struct:
parent = 'struct ' + classinfo.name
else:
parent = 'class ' + classinfo.name
slots = ''
if access_match.group(3):
slots = access_match.group(3)
error(filename, linenum, 'whitespace/indent', 3,
'%s%s: should be indented +1 space inside %s' % (
access_match.group(2), slots, parent))
# Consume braces or semicolons from what's left of the line
while True:
# Match first brace, semicolon, or closed parenthesis.
matched = Match(r'^[^{;)}]*([{;)}])(.*)$', line)
if not matched:
break
token = matched.group(1)
if token == '{':
# If namespace or class hasn't seen a opening brace yet, mark
# namespace/class head as complete. Push a new block onto the
# stack otherwise.
if not self.SeenOpenBrace():
self.stack[-1].seen_open_brace = True
else:
self.stack.append(_BlockInfo(True))
if _MATCH_ASM.match(line):
self.stack[-1].inline_asm = _BLOCK_ASM
elif token == ';' or token == ')':
# If we haven't seen an opening brace yet, but we already saw
# a semicolon, this is probably a forward declaration. Pop
# the stack for these.
#
# Similarly, if we haven't seen an opening brace yet, but we
# already saw a closing parenthesis, then these are probably
# function arguments with extra "class" or "struct" keywords.
# Also pop these stack for these.
if not self.SeenOpenBrace():
self.stack.pop()
else: # token == '}'
# Perform end of block checks and pop the stack.
if self.stack:
self.stack[-1].CheckEnd(filename, clean_lines, linenum, error)
self.stack.pop()
line = matched.group(2) | [
"def",
"Update",
"(",
"self",
",",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"# Update pp_stack first",
"self",
".",
"UpdatePreprocessor",
"(",
"line",
")",
"# Coun... | https://github.com/wenwei202/caffe/blob/f54a74abaf6951d8485cbdcfa1d74a4c37839466/scripts/cpp_lint.py#L2004-L2158 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/third_party/pyserial/serial/urlhandler/protocol_loop.py | python | LoopbackSerial.fromURL | (self, url) | extract host and port from an URL string | extract host and port from an URL string | [
"extract",
"host",
"and",
"port",
"from",
"an",
"URL",
"string"
] | def fromURL(self, url):
"""extract host and port from an URL string"""
if url.lower().startswith("loop://"): url = url[7:]
try:
# process options now, directly altering self
for option in url.split('/'):
if '=' in option:
option, value = option.split('=', 1)
else:
value = None
if not option:
pass
elif option == 'logging':
logging.basicConfig() # XXX is that good to call it here?
self.logger = logging.getLogger('pySerial.loop')
self.logger.setLevel(LOGGER_LEVELS[value])
self.logger.debug('enabled logging')
else:
raise ValueError('unknown option: %r' % (option,))
except ValueError, e:
raise SerialException('expected a string in the form "[loop://][option[/option...]]": %s' % e) | [
"def",
"fromURL",
"(",
"self",
",",
"url",
")",
":",
"if",
"url",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"\"loop://\"",
")",
":",
"url",
"=",
"url",
"[",
"7",
":",
"]",
"try",
":",
"# process options now, directly altering self",
"for",
"option"... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/pyserial/serial/urlhandler/protocol_loop.py#L84-L104 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/vpc/__init__.py | python | VPCConnection.disassociate_network_acl | (self, subnet_id, vpc_id=None) | return self.associate_network_acl(default_acl_id, subnet_id) | Figures out what the default ACL is for the VPC, and associates
current network ACL with the default.
:type subnet_id: str
:param subnet_id: The ID of the subnet to which the ACL belongs.
:type vpc_id: str
:param vpc_id: The ID of the VPC to which the ACL/subnet belongs. Queries EC2 if omitted.
:rtype: str
:return: The ID of the association created | Figures out what the default ACL is for the VPC, and associates
current network ACL with the default. | [
"Figures",
"out",
"what",
"the",
"default",
"ACL",
"is",
"for",
"the",
"VPC",
"and",
"associates",
"current",
"network",
"ACL",
"with",
"the",
"default",
"."
] | def disassociate_network_acl(self, subnet_id, vpc_id=None):
"""
Figures out what the default ACL is for the VPC, and associates
current network ACL with the default.
:type subnet_id: str
:param subnet_id: The ID of the subnet to which the ACL belongs.
:type vpc_id: str
:param vpc_id: The ID of the VPC to which the ACL/subnet belongs. Queries EC2 if omitted.
:rtype: str
:return: The ID of the association created
"""
if not vpc_id:
vpc_id = self.get_all_subnets([subnet_id])[0].vpc_id
acls = self.get_all_network_acls(filters=[('vpc-id', vpc_id), ('default', 'true')])
default_acl_id = acls[0].id
return self.associate_network_acl(default_acl_id, subnet_id) | [
"def",
"disassociate_network_acl",
"(",
"self",
",",
"subnet_id",
",",
"vpc_id",
"=",
"None",
")",
":",
"if",
"not",
"vpc_id",
":",
"vpc_id",
"=",
"self",
".",
"get_all_subnets",
"(",
"[",
"subnet_id",
"]",
")",
"[",
"0",
"]",
".",
"vpc_id",
"acls",
"=... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/vpc/__init__.py#L574-L593 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/feature_column/feature_column_v2.py | python | EmbeddingColumn.parents | (self) | return [self.categorical_column] | See 'FeatureColumn` base class. | See 'FeatureColumn` base class. | [
"See",
"FeatureColumn",
"base",
"class",
"."
] | def parents(self):
"""See 'FeatureColumn` base class."""
return [self.categorical_column] | [
"def",
"parents",
"(",
"self",
")",
":",
"return",
"[",
"self",
".",
"categorical_column",
"]"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/feature_column/feature_column_v2.py#L3124-L3126 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/_extends/parallel_compile/akg_compiler/get_file_path.py | python | get_akg_path | () | return akg_path | get akg directory base path | get akg directory base path | [
"get",
"akg",
"directory",
"base",
"path"
] | def get_akg_path():
"""get akg directory base path"""
search_res = importlib.util.find_spec("mindspore")
if search_res is None:
raise RuntimeError("Cannot find mindspore module!")
res_path = search_res.origin
find_pos = res_path.find("__init__.py")
if find_pos == -1:
raise RuntimeError("Find module mindspore origin file failed!")
akg_path = "{}_akg".format(res_path[:find_pos])
if not os.path.isdir(akg_path):
raise RuntimeError("Cannot find akg from mindspore module!")
return akg_path | [
"def",
"get_akg_path",
"(",
")",
":",
"search_res",
"=",
"importlib",
".",
"util",
".",
"find_spec",
"(",
"\"mindspore\"",
")",
"if",
"search_res",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"Cannot find mindspore module!\"",
")",
"res_path",
"=",
"searc... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/_extends/parallel_compile/akg_compiler/get_file_path.py#L20-L33 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/stc.py | python | StyledTextCtrl.PositionAfter | (*args, **kwargs) | return _stc.StyledTextCtrl_PositionAfter(*args, **kwargs) | PositionAfter(self, int pos) -> int
Given a valid document position, return the next position taking code
page into account. Maximum value returned is the last position in the document. | PositionAfter(self, int pos) -> int | [
"PositionAfter",
"(",
"self",
"int",
"pos",
")",
"-",
">",
"int"
] | def PositionAfter(*args, **kwargs):
"""
PositionAfter(self, int pos) -> int
Given a valid document position, return the next position taking code
page into account. Maximum value returned is the last position in the document.
"""
return _stc.StyledTextCtrl_PositionAfter(*args, **kwargs) | [
"def",
"PositionAfter",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_PositionAfter",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/stc.py#L5309-L5316 | |
RoboJackets/robocup-software | bce13ce53ddb2ecb9696266d980722c34617dc15 | rj_gameplay/stp/rc.py | python | Robot.pose | (self) | return self.__pose | :return: Pose of the robot. [x, y, theta]. | :return: Pose of the robot. [x, y, theta]. | [
":",
"return",
":",
"Pose",
"of",
"the",
"robot",
".",
"[",
"x",
"y",
"theta",
"]",
"."
] | def pose(self) -> np.ndarray:
"""
:return: Pose of the robot. [x, y, theta].
"""
if not self.visible:
# I could see removing this as it's a thing that may happen fairly often
warnings.warn(
"Attempting to retrieve robot pose from non-visible robot",
RuntimeWarning,
)
return self.__pose | [
"def",
"pose",
"(",
"self",
")",
"->",
"np",
".",
"ndarray",
":",
"if",
"not",
"self",
".",
"visible",
":",
"# I could see removing this as it's a thing that may happen fairly often",
"warnings",
".",
"warn",
"(",
"\"Attempting to retrieve robot pose from non-visible robot\... | https://github.com/RoboJackets/robocup-software/blob/bce13ce53ddb2ecb9696266d980722c34617dc15/rj_gameplay/stp/rc.py#L105-L116 | |
eric612/MobileNet-YOLO | 69b4441cb3ec8d553fbdef788ad033e246f901bd | examples/pycaffe/tools.py | python | CaffeSolver.add_from_file | (self, filepath) | Reads a caffe solver prototxt file and updates the Caffesolver
instance parameters. | Reads a caffe solver prototxt file and updates the Caffesolver
instance parameters. | [
"Reads",
"a",
"caffe",
"solver",
"prototxt",
"file",
"and",
"updates",
"the",
"Caffesolver",
"instance",
"parameters",
"."
] | def add_from_file(self, filepath):
"""
Reads a caffe solver prototxt file and updates the Caffesolver
instance parameters.
"""
with open(filepath, 'r') as f:
for line in f:
if line[0] == '#':
continue
splitLine = line.split(':')
self.sp[splitLine[0].strip()] = splitLine[1].strip() | [
"def",
"add_from_file",
"(",
"self",
",",
"filepath",
")",
":",
"with",
"open",
"(",
"filepath",
",",
"'r'",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"if",
"line",
"[",
"0",
"]",
"==",
"'#'",
":",
"continue",
"splitLine",
"=",
"line",
... | https://github.com/eric612/MobileNet-YOLO/blob/69b4441cb3ec8d553fbdef788ad033e246f901bd/examples/pycaffe/tools.py#L101-L111 | ||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Arch/ArchWindow.py | python | _ArchWindowTaskPanel.addElement | (self) | opens the component creation dialog | opens the component creation dialog | [
"opens",
"the",
"component",
"creation",
"dialog"
] | def addElement(self):
'opens the component creation dialog'
self.field1.setText('')
self.field3.setText('')
self.field4.setText('')
self.field5.setText('')
self.field6.setText(QtGui.QApplication.translate("Arch", "Get selected edge", None))
self.field7.setCurrentIndex(0)
self.addp4.setChecked(False)
self.addp5.setChecked(False)
self.newtitle.setVisible(True)
self.new1.setVisible(True)
self.new2.setVisible(True)
self.new3.setVisible(True)
self.new4.setVisible(True)
self.new5.setVisible(True)
self.new6.setVisible(True)
self.new7.setVisible(True)
self.field1.setVisible(True)
self.field2.setVisible(True)
self.field3.setVisible(True)
self.field4.setVisible(True)
self.field5.setVisible(True)
self.field6.setVisible(True)
self.field7.setVisible(True)
self.addp4.setVisible(True)
self.addp5.setVisible(True)
self.createButton.setVisible(True)
self.addButton.setEnabled(False)
self.editButton.setEnabled(False)
self.delButton.setEnabled(False) | [
"def",
"addElement",
"(",
"self",
")",
":",
"self",
".",
"field1",
".",
"setText",
"(",
"''",
")",
"self",
".",
"field3",
".",
"setText",
"(",
"''",
")",
"self",
".",
"field4",
".",
"setText",
"(",
"''",
")",
"self",
".",
"field5",
".",
"setText",
... | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Arch/ArchWindow.py#L1495-L1527 | ||
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | caffe2/python/scope.py | python | EmptyNameScope | () | Allow users to 'disable' the name scope behaviour.
This sets the CurrentNameScope() to None, so that the field is
not set in CreateOperator(...), etc. | Allow users to 'disable' the name scope behaviour. | [
"Allow",
"users",
"to",
"disable",
"the",
"name",
"scope",
"behaviour",
"."
] | def EmptyNameScope():
"""
Allow users to 'disable' the name scope behaviour.
This sets the CurrentNameScope() to None, so that the field is
not set in CreateOperator(...), etc.
"""
old_scope = CurrentNameScope()
try:
_threadlocal_scope.namescope = ''
yield
finally:
_threadlocal_scope.namescope = old_scope
return | [
"def",
"EmptyNameScope",
"(",
")",
":",
"old_scope",
"=",
"CurrentNameScope",
"(",
")",
"try",
":",
"_threadlocal_scope",
".",
"namescope",
"=",
"''",
"yield",
"finally",
":",
"_threadlocal_scope",
".",
"namescope",
"=",
"old_scope",
"return"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/caffe2/python/scope.py#L90-L103 | ||
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Code/Tools/waf-1.7.13/crywaflib/cryengine_modules.py | python | CryConsoleApplication | (ctx, *k, **kw) | Wrapper for CryEngine Executables | Wrapper for CryEngine Executables | [
"Wrapper",
"for",
"CryEngine",
"Executables"
] | def CryConsoleApplication(ctx, *k, **kw):
"""
Wrapper for CryEngine Executables
"""
# Initialize the Task Generator
InitializeTaskGenerator(ctx, kw)
# Setup TaskGenerator specific settings
set_cryengine_flags(ctx, kw)
SetupRunTimeLibraries(ctx,kw)
kw.setdefault('win_linkflags', []).extend(['/SUBSYSTEM:CONSOLE'])
kw['defines'] += [ 'CRY_IS_APPLICATION' ]
ConfigureTaskGenerator(ctx, kw)
if not BuildTaskGenerator(ctx, kw):
return
ctx.program(*k, **kw) | [
"def",
"CryConsoleApplication",
"(",
"ctx",
",",
"*",
"k",
",",
"*",
"*",
"kw",
")",
":",
"# Initialize the Task Generator",
"InitializeTaskGenerator",
"(",
"ctx",
",",
"kw",
")",
"# Setup TaskGenerator specific settings\t",
"set_cryengine_flags",
"(",
"ctx",
",",
"... | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/crywaflib/cryengine_modules.py#L1252-L1270 | ||
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/media/webrtc/trunk/tools/gyp/pylib/gyp/MSVSUserFile.py | python | Writer.__init__ | (self, user_file_path, version, name) | Initializes the user file.
Args:
user_file_path: Path to the user file.
version: Version info.
name: Name of the user file. | Initializes the user file. | [
"Initializes",
"the",
"user",
"file",
"."
] | def __init__(self, user_file_path, version, name):
"""Initializes the user file.
Args:
user_file_path: Path to the user file.
version: Version info.
name: Name of the user file.
"""
self.user_file_path = user_file_path
self.version = version
self.name = name
self.configurations = {} | [
"def",
"__init__",
"(",
"self",
",",
"user_file_path",
",",
"version",
",",
"name",
")",
":",
"self",
".",
"user_file_path",
"=",
"user_file_path",
"self",
".",
"version",
"=",
"version",
"self",
".",
"name",
"=",
"name",
"self",
".",
"configurations",
"="... | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/media/webrtc/trunk/tools/gyp/pylib/gyp/MSVSUserFile.py#L57-L68 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/keras/python/keras/backend.py | python | random_uniform | (shape, minval=0.0, maxval=1.0, dtype=None, seed=None) | return random_ops.random_uniform(
shape, minval=minval, maxval=maxval, dtype=dtype, seed=seed) | Returns a tensor with uniform distribution of values.
Arguments:
shape: A tuple of integers, the shape of tensor to create.
minval: A float, lower boundary of the uniform distribution
to draw samples.
maxval: A float, upper boundary of the uniform distribution
to draw samples.
dtype: String, dtype of returned tensor.
seed: Integer, random seed.
Returns:
A tensor. | Returns a tensor with uniform distribution of values. | [
"Returns",
"a",
"tensor",
"with",
"uniform",
"distribution",
"of",
"values",
"."
] | def random_uniform(shape, minval=0.0, maxval=1.0, dtype=None, seed=None):
"""Returns a tensor with uniform distribution of values.
Arguments:
shape: A tuple of integers, the shape of tensor to create.
minval: A float, lower boundary of the uniform distribution
to draw samples.
maxval: A float, upper boundary of the uniform distribution
to draw samples.
dtype: String, dtype of returned tensor.
seed: Integer, random seed.
Returns:
A tensor.
"""
if dtype is None:
dtype = floatx()
if seed is None:
seed = np.random.randint(10e6)
return random_ops.random_uniform(
shape, minval=minval, maxval=maxval, dtype=dtype, seed=seed) | [
"def",
"random_uniform",
"(",
"shape",
",",
"minval",
"=",
"0.0",
",",
"maxval",
"=",
"1.0",
",",
"dtype",
"=",
"None",
",",
"seed",
"=",
"None",
")",
":",
"if",
"dtype",
"is",
"None",
":",
"dtype",
"=",
"floatx",
"(",
")",
"if",
"seed",
"is",
"N... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/keras/python/keras/backend.py#L3759-L3779 | |
Samsung/veles | 95ed733c2e49bc011ad98ccf2416ecec23fbf352 | libVeles/cpplint.py | python | CheckForNewlineAtEOF | (filename, lines, error) | Logs an error if there is no newline char at the end of the file.
Args:
filename: The name of the current file.
lines: An array of strings, each representing a line of the file.
error: The function to call with any errors found. | Logs an error if there is no newline char at the end of the file. | [
"Logs",
"an",
"error",
"if",
"there",
"is",
"no",
"newline",
"char",
"at",
"the",
"end",
"of",
"the",
"file",
"."
] | def CheckForNewlineAtEOF(filename, lines, error):
"""Logs an error if there is no newline char at the end of the file.
Args:
filename: The name of the current file.
lines: An array of strings, each representing a line of the file.
error: The function to call with any errors found.
"""
# The array lines() was created by adding two newlines to the
# original file (go figure), then splitting on \n.
# To verify that the file ends in \n, we just have to make sure the
# last-but-two element of lines() exists and is empty.
if len(lines) < 3 or lines[-2]:
error(filename, len(lines) - 2, 'whitespace/ending_newline', 5,
'Could not find a newline character at the end of the file.') | [
"def",
"CheckForNewlineAtEOF",
"(",
"filename",
",",
"lines",
",",
"error",
")",
":",
"# The array lines() was created by adding two newlines to the",
"# original file (go figure), then splitting on \\n.",
"# To verify that the file ends in \\n, we just have to make sure the",
"# last-but-... | https://github.com/Samsung/veles/blob/95ed733c2e49bc011ad98ccf2416ecec23fbf352/libVeles/cpplint.py#L1231-L1246 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/turtle.py | python | TNavigator.heading | (self) | return (self._angleOffset + self._angleOrient*result) % self._fullcircle | Return the turtle's current heading.
No arguments.
Example (for a Turtle instance named turtle):
>>> turtle.left(67)
>>> turtle.heading()
67.0 | Return the turtle's current heading. | [
"Return",
"the",
"turtle",
"s",
"current",
"heading",
"."
] | def heading(self):
""" Return the turtle's current heading.
No arguments.
Example (for a Turtle instance named turtle):
>>> turtle.left(67)
>>> turtle.heading()
67.0
"""
x, y = self._orient
result = round(math.atan2(y, x)*180.0/math.pi, 10) % 360.0
result /= self._degreesPerAU
return (self._angleOffset + self._angleOrient*result) % self._fullcircle | [
"def",
"heading",
"(",
"self",
")",
":",
"x",
",",
"y",
"=",
"self",
".",
"_orient",
"result",
"=",
"round",
"(",
"math",
".",
"atan2",
"(",
"y",
",",
"x",
")",
"*",
"180.0",
"/",
"math",
".",
"pi",
",",
"10",
")",
"%",
"360.0",
"result",
"/=... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/turtle.py#L1810-L1823 | |
facebook/fbthrift | fb9c8562aba04c4fd9b17716eb5d970cc88a75bb | build/fbcode_builder/fbcode_builder.py | python | FBCodeBuilder.set_env | (self, key, value) | Set the environment "key" to value "value" | Set the environment "key" to value "value" | [
"Set",
"the",
"environment",
"key",
"to",
"value",
"value"
] | def set_env(self, key, value):
'Set the environment "key" to value "value"'
raise NotImplementedError | [
"def",
"set_env",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/facebook/fbthrift/blob/fb9c8562aba04c4fd9b17716eb5d970cc88a75bb/build/fbcode_builder/fbcode_builder.py#L176-L178 | ||
microsoft/ivy | 9f3c7ecc0b2383129fdd0953e10890d98d09a82d | ivy/ivy_parser.py | python | p_exprterm_var | (p) | exprterm : var | exprterm : var | [
"exprterm",
":",
"var"
] | def p_exprterm_var(p):
'exprterm : var'
p[0] = p[1] | [
"def",
"p_exprterm_var",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]"
] | https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/ivy_parser.py#L2566-L2568 | ||
rsummers11/CADLab | 976ed959a0b5208bb4173127a7ef732ac73a9b6f | panreas_hnn/hed-globalweight/scripts/cpp_lint.py | python | _OutputFormat | () | return _cpplint_state.output_format | Gets the module's output format. | Gets the module's output format. | [
"Gets",
"the",
"module",
"s",
"output",
"format",
"."
] | def _OutputFormat():
"""Gets the module's output format."""
return _cpplint_state.output_format | [
"def",
"_OutputFormat",
"(",
")",
":",
"return",
"_cpplint_state",
".",
"output_format"
] | https://github.com/rsummers11/CADLab/blob/976ed959a0b5208bb4173127a7ef732ac73a9b6f/panreas_hnn/hed-globalweight/scripts/cpp_lint.py#L767-L769 | |
deepmind/open_spiel | 4ca53bea32bb2875c7385d215424048ae92f78c8 | open_spiel/python/policy.py | python | joint_action_probabilities | (state, policy) | Yields action, probability pairs for a joint policy in simultaneous state.
Args:
state: a game state at a simultaneous decision node.
policy: policy that gives the probability distribution over the legal
actions for each players.
Yields:
(action, probability) pairs. An action is a tuple of individual
actions for each player of the game. The probability is a single joint
probability (product of all the individual probabilities). | Yields action, probability pairs for a joint policy in simultaneous state. | [
"Yields",
"action",
"probability",
"pairs",
"for",
"a",
"joint",
"policy",
"in",
"simultaneous",
"state",
"."
] | def joint_action_probabilities(state, policy):
"""Yields action, probability pairs for a joint policy in simultaneous state.
Args:
state: a game state at a simultaneous decision node.
policy: policy that gives the probability distribution over the legal
actions for each players.
Yields:
(action, probability) pairs. An action is a tuple of individual
actions for each player of the game. The probability is a single joint
probability (product of all the individual probabilities).
"""
actions_per_player, probs_per_player = joint_action_probabilities_aux(
state, policy)
for actions, probs in zip(
itertools.product(*actions_per_player),
itertools.product(*probs_per_player)):
yield actions, np.prod(probs) | [
"def",
"joint_action_probabilities",
"(",
"state",
",",
"policy",
")",
":",
"actions_per_player",
",",
"probs_per_player",
"=",
"joint_action_probabilities_aux",
"(",
"state",
",",
"policy",
")",
"for",
"actions",
",",
"probs",
"in",
"zip",
"(",
"itertools",
".",
... | https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/policy.py#L80-L98 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/Inelastic/Direct/ISISDirecInelasticConfig.py | python | UserProperties.GID | (self) | Returns user's group ID which coincide with
number part of the rb directory | Returns user's group ID which coincide with
number part of the rb directory | [
"Returns",
"user",
"s",
"group",
"ID",
"which",
"coincide",
"with",
"number",
"part",
"of",
"the",
"rb",
"directory"
] | def GID(self):
"""Returns user's group ID which coincide with
number part of the rb directory
"""
if self._user_id:
RBfolder = os.path.basename(self.rb_dir)
return RBfolder[2:]
else:
return None | [
"def",
"GID",
"(",
"self",
")",
":",
"if",
"self",
".",
"_user_id",
":",
"RBfolder",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"self",
".",
"rb_dir",
")",
"return",
"RBfolder",
"[",
"2",
":",
"]",
"else",
":",
"return",
"None"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/Inelastic/Direct/ISISDirecInelasticConfig.py#L120-L128 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/distutils/cygwinccompiler.py | python | get_msvcr | () | Include the appropriate MSVC runtime library if Python was built
with MSVC 7.0 or later. | Include the appropriate MSVC runtime library if Python was built
with MSVC 7.0 or later. | [
"Include",
"the",
"appropriate",
"MSVC",
"runtime",
"library",
"if",
"Python",
"was",
"built",
"with",
"MSVC",
"7",
".",
"0",
"or",
"later",
"."
] | def get_msvcr():
"""Include the appropriate MSVC runtime library if Python was built
with MSVC 7.0 or later.
"""
# FIXME: next code is from issue870382
# MS C-runtime libraries never support backward compatibility.
# Linking to a different library without to specify correct runtime
# version for the headers will link renamed functions to msvcrt.
# See issue3308: this piece of code is python problem even
# with correct w32api headers.
# Issue: for MSVC compiler we can get the version and from version
# to determine mcvcrt as code below. But what about if python is
# build with GCC compiler?
# Output of sys.version is information for python build on first
# line, on the next line is information for the compiler and the
# output lack information for the C-runtime.
msc_pos = sys.version.find('MSC v.')
if msc_pos != -1:
msc_ver = sys.version[msc_pos+6:msc_pos+10]
if msc_ver == '1300':
# MSVC 7.0
return ['msvcr70']
elif msc_ver == '1310':
# MSVC 7.1
return ['msvcr71']
elif msc_ver == '1400':
# VS2005 / MSVC 8.0
return ['msvcr80']
elif msc_ver == '1500':
# VS2008 / MSVC 9.0
return ['msvcr90']
else:
raise ValueError("Unknown MS Compiler version %s " % msc_ver)
else:
return [] | [
"def",
"get_msvcr",
"(",
")",
":",
"# FIXME: next code is from issue870382",
"# MS C-runtime libraries never support backward compatibility.",
"# Linking to a different library without to specify correct runtime",
"# version for the headers will link renamed functions to msvcrt.",
"# See issue3308... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/distutils/cygwinccompiler.py#L59-L93 | ||
google/sandboxed-api | 7004d59150c9fbfaa3e5fd1872affffd1ab14fe8 | sandboxed_api/tools/generator2/code.py | python | ArgumentType.__str__ | (self) | return '{} {}'.format(self._clang_type.spelling, self.name) | Returns function argument prepared from the type. | Returns function argument prepared from the type. | [
"Returns",
"function",
"argument",
"prepared",
"from",
"the",
"type",
"."
] | def __str__(self):
# type: () -> Text
"""Returns function argument prepared from the type."""
if self.is_ptr():
return '::sapi::v::Ptr* {}'.format(self.name)
return '{} {}'.format(self._clang_type.spelling, self.name) | [
"def",
"__str__",
"(",
"self",
")",
":",
"# type: () -> Text",
"if",
"self",
".",
"is_ptr",
"(",
")",
":",
"return",
"'::sapi::v::Ptr* {}'",
".",
"format",
"(",
"self",
".",
"name",
")",
"return",
"'{} {}'",
".",
"format",
"(",
"self",
".",
"_clang_type",
... | https://github.com/google/sandboxed-api/blob/7004d59150c9fbfaa3e5fd1872affffd1ab14fe8/sandboxed_api/tools/generator2/code.py#L401-L407 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/gradients_util.py | python | _VerifyGeneratedGradients | (grads, op) | Verify that gradients are valid in number and type.
Args:
grads: List of generated gradients.
op: Operation for which the gradients where generated.
Raises:
ValueError: if sizes of gradients and inputs don't match.
TypeError: if type of any gradient is not valid for its input. | Verify that gradients are valid in number and type. | [
"Verify",
"that",
"gradients",
"are",
"valid",
"in",
"number",
"and",
"type",
"."
] | def _VerifyGeneratedGradients(grads, op):
"""Verify that gradients are valid in number and type.
Args:
grads: List of generated gradients.
op: Operation for which the gradients where generated.
Raises:
ValueError: if sizes of gradients and inputs don't match.
TypeError: if type of any gradient is not valid for its input.
"""
# While ops have inputs added to them during the gradient computation, so we
# skip the below check. See while_v2 for details.
if op.type == "While" or op.type == "StatelessWhile":
return
if len(grads) != len(op.inputs):
raise ValueError("Num gradients %d generated for op %s do not match num "
"inputs %d" % (len(grads), op.node_def, len(op.inputs))) | [
"def",
"_VerifyGeneratedGradients",
"(",
"grads",
",",
"op",
")",
":",
"# While ops have inputs added to them during the gradient computation, so we",
"# skip the below check. See while_v2 for details.",
"if",
"op",
".",
"type",
"==",
"\"While\"",
"or",
"op",
".",
"type",
"==... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/gradients_util.py#L247-L265 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/multiprocessing/__init__.py | python | get_logger | () | return get_logger() | Return package logger -- if it does not already exist then it is created | Return package logger -- if it does not already exist then it is created | [
"Return",
"package",
"logger",
"--",
"if",
"it",
"does",
"not",
"already",
"exist",
"then",
"it",
"is",
"created"
] | def get_logger():
'''
Return package logger -- if it does not already exist then it is created
'''
from multiprocessing.util import get_logger
return get_logger() | [
"def",
"get_logger",
"(",
")",
":",
"from",
"multiprocessing",
".",
"util",
"import",
"get_logger",
"return",
"get_logger",
"(",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/multiprocessing/__init__.py#L147-L152 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/debug/cli/profile_analyzer_cli.py | python | ProfileDataTableView.value | (self,
row,
col,
device_name_filter=None,
node_name_filter=None,
op_type_filter=None) | return RL(text, font_attr=menu_item) | Get the content of a cell of the table.
Args:
row: (int) row index.
col: (int) column index.
device_name_filter: Regular expression to filter by device name.
node_name_filter: Regular expression to filter by node name.
op_type_filter: Regular expression to filter by op type.
Returns:
A debuggre_cli_common.RichLine object representing the content of the
cell, potentially with a clickable MenuItem.
Raises:
IndexError: if row index is out of range. | Get the content of a cell of the table. | [
"Get",
"the",
"content",
"of",
"a",
"cell",
"of",
"the",
"table",
"."
] | def value(self,
row,
col,
device_name_filter=None,
node_name_filter=None,
op_type_filter=None):
"""Get the content of a cell of the table.
Args:
row: (int) row index.
col: (int) column index.
device_name_filter: Regular expression to filter by device name.
node_name_filter: Regular expression to filter by node name.
op_type_filter: Regular expression to filter by op type.
Returns:
A debuggre_cli_common.RichLine object representing the content of the
cell, potentially with a clickable MenuItem.
Raises:
IndexError: if row index is out of range.
"""
menu_item = None
if col == 0:
text = self._profile_datum_list[row].node_exec_stats.node_name
elif col == 1:
text = self._profile_datum_list[row].op_type
elif col == 2:
text = str(self.formatted_start_time[row])
elif col == 3:
text = str(self.formatted_op_time[row])
elif col == 4:
text = str(self.formatted_exec_time[row])
elif col == 5:
command = "ps"
if device_name_filter:
command += " --%s %s" % (_DEVICE_NAME_FILTER_FLAG,
device_name_filter)
if node_name_filter:
command += " --%s %s" % (_NODE_NAME_FILTER_FLAG, node_name_filter)
if op_type_filter:
command += " --%s %s" % (_OP_TYPE_FILTER_FLAG, op_type_filter)
command += " %s --init_line %d" % (
self._profile_datum_list[row].file_path,
self._profile_datum_list[row].line_number)
menu_item = debugger_cli_common.MenuItem(None, command)
text = self._profile_datum_list[row].file_line_func
else:
raise IndexError("Invalid column index %d." % col)
return RL(text, font_attr=menu_item) | [
"def",
"value",
"(",
"self",
",",
"row",
",",
"col",
",",
"device_name_filter",
"=",
"None",
",",
"node_name_filter",
"=",
"None",
",",
"op_type_filter",
"=",
"None",
")",
":",
"menu_item",
"=",
"None",
"if",
"col",
"==",
"0",
":",
"text",
"=",
"self",... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/debug/cli/profile_analyzer_cli.py#L81-L131 | |
NVIDIA-Merlin/HugeCTR | b596bcc44e14bb0c62c4f7e9c0b55301d94f2154 | tutorial/dump_to_tf/main.py | python | read_a_sample_for_criteo | (args, key_type='I64', slot_num=1) | return label, dense, keys | read a sample from criteo dataset | read a sample from criteo dataset | [
"read",
"a",
"sample",
"from",
"criteo",
"dataset"
] | def read_a_sample_for_criteo(args, key_type='I64', slot_num=1):
"""
read a sample from criteo dataset
"""
key_type_map = {"I32": ["I", 4], "I64": ["q", 8]}
with open(args.dataset, 'rb') as file:
# skip data_header
file.seek(4 + 64 + 1, 0)
# one sample
length_buffer = file.read(4) # int
length = struct.unpack("i", length_buffer)[0]
label_buffer = file.read(4) # int
label = struct.unpack("i", label_buffer)[0]
# no dense
keys = []
for _ in range(slot_num):
nnz_buffer = file.read(4) # int
nnz = struct.unpack("i", nnz_buffer)[0]
keys_buffer = file.read(key_type_map[key_type][1] * nnz)
key = struct.unpack(str(nnz) + key_type_map[key_type][0], keys_buffer)
keys += list(key)
check_bit_buffer = file.read(1) # char
check_bit = struct.unpack("c", check_bit_buffer)
label = np.int64(label)
dense = []
keys = np.reshape(np.array(keys, dtype=np.int64), newshape=(1, 1, 39)) #[batch, slot_num, nnz]
return label, dense, keys | [
"def",
"read_a_sample_for_criteo",
"(",
"args",
",",
"key_type",
"=",
"'I64'",
",",
"slot_num",
"=",
"1",
")",
":",
"key_type_map",
"=",
"{",
"\"I32\"",
":",
"[",
"\"I\"",
",",
"4",
"]",
",",
"\"I64\"",
":",
"[",
"\"q\"",
",",
"8",
"]",
"}",
"with",
... | https://github.com/NVIDIA-Merlin/HugeCTR/blob/b596bcc44e14bb0c62c4f7e9c0b55301d94f2154/tutorial/dump_to_tf/main.py#L200-L235 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/saved_model/python/saved_model/reader.py | python | read_saved_model | (saved_model_dir) | Reads the savedmodel.pb or savedmodel.pbtxt file containing `SavedModel`.
Args:
saved_model_dir: Directory containing the SavedModel file.
Returns:
A `SavedModel` protocol buffer.
Raises:
IOError: If the file does not exist, or cannot be successfully parsed. | Reads the savedmodel.pb or savedmodel.pbtxt file containing `SavedModel`. | [
"Reads",
"the",
"savedmodel",
".",
"pb",
"or",
"savedmodel",
".",
"pbtxt",
"file",
"containing",
"SavedModel",
"."
] | def read_saved_model(saved_model_dir):
"""Reads the savedmodel.pb or savedmodel.pbtxt file containing `SavedModel`.
Args:
saved_model_dir: Directory containing the SavedModel file.
Returns:
A `SavedModel` protocol buffer.
Raises:
IOError: If the file does not exist, or cannot be successfully parsed.
"""
# Build the path to the SavedModel in pbtxt format.
path_to_pbtxt = os.path.join(
compat.as_bytes(saved_model_dir),
compat.as_bytes(constants.SAVED_MODEL_FILENAME_PBTXT))
# Build the path to the SavedModel in pb format.
path_to_pb = os.path.join(
compat.as_bytes(saved_model_dir),
compat.as_bytes(constants.SAVED_MODEL_FILENAME_PB))
# Ensure that the SavedModel exists at either path.
if not file_io.file_exists(path_to_pbtxt) and not file_io.file_exists(
path_to_pb):
raise IOError("SavedModel file does not exist at: %s" % saved_model_dir)
# Parse the SavedModel protocol buffer.
saved_model = saved_model_pb2.SavedModel()
if file_io.file_exists(path_to_pb):
try:
file_content = file_io.FileIO(path_to_pb, "rb").read()
saved_model.ParseFromString(file_content)
return saved_model
except message.DecodeError as e:
raise IOError("Cannot parse file %s: %s." % (path_to_pb, str(e)))
elif file_io.file_exists(path_to_pbtxt):
try:
file_content = file_io.FileIO(path_to_pbtxt, "rb").read()
text_format.Merge(file_content.decode("utf-8"), saved_model)
return saved_model
except text_format.ParseError as e:
raise IOError("Cannot parse file %s: %s." % (path_to_pbtxt, str(e)))
else:
raise IOError("SavedModel file does not exist at: %s/{%s|%s}" %
(saved_model_dir, constants.SAVED_MODEL_FILENAME_PBTXT,
constants.SAVED_MODEL_FILENAME_PB)) | [
"def",
"read_saved_model",
"(",
"saved_model_dir",
")",
":",
"# Build the path to the SavedModel in pbtxt format.",
"path_to_pbtxt",
"=",
"os",
".",
"path",
".",
"join",
"(",
"compat",
".",
"as_bytes",
"(",
"saved_model_dir",
")",
",",
"compat",
".",
"as_bytes",
"("... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/saved_model/python/saved_model/reader.py#L31-L76 | ||
baidu/AnyQ | d94d450d2aaa5f7ed73424b10aa4539835b97527 | tools/simnet/train/paddle/layers/paddle_layers.py | python | ElementwiseAddLayer.ops | (self, x, y) | return add | operation | operation | [
"operation"
] | def ops(self, x, y):
"""
operation
"""
add = fluid.layers.elementwise_add(x, y)
return add | [
"def",
"ops",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"add",
"=",
"fluid",
".",
"layers",
".",
"elementwise_add",
"(",
"x",
",",
"y",
")",
"return",
"add"
] | https://github.com/baidu/AnyQ/blob/d94d450d2aaa5f7ed73424b10aa4539835b97527/tools/simnet/train/paddle/layers/paddle_layers.py#L311-L316 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/src/robotsim.py | python | WorldModel.robot | (self, *args) | return _robotsim.WorldModel_robot(self, *args) | robot(WorldModel self, int index) -> RobotModel
robot(WorldModel self, char const * name) -> RobotModel
Returns a RobotModel in the world by index or name. | robot(WorldModel self, int index) -> RobotModel
robot(WorldModel self, char const * name) -> RobotModel | [
"robot",
"(",
"WorldModel",
"self",
"int",
"index",
")",
"-",
">",
"RobotModel",
"robot",
"(",
"WorldModel",
"self",
"char",
"const",
"*",
"name",
")",
"-",
">",
"RobotModel"
] | def robot(self, *args):
"""
robot(WorldModel self, int index) -> RobotModel
robot(WorldModel self, char const * name) -> RobotModel
Returns a RobotModel in the world by index or name.
"""
return _robotsim.WorldModel_robot(self, *args) | [
"def",
"robot",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_robotsim",
".",
"WorldModel_robot",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/src/robotsim.py#L5871-L5881 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/operations/_thor_ops.py | python | CusMatMulCube.__init__ | (self, transpose_a=False, transpose_b=False) | Initialize CusMatMulCube | Initialize CusMatMulCube | [
"Initialize",
"CusMatMulCube"
] | def __init__(self, transpose_a=False, transpose_b=False):
"""Initialize CusMatMulCube"""
self.init_prim_io_names(inputs=['x1', 'x2'], outputs=['y'])
self.transpose_a = transpose_a
self.transpose_b = transpose_b
from mindspore.ops._op_impl._custom_op.matmul_cube_impl import cus_matmul_cube | [
"def",
"__init__",
"(",
"self",
",",
"transpose_a",
"=",
"False",
",",
"transpose_b",
"=",
"False",
")",
":",
"self",
".",
"init_prim_io_names",
"(",
"inputs",
"=",
"[",
"'x1'",
",",
"'x2'",
"]",
",",
"outputs",
"=",
"[",
"'y'",
"]",
")",
"self",
"."... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/operations/_thor_ops.py#L284-L289 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/piectrl.py | python | PieCtrlLegend.RecreateBackground | (self, parentdc) | Recreates the legend background.
:param `parentdc`: an instance of :class:`DC`. | Recreates the legend background. | [
"Recreates",
"the",
"legend",
"background",
"."
] | def RecreateBackground(self, parentdc):
"""
Recreates the legend background.
:param `parentdc`: an instance of :class:`DC`.
"""
w, h = self.GetSize()
self._background = wx.EmptyBitmap(w, h)
self._backgroundDC.SelectObject(self._background)
if self.IsTransparent():
self._backgroundDC.Blit(0, 0, w, h, parentdc, self.GetPosition().x,
self.GetPosition().y)
else:
self._backgroundDC.SetBackground(wx.Brush(self._backcolour))
self._backgroundDC.Clear()
self.Refresh() | [
"def",
"RecreateBackground",
"(",
"self",
",",
"parentdc",
")",
":",
"w",
",",
"h",
"=",
"self",
".",
"GetSize",
"(",
")",
"self",
".",
"_background",
"=",
"wx",
".",
"EmptyBitmap",
"(",
"w",
",",
"h",
")",
"self",
".",
"_backgroundDC",
".",
"SelectO... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/piectrl.py#L213-L234 | ||
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/client/session.py | python | BaseSession.__init__ | (self, target='', graph=None, config=None) | Constructs a new TensorFlow session.
Args:
target: (Optional) The TensorFlow execution engine to connect to.
graph: (Optional) The graph to be used. If this argument is None,
the default graph will be used.
config: (Optional) ConfigProto proto used to configure the session.
Raises:
tf.errors.OpError: Or one of its subclasses if an error occurs while
creating the TensorFlow session.
TypeError: If one of the arguments has the wrong type. | Constructs a new TensorFlow session. | [
"Constructs",
"a",
"new",
"TensorFlow",
"session",
"."
] | def __init__(self, target='', graph=None, config=None):
"""Constructs a new TensorFlow session.
Args:
target: (Optional) The TensorFlow execution engine to connect to.
graph: (Optional) The graph to be used. If this argument is None,
the default graph will be used.
config: (Optional) ConfigProto proto used to configure the session.
Raises:
tf.errors.OpError: Or one of its subclasses if an error occurs while
creating the TensorFlow session.
TypeError: If one of the arguments has the wrong type.
"""
if graph is None:
self._graph = ops.get_default_graph()
else:
if not isinstance(graph, ops.Graph):
raise TypeError('graph must be a tf.Graph, but got %s' % type(graph))
self._graph = graph
self._opened = False
self._closed = False
self._current_version = 0
self._extend_lock = threading.Lock()
if target is not None:
try:
self._target = compat.as_bytes(target)
except TypeError:
raise TypeError('target must be a string, but got %s' % type(target))
else:
self._target = None
self._delete_lock = threading.Lock()
self._dead_handles = []
if config is not None:
if not isinstance(config, config_pb2.ConfigProto):
raise TypeError('config must be a tf.ConfigProto, but got %s'
% type(config))
self._config = config
self._add_shapes = config.graph_options.infer_shapes
else:
self._config = None
self._add_shapes = False
self._session = None
opts = tf_session.TF_NewSessionOptions(target=self._target, config=config)
try:
with errors.raise_exception_on_not_ok_status() as status:
self._session = tf_session.TF_NewSession(opts, status)
finally:
tf_session.TF_DeleteSessionOptions(opts) | [
"def",
"__init__",
"(",
"self",
",",
"target",
"=",
"''",
",",
"graph",
"=",
"None",
",",
"config",
"=",
"None",
")",
":",
"if",
"graph",
"is",
"None",
":",
"self",
".",
"_graph",
"=",
"ops",
".",
"get_default_graph",
"(",
")",
"else",
":",
"if",
... | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/client/session.py#L451-L504 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/enum.py | python | Enum.value | (self) | return self._value_ | The value of the Enum member. | The value of the Enum member. | [
"The",
"value",
"of",
"the",
"Enum",
"member",
"."
] | def value(self):
"""The value of the Enum member."""
return self._value_ | [
"def",
"value",
"(",
"self",
")",
":",
"return",
"self",
".",
"_value_"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/enum.py#L793-L795 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/reduce4circleGUI.py | python | MainWindow.evt_show_survey | (self) | Show survey result
:return: | Show survey result
:return: | [
"Show",
"survey",
"result",
":",
"return",
":"
] | def evt_show_survey(self):
"""
Show survey result
:return:
"""
if self.ui.tableWidget_surveyTable.rowCount() == 0:
# do nothing if the table is empty
return
max_number_str = str(self.ui.lineEdit_numSurveyOutput.text()).strip()
if max_number_str == '':
# empty: select all
surveyed_scan_list = self._myControl.get_surveyed_scans()
max_number = len(surveyed_scan_list)
else:
# get maximum number and
max_number = int(max_number_str)
# ignore the situation that this line edit is cleared
if max_number <= 0:
return
# reset row number
if max_number != self.ui.tableWidget_surveyTable.rowCount():
# re-show survey
self.ui.tableWidget_surveyTable.remove_all_rows()
self.ui.tableWidget_surveyTable.show_reflections(max_number) | [
"def",
"evt_show_survey",
"(",
"self",
")",
":",
"if",
"self",
".",
"ui",
".",
"tableWidget_surveyTable",
".",
"rowCount",
"(",
")",
"==",
"0",
":",
"# do nothing if the table is empty",
"return",
"max_number_str",
"=",
"str",
"(",
"self",
".",
"ui",
".",
"l... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/reduce4circleGUI.py#L3322-L3349 | ||
perilouswithadollarsign/cstrike15_src | f82112a2388b841d72cb62ca48ab1846dfcc11c8 | thirdparty/protobuf-2.5.0/python/google/protobuf/internal/decoder.py | python | _SkipFixed32 | (buffer, pos, end) | return pos | Skip a fixed32 value. Returns the new position. | Skip a fixed32 value. Returns the new position. | [
"Skip",
"a",
"fixed32",
"value",
".",
"Returns",
"the",
"new",
"position",
"."
] | def _SkipFixed32(buffer, pos, end):
"""Skip a fixed32 value. Returns the new position."""
pos += 4
if pos > end:
raise _DecodeError('Truncated message.')
return pos | [
"def",
"_SkipFixed32",
"(",
"buffer",
",",
"pos",
",",
"end",
")",
":",
"pos",
"+=",
"4",
"if",
"pos",
">",
"end",
":",
"raise",
"_DecodeError",
"(",
"'Truncated message.'",
")",
"return",
"pos"
] | https://github.com/perilouswithadollarsign/cstrike15_src/blob/f82112a2388b841d72cb62ca48ab1846dfcc11c8/thirdparty/protobuf-2.5.0/python/google/protobuf/internal/decoder.py#L674-L680 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/http/cookiejar.py | python | CookieJar.clear_session_cookies | (self) | Discard all session cookies.
Note that the .save() method won't save session cookies anyway, unless
you ask otherwise by passing a true ignore_discard argument. | Discard all session cookies. | [
"Discard",
"all",
"session",
"cookies",
"."
] | def clear_session_cookies(self):
"""Discard all session cookies.
Note that the .save() method won't save session cookies anyway, unless
you ask otherwise by passing a true ignore_discard argument.
"""
self._cookies_lock.acquire()
try:
for cookie in self:
if cookie.discard:
self.clear(cookie.domain, cookie.path, cookie.name)
finally:
self._cookies_lock.release() | [
"def",
"clear_session_cookies",
"(",
"self",
")",
":",
"self",
".",
"_cookies_lock",
".",
"acquire",
"(",
")",
"try",
":",
"for",
"cookie",
"in",
"self",
":",
"if",
"cookie",
".",
"discard",
":",
"self",
".",
"clear",
"(",
"cookie",
".",
"domain",
",",... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/http/cookiejar.py#L1713-L1726 | ||
Tencent/CMONGO | c40380caa14e05509f46993aa8b8da966b09b0b5 | src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/jar.py | python | jarFlags | (target, source, env, for_signature) | return jarflags | If we have a manifest, make sure that the 'm'
flag is specified. | If we have a manifest, make sure that the 'm'
flag is specified. | [
"If",
"we",
"have",
"a",
"manifest",
"make",
"sure",
"that",
"the",
"m",
"flag",
"is",
"specified",
"."
] | def jarFlags(target, source, env, for_signature):
"""If we have a manifest, make sure that the 'm'
flag is specified."""
jarflags = env.subst('$JARFLAGS', target=target, source=source)
for src in source:
contents = src.get_text_contents()
if contents[:16] == "Manifest-Version":
if not 'm' in jarflags:
return jarflags + 'm'
break
return jarflags | [
"def",
"jarFlags",
"(",
"target",
",",
"source",
",",
"env",
",",
"for_signature",
")",
":",
"jarflags",
"=",
"env",
".",
"subst",
"(",
"'$JARFLAGS'",
",",
"target",
"=",
"target",
",",
"source",
"=",
"source",
")",
"for",
"src",
"in",
"source",
":",
... | https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/jar.py#L78-L88 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/memory_inspector/memory_inspector/core/backends.py | python | Device.name | (self) | Friendly name of the target device (e.g., phone model). | Friendly name of the target device (e.g., phone model). | [
"Friendly",
"name",
"of",
"the",
"target",
"device",
"(",
"e",
".",
"g",
".",
"phone",
"model",
")",
"."
] | def name(self):
"""Friendly name of the target device (e.g., phone model)."""
raise NotImplementedError() | [
"def",
"name",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/memory_inspector/memory_inspector/core/backends.py#L109-L111 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/linear_model/omp.py | python | _omp_path_residues | (X_train, y_train, X_test, y_test, copy=True,
fit_intercept=True, normalize=True, max_iter=100) | return np.dot(coefs.T, X_test.T) - y_test | Compute the residues on left-out data for a full LARS path
Parameters
-----------
X_train : array, shape (n_samples, n_features)
The data to fit the LARS on
y_train : array, shape (n_samples)
The target variable to fit LARS on
X_test : array, shape (n_samples, n_features)
The data to compute the residues on
y_test : array, shape (n_samples)
The target variable to compute the residues on
copy : boolean, optional
Whether X_train, X_test, y_train and y_test should be copied. If
False, they may be overwritten.
fit_intercept : boolean
whether to calculate the intercept for this model. If set
to false, no intercept will be used in calculations
(e.g. data is expected to be already centered).
normalize : boolean, optional, default False
If True, the regressors X will be normalized before regression.
This parameter is ignored when `fit_intercept` is set to `False`.
When the regressors are normalized, note that this makes the
hyperparameters learnt more robust and almost independent of the number
of samples. The same property is not valid for standardized data.
However, if you wish to standardize, please use
`preprocessing.StandardScaler` before calling `fit` on an estimator
with `normalize=False`.
max_iter : integer, optional
Maximum numbers of iterations to perform, therefore maximum features
to include. 100 by default.
Returns
-------
residues: array, shape (n_samples, max_features)
Residues of the prediction on the test data | Compute the residues on left-out data for a full LARS path | [
"Compute",
"the",
"residues",
"on",
"left",
"-",
"out",
"data",
"for",
"a",
"full",
"LARS",
"path"
] | def _omp_path_residues(X_train, y_train, X_test, y_test, copy=True,
fit_intercept=True, normalize=True, max_iter=100):
"""Compute the residues on left-out data for a full LARS path
Parameters
-----------
X_train : array, shape (n_samples, n_features)
The data to fit the LARS on
y_train : array, shape (n_samples)
The target variable to fit LARS on
X_test : array, shape (n_samples, n_features)
The data to compute the residues on
y_test : array, shape (n_samples)
The target variable to compute the residues on
copy : boolean, optional
Whether X_train, X_test, y_train and y_test should be copied. If
False, they may be overwritten.
fit_intercept : boolean
whether to calculate the intercept for this model. If set
to false, no intercept will be used in calculations
(e.g. data is expected to be already centered).
normalize : boolean, optional, default False
If True, the regressors X will be normalized before regression.
This parameter is ignored when `fit_intercept` is set to `False`.
When the regressors are normalized, note that this makes the
hyperparameters learnt more robust and almost independent of the number
of samples. The same property is not valid for standardized data.
However, if you wish to standardize, please use
`preprocessing.StandardScaler` before calling `fit` on an estimator
with `normalize=False`.
max_iter : integer, optional
Maximum numbers of iterations to perform, therefore maximum features
to include. 100 by default.
Returns
-------
residues: array, shape (n_samples, max_features)
Residues of the prediction on the test data
"""
if copy:
X_train = X_train.copy()
y_train = y_train.copy()
X_test = X_test.copy()
y_test = y_test.copy()
if fit_intercept:
X_mean = X_train.mean(axis=0)
X_train -= X_mean
X_test -= X_mean
y_mean = y_train.mean(axis=0)
y_train = as_float_array(y_train, copy=False)
y_train -= y_mean
y_test = as_float_array(y_test, copy=False)
y_test -= y_mean
if normalize:
norms = np.sqrt(np.sum(X_train ** 2, axis=0))
nonzeros = np.flatnonzero(norms)
X_train[:, nonzeros] /= norms[nonzeros]
coefs = orthogonal_mp(X_train, y_train, n_nonzero_coefs=max_iter, tol=None,
precompute=False, copy_X=False,
return_path=True)
if coefs.ndim == 1:
coefs = coefs[:, np.newaxis]
if normalize:
coefs[nonzeros] /= norms[nonzeros][:, np.newaxis]
return np.dot(coefs.T, X_test.T) - y_test | [
"def",
"_omp_path_residues",
"(",
"X_train",
",",
"y_train",
",",
"X_test",
",",
"y_test",
",",
"copy",
"=",
"True",
",",
"fit_intercept",
"=",
"True",
",",
"normalize",
"=",
"True",
",",
"max_iter",
"=",
"100",
")",
":",
"if",
"copy",
":",
"X_train",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/linear_model/omp.py#L671-L747 | |
tpfister/caffe-heatmap | 4db69ef53e6b8a0b3b4ebb29328b0ab3dbf67c4e | scripts/cpp_lint.py | python | CheckStyle | (filename, clean_lines, linenum, file_extension, nesting_state,
error) | Checks rules from the 'C++ style rules' section of cppguide.html.
Most of these rules are hard to test (naming, comment style), but we
do what we can. In particular we check for 2-space indents, line lengths,
tab usage, spaces inside code, etc.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
file_extension: The extension (without the dot) of the filename.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found. | Checks rules from the 'C++ style rules' section of cppguide.html. | [
"Checks",
"rules",
"from",
"the",
"C",
"++",
"style",
"rules",
"section",
"of",
"cppguide",
".",
"html",
"."
] | def CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state,
error):
"""Checks rules from the 'C++ style rules' section of cppguide.html.
Most of these rules are hard to test (naming, comment style), but we
do what we can. In particular we check for 2-space indents, line lengths,
tab usage, spaces inside code, etc.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
file_extension: The extension (without the dot) of the filename.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found.
"""
# Don't use "elided" lines here, otherwise we can't check commented lines.
# Don't want to use "raw" either, because we don't want to check inside C++11
# raw strings,
raw_lines = clean_lines.lines_without_raw_strings
line = raw_lines[linenum]
if line.find('\t') != -1:
error(filename, linenum, 'whitespace/tab', 1,
'Tab found; better to use spaces')
# One or three blank spaces at the beginning of the line is weird; it's
# hard to reconcile that with 2-space indents.
# NOTE: here are the conditions rob pike used for his tests. Mine aren't
# as sophisticated, but it may be worth becoming so: RLENGTH==initial_spaces
# if(RLENGTH > 20) complain = 0;
# if(match($0, " +(error|private|public|protected):")) complain = 0;
# if(match(prev, "&& *$")) complain = 0;
# if(match(prev, "\\|\\| *$")) complain = 0;
# if(match(prev, "[\",=><] *$")) complain = 0;
# if(match($0, " <<")) complain = 0;
# if(match(prev, " +for \\(")) complain = 0;
# if(prevodd && match(prevprev, " +for \\(")) complain = 0;
initial_spaces = 0
cleansed_line = clean_lines.elided[linenum]
while initial_spaces < len(line) and line[initial_spaces] == ' ':
initial_spaces += 1
if line and line[-1].isspace():
error(filename, linenum, 'whitespace/end_of_line', 4,
'Line ends in whitespace. Consider deleting these extra spaces.')
# There are certain situations we allow one space, notably for section labels
elif ((initial_spaces == 1 or initial_spaces == 3) and
not Match(r'\s*\w+\s*:\s*$', cleansed_line)):
error(filename, linenum, 'whitespace/indent', 3,
'Weird number of spaces at line-start. '
'Are you using a 2-space indent?')
# Check if the line is a header guard.
is_header_guard = False
if file_extension == 'h':
cppvar = GetHeaderGuardCPPVariable(filename)
if (line.startswith('#ifndef %s' % cppvar) or
line.startswith('#define %s' % cppvar) or
line.startswith('#endif // %s' % cppvar)):
is_header_guard = True
# #include lines and header guards can be long, since there's no clean way to
# split them.
#
# URLs can be long too. It's possible to split these, but it makes them
# harder to cut&paste.
#
# The "$Id:...$" comment may also get very long without it being the
# developers fault.
if (not line.startswith('#include') and not is_header_guard and
not Match(r'^\s*//.*http(s?)://\S*$', line) and
not Match(r'^// \$Id:.*#[0-9]+ \$$', line)):
line_width = GetLineWidth(line)
extended_length = int((_line_length * 1.25))
if line_width > extended_length:
error(filename, linenum, 'whitespace/line_length', 4,
'Lines should very rarely be longer than %i characters' %
extended_length)
elif line_width > _line_length:
error(filename, linenum, 'whitespace/line_length', 2,
'Lines should be <= %i characters long' % _line_length)
if (cleansed_line.count(';') > 1 and
# for loops are allowed two ;'s (and may run over two lines).
cleansed_line.find('for') == -1 and
(GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or
GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and
# It's ok to have many commands in a switch case that fits in 1 line
not ((cleansed_line.find('case ') != -1 or
cleansed_line.find('default:') != -1) and
cleansed_line.find('break;') != -1)):
error(filename, linenum, 'whitespace/newline', 0,
'More than one command on the same line')
# Some more style checks
CheckBraces(filename, clean_lines, linenum, error)
CheckEmptyBlockBody(filename, clean_lines, linenum, error)
CheckAccess(filename, clean_lines, linenum, nesting_state, error)
CheckSpacing(filename, clean_lines, linenum, nesting_state, error)
CheckCheck(filename, clean_lines, linenum, error)
CheckAltTokens(filename, clean_lines, linenum, error)
classinfo = nesting_state.InnermostClass()
if classinfo:
CheckSectionSpacing(filename, clean_lines, classinfo, linenum, error) | [
"def",
"CheckStyle",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"file_extension",
",",
"nesting_state",
",",
"error",
")",
":",
"# Don't use \"elided\" lines here, otherwise we can't check commented lines.",
"# Don't want to use \"raw\" either, because we don't want ... | https://github.com/tpfister/caffe-heatmap/blob/4db69ef53e6b8a0b3b4ebb29328b0ab3dbf67c4e/scripts/cpp_lint.py#L3459-L3563 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/ast.py | python | parse | (source, filename='<unknown>', mode='exec') | return compile(source, filename, mode, PyCF_ONLY_AST) | Parse the source into an AST node.
Equivalent to compile(source, filename, mode, PyCF_ONLY_AST). | Parse the source into an AST node.
Equivalent to compile(source, filename, mode, PyCF_ONLY_AST). | [
"Parse",
"the",
"source",
"into",
"an",
"AST",
"node",
".",
"Equivalent",
"to",
"compile",
"(",
"source",
"filename",
"mode",
"PyCF_ONLY_AST",
")",
"."
] | def parse(source, filename='<unknown>', mode='exec'):
"""
Parse the source into an AST node.
Equivalent to compile(source, filename, mode, PyCF_ONLY_AST).
"""
return compile(source, filename, mode, PyCF_ONLY_AST) | [
"def",
"parse",
"(",
"source",
",",
"filename",
"=",
"'<unknown>'",
",",
"mode",
"=",
"'exec'",
")",
":",
"return",
"compile",
"(",
"source",
",",
"filename",
",",
"mode",
",",
"PyCF_ONLY_AST",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/ast.py#L32-L37 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | Window.PageDown | (*args, **kwargs) | return _core_.Window_PageDown(*args, **kwargs) | PageDown(self) -> bool
This is just a wrapper for ScrollPages(1). | PageDown(self) -> bool | [
"PageDown",
"(",
"self",
")",
"-",
">",
"bool"
] | def PageDown(*args, **kwargs):
"""
PageDown(self) -> bool
This is just a wrapper for ScrollPages(1).
"""
return _core_.Window_PageDown(*args, **kwargs) | [
"def",
"PageDown",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Window_PageDown",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L11317-L11323 | |
microsoft/CNTK | e9396480025b9ca457d26b6f33dd07c474c6aa04 | bindings/python/cntk/layers/higher_order_layers.py | python | ResNetBlock | (f, name='') | return skip | ResNetBlock(f, name='')
Layer factory function to create a composite that adds a skip connection to a function.
This is equivalent to ``Sequential((f, identity), plus)``.
Example:
>>> # a ResNet layer
>>> from cntk.layers import *
>>> from cntk.ops import relu
>>> resnet_layer = Sequential([ResNetBlock(Convolution((3,3), 64, activation=None)), relu])
Args:
f (:class:`~cntk.ops.functions.Function` or equivalent Python function):
the function to add the skip connection to.
Returns:
cntk.ops.functions.Function:
A function that accepts one argument, applies ``f`` to it, and adds the original argument. | ResNetBlock(f, name='') | [
"ResNetBlock",
"(",
"f",
"name",
"=",
")"
] | def ResNetBlock(f, name=''):
'''
ResNetBlock(f, name='')
Layer factory function to create a composite that adds a skip connection to a function.
This is equivalent to ``Sequential((f, identity), plus)``.
Example:
>>> # a ResNet layer
>>> from cntk.layers import *
>>> from cntk.ops import relu
>>> resnet_layer = Sequential([ResNetBlock(Convolution((3,3), 64, activation=None)), relu])
Args:
f (:class:`~cntk.ops.functions.Function` or equivalent Python function):
the function to add the skip connection to.
Returns:
cntk.ops.functions.Function:
A function that accepts one argument, applies ``f`` to it, and adds the original argument.
'''
def skip(x):
return f(x) + x
skip = _inject_name(skip, name)
return skip | [
"def",
"ResNetBlock",
"(",
"f",
",",
"name",
"=",
"''",
")",
":",
"def",
"skip",
"(",
"x",
")",
":",
"return",
"f",
"(",
"x",
")",
"+",
"x",
"skip",
"=",
"_inject_name",
"(",
"skip",
",",
"name",
")",
"return",
"skip"
] | https://github.com/microsoft/CNTK/blob/e9396480025b9ca457d26b6f33dd07c474c6aa04/bindings/python/cntk/layers/higher_order_layers.py#L204-L230 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/external/bazel_tools/tools/objc/j2objc_dead_code_pruner.py | python | PruneArchiveFile | (input_archive, output_archive, dummy_archive,
dependency_mapping_files, header_mapping_files,
archive_source_mapping_files, entry_classes, xcrunwrapper,
file_open=open) | Remove unreachable objects from archive file.
Args:
input_archive: The source archive file to prune.
output_archive: The location of the pruned archive file.
dummy_archive: A dummy archive file that contains no object.
dependency_mapping_files: A comma separated list of J2ObjC-generated
dependency mapping files.
header_mapping_files: A comma separated list of J2ObjC-generated
header mapping files.
archive_source_mapping_files: A comma separated list of J2ObjC-generated
mapping between archive files and their associated source files.
entry_classes: A comma separated list of Java entry classes.
xcrunwrapper: A wrapper script over xcrun.
file_open: Reference to the builtin open function so it may be
overridden for testing. | Remove unreachable objects from archive file. | [
"Remove",
"unreachable",
"objects",
"from",
"archive",
"file",
"."
] | def PruneArchiveFile(input_archive, output_archive, dummy_archive,
dependency_mapping_files, header_mapping_files,
archive_source_mapping_files, entry_classes, xcrunwrapper,
file_open=open):
"""Remove unreachable objects from archive file.
Args:
input_archive: The source archive file to prune.
output_archive: The location of the pruned archive file.
dummy_archive: A dummy archive file that contains no object.
dependency_mapping_files: A comma separated list of J2ObjC-generated
dependency mapping files.
header_mapping_files: A comma separated list of J2ObjC-generated
header mapping files.
archive_source_mapping_files: A comma separated list of J2ObjC-generated
mapping between archive files and their associated source files.
entry_classes: A comma separated list of Java entry classes.
xcrunwrapper: A wrapper script over xcrun.
file_open: Reference to the builtin open function so it may be
overridden for testing.
"""
reachability_file_mapping = BuildReachabilityTree(
dependency_mapping_files, file_open)
header_map = BuildHeaderMapping(header_mapping_files, file_open)
archive_source_file_mapping = BuildArchiveSourceFileMapping(
archive_source_mapping_files, file_open)
reachable_files_set = BuildReachableFileSet(entry_classes,
reachability_file_mapping,
header_map,
archive_source_file_mapping)
j2objc_cmd = ''
if input_archive in archive_source_file_mapping:
source_files = archive_source_file_mapping[input_archive]
unreachable_object_names = []
for source_file in source_files:
if os.path.splitext(source_file)[0] not in reachable_files_set:
unreachable_object_names.append(
os.path.basename(os.path.splitext(source_file)[0]))
# There are unreachable objects in the archive to prune
if unreachable_object_names:
# If all objects in the archive are unreachable, just copy over a dummy
# archive that contains no object
if len(unreachable_object_names) == len(source_files):
j2objc_cmd = 'cp %s %s' % (dummy_archive, output_archive)
# Else we need to prune the archive of unreachable objects
else:
# Copy the input archive to the output location
j2objc_cmd += 'cp %s %s;' % (input_archive, output_archive)
# Make the output archive editable
j2objc_cmd += 'chmod +w %s;' % (output_archive)
# Remove the unreachable objects from the archive
unreachable_object_names = MatchObjectNamesInArchive(
xcrunwrapper, input_archive, unreachable_object_names)
j2objc_cmd += '%s ar -d -s %s %s;' % (
xcrunwrapper, output_archive, ' '.join(unreachable_object_names))
# Update the table of content of the archive file
j2objc_cmd += '%s ranlib -a %s' % (xcrunwrapper, output_archive)
# There are no unreachable objects, we just copy over the original archive
else:
j2objc_cmd = 'cp %s %s' % (input_archive, output_archive)
# The archive cannot be pruned by J2ObjC dead code removal, just copy over
# the original archive
else:
j2objc_cmd = 'cp %s %s' % (input_archive, output_archive)
subprocess.check_output(j2objc_cmd, stderr=subprocess.STDOUT, shell=True) | [
"def",
"PruneArchiveFile",
"(",
"input_archive",
",",
"output_archive",
",",
"dummy_archive",
",",
"dependency_mapping_files",
",",
"header_mapping_files",
",",
"archive_source_mapping_files",
",",
"entry_classes",
",",
"xcrunwrapper",
",",
"file_open",
"=",
"open",
")",
... | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/external/bazel_tools/tools/objc/j2objc_dead_code_pruner.py#L323-L391 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/dataset/engine/validators.py | python | check_tedlium_dataset | (method) | return new_method | Wrapper method to check the parameters of TedliumDataset. | Wrapper method to check the parameters of TedliumDataset. | [
"Wrapper",
"method",
"to",
"check",
"the",
"parameters",
"of",
"TedliumDataset",
"."
] | def check_tedlium_dataset(method):
"""Wrapper method to check the parameters of TedliumDataset."""
@wraps(method)
def new_method(self, *args, **kwargs):
_, param_dict = parse_user_args(method, *args, **kwargs)
nreq_param_int = ['num_samples', 'num_parallel_workers', 'num_shards', 'shard_id']
nreq_param_bool = ['shuffle']
release = param_dict.get('release')
check_valid_str(release, ["release1", "release2", "release3"], "release")
dataset_dir = param_dict.get('dataset_dir')
check_dir(dataset_dir)
usage = param_dict.get('usage')
if usage is not None:
if release in ["release1", "release2"]:
check_valid_str(usage, ["train", "test", "dev", "all"], "usage")
else:
check_valid_str(usage, ["all"], "usage")
validate_dataset_param_value(nreq_param_int, param_dict, int)
validate_dataset_param_value(nreq_param_bool, param_dict, bool)
check_sampler_shuffle_shard_options(param_dict)
cache = param_dict.get('cache')
check_cache_option(cache)
return method(self, *args, **kwargs)
return new_method | [
"def",
"check_tedlium_dataset",
"(",
"method",
")",
":",
"@",
"wraps",
"(",
"method",
")",
"def",
"new_method",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_",
",",
"param_dict",
"=",
"parse_user_args",
"(",
"method",
",",
"*",
... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/dataset/engine/validators.py#L2250-L2283 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/richtext.py | python | RichTextObject.IsFloating | (*args, **kwargs) | return _richtext.RichTextObject_IsFloating(*args, **kwargs) | IsFloating(self) -> bool | IsFloating(self) -> bool | [
"IsFloating",
"(",
"self",
")",
"-",
">",
"bool"
] | def IsFloating(*args, **kwargs):
"""IsFloating(self) -> bool"""
return _richtext.RichTextObject_IsFloating(*args, **kwargs) | [
"def",
"IsFloating",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextObject_IsFloating",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/richtext.py#L1226-L1228 | |
WeitaoVan/L-GM-loss | 598582f0631bac876b3eeb8d6c4cd1d780269e03 | scripts/cpp_lint.py | python | CleansedLines._CollapseStrings | (elided) | return elided | Collapses strings and chars on a line to simple "" or '' blocks.
We nix strings first so we're not fooled by text like '"http://"'
Args:
elided: The line being processed.
Returns:
The line with collapsed strings. | Collapses strings and chars on a line to simple "" or '' blocks. | [
"Collapses",
"strings",
"and",
"chars",
"on",
"a",
"line",
"to",
"simple",
"or",
"blocks",
"."
] | def _CollapseStrings(elided):
"""Collapses strings and chars on a line to simple "" or '' blocks.
We nix strings first so we're not fooled by text like '"http://"'
Args:
elided: The line being processed.
Returns:
The line with collapsed strings.
"""
if not _RE_PATTERN_INCLUDE.match(elided):
# Remove escaped characters first to make quote/single quote collapsing
# basic. Things that look like escaped characters shouldn't occur
# outside of strings and chars.
elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided)
elided = _RE_PATTERN_CLEANSE_LINE_SINGLE_QUOTES.sub("''", elided)
elided = _RE_PATTERN_CLEANSE_LINE_DOUBLE_QUOTES.sub('""', elided)
return elided | [
"def",
"_CollapseStrings",
"(",
"elided",
")",
":",
"if",
"not",
"_RE_PATTERN_INCLUDE",
".",
"match",
"(",
"elided",
")",
":",
"# Remove escaped characters first to make quote/single quote collapsing",
"# basic. Things that look like escaped characters shouldn't occur",
"# outside... | https://github.com/WeitaoVan/L-GM-loss/blob/598582f0631bac876b3eeb8d6c4cd1d780269e03/scripts/cpp_lint.py#L1209-L1227 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/external/boost/boost_1_68_0/tools/build/src/build/feature.py | python | is_implicit_value | (value_string) | return True | Returns true iff 'value_string' is a value_string
of an implicit feature. | Returns true iff 'value_string' is a value_string
of an implicit feature. | [
"Returns",
"true",
"iff",
"value_string",
"is",
"a",
"value_string",
"of",
"an",
"implicit",
"feature",
"."
] | def is_implicit_value (value_string):
""" Returns true iff 'value_string' is a value_string
of an implicit feature.
"""
assert isinstance(value_string, basestring)
if value_string in __implicit_features:
return __implicit_features[value_string]
v = value_string.split('-')
if v[0] not in __implicit_features:
return False
feature = __implicit_features[v[0]]
for subvalue in (v[1:]):
if not __find_implied_subfeature(feature, subvalue, v[0]):
return False
return True | [
"def",
"is_implicit_value",
"(",
"value_string",
")",
":",
"assert",
"isinstance",
"(",
"value_string",
",",
"basestring",
")",
"if",
"value_string",
"in",
"__implicit_features",
":",
"return",
"__implicit_features",
"[",
"value_string",
"]",
"v",
"=",
"value_string... | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/boost/boost_1_68_0/tools/build/src/build/feature.py#L222-L241 | |
apple/swift | 469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893 | utils/swift_build_support/swift_build_support/targets.py | python | AndroidPlatform.uses_host_tests | (self) | return True | Check if this is a Darwin platform that needs a connected device
for tests. | Check if this is a Darwin platform that needs a connected device
for tests. | [
"Check",
"if",
"this",
"is",
"a",
"Darwin",
"platform",
"that",
"needs",
"a",
"connected",
"device",
"for",
"tests",
"."
] | def uses_host_tests(self):
"""
Check if this is a Darwin platform that needs a connected device
for tests.
"""
return True | [
"def",
"uses_host_tests",
"(",
"self",
")",
":",
"return",
"True"
] | https://github.com/apple/swift/blob/469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893/utils/swift_build_support/swift_build_support/targets.py#L151-L156 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/cloudsearch2/optionstatus.py | python | OptionStatus.save | (self) | Write the current state of the local object back to the
CloudSearch service. | Write the current state of the local object back to the
CloudSearch service. | [
"Write",
"the",
"current",
"state",
"of",
"the",
"local",
"object",
"back",
"to",
"the",
"CloudSearch",
"service",
"."
] | def save(self):
"""
Write the current state of the local object back to the
CloudSearch service.
"""
if self.save_fn:
data = self.save_fn(self.domain.name, self.to_json())
self.refresh(data) | [
"def",
"save",
"(",
"self",
")",
":",
"if",
"self",
".",
"save_fn",
":",
"data",
"=",
"self",
".",
"save_fn",
"(",
"self",
".",
"domain",
".",
"name",
",",
"self",
".",
"to_json",
"(",
")",
")",
"self",
".",
"refresh",
"(",
"data",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/cloudsearch2/optionstatus.py#L95-L102 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/urllib3/_collections.py | python | HTTPHeaderDict.getlist | (self, key, default=__marker) | Returns a list of all the values for the named field. Returns an
empty list if the key doesn't exist. | Returns a list of all the values for the named field. Returns an
empty list if the key doesn't exist. | [
"Returns",
"a",
"list",
"of",
"all",
"the",
"values",
"for",
"the",
"named",
"field",
".",
"Returns",
"an",
"empty",
"list",
"if",
"the",
"key",
"doesn",
"t",
"exist",
"."
] | def getlist(self, key, default=__marker):
"""Returns a list of all the values for the named field. Returns an
empty list if the key doesn't exist."""
try:
vals = self._container[key.lower()]
except KeyError:
if default is self.__marker:
return []
return default
else:
return vals[1:] | [
"def",
"getlist",
"(",
"self",
",",
"key",
",",
"default",
"=",
"__marker",
")",
":",
"try",
":",
"vals",
"=",
"self",
".",
"_container",
"[",
"key",
".",
"lower",
"(",
")",
"]",
"except",
"KeyError",
":",
"if",
"default",
"is",
"self",
".",
"__mar... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/urllib3/_collections.py#L258-L268 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/encodings/punycode.py | python | decode_generalized_number | (extended, extpos, bias, errors) | 3.3 Generalized variable-length integers | 3.3 Generalized variable-length integers | [
"3",
".",
"3",
"Generalized",
"variable",
"-",
"length",
"integers"
] | def decode_generalized_number(extended, extpos, bias, errors):
"""3.3 Generalized variable-length integers"""
result = 0
w = 1
j = 0
while 1:
try:
char = ord(extended[extpos])
except IndexError:
if errors == "strict":
raise UnicodeError("incomplete punicode string")
return extpos + 1, None
extpos += 1
if 0x41 <= char <= 0x5A: # A-Z
digit = char - 0x41
elif 0x30 <= char <= 0x39:
digit = char - 22 # 0x30-26
elif errors == "strict":
raise UnicodeError("Invalid extended code point '%s'"
% extended[extpos-1])
else:
return extpos, None
t = T(j, bias)
result += digit * w
if digit < t:
return extpos, result
w = w * (36 - t)
j += 1 | [
"def",
"decode_generalized_number",
"(",
"extended",
",",
"extpos",
",",
"bias",
",",
"errors",
")",
":",
"result",
"=",
"0",
"w",
"=",
"1",
"j",
"=",
"0",
"while",
"1",
":",
"try",
":",
"char",
"=",
"ord",
"(",
"extended",
"[",
"extpos",
"]",
")",... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/encodings/punycode.py#L127-L154 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/dashboard/dashboard/edit_config_handler.py | python | _RemoveOverlapping | (added_items, removed_items) | return added - removed, removed - added | Returns two sets of items with the common items removed. | Returns two sets of items with the common items removed. | [
"Returns",
"two",
"sets",
"of",
"items",
"with",
"the",
"common",
"items",
"removed",
"."
] | def _RemoveOverlapping(added_items, removed_items):
"""Returns two sets of items with the common items removed."""
added, removed = set(added_items), set(removed_items)
return added - removed, removed - added | [
"def",
"_RemoveOverlapping",
"(",
"added_items",
",",
"removed_items",
")",
":",
"added",
",",
"removed",
"=",
"set",
"(",
"added_items",
")",
",",
"set",
"(",
"removed_items",
")",
"return",
"added",
"-",
"removed",
",",
"removed",
"-",
"added"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/dashboard/dashboard/edit_config_handler.py#L206-L209 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/richtext.py | python | RichTextFileHandlerList.__contains__ | (*args, **kwargs) | return _richtext.RichTextFileHandlerList___contains__(*args, **kwargs) | __contains__(self, RichTextFileHandler obj) -> bool | __contains__(self, RichTextFileHandler obj) -> bool | [
"__contains__",
"(",
"self",
"RichTextFileHandler",
"obj",
")",
"-",
">",
"bool"
] | def __contains__(*args, **kwargs):
"""__contains__(self, RichTextFileHandler obj) -> bool"""
return _richtext.RichTextFileHandlerList___contains__(*args, **kwargs) | [
"def",
"__contains__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextFileHandlerList___contains__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/richtext.py#L2183-L2185 | |
protocolbuffers/protobuf | b5ab0b7a18b7336c60130f4ddb2d97c51792f896 | python/google/protobuf/message.py | python | _InternalConstructMessage | (full_name) | return symbol_database.Default().GetSymbol(full_name)() | Constructs a nested message. | Constructs a nested message. | [
"Constructs",
"a",
"nested",
"message",
"."
] | def _InternalConstructMessage(full_name):
"""Constructs a nested message."""
from google.protobuf import symbol_database # pylint:disable=g-import-not-at-top
return symbol_database.Default().GetSymbol(full_name)() | [
"def",
"_InternalConstructMessage",
"(",
"full_name",
")",
":",
"from",
"google",
".",
"protobuf",
"import",
"symbol_database",
"# pylint:disable=g-import-not-at-top",
"return",
"symbol_database",
".",
"Default",
"(",
")",
".",
"GetSymbol",
"(",
"full_name",
")",
"(",... | https://github.com/protocolbuffers/protobuf/blob/b5ab0b7a18b7336c60130f4ddb2d97c51792f896/python/google/protobuf/message.py#L417-L421 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/extern/flatnotebook.py | python | FlatNotebook.DeleteAllPages | (self) | return True | Deletes all the pages. | Deletes all the pages. | [
"Deletes",
"all",
"the",
"pages",
"."
] | def DeleteAllPages(self):
""" Deletes all the pages. """
if not self._windows:
return False
self.Freeze()
for page in self._windows:
page.Destroy()
self._windows = []
self.Thaw()
# Clear the container of the tabs as well
self._pages.DeleteAllPages()
return True | [
"def",
"DeleteAllPages",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_windows",
":",
"return",
"False",
"self",
".",
"Freeze",
"(",
")",
"for",
"page",
"in",
"self",
".",
"_windows",
":",
"page",
".",
"Destroy",
"(",
")",
"self",
".",
"_windows... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/flatnotebook.py#L3379-L3395 | |
SFTtech/openage | d6a08c53c48dc1e157807471df92197f6ca9e04d | openage/util/struct.py | python | NamedStruct.__len__ | (self) | return len(self._attributes) | Returns the number of fields. | Returns the number of fields. | [
"Returns",
"the",
"number",
"of",
"fields",
"."
] | def __len__(self):
"""
Returns the number of fields.
"""
return len(self._attributes) | [
"def",
"__len__",
"(",
"self",
")",
":",
"return",
"len",
"(",
"self",
".",
"_attributes",
")"
] | https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/util/struct.py#L172-L176 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib2to3/btm_matcher.py | python | BottomMatcher.print_ac | (self) | Prints a graphviz diagram of the BM automaton(for debugging) | Prints a graphviz diagram of the BM automaton(for debugging) | [
"Prints",
"a",
"graphviz",
"diagram",
"of",
"the",
"BM",
"automaton",
"(",
"for",
"debugging",
")"
] | def print_ac(self):
"Prints a graphviz diagram of the BM automaton(for debugging)"
print("digraph g{")
def print_node(node):
for subnode_key in node.transition_table.keys():
subnode = node.transition_table[subnode_key]
print("%d -> %d [label=%s] //%s" %
(node.id, subnode.id, type_repr(subnode_key), str(subnode.fixers)))
if subnode_key == 1:
print(subnode.content)
print_node(subnode)
print_node(self.root)
print("}") | [
"def",
"print_ac",
"(",
"self",
")",
":",
"print",
"(",
"\"digraph g{\"",
")",
"def",
"print_node",
"(",
"node",
")",
":",
"for",
"subnode_key",
"in",
"node",
".",
"transition_table",
".",
"keys",
"(",
")",
":",
"subnode",
"=",
"node",
".",
"transition_t... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib2to3/btm_matcher.py#L144-L156 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_controls.py | python | DatePickerCtrl.__init__ | (self, *args, **kwargs) | __init__(self, Window parent, int id=-1, DateTime dt=wxDefaultDateTime,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=wxDP_DEFAULT|wxDP_SHOWCENTURY,
Validator validator=DefaultValidator,
String name=DatePickerCtrlNameStr) -> DatePickerCtrl
Create a new DatePickerCtrl. | __init__(self, Window parent, int id=-1, DateTime dt=wxDefaultDateTime,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=wxDP_DEFAULT|wxDP_SHOWCENTURY,
Validator validator=DefaultValidator,
String name=DatePickerCtrlNameStr) -> DatePickerCtrl | [
"__init__",
"(",
"self",
"Window",
"parent",
"int",
"id",
"=",
"-",
"1",
"DateTime",
"dt",
"=",
"wxDefaultDateTime",
"Point",
"pos",
"=",
"DefaultPosition",
"Size",
"size",
"=",
"DefaultSize",
"long",
"style",
"=",
"wxDP_DEFAULT|wxDP_SHOWCENTURY",
"Validator",
"... | def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, DateTime dt=wxDefaultDateTime,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=wxDP_DEFAULT|wxDP_SHOWCENTURY,
Validator validator=DefaultValidator,
String name=DatePickerCtrlNameStr) -> DatePickerCtrl
Create a new DatePickerCtrl.
"""
_controls_.DatePickerCtrl_swiginit(self,_controls_.new_DatePickerCtrl(*args, **kwargs))
self._setOORInfo(self) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_controls_",
".",
"DatePickerCtrl_swiginit",
"(",
"self",
",",
"_controls_",
".",
"new_DatePickerCtrl",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"self",
"... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L6502-L6513 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/dtypes/common.py | python | is_1d_only_ea_obj | (obj: Any) | return isinstance(obj, ExtensionArray) and not isinstance(
obj, (DatetimeArray, TimedeltaArray)
) | ExtensionArray that does not support 2D, or more specifically that does
not use HybridBlock. | ExtensionArray that does not support 2D, or more specifically that does
not use HybridBlock. | [
"ExtensionArray",
"that",
"does",
"not",
"support",
"2D",
"or",
"more",
"specifically",
"that",
"does",
"not",
"use",
"HybridBlock",
"."
] | def is_1d_only_ea_obj(obj: Any) -> bool:
"""
ExtensionArray that does not support 2D, or more specifically that does
not use HybridBlock.
"""
from pandas.core.arrays import (
DatetimeArray,
ExtensionArray,
TimedeltaArray,
)
return isinstance(obj, ExtensionArray) and not isinstance(
obj, (DatetimeArray, TimedeltaArray)
) | [
"def",
"is_1d_only_ea_obj",
"(",
"obj",
":",
"Any",
")",
"->",
"bool",
":",
"from",
"pandas",
".",
"core",
".",
"arrays",
"import",
"(",
"DatetimeArray",
",",
"ExtensionArray",
",",
"TimedeltaArray",
",",
")",
"return",
"isinstance",
"(",
"obj",
",",
"Exte... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/dtypes/common.py#L1393-L1406 | |
InsightSoftwareConsortium/ITK | 87acfce9a93d928311c38bc371b666b515b9f19d | Modules/ThirdParty/pygccxml/src/pygccxml/parser/config.py | python | parser_configuration_t.keep_xml | (self, keep_xml) | Set if xml files kept after errors. | Set if xml files kept after errors. | [
"Set",
"if",
"xml",
"files",
"kept",
"after",
"errors",
"."
] | def keep_xml(self, keep_xml):
"""Set if xml files kept after errors."""
self.__keep_xml = keep_xml | [
"def",
"keep_xml",
"(",
"self",
",",
"keep_xml",
")",
":",
"self",
".",
"__keep_xml",
"=",
"keep_xml"
] | https://github.com/InsightSoftwareConsortium/ITK/blob/87acfce9a93d928311c38bc371b666b515b9f19d/Modules/ThirdParty/pygccxml/src/pygccxml/parser/config.py#L161-L163 | ||
Tencent/CMONGO | c40380caa14e05509f46993aa8b8da966b09b0b5 | buildscripts/cpplint.py | python | CheckDefaultLambdaCaptures | (filename, clean_lines, linenum, error) | Check that default lambda captures are not used.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Check that default lambda captures are not used. | [
"Check",
"that",
"default",
"lambda",
"captures",
"are",
"not",
"used",
"."
] | def CheckDefaultLambdaCaptures(filename, clean_lines, linenum, error):
"""Check that default lambda captures are not used.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
# A lambda introducer specifies a default capture if it starts with "[="
# or if it starts with "[&" _not_ followed by an identifier.
match = Match(r'^(.*)\[\s*(?:=|&[^\w])', line)
if match:
# Found a potential error, check what comes after the lambda-introducer.
# If it's not open parenthesis (for lambda-declarator) or open brace
# (for compound-statement), it's not a lambda.
line, _, pos = CloseExpression(clean_lines, linenum, len(match.group(1)))
if pos >= 0 and Match(r'^\s*[{(]', line[pos:]):
error(filename, linenum, 'build/c++11',
4, # 4 = high confidence
'Default lambda captures are an unapproved C++ feature.') | [
"def",
"CheckDefaultLambdaCaptures",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"# A lambda introducer specifies a default capture if it starts with \"[=\"",
"# or if it starts... | https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/buildscripts/cpplint.py#L5623-L5645 | ||
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/deps/v8/PRESUBMIT.py | python | _CheckCommitMessageBugEntry | (input_api, output_api) | return [output_api.PresubmitError(r) for r in results] | Check that bug entries are well-formed in commit message. | Check that bug entries are well-formed in commit message. | [
"Check",
"that",
"bug",
"entries",
"are",
"well",
"-",
"formed",
"in",
"commit",
"message",
"."
] | def _CheckCommitMessageBugEntry(input_api, output_api):
"""Check that bug entries are well-formed in commit message."""
bogus_bug_msg = (
'Bogus BUG entry: %s. Please specify the issue tracker prefix and the '
'issue number, separated by a colon, e.g. v8:123 or chromium:12345.')
results = []
for bug in (input_api.change.BUG or '').split(','):
bug = bug.strip()
if 'none'.startswith(bug.lower()):
continue
if ':' not in bug:
try:
if int(bug) > 100000:
# Rough indicator for current chromium bugs.
prefix_guess = 'chromium'
else:
prefix_guess = 'v8'
results.append('BUG entry requires issue tracker prefix, e.g. %s:%s' %
(prefix_guess, bug))
except ValueError:
results.append(bogus_bug_msg % bug)
elif not re.match(r'\w+:\d+', bug):
results.append(bogus_bug_msg % bug)
return [output_api.PresubmitError(r) for r in results] | [
"def",
"_CheckCommitMessageBugEntry",
"(",
"input_api",
",",
"output_api",
")",
":",
"bogus_bug_msg",
"=",
"(",
"'Bogus BUG entry: %s. Please specify the issue tracker prefix and the '",
"'issue number, separated by a colon, e.g. v8:123 or chromium:12345.'",
")",
"results",
"=",
"[",... | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/v8/PRESUBMIT.py#L328-L351 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/codecs.py | python | getdecoder | (encoding) | return lookup(encoding).decode | Lookup up the codec for the given encoding and return
its decoder function.
Raises a LookupError in case the encoding cannot be found. | Lookup up the codec for the given encoding and return
its decoder function. | [
"Lookup",
"up",
"the",
"codec",
"for",
"the",
"given",
"encoding",
"and",
"return",
"its",
"decoder",
"function",
"."
] | def getdecoder(encoding):
""" Lookup up the codec for the given encoding and return
its decoder function.
Raises a LookupError in case the encoding cannot be found.
"""
return lookup(encoding).decode | [
"def",
"getdecoder",
"(",
"encoding",
")",
":",
"return",
"lookup",
"(",
"encoding",
")",
".",
"decode"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/codecs.py#L938-L946 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/protobuf/python/mox.py | python | MockObject.__init__ | (self, class_to_mock) | Initialize a mock object.
This determines the methods and properties of the class and stores them.
Args:
# class_to_mock: class to be mocked
class_to_mock: class | Initialize a mock object. | [
"Initialize",
"a",
"mock",
"object",
"."
] | def __init__(self, class_to_mock):
"""Initialize a mock object.
This determines the methods and properties of the class and stores them.
Args:
# class_to_mock: class to be mocked
class_to_mock: class
"""
# This is used to hack around the mixin/inheritance of MockAnything, which
# is not a proper object (it can be anything. :-)
MockAnything.__dict__['__init__'](self)
# Get a list of all the public and special methods we should mock.
self._known_methods = set()
self._known_vars = set()
self._class_to_mock = class_to_mock
for method in dir(class_to_mock):
if callable(getattr(class_to_mock, method)):
self._known_methods.add(method)
else:
self._known_vars.add(method) | [
"def",
"__init__",
"(",
"self",
",",
"class_to_mock",
")",
":",
"# This is used to hack around the mixin/inheritance of MockAnything, which",
"# is not a proper object (it can be anything. :-)",
"MockAnything",
".",
"__dict__",
"[",
"'__init__'",
"]",
"(",
"self",
")",
"# Get a... | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/protobuf/python/mox.py#L362-L384 | ||
gimli-org/gimli | 17aa2160de9b15ababd9ef99e89b1bc3277bbb23 | doc/apigen.py | python | ApiDocWriter._parse_module | (self, uri) | return functions, classes | Parse module defined in *uri* | Parse module defined in *uri* | [
"Parse",
"module",
"defined",
"in",
"*",
"uri",
"*"
] | def _parse_module(self, uri):
""" Parse module defined in *uri* """
filename = self._uri2path(uri)
if filename is None:
print(filename, 'erk')
# nothing that we could handle here.
return ([], [])
f = open(filename, 'rt')
functions, classes = self._parse_lines(f)
f.close()
return functions, classes | [
"def",
"_parse_module",
"(",
"self",
",",
"uri",
")",
":",
"filename",
"=",
"self",
".",
"_uri2path",
"(",
"uri",
")",
"if",
"filename",
"is",
"None",
":",
"print",
"(",
"filename",
",",
"'erk'",
")",
"# nothing that we could handle here.",
"return",
"(",
... | https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/doc/apigen.py#L188-L198 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/richtext.py | python | RichTextBuffer.EndTextColour | (*args, **kwargs) | return _richtext.RichTextBuffer_EndTextColour(*args, **kwargs) | EndTextColour(self) -> bool | EndTextColour(self) -> bool | [
"EndTextColour",
"(",
"self",
")",
"-",
">",
"bool"
] | def EndTextColour(*args, **kwargs):
"""EndTextColour(self) -> bool"""
return _richtext.RichTextBuffer_EndTextColour(*args, **kwargs) | [
"def",
"EndTextColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextBuffer_EndTextColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L2377-L2379 | |
KratosMultiphysics/Kratos | 0000833054ed0503424eb28205d6508d9ca6cbbc | applications/StructuralMechanicsApplication/python_scripts/perturb_geometry_sparse_utility.py | python | PerturbGeometrySparseUtility.__init__ | (self, mp, settings ) | Constructor of Utility-Object
Checks parameter settings and initializes the utility. | Constructor of Utility-Object | [
"Constructor",
"of",
"Utility",
"-",
"Object"
] | def __init__(self, mp, settings ):
"""Constructor of Utility-Object
Checks parameter settings and initializes the utility.
"""
default_settings = KratosMultiphysics.Parameters("""{
"eigensolver_settings" : {
"solver_type" : "eigen_eigensystem",
"max_iteration" : 1000,
"tolerance" : 1e-4,
"number_of_eigenvalues" : 100,
"normalize_eigenvectors" : false,
"echo_level" : 0
},
"perturbation_settings" : {
"max_displacement" : 1,
"correlation_length" : 100,
"truncation_error" : 1e-3,
"echo_level" : 0
}
}""")
settings.ValidateAndAssignDefaults(default_settings)
eigen_solver = eigen_solver_factory.ConstructSolver(settings["eigensolver_settings"])
mp.AddNodalSolutionStepVariable(KratosMultiphysics.NORMAL)
perturbation_settings = settings["perturbation_settings"]
# Initialize utility
self.utility = StructuralMechanicsApplication.PerturbGeometrySparseUtility(mp, eigen_solver, perturbation_settings)
# Generate perturbation matrix
self.number_random_variables = self.utility.CreateRandomFieldVectors() | [
"def",
"__init__",
"(",
"self",
",",
"mp",
",",
"settings",
")",
":",
"default_settings",
"=",
"KratosMultiphysics",
".",
"Parameters",
"(",
"\"\"\"{\n \"eigensolver_settings\" : {\n \"solver_type\" : \"eigen_eigensystem\",\n \"... | https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/StructuralMechanicsApplication/python_scripts/perturb_geometry_sparse_utility.py#L15-L45 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/Maya_AnimationRiggingTools/ARTv1/MayaTools/General/Scripts/Modules/facial/utils.py | python | createArrow | (name=None, thickness=0.1, length=2, vector=[1,0,0], point=[0,0,0]) | return xform | Creates an arrow in the direction of the vector
Example:
arrow = createArrow(vector=[0,1,0], length=4) | [] | def createArrow(name=None, thickness=0.1, length=2, vector=[1,0,0], point=[0,0,0]):
'''
Creates an arrow in the direction of the vector
Example:
arrow = createArrow(vector=[0,1,0], length=4)
'''
if not name:
name = 'arrow_CTRL'
#calc length for thickness
ratio = length/thickness
cyl = cmds.cylinder(radius=thickness, sections=4, heightRatio=ratio, pivot=[length/2, 0, 0], ch=0)[0]
cone = cmds.cone(radius=thickness*2, sections=4, ch=0, pivot=(length*1.0005,0,0))[0]
xform = cmds.createNode('transform', ss=1, name=name)
shapes = []
transforms = []
for node in [cone,cyl]:
shapes.append(cmds.listRelatives(node, fullPath=1, shapes=1)[0])
transforms.append(node)
cmds.parent(shapes, xform, r=1, s=1)
rotateBy = cmds.angleBetween(euler=True, v1=(1,0,0), v2=vector)
cmds.rotate(rotateBy[0], rotateBy[1], rotateBy[2], xform)
cmds.xform(xform, t=point)
cmds.delete(transforms)
return xform | [
"def",
"createArrow",
"(",
"name",
"=",
"None",
",",
"thickness",
"=",
"0.1",
",",
"length",
"=",
"2",
",",
"vector",
"=",
"[",
"1",
",",
"0",
",",
"0",
"]",
",",
"point",
"=",
"[",
"0",
",",
"0",
",",
"0",
"]",
")",
":",
"if",
"not",
"name... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/Maya_AnimationRiggingTools/ARTv1/MayaTools/General/Scripts/Modules/facial/utils.py#L315-L363 | ||
stereolabs/zed-examples | ed3f068301fbdf3898f7c42de864dc578467e061 | object detection/birds eye viewer/python/batch_system_handler.py | python | BatchSystemHandler.__del__ | (self) | BatchSystemHandler destructor | BatchSystemHandler destructor | [
"BatchSystemHandler",
"destructor"
] | def __del__(self):
'''
BatchSystemHandler destructor
'''
self.clear() | [
"def",
"__del__",
"(",
"self",
")",
":",
"self",
".",
"clear",
"(",
")"
] | https://github.com/stereolabs/zed-examples/blob/ed3f068301fbdf3898f7c42de864dc578467e061/object detection/birds eye viewer/python/batch_system_handler.py#L35-L39 | ||
Cisco-Talos/moflow | ed71dfb0540d9e0d7a4c72f0881b58958d573728 | BAP-0.7-moflow/libtracewrap/libtrace/protobuf/python/google/protobuf/internal/wire_format.py | python | PackTag | (field_number, wire_type) | return (field_number << TAG_TYPE_BITS) | wire_type | Returns an unsigned 32-bit integer that encodes the field number and
wire type information in standard protocol message wire format.
Args:
field_number: Expected to be an integer in the range [1, 1 << 29)
wire_type: One of the WIRETYPE_* constants. | Returns an unsigned 32-bit integer that encodes the field number and
wire type information in standard protocol message wire format. | [
"Returns",
"an",
"unsigned",
"32",
"-",
"bit",
"integer",
"that",
"encodes",
"the",
"field",
"number",
"and",
"wire",
"type",
"information",
"in",
"standard",
"protocol",
"message",
"wire",
"format",
"."
] | def PackTag(field_number, wire_type):
"""Returns an unsigned 32-bit integer that encodes the field number and
wire type information in standard protocol message wire format.
Args:
field_number: Expected to be an integer in the range [1, 1 << 29)
wire_type: One of the WIRETYPE_* constants.
"""
if not 0 <= wire_type <= _WIRETYPE_MAX:
raise message.EncodeError('Unknown wire type: %d' % wire_type)
return (field_number << TAG_TYPE_BITS) | wire_type | [
"def",
"PackTag",
"(",
"field_number",
",",
"wire_type",
")",
":",
"if",
"not",
"0",
"<=",
"wire_type",
"<=",
"_WIRETYPE_MAX",
":",
"raise",
"message",
".",
"EncodeError",
"(",
"'Unknown wire type: %d'",
"%",
"wire_type",
")",
"return",
"(",
"field_number",
"<... | https://github.com/Cisco-Talos/moflow/blob/ed71dfb0540d9e0d7a4c72f0881b58958d573728/BAP-0.7-moflow/libtracewrap/libtrace/protobuf/python/google/protobuf/internal/wire_format.py#L80-L90 | |
ucbrise/confluo | 578883a4f7fbbb4aea78c342d366f5122ef598f7 | pyclient/confluo/rpc/rpc_service.py | python | Iface.get_atomic_multilog_info | (self, name) | Parameters:
- name | Parameters:
- name | [
"Parameters",
":",
"-",
"name"
] | def get_atomic_multilog_info(self, name):
"""
Parameters:
- name
"""
pass | [
"def",
"get_atomic_multilog_info",
"(",
"self",
",",
"name",
")",
":",
"pass"
] | https://github.com/ucbrise/confluo/blob/578883a4f7fbbb4aea78c342d366f5122ef598f7/pyclient/confluo/rpc/rpc_service.py#L50-L56 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/html.py | python | HtmlFontCell.__init__ | (self, *args, **kwargs) | __init__(self, Font font) -> HtmlFontCell | __init__(self, Font font) -> HtmlFontCell | [
"__init__",
"(",
"self",
"Font",
"font",
")",
"-",
">",
"HtmlFontCell"
] | def __init__(self, *args, **kwargs):
"""__init__(self, Font font) -> HtmlFontCell"""
_html.HtmlFontCell_swiginit(self,_html.new_HtmlFontCell(*args, **kwargs)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_html",
".",
"HtmlFontCell_swiginit",
"(",
"self",
",",
"_html",
".",
"new_HtmlFontCell",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/html.py#L886-L888 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/config.py | python | IdleConf.CurrentTheme | (self) | return self.current_colors_and_keys('Theme') | Return the name of the currently active text color theme. | Return the name of the currently active text color theme. | [
"Return",
"the",
"name",
"of",
"the",
"currently",
"active",
"text",
"color",
"theme",
"."
] | def CurrentTheme(self):
"Return the name of the currently active text color theme."
return self.current_colors_and_keys('Theme') | [
"def",
"CurrentTheme",
"(",
"self",
")",
":",
"return",
"self",
".",
"current_colors_and_keys",
"(",
"'Theme'",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/config.py#L357-L359 | |
google/shaka-packager | e1b0c7c45431327fd3ce193514a5407d07b39b22 | packager/third_party/protobuf/python/google/protobuf/internal/encoder.py | python | TagBytes | (field_number, wire_type) | return _VarintBytes(wire_format.PackTag(field_number, wire_type)) | Encode the given tag and return the bytes. Only called at startup. | Encode the given tag and return the bytes. Only called at startup. | [
"Encode",
"the",
"given",
"tag",
"and",
"return",
"the",
"bytes",
".",
"Only",
"called",
"at",
"startup",
"."
] | def TagBytes(field_number, wire_type):
"""Encode the given tag and return the bytes. Only called at startup."""
return _VarintBytes(wire_format.PackTag(field_number, wire_type)) | [
"def",
"TagBytes",
"(",
"field_number",
",",
"wire_type",
")",
":",
"return",
"_VarintBytes",
"(",
"wire_format",
".",
"PackTag",
"(",
"field_number",
",",
"wire_type",
")",
")"
] | https://github.com/google/shaka-packager/blob/e1b0c7c45431327fd3ce193514a5407d07b39b22/packager/third_party/protobuf/python/google/protobuf/internal/encoder.py#L418-L421 | |
gem5/gem5 | 141cc37c2d4b93959d4c249b8f7e6a8b2ef75338 | util/minorview/model.py | python | BlobModel.add_unit_event | (self, event) | Add a single event to the model. This must be an event at a
time >= the current maximum time | Add a single event to the model. This must be an event at a
time >= the current maximum time | [
"Add",
"a",
"single",
"event",
"to",
"the",
"model",
".",
"This",
"must",
"be",
"an",
"event",
"at",
"a",
"time",
">",
"=",
"the",
"current",
"maximum",
"time"
] | def add_unit_event(self, event):
"""Add a single event to the model. This must be an event at a
time >= the current maximum time"""
if event.unit in self.unitEvents:
events = self.unitEvents[event.unit]
if len(events) > 0 and events[len(events)-1].time > event.time:
print("Bad event ordering")
events.append(event)
self.numEvents += 1
self.lastTime = max(self.lastTime, event.time) | [
"def",
"add_unit_event",
"(",
"self",
",",
"event",
")",
":",
"if",
"event",
".",
"unit",
"in",
"self",
".",
"unitEvents",
":",
"events",
"=",
"self",
".",
"unitEvents",
"[",
"event",
".",
"unit",
"]",
"if",
"len",
"(",
"events",
")",
">",
"0",
"an... | https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/util/minorview/model.py#L596-L605 | ||
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/simpla/_pvehicle.py | python | PVehicle.resetSwitchWaitingTime | (self, mode=None) | resetSwitchWaitingTime(PlatoonMode) -> void
Resets waiting time for a switch to a mode to 0. or, if mode==None, all times are reset to 0.
The active speed factor is also reset. | resetSwitchWaitingTime(PlatoonMode) -> void | [
"resetSwitchWaitingTime",
"(",
"PlatoonMode",
")",
"-",
">",
"void"
] | def resetSwitchWaitingTime(self, mode=None):
'''resetSwitchWaitingTime(PlatoonMode) -> void
Resets waiting time for a switch to a mode to 0. or, if mode==None, all times are reset to 0.
The active speed factor is also reset.
'''
if rp.VERBOSITY >= 4:
report("Vehicle '%s' resets switch waiting time." % self._ID, 3)
if mode is None:
for e in PlatoonMode:
self._switchWaitingTime[e] = 0.
else:
self._switchWaitingTime[mode] = 0.
self._resetActiveSpeedFactor() | [
"def",
"resetSwitchWaitingTime",
"(",
"self",
",",
"mode",
"=",
"None",
")",
":",
"if",
"rp",
".",
"VERBOSITY",
">=",
"4",
":",
"report",
"(",
"\"Vehicle '%s' resets switch waiting time.\"",
"%",
"self",
".",
"_ID",
",",
"3",
")",
"if",
"mode",
"is",
"None... | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/simpla/_pvehicle.py#L238-L251 | ||
gimli-org/gimli | 17aa2160de9b15ababd9ef99e89b1bc3277bbb23 | core/python/apps/script_template.py | python | main | () | Entry function | Entry function | [
"Entry",
"function"
] | def main():
"""
Entry function
"""
import argparse
# intialisize parser
parser = argparse.ArgumentParser(description="sample application")
# define some options (better import from defaultParser)
parser.add_argument("-v", "--verbose", dest="verbose", action="store_true",
help="Be verbose")
parser.add_argument("-i", "--integer", dest="integer", type=int,
help="Eine Integer Variable mit long und short option",
default=0)
parser.add_argument("-s", dest="string", type=str,
help="Eine string Variable mit short option",
default='none')
parser.add_argument('target')
args = parser.parse_args()
# results are in args
if args.verbose:
print(args)
print('Integer is:', args.integer)
print('String is:', args.string)
print('Target is:', args.target) | [
"def",
"main",
"(",
")",
":",
"import",
"argparse",
"# intialisize parser",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"sample application\"",
")",
"# define some options (better import from defaultParser)",
"parser",
".",
"add_argument",
... | https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/core/python/apps/script_template.py#L11-L41 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/decomposition/pca.py | python | _assess_dimension_ | (spectrum, rank, n_samples, n_features) | return ll | Compute the likelihood of a rank ``rank`` dataset
The dataset is assumed to be embedded in gaussian noise of shape(n,
dimf) having spectrum ``spectrum``.
Parameters
----------
spectrum: array of shape (n)
Data spectrum.
rank: int
Tested rank value.
n_samples: int
Number of samples.
n_features: int
Number of features.
Returns
-------
ll: float,
The log-likelihood
Notes
-----
This implements the method of `Thomas P. Minka:
Automatic Choice of Dimensionality for PCA. NIPS 2000: 598-604` | Compute the likelihood of a rank ``rank`` dataset | [
"Compute",
"the",
"likelihood",
"of",
"a",
"rank",
"rank",
"dataset"
] | def _assess_dimension_(spectrum, rank, n_samples, n_features):
"""Compute the likelihood of a rank ``rank`` dataset
The dataset is assumed to be embedded in gaussian noise of shape(n,
dimf) having spectrum ``spectrum``.
Parameters
----------
spectrum: array of shape (n)
Data spectrum.
rank: int
Tested rank value.
n_samples: int
Number of samples.
n_features: int
Number of features.
Returns
-------
ll: float,
The log-likelihood
Notes
-----
This implements the method of `Thomas P. Minka:
Automatic Choice of Dimensionality for PCA. NIPS 2000: 598-604`
"""
if rank > len(spectrum):
raise ValueError("The tested rank cannot exceed the rank of the"
" dataset")
pu = -rank * log(2.)
for i in range(rank):
pu += (gammaln((n_features - i) / 2.) -
log(np.pi) * (n_features - i) / 2.)
pl = np.sum(np.log(spectrum[:rank]))
pl = -pl * n_samples / 2.
if rank == n_features:
pv = 0
v = 1
else:
v = np.sum(spectrum[rank:]) / (n_features - rank)
pv = -np.log(v) * n_samples * (n_features - rank) / 2.
m = n_features * rank - rank * (rank + 1.) / 2.
pp = log(2. * np.pi) * (m + rank + 1.) / 2.
pa = 0.
spectrum_ = spectrum.copy()
spectrum_[rank:n_features] = v
for i in range(rank):
for j in range(i + 1, len(spectrum)):
pa += log((spectrum[i] - spectrum[j]) *
(1. / spectrum_[j] - 1. / spectrum_[i])) + log(n_samples)
ll = pu + pl + pv + pp - pa / 2. - rank * log(n_samples) / 2.
return ll | [
"def",
"_assess_dimension_",
"(",
"spectrum",
",",
"rank",
",",
"n_samples",
",",
"n_features",
")",
":",
"if",
"rank",
">",
"len",
"(",
"spectrum",
")",
":",
"raise",
"ValueError",
"(",
"\"The tested rank cannot exceed the rank of the\"",
"\" dataset\"",
")",
"pu... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/decomposition/pca.py#L32-L91 | |
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | TPM2_ClearControl_REQUEST.toTpm | (self, buf) | TpmMarshaller method | TpmMarshaller method | [
"TpmMarshaller",
"method"
] | def toTpm(self, buf):
""" TpmMarshaller method """
buf.writeByte(self.disable) | [
"def",
"toTpm",
"(",
"self",
",",
"buf",
")",
":",
"buf",
".",
"writeByte",
"(",
"self",
".",
"disable",
")"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L15589-L15591 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pkg_resources/__init__.py | python | non_empty_lines | (path) | Yield non-empty lines from file at path | Yield non-empty lines from file at path | [
"Yield",
"non",
"-",
"empty",
"lines",
"from",
"file",
"at",
"path"
] | def non_empty_lines(path):
"""
Yield non-empty lines from file at path
"""
with open(path) as f:
for line in f:
line = line.strip()
if line:
yield line | [
"def",
"non_empty_lines",
"(",
"path",
")",
":",
"with",
"open",
"(",
"path",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"line",
":",
"yield",
"line"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pkg_resources/__init__.py#L2153-L2161 | ||
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | GetMxWcc | (*args) | return _snap.GetMxWcc(*args) | GetMxWcc(PNEANet Graph) -> PNEANet
Parameters:
Graph: TPt< TNEANet > const & | GetMxWcc(PNEANet Graph) -> PNEANet | [
"GetMxWcc",
"(",
"PNEANet",
"Graph",
")",
"-",
">",
"PNEANet"
] | def GetMxWcc(*args):
"""
GetMxWcc(PNEANet Graph) -> PNEANet
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.GetMxWcc(*args) | [
"def",
"GetMxWcc",
"(",
"*",
"args",
")",
":",
"return",
"_snap",
".",
"GetMxWcc",
"(",
"*",
"args",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L24692-L24700 | |
apiaryio/drafter | 4634ebd07f6c6f257cc656598ccd535492fdfb55 | tools/gyp/pylib/gyp/win_tool.py | python | WinTool.ExecClCompile | (self, project_dir, selected_files) | return subprocess.call(cmd, shell=True, cwd=BASE_DIR) | Executed by msvs-ninja projects when the 'ClCompile' target is used to
build selected C/C++ files. | Executed by msvs-ninja projects when the 'ClCompile' target is used to
build selected C/C++ files. | [
"Executed",
"by",
"msvs",
"-",
"ninja",
"projects",
"when",
"the",
"ClCompile",
"target",
"is",
"used",
"to",
"build",
"selected",
"C",
"/",
"C",
"++",
"files",
"."
] | def ExecClCompile(self, project_dir, selected_files):
"""Executed by msvs-ninja projects when the 'ClCompile' target is used to
build selected C/C++ files."""
project_dir = os.path.relpath(project_dir, BASE_DIR)
selected_files = selected_files.split(';')
ninja_targets = [os.path.join(project_dir, filename) + '^^'
for filename in selected_files]
cmd = ['ninja.exe']
cmd.extend(ninja_targets)
return subprocess.call(cmd, shell=True, cwd=BASE_DIR) | [
"def",
"ExecClCompile",
"(",
"self",
",",
"project_dir",
",",
"selected_files",
")",
":",
"project_dir",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"project_dir",
",",
"BASE_DIR",
")",
"selected_files",
"=",
"selected_files",
".",
"split",
"(",
"';'",
")",... | https://github.com/apiaryio/drafter/blob/4634ebd07f6c6f257cc656598ccd535492fdfb55/tools/gyp/pylib/gyp/win_tool.py#L302-L311 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/lib2to3/pytree.py | python | Base.clone | (self) | Return a cloned (deep) copy of self.
This must be implemented by the concrete subclass. | Return a cloned (deep) copy of self. | [
"Return",
"a",
"cloned",
"(",
"deep",
")",
"copy",
"of",
"self",
"."
] | def clone(self):
"""
Return a cloned (deep) copy of self.
This must be implemented by the concrete subclass.
"""
raise NotImplementedError | [
"def",
"clone",
"(",
"self",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/lib2to3/pytree.py#L77-L83 | ||
BitMEX/api-connectors | 37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812 | auto-generated/python/swagger_client/models/execution.py | python | Execution.display_qty | (self, display_qty) | Sets the display_qty of this Execution.
:param display_qty: The display_qty of this Execution. # noqa: E501
:type: float | Sets the display_qty of this Execution. | [
"Sets",
"the",
"display_qty",
"of",
"this",
"Execution",
"."
] | def display_qty(self, display_qty):
"""Sets the display_qty of this Execution.
:param display_qty: The display_qty of this Execution. # noqa: E501
:type: float
"""
self._display_qty = display_qty | [
"def",
"display_qty",
"(",
"self",
",",
"display_qty",
")",
":",
"self",
".",
"_display_qty",
"=",
"display_qty"
] | https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/execution.py#L607-L615 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/xmlrpc/server.py | python | CGIXMLRPCRequestHandler.handle_xmlrpc | (self, request_text) | Handle a single XML-RPC request | Handle a single XML-RPC request | [
"Handle",
"a",
"single",
"XML",
"-",
"RPC",
"request"
] | def handle_xmlrpc(self, request_text):
"""Handle a single XML-RPC request"""
response = self._marshaled_dispatch(request_text)
print('Content-Type: text/xml')
print('Content-Length: %d' % len(response))
print()
sys.stdout.flush()
sys.stdout.buffer.write(response)
sys.stdout.buffer.flush() | [
"def",
"handle_xmlrpc",
"(",
"self",
",",
"request_text",
")",
":",
"response",
"=",
"self",
".",
"_marshaled_dispatch",
"(",
"request_text",
")",
"print",
"(",
"'Content-Type: text/xml'",
")",
"print",
"(",
"'Content-Length: %d'",
"%",
"len",
"(",
"response",
"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/xmlrpc/server.py#L658-L668 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/imaplib.py | python | IMAP4.send | (self, data) | Send data to remote. | Send data to remote. | [
"Send",
"data",
"to",
"remote",
"."
] | def send(self, data):
"""Send data to remote."""
self.sock.sendall(data) | [
"def",
"send",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"sock",
".",
"sendall",
"(",
"data",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/imaplib.py#L316-L318 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | WindowList.__iter__ | (*args, **kwargs) | return _core_.WindowList___iter__(*args, **kwargs) | __iter__(self) -> WindowList_iterator | __iter__(self) -> WindowList_iterator | [
"__iter__",
"(",
"self",
")",
"-",
">",
"WindowList_iterator"
] | def __iter__(*args, **kwargs):
"""__iter__(self) -> WindowList_iterator"""
return _core_.WindowList___iter__(*args, **kwargs) | [
"def",
"__iter__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"WindowList___iter__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L9067-L9069 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/difflib.py | python | HtmlDiff._collect_lines | (self,diffs) | return fromlist,tolist,flaglist | Collects mdiff output into separate lists
Before storing the mdiff from/to data into a list, it is converted
into a single line of text with HTML markup. | Collects mdiff output into separate lists | [
"Collects",
"mdiff",
"output",
"into",
"separate",
"lists"
] | def _collect_lines(self,diffs):
"""Collects mdiff output into separate lists
Before storing the mdiff from/to data into a list, it is converted
into a single line of text with HTML markup.
"""
fromlist,tolist,flaglist = [],[],[]
# pull from/to data and flags from mdiff style iterator
for fromdata,todata,flag in diffs:
try:
# store HTML markup of the lines into the lists
fromlist.append(self._format_line(0,flag,*fromdata))
tolist.append(self._format_line(1,flag,*todata))
except TypeError:
# exceptions occur for lines where context separators go
fromlist.append(None)
tolist.append(None)
flaglist.append(flag)
return fromlist,tolist,flaglist | [
"def",
"_collect_lines",
"(",
"self",
",",
"diffs",
")",
":",
"fromlist",
",",
"tolist",
",",
"flaglist",
"=",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
"# pull from/to data and flags from mdiff style iterator",
"for",
"fromdata",
",",
"todata",
",",
"flag",
"... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/difflib.py#L1841-L1860 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/config.py | python | ConfigHandler._parse_attr | (cls, value) | return value | Represents value as a module attribute.
Examples:
attr: package.attr
attr: package.module.attr
:param str value:
:rtype: str | Represents value as a module attribute. | [
"Represents",
"value",
"as",
"a",
"module",
"attribute",
"."
] | def _parse_attr(cls, value):
"""Represents value as a module attribute.
Examples:
attr: package.attr
attr: package.module.attr
:param str value:
:rtype: str
"""
attr_directive = 'attr:'
if not value.startswith(attr_directive):
return value
attrs_path = value.replace(attr_directive, '').strip().split('.')
attr_name = attrs_path.pop()
module_name = '.'.join(attrs_path)
module_name = module_name or '__init__'
sys.path.insert(0, os.getcwd())
try:
module = import_module(module_name)
value = getattr(module, attr_name)
finally:
sys.path = sys.path[1:]
return value | [
"def",
"_parse_attr",
"(",
"cls",
",",
"value",
")",
":",
"attr_directive",
"=",
"'attr:'",
"if",
"not",
"value",
".",
"startswith",
"(",
"attr_directive",
")",
":",
"return",
"value",
"attrs_path",
"=",
"value",
".",
"replace",
"(",
"attr_directive",
",",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/config.py#L283-L311 | |
bigartm/bigartm | 47e37f982de87aa67bfd475ff1f39da696b181b3 | python/artm/master_component.py | python | MasterComponent.normalize_model | (self, pwt, nwt, rwt=None) | :param str pwt: name of pwt matrix in BigARTM
:param str nwt: name of nwt matrix in BigARTM
:param str rwt: name of rwt matrix in BigARTM | :param str pwt: name of pwt matrix in BigARTM
:param str nwt: name of nwt matrix in BigARTM
:param str rwt: name of rwt matrix in BigARTM | [
":",
"param",
"str",
"pwt",
":",
"name",
"of",
"pwt",
"matrix",
"in",
"BigARTM",
":",
"param",
"str",
"nwt",
":",
"name",
"of",
"nwt",
"matrix",
"in",
"BigARTM",
":",
"param",
"str",
"rwt",
":",
"name",
"of",
"rwt",
"matrix",
"in",
"BigARTM"
] | def normalize_model(self, pwt, nwt, rwt=None):
"""
:param str pwt: name of pwt matrix in BigARTM
:param str nwt: name of nwt matrix in BigARTM
:param str rwt: name of rwt matrix in BigARTM
"""
args = messages.NormalizeModelArgs(pwt_target_name=pwt, nwt_source_name=nwt)
if rwt is not None:
args.rwt_source_name = rwt
self._lib.ArtmNormalizeModel(self.master_id, args) | [
"def",
"normalize_model",
"(",
"self",
",",
"pwt",
",",
"nwt",
",",
"rwt",
"=",
"None",
")",
":",
"args",
"=",
"messages",
".",
"NormalizeModelArgs",
"(",
"pwt_target_name",
"=",
"pwt",
",",
"nwt_source_name",
"=",
"nwt",
")",
"if",
"rwt",
"is",
"not",
... | https://github.com/bigartm/bigartm/blob/47e37f982de87aa67bfd475ff1f39da696b181b3/python/artm/master_component.py#L597-L607 | ||
SequoiaDB/SequoiaDB | 2894ed7e5bd6fe57330afc900cf76d0ff0df9f64 | tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py | python | xmlTextReader.Setup | (self, input, URL, encoding, options) | return ret | Setup an XML reader with new options | Setup an XML reader with new options | [
"Setup",
"an",
"XML",
"reader",
"with",
"new",
"options"
] | def Setup(self, input, URL, encoding, options):
"""Setup an XML reader with new options """
if input is None: input__o = None
else: input__o = input._o
ret = libxml2mod.xmlTextReaderSetup(self._o, input__o, URL, encoding, options)
return ret | [
"def",
"Setup",
"(",
"self",
",",
"input",
",",
"URL",
",",
"encoding",
",",
"options",
")",
":",
"if",
"input",
"is",
"None",
":",
"input__o",
"=",
"None",
"else",
":",
"input__o",
"=",
"input",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"xmlTextRead... | https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L6871-L6876 | |
google/mysql-protobuf | 467cda676afaa49e762c5c9164a43f6ad31a1fbf | protobuf/python/mox.py | python | MockObject.__call__ | (self, *params, **named_params) | return mock_method(*params, **named_params) | Provide custom logic for mocking classes that are callable. | Provide custom logic for mocking classes that are callable. | [
"Provide",
"custom",
"logic",
"for",
"mocking",
"classes",
"that",
"are",
"callable",
"."
] | def __call__(self, *params, **named_params):
"""Provide custom logic for mocking classes that are callable."""
# Verify the class we are mocking is callable
callable = self._class_to_mock.__dict__.get('__call__', None)
if callable is None:
raise TypeError('Not callable')
# Because the call is happening directly on this object instead of a method,
# the call on the mock method is made right here
mock_method = self._CreateMockMethod('__call__')
return mock_method(*params, **named_params) | [
"def",
"__call__",
"(",
"self",
",",
"*",
"params",
",",
"*",
"*",
"named_params",
")",
":",
"# Verify the class we are mocking is callable",
"callable",
"=",
"self",
".",
"_class_to_mock",
".",
"__dict__",
".",
"get",
"(",
"'__call__'",
",",
"None",
")",
"if"... | https://github.com/google/mysql-protobuf/blob/467cda676afaa49e762c5c9164a43f6ad31a1fbf/protobuf/python/mox.py#L490-L501 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.