nwo stringlengths 5 86 | sha stringlengths 40 40 | path stringlengths 4 189 | language stringclasses 1 value | identifier stringlengths 1 94 | parameters stringlengths 2 4.03k | argument_list stringclasses 1 value | return_statement stringlengths 0 11.5k | docstring stringlengths 1 33.2k | docstring_summary stringlengths 0 5.15k | docstring_tokens list | function stringlengths 34 151k | function_tokens list | url stringlengths 90 278 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | TPMS_CREATION_INFO.__init__ | (self, objectName = None, creationHash = None) | This is the attested data for TPM2_CertifyCreation().
Attributes:
objectName (bytes): Name of the object
creationHash (bytes): CreationHash | This is the attested data for TPM2_CertifyCreation(). | [
"This",
"is",
"the",
"attested",
"data",
"for",
"TPM2_CertifyCreation",
"()",
"."
] | def __init__(self, objectName = None, creationHash = None):
""" This is the attested data for TPM2_CertifyCreation().
Attributes:
objectName (bytes): Name of the object
creationHash (bytes): CreationHash
"""
self.objectName = objectName
self.creationHash = creationHash | [
"def",
"__init__",
"(",
"self",
",",
"objectName",
"=",
"None",
",",
"creationHash",
"=",
"None",
")",
":",
"self",
".",
"objectName",
"=",
"objectName",
"self",
".",
"creationHash",
"=",
"creationHash"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L5280-L5288 | ||
stellar-deprecated/stellard | 67eabb2217bdfa9a6ea317f62338fb6bca458c90 | src/protobuf/python/google/protobuf/internal/decoder.py | python | GroupDecoder | (field_number, is_repeated, is_packed, key, new_default) | Returns a decoder for a group field. | Returns a decoder for a group field. | [
"Returns",
"a",
"decoder",
"for",
"a",
"group",
"field",
"."
] | def GroupDecoder(field_number, is_repeated, is_packed, key, new_default):
"""Returns a decoder for a group field."""
end_tag_bytes = encoder.TagBytes(field_number,
wire_format.WIRETYPE_END_GROUP)
end_tag_len = len(end_tag_bytes)
assert not is_packed
if is_repeated:
tag_bytes = encoder.TagBytes(field_number,
wire_format.WIRETYPE_START_GROUP)
tag_len = len(tag_bytes)
def DecodeRepeatedField(buffer, pos, end, message, field_dict):
value = field_dict.get(key)
if value is None:
value = field_dict.setdefault(key, new_default(message))
while 1:
value = field_dict.get(key)
if value is None:
value = field_dict.setdefault(key, new_default(message))
# Read sub-message.
pos = value.add()._InternalParse(buffer, pos, end)
# Read end tag.
new_pos = pos+end_tag_len
if buffer[pos:new_pos] != end_tag_bytes or new_pos > end:
raise _DecodeError('Missing group end tag.')
# Predict that the next tag is another copy of the same repeated field.
pos = new_pos + tag_len
if buffer[new_pos:pos] != tag_bytes or new_pos == end:
# Prediction failed. Return.
return new_pos
return DecodeRepeatedField
else:
def DecodeField(buffer, pos, end, message, field_dict):
value = field_dict.get(key)
if value is None:
value = field_dict.setdefault(key, new_default(message))
# Read sub-message.
pos = value._InternalParse(buffer, pos, end)
# Read end tag.
new_pos = pos+end_tag_len
if buffer[pos:new_pos] != end_tag_bytes or new_pos > end:
raise _DecodeError('Missing group end tag.')
return new_pos
return DecodeField | [
"def",
"GroupDecoder",
"(",
"field_number",
",",
"is_repeated",
",",
"is_packed",
",",
"key",
",",
"new_default",
")",
":",
"end_tag_bytes",
"=",
"encoder",
".",
"TagBytes",
"(",
"field_number",
",",
"wire_format",
".",
"WIRETYPE_END_GROUP",
")",
"end_tag_len",
... | https://github.com/stellar-deprecated/stellard/blob/67eabb2217bdfa9a6ea317f62338fb6bca458c90/src/protobuf/python/google/protobuf/internal/decoder.py#L452-L496 | ||
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/contrib/learn/python/learn/experiment.py | python | _new_attr_context | (obj, attr) | Creates a new context in which an object's attribute can be changed.
This creates a context in which an object's attribute can be changed.
Once the context is exited, the attribute reverts to its original value.
Example usage:
my_obj.x = 1
with _new_attr_context(my_obj, "x"):
my_obj.x = 2
print(my_obj.x)
print(my_obj.x) | Creates a new context in which an object's attribute can be changed. | [
"Creates",
"a",
"new",
"context",
"in",
"which",
"an",
"object",
"s",
"attribute",
"can",
"be",
"changed",
"."
] | def _new_attr_context(obj, attr):
"""Creates a new context in which an object's attribute can be changed.
This creates a context in which an object's attribute can be changed.
Once the context is exited, the attribute reverts to its original value.
Example usage:
my_obj.x = 1
with _new_attr_context(my_obj, "x"):
my_obj.x = 2
print(my_obj.x)
print(my_obj.x)
"""
saved = getattr(obj, attr)
try:
yield
finally:
setattr(obj, attr, saved) | [
"def",
"_new_attr_context",
"(",
"obj",
",",
"attr",
")",
":",
"saved",
"=",
"getattr",
"(",
"obj",
",",
"attr",
")",
"try",
":",
"yield",
"finally",
":",
"setattr",
"(",
"obj",
",",
"attr",
",",
"saved",
")"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/learn/python/learn/experiment.py#L348-L365 | ||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/contrib/graph_editor/select.py | python | select_ops_and_ts | (*args, **kwargs) | return ops, ts | Helper to select operations and tensors.
Args:
*args: list of 1) regular expressions (compiled or not) or 2) (array of)
tf.Operation 3) (array of) tf.Tensor. Regular expressions matching tensors
must start with the comment "(?#ts)", for instance: "(?#ts)^foo/.*".
**kwargs: 'graph': tf.Graph in which to perform the regex query.This is
required when using regex.
'positive_filter': an elem if selected only if positive_filter(elem) is
True. This is optional.
Returns:
list of tf.Operation
list of tf.Tensor
Raises:
TypeError: if the optional keyword argument graph is not a tf.Graph
or if an argument in args is not an (array of) tf.Tensor
or an (array of) tf.Operation or a string or a regular expression.
ValueError: if one of the keyword arguments is unexpected or if a regular
expression is used without passing a graph as a keyword argument. | Helper to select operations and tensors. | [
"Helper",
"to",
"select",
"operations",
"and",
"tensors",
"."
] | def select_ops_and_ts(*args, **kwargs):
"""Helper to select operations and tensors.
Args:
*args: list of 1) regular expressions (compiled or not) or 2) (array of)
tf.Operation 3) (array of) tf.Tensor. Regular expressions matching tensors
must start with the comment "(?#ts)", for instance: "(?#ts)^foo/.*".
**kwargs: 'graph': tf.Graph in which to perform the regex query.This is
required when using regex.
'positive_filter': an elem if selected only if positive_filter(elem) is
True. This is optional.
Returns:
list of tf.Operation
list of tf.Tensor
Raises:
TypeError: if the optional keyword argument graph is not a tf.Graph
or if an argument in args is not an (array of) tf.Tensor
or an (array of) tf.Operation or a string or a regular expression.
ValueError: if one of the keyword arguments is unexpected or if a regular
expression is used without passing a graph as a keyword argument.
"""
ops = select_ops(*args, restrict_ops_regex=False, **kwargs)
ts = select_ts(*args, restrict_ts_regex=True, **kwargs)
return ops, ts | [
"def",
"select_ops_and_ts",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ops",
"=",
"select_ops",
"(",
"*",
"args",
",",
"restrict_ops_regex",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
"ts",
"=",
"select_ts",
"(",
"*",
"args",
",",
"restri... | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/graph_editor/select.py#L704-L727 | |
SpenceKonde/megaTinyCore | 1c4a70b18a149fe6bcb551dfa6db11ca50b8997b | megaavr/tools/libs/serial/tools/list_ports_windows.py | python | iterate_comports | () | Return a generator that yields descriptions for serial ports | Return a generator that yields descriptions for serial ports | [
"Return",
"a",
"generator",
"that",
"yields",
"descriptions",
"for",
"serial",
"ports"
] | def iterate_comports():
"""Return a generator that yields descriptions for serial ports"""
GUIDs = (GUID * 8)() # so far only seen one used, so hope 8 are enough...
guids_size = DWORD()
if not SetupDiClassGuidsFromName(
"Ports",
GUIDs,
ctypes.sizeof(GUIDs),
ctypes.byref(guids_size)):
raise ctypes.WinError()
# repeat for all possible GUIDs
for index in range(guids_size.value):
bInterfaceNumber = None
g_hdi = SetupDiGetClassDevs(
ctypes.byref(GUIDs[index]),
None,
NULL,
DIGCF_PRESENT) # was DIGCF_PRESENT|DIGCF_DEVICEINTERFACE which misses CDC ports
devinfo = SP_DEVINFO_DATA()
devinfo.cbSize = ctypes.sizeof(devinfo)
index = 0
while SetupDiEnumDeviceInfo(g_hdi, index, ctypes.byref(devinfo)):
index += 1
# get the real com port name
hkey = SetupDiOpenDevRegKey(
g_hdi,
ctypes.byref(devinfo),
DICS_FLAG_GLOBAL,
0,
DIREG_DEV, # DIREG_DRV for SW info
KEY_READ)
port_name_buffer = ctypes.create_unicode_buffer(250)
port_name_length = ULONG(ctypes.sizeof(port_name_buffer))
RegQueryValueEx(
hkey,
"PortName",
None,
None,
ctypes.byref(port_name_buffer),
ctypes.byref(port_name_length))
RegCloseKey(hkey)
# unfortunately does this method also include parallel ports.
# we could check for names starting with COM or just exclude LPT
# and hope that other "unknown" names are serial ports...
if port_name_buffer.value.startswith('LPT'):
continue
# hardware ID
szHardwareID = ctypes.create_unicode_buffer(250)
# try to get ID that includes serial number
if not SetupDiGetDeviceInstanceId(
g_hdi,
ctypes.byref(devinfo),
#~ ctypes.byref(szHardwareID),
szHardwareID,
ctypes.sizeof(szHardwareID) - 1,
None):
# fall back to more generic hardware ID if that would fail
if not SetupDiGetDeviceRegistryProperty(
g_hdi,
ctypes.byref(devinfo),
SPDRP_HARDWAREID,
None,
ctypes.byref(szHardwareID),
ctypes.sizeof(szHardwareID) - 1,
None):
# Ignore ERROR_INSUFFICIENT_BUFFER
if ctypes.GetLastError() != ERROR_INSUFFICIENT_BUFFER:
raise ctypes.WinError()
# stringify
szHardwareID_str = szHardwareID.value
info = list_ports_common.ListPortInfo(port_name_buffer.value)
# in case of USB, make a more readable string, similar to that form
# that we also generate on other platforms
if szHardwareID_str.startswith('USB'):
m = re.search(r'VID_([0-9a-f]{4})(&PID_([0-9a-f]{4}))?(&MI_(\d{2}))?(\\(\w+))?', szHardwareID_str, re.I)
if m:
info.vid = int(m.group(1), 16)
if m.group(3):
info.pid = int(m.group(3), 16)
if m.group(5):
bInterfaceNumber = int(m.group(5))
if m.group(7):
info.serial_number = m.group(7)
# calculate a location string
loc_path_str = ctypes.create_unicode_buffer(250)
if SetupDiGetDeviceRegistryProperty(
g_hdi,
ctypes.byref(devinfo),
SPDRP_LOCATION_PATHS,
None,
ctypes.byref(loc_path_str),
ctypes.sizeof(loc_path_str) - 1,
None):
m = re.finditer(r'USBROOT\((\w+)\)|#USB\((\w+)\)', loc_path_str.value)
location = []
for g in m:
if g.group(1):
location.append('{:d}'.format(int(g.group(1)) + 1))
else:
if len(location) > 1:
location.append('.')
else:
location.append('-')
location.append(g.group(2))
if bInterfaceNumber is not None:
location.append(':{}.{}'.format(
'x', # XXX how to determine correct bConfigurationValue?
bInterfaceNumber))
if location:
info.location = ''.join(location)
info.hwid = info.usb_info()
elif szHardwareID_str.startswith('FTDIBUS'):
m = re.search(r'VID_([0-9a-f]{4})\+PID_([0-9a-f]{4})(\+(\w+))?', szHardwareID_str, re.I)
if m:
info.vid = int(m.group(1), 16)
info.pid = int(m.group(2), 16)
if m.group(4):
info.serial_number = m.group(4)
# USB location is hidden by FDTI driver :(
info.hwid = info.usb_info()
else:
info.hwid = szHardwareID_str
# friendly name
szFriendlyName = ctypes.create_unicode_buffer(250)
if SetupDiGetDeviceRegistryProperty(
g_hdi,
ctypes.byref(devinfo),
SPDRP_FRIENDLYNAME,
#~ SPDRP_DEVICEDESC,
None,
ctypes.byref(szFriendlyName),
ctypes.sizeof(szFriendlyName) - 1,
None):
info.description = szFriendlyName.value
#~ else:
# Ignore ERROR_INSUFFICIENT_BUFFER
#~ if ctypes.GetLastError() != ERROR_INSUFFICIENT_BUFFER:
#~ raise IOError("failed to get details for %s (%s)" % (devinfo, szHardwareID.value))
# ignore errors and still include the port in the list, friendly name will be same as port name
# manufacturer
szManufacturer = ctypes.create_unicode_buffer(250)
if SetupDiGetDeviceRegistryProperty(
g_hdi,
ctypes.byref(devinfo),
SPDRP_MFG,
#~ SPDRP_DEVICEDESC,
None,
ctypes.byref(szManufacturer),
ctypes.sizeof(szManufacturer) - 1,
None):
info.manufacturer = szManufacturer.value
yield info
SetupDiDestroyDeviceInfoList(g_hdi) | [
"def",
"iterate_comports",
"(",
")",
":",
"GUIDs",
"=",
"(",
"GUID",
"*",
"8",
")",
"(",
")",
"# so far only seen one used, so hope 8 are enough...",
"guids_size",
"=",
"DWORD",
"(",
")",
"if",
"not",
"SetupDiClassGuidsFromName",
"(",
"\"Ports\"",
",",
"GUIDs",
... | https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/serial/tools/list_ports_windows.py#L133-L294 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/typedobjectutils.py | python | _sentry_safe_cast_default | (default, valty) | return _sentry_safe_cast(default, valty) | Similar to _sentry_safe_cast but handle default value. | Similar to _sentry_safe_cast but handle default value. | [
"Similar",
"to",
"_sentry_safe_cast",
"but",
"handle",
"default",
"value",
"."
] | def _sentry_safe_cast_default(default, valty):
"""Similar to _sentry_safe_cast but handle default value.
"""
# Handle default values
# TODO: simplify default values; too many possible way to spell None
if default is None:
return
if isinstance(default, (types.Omitted, types.NoneType)):
return
return _sentry_safe_cast(default, valty) | [
"def",
"_sentry_safe_cast_default",
"(",
"default",
",",
"valty",
")",
":",
"# Handle default values",
"# TODO: simplify default values; too many possible way to spell None",
"if",
"default",
"is",
"None",
":",
"return",
"if",
"isinstance",
"(",
"default",
",",
"(",
"type... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/typedobjectutils.py#L77-L86 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/model/coordinates.py | python | Frame.relativeOrigin | (self) | return self._relativeCoordinates[1] | Returns an element of R^3 denoting the translation of the origin
of this frame relative to its parent | Returns an element of R^3 denoting the translation of the origin
of this frame relative to its parent | [
"Returns",
"an",
"element",
"of",
"R^3",
"denoting",
"the",
"translation",
"of",
"the",
"origin",
"of",
"this",
"frame",
"relative",
"to",
"its",
"parent"
] | def relativeOrigin(self):
"""Returns an element of R^3 denoting the translation of the origin
of this frame relative to its parent"""
return self._relativeCoordinates[1] | [
"def",
"relativeOrigin",
"(",
"self",
")",
":",
"return",
"self",
".",
"_relativeCoordinates",
"[",
"1",
"]"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/model/coordinates.py#L55-L58 | |
zhaoweicai/cascade-rcnn | 2252f46158ea6555868ca6fa5c221ea71d9b5e6c | scripts/cpp_lint.py | python | CheckForNonConstReference | (filename, clean_lines, linenum,
nesting_state, error) | Check for non-const references.
Separate from CheckLanguage since it scans backwards from current
line, instead of scanning forward.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found. | Check for non-const references. | [
"Check",
"for",
"non",
"-",
"const",
"references",
"."
] | def CheckForNonConstReference(filename, clean_lines, linenum,
nesting_state, error):
"""Check for non-const references.
Separate from CheckLanguage since it scans backwards from current
line, instead of scanning forward.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found.
"""
# Do nothing if there is no '&' on current line.
line = clean_lines.elided[linenum]
if '&' not in line:
return
# Long type names may be broken across multiple lines, usually in one
# of these forms:
# LongType
# ::LongTypeContinued &identifier
# LongType::
# LongTypeContinued &identifier
# LongType<
# ...>::LongTypeContinued &identifier
#
# If we detected a type split across two lines, join the previous
# line to current line so that we can match const references
# accordingly.
#
# Note that this only scans back one line, since scanning back
# arbitrary number of lines would be expensive. If you have a type
# that spans more than 2 lines, please use a typedef.
if linenum > 1:
previous = None
if Match(r'\s*::(?:[\w<>]|::)+\s*&\s*\S', line):
# previous_line\n + ::current_line
previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+[\w<>])\s*$',
clean_lines.elided[linenum - 1])
elif Match(r'\s*[a-zA-Z_]([\w<>]|::)+\s*&\s*\S', line):
# previous_line::\n + current_line
previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+::)\s*$',
clean_lines.elided[linenum - 1])
if previous:
line = previous.group(1) + line.lstrip()
else:
# Check for templated parameter that is split across multiple lines
endpos = line.rfind('>')
if endpos > -1:
(_, startline, startpos) = ReverseCloseExpression(
clean_lines, linenum, endpos)
if startpos > -1 and startline < linenum:
# Found the matching < on an earlier line, collect all
# pieces up to current line.
line = ''
for i in xrange(startline, linenum + 1):
line += clean_lines.elided[i].strip()
# Check for non-const references in function parameters. A single '&' may
# found in the following places:
# inside expression: binary & for bitwise AND
# inside expression: unary & for taking the address of something
# inside declarators: reference parameter
# We will exclude the first two cases by checking that we are not inside a
# function body, including one that was just introduced by a trailing '{'.
# TODO(unknwon): Doesn't account for preprocessor directives.
# TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare].
check_params = False
if not nesting_state.stack:
check_params = True # top level
elif (isinstance(nesting_state.stack[-1], _ClassInfo) or
isinstance(nesting_state.stack[-1], _NamespaceInfo)):
check_params = True # within class or namespace
elif Match(r'.*{\s*$', line):
if (len(nesting_state.stack) == 1 or
isinstance(nesting_state.stack[-2], _ClassInfo) or
isinstance(nesting_state.stack[-2], _NamespaceInfo)):
check_params = True # just opened global/class/namespace block
# We allow non-const references in a few standard places, like functions
# called "swap()" or iostream operators like "<<" or ">>". Do not check
# those function parameters.
#
# We also accept & in static_assert, which looks like a function but
# it's actually a declaration expression.
whitelisted_functions = (r'(?:[sS]wap(?:<\w:+>)?|'
r'operator\s*[<>][<>]|'
r'static_assert|COMPILE_ASSERT'
r')\s*\(')
if Search(whitelisted_functions, line):
check_params = False
elif not Search(r'\S+\([^)]*$', line):
# Don't see a whitelisted function on this line. Actually we
# didn't see any function name on this line, so this is likely a
# multi-line parameter list. Try a bit harder to catch this case.
for i in xrange(2):
if (linenum > i and
Search(whitelisted_functions, clean_lines.elided[linenum - i - 1])):
check_params = False
break
if check_params:
decls = ReplaceAll(r'{[^}]*}', ' ', line) # exclude function body
for parameter in re.findall(_RE_PATTERN_REF_PARAM, decls):
if not Match(_RE_PATTERN_CONST_REF_PARAM, parameter):
error(filename, linenum, 'runtime/references', 2,
'Is this a non-const reference? '
'If so, make const or use a pointer: ' +
ReplaceAll(' *<', '<', parameter)) | [
"def",
"CheckForNonConstReference",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"nesting_state",
",",
"error",
")",
":",
"# Do nothing if there is no '&' on current line.",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"if",
"'&'",
"n... | https://github.com/zhaoweicai/cascade-rcnn/blob/2252f46158ea6555868ca6fa5c221ea71d9b5e6c/scripts/cpp_lint.py#L4138-L4248 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/distutils/ccompiler.py | python | CCompiler.find_library_file | (self, dirs, lib, debug=0) | Search the specified list of directories for a static or shared
library file 'lib' and return the full path to that file. If
'debug' true, look for a debugging version (if that makes sense on
the current platform). Return None if 'lib' wasn't found in any of
the specified directories. | Search the specified list of directories for a static or shared
library file 'lib' and return the full path to that file. If
'debug' true, look for a debugging version (if that makes sense on
the current platform). Return None if 'lib' wasn't found in any of
the specified directories. | [
"Search",
"the",
"specified",
"list",
"of",
"directories",
"for",
"a",
"static",
"or",
"shared",
"library",
"file",
"lib",
"and",
"return",
"the",
"full",
"path",
"to",
"that",
"file",
".",
"If",
"debug",
"true",
"look",
"for",
"a",
"debugging",
"version",... | def find_library_file (self, dirs, lib, debug=0):
"""Search the specified list of directories for a static or shared
library file 'lib' and return the full path to that file. If
'debug' true, look for a debugging version (if that makes sense on
the current platform). Return None if 'lib' wasn't found in any of
the specified directories.
"""
raise NotImplementedError | [
"def",
"find_library_file",
"(",
"self",
",",
"dirs",
",",
"lib",
",",
"debug",
"=",
"0",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/distutils/ccompiler.py#L804-L811 | ||
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py | python | XcodeSettings.GetLibtoolflags | (self, configname) | return libtoolflags | Returns flags that need to be passed to the static linker.
Args:
configname: The name of the configuration to get ld flags for. | Returns flags that need to be passed to the static linker. | [
"Returns",
"flags",
"that",
"need",
"to",
"be",
"passed",
"to",
"the",
"static",
"linker",
"."
] | def GetLibtoolflags(self, configname):
"""Returns flags that need to be passed to the static linker.
Args:
configname: The name of the configuration to get ld flags for.
"""
self.configname = configname
libtoolflags = []
for libtoolflag in self._Settings().get("OTHER_LDFLAGS", []):
libtoolflags.append(libtoolflag)
# TODO(thakis): ARCHS?
self.configname = None
return libtoolflags | [
"def",
"GetLibtoolflags",
"(",
"self",
",",
"configname",
")",
":",
"self",
".",
"configname",
"=",
"configname",
"libtoolflags",
"=",
"[",
"]",
"for",
"libtoolflag",
"in",
"self",
".",
"_Settings",
"(",
")",
".",
"get",
"(",
"\"OTHER_LDFLAGS\"",
",",
"[",... | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py#L1001-L1015 | |
monacoinproject/monacoin | 0d94a247eeabf0c1ed43ff1e1a62d115043a056e | contrib/devtools/copyright_header.py | python | call_git_toplevel | () | return subprocess.check_output(GIT_TOPLEVEL_CMD).strip().decode("utf-8") | Returns the absolute path to the project root | Returns the absolute path to the project root | [
"Returns",
"the",
"absolute",
"path",
"to",
"the",
"project",
"root"
] | def call_git_toplevel():
"Returns the absolute path to the project root"
return subprocess.check_output(GIT_TOPLEVEL_CMD).strip().decode("utf-8") | [
"def",
"call_git_toplevel",
"(",
")",
":",
"return",
"subprocess",
".",
"check_output",
"(",
"GIT_TOPLEVEL_CMD",
")",
".",
"strip",
"(",
")",
".",
"decode",
"(",
"\"utf-8\"",
")"
] | https://github.com/monacoinproject/monacoin/blob/0d94a247eeabf0c1ed43ff1e1a62d115043a056e/contrib/devtools/copyright_header.py#L61-L63 | |
tfwu/FaceDetection-ConvNet-3D | f9251c48eb40c5aec8fba7455115c355466555be | python/mxnet/ndarray.py | python | save | (fname, data) | Save list of NDArray or dict of str->NDArray to binary file.
You can also use pickle to do the job if you only work on python.
The advantage of load/save is the file is language agnostic.
This means the file saved using save can be loaded by other language binding of mxnet.
You also get the benefit being able to directly load/save from cloud storage(S3, HDFS)
Parameters
----------
fname : str
The name of the file.Can be S3 or HDFS address (remember built with S3 support).
Example of fname:
- `s3://my-bucket/path/my-s3-ndarray`
- `hdfs://my-bucket/path/my-hdfs-ndarray`
- `/path-to/my-local-ndarray`
data : list of NDArray or dict of str to NDArray
The data to be saved. | Save list of NDArray or dict of str->NDArray to binary file. | [
"Save",
"list",
"of",
"NDArray",
"or",
"dict",
"of",
"str",
"-",
">",
"NDArray",
"to",
"binary",
"file",
"."
] | def save(fname, data):
"""Save list of NDArray or dict of str->NDArray to binary file.
You can also use pickle to do the job if you only work on python.
The advantage of load/save is the file is language agnostic.
This means the file saved using save can be loaded by other language binding of mxnet.
You also get the benefit being able to directly load/save from cloud storage(S3, HDFS)
Parameters
----------
fname : str
The name of the file.Can be S3 or HDFS address (remember built with S3 support).
Example of fname:
- `s3://my-bucket/path/my-s3-ndarray`
- `hdfs://my-bucket/path/my-hdfs-ndarray`
- `/path-to/my-local-ndarray`
data : list of NDArray or dict of str to NDArray
The data to be saved.
"""
handles = []
if isinstance(data, dict):
keys = []
for key, val in data.items():
if not isinstance(key, string_types):
raise TypeError('save only accept dict str->NDArray or list of NDArray')
if not isinstance(val, NDArray):
raise TypeError('save only accept dict str->NDArray or list of NDArray')
keys.append(c_str(key))
handles.append(val.handle)
keys = c_array(ctypes.c_char_p, keys)
else:
for val in data:
if not isinstance(val, NDArray):
raise TypeError('save only accept dict str->NDArray or list of NDArray')
handles.append(val.handle)
keys = None
check_call(_LIB.MXNDArraySave(c_str(fname),
mx_uint(len(handles)),
c_array(NDArrayHandle, handles),
keys)) | [
"def",
"save",
"(",
"fname",
",",
"data",
")",
":",
"handles",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"keys",
"=",
"[",
"]",
"for",
"key",
",",
"val",
"in",
"data",
".",
"items",
"(",
")",
":",
"if",
"not",
"is... | https://github.com/tfwu/FaceDetection-ConvNet-3D/blob/f9251c48eb40c5aec8fba7455115c355466555be/python/mxnet/ndarray.py#L845-L886 | ||
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/find-the-longest-valid-obstacle-course-at-each-position.py | python | Solution2_TLE.longestObstacleCourseAtEachPosition | (self, obstacles) | return result | :type obstacles: List[int]
:rtype: List[int] | :type obstacles: List[int]
:rtype: List[int] | [
":",
"type",
"obstacles",
":",
"List",
"[",
"int",
"]",
":",
"rtype",
":",
"List",
"[",
"int",
"]"
] | def longestObstacleCourseAtEachPosition(self, obstacles):
"""
:type obstacles: List[int]
:rtype: List[int]
"""
sorted_obstacles = sorted(set(obstacles))
lookup = {x:i for i, x in enumerate(sorted_obstacles)}
segment_tree = SegmentTree(len(lookup))
result = []
for x in obstacles:
cnt = segment_tree.query(0, lookup[x])+1
result.append(cnt)
segment_tree.update(lookup[x], lookup[x], cnt)
return result | [
"def",
"longestObstacleCourseAtEachPosition",
"(",
"self",
",",
"obstacles",
")",
":",
"sorted_obstacles",
"=",
"sorted",
"(",
"set",
"(",
"obstacles",
")",
")",
"lookup",
"=",
"{",
"x",
":",
"i",
"for",
"i",
",",
"x",
"in",
"enumerate",
"(",
"sorted_obsta... | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/find-the-longest-valid-obstacle-course-at-each-position.py#L108-L121 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/requests/models.py | python | Response.iter_lines | (self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=None, delimiter=None) | Iterates over the response data, one line at a time. When
stream=True is set on the request, this avoids reading the
content at once into memory for large responses.
.. note:: This method is not reentrant safe. | Iterates over the response data, one line at a time. When
stream=True is set on the request, this avoids reading the
content at once into memory for large responses. | [
"Iterates",
"over",
"the",
"response",
"data",
"one",
"line",
"at",
"a",
"time",
".",
"When",
"stream",
"=",
"True",
"is",
"set",
"on",
"the",
"request",
"this",
"avoids",
"reading",
"the",
"content",
"at",
"once",
"into",
"memory",
"for",
"large",
"resp... | def iter_lines(self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=None, delimiter=None):
"""Iterates over the response data, one line at a time. When
stream=True is set on the request, this avoids reading the
content at once into memory for large responses.
.. note:: This method is not reentrant safe.
"""
pending = None
for chunk in self.iter_content(chunk_size=chunk_size, decode_unicode=decode_unicode):
if pending is not None:
chunk = pending + chunk
if delimiter:
lines = chunk.split(delimiter)
else:
lines = chunk.splitlines()
if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]:
pending = lines.pop()
else:
pending = None
for line in lines:
yield line
if pending is not None:
yield pending | [
"def",
"iter_lines",
"(",
"self",
",",
"chunk_size",
"=",
"ITER_CHUNK_SIZE",
",",
"decode_unicode",
"=",
"None",
",",
"delimiter",
"=",
"None",
")",
":",
"pending",
"=",
"None",
"for",
"chunk",
"in",
"self",
".",
"iter_content",
"(",
"chunk_size",
"=",
"ch... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/requests/models.py#L779-L808 | ||
microsoft/checkedc-clang | a173fefde5d7877b7750e7ce96dd08cf18baebf2 | clang/bindings/python/clang/cindex.py | python | Cursor.is_default_constructor | (self) | return conf.lib.clang_CXXConstructor_isDefaultConstructor(self) | Returns True if the cursor refers to a C++ default constructor. | Returns True if the cursor refers to a C++ default constructor. | [
"Returns",
"True",
"if",
"the",
"cursor",
"refers",
"to",
"a",
"C",
"++",
"default",
"constructor",
"."
] | def is_default_constructor(self):
"""Returns True if the cursor refers to a C++ default constructor.
"""
return conf.lib.clang_CXXConstructor_isDefaultConstructor(self) | [
"def",
"is_default_constructor",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_CXXConstructor_isDefaultConstructor",
"(",
"self",
")"
] | https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/clang/bindings/python/clang/cindex.py#L1460-L1463 | |
ideawu/ssdb | f229ba277c7f7d0ca5a441c0c6fb3d1209af68e4 | deps/cpy/antlr3/streams.py | python | CommonTokenStream.skipOffTokenChannels | (self, i) | return i | Given a starting index, return the index of the first on-channel
token. | Given a starting index, return the index of the first on-channel
token. | [
"Given",
"a",
"starting",
"index",
"return",
"the",
"index",
"of",
"the",
"first",
"on",
"-",
"channel",
"token",
"."
] | def skipOffTokenChannels(self, i):
"""
Given a starting index, return the index of the first on-channel
token.
"""
try:
while self.tokens[i].channel != self.channel:
i += 1
except IndexError:
# hit the end of token stream
pass
return i | [
"def",
"skipOffTokenChannels",
"(",
"self",
",",
"i",
")",
":",
"try",
":",
"while",
"self",
".",
"tokens",
"[",
"i",
"]",
".",
"channel",
"!=",
"self",
".",
"channel",
":",
"i",
"+=",
"1",
"except",
"IndexError",
":",
"# hit the end of token stream",
"p... | https://github.com/ideawu/ssdb/blob/f229ba277c7f7d0ca5a441c0c6fb3d1209af68e4/deps/cpy/antlr3/streams.py#L721-L734 | |
rrwick/Unicycler | 96ffea71e3a78d63ade19d6124946773e65cf129 | unicycler/assembly_graph_copy_depth.py | python | get_error | (source, target) | Returns the relative error from trying to assign the source value to the target value.
E.g. if source = 1.6 and target = 2.0, the error is 0.2 | Returns the relative error from trying to assign the source value to the target value.
E.g. if source = 1.6 and target = 2.0, the error is 0.2 | [
"Returns",
"the",
"relative",
"error",
"from",
"trying",
"to",
"assign",
"the",
"source",
"value",
"to",
"the",
"target",
"value",
".",
"E",
".",
"g",
".",
"if",
"source",
"=",
"1",
".",
"6",
"and",
"target",
"=",
"2",
".",
"0",
"the",
"error",
"is... | def get_error(source, target):
"""
Returns the relative error from trying to assign the source value to the target value.
E.g. if source = 1.6 and target = 2.0, the error is 0.2
"""
if target > 0.0:
return abs(source - target) / target
else:
return float('inf') | [
"def",
"get_error",
"(",
"source",
",",
"target",
")",
":",
"if",
"target",
">",
"0.0",
":",
"return",
"abs",
"(",
"source",
"-",
"target",
")",
"/",
"target",
"else",
":",
"return",
"float",
"(",
"'inf'",
")"
] | https://github.com/rrwick/Unicycler/blob/96ffea71e3a78d63ade19d6124946773e65cf129/unicycler/assembly_graph_copy_depth.py#L422-L430 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/index/package_finder.py | python | PackageFinder.find_requirement | (self, req, upgrade) | return best_candidate | Try to find a Link matching req
Expects req, an InstallRequirement and upgrade, a boolean
Returns a InstallationCandidate if found,
Raises DistributionNotFound or BestVersionAlreadyInstalled otherwise | Try to find a Link matching req | [
"Try",
"to",
"find",
"a",
"Link",
"matching",
"req"
] | def find_requirement(self, req, upgrade):
# type: (InstallRequirement, bool) -> Optional[InstallationCandidate]
"""Try to find a Link matching req
Expects req, an InstallRequirement and upgrade, a boolean
Returns a InstallationCandidate if found,
Raises DistributionNotFound or BestVersionAlreadyInstalled otherwise
"""
hashes = req.hashes(trust_internet=False)
best_candidate_result = self.find_best_candidate(
req.name, specifier=req.specifier, hashes=hashes,
)
best_candidate = best_candidate_result.best_candidate
installed_version = None # type: Optional[_BaseVersion]
if req.satisfied_by is not None:
installed_version = parse_version(req.satisfied_by.version)
def _format_versions(cand_iter):
# type: (Iterable[InstallationCandidate]) -> str
# This repeated parse_version and str() conversion is needed to
# handle different vendoring sources from pip and pkg_resources.
# If we stop using the pkg_resources provided specifier and start
# using our own, we can drop the cast to str().
return ", ".join(sorted(
{str(c.version) for c in cand_iter},
key=parse_version,
)) or "none"
if installed_version is None and best_candidate is None:
logger.critical(
'Could not find a version that satisfies the requirement %s '
'(from versions: %s)',
req,
_format_versions(best_candidate_result.iter_all()),
)
raise DistributionNotFound(
'No matching distribution found for {}'.format(
req)
)
best_installed = False
if installed_version and (
best_candidate is None or
best_candidate.version <= installed_version):
best_installed = True
if not upgrade and installed_version is not None:
if best_installed:
logger.debug(
'Existing installed version (%s) is most up-to-date and '
'satisfies requirement',
installed_version,
)
else:
logger.debug(
'Existing installed version (%s) satisfies requirement '
'(most up-to-date version is %s)',
installed_version,
best_candidate.version,
)
return None
if best_installed:
# We have an existing version, and its the best version
logger.debug(
'Installed version (%s) is most up-to-date (past versions: '
'%s)',
installed_version,
_format_versions(best_candidate_result.iter_applicable()),
)
raise BestVersionAlreadyInstalled
logger.debug(
'Using version %s (newest of versions: %s)',
best_candidate.version,
_format_versions(best_candidate_result.iter_applicable()),
)
return best_candidate | [
"def",
"find_requirement",
"(",
"self",
",",
"req",
",",
"upgrade",
")",
":",
"# type: (InstallRequirement, bool) -> Optional[InstallationCandidate]",
"hashes",
"=",
"req",
".",
"hashes",
"(",
"trust_internet",
"=",
"False",
")",
"best_candidate_result",
"=",
"self",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/index/package_finder.py#L880-L959 | |
MichalBusta/E2E-MLT | 2f0b54e31ebb414cd2daad824d7d474062ebe834 | train.py | python | area | (a) | return width * height | Computes rectangle area | Computes rectangle area | [
"Computes",
"rectangle",
"area"
] | def area(a):
'''Computes rectangle area'''
width = a[2] - a[0]
height = a[3] - a[1]
return width * height | [
"def",
"area",
"(",
"a",
")",
":",
"width",
"=",
"a",
"[",
"2",
"]",
"-",
"a",
"[",
"0",
"]",
"height",
"=",
"a",
"[",
"3",
"]",
"-",
"a",
"[",
"1",
"]",
"return",
"width",
"*",
"height"
] | https://github.com/MichalBusta/E2E-MLT/blob/2f0b54e31ebb414cd2daad824d7d474062ebe834/train.py#L69-L73 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | VersionInfo.GetDescription | (*args, **kwargs) | return _core_.VersionInfo_GetDescription(*args, **kwargs) | GetDescription(self) -> String | GetDescription(self) -> String | [
"GetDescription",
"(",
"self",
")",
"-",
">",
"String"
] | def GetDescription(*args, **kwargs):
"""GetDescription(self) -> String"""
return _core_.VersionInfo_GetDescription(*args, **kwargs) | [
"def",
"GetDescription",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"VersionInfo_GetDescription",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L16593-L16595 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/pytables.py | python | Fixed.set_object_info | (self) | set my pandas type & version | set my pandas type & version | [
"set",
"my",
"pandas",
"type",
"&",
"version"
] | def set_object_info(self):
""" set my pandas type & version """
self.attrs.pandas_type = str(self.pandas_kind)
self.attrs.pandas_version = str(_version) | [
"def",
"set_object_info",
"(",
"self",
")",
":",
"self",
".",
"attrs",
".",
"pandas_type",
"=",
"str",
"(",
"self",
".",
"pandas_kind",
")",
"self",
".",
"attrs",
".",
"pandas_version",
"=",
"str",
"(",
"_version",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/pytables.py#L2532-L2535 | ||
ros2/demos | fb3ad7e7fc6548c30e77a6ed86a2bd108fce5d82 | quality_of_service_demo/rclpy/quality_of_service_demo_py/common_nodes.py | python | Listener.start_listening | (self) | Instantiate Subscription.
Does nothing if it has already been called. | Instantiate Subscription. | [
"Instantiate",
"Subscription",
"."
] | def start_listening(self):
"""
Instantiate Subscription.
Does nothing if it has already been called.
"""
if not self.subscription:
self.subscription = self.create_subscription(
String, self.topic_name, self._message_callback,
self.qos_profile,
event_callbacks=self.event_callbacks)
self.get_logger().info('Subscription created') | [
"def",
"start_listening",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"subscription",
":",
"self",
".",
"subscription",
"=",
"self",
".",
"create_subscription",
"(",
"String",
",",
"self",
".",
"topic_name",
",",
"self",
".",
"_message_callback",
",",
... | https://github.com/ros2/demos/blob/fb3ad7e7fc6548c30e77a6ed86a2bd108fce5d82/quality_of_service_demo/rclpy/quality_of_service_demo_py/common_nodes.py#L110-L121 | ||
floooh/oryol | eb08cffe1b1cb6b05ed14ec692bca9372cef064e | fips-files/generators/util/png.py | python | Test.testExtraPixels | (self) | Test file that contains too many pixels. | Test file that contains too many pixels. | [
"Test",
"file",
"that",
"contains",
"too",
"many",
"pixels",
"."
] | def testExtraPixels(self):
"""Test file that contains too many pixels."""
def eachchunk(chunk):
if chunk[0] != 'IDAT':
return chunk
data = zlib.decompress(chunk[1])
data += strtobytes('\x00garbage')
data = zlib.compress(data)
chunk = (chunk[0], data)
return chunk
self.assertRaises(FormatError, self.helperFormat, eachchunk) | [
"def",
"testExtraPixels",
"(",
"self",
")",
":",
"def",
"eachchunk",
"(",
"chunk",
")",
":",
"if",
"chunk",
"[",
"0",
"]",
"!=",
"'IDAT'",
":",
"return",
"chunk",
"data",
"=",
"zlib",
".",
"decompress",
"(",
"chunk",
"[",
"1",
"]",
")",
"data",
"+=... | https://github.com/floooh/oryol/blob/eb08cffe1b1cb6b05ed14ec692bca9372cef064e/fips-files/generators/util/png.py#L2656-L2667 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/lib2to3/pytree.py | python | convert | (gr, raw_node) | Convert raw node information to a Node or Leaf instance.
This is passed to the parser driver which calls it whenever a reduction of a
grammar rule produces a new complete node, so that the tree is build
strictly bottom-up. | Convert raw node information to a Node or Leaf instance. | [
"Convert",
"raw",
"node",
"information",
"to",
"a",
"Node",
"or",
"Leaf",
"instance",
"."
] | def convert(gr, raw_node):
"""
Convert raw node information to a Node or Leaf instance.
This is passed to the parser driver which calls it whenever a reduction of a
grammar rule produces a new complete node, so that the tree is build
strictly bottom-up.
"""
type, value, context, children = raw_node
if children or type in gr.number2symbol:
# If there's exactly one child, return that child instead of
# creating a new node.
if len(children) == 1:
return children[0]
return Node(type, children, context=context)
else:
return Leaf(type, value, context=context) | [
"def",
"convert",
"(",
"gr",
",",
"raw_node",
")",
":",
"type",
",",
"value",
",",
"context",
",",
"children",
"=",
"raw_node",
"if",
"children",
"or",
"type",
"in",
"gr",
".",
"number2symbol",
":",
"# If there's exactly one child, return that child instead of",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/lib2to3/pytree.py#L395-L411 | ||
microsoft/CNTK | e9396480025b9ca457d26b6f33dd07c474c6aa04 | Examples/Image/Detection/utils/rpn/bbox_transform.py | python | clip_boxes | (boxes, im_info) | return boxes | Clip boxes to image boundaries.
:param boxes: boxes
:param im_info: (pad_width, pad_height, scaled_image_width, scaled_image_height, orig_img_width, orig_img_height)
e.g.(1000, 1000, 1000, 600, 500, 300) for an original image of 600x300 that is scaled and padded to 1000x1000 | Clip boxes to image boundaries.
:param boxes: boxes
:param im_info: (pad_width, pad_height, scaled_image_width, scaled_image_height, orig_img_width, orig_img_height)
e.g.(1000, 1000, 1000, 600, 500, 300) for an original image of 600x300 that is scaled and padded to 1000x1000 | [
"Clip",
"boxes",
"to",
"image",
"boundaries",
".",
":",
"param",
"boxes",
":",
"boxes",
":",
"param",
"im_info",
":",
"(",
"pad_width",
"pad_height",
"scaled_image_width",
"scaled_image_height",
"orig_img_width",
"orig_img_height",
")",
"e",
".",
"g",
".",
"(",
... | def clip_boxes(boxes, im_info):
'''
Clip boxes to image boundaries.
:param boxes: boxes
:param im_info: (pad_width, pad_height, scaled_image_width, scaled_image_height, orig_img_width, orig_img_height)
e.g.(1000, 1000, 1000, 600, 500, 300) for an original image of 600x300 that is scaled and padded to 1000x1000
'''
im_info.shape = (6)
padded_wh = im_info[0:2]
scaled_wh = im_info[2:4]
xy_offset = (padded_wh - scaled_wh) / 2
xy_min = xy_offset
xy_max = xy_offset + scaled_wh
# x_min <= x1 <= x_max
boxes[:, 0::4] = np.maximum(np.minimum(boxes[:, 0::4], xy_max[0] - 1), xy_min[0])
# y_min <= y1 <= y_max
boxes[:, 1::4] = np.maximum(np.minimum(boxes[:, 1::4], xy_max[1] - 1), xy_min[1])
# x_min <= x2 <= x_max
boxes[:, 2::4] = np.maximum(np.minimum(boxes[:, 2::4], xy_max[0] - 1), xy_min[0])
# y_min <= y2 <= y_max
boxes[:, 3::4] = np.maximum(np.minimum(boxes[:, 3::4], xy_max[1] - 1), xy_min[1])
return boxes | [
"def",
"clip_boxes",
"(",
"boxes",
",",
"im_info",
")",
":",
"im_info",
".",
"shape",
"=",
"(",
"6",
")",
"padded_wh",
"=",
"im_info",
"[",
"0",
":",
"2",
"]",
"scaled_wh",
"=",
"im_info",
"[",
"2",
":",
"4",
"]",
"xy_offset",
"=",
"(",
"padded_wh"... | https://github.com/microsoft/CNTK/blob/e9396480025b9ca457d26b6f33dd07c474c6aa04/Examples/Image/Detection/utils/rpn/bbox_transform.py#L74-L97 | |
FirebirdSQL/firebird | 95e3e71622ab0b26cafa8b184ce08500f2eb613f | extern/re2/re2/make_unicode_casefold.py | python | _MakeRanges | (pairs) | return ranges | Turn a list like [(65,97), (66, 98), ..., (90,122)]
into [(65, 90, +32)]. | Turn a list like [(65,97), (66, 98), ..., (90,122)]
into [(65, 90, +32)]. | [
"Turn",
"a",
"list",
"like",
"[",
"(",
"65",
"97",
")",
"(",
"66",
"98",
")",
"...",
"(",
"90",
"122",
")",
"]",
"into",
"[",
"(",
"65",
"90",
"+",
"32",
")",
"]",
"."
] | def _MakeRanges(pairs):
"""Turn a list like [(65,97), (66, 98), ..., (90,122)]
into [(65, 90, +32)]."""
ranges = []
last = -100
def evenodd(last, a, b, r):
if a != last+1 or b != _AddDelta(a, r[2]):
return False
r[1] = a
return True
def evenoddpair(last, a, b, r):
if a != last+2:
return False
delta = r[2]
d = delta
if type(delta) is not str:
return False
if delta.endswith('Skip'):
d = delta[:-4]
else:
delta = d + 'Skip'
if b != _AddDelta(a, d):
return False
r[1] = a
r[2] = delta
return True
for a, b in pairs:
if ranges and evenodd(last, a, b, ranges[-1]):
pass
elif ranges and evenoddpair(last, a, b, ranges[-1]):
pass
else:
ranges.append([a, a, _Delta(a, b)])
last = a
return ranges | [
"def",
"_MakeRanges",
"(",
"pairs",
")",
":",
"ranges",
"=",
"[",
"]",
"last",
"=",
"-",
"100",
"def",
"evenodd",
"(",
"last",
",",
"a",
",",
"b",
",",
"r",
")",
":",
"if",
"a",
"!=",
"last",
"+",
"1",
"or",
"b",
"!=",
"_AddDelta",
"(",
"a",
... | https://github.com/FirebirdSQL/firebird/blob/95e3e71622ab0b26cafa8b184ce08500f2eb613f/extern/re2/re2/make_unicode_casefold.py#L67-L104 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/ipaddress.py | python | IPv6Address.scope_id | (self) | return self._scope_id | Identifier of a particular zone of the address's scope.
See RFC 4007 for details.
Returns:
A string identifying the zone of the address if specified, else None. | Identifier of a particular zone of the address's scope. | [
"Identifier",
"of",
"a",
"particular",
"zone",
"of",
"the",
"address",
"s",
"scope",
"."
] | def scope_id(self):
"""Identifier of a particular zone of the address's scope.
See RFC 4007 for details.
Returns:
A string identifying the zone of the address if specified, else None.
"""
return self._scope_id | [
"def",
"scope_id",
"(",
"self",
")",
":",
"return",
"self",
".",
"_scope_id"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/ipaddress.py#L1936-L1945 | |
generalized-intelligence/GAAS | 29ab17d3e8a4ba18edef3a57c36d8db6329fac73 | deprecated/algorithms/sfm/OpenSfM/opensfm/dataset.py | python | DataSet.load_exif_overrides | (self) | Load EXIF overrides data. | Load EXIF overrides data. | [
"Load",
"EXIF",
"overrides",
"data",
"."
] | def load_exif_overrides(self):
"""Load EXIF overrides data."""
with io.open_rt(self._exif_overrides_file()) as fin:
return json.load(fin) | [
"def",
"load_exif_overrides",
"(",
"self",
")",
":",
"with",
"io",
".",
"open_rt",
"(",
"self",
".",
"_exif_overrides_file",
"(",
")",
")",
"as",
"fin",
":",
"return",
"json",
".",
"load",
"(",
"fin",
")"
] | https://github.com/generalized-intelligence/GAAS/blob/29ab17d3e8a4ba18edef3a57c36d8db6329fac73/deprecated/algorithms/sfm/OpenSfM/opensfm/dataset.py#L678-L681 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/asyncio/unix_events.py | python | _sighandler_noop | (signum, frame) | Dummy signal handler. | Dummy signal handler. | [
"Dummy",
"signal",
"handler",
"."
] | def _sighandler_noop(signum, frame):
"""Dummy signal handler."""
pass | [
"def",
"_sighandler_noop",
"(",
"signum",
",",
"frame",
")",
":",
"pass"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/asyncio/unix_events.py#L39-L41 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/util/_decorators.py | python | Substitution.update | (self, *args, **kwargs) | Update self.params with supplied args.
If called, we assume self.params is a dict. | Update self.params with supplied args. | [
"Update",
"self",
".",
"params",
"with",
"supplied",
"args",
"."
] | def update(self, *args, **kwargs):
"""
Update self.params with supplied args.
If called, we assume self.params is a dict.
"""
self.params.update(*args, **kwargs) | [
"def",
"update",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"params",
".",
"update",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/util/_decorators.py#L261-L268 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | version | () | return "%s %s (classic)" % (wx.VERSION_STRING, port) | Returns a string containing version and port info | Returns a string containing version and port info | [
"Returns",
"a",
"string",
"containing",
"version",
"and",
"port",
"info"
] | def version():
"""Returns a string containing version and port info"""
if wx.Platform == '__WXMSW__':
port = 'msw'
elif wx.Platform == '__WXMAC__':
if 'wxOSX-carbon' in wx.PlatformInfo:
port = 'osx-carbon'
else:
port = 'osx-cocoa'
elif wx.Platform == '__WXGTK__':
port = 'gtk'
if 'gtk2' in wx.PlatformInfo:
port = 'gtk2'
elif 'gtk3' in wx.PlatformInfo:
port = 'gtk3'
else:
port = '?'
return "%s %s (classic)" % (wx.VERSION_STRING, port) | [
"def",
"version",
"(",
")",
":",
"if",
"wx",
".",
"Platform",
"==",
"'__WXMSW__'",
":",
"port",
"=",
"'msw'",
"elif",
"wx",
".",
"Platform",
"==",
"'__WXMAC__'",
":",
"if",
"'wxOSX-carbon'",
"in",
"wx",
".",
"PlatformInfo",
":",
"port",
"=",
"'osx-carbon... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L16640-L16658 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py | python | ContainerSize.extractnumber | (self, text) | return result | Extract the first number in the given text. | Extract the first number in the given text. | [
"Extract",
"the",
"first",
"number",
"in",
"the",
"given",
"text",
"."
] | def extractnumber(self, text):
"Extract the first number in the given text."
result = ''
decimal = False
for char in text:
if char.isdigit():
result += char
elif char == '.' and not decimal:
result += char
decimal = True
else:
return result
return result | [
"def",
"extractnumber",
"(",
"self",
",",
"text",
")",
":",
"result",
"=",
"''",
"decimal",
"=",
"False",
"for",
"char",
"in",
"text",
":",
"if",
"char",
".",
"isdigit",
"(",
")",
":",
"result",
"+=",
"char",
"elif",
"char",
"==",
"'.'",
"and",
"no... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py#L3471-L3483 | |
vgough/encfs | c444f9b9176beea1ad41a7b2e29ca26e709b57f7 | vendor/github.com/muflihun/easyloggingpp/tools/cpplint.py | python | _IncludeState.CheckNextIncludeOrder | (self, header_type) | return '' | Returns a non-empty error message if the next header is out of order.
This function also updates the internal state to be ready to check
the next include.
Args:
header_type: One of the _XXX_HEADER constants defined above.
Returns:
The empty string if the header is in the right order, or an
error message describing what's wrong. | Returns a non-empty error message if the next header is out of order. | [
"Returns",
"a",
"non",
"-",
"empty",
"error",
"message",
"if",
"the",
"next",
"header",
"is",
"out",
"of",
"order",
"."
] | def CheckNextIncludeOrder(self, header_type):
"""Returns a non-empty error message if the next header is out of order.
This function also updates the internal state to be ready to check
the next include.
Args:
header_type: One of the _XXX_HEADER constants defined above.
Returns:
The empty string if the header is in the right order, or an
error message describing what's wrong.
"""
error_message = ('Found %s after %s' %
(self._TYPE_NAMES[header_type],
self._SECTION_NAMES[self._section]))
last_section = self._section
if header_type == _C_SYS_HEADER:
if self._section <= self._C_SECTION:
self._section = self._C_SECTION
else:
self._last_header = ''
return error_message
elif header_type == _CPP_SYS_HEADER:
if self._section <= self._CPP_SECTION:
self._section = self._CPP_SECTION
else:
self._last_header = ''
return error_message
elif header_type == _LIKELY_MY_HEADER:
if self._section <= self._MY_H_SECTION:
self._section = self._MY_H_SECTION
else:
self._section = self._OTHER_H_SECTION
elif header_type == _POSSIBLE_MY_HEADER:
if self._section <= self._MY_H_SECTION:
self._section = self._MY_H_SECTION
else:
# This will always be the fallback because we're not sure
# enough that the header is associated with this file.
self._section = self._OTHER_H_SECTION
else:
assert header_type == _OTHER_HEADER
self._section = self._OTHER_H_SECTION
if last_section != self._section:
self._last_header = ''
return '' | [
"def",
"CheckNextIncludeOrder",
"(",
"self",
",",
"header_type",
")",
":",
"error_message",
"=",
"(",
"'Found %s after %s'",
"%",
"(",
"self",
".",
"_TYPE_NAMES",
"[",
"header_type",
"]",
",",
"self",
".",
"_SECTION_NAMES",
"[",
"self",
".",
"_section",
"]",
... | https://github.com/vgough/encfs/blob/c444f9b9176beea1ad41a7b2e29ca26e709b57f7/vendor/github.com/muflihun/easyloggingpp/tools/cpplint.py#L610-L661 | |
gem5/gem5 | 141cc37c2d4b93959d4c249b8f7e6a8b2ef75338 | src/mem/slicc/parser.py | python | SLICC.p_typestr__multi | (self, p) | typestr : typestr DOUBLE_COLON ident | typestr : typestr DOUBLE_COLON ident | [
"typestr",
":",
"typestr",
"DOUBLE_COLON",
"ident"
] | def p_typestr__multi(self, p):
"typestr : typestr DOUBLE_COLON ident"
p[0] = '%s::%s' % (p[1], p[3]) | [
"def",
"p_typestr__multi",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"'%s::%s'",
"%",
"(",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"3",
"]",
")"
] | https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/src/mem/slicc/parser.py#L491-L493 | ||
emscripten-core/emscripten | 0d413d3c5af8b28349682496edc14656f5700c2f | third_party/ply/example/yply/yparse.py | python | p_rule | (p) | rule : ID ':' rulelist ';' | rule : ID ':' rulelist ';' | [
"rule",
":",
"ID",
":",
"rulelist",
";"
] | def p_rule(p):
'''rule : ID ':' rulelist ';' '''
p[0] = (p[1],[p[3]]) | [
"def",
"p_rule",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"(",
"p",
"[",
"1",
"]",
",",
"[",
"p",
"[",
"3",
"]",
"]",
")"
] | https://github.com/emscripten-core/emscripten/blob/0d413d3c5af8b28349682496edc14656f5700c2f/third_party/ply/example/yply/yparse.py#L153-L155 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/_checkparam.py | python | Rel.get_strs | (rel) | return rel_strs.get(rel, "") | Get value from rel_strs. | Get value from rel_strs. | [
"Get",
"value",
"from",
"rel_strs",
"."
] | def get_strs(rel):
"""Get value from rel_strs."""
return rel_strs.get(rel, "") | [
"def",
"get_strs",
"(",
"rel",
")",
":",
"return",
"rel_strs",
".",
"get",
"(",
"rel",
",",
"\"\"",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/_checkparam.py#L52-L54 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/ros_comm/rospy/src/rospy/impl/tcpros_pubsub.py | python | _configure_pub_socket | (sock, is_tcp_nodelay) | Configure socket options on a new publisher socket.
@param sock: socket.socket
@type sock: socket.socket
@param is_tcp_nodelay: if True, TCP_NODELAY will be set on outgoing socket if available
@param is_tcp_nodelay: bool | Configure socket options on a new publisher socket. | [
"Configure",
"socket",
"options",
"on",
"a",
"new",
"publisher",
"socket",
"."
] | def _configure_pub_socket(sock, is_tcp_nodelay):
"""
Configure socket options on a new publisher socket.
@param sock: socket.socket
@type sock: socket.socket
@param is_tcp_nodelay: if True, TCP_NODELAY will be set on outgoing socket if available
@param is_tcp_nodelay: bool
"""
# #956: low latency, TCP_NODELAY support
if is_tcp_nodelay:
if hasattr(socket, 'TCP_NODELAY'):
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
else:
logwarn("WARNING: cannot enable TCP_NODELAY as its not supported on this platform") | [
"def",
"_configure_pub_socket",
"(",
"sock",
",",
"is_tcp_nodelay",
")",
":",
"# #956: low latency, TCP_NODELAY support",
"if",
"is_tcp_nodelay",
":",
"if",
"hasattr",
"(",
"socket",
",",
"'TCP_NODELAY'",
")",
":",
"sock",
".",
"setsockopt",
"(",
"socket",
".",
"I... | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rospy/src/rospy/impl/tcpros_pubsub.py#L103-L116 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/ops/resource_variable_ops.py | python | ResourceVariable._OverloadOperator | (operator) | Defer an operator overload to `ops.Tensor`.
We pull the operator out of ops.Tensor dynamically to avoid ordering issues.
Args:
operator: string. The operator name. | Defer an operator overload to `ops.Tensor`. | [
"Defer",
"an",
"operator",
"overload",
"to",
"ops",
".",
"Tensor",
"."
] | def _OverloadOperator(operator): # pylint: disable=invalid-name
"""Defer an operator overload to `ops.Tensor`.
We pull the operator out of ops.Tensor dynamically to avoid ordering issues.
Args:
operator: string. The operator name.
"""
def _run_op(a, *args):
# pylint: disable=protected-access
value = a._AsTensor()
return getattr(ops.Tensor, operator)(value, *args)
# Propagate __doc__ to wrapper
try:
_run_op.__doc__ = getattr(ops.Tensor, operator).__doc__
except AttributeError:
pass
setattr(ResourceVariable, operator, _run_op) | [
"def",
"_OverloadOperator",
"(",
"operator",
")",
":",
"# pylint: disable=invalid-name",
"def",
"_run_op",
"(",
"a",
",",
"*",
"args",
")",
":",
"# pylint: disable=protected-access",
"value",
"=",
"a",
".",
"_AsTensor",
"(",
")",
"return",
"getattr",
"(",
"ops",... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/resource_variable_ops.py#L684-L704 | ||
MegEngine/MegEngine | ce9ad07a27ec909fb8db4dd67943d24ba98fb93a | lite/pylite/megenginelite/tensor.py | python | LiteTensor.update | (self) | update the member from C, this will auto used after slice, share | update the member from C, this will auto used after slice, share | [
"update",
"the",
"member",
"from",
"C",
"this",
"will",
"auto",
"used",
"after",
"slice",
"share"
] | def update(self):
"""
update the member from C, this will auto used after slice, share
"""
pinned = c_int()
self._api.LITE_is_pinned_host(self._tensor, byref(pinned))
self._is_pinned_host = pinned
device_type = c_int()
self._api.LITE_get_tensor_device_type(self._tensor, byref(device_type))
self._device_type = device_type
self._api.LITE_get_tensor_layout(self._tensor, byref(self._layout)) | [
"def",
"update",
"(",
"self",
")",
":",
"pinned",
"=",
"c_int",
"(",
")",
"self",
".",
"_api",
".",
"LITE_is_pinned_host",
"(",
"self",
".",
"_tensor",
",",
"byref",
"(",
"pinned",
")",
")",
"self",
".",
"_is_pinned_host",
"=",
"pinned",
"device_type",
... | https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/lite/pylite/megenginelite/tensor.py#L309-L319 | ||
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/python/turicreate/data_structures/sarray.py | python | SArray.contains | (self, item) | return SArray(_proxy=self.__proxy__.left_scalar_operator(item, "in")) | Performs an element-wise search of "item" in the SArray.
Conceptually equivalent to:
>>> sa.apply(lambda x: item in x)
If the current SArray contains strings and item is a string. Produces a 1
for each row if 'item' is a substring of the row and 0 otherwise.
If the current SArray contains list or arrays, this produces a 1
for each row if 'item' is an element of the list or array.
If the current SArray contains dictionaries, this produces a 1
for each row if 'item' is a key in the dictionary.
Parameters
----------
item : any type
The item to search for.
Returns
-------
out : SArray
A binary SArray where a non-zero value denotes that the item
was found in the row. And 0 if it is not found.
Examples
--------
>>> SArray(['abc','def','ghi']).contains('a')
dtype: int
Rows: 3
[1, 0, 0]
>>> SArray([['a','b'],['b','c'],['c','d']]).contains('b')
dtype: int
Rows: 3
[1, 1, 0]
>>> SArray([{'a':1},{'a':2,'b':1}, {'c':1}]).contains('a')
dtype: int
Rows: 3
[1, 1, 0]
See Also
--------
is_in | Performs an element-wise search of "item" in the SArray. | [
"Performs",
"an",
"element",
"-",
"wise",
"search",
"of",
"item",
"in",
"the",
"SArray",
"."
] | def contains(self, item):
"""
Performs an element-wise search of "item" in the SArray.
Conceptually equivalent to:
>>> sa.apply(lambda x: item in x)
If the current SArray contains strings and item is a string. Produces a 1
for each row if 'item' is a substring of the row and 0 otherwise.
If the current SArray contains list or arrays, this produces a 1
for each row if 'item' is an element of the list or array.
If the current SArray contains dictionaries, this produces a 1
for each row if 'item' is a key in the dictionary.
Parameters
----------
item : any type
The item to search for.
Returns
-------
out : SArray
A binary SArray where a non-zero value denotes that the item
was found in the row. And 0 if it is not found.
Examples
--------
>>> SArray(['abc','def','ghi']).contains('a')
dtype: int
Rows: 3
[1, 0, 0]
>>> SArray([['a','b'],['b','c'],['c','d']]).contains('b')
dtype: int
Rows: 3
[1, 1, 0]
>>> SArray([{'a':1},{'a':2,'b':1}, {'c':1}]).contains('a')
dtype: int
Rows: 3
[1, 1, 0]
See Also
--------
is_in
"""
return SArray(_proxy=self.__proxy__.left_scalar_operator(item, "in")) | [
"def",
"contains",
"(",
"self",
",",
"item",
")",
":",
"return",
"SArray",
"(",
"_proxy",
"=",
"self",
".",
"__proxy__",
".",
"left_scalar_operator",
"(",
"item",
",",
"\"in\"",
")",
")"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/data_structures/sarray.py#L952-L999 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/distributions/python/ops/distribution_util.py | python | make_diag_scale | (
loc=None,
scale_diag=None,
scale_identity_multiplier=None,
shape_hint=None,
validate_args=False,
assert_positive=False,
name=None) | Creates a LinOp representing a diagonal matrix.
Args:
loc: Floating-point `Tensor`. This is used for inferring shape in the case
where only `scale_identity_multiplier` is set.
scale_diag: Floating-point `Tensor` representing the diagonal matrix.
`scale_diag` has shape [N1, N2, ... k], which represents a k x k
diagonal matrix.
When `None` no diagonal term is added to the LinOp.
scale_identity_multiplier: floating point rank 0 `Tensor` representing a
scaling done to the identity matrix.
When `scale_identity_multiplier = scale_diag = scale_tril = None` then
`scale += IdentityMatrix`. Otherwise no scaled-identity-matrix is added
to `scale`.
shape_hint: scalar integer `Tensor` representing a hint at the dimension of
the identity matrix when only `scale_identity_multiplier` is set.
validate_args: Python `bool` indicating whether arguments should be
checked for correctness.
assert_positive: Python `bool` indicating whether LinOp should be checked
for being positive definite.
name: Python `str` name given to ops managed by this object.
Returns:
`LinearOperator` representing a lower triangular matrix.
Raises:
ValueError: If only `scale_identity_multiplier` is set and `loc` and
`shape_hint` are both None. | Creates a LinOp representing a diagonal matrix. | [
"Creates",
"a",
"LinOp",
"representing",
"a",
"diagonal",
"matrix",
"."
] | def make_diag_scale(
loc=None,
scale_diag=None,
scale_identity_multiplier=None,
shape_hint=None,
validate_args=False,
assert_positive=False,
name=None):
"""Creates a LinOp representing a diagonal matrix.
Args:
loc: Floating-point `Tensor`. This is used for inferring shape in the case
where only `scale_identity_multiplier` is set.
scale_diag: Floating-point `Tensor` representing the diagonal matrix.
`scale_diag` has shape [N1, N2, ... k], which represents a k x k
diagonal matrix.
When `None` no diagonal term is added to the LinOp.
scale_identity_multiplier: floating point rank 0 `Tensor` representing a
scaling done to the identity matrix.
When `scale_identity_multiplier = scale_diag = scale_tril = None` then
`scale += IdentityMatrix`. Otherwise no scaled-identity-matrix is added
to `scale`.
shape_hint: scalar integer `Tensor` representing a hint at the dimension of
the identity matrix when only `scale_identity_multiplier` is set.
validate_args: Python `bool` indicating whether arguments should be
checked for correctness.
assert_positive: Python `bool` indicating whether LinOp should be checked
for being positive definite.
name: Python `str` name given to ops managed by this object.
Returns:
`LinearOperator` representing a lower triangular matrix.
Raises:
ValueError: If only `scale_identity_multiplier` is set and `loc` and
`shape_hint` are both None.
"""
def _maybe_attach_assertion(x):
if not validate_args:
return x
if assert_positive:
return control_flow_ops.with_dependencies([
check_ops.assert_positive(
x, message="diagonal part must be positive"),
], x)
return control_flow_ops.with_dependencies([
check_ops.assert_none_equal(
x,
array_ops.zeros([], x.dtype),
message="diagonal part must be non-zero")], x)
with ops.name_scope(name, "make_diag_scale",
values=[loc, scale_diag, scale_identity_multiplier]):
loc = _convert_to_tensor(loc, name="loc")
scale_diag = _convert_to_tensor(scale_diag, name="scale_diag")
scale_identity_multiplier = _convert_to_tensor(
scale_identity_multiplier,
name="scale_identity_multiplier")
if scale_diag is not None:
if scale_identity_multiplier is not None:
scale_diag += scale_identity_multiplier[..., array_ops.newaxis]
return linalg.LinearOperatorDiag(
diag=_maybe_attach_assertion(scale_diag),
is_non_singular=True,
is_self_adjoint=True,
is_positive_definite=assert_positive)
if loc is None and shape_hint is None:
raise ValueError(
"Cannot infer `event_shape` unless `loc` or "
"`shape_hint` is specified.")
if shape_hint is None:
shape_hint = loc.shape[-1]
if scale_identity_multiplier is None:
return linalg.LinearOperatorIdentity(
num_rows=shape_hint,
dtype=loc.dtype.base_dtype,
is_self_adjoint=True,
is_positive_definite=True,
assert_proper_shapes=validate_args)
return linalg.LinearOperatorScaledIdentity(
num_rows=shape_hint,
multiplier=_maybe_attach_assertion(scale_identity_multiplier),
is_non_singular=True,
is_self_adjoint=True,
is_positive_definite=assert_positive,
assert_proper_shapes=validate_args) | [
"def",
"make_diag_scale",
"(",
"loc",
"=",
"None",
",",
"scale_diag",
"=",
"None",
",",
"scale_identity_multiplier",
"=",
"None",
",",
"shape_hint",
"=",
"None",
",",
"validate_args",
"=",
"False",
",",
"assert_positive",
"=",
"False",
",",
"name",
"=",
"Non... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/distributions/python/ops/distribution_util.py#L186-L277 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py2/setuptools/wheel.py | python | Wheel._move_data_entries | (destination_eggdir, dist_data) | Move data entries to their correct location. | Move data entries to their correct location. | [
"Move",
"data",
"entries",
"to",
"their",
"correct",
"location",
"."
] | def _move_data_entries(destination_eggdir, dist_data):
"""Move data entries to their correct location."""
dist_data = os.path.join(destination_eggdir, dist_data)
dist_data_scripts = os.path.join(dist_data, 'scripts')
if os.path.exists(dist_data_scripts):
egg_info_scripts = os.path.join(
destination_eggdir, 'EGG-INFO', 'scripts')
os.mkdir(egg_info_scripts)
for entry in os.listdir(dist_data_scripts):
# Remove bytecode, as it's not properly handled
# during easy_install scripts install phase.
if entry.endswith('.pyc'):
os.unlink(os.path.join(dist_data_scripts, entry))
else:
os.rename(
os.path.join(dist_data_scripts, entry),
os.path.join(egg_info_scripts, entry),
)
os.rmdir(dist_data_scripts)
for subdir in filter(os.path.exists, (
os.path.join(dist_data, d)
for d in ('data', 'headers', 'purelib', 'platlib')
)):
unpack(subdir, destination_eggdir)
if os.path.exists(dist_data):
os.rmdir(dist_data) | [
"def",
"_move_data_entries",
"(",
"destination_eggdir",
",",
"dist_data",
")",
":",
"dist_data",
"=",
"os",
".",
"path",
".",
"join",
"(",
"destination_eggdir",
",",
"dist_data",
")",
"dist_data_scripts",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dist_data",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/setuptools/wheel.py#L179-L204 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/prompt-toolkit/py3/prompt_toolkit/buffer.py | python | Buffer.go_to_completion | (self, index: Optional[int]) | Select a completion from the list of current completions. | Select a completion from the list of current completions. | [
"Select",
"a",
"completion",
"from",
"the",
"list",
"of",
"current",
"completions",
"."
] | def go_to_completion(self, index: Optional[int]) -> None:
"""
Select a completion from the list of current completions.
"""
assert self.complete_state
# Set new completion
state = self.complete_state
state.go_to_index(index)
# Set text/cursor position
new_text, new_cursor_position = state.new_text_and_position()
self.document = Document(new_text, new_cursor_position)
# (changing text/cursor position will unset complete_state.)
self.complete_state = state | [
"def",
"go_to_completion",
"(",
"self",
",",
"index",
":",
"Optional",
"[",
"int",
"]",
")",
"->",
"None",
":",
"assert",
"self",
".",
"complete_state",
"# Set new completion",
"state",
"=",
"self",
".",
"complete_state",
"state",
".",
"go_to_index",
"(",
"i... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py3/prompt_toolkit/buffer.py#L983-L998 | ||
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Tool/masm.py | python | generate | (env) | Add Builders and construction variables for masm to an Environment. | Add Builders and construction variables for masm to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"masm",
"to",
"an",
"Environment",
"."
] | def generate(env):
"""Add Builders and construction variables for masm to an Environment."""
static_obj, shared_obj = SCons.Tool.createObjBuilders(env)
for suffix in ASSuffixes:
static_obj.add_action(suffix, SCons.Defaults.ASAction)
shared_obj.add_action(suffix, SCons.Defaults.ASAction)
static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter)
shared_obj.add_emitter(suffix, SCons.Defaults.SharedObjectEmitter)
for suffix in ASPPSuffixes:
static_obj.add_action(suffix, SCons.Defaults.ASPPAction)
shared_obj.add_action(suffix, SCons.Defaults.ASPPAction)
static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter)
shared_obj.add_emitter(suffix, SCons.Defaults.SharedObjectEmitter)
env['AS'] = 'ml'
env['ASFLAGS'] = SCons.Util.CLVar('/nologo')
env['ASPPFLAGS'] = '$ASFLAGS'
env['ASCOM'] = '$AS $ASFLAGS /c /Fo$TARGET $SOURCES'
env['ASPPCOM'] = '$CC $ASPPFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS /c /Fo$TARGET $SOURCES'
env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1 | [
"def",
"generate",
"(",
"env",
")",
":",
"static_obj",
",",
"shared_obj",
"=",
"SCons",
".",
"Tool",
".",
"createObjBuilders",
"(",
"env",
")",
"for",
"suffix",
"in",
"ASSuffixes",
":",
"static_obj",
".",
"add_action",
"(",
"suffix",
",",
"SCons",
".",
"... | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Tool/masm.py#L47-L68 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/distributions/util.py | python | prefer_static_broadcast_shape | (shape1,
shape2,
name="prefer_static_broadcast_shape") | Convenience function which statically broadcasts shape when possible.
Args:
shape1: `1-D` integer `Tensor`. Already converted to tensor!
shape2: `1-D` integer `Tensor`. Already converted to tensor!
name: A string name to prepend to created ops.
Returns:
The broadcast shape, either as `TensorShape` (if broadcast can be done
statically), or as a `Tensor`. | Convenience function which statically broadcasts shape when possible. | [
"Convenience",
"function",
"which",
"statically",
"broadcasts",
"shape",
"when",
"possible",
"."
] | def prefer_static_broadcast_shape(shape1,
shape2,
name="prefer_static_broadcast_shape"):
"""Convenience function which statically broadcasts shape when possible.
Args:
shape1: `1-D` integer `Tensor`. Already converted to tensor!
shape2: `1-D` integer `Tensor`. Already converted to tensor!
name: A string name to prepend to created ops.
Returns:
The broadcast shape, either as `TensorShape` (if broadcast can be done
statically), or as a `Tensor`.
"""
with ops.name_scope(name, values=[shape1, shape2]):
def make_shape_tensor(x):
return ops.convert_to_tensor(x, name="shape", dtype=dtypes.int32)
def get_tensor_shape(s):
if isinstance(s, tensor_shape.TensorShape):
return s
s_ = tensor_util.constant_value(make_shape_tensor(s))
if s_ is not None:
return tensor_shape.TensorShape(s_)
return None
def get_shape_tensor(s):
if not isinstance(s, tensor_shape.TensorShape):
return make_shape_tensor(s)
if s.is_fully_defined():
return make_shape_tensor(s.as_list())
raise ValueError("Cannot broadcast from partially "
"defined `TensorShape`.")
shape1_ = get_tensor_shape(shape1)
shape2_ = get_tensor_shape(shape2)
if shape1_ is not None and shape2_ is not None:
return array_ops.broadcast_static_shape(shape1_, shape2_)
shape1_ = get_shape_tensor(shape1)
shape2_ = get_shape_tensor(shape2)
return array_ops.broadcast_dynamic_shape(shape1_, shape2_) | [
"def",
"prefer_static_broadcast_shape",
"(",
"shape1",
",",
"shape2",
",",
"name",
"=",
"\"prefer_static_broadcast_shape\"",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"values",
"=",
"[",
"shape1",
",",
"shape2",
"]",
")",
":",
"def",
"mak... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/distributions/util.py#L703-L745 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/sets.py | python | BaseSet.symmetric_difference | (self, other) | return result | Return the symmetric difference of two sets as a new set.
(I.e. all elements that are in exactly one of the sets.) | Return the symmetric difference of two sets as a new set. | [
"Return",
"the",
"symmetric",
"difference",
"of",
"two",
"sets",
"as",
"a",
"new",
"set",
"."
] | def symmetric_difference(self, other):
"""Return the symmetric difference of two sets as a new set.
(I.e. all elements that are in exactly one of the sets.)
"""
result = self.__class__()
data = result._data
value = True
selfdata = self._data
try:
otherdata = other._data
except AttributeError:
otherdata = Set(other)._data
for elt in ifilterfalse(otherdata.__contains__, selfdata):
data[elt] = value
for elt in ifilterfalse(selfdata.__contains__, otherdata):
data[elt] = value
return result | [
"def",
"symmetric_difference",
"(",
"self",
",",
"other",
")",
":",
"result",
"=",
"self",
".",
"__class__",
"(",
")",
"data",
"=",
"result",
".",
"_data",
"value",
"=",
"True",
"selfdata",
"=",
"self",
".",
"_data",
"try",
":",
"otherdata",
"=",
"othe... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/sets.py#L228-L245 | |
ros-planning/moveit | ee48dc5cedc981d0869352aa3db0b41469c2735c | moveit_commander/src/moveit_commander/robot.py | python | RobotCommander.get_link | (self, name) | @param name str: Name of movegroup
@rtype: moveit_commander.robot.Link
@raise exception: MoveItCommanderException | [] | def get_link(self, name):
"""
@param name str: Name of movegroup
@rtype: moveit_commander.robot.Link
@raise exception: MoveItCommanderException
"""
if name in self.get_link_names():
return self.Link(self, name)
else:
raise MoveItCommanderException("There is no link named %s" % name) | [
"def",
"get_link",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"in",
"self",
".",
"get_link_names",
"(",
")",
":",
"return",
"self",
".",
"Link",
"(",
"self",
",",
"name",
")",
"else",
":",
"raise",
"MoveItCommanderException",
"(",
"\"There is no l... | https://github.com/ros-planning/moveit/blob/ee48dc5cedc981d0869352aa3db0b41469c2735c/moveit_commander/src/moveit_commander/robot.py#L267-L276 | |||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/core/generic.py | python | NDFrame._dir_additions | (self) | return super(NDFrame, self)._dir_additions().union(additions) | add the string-like attributes from the info_axis.
If info_axis is a MultiIndex, it's first level values are used. | add the string-like attributes from the info_axis.
If info_axis is a MultiIndex, it's first level values are used. | [
"add",
"the",
"string",
"-",
"like",
"attributes",
"from",
"the",
"info_axis",
".",
"If",
"info_axis",
"is",
"a",
"MultiIndex",
"it",
"s",
"first",
"level",
"values",
"are",
"used",
"."
] | def _dir_additions(self):
""" add the string-like attributes from the info_axis.
If info_axis is a MultiIndex, it's first level values are used.
"""
additions = {c for c in self._info_axis.unique(level=0)[:100]
if isinstance(c, string_types) and isidentifier(c)}
return super(NDFrame, self)._dir_additions().union(additions) | [
"def",
"_dir_additions",
"(",
"self",
")",
":",
"additions",
"=",
"{",
"c",
"for",
"c",
"in",
"self",
".",
"_info_axis",
".",
"unique",
"(",
"level",
"=",
"0",
")",
"[",
":",
"100",
"]",
"if",
"isinstance",
"(",
"c",
",",
"string_types",
")",
"and"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/generic.py#L5108-L5114 | |
RamadhanAmizudin/malware | 2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1 | Fuzzbunch/fuzzbunch/pyreadline/console/console.py | python | Console.rectangle | (self, rect, attr=None, fill=' ') | Fill Rectangle. | Fill Rectangle. | [
"Fill",
"Rectangle",
"."
] | def rectangle(self, rect, attr=None, fill=' '):
'''Fill Rectangle.'''
log_sock("rect:%s"%[rect])
x0, y0, x1, y1 = rect
n = c_int(0)
if attr is None:
attr = self.attr
for y in range(y0, y1):
pos = self.fixcoord(x0, y)
self.FillConsoleOutputAttribute(self.hout, attr, x1-x0, pos, byref(n))
self.FillConsoleOutputCharacterA(self.hout, ord(fill[0]), x1-x0, pos, byref(n)) | [
"def",
"rectangle",
"(",
"self",
",",
"rect",
",",
"attr",
"=",
"None",
",",
"fill",
"=",
"' '",
")",
":",
"log_sock",
"(",
"\"rect:%s\"",
"%",
"[",
"rect",
"]",
")",
"x0",
",",
"y0",
",",
"x1",
",",
"y1",
"=",
"rect",
"n",
"=",
"c_int",
"(",
... | https://github.com/RamadhanAmizudin/malware/blob/2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1/Fuzzbunch/fuzzbunch/pyreadline/console/console.py#L436-L446 | ||
SFTtech/openage | d6a08c53c48dc1e157807471df92197f6ca9e04d | openage/convert/entity_object/export/formats/nyan_file.py | python | NyanFile.set_modpack_name | (self, modpack_name) | Set the name of the modpack, the file is contained in. | Set the name of the modpack, the file is contained in. | [
"Set",
"the",
"name",
"of",
"the",
"modpack",
"the",
"file",
"is",
"contained",
"in",
"."
] | def set_modpack_name(self, modpack_name):
"""
Set the name of the modpack, the file is contained in.
"""
self.modpack_name = modpack_name | [
"def",
"set_modpack_name",
"(",
"self",
",",
"modpack_name",
")",
":",
"self",
".",
"modpack_name",
"=",
"modpack_name"
] | https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/convert/entity_object/export/formats/nyan_file.py#L102-L106 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/ImageShow.py | python | Viewer.show_image | (self, image, **options) | return self.show_file(self.save_image(image), **options) | Display given image | Display given image | [
"Display",
"given",
"image"
] | def show_image(self, image, **options):
"""Display given image"""
return self.show_file(self.save_image(image), **options) | [
"def",
"show_image",
"(",
"self",
",",
"image",
",",
"*",
"*",
"options",
")",
":",
"return",
"self",
".",
"show_file",
"(",
"self",
".",
"save_image",
"(",
"image",
")",
",",
"*",
"*",
"options",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/ImageShow.py#L86-L88 | |
goldeneye-source/ges-code | 2630cd8ef3d015af53c72ec2e19fc1f7e7fe8d9d | thirdparty/protobuf-2.3.0/python/google/protobuf/reflection.py | python | _AddSetListenerMethod | (cls) | Helper for _AddMessageMethods(). | Helper for _AddMessageMethods(). | [
"Helper",
"for",
"_AddMessageMethods",
"()",
"."
] | def _AddSetListenerMethod(cls):
"""Helper for _AddMessageMethods()."""
def SetListener(self, listener):
if listener is None:
self._listener = message_listener_mod.NullMessageListener()
else:
self._listener = listener
cls._SetListener = SetListener | [
"def",
"_AddSetListenerMethod",
"(",
"cls",
")",
":",
"def",
"SetListener",
"(",
"self",
",",
"listener",
")",
":",
"if",
"listener",
"is",
"None",
":",
"self",
".",
"_listener",
"=",
"message_listener_mod",
".",
"NullMessageListener",
"(",
")",
"else",
":",... | https://github.com/goldeneye-source/ges-code/blob/2630cd8ef3d015af53c72ec2e19fc1f7e7fe8d9d/thirdparty/protobuf-2.3.0/python/google/protobuf/reflection.py#L738-L745 | ||
ideawu/ssdb-rocks | a3cbb322cafb2f493252829c608e2239df98c9ac | deps/cpy/antlr3/recognizers.py | python | BaseRecognizer.mismatch | (self, input, ttype, follow) | Factor out what to do upon token mismatch so tree parsers can behave
differently. Override and call mismatchRecover(input, ttype, follow)
to get single token insertion and deletion. Use this to turn of
single token insertion and deletion. Override mismatchRecover
to call this instead. | Factor out what to do upon token mismatch so tree parsers can behave
differently. Override and call mismatchRecover(input, ttype, follow)
to get single token insertion and deletion. Use this to turn of
single token insertion and deletion. Override mismatchRecover
to call this instead. | [
"Factor",
"out",
"what",
"to",
"do",
"upon",
"token",
"mismatch",
"so",
"tree",
"parsers",
"can",
"behave",
"differently",
".",
"Override",
"and",
"call",
"mismatchRecover",
"(",
"input",
"ttype",
"follow",
")",
"to",
"get",
"single",
"token",
"insertion",
"... | def mismatch(self, input, ttype, follow):
"""
Factor out what to do upon token mismatch so tree parsers can behave
differently. Override and call mismatchRecover(input, ttype, follow)
to get single token insertion and deletion. Use this to turn of
single token insertion and deletion. Override mismatchRecover
to call this instead.
"""
if self.mismatchIsUnwantedToken(input, ttype):
raise UnwantedTokenException(ttype, input)
elif self.mismatchIsMissingToken(input, follow):
raise MissingTokenException(ttype, input, None)
raise MismatchedTokenException(ttype, input) | [
"def",
"mismatch",
"(",
"self",
",",
"input",
",",
"ttype",
",",
"follow",
")",
":",
"if",
"self",
".",
"mismatchIsUnwantedToken",
"(",
"input",
",",
"ttype",
")",
":",
"raise",
"UnwantedTokenException",
"(",
"ttype",
",",
"input",
")",
"elif",
"self",
"... | https://github.com/ideawu/ssdb-rocks/blob/a3cbb322cafb2f493252829c608e2239df98c9ac/deps/cpy/antlr3/recognizers.py#L276-L291 | ||
PlatformLab/RAMCloud | b1866af19124325a6dfd8cbc267e2e3ef1f965d1 | scripts/common.py | python | captureSh | (command, **kwargs) | Execute a local command and capture its output. | Execute a local command and capture its output. | [
"Execute",
"a",
"local",
"command",
"and",
"capture",
"its",
"output",
"."
] | def captureSh(command, **kwargs):
"""Execute a local command and capture its output."""
kwargs['shell'] = True
kwargs['stdout'] = subprocess.PIPE
p = subprocess.Popen(command, **kwargs)
output = p.communicate()[0]
if p.returncode:
raise subprocess.CalledProcessError(p.returncode, command)
if output.count('\n') and output[-1] == '\n':
return output[:-1]
else:
return output | [
"def",
"captureSh",
"(",
"command",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'shell'",
"]",
"=",
"True",
"kwargs",
"[",
"'stdout'",
"]",
"=",
"subprocess",
".",
"PIPE",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"command",
",",
"*",
"*",
... | https://github.com/PlatformLab/RAMCloud/blob/b1866af19124325a6dfd8cbc267e2e3ef1f965d1/scripts/common.py#L40-L52 | ||
SIPp/sipp | f44d0cf5dec0013eff8fd7b4da885d455aa82e0e | cpplint.py | python | CheckCStyleCast | (filename, linenum, line, raw_line, cast_type, pattern,
error) | return True | Checks for a C-style cast by looking for the pattern.
This also handles sizeof(type) warnings, due to similarity of content.
Args:
filename: The name of the current file.
linenum: The number of the line to check.
line: The line of code to check.
raw_line: The raw line of code to check, with comments.
cast_type: The string for the C++ cast to recommend. This is either
reinterpret_cast, static_cast, or const_cast, depending.
pattern: The regular expression used to find C-style casts.
error: The function to call with any errors found.
Returns:
True if an error was emitted.
False otherwise. | Checks for a C-style cast by looking for the pattern. | [
"Checks",
"for",
"a",
"C",
"-",
"style",
"cast",
"by",
"looking",
"for",
"the",
"pattern",
"."
] | def CheckCStyleCast(filename, linenum, line, raw_line, cast_type, pattern,
error):
"""Checks for a C-style cast by looking for the pattern.
This also handles sizeof(type) warnings, due to similarity of content.
Args:
filename: The name of the current file.
linenum: The number of the line to check.
line: The line of code to check.
raw_line: The raw line of code to check, with comments.
cast_type: The string for the C++ cast to recommend. This is either
reinterpret_cast, static_cast, or const_cast, depending.
pattern: The regular expression used to find C-style casts.
error: The function to call with any errors found.
Returns:
True if an error was emitted.
False otherwise.
"""
match = Search(pattern, line)
if not match:
return False
# e.g., sizeof(int)
sizeof_match = Match(r'.*sizeof\s*$', line[0:match.start(1) - 1])
if sizeof_match:
error(filename, linenum, 'runtime/sizeof', 1,
'Using sizeof(type). Use sizeof(varname) instead if possible')
return True
# operator++(int) and operator--(int)
if (line[0:match.start(1) - 1].endswith(' operator++') or
line[0:match.start(1) - 1].endswith(' operator--')):
return False
remainder = line[match.end(0):]
# The close paren is for function pointers as arguments to a function.
# eg, void foo(void (*bar)(int));
# The semicolon check is a more basic function check; also possibly a
# function pointer typedef.
# eg, void foo(int); or void foo(int) const;
# The equals check is for function pointer assignment.
# eg, void *(*foo)(int) = ...
# The > is for MockCallback<...> ...
#
# Right now, this will only catch cases where there's a single argument, and
# it's unnamed. It should probably be expanded to check for multiple
# arguments with some unnamed.
function_match = Match(r'\s*(\)|=|(const)?\s*(;|\{|throw\(\)|>))', remainder)
if function_match:
if (not function_match.group(3) or
function_match.group(3) == ';' or
('MockCallback<' not in raw_line and
'/*' not in raw_line)):
error(filename, linenum, 'readability/function', 3,
'All parameters should be named in a function')
return True
# At this point, all that should be left is actual casts.
error(filename, linenum, 'readability/casting', 4,
'Using C-style cast. Use %s<%s>(...) instead' %
(cast_type, match.group(1)))
return True | [
"def",
"CheckCStyleCast",
"(",
"filename",
",",
"linenum",
",",
"line",
",",
"raw_line",
",",
"cast_type",
",",
"pattern",
",",
"error",
")",
":",
"match",
"=",
"Search",
"(",
"pattern",
",",
"line",
")",
"if",
"not",
"match",
":",
"return",
"False",
"... | https://github.com/SIPp/sipp/blob/f44d0cf5dec0013eff8fd7b4da885d455aa82e0e/cpplint.py#L3447-L3512 | |
TheImagingSource/tiscamera | baacb4cfaa7858c2e6cfb4f1a297b404c4e002f6 | examples/python/02-set-properties.py | python | print_properties | (camera) | Print selected properties | Print selected properties | [
"Print",
"selected",
"properties"
] | def print_properties(camera):
"""
Print selected properties
"""
(ret, value,
min_value, max_value,
default_value, step_size,
value_type, flags,
category, group) = camera.get_tcam_property("Exposure Auto")
if ret:
print("Exposure Auto has value: {}".format(value))
else:
print("Could not query Exposure Auto")
(ret, value,
min_value, max_value,
default_value, step_size,
value_type, flags,
category, group) = camera.get_tcam_property("Gain Auto")
if ret:
print("Gain Auto has value: {}".format(value))
else:
print("Could not query Gain Auto")
(ret, value,
min_value, max_value,
default_value, step_size,
value_type, flags,
category, group) = camera.get_tcam_property("Brightness")
if ret:
print("Brightness has value: {}".format(value))
else:
print("Could not query Brightness") | [
"def",
"print_properties",
"(",
"camera",
")",
":",
"(",
"ret",
",",
"value",
",",
"min_value",
",",
"max_value",
",",
"default_value",
",",
"step_size",
",",
"value_type",
",",
"flags",
",",
"category",
",",
"group",
")",
"=",
"camera",
".",
"get_tcam_pro... | https://github.com/TheImagingSource/tiscamera/blob/baacb4cfaa7858c2e6cfb4f1a297b404c4e002f6/examples/python/02-set-properties.py#L30-L65 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/grit/grit/format/policy_templates/writers/template_writer.py | python | TemplateWriter.SortPoliciesGroupsFirst | (self, policy_list) | return policy_list | Sorts a list of policies alphabetically. The order is the
following: first groups alphabetically by caption, then other policies
alphabetically by name. The order of policies inside groups is unchanged.
Args:
policy_list: The list of policies to sort. Sub-lists in groups will not
be sorted. | Sorts a list of policies alphabetically. The order is the
following: first groups alphabetically by caption, then other policies
alphabetically by name. The order of policies inside groups is unchanged. | [
"Sorts",
"a",
"list",
"of",
"policies",
"alphabetically",
".",
"The",
"order",
"is",
"the",
"following",
":",
"first",
"groups",
"alphabetically",
"by",
"caption",
"then",
"other",
"policies",
"alphabetically",
"by",
"name",
".",
"The",
"order",
"of",
"policie... | def SortPoliciesGroupsFirst(self, policy_list):
'''Sorts a list of policies alphabetically. The order is the
following: first groups alphabetically by caption, then other policies
alphabetically by name. The order of policies inside groups is unchanged.
Args:
policy_list: The list of policies to sort. Sub-lists in groups will not
be sorted.
'''
policy_list.sort(key=self.GetPolicySortingKeyGroupsFirst)
return policy_list | [
"def",
"SortPoliciesGroupsFirst",
"(",
"self",
",",
"policy_list",
")",
":",
"policy_list",
".",
"sort",
"(",
"key",
"=",
"self",
".",
"GetPolicySortingKeyGroupsFirst",
")",
"return",
"policy_list"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/grit/grit/format/policy_templates/writers/template_writer.py#L276-L286 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/distutils/misc_util.py | python | Configuration.append_to | (self, extlib) | Append libraries, include_dirs to extension or library item. | Append libraries, include_dirs to extension or library item. | [
"Append",
"libraries",
"include_dirs",
"to",
"extension",
"or",
"library",
"item",
"."
] | def append_to(self, extlib):
"""Append libraries, include_dirs to extension or library item.
"""
if is_sequence(extlib):
lib_name, build_info = extlib
dict_append(build_info,
libraries=self.libraries,
include_dirs=self.include_dirs)
else:
from numpy.distutils.core import Extension
assert isinstance(extlib, Extension), repr(extlib)
extlib.libraries.extend(self.libraries)
extlib.include_dirs.extend(self.include_dirs) | [
"def",
"append_to",
"(",
"self",
",",
"extlib",
")",
":",
"if",
"is_sequence",
"(",
"extlib",
")",
":",
"lib_name",
",",
"build_info",
"=",
"extlib",
"dict_append",
"(",
"build_info",
",",
"libraries",
"=",
"self",
".",
"libraries",
",",
"include_dirs",
"=... | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/distutils/misc_util.py#L1753-L1765 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/asyncio/sslproto.py | python | _SSLProtocolTransport.pause_reading | (self) | Pause the receiving end.
No data will be passed to the protocol's data_received()
method until resume_reading() is called. | Pause the receiving end. | [
"Pause",
"the",
"receiving",
"end",
"."
] | def pause_reading(self):
"""Pause the receiving end.
No data will be passed to the protocol's data_received()
method until resume_reading() is called.
"""
self._ssl_protocol._transport.pause_reading() | [
"def",
"pause_reading",
"(",
"self",
")",
":",
"self",
".",
"_ssl_protocol",
".",
"_transport",
".",
"pause_reading",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/asyncio/sslproto.py#L331-L337 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_misc.py | python | DateTime.GetMillisecond | (*args, **kwargs) | return _misc_.DateTime_GetMillisecond(*args, **kwargs) | GetMillisecond(self, wxDateTime::TimeZone tz=LOCAL_TZ) -> int | GetMillisecond(self, wxDateTime::TimeZone tz=LOCAL_TZ) -> int | [
"GetMillisecond",
"(",
"self",
"wxDateTime",
"::",
"TimeZone",
"tz",
"=",
"LOCAL_TZ",
")",
"-",
">",
"int"
] | def GetMillisecond(*args, **kwargs):
"""GetMillisecond(self, wxDateTime::TimeZone tz=LOCAL_TZ) -> int"""
return _misc_.DateTime_GetMillisecond(*args, **kwargs) | [
"def",
"GetMillisecond",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"DateTime_GetMillisecond",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L4005-L4007 | |
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | python/psutil/psutil/_psosx.py | python | Process.get_process_ppid | (self) | return _psutil_osx.get_process_ppid(self.pid) | Return process parent pid. | Return process parent pid. | [
"Return",
"process",
"parent",
"pid",
"."
] | def get_process_ppid(self):
"""Return process parent pid."""
return _psutil_osx.get_process_ppid(self.pid) | [
"def",
"get_process_ppid",
"(",
"self",
")",
":",
"return",
"_psutil_osx",
".",
"get_process_ppid",
"(",
"self",
".",
"pid",
")"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/psutil/psutil/_psosx.py#L192-L194 | |
bigartm/bigartm | 47e37f982de87aa67bfd475ff1f39da696b181b3 | 3rdparty/protobuf-3.0.0/python/google/protobuf/descriptor.py | python | MakeDescriptor | (desc_proto, package='', build_file_if_cpp=True,
syntax=None) | return Descriptor(desc_proto.name, desc_name, None, None, fields,
list(nested_types.values()), list(enum_types.values()), [],
options=desc_proto.options) | Make a protobuf Descriptor given a DescriptorProto protobuf.
Handles nested descriptors. Note that this is limited to the scope of defining
a message inside of another message. Composite fields can currently only be
resolved if the message is defined in the same scope as the field.
Args:
desc_proto: The descriptor_pb2.DescriptorProto protobuf message.
package: Optional package name for the new message Descriptor (string).
build_file_if_cpp: Update the C++ descriptor pool if api matches.
Set to False on recursion, so no duplicates are created.
syntax: The syntax/semantics that should be used. Set to "proto3" to get
proto3 field presence semantics.
Returns:
A Descriptor for protobuf messages. | Make a protobuf Descriptor given a DescriptorProto protobuf. | [
"Make",
"a",
"protobuf",
"Descriptor",
"given",
"a",
"DescriptorProto",
"protobuf",
"."
] | def MakeDescriptor(desc_proto, package='', build_file_if_cpp=True,
syntax=None):
"""Make a protobuf Descriptor given a DescriptorProto protobuf.
Handles nested descriptors. Note that this is limited to the scope of defining
a message inside of another message. Composite fields can currently only be
resolved if the message is defined in the same scope as the field.
Args:
desc_proto: The descriptor_pb2.DescriptorProto protobuf message.
package: Optional package name for the new message Descriptor (string).
build_file_if_cpp: Update the C++ descriptor pool if api matches.
Set to False on recursion, so no duplicates are created.
syntax: The syntax/semantics that should be used. Set to "proto3" to get
proto3 field presence semantics.
Returns:
A Descriptor for protobuf messages.
"""
if api_implementation.Type() == 'cpp' and build_file_if_cpp:
# The C++ implementation requires all descriptors to be backed by the same
# definition in the C++ descriptor pool. To do this, we build a
# FileDescriptorProto with the same definition as this descriptor and build
# it into the pool.
from google.protobuf import descriptor_pb2
file_descriptor_proto = descriptor_pb2.FileDescriptorProto()
file_descriptor_proto.message_type.add().MergeFrom(desc_proto)
# Generate a random name for this proto file to prevent conflicts with any
# imported ones. We need to specify a file name so the descriptor pool
# accepts our FileDescriptorProto, but it is not important what that file
# name is actually set to.
proto_name = str(uuid.uuid4())
if package:
file_descriptor_proto.name = os.path.join(package.replace('.', '/'),
proto_name + '.proto')
file_descriptor_proto.package = package
else:
file_descriptor_proto.name = proto_name + '.proto'
_message.default_pool.Add(file_descriptor_proto)
result = _message.default_pool.FindFileByName(file_descriptor_proto.name)
if _USE_C_DESCRIPTORS:
return result.message_types_by_name[desc_proto.name]
full_message_name = [desc_proto.name]
if package: full_message_name.insert(0, package)
# Create Descriptors for enum types
enum_types = {}
for enum_proto in desc_proto.enum_type:
full_name = '.'.join(full_message_name + [enum_proto.name])
enum_desc = EnumDescriptor(
enum_proto.name, full_name, None, [
EnumValueDescriptor(enum_val.name, ii, enum_val.number)
for ii, enum_val in enumerate(enum_proto.value)])
enum_types[full_name] = enum_desc
# Create Descriptors for nested types
nested_types = {}
for nested_proto in desc_proto.nested_type:
full_name = '.'.join(full_message_name + [nested_proto.name])
# Nested types are just those defined inside of the message, not all types
# used by fields in the message, so no loops are possible here.
nested_desc = MakeDescriptor(nested_proto,
package='.'.join(full_message_name),
build_file_if_cpp=False,
syntax=syntax)
nested_types[full_name] = nested_desc
fields = []
for field_proto in desc_proto.field:
full_name = '.'.join(full_message_name + [field_proto.name])
enum_desc = None
nested_desc = None
if field_proto.HasField('type_name'):
type_name = field_proto.type_name
full_type_name = '.'.join(full_message_name +
[type_name[type_name.rfind('.')+1:]])
if full_type_name in nested_types:
nested_desc = nested_types[full_type_name]
elif full_type_name in enum_types:
enum_desc = enum_types[full_type_name]
# Else type_name references a non-local type, which isn't implemented
field = FieldDescriptor(
field_proto.name, full_name, field_proto.number - 1,
field_proto.number, field_proto.type,
FieldDescriptor.ProtoTypeToCppProtoType(field_proto.type),
field_proto.label, None, nested_desc, enum_desc, None, False, None,
options=field_proto.options, has_default_value=False)
fields.append(field)
desc_name = '.'.join(full_message_name)
return Descriptor(desc_proto.name, desc_name, None, None, fields,
list(nested_types.values()), list(enum_types.values()), [],
options=desc_proto.options) | [
"def",
"MakeDescriptor",
"(",
"desc_proto",
",",
"package",
"=",
"''",
",",
"build_file_if_cpp",
"=",
"True",
",",
"syntax",
"=",
"None",
")",
":",
"if",
"api_implementation",
".",
"Type",
"(",
")",
"==",
"'cpp'",
"and",
"build_file_if_cpp",
":",
"# The C++ ... | https://github.com/bigartm/bigartm/blob/47e37f982de87aa67bfd475ff1f39da696b181b3/3rdparty/protobuf-3.0.0/python/google/protobuf/descriptor.py#L897-L993 | |
Tencent/CMONGO | c40380caa14e05509f46993aa8b8da966b09b0b5 | src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/packaging/rpm.py | python | build_specfile | (target, source, env) | Builds a RPM specfile from a dictionary with string metadata and
by analyzing a tree of nodes. | Builds a RPM specfile from a dictionary with string metadata and
by analyzing a tree of nodes. | [
"Builds",
"a",
"RPM",
"specfile",
"from",
"a",
"dictionary",
"with",
"string",
"metadata",
"and",
"by",
"analyzing",
"a",
"tree",
"of",
"nodes",
"."
] | def build_specfile(target, source, env):
""" Builds a RPM specfile from a dictionary with string metadata and
by analyzing a tree of nodes.
"""
file = open(target[0].get_abspath(), 'w')
try:
file.write( build_specfile_header(env) )
file.write( build_specfile_sections(env) )
file.write( build_specfile_filesection(env, source) )
file.close()
# call a user specified function
if 'CHANGE_SPECFILE' in env:
env['CHANGE_SPECFILE'](target, source)
except KeyError, e:
raise SCons.Errors.UserError( '"%s" package field for RPM is missing.' % e.args[0] ) | [
"def",
"build_specfile",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"file",
"=",
"open",
"(",
"target",
"[",
"0",
"]",
".",
"get_abspath",
"(",
")",
",",
"'w'",
")",
"try",
":",
"file",
".",
"write",
"(",
"build_specfile_header",
"(",
"env",... | https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/packaging/rpm.py#L123-L140 | ||
gnuradio/gnuradio | 09c3c4fa4bfb1a02caac74cb5334dfe065391e3b | gr-blocks/python/blocks/qa_block_behavior.py | python | test_block_behavior.test_000 | (self) | Tests the max noutput sizes set by the scheduler. When creating
the block, there is no block_detail and so the max buffer size
is 0. When the top_block is run, it builds the detail and
buffers and sets the max value. test_0001 tests when the
max_noutput_items is set by hand. | Tests the max noutput sizes set by the scheduler. When creating
the block, there is no block_detail and so the max buffer size
is 0. When the top_block is run, it builds the detail and
buffers and sets the max value. test_0001 tests when the
max_noutput_items is set by hand. | [
"Tests",
"the",
"max",
"noutput",
"sizes",
"set",
"by",
"the",
"scheduler",
".",
"When",
"creating",
"the",
"block",
"there",
"is",
"no",
"block_detail",
"and",
"so",
"the",
"max",
"buffer",
"size",
"is",
"0",
".",
"When",
"the",
"top_block",
"is",
"run"... | def test_000(self):
'''
Tests the max noutput sizes set by the scheduler. When creating
the block, there is no block_detail and so the max buffer size
is 0. When the top_block is run, it builds the detail and
buffers and sets the max value. test_0001 tests when the
max_noutput_items is set by hand.
'''
src = blocks.null_source(gr.sizeof_float)
op = blocks.head(gr.sizeof_float, 100)
snk = blocks.null_sink(gr.sizeof_float)
maxn_pre = op.max_noutput_items()
self.tb.connect(src, op, snk)
self.tb.run()
maxn_post = op.max_noutput_items()
self.assertEqual(maxn_pre, 0)
self.assertEqual(maxn_post, 16384) | [
"def",
"test_000",
"(",
"self",
")",
":",
"src",
"=",
"blocks",
".",
"null_source",
"(",
"gr",
".",
"sizeof_float",
")",
"op",
"=",
"blocks",
".",
"head",
"(",
"gr",
".",
"sizeof_float",
",",
"100",
")",
"snk",
"=",
"blocks",
".",
"null_sink",
"(",
... | https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/gr-blocks/python/blocks/qa_block_behavior.py#L23-L45 | ||
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | modules/geochemistry/python/dbutils.py | python | printSpeciesInfo | (db, species) | return | Find the given species and return all information related to it | Find the given species and return all information related to it | [
"Find",
"the",
"given",
"species",
"and",
"return",
"all",
"information",
"related",
"to",
"it"
] | def printSpeciesInfo(db, species):
"""
Find the given species and return all information related to it
"""
while True:
# Check basis species
if db['basis species']:
if species in db['basis species']:
type, result = 'basis species', db['basis species'][species]
break
# Check secondary species
if db['secondary species']:
if species in db['secondary species']:
type, result = 'secondary species', db['secondary species'][species]
break
# Check redox couples
if db['redox couples']:
if species in db['redox couples']:
type, result = 'redox couple', db['redox couples'][species]
break
# Check gas species
if db['gas species']:
if species in db['gas species']:
type, result = 'gas species', db['gas species'][species]
break
# Check minerals
if db['mineral species']:
if species in db['mineral species']:
type, result = 'mineral species', db['mineral species'][species]
break
# If we get here, species is not is database
print(species, "not in database")
return
# Now print out the information
indent = ' '
print(species + ':')
print(indent + 'type:', type)
for (key, values) in result.items():
print(indent + key + ": ", values)
return | [
"def",
"printSpeciesInfo",
"(",
"db",
",",
"species",
")",
":",
"while",
"True",
":",
"# Check basis species",
"if",
"db",
"[",
"'basis species'",
"]",
":",
"if",
"species",
"in",
"db",
"[",
"'basis species'",
"]",
":",
"type",
",",
"result",
"=",
"'basis ... | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/modules/geochemistry/python/dbutils.py#L20-L66 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/resolvelib/providers.py | python | AbstractResolver.resolve | (self, requirements, **kwargs) | Take a collection of constraints, spit out the resolution result.
This returns a representation of the final resolution state, with one
guarenteed attribute ``mapping`` that contains resolved candidates as
values. The keys are their respective identifiers.
:param requirements: A collection of constraints.
:param kwargs: Additional keyword arguments that subclasses may accept.
:raises: ``self.base_exception`` or its subclass. | Take a collection of constraints, spit out the resolution result. | [
"Take",
"a",
"collection",
"of",
"constraints",
"spit",
"out",
"the",
"resolution",
"result",
"."
] | def resolve(self, requirements, **kwargs):
"""Take a collection of constraints, spit out the resolution result.
This returns a representation of the final resolution state, with one
guarenteed attribute ``mapping`` that contains resolved candidates as
values. The keys are their respective identifiers.
:param requirements: A collection of constraints.
:param kwargs: Additional keyword arguments that subclasses may accept.
:raises: ``self.base_exception`` or its subclass.
"""
raise NotImplementedError | [
"def",
"resolve",
"(",
"self",
",",
"requirements",
",",
"*",
"*",
"kwargs",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/resolvelib/providers.py#L107-L119 | ||
nvdla/sw | 79538ba1b52b040a4a4645f630e457fa01839e90 | umd/external/protobuf-2.6/python/google/protobuf/service_reflection.py | python | GeneratedServiceStubType.__init__ | (cls, name, bases, dictionary) | Creates a message service stub class.
Args:
name: Name of the class (ignored, here).
bases: Base classes of the class being constructed.
dictionary: The class dictionary of the class being constructed.
dictionary[_DESCRIPTOR_KEY] must contain a ServiceDescriptor object
describing this protocol service type. | Creates a message service stub class. | [
"Creates",
"a",
"message",
"service",
"stub",
"class",
"."
] | def __init__(cls, name, bases, dictionary):
"""Creates a message service stub class.
Args:
name: Name of the class (ignored, here).
bases: Base classes of the class being constructed.
dictionary: The class dictionary of the class being constructed.
dictionary[_DESCRIPTOR_KEY] must contain a ServiceDescriptor object
describing this protocol service type.
"""
super(GeneratedServiceStubType, cls).__init__(name, bases, dictionary)
# Don't do anything if this class doesn't have a descriptor. This happens
# when a service stub is subclassed.
if GeneratedServiceStubType._DESCRIPTOR_KEY not in dictionary:
return
descriptor = dictionary[GeneratedServiceStubType._DESCRIPTOR_KEY]
service_stub_builder = _ServiceStubBuilder(descriptor)
service_stub_builder.BuildServiceStub(cls) | [
"def",
"__init__",
"(",
"cls",
",",
"name",
",",
"bases",
",",
"dictionary",
")",
":",
"super",
"(",
"GeneratedServiceStubType",
",",
"cls",
")",
".",
"__init__",
"(",
"name",
",",
"bases",
",",
"dictionary",
")",
"# Don't do anything if this class doesn't have ... | https://github.com/nvdla/sw/blob/79538ba1b52b040a4a4645f630e457fa01839e90/umd/external/protobuf-2.6/python/google/protobuf/service_reflection.py#L94-L111 | ||
abforce/xposed_art_n | ec3fbe417d74d4664cec053d91dd4e3881176374 | tools/checker/file_format/checker/parser.py | python | __extractLine | (prefix, line, arch = None, debuggable = False) | Attempts to parse a check line. The regex searches for a comment symbol
followed by the CHECK keyword, given attribute and a colon at the very
beginning of the line. Whitespaces are ignored. | Attempts to parse a check line. The regex searches for a comment symbol
followed by the CHECK keyword, given attribute and a colon at the very
beginning of the line. Whitespaces are ignored. | [
"Attempts",
"to",
"parse",
"a",
"check",
"line",
".",
"The",
"regex",
"searches",
"for",
"a",
"comment",
"symbol",
"followed",
"by",
"the",
"CHECK",
"keyword",
"given",
"attribute",
"and",
"a",
"colon",
"at",
"the",
"very",
"beginning",
"of",
"the",
"line"... | def __extractLine(prefix, line, arch = None, debuggable = False):
""" Attempts to parse a check line. The regex searches for a comment symbol
followed by the CHECK keyword, given attribute and a colon at the very
beginning of the line. Whitespaces are ignored.
"""
rIgnoreWhitespace = r"\s*"
rCommentSymbols = [r"///", r"##"]
arch_specifier = r"-%s" % arch if arch is not None else r""
dbg_specifier = r"-DEBUGGABLE" if debuggable else r""
regexPrefix = rIgnoreWhitespace + \
r"(" + r"|".join(rCommentSymbols) + r")" + \
rIgnoreWhitespace + \
prefix + arch_specifier + dbg_specifier + r":"
# The 'match' function succeeds only if the pattern is matched at the
# beginning of the line.
match = re.match(regexPrefix, line)
if match is not None:
return line[match.end():].strip()
else:
return None | [
"def",
"__extractLine",
"(",
"prefix",
",",
"line",
",",
"arch",
"=",
"None",
",",
"debuggable",
"=",
"False",
")",
":",
"rIgnoreWhitespace",
"=",
"r\"\\s*\"",
"rCommentSymbols",
"=",
"[",
"r\"///\"",
",",
"r\"##\"",
"]",
"arch_specifier",
"=",
"r\"-%s\"",
"... | https://github.com/abforce/xposed_art_n/blob/ec3fbe417d74d4664cec053d91dd4e3881176374/tools/checker/file_format/checker/parser.py#L25-L45 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | Window.HasFocus | (*args, **kwargs) | return _core_.Window_HasFocus(*args, **kwargs) | HasFocus(self) -> bool
Returns ``True`` if the window has the keyboard focus. | HasFocus(self) -> bool | [
"HasFocus",
"(",
"self",
")",
"-",
">",
"bool"
] | def HasFocus(*args, **kwargs):
"""
HasFocus(self) -> bool
Returns ``True`` if the window has the keyboard focus.
"""
return _core_.Window_HasFocus(*args, **kwargs) | [
"def",
"HasFocus",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Window_HasFocus",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L10150-L10156 | |
sdhash/sdhash | b9eff63e4e5867e910f41fd69032bbb1c94a2a5e | sdhash-server/gen-py/sdhashsrv/sdhashsrv.py | python | Iface.removeResult | (self, resultID) | Parameters:
- resultID | Parameters:
- resultID | [
"Parameters",
":",
"-",
"resultID"
] | def removeResult(self, resultID):
"""
Parameters:
- resultID
"""
pass | [
"def",
"removeResult",
"(",
"self",
",",
"resultID",
")",
":",
"pass"
] | https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-server/gen-py/sdhashsrv/sdhashsrv.py#L151-L156 | ||
VAR-solutions/Algorithms | 4ad6773e9675ef35aa858ca3969be5ddf6e3daea | LinkedList/LinkedListModule.py | python | LinkedList.addNodeAtEnd | (self,value) | return True | Adds a node containing given value to the end of the list | Adds a node containing given value to the end of the list | [
"Adds",
"a",
"node",
"containing",
"given",
"value",
"to",
"the",
"end",
"of",
"the",
"list"
] | def addNodeAtEnd(self,value):
"""Adds a node containing given value to the end of the list"""
if self.head is None:
self.head = Node(value)
else:
# iterate to the end of the list and add the node
CurrentNode = self.head
while CurrentNode.next is not None:
CurrentNode = CurrentNode.next
CurrentNode.next = Node(value)
return True | [
"def",
"addNodeAtEnd",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"head",
"is",
"None",
":",
"self",
".",
"head",
"=",
"Node",
"(",
"value",
")",
"else",
":",
"# iterate to the end of the list and add the node",
"CurrentNode",
"=",
"self",
".",
... | https://github.com/VAR-solutions/Algorithms/blob/4ad6773e9675ef35aa858ca3969be5ddf6e3daea/LinkedList/LinkedListModule.py#L15-L28 | |
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBProcess.ReadPointerFromMemory | (self, addr, error) | return _lldb.SBProcess_ReadPointerFromMemory(self, addr, error) | Reads a pointer from memory from an address and returns the value. Example:
# Read a pointer from address 0x1000
error = lldb.SBError()
ptr = ReadPointerFromMemory(0x1000, error)
if error.Success():
print('pointer: 0x%x' % ptr)
else
print('error: ', error) | [] | def ReadPointerFromMemory(self, addr, error):
"""
Reads a pointer from memory from an address and returns the value. Example:
# Read a pointer from address 0x1000
error = lldb.SBError()
ptr = ReadPointerFromMemory(0x1000, error)
if error.Success():
print('pointer: 0x%x' % ptr)
else
print('error: ', error)
"""
return _lldb.SBProcess_ReadPointerFromMemory(self, addr, error) | [
"def",
"ReadPointerFromMemory",
"(",
"self",
",",
"addr",
",",
"error",
")",
":",
"return",
"_lldb",
".",
"SBProcess_ReadPointerFromMemory",
"(",
"self",
",",
"addr",
",",
"error",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L8631-L8644 | ||
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/peacock/ExodusViewer/plugins/BackgroundPlugin.py | python | BackgroundPlugin.onSetEnableWidget | (self, value) | Enable/disable the menu items. | Enable/disable the menu items. | [
"Enable",
"/",
"disable",
"the",
"menu",
"items",
"."
] | def onSetEnableWidget(self, value):
"""
Enable/disable the menu items.
"""
super(BackgroundPlugin, self).onSetEnableWidget(value)
self.GradientToggle.setEnabled(value)
self.BlackPreset.setEnabled(value)
self.WhitePreset.setEnabled(value)
self.ColorbarBlackFontToggle.setEnabled(value)
self.TopGradientColor.setEnabled(value)
self.BottomGradientColor.setEnabled(value)
self.SolidColor.setEnabled(value) | [
"def",
"onSetEnableWidget",
"(",
"self",
",",
"value",
")",
":",
"super",
"(",
"BackgroundPlugin",
",",
"self",
")",
".",
"onSetEnableWidget",
"(",
"value",
")",
"self",
".",
"GradientToggle",
".",
"setEnabled",
"(",
"value",
")",
"self",
".",
"BlackPreset",... | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/peacock/ExodusViewer/plugins/BackgroundPlugin.py#L161-L172 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/ipython/py2/IPython/core/completerlib.py | python | magic_run_completer | (self, event) | return [compress_user(p, tilde_expand, tilde_val) for p in matches] | Complete files that end in .py or .ipy or .ipynb for the %run command. | Complete files that end in .py or .ipy or .ipynb for the %run command. | [
"Complete",
"files",
"that",
"end",
"in",
".",
"py",
"or",
".",
"ipy",
"or",
".",
"ipynb",
"for",
"the",
"%run",
"command",
"."
] | def magic_run_completer(self, event):
"""Complete files that end in .py or .ipy or .ipynb for the %run command.
"""
comps = arg_split(event.line, strict=False)
# relpath should be the current token that we need to complete.
if (len(comps) > 1) and (not event.line.endswith(' ')):
relpath = comps[-1].strip("'\"")
else:
relpath = ''
#print("\nev=", event) # dbg
#print("rp=", relpath) # dbg
#print('comps=', comps) # dbg
lglob = glob.glob
isdir = os.path.isdir
relpath, tilde_expand, tilde_val = expand_user(relpath)
# Find if the user has already typed the first filename, after which we
# should complete on all files, since after the first one other files may
# be arguments to the input script.
if any(magic_run_re.match(c) for c in comps):
matches = [f.replace('\\','/') + ('/' if isdir(f) else '')
for f in lglob(relpath+'*')]
else:
dirs = [f.replace('\\','/') + "/" for f in lglob(relpath+'*') if isdir(f)]
pys = [f.replace('\\','/')
for f in lglob(relpath+'*.py') + lglob(relpath+'*.ipy') +
lglob(relpath+'*.ipynb') + lglob(relpath + '*.pyw')]
matches = dirs + pys
#print('run comp:', dirs+pys) # dbg
return [compress_user(p, tilde_expand, tilde_val) for p in matches] | [
"def",
"magic_run_completer",
"(",
"self",
",",
"event",
")",
":",
"comps",
"=",
"arg_split",
"(",
"event",
".",
"line",
",",
"strict",
"=",
"False",
")",
"# relpath should be the current token that we need to complete.",
"if",
"(",
"len",
"(",
"comps",
")",
">"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py2/IPython/core/completerlib.py#L313-L347 | |
BitMEX/api-connectors | 37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812 | auto-generated/python/swagger_client/models/trade.py | python | Trade.gross_value | (self, gross_value) | Sets the gross_value of this Trade.
:param gross_value: The gross_value of this Trade. # noqa: E501
:type: float | Sets the gross_value of this Trade. | [
"Sets",
"the",
"gross_value",
"of",
"this",
"Trade",
"."
] | def gross_value(self, gross_value):
"""Sets the gross_value of this Trade.
:param gross_value: The gross_value of this Trade. # noqa: E501
:type: float
"""
self._gross_value = gross_value | [
"def",
"gross_value",
"(",
"self",
",",
"gross_value",
")",
":",
"self",
".",
"_gross_value",
"=",
"gross_value"
] | https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/trade.py#L255-L263 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/ipython/py3/IPython/core/prefilter.py | python | AutocallChecker.check | (self, line_info) | Check if the initial word/function is callable and autocall is on. | Check if the initial word/function is callable and autocall is on. | [
"Check",
"if",
"the",
"initial",
"word",
"/",
"function",
"is",
"callable",
"and",
"autocall",
"is",
"on",
"."
] | def check(self, line_info):
"Check if the initial word/function is callable and autocall is on."
if not self.shell.autocall:
return None
oinfo = line_info.ofind(self.shell) # This can mutate state via getattr
if not oinfo['found']:
return None
ignored_funs = ['b', 'f', 'r', 'u', 'br', 'rb', 'fr', 'rf']
ifun = line_info.ifun
line = line_info.line
if ifun.lower() in ignored_funs and (line.startswith(ifun + "'") or line.startswith(ifun + '"')):
return None
if callable(oinfo['obj']) \
and (not self.exclude_regexp.match(line_info.the_rest)) \
and self.function_name_regexp.match(line_info.ifun):
return self.prefilter_manager.get_handler_by_name('auto')
else:
return None | [
"def",
"check",
"(",
"self",
",",
"line_info",
")",
":",
"if",
"not",
"self",
".",
"shell",
".",
"autocall",
":",
"return",
"None",
"oinfo",
"=",
"line_info",
".",
"ofind",
"(",
"self",
".",
"shell",
")",
"# This can mutate state via getattr",
"if",
"not",... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/core/prefilter.py#L504-L524 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/importlib/_bootstrap.py | python | _sanity_check | (name, package, level) | Verify arguments are "sane". | Verify arguments are "sane". | [
"Verify",
"arguments",
"are",
"sane",
"."
] | def _sanity_check(name, package, level):
"""Verify arguments are "sane"."""
if not isinstance(name, str):
raise TypeError('module name must be str, not {}'.format(type(name)))
if level < 0:
raise ValueError('level must be >= 0')
if level > 0:
if not isinstance(package, str):
raise TypeError('__package__ not set to a string')
elif not package:
raise ImportError('attempted relative import with no known parent '
'package')
if not name and level == 0:
raise ValueError('Empty module name') | [
"def",
"_sanity_check",
"(",
"name",
",",
"package",
",",
"level",
")",
":",
"if",
"not",
"isinstance",
"(",
"name",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"'module name must be str, not {}'",
".",
"format",
"(",
"type",
"(",
"name",
")",
")",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/importlib/_bootstrap.py#L948-L961 | ||
apiaryio/snowcrash | b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3 | tools/gyp/pylib/gyp/generator/msvs.py | python | _ConvertToolsToExpectedForm | (tools) | return tool_list | Convert tools to a form expected by Visual Studio.
Arguments:
tools: A dictionary of settings; the tool name is the key.
Returns:
A list of Tool objects. | Convert tools to a form expected by Visual Studio. | [
"Convert",
"tools",
"to",
"a",
"form",
"expected",
"by",
"Visual",
"Studio",
"."
] | def _ConvertToolsToExpectedForm(tools):
"""Convert tools to a form expected by Visual Studio.
Arguments:
tools: A dictionary of settings; the tool name is the key.
Returns:
A list of Tool objects.
"""
tool_list = []
for tool, settings in tools.iteritems():
# Collapse settings with lists.
settings_fixed = {}
for setting, value in settings.iteritems():
if type(value) == list:
if ((tool == 'VCLinkerTool' and
setting == 'AdditionalDependencies') or
setting == 'AdditionalOptions'):
settings_fixed[setting] = ' '.join(value)
else:
settings_fixed[setting] = ';'.join(value)
else:
settings_fixed[setting] = value
# Add in this tool.
tool_list.append(MSVSProject.Tool(tool, settings_fixed))
return tool_list | [
"def",
"_ConvertToolsToExpectedForm",
"(",
"tools",
")",
":",
"tool_list",
"=",
"[",
"]",
"for",
"tool",
",",
"settings",
"in",
"tools",
".",
"iteritems",
"(",
")",
":",
"# Collapse settings with lists.",
"settings_fixed",
"=",
"{",
"}",
"for",
"setting",
",",... | https://github.com/apiaryio/snowcrash/blob/b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3/tools/gyp/pylib/gyp/generator/msvs.py#L1346-L1370 | |
trailofbits/llvm-sanitizer-tutorial | d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99 | llvm/tools/clang/tools/scan-build-py/libscanbuild/report.py | python | parse_bug_html | (filename) | Parse out the bug information from HTML output. | Parse out the bug information from HTML output. | [
"Parse",
"out",
"the",
"bug",
"information",
"from",
"HTML",
"output",
"."
] | def parse_bug_html(filename):
""" Parse out the bug information from HTML output. """
patterns = [re.compile(r'<!-- BUGTYPE (?P<bug_type>.*) -->$'),
re.compile(r'<!-- BUGFILE (?P<bug_file>.*) -->$'),
re.compile(r'<!-- BUGPATHLENGTH (?P<bug_path_length>.*) -->$'),
re.compile(r'<!-- BUGLINE (?P<bug_line>.*) -->$'),
re.compile(r'<!-- BUGCATEGORY (?P<bug_category>.*) -->$'),
re.compile(r'<!-- BUGDESC (?P<bug_description>.*) -->$'),
re.compile(r'<!-- FUNCTIONNAME (?P<bug_function>.*) -->$')]
endsign = re.compile(r'<!-- BUGMETAEND -->')
bug = {
'report_file': filename,
'bug_function': 'n/a', # compatibility with < clang-3.5
'bug_category': 'Other',
'bug_line': 0,
'bug_path_length': 1
}
with open(filename) as handler:
for line in handler.readlines():
# do not read the file further
if endsign.match(line):
break
# search for the right lines
for regex in patterns:
match = regex.match(line.strip())
if match:
bug.update(match.groupdict())
break
encode_value(bug, 'bug_line', int)
encode_value(bug, 'bug_path_length', int)
yield bug | [
"def",
"parse_bug_html",
"(",
"filename",
")",
":",
"patterns",
"=",
"[",
"re",
".",
"compile",
"(",
"r'<!-- BUGTYPE (?P<bug_type>.*) -->$'",
")",
",",
"re",
".",
"compile",
"(",
"r'<!-- BUGFILE (?P<bug_file>.*) -->$'",
")",
",",
"re",
".",
"compile",
"(",
"r'<!... | https://github.com/trailofbits/llvm-sanitizer-tutorial/blob/d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99/llvm/tools/clang/tools/scan-build-py/libscanbuild/report.py#L302-L337 | ||
google/llvm-propeller | 45c226984fe8377ebfb2ad7713c680d652ba678d | compiler-rt/lib/sanitizer_common/scripts/cpplint.py | python | FileInfo.RepositoryName | (self) | return fullname | FullName after removing the local path to the repository.
If we have a real absolute path name here we can try to do something smart:
detecting the root of the checkout and truncating /path/to/checkout from
the name so that we get header guards that don't include things like
"C:\Documents and Settings\..." or "/home/username/..." in them and thus
people on different computers who have checked the source out to different
locations won't see bogus errors. | FullName after removing the local path to the repository. | [
"FullName",
"after",
"removing",
"the",
"local",
"path",
"to",
"the",
"repository",
"."
] | def RepositoryName(self):
"""FullName after removing the local path to the repository.
If we have a real absolute path name here we can try to do something smart:
detecting the root of the checkout and truncating /path/to/checkout from
the name so that we get header guards that don't include things like
"C:\Documents and Settings\..." or "/home/username/..." in them and thus
people on different computers who have checked the source out to different
locations won't see bogus errors.
"""
fullname = self.FullName()
if os.path.exists(fullname):
project_dir = os.path.dirname(fullname)
if os.path.exists(os.path.join(project_dir, ".svn")):
# If there's a .svn file in the current directory, we recursively look
# up the directory tree for the top of the SVN checkout
root_dir = project_dir
one_up_dir = os.path.dirname(root_dir)
while os.path.exists(os.path.join(one_up_dir, ".svn")):
root_dir = os.path.dirname(root_dir)
one_up_dir = os.path.dirname(one_up_dir)
prefix = os.path.commonprefix([root_dir, project_dir])
return fullname[len(prefix) + 1:]
# Not SVN <= 1.6? Try to find a git, hg, or svn top level directory by
# searching up from the current path.
root_dir = current_dir = os.path.dirname(fullname)
while current_dir != os.path.dirname(current_dir):
if (os.path.exists(os.path.join(current_dir, ".git")) or
os.path.exists(os.path.join(current_dir, ".hg")) or
os.path.exists(os.path.join(current_dir, ".svn"))):
root_dir = current_dir
current_dir = os.path.dirname(current_dir)
if (os.path.exists(os.path.join(root_dir, ".git")) or
os.path.exists(os.path.join(root_dir, ".hg")) or
os.path.exists(os.path.join(root_dir, ".svn"))):
prefix = os.path.commonprefix([root_dir, project_dir])
return fullname[len(prefix) + 1:]
# Don't know what to do; header guard warnings may be wrong...
return fullname | [
"def",
"RepositoryName",
"(",
"self",
")",
":",
"fullname",
"=",
"self",
".",
"FullName",
"(",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"fullname",
")",
":",
"project_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"fullname",
")",
"if",
... | https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L1111-L1155 | |
panda3d/panda3d | 833ad89ebad58395d0af0b7ec08538e5e4308265 | direct/src/showbase/Transitions.py | python | Transitions.getFadeOutIval | (self, t=0.5, finishIval=None, blendType='noBlend') | return transitionIval | Create a sequence that lerps the color out, then
parents the fade to hidden | Create a sequence that lerps the color out, then
parents the fade to hidden | [
"Create",
"a",
"sequence",
"that",
"lerps",
"the",
"color",
"out",
"then",
"parents",
"the",
"fade",
"to",
"hidden"
] | def getFadeOutIval(self, t=0.5, finishIval=None, blendType='noBlend'):
"""
Create a sequence that lerps the color out, then
parents the fade to hidden
"""
self.noTransitions()
self.loadFade()
transitionIval = Sequence(Func(self.fade.reparentTo, ShowBaseGlobal.aspect2d, DGG.FADE_SORT_INDEX),
Func(self.fade.showThrough), # in case aspect2d is hidden for some reason
self.lerpFunc(self.fade, t,
self.alphaOn,
# self.alphaOff,
blendType=blendType
),
name = self.fadeTaskName,
)
if finishIval:
transitionIval.append(finishIval)
return transitionIval | [
"def",
"getFadeOutIval",
"(",
"self",
",",
"t",
"=",
"0.5",
",",
"finishIval",
"=",
"None",
",",
"blendType",
"=",
"'noBlend'",
")",
":",
"self",
".",
"noTransitions",
"(",
")",
"self",
".",
"loadFade",
"(",
")",
"transitionIval",
"=",
"Sequence",
"(",
... | https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/showbase/Transitions.py#L118-L137 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/client/session.py | python | SessionInterface.run | (self, fetches, feed_dict=None, options=None, run_metadata=None) | Runs operations in the session. See `Session.run()` for details. | Runs operations in the session. See `Session.run()` for details. | [
"Runs",
"operations",
"in",
"the",
"session",
".",
"See",
"Session",
".",
"run",
"()",
"for",
"details",
"."
] | def run(self, fetches, feed_dict=None, options=None, run_metadata=None):
"""Runs operations in the session. See `Session.run()` for details."""
raise NotImplementedError('run') | [
"def",
"run",
"(",
"self",
",",
"fetches",
",",
"feed_dict",
"=",
"None",
",",
"options",
"=",
"None",
",",
"run_metadata",
"=",
"None",
")",
":",
"raise",
"NotImplementedError",
"(",
"'run'",
")"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/client/session.py#L50-L52 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/plot.py | python | PlotCanvas._getFont | (self, size) | Take font size, adjusts if printing and returns wx.Font | Take font size, adjusts if printing and returns wx.Font | [
"Take",
"font",
"size",
"adjusts",
"if",
"printing",
"and",
"returns",
"wx",
".",
"Font"
] | def _getFont(self, size):
"""Take font size, adjusts if printing and returns wx.Font"""
s = size * self.printerScale * self._fontScale
of = self.GetFont()
# Linux speed up to get font from cache rather than X font server
key = (int(s), of.GetFamily(), of.GetStyle(), of.GetWeight())
font = self._fontCache.get(key, None)
if font:
return font # yeah! cache hit
else:
font = wx.Font(
int(s), of.GetFamily(), of.GetStyle(), of.GetWeight())
self._fontCache[key] = font
return font | [
"def",
"_getFont",
"(",
"self",
",",
"size",
")",
":",
"s",
"=",
"size",
"*",
"self",
".",
"printerScale",
"*",
"self",
".",
"_fontScale",
"of",
"=",
"self",
".",
"GetFont",
"(",
")",
"# Linux speed up to get font from cache rather than X font server",
"key",
... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/plot.py#L1680-L1693 | ||
domino-team/openwrt-cc | 8b181297c34d14d3ca521cc9f31430d561dbc688 | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/generator/ninja.py | python | NinjaWriter.ComputeExportEnvString | (self, env) | return ' '.join(export_str) | Given an environment, returns a string looking like
'export FOO=foo; export BAR="${FOO} bar;'
that exports |env| to the shell. | Given an environment, returns a string looking like
'export FOO=foo; export BAR="${FOO} bar;'
that exports |env| to the shell. | [
"Given",
"an",
"environment",
"returns",
"a",
"string",
"looking",
"like",
"export",
"FOO",
"=",
"foo",
";",
"export",
"BAR",
"=",
"$",
"{",
"FOO",
"}",
"bar",
";",
"that",
"exports",
"|env|",
"to",
"the",
"shell",
"."
] | def ComputeExportEnvString(self, env):
"""Given an environment, returns a string looking like
'export FOO=foo; export BAR="${FOO} bar;'
that exports |env| to the shell."""
export_str = []
for k, v in env:
export_str.append('export %s=%s;' %
(k, ninja_syntax.escape(gyp.common.EncodePOSIXShellArgument(v))))
return ' '.join(export_str) | [
"def",
"ComputeExportEnvString",
"(",
"self",
",",
"env",
")",
":",
"export_str",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"env",
":",
"export_str",
".",
"append",
"(",
"'export %s=%s;'",
"%",
"(",
"k",
",",
"ninja_syntax",
".",
"escape",
"(",
"gyp",... | https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/generator/ninja.py#L1401-L1409 | |
GNOME/gjs | ccbfa21e2be3ebe700050f85e93bfcbc18cc676d | tools/heapgraph.py | python | parse_roots | (fobj) | return [roots, root_labels, weakMapEntries] | Parse the roots portion of a garbage collector heap. | Parse the roots portion of a garbage collector heap. | [
"Parse",
"the",
"roots",
"portion",
"of",
"a",
"garbage",
"collector",
"heap",
"."
] | def parse_roots(fobj):
"""Parse the roots portion of a garbage collector heap."""
roots = {}
root_labels = {}
weakMapEntries = []
for line in fobj:
node = node_regex.match(line)
if node:
addr = node.group(1)
color = node.group(2)
label = node.group(3)
# Only overwrite an existing root with a black root.
if addr not in roots or color == 'B':
roots[addr] = (color == 'B')
# It would be classier to save all the root labels, though then
# we have to worry about gray vs black.
root_labels[addr] = label
else:
wme = wme_regex.match(line)
if wme:
weakMapEntries.append(WeakMapEntry(weakMap=wme.group(1),
key=wme.group(2),
keyDelegate=wme.group(3),
value=wme.group(4)))
# Skip comments, arenas, realms and zones
elif line[0] == '#':
continue
# Marks the end of the roots section
elif line[:10] == '==========':
break
else:
sys.stderr.write('Error: unknown line {}\n'.format(line))
exit(-1)
return [roots, root_labels, weakMapEntries] | [
"def",
"parse_roots",
"(",
"fobj",
")",
":",
"roots",
"=",
"{",
"}",
"root_labels",
"=",
"{",
"}",
"weakMapEntries",
"=",
"[",
"]",
"for",
"line",
"in",
"fobj",
":",
"node",
"=",
"node_regex",
".",
"match",
"(",
"line",
")",
"if",
"node",
":",
"add... | https://github.com/GNOME/gjs/blob/ccbfa21e2be3ebe700050f85e93bfcbc18cc676d/tools/heapgraph.py#L132-L171 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/utils/virtualenv.py | python | _get_pyvenv_cfg_lines | () | Reads {sys.prefix}/pyvenv.cfg and returns its contents as list of lines
Returns None, if it could not read/access the file. | Reads {sys.prefix}/pyvenv.cfg and returns its contents as list of lines | [
"Reads",
"{",
"sys",
".",
"prefix",
"}",
"/",
"pyvenv",
".",
"cfg",
"and",
"returns",
"its",
"contents",
"as",
"list",
"of",
"lines"
] | def _get_pyvenv_cfg_lines():
# type: () -> Optional[List[str]]
"""Reads {sys.prefix}/pyvenv.cfg and returns its contents as list of lines
Returns None, if it could not read/access the file.
"""
pyvenv_cfg_file = os.path.join(sys.prefix, 'pyvenv.cfg')
try:
# Although PEP 405 does not specify, the built-in venv module always
# writes with UTF-8. (pypa/pip#8717)
with open(pyvenv_cfg_file, encoding='utf-8') as f:
return f.read().splitlines() # avoids trailing newlines
except OSError:
return None | [
"def",
"_get_pyvenv_cfg_lines",
"(",
")",
":",
"# type: () -> Optional[List[str]]",
"pyvenv_cfg_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"sys",
".",
"prefix",
",",
"'pyvenv.cfg'",
")",
"try",
":",
"# Although PEP 405 does not specify, the built-in venv module alwa... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/utils/virtualenv.py#L44-L57 | ||
kevin-ssy/Optical-Flow-Guided-Feature | 07d4501a29002ee7821c38c1820e4a64c1acf6e8 | lib/caffe-action/scripts/cpp_lint.py | python | CheckCaffeDataLayerSetUp | (filename, clean_lines, linenum, error) | Except the base classes, Caffe DataLayer should define DataLayerSetUp
instead of LayerSetUp.
The base DataLayers define common SetUp steps, the subclasses should
not override them.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Except the base classes, Caffe DataLayer should define DataLayerSetUp
instead of LayerSetUp.
The base DataLayers define common SetUp steps, the subclasses should
not override them.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | [
"Except",
"the",
"base",
"classes",
"Caffe",
"DataLayer",
"should",
"define",
"DataLayerSetUp",
"instead",
"of",
"LayerSetUp",
".",
"The",
"base",
"DataLayers",
"define",
"common",
"SetUp",
"steps",
"the",
"subclasses",
"should",
"not",
"override",
"them",
".",
... | def CheckCaffeDataLayerSetUp(filename, clean_lines, linenum, error):
"""Except the base classes, Caffe DataLayer should define DataLayerSetUp
instead of LayerSetUp.
The base DataLayers define common SetUp steps, the subclasses should
not override them.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
ix = line.find('DataLayer<Dtype>::LayerSetUp')
if ix >= 0 and (
line.find('void DataLayer<Dtype>::LayerSetUp') != -1 or
line.find('void ImageDataLayer<Dtype>::LayerSetUp') != -1 or
line.find('void MemoryDataLayer<Dtype>::LayerSetUp') != -1 or
line.find('void WindowDataLayer<Dtype>::LayerSetUp') != -1):
error(filename, linenum, 'caffe/data_layer_setup', 2,
'Except the base classes, Caffe DataLayer should define'
+ ' DataLayerSetUp instead of LayerSetUp. The base DataLayers'
+ ' define common SetUp steps, the subclasses should'
+ ' not override them.')
ix = line.find('DataLayer<Dtype>::DataLayerSetUp')
if ix >= 0 and (
line.find('void Base') == -1 and
line.find('void DataLayer<Dtype>::DataLayerSetUp') == -1 and
line.find('void ImageDataLayer<Dtype>::DataLayerSetUp') == -1 and
line.find('void MemoryDataLayer<Dtype>::DataLayerSetUp') == -1 and
line.find('void WindowDataLayer<Dtype>::DataLayerSetUp') == -1):
error(filename, linenum, 'caffe/data_layer_setup', 2,
'Except the base classes, Caffe DataLayer should define'
+ ' DataLayerSetUp instead of LayerSetUp. The base DataLayers'
+ ' define common SetUp steps, the subclasses should'
+ ' not override them.') | [
"def",
"CheckCaffeDataLayerSetUp",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"ix",
"=",
"line",
".",
"find",
"(",
"'DataLayer<Dtype>::LayerSetUp'",
")",
"if",
... | https://github.com/kevin-ssy/Optical-Flow-Guided-Feature/blob/07d4501a29002ee7821c38c1820e4a64c1acf6e8/lib/caffe-action/scripts/cpp_lint.py#L1595-L1631 | ||
koth/kcws | 88efbd36a7022de4e6e90f5a1fb880cf87cfae9f | third_party/setuptools/pkg_resources.py | python | file_ns_handler | (importer, path_item, packageName, module) | Compute an ns-package subpath for a filesystem or zipfile importer | Compute an ns-package subpath for a filesystem or zipfile importer | [
"Compute",
"an",
"ns",
"-",
"package",
"subpath",
"for",
"a",
"filesystem",
"or",
"zipfile",
"importer"
] | def file_ns_handler(importer, path_item, packageName, module):
"""Compute an ns-package subpath for a filesystem or zipfile importer"""
subpath = os.path.join(path_item, packageName.split('.')[-1])
normalized = _normalize_cached(subpath)
for item in module.__path__:
if _normalize_cached(item)==normalized:
break
else:
# Only return the path if it's not already there
return subpath | [
"def",
"file_ns_handler",
"(",
"importer",
",",
"path_item",
",",
"packageName",
",",
"module",
")",
":",
"subpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path_item",
",",
"packageName",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
")",
"n... | https://github.com/koth/kcws/blob/88efbd36a7022de4e6e90f5a1fb880cf87cfae9f/third_party/setuptools/pkg_resources.py#L1993-L2003 | ||
MythTV/mythtv | d282a209cb8be85d036f85a62a8ec971b67d45f4 | mythtv/bindings/python/MythTV/dataheap.py | python | Recorded.getRecordedFile | (self) | return RecordedFile.fromRecorded(self) | Recorded.getRecordedFile() -> RecordedFile object | Recorded.getRecordedFile() -> RecordedFile object | [
"Recorded",
".",
"getRecordedFile",
"()",
"-",
">",
"RecordedFile",
"object"
] | def getRecordedFile(self):
"""Recorded.getRecordedFile() -> RecordedFile object"""
return RecordedFile.fromRecorded(self) | [
"def",
"getRecordedFile",
"(",
"self",
")",
":",
"return",
"RecordedFile",
".",
"fromRecorded",
"(",
"self",
")"
] | https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/bindings/python/MythTV/dataheap.py#L378-L380 | |
yuxng/PoseCNN | 9f3dd7b7bce21dcafc05e8f18ccc90da3caabd04 | lib/gt_synthesize_layer/layer.py | python | GtSynthesizeLayer.__init__ | (self, roidb, num_classes, extents, points, symmetry, cache_path, name, data_queue, model_file, pose_file) | Set the roidb to be used by this layer during training. | Set the roidb to be used by this layer during training. | [
"Set",
"the",
"roidb",
"to",
"be",
"used",
"by",
"this",
"layer",
"during",
"training",
"."
] | def __init__(self, roidb, num_classes, extents, points, symmetry, cache_path, name, data_queue, model_file, pose_file):
"""Set the roidb to be used by this layer during training."""
self._roidb = roidb
self._num_classes = num_classes
self._extents = extents
self._points = points
self._symmetry = symmetry
self._cache_path = cache_path
self._name = name
self._data_queue = data_queue
self._shuffle_roidb_inds()
self._shuffle_syn_inds()
self._shuffle_adapt_inds()
self._build_background_images()
self._build_background_depth_images()
self._read_camera_parameters() | [
"def",
"__init__",
"(",
"self",
",",
"roidb",
",",
"num_classes",
",",
"extents",
",",
"points",
",",
"symmetry",
",",
"cache_path",
",",
"name",
",",
"data_queue",
",",
"model_file",
",",
"pose_file",
")",
":",
"self",
".",
"_roidb",
"=",
"roidb",
"self... | https://github.com/yuxng/PoseCNN/blob/9f3dd7b7bce21dcafc05e8f18ccc90da3caabd04/lib/gt_synthesize_layer/layer.py#L23-L38 | ||
bulletphysics/bullet3 | f0f2a952e146f016096db6f85cf0c44ed75b0b9a | examples/pybullet/gym/pybullet_envs/agents/ppo/utility.py | python | available_gpus | () | return [x.name for x in local_device_protos if x.device_type == 'GPU'] | List of GPU device names detected by TensorFlow. | List of GPU device names detected by TensorFlow. | [
"List",
"of",
"GPU",
"device",
"names",
"detected",
"by",
"TensorFlow",
"."
] | def available_gpus():
"""List of GPU device names detected by TensorFlow."""
local_device_protos = device_lib.list_local_devices()
return [x.name for x in local_device_protos if x.device_type == 'GPU'] | [
"def",
"available_gpus",
"(",
")",
":",
"local_device_protos",
"=",
"device_lib",
".",
"list_local_devices",
"(",
")",
"return",
"[",
"x",
".",
"name",
"for",
"x",
"in",
"local_device_protos",
"if",
"x",
".",
"device_type",
"==",
"'GPU'",
"]"
] | https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/agents/ppo/utility.py#L145-L148 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/covariance/_robust_covariance.py | python | select_candidates | (X, n_support, n_trials, select=1, n_iter=30,
verbose=False,
cov_computation_method=empirical_covariance,
random_state=None) | return best_locations, best_covariances, best_supports, best_ds | Finds the best pure subset of observations to compute MCD from it.
The purpose of this function is to find the best sets of n_support
observations with respect to a minimization of their covariance
matrix determinant. Equivalently, it removes n_samples-n_support
observations to construct what we call a pure data set (i.e. not
containing outliers). The list of the observations of the pure
data set is referred to as the `support`.
Starting from a random support, the pure data set is found by the
c_step procedure introduced by Rousseeuw and Van Driessen in
[RV]_.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Data (sub)set in which we look for the n_support purest observations.
n_support : int, [(n + p + 1)/2] < n_support < n
The number of samples the pure data set must contain.
n_trials : int, nb_trials > 0 or 2-tuple
Number of different initial sets of observations from which to
run the algorithm.
Instead of giving a number of trials to perform, one can provide a
list of initial estimates that will be used to iteratively run
c_step procedures. In this case:
- n_trials[0]: array-like, shape (n_trials, n_features)
is the list of `n_trials` initial location estimates
- n_trials[1]: array-like, shape (n_trials, n_features, n_features)
is the list of `n_trials` initial covariances estimates
select : int, int > 0
Number of best candidates results to return.
n_iter : int, nb_iter > 0
Maximum number of iterations for the c_step procedure.
(2 is enough to be close to the final solution. "Never" exceeds 20).
verbose : boolean, default False
Control the output verbosity.
cov_computation_method : callable, default empirical_covariance
The function which will be used to compute the covariance.
Must return shape (n_features, n_features)
random_state : int, RandomState instance or None, optional (default=None)
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
See Also
---------
c_step
Returns
-------
best_locations : array-like, shape (select, n_features)
The `select` location estimates computed from the `select` best
supports found in the data set (`X`).
best_covariances : array-like, shape (select, n_features, n_features)
The `select` covariance estimates computed from the `select`
best supports found in the data set (`X`).
best_supports : array-like, shape (select, n_samples)
The `select` best supports found in the data set (`X`).
References
----------
.. [RV] A Fast Algorithm for the Minimum Covariance Determinant
Estimator, 1999, American Statistical Association and the American
Society for Quality, TECHNOMETRICS | Finds the best pure subset of observations to compute MCD from it. | [
"Finds",
"the",
"best",
"pure",
"subset",
"of",
"observations",
"to",
"compute",
"MCD",
"from",
"it",
"."
] | def select_candidates(X, n_support, n_trials, select=1, n_iter=30,
verbose=False,
cov_computation_method=empirical_covariance,
random_state=None):
"""Finds the best pure subset of observations to compute MCD from it.
The purpose of this function is to find the best sets of n_support
observations with respect to a minimization of their covariance
matrix determinant. Equivalently, it removes n_samples-n_support
observations to construct what we call a pure data set (i.e. not
containing outliers). The list of the observations of the pure
data set is referred to as the `support`.
Starting from a random support, the pure data set is found by the
c_step procedure introduced by Rousseeuw and Van Driessen in
[RV]_.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Data (sub)set in which we look for the n_support purest observations.
n_support : int, [(n + p + 1)/2] < n_support < n
The number of samples the pure data set must contain.
n_trials : int, nb_trials > 0 or 2-tuple
Number of different initial sets of observations from which to
run the algorithm.
Instead of giving a number of trials to perform, one can provide a
list of initial estimates that will be used to iteratively run
c_step procedures. In this case:
- n_trials[0]: array-like, shape (n_trials, n_features)
is the list of `n_trials` initial location estimates
- n_trials[1]: array-like, shape (n_trials, n_features, n_features)
is the list of `n_trials` initial covariances estimates
select : int, int > 0
Number of best candidates results to return.
n_iter : int, nb_iter > 0
Maximum number of iterations for the c_step procedure.
(2 is enough to be close to the final solution. "Never" exceeds 20).
verbose : boolean, default False
Control the output verbosity.
cov_computation_method : callable, default empirical_covariance
The function which will be used to compute the covariance.
Must return shape (n_features, n_features)
random_state : int, RandomState instance or None, optional (default=None)
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
See Also
---------
c_step
Returns
-------
best_locations : array-like, shape (select, n_features)
The `select` location estimates computed from the `select` best
supports found in the data set (`X`).
best_covariances : array-like, shape (select, n_features, n_features)
The `select` covariance estimates computed from the `select`
best supports found in the data set (`X`).
best_supports : array-like, shape (select, n_samples)
The `select` best supports found in the data set (`X`).
References
----------
.. [RV] A Fast Algorithm for the Minimum Covariance Determinant
Estimator, 1999, American Statistical Association and the American
Society for Quality, TECHNOMETRICS
"""
random_state = check_random_state(random_state)
if isinstance(n_trials, numbers.Integral):
run_from_estimates = False
elif isinstance(n_trials, tuple):
run_from_estimates = True
estimates_list = n_trials
n_trials = estimates_list[0].shape[0]
else:
raise TypeError("Invalid 'n_trials' parameter, expected tuple or "
" integer, got %s (%s)" % (n_trials, type(n_trials)))
# compute `n_trials` location and shape estimates candidates in the subset
all_estimates = []
if not run_from_estimates:
# perform `n_trials` computations from random initial supports
for j in range(n_trials):
all_estimates.append(
_c_step(
X, n_support, remaining_iterations=n_iter, verbose=verbose,
cov_computation_method=cov_computation_method,
random_state=random_state))
else:
# perform computations from every given initial estimates
for j in range(n_trials):
initial_estimates = (estimates_list[0][j], estimates_list[1][j])
all_estimates.append(_c_step(
X, n_support, remaining_iterations=n_iter,
initial_estimates=initial_estimates, verbose=verbose,
cov_computation_method=cov_computation_method,
random_state=random_state))
all_locs_sub, all_covs_sub, all_dets_sub, all_supports_sub, all_ds_sub = \
zip(*all_estimates)
# find the `n_best` best results among the `n_trials` ones
index_best = np.argsort(all_dets_sub)[:select]
best_locations = np.asarray(all_locs_sub)[index_best]
best_covariances = np.asarray(all_covs_sub)[index_best]
best_supports = np.asarray(all_supports_sub)[index_best]
best_ds = np.asarray(all_ds_sub)[index_best]
return best_locations, best_covariances, best_supports, best_ds | [
"def",
"select_candidates",
"(",
"X",
",",
"n_support",
",",
"n_trials",
",",
"select",
"=",
"1",
",",
"n_iter",
"=",
"30",
",",
"verbose",
"=",
"False",
",",
"cov_computation_method",
"=",
"empirical_covariance",
",",
"random_state",
"=",
"None",
")",
":",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/covariance/_robust_covariance.py#L183-L303 | |
llvm/llvm-project | ffa6262cb4e2a335d26416fad39a581b4f98c5f4 | llvm/bindings/python/llvm/object.py | python | ObjectFile.__init__ | (self, filename=None, contents=None) | Construct an instance from a filename or binary data.
filename must be a path to a file that can be opened with open().
contents can be either a native Python buffer type (like str) or a
llvm.core.MemoryBuffer instance. | Construct an instance from a filename or binary data. | [
"Construct",
"an",
"instance",
"from",
"a",
"filename",
"or",
"binary",
"data",
"."
] | def __init__(self, filename=None, contents=None):
"""Construct an instance from a filename or binary data.
filename must be a path to a file that can be opened with open().
contents can be either a native Python buffer type (like str) or a
llvm.core.MemoryBuffer instance.
"""
if contents:
assert isinstance(contents, MemoryBuffer)
if filename is not None:
contents = MemoryBuffer(filename=filename)
if contents is None:
raise Exception('No input found.')
ptr = lib.LLVMCreateObjectFile(contents)
LLVMObject.__init__(self, ptr, disposer=lib.LLVMDisposeObjectFile)
self.take_ownership(contents) | [
"def",
"__init__",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"contents",
"=",
"None",
")",
":",
"if",
"contents",
":",
"assert",
"isinstance",
"(",
"contents",
",",
"MemoryBuffer",
")",
"if",
"filename",
"is",
"not",
"None",
":",
"contents",
"=",
... | https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/llvm/bindings/python/llvm/object.py#L102-L120 | ||
msracver/Deep-Image-Analogy | 632b9287b42552e32dad64922967c8c9ec7fc4d3 | scripts/cpp_lint.py | python | _CppLintState.SetVerboseLevel | (self, level) | return last_verbose_level | Sets the module's verbosity, and returns the previous setting. | Sets the module's verbosity, and returns the previous setting. | [
"Sets",
"the",
"module",
"s",
"verbosity",
"and",
"returns",
"the",
"previous",
"setting",
"."
] | def SetVerboseLevel(self, level):
"""Sets the module's verbosity, and returns the previous setting."""
last_verbose_level = self.verbose_level
self.verbose_level = level
return last_verbose_level | [
"def",
"SetVerboseLevel",
"(",
"self",
",",
"level",
")",
":",
"last_verbose_level",
"=",
"self",
".",
"verbose_level",
"self",
".",
"verbose_level",
"=",
"level",
"return",
"last_verbose_level"
] | https://github.com/msracver/Deep-Image-Analogy/blob/632b9287b42552e32dad64922967c8c9ec7fc4d3/scripts/cpp_lint.py#L707-L711 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/cgitb.py | python | enable | (display=1, logdir=None, context=5, format="html") | Install an exception handler that formats tracebacks as HTML.
The optional argument 'display' can be set to 0 to suppress sending the
traceback to the browser, and 'logdir' can be set to a directory to cause
tracebacks to be written to files there. | Install an exception handler that formats tracebacks as HTML. | [
"Install",
"an",
"exception",
"handler",
"that",
"formats",
"tracebacks",
"as",
"HTML",
"."
] | def enable(display=1, logdir=None, context=5, format="html"):
"""Install an exception handler that formats tracebacks as HTML.
The optional argument 'display' can be set to 0 to suppress sending the
traceback to the browser, and 'logdir' can be set to a directory to cause
tracebacks to be written to files there."""
sys.excepthook = Hook(display=display, logdir=logdir,
context=context, format=format) | [
"def",
"enable",
"(",
"display",
"=",
"1",
",",
"logdir",
"=",
"None",
",",
"context",
"=",
"5",
",",
"format",
"=",
"\"html\"",
")",
":",
"sys",
".",
"excepthook",
"=",
"Hook",
"(",
"display",
"=",
"display",
",",
"logdir",
"=",
"logdir",
",",
"co... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/cgitb.py#L316-L323 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/logging/__init__.py | python | LoggerAdapter.critical | (self, msg, *args, **kwargs) | Delegate a critical call to the underlying logger, after adding
contextual information from this adapter instance. | Delegate a critical call to the underlying logger, after adding
contextual information from this adapter instance. | [
"Delegate",
"a",
"critical",
"call",
"to",
"the",
"underlying",
"logger",
"after",
"adding",
"contextual",
"information",
"from",
"this",
"adapter",
"instance",
"."
] | def critical(self, msg, *args, **kwargs):
"""
Delegate a critical call to the underlying logger, after adding
contextual information from this adapter instance.
"""
msg, kwargs = self.process(msg, kwargs)
self.logger.critical(msg, *args, **kwargs) | [
"def",
"critical",
"(",
"self",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"msg",
",",
"kwargs",
"=",
"self",
".",
"process",
"(",
"msg",
",",
"kwargs",
")",
"self",
".",
"logger",
".",
"critical",
"(",
"msg",
",",
"*",
"a... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/logging/__init__.py#L1457-L1463 | ||
freesurfer/freesurfer | 6dbe527d43ffa611acb2cd112e9469f9bfec8e36 | sscnn_skullstripping/sscnn_skullstripping/image_utils/image_utils/patch_utils.py | python | build_image_from_patches | (in_patches, patch_size, idx_x, idx_y, idx_z, padded_img_size, patch_crop_size) | return out_img_data, count_img_data | patch_crop_size depends on the size of the cnn filter. If [3,3,3] then [1,1,1] | patch_crop_size depends on the size of the cnn filter. If [3,3,3] then [1,1,1] | [
"patch_crop_size",
"depends",
"on",
"the",
"size",
"of",
"the",
"cnn",
"filter",
".",
"If",
"[",
"3",
"3",
"3",
"]",
"then",
"[",
"1",
"1",
"1",
"]"
] | def build_image_from_patches(in_patches, patch_size, idx_x, idx_y, idx_z, padded_img_size, patch_crop_size):
''' patch_crop_size depends on the size of the cnn filter. If [3,3,3] then [1,1,1]'''
import numpy as np
out_img_data = np.zeros(padded_img_size)
count_img_data = np.zeros(padded_img_size)
patch_mask = np.zeros(patch_size)
patch_mask[0 + patch_crop_size[0]: patch_size[0] - patch_crop_size[0],
0 + patch_crop_size[1]: patch_size[1] - patch_crop_size[1],
0 + patch_crop_size[2]: patch_size[2] - patch_crop_size[2]] = 1
# this code will build an image from a collection of patches sampled at idx_x, idx_y, idx_z indices
# these idxs are continuous on the image grid (i.e. step_size = 1
# however we may want to paste a patch after a step_size=5 after current patch
# averaging the overlap. the snippet below will consider all the fg idxs
# and consider only the ones which are subsampled at step_size
# hash_idxs = idx_x*1000000 + idx_y*1000 + idx_z
#
# subsampled_x = np.arange(0, padded_img_size[0], step_size[0])
# subsampled_y = np.arange(0, padded_img_size[1], step_size[1])
# subsampled_z = np.arange(0, padded_img_size[2], step_size[2])
#
# sub_idx_x, sub_idx_y, sub_idx_z = np.meshgrid(subsampled_x,
# subsampled_y,
# subsampled_z,
# sparse=False, indexing='ij')
# sub_hash_idxs = sub_idx_x.flatten()*1000000 + sub_idx_y.flatten()*1000 + sub_idx_z.flatten()
#
# # now only consider sub_has_idxs that are present in hash_idxs
# fg_sub_hash_idxs = np.intersect1d(hash_idxs, sub_hash_idxs, assume_unique=True)
# bool_idxs = np.in1d(hash_idxs, sub_hash_idxs)
# np.arange(hash_idxs.shape[0])[np.in1d(hash_idxs, sub_hash_idxs)]
# sub_patch_indices = np.arange(hash_idxs.shape[0])[np.in1d(hash_idxs, sub_hash_idxs)]
#
# fg_idx_z = np.mod(fg_sub_hash_idxs, 1000)
# fg_idx_x_y = np.floor_divide(fg_sub_hash_idxs, 1000)
# fg_idx_y = np.mod(fg_idx_x_y, 1000)
# fg_idx_x = np.floor_divide(fg_idx_x_y, 1000)
for patch_iter in range(len(idx_x)):
out_img_data[idx_x[patch_iter]:idx_x[patch_iter] + patch_size[0],
idx_y[patch_iter]:idx_y[patch_iter] + patch_size[1],
idx_z[patch_iter]:idx_z[patch_iter] + patch_size[2]] += np.multiply(np.reshape(in_patches[patch_iter, :],
in_patches.shape[1:4]), patch_mask)
count_img_data[idx_x[patch_iter]:idx_x[patch_iter] + patch_size[0],
idx_y[patch_iter]:idx_y[patch_iter] + patch_size[1],
idx_z[patch_iter]:idx_z[patch_iter] + patch_size[2]] += patch_mask
out_img_data = np.divide(out_img_data, count_img_data)
out_img_data[np.isnan(out_img_data)] = 0
# remove the padding
unpadded_img_size = padded_img_size - np.multiply(patch_size, 2)
out_img_data = out_img_data[patch_size[0]:patch_size[0] + unpadded_img_size[0],
patch_size[1]:patch_size[1] + unpadded_img_size[1],
patch_size[2]:patch_size[2] + unpadded_img_size[2]]
count_img_data = count_img_data[patch_size[0]:patch_size[0] + unpadded_img_size[0],
patch_size[1]:patch_size[1] + unpadded_img_size[1],
patch_size[2]:patch_size[2] + unpadded_img_size[2]]
return out_img_data, count_img_data | [
"def",
"build_image_from_patches",
"(",
"in_patches",
",",
"patch_size",
",",
"idx_x",
",",
"idx_y",
",",
"idx_z",
",",
"padded_img_size",
",",
"patch_crop_size",
")",
":",
"import",
"numpy",
"as",
"np",
"out_img_data",
"=",
"np",
".",
"zeros",
"(",
"padded_im... | https://github.com/freesurfer/freesurfer/blob/6dbe527d43ffa611acb2cd112e9469f9bfec8e36/sscnn_skullstripping/sscnn_skullstripping/image_utils/image_utils/patch_utils.py#L110-L174 | |
ppizarro/coursera | b39847928df4d9d5986b801085c025e8e9122b6a | cloud-computing/concepts1/mp1_assignment/submit.py | python | basicPrompt | () | return login, password | Prompt the user for login credentials. Returns a tuple (login, password). | Prompt the user for login credentials. Returns a tuple (login, password). | [
"Prompt",
"the",
"user",
"for",
"login",
"credentials",
".",
"Returns",
"a",
"tuple",
"(",
"login",
"password",
")",
"."
] | def basicPrompt():
"""Prompt the user for login credentials. Returns a tuple (login, password)."""
login = raw_input('Login (Email address): ')
password = raw_input('One-time Password (from the assignment page. This is NOT your own account\'s password): ')
return login, password | [
"def",
"basicPrompt",
"(",
")",
":",
"login",
"=",
"raw_input",
"(",
"'Login (Email address): '",
")",
"password",
"=",
"raw_input",
"(",
"'One-time Password (from the assignment page. This is NOT your own account\\'s password): '",
")",
"return",
"login",
",",
"password"
] | https://github.com/ppizarro/coursera/blob/b39847928df4d9d5986b801085c025e8e9122b6a/cloud-computing/concepts1/mp1_assignment/submit.py#L68-L72 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | build/android/buildbot/bb_device_steps.py | python | RebootDeviceSafe | (device) | Reboot a device, wait for it to start, and squelch timeout exceptions. | Reboot a device, wait for it to start, and squelch timeout exceptions. | [
"Reboot",
"a",
"device",
"wait",
"for",
"it",
"to",
"start",
"and",
"squelch",
"timeout",
"exceptions",
"."
] | def RebootDeviceSafe(device):
"""Reboot a device, wait for it to start, and squelch timeout exceptions."""
try:
android_commands.AndroidCommands(device).Reboot(True)
except errors.DeviceUnresponsiveError as e:
return e | [
"def",
"RebootDeviceSafe",
"(",
"device",
")",
":",
"try",
":",
"android_commands",
".",
"AndroidCommands",
"(",
"device",
")",
".",
"Reboot",
"(",
"True",
")",
"except",
"errors",
".",
"DeviceUnresponsiveError",
"as",
"e",
":",
"return",
"e"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/build/android/buildbot/bb_device_steps.py#L102-L107 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ILL_utilities.py | python | Cleanup.__init__ | (self, cleanupMode, deleteAlgorithmLogging) | Initialize an instance of the class. | Initialize an instance of the class. | [
"Initialize",
"an",
"instance",
"of",
"the",
"class",
"."
] | def __init__(self, cleanupMode, deleteAlgorithmLogging):
"""Initialize an instance of the class."""
self._deleteAlgorithmLogging = deleteAlgorithmLogging
self._doDelete = cleanupMode == self.ON
self._protected = set()
self._toBeDeleted = set() | [
"def",
"__init__",
"(",
"self",
",",
"cleanupMode",
",",
"deleteAlgorithmLogging",
")",
":",
"self",
".",
"_deleteAlgorithmLogging",
"=",
"deleteAlgorithmLogging",
"self",
".",
"_doDelete",
"=",
"cleanupMode",
"==",
"self",
".",
"ON",
"self",
".",
"_protected",
... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ILL_utilities.py#L18-L23 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.