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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/learn/python/learn/estimators/rnn_common.py | python | _get_single_cell | (cell_type, num_units) | return cell_type(num_units=num_units) | Constructs and return a single `RNNCell`.
Args:
cell_type: Either a string identifying the `RNNCell` type or a subclass of
`RNNCell`.
num_units: The number of units in the `RNNCell`.
Returns:
An initialized `RNNCell`.
Raises:
ValueError: `cell_type` is an invalid `RNNCell` name.
TypeError: `cell_type` is not a string or a subclass of `RNNCell`. | Constructs and return a single `RNNCell`. | [
"Constructs",
"and",
"return",
"a",
"single",
"RNNCell",
"."
] | def _get_single_cell(cell_type, num_units):
"""Constructs and return a single `RNNCell`.
Args:
cell_type: Either a string identifying the `RNNCell` type or a subclass of
`RNNCell`.
num_units: The number of units in the `RNNCell`.
Returns:
An initialized `RNNCell`.
Raises:
ValueError: `cell_type` is an invalid `RNNCell` name.
TypeError: `cell_type` is not a string or a subclass of `RNNCell`.
"""
cell_type = _CELL_TYPES.get(cell_type, cell_type)
if not cell_type or not issubclass(cell_type, contrib_rnn.RNNCell):
raise ValueError('The supported cell types are {}; got {}'.format(
list(_CELL_TYPES.keys()), cell_type))
return cell_type(num_units=num_units) | [
"def",
"_get_single_cell",
"(",
"cell_type",
",",
"num_units",
")",
":",
"cell_type",
"=",
"_CELL_TYPES",
".",
"get",
"(",
"cell_type",
",",
"cell_type",
")",
"if",
"not",
"cell_type",
"or",
"not",
"issubclass",
"(",
"cell_type",
",",
"contrib_rnn",
".",
"RN... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/learn/python/learn/estimators/rnn_common.py#L56-L73 | |
twhui/LiteFlowNet | 00925aebf2db9ac50f4b1666f718688b10dd10d1 | tools/extra/parse_log.py | python | save_csv_files | (logfile_path, output_dir, train_dict_list, test_dict_list,
delimiter=',', verbose=False) | Save CSV files to output_dir
If the input log file is, e.g., caffe.INFO, the names will be
caffe.INFO.train and caffe.INFO.test | Save CSV files to output_dir | [
"Save",
"CSV",
"files",
"to",
"output_dir"
] | def save_csv_files(logfile_path, output_dir, train_dict_list, test_dict_list,
delimiter=',', verbose=False):
"""Save CSV files to output_dir
If the input log file is, e.g., caffe.INFO, the names will be
caffe.INFO.train and caffe.INFO.test
"""
log_basename = os.path.basename(logfile_path)
train_filename = os.path.join(output_dir, log_basename + '.train')
write_csv(train_filename, train_dict_list, delimiter, verbose)
test_filename = os.path.join(output_dir, log_basename + '.test')
write_csv(test_filename, test_dict_list, delimiter, verbose) | [
"def",
"save_csv_files",
"(",
"logfile_path",
",",
"output_dir",
",",
"train_dict_list",
",",
"test_dict_list",
",",
"delimiter",
"=",
"','",
",",
"verbose",
"=",
"False",
")",
":",
"log_basename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"logfile_path",
... | https://github.com/twhui/LiteFlowNet/blob/00925aebf2db9ac50f4b1666f718688b10dd10d1/tools/extra/parse_log.py#L132-L145 | ||
microsoft/onnxruntime | f92e47e95b13a240e37caf7b36577983544f98fc | tools/ci_build/github/linux/ort_minimal/readelf_utils.py | python | diff_sections_total_size | (base_binary_path, binary_path, readelf_path='readelf') | return results | Diff the sections entries for two binaries.
:param base_binary_path: Path to base binary for diff.
:param binary_path: Path to binary to diff using.
:param readelf_path: Path to 'readelf' binary. Defaults to 'readelf'
:return: Ordered dictionary containing size of diff for all sections with a diff, the diff for the sum of the
sections in the 'Sections total' entry, and the diff for the on-disk file size in the 'File size' entry | Diff the sections entries for two binaries.
:param base_binary_path: Path to base binary for diff.
:param binary_path: Path to binary to diff using.
:param readelf_path: Path to 'readelf' binary. Defaults to 'readelf'
:return: Ordered dictionary containing size of diff for all sections with a diff, the diff for the sum of the
sections in the 'Sections total' entry, and the diff for the on-disk file size in the 'File size' entry | [
"Diff",
"the",
"sections",
"entries",
"for",
"two",
"binaries",
".",
":",
"param",
"base_binary_path",
":",
"Path",
"to",
"base",
"binary",
"for",
"diff",
".",
":",
"param",
"binary_path",
":",
"Path",
"to",
"binary",
"to",
"diff",
"using",
".",
":",
"pa... | def diff_sections_total_size(base_binary_path, binary_path, readelf_path='readelf'):
'''
Diff the sections entries for two binaries.
:param base_binary_path: Path to base binary for diff.
:param binary_path: Path to binary to diff using.
:param readelf_path: Path to 'readelf' binary. Defaults to 'readelf'
:return: Ordered dictionary containing size of diff for all sections with a diff, the diff for the sum of the
sections in the 'Sections total' entry, and the diff for the on-disk file size in the 'File size' entry
'''
filesize = os.path.getsize(binary_path)
base_filesize = os.path.getsize(base_binary_path)
section_sizes = get_section_sizes(binary_path, readelf_path)
base_section_sizes = get_section_sizes(base_binary_path, readelf_path)
merged_keys = set(base_section_sizes.keys()) | set(section_sizes.keys())
base_total = 0
total = 0
results = collections.OrderedDict()
for section in sorted(merged_keys):
base_size = base_section_sizes[section] if section in base_section_sizes else 0
size = section_sizes[section] if section in section_sizes else 0
base_total += base_size
total += size
if size != base_size:
results[section] = size - base_size
results['Sections total'] = total - base_total
results['File size'] = filesize - base_filesize
return results | [
"def",
"diff_sections_total_size",
"(",
"base_binary_path",
",",
"binary_path",
",",
"readelf_path",
"=",
"'readelf'",
")",
":",
"filesize",
"=",
"os",
".",
"path",
".",
"getsize",
"(",
"binary_path",
")",
"base_filesize",
"=",
"os",
".",
"path",
".",
"getsize... | https://github.com/microsoft/onnxruntime/blob/f92e47e95b13a240e37caf7b36577983544f98fc/tools/ci_build/github/linux/ort_minimal/readelf_utils.py#L47-L81 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/distutils/system_info.py | python | get_standard_file | (fname) | return filenames | Returns a list of files named 'fname' from
1) System-wide directory (directory-location of this module)
2) Users HOME directory (os.environ['HOME'])
3) Local directory | Returns a list of files named 'fname' from
1) System-wide directory (directory-location of this module)
2) Users HOME directory (os.environ['HOME'])
3) Local directory | [
"Returns",
"a",
"list",
"of",
"files",
"named",
"fname",
"from",
"1",
")",
"System",
"-",
"wide",
"directory",
"(",
"directory",
"-",
"location",
"of",
"this",
"module",
")",
"2",
")",
"Users",
"HOME",
"directory",
"(",
"os",
".",
"environ",
"[",
"HOME... | def get_standard_file(fname):
"""Returns a list of files named 'fname' from
1) System-wide directory (directory-location of this module)
2) Users HOME directory (os.environ['HOME'])
3) Local directory
"""
# System-wide file
filenames = []
try:
f = __file__
except NameError:
f = sys.argv[0]
else:
sysfile = os.path.join(os.path.split(os.path.abspath(f))[0],
fname)
if os.path.isfile(sysfile):
filenames.append(sysfile)
# Home directory
# And look for the user config file
try:
f = os.path.expanduser('~')
except KeyError:
pass
else:
user_file = os.path.join(f, fname)
if os.path.isfile(user_file):
filenames.append(user_file)
# Local file
if os.path.isfile(fname):
filenames.append(os.path.abspath(fname))
return filenames | [
"def",
"get_standard_file",
"(",
"fname",
")",
":",
"# System-wide file",
"filenames",
"=",
"[",
"]",
"try",
":",
"f",
"=",
"__file__",
"except",
"NameError",
":",
"f",
"=",
"sys",
".",
"argv",
"[",
"0",
"]",
"else",
":",
"sysfile",
"=",
"os",
".",
"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/distutils/system_info.py#L351-L384 | |
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/contributed/sumopy/plugins/prt/prt.py | python | PrtVehicles.switch_off_control | (self, id_veh) | Direct way to switch of SUMO control of vehicles | Direct way to switch of SUMO control of vehicles | [
"Direct",
"way",
"to",
"switch",
"of",
"SUMO",
"control",
"of",
"vehicles"
] | def switch_off_control(self, id_veh):
"""Direct way to switch of SUMO control of vehicles"""
# print 'switch_off_control id_veh',id_veh
traci.vehicle.setSpeedMode(self.ids_sumo[id_veh], 6) | [
"def",
"switch_off_control",
"(",
"self",
",",
"id_veh",
")",
":",
"# print 'switch_off_control id_veh',id_veh",
"traci",
".",
"vehicle",
".",
"setSpeedMode",
"(",
"self",
".",
"ids_sumo",
"[",
"id_veh",
"]",
",",
"6",
")"
] | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/plugins/prt/prt.py#L4043-L4046 | ||
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBTarget.GetTargetFromEvent | (event) | return _lldb.SBTarget_GetTargetFromEvent(event) | GetTargetFromEvent(SBEvent event) -> SBTarget | GetTargetFromEvent(SBEvent event) -> SBTarget | [
"GetTargetFromEvent",
"(",
"SBEvent",
"event",
")",
"-",
">",
"SBTarget"
] | def GetTargetFromEvent(event):
"""GetTargetFromEvent(SBEvent event) -> SBTarget"""
return _lldb.SBTarget_GetTargetFromEvent(event) | [
"def",
"GetTargetFromEvent",
"(",
"event",
")",
":",
"return",
"_lldb",
".",
"SBTarget_GetTargetFromEvent",
"(",
"event",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L10307-L10309 | |
turi-code/SFrame | 796b9bdfb2fa1b881d82080754643c7e68629cd2 | oss_src/unity/python/sframe/data_structures/sarray.py | python | SArray.cumulative_min | (self) | return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op)) | Return the cumulative minimum value of the elements in the SArray.
Returns an SArray where each element in the output corresponds to the
minimum value of all the elements preceding and including it. The
SArray is expected to be of numeric type (int, float).
Returns
-------
out : SArray[int, float]
Notes
-----
- Missing values are ignored while performing the cumulative
aggregate operation.
Examples
--------
>>> sa = SArray([1, 2, 3, 4, 0])
>>> sa.cumulative_min()
dtype: int
rows: 3
[1, 1, 1, 1, 0] | Return the cumulative minimum value of the elements in the SArray. | [
"Return",
"the",
"cumulative",
"minimum",
"value",
"of",
"the",
"elements",
"in",
"the",
"SArray",
"."
] | def cumulative_min(self):
"""
Return the cumulative minimum value of the elements in the SArray.
Returns an SArray where each element in the output corresponds to the
minimum value of all the elements preceding and including it. The
SArray is expected to be of numeric type (int, float).
Returns
-------
out : SArray[int, float]
Notes
-----
- Missing values are ignored while performing the cumulative
aggregate operation.
Examples
--------
>>> sa = SArray([1, 2, 3, 4, 0])
>>> sa.cumulative_min()
dtype: int
rows: 3
[1, 1, 1, 1, 0]
"""
from .. import extensions
agg_op = "__builtin__cum_min__"
return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op)) | [
"def",
"cumulative_min",
"(",
"self",
")",
":",
"from",
".",
".",
"import",
"extensions",
"agg_op",
"=",
"\"__builtin__cum_min__\"",
"return",
"SArray",
"(",
"_proxy",
"=",
"self",
".",
"__proxy__",
".",
"builtin_cumulative_aggregate",
"(",
"agg_op",
")",
")"
] | https://github.com/turi-code/SFrame/blob/796b9bdfb2fa1b881d82080754643c7e68629cd2/oss_src/unity/python/sframe/data_structures/sarray.py#L4056-L4083 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/telnetlib.py | python | Telnet.sock_avail | (self) | Test whether data is available on the socket. | Test whether data is available on the socket. | [
"Test",
"whether",
"data",
"is",
"available",
"on",
"the",
"socket",
"."
] | def sock_avail(self):
"""Test whether data is available on the socket."""
with _TelnetSelector() as selector:
selector.register(self, selectors.EVENT_READ)
return bool(selector.select(0)) | [
"def",
"sock_avail",
"(",
"self",
")",
":",
"with",
"_TelnetSelector",
"(",
")",
"as",
"selector",
":",
"selector",
".",
"register",
"(",
"self",
",",
"selectors",
".",
"EVENT_READ",
")",
"return",
"bool",
"(",
"selector",
".",
"select",
"(",
"0",
")",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/telnetlib.py#L529-L533 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/tensor_array_ops.py | python | _GraphTensorArray.grad | (self, source, flow=None, name=None) | See TensorArray. | See TensorArray. | [
"See",
"TensorArray",
"."
] | def grad(self, source, flow=None, name=None):
"""See TensorArray."""
# tensor_array_grad requires a flow input when forward
# TensorArrays are dynamically sized. This forces the creation
# of the grad TensorArray only once the final forward array's size
# is fixed.
if flow is None:
flow = self.flow
with ops.name_scope(name, "TensorArrayGrad", [self._handle]):
with ops.colocate_with(self._handle):
g_handle, unused_flow = gen_data_flow_ops.tensor_array_grad_v3(
handle=self._handle, source=source, flow_in=flow, name=name)
with ops.control_dependencies([g_handle]):
flow = array_ops.identity(flow, name="gradient_flow")
g = TensorArray(
dtype=self._dtype,
handle=g_handle,
flow=flow,
infer_shape=self._infer_shape,
colocate_with_first_write_call=False)
# pylint: disable=protected-access
g._implementation._element_shape = self._element_shape
# pylint: enable=protected-access
return g | [
"def",
"grad",
"(",
"self",
",",
"source",
",",
"flow",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"# tensor_array_grad requires a flow input when forward",
"# TensorArrays are dynamically sized. This forces the creation",
"# of the grad TensorArray only once the final for... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/tensor_array_ops.py#L224-L247 | ||
PrincetonUniversity/athena-public-version | 9c266692b9423743d8e23509b3ab266a232a92d2 | tst/style/cpplint.py | python | IsDerivedFunction | (clean_lines, linenum) | return False | Check if current line contains an inherited function.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if current line contains a function with "override"
virt-specifier. | Check if current line contains an inherited function. | [
"Check",
"if",
"current",
"line",
"contains",
"an",
"inherited",
"function",
"."
] | def IsDerivedFunction(clean_lines, linenum):
"""Check if current line contains an inherited function.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if current line contains a function with "override"
virt-specifier.
"""
# Scan back a few lines for start of current function
for i in xrange(linenum, max(-1, linenum - 10), -1):
match = Match(r'^([^()]*\w+)\(', clean_lines.elided[i])
if match:
# Look for "override" after the matching closing parenthesis
line, _, closing_paren = CloseExpression(
clean_lines, i, len(match.group(1)))
return (closing_paren >= 0
and Search(r'\boverride\b', line[closing_paren:]))
return False | [
"def",
"IsDerivedFunction",
"(",
"clean_lines",
",",
"linenum",
")",
":",
"# Scan back a few lines for start of current function",
"for",
"i",
"in",
"xrange",
"(",
"linenum",
",",
"max",
"(",
"-",
"1",
",",
"linenum",
"-",
"10",
")",
",",
"-",
"1",
")",
":",... | https://github.com/PrincetonUniversity/athena-public-version/blob/9c266692b9423743d8e23509b3ab266a232a92d2/tst/style/cpplint.py#L5210-L5229 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/sparse/lil.py | python | lil_matrix.getrowview | (self, i) | return new | Returns a view of the 'i'th row (without copying). | Returns a view of the 'i'th row (without copying). | [
"Returns",
"a",
"view",
"of",
"the",
"i",
"th",
"row",
"(",
"without",
"copying",
")",
"."
] | def getrowview(self, i):
"""Returns a view of the 'i'th row (without copying).
"""
new = lil_matrix((1, self.shape[1]), dtype=self.dtype)
new.rows[0] = self.rows[i]
new.data[0] = self.data[i]
return new | [
"def",
"getrowview",
"(",
"self",
",",
"i",
")",
":",
"new",
"=",
"lil_matrix",
"(",
"(",
"1",
",",
"self",
".",
"shape",
"[",
"1",
"]",
")",
",",
"dtype",
"=",
"self",
".",
"dtype",
")",
"new",
".",
"rows",
"[",
"0",
"]",
"=",
"self",
".",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/sparse/lil.py#L193-L199 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/turtle.py | python | TurtleScreenBase._onkeyrelease | (self, fun, key) | Bind fun to key-release event of key.
Canvas must have focus. See method listen | Bind fun to key-release event of key.
Canvas must have focus. See method listen | [
"Bind",
"fun",
"to",
"key",
"-",
"release",
"event",
"of",
"key",
".",
"Canvas",
"must",
"have",
"focus",
".",
"See",
"method",
"listen"
] | def _onkeyrelease(self, fun, key):
"""Bind fun to key-release event of key.
Canvas must have focus. See method listen
"""
if fun is None:
self.cv.unbind("<KeyRelease-%s>" % key, None)
else:
def eventfun(event):
fun()
self.cv.bind("<KeyRelease-%s>" % key, eventfun) | [
"def",
"_onkeyrelease",
"(",
"self",
",",
"fun",
",",
"key",
")",
":",
"if",
"fun",
"is",
"None",
":",
"self",
".",
"cv",
".",
"unbind",
"(",
"\"<KeyRelease-%s>\"",
"%",
"key",
",",
"None",
")",
"else",
":",
"def",
"eventfun",
"(",
"event",
")",
":... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/turtle.py#L678-L687 | ||
synfig/synfig | a5ec91db5b751dc12e4400ccfb5c063fd6d2d928 | synfig-studio/plugins/lottie-exporter/common/Gradient.py | python | Gradient.reverse_gamma | (self, color) | return ret | Given a color, it reverses the effect of gamma as done in extract_colors()
Args:
color (common.Color.Color) : color element
Returns:
(common.Color.Color) : color element with gamma effect reversed | Given a color, it reverses the effect of gamma as done in extract_colors() | [
"Given",
"a",
"color",
"it",
"reverses",
"the",
"effect",
"of",
"gamma",
"as",
"done",
"in",
"extract_colors",
"()"
] | def reverse_gamma(self, color):
"""
Given a color, it reverses the effect of gamma as done in extract_colors()
Args:
color (common.Color.Color) : color element
Returns:
(common.Color.Color) : color element with gamma effect reversed
"""
ret = copy.deepcopy(color)
ret.red = ret.red ** settings.GAMMA[0]
ret.green = ret.green ** settings.GAMMA[1]
ret.blue = ret.blue ** settings.GAMMA[2]
return ret | [
"def",
"reverse_gamma",
"(",
"self",
",",
"color",
")",
":",
"ret",
"=",
"copy",
".",
"deepcopy",
"(",
"color",
")",
"ret",
".",
"red",
"=",
"ret",
".",
"red",
"**",
"settings",
".",
"GAMMA",
"[",
"0",
"]",
"ret",
".",
"green",
"=",
"ret",
".",
... | https://github.com/synfig/synfig/blob/a5ec91db5b751dc12e4400ccfb5c063fd6d2d928/synfig-studio/plugins/lottie-exporter/common/Gradient.py#L46-L60 | |
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | example/gluon/lipnet/utils/align.py | python | Align.word | (self, _id, padding=75) | return np.array(vec, dtype=np.int32) | Get words | Get words | [
"Get",
"words"
] | def word(self, _id, padding=75):
"""
Get words
"""
word = self.words[_id][2]
vec = word_to_vector(word)
vec += [-1] * (padding - len(vec))
return np.array(vec, dtype=np.int32) | [
"def",
"word",
"(",
"self",
",",
"_id",
",",
"padding",
"=",
"75",
")",
":",
"word",
"=",
"self",
".",
"words",
"[",
"_id",
"]",
"[",
"2",
"]",
"vec",
"=",
"word_to_vector",
"(",
"word",
")",
"vec",
"+=",
"[",
"-",
"1",
"]",
"*",
"(",
"paddin... | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/example/gluon/lipnet/utils/align.py#L62-L69 | |
apiaryio/snowcrash | b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3 | tools/gyp/pylib/gyp/generator/msvs.py | python | _EscapeEnvironmentVariableExpansion | (s) | return s | Escapes % characters.
Escapes any % characters so that Windows-style environment variable
expansions will leave them alone.
See http://connect.microsoft.com/VisualStudio/feedback/details/106127/cl-d-name-text-containing-percentage-characters-doesnt-compile
to understand why we have to do this.
Args:
s: The string to be escaped.
Returns:
The escaped string. | Escapes % characters. | [
"Escapes",
"%",
"characters",
"."
] | def _EscapeEnvironmentVariableExpansion(s):
"""Escapes % characters.
Escapes any % characters so that Windows-style environment variable
expansions will leave them alone.
See http://connect.microsoft.com/VisualStudio/feedback/details/106127/cl-d-name-text-containing-percentage-characters-doesnt-compile
to understand why we have to do this.
Args:
s: The string to be escaped.
Returns:
The escaped string.
"""
s = s.replace('%', '%%')
return s | [
"def",
"_EscapeEnvironmentVariableExpansion",
"(",
"s",
")",
":",
"s",
"=",
"s",
".",
"replace",
"(",
"'%'",
",",
"'%%'",
")",
"return",
"s"
] | https://github.com/apiaryio/snowcrash/blob/b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3/tools/gyp/pylib/gyp/generator/msvs.py#L649-L664 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py | python | CommandBit.parseparameter | (self, pos) | return parameter | Parse a parameter at the current position | Parse a parameter at the current position | [
"Parse",
"a",
"parameter",
"at",
"the",
"current",
"position"
] | def parseparameter(self, pos):
"Parse a parameter at the current position"
self.factory.clearskipped(pos)
if pos.finished():
return None
parameter = self.factory.parseany(pos)
self.add(parameter)
return parameter | [
"def",
"parseparameter",
"(",
"self",
",",
"pos",
")",
":",
"self",
".",
"factory",
".",
"clearskipped",
"(",
"pos",
")",
"if",
"pos",
".",
"finished",
"(",
")",
":",
"return",
"None",
"parameter",
"=",
"self",
".",
"factory",
".",
"parseany",
"(",
"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py#L4138-L4145 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/msvc.py | python | EnvironmentInfo.VSTools | (self) | return [join(self.si.VSInstallDir, path) for path in paths] | Microsoft Visual Studio Tools.
Return
------
list of str
paths | Microsoft Visual Studio Tools. | [
"Microsoft",
"Visual",
"Studio",
"Tools",
"."
] | def VSTools(self):
"""
Microsoft Visual Studio Tools.
Return
------
list of str
paths
"""
paths = [r'Common7\IDE', r'Common7\Tools']
if self.vs_ver >= 14.0:
arch_subdir = self.pi.current_dir(hidex86=True, x64=True)
paths += [r'Common7\IDE\CommonExtensions\Microsoft\TestWindow']
paths += [r'Team Tools\Performance Tools']
paths += [r'Team Tools\Performance Tools%s' % arch_subdir]
return [join(self.si.VSInstallDir, path) for path in paths] | [
"def",
"VSTools",
"(",
"self",
")",
":",
"paths",
"=",
"[",
"r'Common7\\IDE'",
",",
"r'Common7\\Tools'",
"]",
"if",
"self",
".",
"vs_ver",
">=",
"14.0",
":",
"arch_subdir",
"=",
"self",
".",
"pi",
".",
"current_dir",
"(",
"hidex86",
"=",
"True",
",",
"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/msvc.py#L1249-L1266 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/python/turicreate/toolkits/image_similarity/image_similarity.py | python | ImageSimilarityModel.__repr__ | (self) | return out | Print a string description of the model when the model name is entered
in the terminal. | Print a string description of the model when the model name is entered
in the terminal. | [
"Print",
"a",
"string",
"description",
"of",
"the",
"model",
"when",
"the",
"model",
"name",
"is",
"entered",
"in",
"the",
"terminal",
"."
] | def __repr__(self):
"""
Print a string description of the model when the model name is entered
in the terminal.
"""
width = 40
sections, section_titles = self._get_summary_struct()
out = _tkutl._toolkit_repr_print(self, sections, section_titles, width=width)
return out | [
"def",
"__repr__",
"(",
"self",
")",
":",
"width",
"=",
"40",
"sections",
",",
"section_titles",
"=",
"self",
".",
"_get_summary_struct",
"(",
")",
"out",
"=",
"_tkutl",
".",
"_toolkit_repr_print",
"(",
"self",
",",
"sections",
",",
"section_titles",
",",
... | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/toolkits/image_similarity/image_similarity.py#L296-L306 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/pydocview.py | python | DocApp.SetDefaultIcon | (self, icon) | Sets the application's default icon. | Sets the application's default icon. | [
"Sets",
"the",
"application",
"s",
"default",
"icon",
"."
] | def SetDefaultIcon(self, icon):
"""
Sets the application's default icon.
"""
self._defaultIcon = icon | [
"def",
"SetDefaultIcon",
"(",
"self",
",",
"icon",
")",
":",
"self",
".",
"_defaultIcon",
"=",
"icon"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/pydocview.py#L2075-L2079 | ||
koth/kcws | 88efbd36a7022de4e6e90f5a1fb880cf87cfae9f | third_party/python/cpplint/cpplint.py | python | ParseArguments | (args) | return filenames | Parses the command line arguments.
This may set the output format and verbosity level as side-effects.
Args:
args: The command line arguments:
Returns:
The list of filenames to lint. | Parses the command line arguments. | [
"Parses",
"the",
"command",
"line",
"arguments",
"."
] | def ParseArguments(args):
"""Parses the command line arguments.
This may set the output format and verbosity level as side-effects.
Args:
args: The command line arguments:
Returns:
The list of filenames to lint.
"""
try:
(opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=',
'counting=',
'filter=',
'root=',
'linelength=',
'extensions='])
except getopt.GetoptError:
PrintUsage('Invalid arguments.')
verbosity = _VerboseLevel()
output_format = _OutputFormat()
filters = ''
counting_style = ''
for (opt, val) in opts:
if opt == '--help':
PrintUsage(None)
elif opt == '--output':
if val not in ('emacs', 'vs7', 'eclipse'):
PrintUsage('The only allowed output formats are emacs, vs7 and eclipse.')
output_format = val
elif opt == '--verbose':
verbosity = int(val)
elif opt == '--filter':
filters = val
if not filters:
PrintCategories()
elif opt == '--counting':
if val not in ('total', 'toplevel', 'detailed'):
PrintUsage('Valid counting options are total, toplevel, and detailed')
counting_style = val
elif opt == '--root':
global _root
_root = val
elif opt == '--linelength':
global _line_length
try:
_line_length = int(val)
except ValueError:
PrintUsage('Line length must be digits.')
elif opt == '--extensions':
global _valid_extensions
try:
_valid_extensions = set(val.split(','))
except ValueError:
PrintUsage('Extensions must be comma seperated list.')
if not filenames:
PrintUsage('No files were specified.')
_SetOutputFormat(output_format)
_SetVerboseLevel(verbosity)
_SetFilters(filters)
_SetCountingStyle(counting_style)
return filenames | [
"def",
"ParseArguments",
"(",
"args",
")",
":",
"try",
":",
"(",
"opts",
",",
"filenames",
")",
"=",
"getopt",
".",
"getopt",
"(",
"args",
",",
"''",
",",
"[",
"'help'",
",",
"'output='",
",",
"'verbose='",
",",
"'counting='",
",",
"'filter='",
",",
... | https://github.com/koth/kcws/blob/88efbd36a7022de4e6e90f5a1fb880cf87cfae9f/third_party/python/cpplint/cpplint.py#L6241-L6308 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/logging/__init__.py | python | Formatter.formatTime | (self, record, datefmt=None) | return s | Return the creation time of the specified LogRecord as formatted text.
This method should be called from format() by a formatter which
wants to make use of a formatted time. This method can be overridden
in formatters to provide for any specific requirement, but the
basic behaviour is as follows: if datefmt (a string) is specified,
it is used with time.strftime() to format the creation time of the
record. Otherwise, the ISO8601 format is used. The resulting
string is returned. This function uses a user-configurable function
to convert the creation time to a tuple. By default, time.localtime()
is used; to change this for a particular formatter instance, set the
'converter' attribute to a function with the same signature as
time.localtime() or time.gmtime(). To change it for all formatters,
for example if you want all logging times to be shown in GMT,
set the 'converter' attribute in the Formatter class. | Return the creation time of the specified LogRecord as formatted text. | [
"Return",
"the",
"creation",
"time",
"of",
"the",
"specified",
"LogRecord",
"as",
"formatted",
"text",
"."
] | def formatTime(self, record, datefmt=None):
"""
Return the creation time of the specified LogRecord as formatted text.
This method should be called from format() by a formatter which
wants to make use of a formatted time. This method can be overridden
in formatters to provide for any specific requirement, but the
basic behaviour is as follows: if datefmt (a string) is specified,
it is used with time.strftime() to format the creation time of the
record. Otherwise, the ISO8601 format is used. The resulting
string is returned. This function uses a user-configurable function
to convert the creation time to a tuple. By default, time.localtime()
is used; to change this for a particular formatter instance, set the
'converter' attribute to a function with the same signature as
time.localtime() or time.gmtime(). To change it for all formatters,
for example if you want all logging times to be shown in GMT,
set the 'converter' attribute in the Formatter class.
"""
ct = self.converter(record.created)
if datefmt:
s = time.strftime(datefmt, ct)
else:
t = time.strftime("%Y-%m-%d %H:%M:%S", ct)
s = "%s,%03d" % (t, record.msecs)
return s | [
"def",
"formatTime",
"(",
"self",
",",
"record",
",",
"datefmt",
"=",
"None",
")",
":",
"ct",
"=",
"self",
".",
"converter",
"(",
"record",
".",
"created",
")",
"if",
"datefmt",
":",
"s",
"=",
"time",
".",
"strftime",
"(",
"datefmt",
",",
"ct",
")"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/logging/__init__.py#L405-L429 | |
daijifeng001/caffe-rfcn | 543f8f6a4b7c88256ea1445ae951a12d1ad9cffd | scripts/cpp_lint.py | python | CheckIncludeLine | (filename, clean_lines, linenum, include_state, error) | Check rules that are applicable to #include lines.
Strings on #include lines are NOT removed from elided line, to make
certain tasks easier. However, to prevent false positives, checks
applicable to #include lines in CheckLanguage must be put here.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
include_state: An _IncludeState instance in which the headers are inserted.
error: The function to call with any errors found. | Check rules that are applicable to #include lines. | [
"Check",
"rules",
"that",
"are",
"applicable",
"to",
"#include",
"lines",
"."
] | def CheckIncludeLine(filename, clean_lines, linenum, include_state, error):
"""Check rules that are applicable to #include lines.
Strings on #include lines are NOT removed from elided line, to make
certain tasks easier. However, to prevent false positives, checks
applicable to #include lines in CheckLanguage must be put here.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
include_state: An _IncludeState instance in which the headers are inserted.
error: The function to call with any errors found.
"""
fileinfo = FileInfo(filename)
line = clean_lines.lines[linenum]
# "include" should use the new style "foo/bar.h" instead of just "bar.h"
if _RE_PATTERN_INCLUDE_NEW_STYLE.search(line):
error(filename, linenum, 'build/include_dir', 4,
'Include the directory when naming .h files')
# we shouldn't include a file more than once. actually, there are a
# handful of instances where doing so is okay, but in general it's
# not.
match = _RE_PATTERN_INCLUDE.search(line)
if match:
include = match.group(2)
is_system = (match.group(1) == '<')
if include in include_state:
error(filename, linenum, 'build/include', 4,
'"%s" already included at %s:%s' %
(include, filename, include_state[include]))
else:
include_state[include] = linenum
# We want to ensure that headers appear in the right order:
# 1) for foo.cc, foo.h (preferred location)
# 2) c system files
# 3) cpp system files
# 4) for foo.cc, foo.h (deprecated location)
# 5) other google headers
#
# We classify each include statement as one of those 5 types
# using a number of techniques. The include_state object keeps
# track of the highest type seen, and complains if we see a
# lower type after that.
error_message = include_state.CheckNextIncludeOrder(
_ClassifyInclude(fileinfo, include, is_system))
if error_message:
error(filename, linenum, 'build/include_order', 4,
'%s. Should be: %s.h, c system, c++ system, other.' %
(error_message, fileinfo.BaseName()))
canonical_include = include_state.CanonicalizeAlphabeticalOrder(include)
if not include_state.IsInAlphabeticalOrder(
clean_lines, linenum, canonical_include):
error(filename, linenum, 'build/include_alpha', 4,
'Include "%s" not in alphabetical order' % include)
include_state.SetLastHeader(canonical_include)
# Look for any of the stream classes that are part of standard C++.
match = _RE_PATTERN_INCLUDE.match(line)
if match:
include = match.group(2)
if Match(r'(f|ind|io|i|o|parse|pf|stdio|str|)?stream$', include):
# Many unit tests use cout, so we exempt them.
if not _IsTestFilename(filename):
error(filename, linenum, 'readability/streams', 3,
'Streams are highly discouraged.') | [
"def",
"CheckIncludeLine",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"include_state",
",",
"error",
")",
":",
"fileinfo",
"=",
"FileInfo",
"(",
"filename",
")",
"line",
"=",
"clean_lines",
".",
"lines",
"[",
"linenum",
"]",
"# \"include\" shoul... | https://github.com/daijifeng001/caffe-rfcn/blob/543f8f6a4b7c88256ea1445ae951a12d1ad9cffd/scripts/cpp_lint.py#L3680-L3749 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/_pydecimal.py | python | _dlog | (c, e, p) | return _div_nearest(f_log_ten + log_d, 100) | Given integers c, e and p with c > 0, compute an integer
approximation to 10**p * log(c*10**e), with an absolute error of
at most 1. Assumes that c*10**e is not exactly 1. | Given integers c, e and p with c > 0, compute an integer
approximation to 10**p * log(c*10**e), with an absolute error of
at most 1. Assumes that c*10**e is not exactly 1. | [
"Given",
"integers",
"c",
"e",
"and",
"p",
"with",
"c",
">",
"0",
"compute",
"an",
"integer",
"approximation",
"to",
"10",
"**",
"p",
"*",
"log",
"(",
"c",
"*",
"10",
"**",
"e",
")",
"with",
"an",
"absolute",
"error",
"of",
"at",
"most",
"1",
"."... | def _dlog(c, e, p):
"""Given integers c, e and p with c > 0, compute an integer
approximation to 10**p * log(c*10**e), with an absolute error of
at most 1. Assumes that c*10**e is not exactly 1."""
# Increase precision by 2. The precision increase is compensated
# for at the end with a division by 100.
p += 2
# rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
# or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
# as 10**p * log(d) + 10**p*f * log(10).
l = len(str(c))
f = e+l - (e+l >= 1)
# compute approximation to 10**p*log(d), with error < 27
if p > 0:
k = e+p-f
if k >= 0:
c *= 10**k
else:
c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
# _ilog magnifies existing error in c by a factor of at most 10
log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
else:
# p <= 0: just approximate the whole thing by 0; error < 2.31
log_d = 0
# compute approximation to f*10**p*log(10), with error < 11.
if f:
extra = len(str(abs(f)))-1
if p + extra >= 0:
# error in f * _log10_digits(p+extra) < |f| * 1 = |f|
# after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
else:
f_log_ten = 0
else:
f_log_ten = 0
# error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
return _div_nearest(f_log_ten + log_d, 100) | [
"def",
"_dlog",
"(",
"c",
",",
"e",
",",
"p",
")",
":",
"# Increase precision by 2. The precision increase is compensated",
"# for at the end with a division by 100.",
"p",
"+=",
"2",
"# rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,",
"# or f <= 0 and 0.1 <= d <= 1.... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/_pydecimal.py#L5808-L5850 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/ensurepip/__init__.py | python | _bootstrap | (root=None, upgrade=False, user=False,
altinstall=False, default_pip=True,
verbosity=0) | Bootstrap pip into the current Python installation (or the given root
directory). Returns pip command status code.
Note that calling this function will alter both sys.path and os.environ. | Bootstrap pip into the current Python installation (or the given root
directory). Returns pip command status code. | [
"Bootstrap",
"pip",
"into",
"the",
"current",
"Python",
"installation",
"(",
"or",
"the",
"given",
"root",
"directory",
")",
".",
"Returns",
"pip",
"command",
"status",
"code",
"."
] | def _bootstrap(root=None, upgrade=False, user=False,
altinstall=False, default_pip=True,
verbosity=0):
"""
Bootstrap pip into the current Python installation (or the given root
directory). Returns pip command status code.
Note that calling this function will alter both sys.path and os.environ.
"""
if altinstall and default_pip:
raise ValueError("Cannot use altinstall and default_pip together")
_disable_pip_configuration_settings()
# By default, installing pip and setuptools installs all of the
# following scripts (X.Y == running Python version):
#
# pip, pipX, pipX.Y, easy_install, easy_install-X.Y
#
# pip 1.5+ allows ensurepip to request that some of those be left out
if altinstall:
# omit pip, pipX and easy_install
os.environ["ENSUREPIP_OPTIONS"] = "altinstall"
elif not default_pip:
# omit pip and easy_install
os.environ["ENSUREPIP_OPTIONS"] = "install"
tmpdir = tempfile.mkdtemp()
try:
# Put our bundled wheels into a temporary directory and construct the
# additional paths that need added to sys.path
additional_paths = []
for project, version in _PROJECTS:
wheel_name = "{}-{}-py2.py3-none-any.whl".format(project, version)
whl = pkgutil.get_data(
"ensurepip",
"_bundled/{}".format(wheel_name),
)
with open(os.path.join(tmpdir, wheel_name), "wb") as fp:
fp.write(whl)
additional_paths.append(os.path.join(tmpdir, wheel_name))
# Construct the arguments to be passed to the pip command
args = ["install", "--no-index", "--find-links", tmpdir]
if root:
args += ["--root", root]
if upgrade:
args += ["--upgrade"]
if user:
args += ["--user"]
if verbosity:
args += ["-" + "v" * verbosity]
return _run_pip(args + [p[0] for p in _PROJECTS], additional_paths)
finally:
shutil.rmtree(tmpdir, ignore_errors=True) | [
"def",
"_bootstrap",
"(",
"root",
"=",
"None",
",",
"upgrade",
"=",
"False",
",",
"user",
"=",
"False",
",",
"altinstall",
"=",
"False",
",",
"default_pip",
"=",
"True",
",",
"verbosity",
"=",
"0",
")",
":",
"if",
"altinstall",
"and",
"default_pip",
":... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/ensurepip/__init__.py#L69-L125 | ||
freesurfer/freesurfer | 6dbe527d43ffa611acb2cd112e9469f9bfec8e36 | cnn_sphere_register/ext/pytools-lib/pytools/patchlib.py | python | grid | (vol_size, patch_size, patch_stride=1, start_sub=0, nargout=1, grid_type='idx') | grid of patch starting points for nd volume that fit into given volume size
The index is in the given volume. If the volume gets cropped as part of the function and you
want a linear indexing into the new volume size, use
>> newidx = ind2ind(new_vol_size, vol_size, idx)
new_vol_size can be passed by the current function, see below.
Parameters:
vol_size (numpy vector): the size of the input volume
patch_size (numpy vector): the size of the patches
patch_stride (int or numpy vector, optional): stride (separation) in each dimension.
default: 1
start_sub (int or numpy vector, optional): the volume location where patches start
This essentially means that the volume will be cropped starting at that location.
e.g. if startSub is [2, 2], then only vol(2:end, 2:end) will be included.
default: 0
nargout (int, 1,2 or 3): optionally output new (cropped) volume size and the grid size
return the idx array only if nargout is 1, or (idx, new_vol_size) if nargout is 2,
or (idx, new_vol_size, grid_size) if nargout is 3
grid_type ('idx' or 'sub', optional): how to describe the grid, in linear index (idx)
or nd subscripts ('sub'). sub will be a nb_patches x nb_dims ndarray. This is
equivalent to sub = ind2sub(vol_size, idx), but is done faster inside this function.
[TODO: or it was faster in MATLAB, this might not be true in python anymore]
Returns:
idx nd array only if nargout is 1, or (idx, new_vol_size) if nargout is 2,
or (idx, new_vol_size, grid_size) if nargout is 3
See also:
gridsize()
Contact:
{adalca,klbouman}@csail.mit.edu | grid of patch starting points for nd volume that fit into given volume size | [
"grid",
"of",
"patch",
"starting",
"points",
"for",
"nd",
"volume",
"that",
"fit",
"into",
"given",
"volume",
"size"
] | def grid(vol_size, patch_size, patch_stride=1, start_sub=0, nargout=1, grid_type='idx'):
"""
grid of patch starting points for nd volume that fit into given volume size
The index is in the given volume. If the volume gets cropped as part of the function and you
want a linear indexing into the new volume size, use
>> newidx = ind2ind(new_vol_size, vol_size, idx)
new_vol_size can be passed by the current function, see below.
Parameters:
vol_size (numpy vector): the size of the input volume
patch_size (numpy vector): the size of the patches
patch_stride (int or numpy vector, optional): stride (separation) in each dimension.
default: 1
start_sub (int or numpy vector, optional): the volume location where patches start
This essentially means that the volume will be cropped starting at that location.
e.g. if startSub is [2, 2], then only vol(2:end, 2:end) will be included.
default: 0
nargout (int, 1,2 or 3): optionally output new (cropped) volume size and the grid size
return the idx array only if nargout is 1, or (idx, new_vol_size) if nargout is 2,
or (idx, new_vol_size, grid_size) if nargout is 3
grid_type ('idx' or 'sub', optional): how to describe the grid, in linear index (idx)
or nd subscripts ('sub'). sub will be a nb_patches x nb_dims ndarray. This is
equivalent to sub = ind2sub(vol_size, idx), but is done faster inside this function.
[TODO: or it was faster in MATLAB, this might not be true in python anymore]
Returns:
idx nd array only if nargout is 1, or (idx, new_vol_size) if nargout is 2,
or (idx, new_vol_size, grid_size) if nargout is 3
See also:
gridsize()
Contact:
{adalca,klbouman}@csail.mit.edu
"""
# parameter checking
assert grid_type in ('idx', 'sub')
if not isinstance(vol_size, np.ndarray):
vol_size = np.array(vol_size, 'int')
if not isinstance(patch_size, np.ndarray):
patch_size = np.array(patch_size, 'int')
nb_dims = len(patch_size) # number of dimensions
if isinstance(patch_stride, int):
patch_stride = np.repeat(patch_stride, nb_dims).astype('int')
if isinstance(start_sub, int):
start_sub = np.repeat(start_sub, nb_dims).astype('int')
# get the grid data
[grid_size, new_vol_size] = gridsize(vol_size, patch_size,
patch_stride=patch_stride,
start_sub=start_sub,
nargout=2)
# compute grid linear index
# prepare the sample grid in each dimension
xvec = ()
for idx in range(nb_dims):
volend = new_vol_size[idx] + start_sub[idx] - patch_size[idx] + 1
locs = list(range(start_sub[idx], volend, patch_stride[idx]))
xvec += (locs, )
assert any((locs[-1] + patch_size - 1) == (new_vol_size + start_sub - 1))
# get the nd grid
# if want subs, this is the faster way to compute in MATLAB (rather than ind -> ind2sub)
# TODO: need to investigate for python, maybe use np.ix_ ?
idx = nd.ndgrid(*xvec)
if grid_type == 'idx':
# if want index, this is the faster way to compute (rather than sub -> sub2ind
all_idx = np.array(list(range(0, np.prod(vol_size))))
all_idx = np.reshape(all_idx, vol_size)
idx = all_idx[idx]
if nargout == 1:
return idx
elif nargout == 2:
return (idx, new_vol_size)
else:
return (idx, new_vol_size, grid_size) | [
"def",
"grid",
"(",
"vol_size",
",",
"patch_size",
",",
"patch_stride",
"=",
"1",
",",
"start_sub",
"=",
"0",
",",
"nargout",
"=",
"1",
",",
"grid_type",
"=",
"'idx'",
")",
":",
"# parameter checking",
"assert",
"grid_type",
"in",
"(",
"'idx'",
",",
"'su... | https://github.com/freesurfer/freesurfer/blob/6dbe527d43ffa611acb2cd112e9469f9bfec8e36/cnn_sphere_register/ext/pytools-lib/pytools/patchlib.py#L298-L377 | ||
plaidml/plaidml | f3c6681db21460e5fdc11ae651d6d7b6c27f8262 | plaidml/edsl/__init__.py | python | TensorDim.__rmul__ | (self, other) | return TensorDim(_dim_op(lib.PLAIDML_INT_OP_MUL, other, self)) | Performs a multiplication between a TensorDim and another operand in
a polynomial expression.
Example:
>>> N, M = TensorDims(2)
>>> A = Placeholder(DType.FLOAT32, [3, 3])
>>> A.bind_dims(N, M)
>>> R = Contraction().outShape(5 * N) | Performs a multiplication between a TensorDim and another operand in
a polynomial expression. | [
"Performs",
"a",
"multiplication",
"between",
"a",
"TensorDim",
"and",
"another",
"operand",
"in",
"a",
"polynomial",
"expression",
"."
] | def __rmul__(self, other):
"""Performs a multiplication between a TensorDim and another operand in
a polynomial expression.
Example:
>>> N, M = TensorDims(2)
>>> A = Placeholder(DType.FLOAT32, [3, 3])
>>> A.bind_dims(N, M)
>>> R = Contraction().outShape(5 * N)
"""
return TensorDim(_dim_op(lib.PLAIDML_INT_OP_MUL, other, self)) | [
"def",
"__rmul__",
"(",
"self",
",",
"other",
")",
":",
"return",
"TensorDim",
"(",
"_dim_op",
"(",
"lib",
".",
"PLAIDML_INT_OP_MUL",
",",
"other",
",",
"self",
")",
")"
] | https://github.com/plaidml/plaidml/blob/f3c6681db21460e5fdc11ae651d6d7b6c27f8262/plaidml/edsl/__init__.py#L115-L125 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Code/Tools/waf-1.7.13/waflib/Tools/python.py | python | check_python_module | (conf, module_name, condition='') | Check if the selected python interpreter can import the given python module::
def configure(conf):
conf.check_python_module('pygccxml')
conf.check_python_module('re', condition="ver > num(2, 0, 4) and ver <= num(3, 0, 0)")
:param module_name: module
:type module_name: string | Check if the selected python interpreter can import the given python module:: | [
"Check",
"if",
"the",
"selected",
"python",
"interpreter",
"can",
"import",
"the",
"given",
"python",
"module",
"::"
] | def check_python_module(conf, module_name, condition=''):
"""
Check if the selected python interpreter can import the given python module::
def configure(conf):
conf.check_python_module('pygccxml')
conf.check_python_module('re', condition="ver > num(2, 0, 4) and ver <= num(3, 0, 0)")
:param module_name: module
:type module_name: string
"""
msg = 'Python module %s' % module_name
if condition:
msg = '%s (%s)' % (msg, condition)
conf.start_msg(msg)
try:
ret = conf.cmd_and_log(conf.env['PYTHON'] + ['-c', PYTHON_MODULE_TEMPLATE % module_name])
except Exception:
conf.end_msg(False)
conf.fatal('Could not find the python module %r' % module_name)
ret = ret.strip()
if condition:
conf.end_msg(ret)
if ret == 'unknown version':
conf.fatal('Could not check the %s version' % module_name)
from distutils.version import LooseVersion
def num(*k):
if isinstance(k[0], int):
return LooseVersion('.'.join([str(x) for x in k]))
else:
return LooseVersion(k[0])
d = {'num': num, 'ver': LooseVersion(ret)}
ev = eval(condition, {}, d)
if not ev:
conf.fatal('The %s version does not satisfy the requirements' % module_name)
else:
if ret == 'unknown version':
conf.end_msg(True)
else:
conf.end_msg(ret) | [
"def",
"check_python_module",
"(",
"conf",
",",
"module_name",
",",
"condition",
"=",
"''",
")",
":",
"msg",
"=",
"'Python module %s'",
"%",
"module_name",
"if",
"condition",
":",
"msg",
"=",
"'%s (%s)'",
"%",
"(",
"msg",
",",
"condition",
")",
"conf",
"."... | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/Tools/python.py#L461-L502 | ||
hpi-xnor/BMXNet | ed0b201da6667887222b8e4b5f997c4f6b61943d | python/mxnet/ndarray/ndarray.py | python | NDArray.flatten | (self, *args, **kwargs) | return op.flatten(self, *args, **kwargs) | Convenience fluent method for :py:func:`flatten`.
The arguments are the same as for :py:func:`flatten`, with
this array as data. | Convenience fluent method for :py:func:`flatten`. | [
"Convenience",
"fluent",
"method",
"for",
":",
"py",
":",
"func",
":",
"flatten",
"."
] | def flatten(self, *args, **kwargs):
"""Convenience fluent method for :py:func:`flatten`.
The arguments are the same as for :py:func:`flatten`, with
this array as data.
"""
return op.flatten(self, *args, **kwargs) | [
"def",
"flatten",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"op",
".",
"flatten",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/ndarray/ndarray.py#L1156-L1162 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py | python | HybridFunction.readtag | (self, pos) | return tag | Get the tag corresponding to the given index. Does parameter substitution. | Get the tag corresponding to the given index. Does parameter substitution. | [
"Get",
"the",
"tag",
"corresponding",
"to",
"the",
"given",
"index",
".",
"Does",
"parameter",
"substitution",
"."
] | def readtag(self, pos):
"Get the tag corresponding to the given index. Does parameter substitution."
if not pos.current().isdigit():
Trace.error('Function should be f0,...,f9: f' + pos.current())
return None
index = int(pos.skipcurrent())
if 2 + index > len(self.translated):
Trace.error('Function f' + unicode(index) + ' is not defined')
return None
tag = self.translated[2 + index]
if not '$' in tag:
return tag
for variable in self.params:
if variable in tag:
param = self.params[variable]
if not param.literal:
Trace.error('Parameters in tag ' + tag + ' should be literal: {' + variable + '!}')
continue
if param.literalvalue:
value = param.literalvalue
else:
value = ''
tag = tag.replace(variable, value)
return tag | [
"def",
"readtag",
"(",
"self",
",",
"pos",
")",
":",
"if",
"not",
"pos",
".",
"current",
"(",
")",
".",
"isdigit",
"(",
")",
":",
"Trace",
".",
"error",
"(",
"'Function should be f0,...,f9: f'",
"+",
"pos",
".",
"current",
"(",
")",
")",
"return",
"N... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py#L5008-L5031 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/idlelib/configHandler.py | python | IdleUserConfParser.RemoveFile | (self) | Removes the user config file from disk if it exists. | Removes the user config file from disk if it exists. | [
"Removes",
"the",
"user",
"config",
"file",
"from",
"disk",
"if",
"it",
"exists",
"."
] | def RemoveFile(self):
"""
Removes the user config file from disk if it exists.
"""
if os.path.exists(self.file):
os.remove(self.file) | [
"def",
"RemoveFile",
"(",
"self",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"file",
")",
":",
"os",
".",
"remove",
"(",
"self",
".",
"file",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/idlelib/configHandler.py#L127-L132 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/grid.py | python | Grid.IsCurrentCellReadOnly | (*args, **kwargs) | return _grid.Grid_IsCurrentCellReadOnly(*args, **kwargs) | IsCurrentCellReadOnly(self) -> bool | IsCurrentCellReadOnly(self) -> bool | [
"IsCurrentCellReadOnly",
"(",
"self",
")",
"-",
">",
"bool"
] | def IsCurrentCellReadOnly(*args, **kwargs):
"""IsCurrentCellReadOnly(self) -> bool"""
return _grid.Grid_IsCurrentCellReadOnly(*args, **kwargs) | [
"def",
"IsCurrentCellReadOnly",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"Grid_IsCurrentCellReadOnly",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/grid.py#L1366-L1368 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/Jinja2/py3/jinja2/lexer.py | python | Lexer.tokenize | (
self,
source: str,
name: t.Optional[str] = None,
filename: t.Optional[str] = None,
state: t.Optional[str] = None,
) | return TokenStream(self.wrap(stream, name, filename), name, filename) | Calls tokeniter + tokenize and wraps it in a token stream. | Calls tokeniter + tokenize and wraps it in a token stream. | [
"Calls",
"tokeniter",
"+",
"tokenize",
"and",
"wraps",
"it",
"in",
"a",
"token",
"stream",
"."
] | def tokenize(
self,
source: str,
name: t.Optional[str] = None,
filename: t.Optional[str] = None,
state: t.Optional[str] = None,
) -> TokenStream:
"""Calls tokeniter + tokenize and wraps it in a token stream."""
stream = self.tokeniter(source, name, filename, state)
return TokenStream(self.wrap(stream, name, filename), name, filename) | [
"def",
"tokenize",
"(",
"self",
",",
"source",
":",
"str",
",",
"name",
":",
"t",
".",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"filename",
":",
"t",
".",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"state",
":",
"t",
".",
"Optional",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Jinja2/py3/jinja2/lexer.py#L604-L613 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/propgrid.py | python | PropertyGridManager.__init__ | (self, *args, **kwargs) | __init__(self, Window parent, int id=ID_ANY, Point pos=DefaultPosition,
Size size=DefaultSize, long style=(0),
String name=wxPropertyGridManagerNameStr) -> PropertyGridManager | __init__(self, Window parent, int id=ID_ANY, Point pos=DefaultPosition,
Size size=DefaultSize, long style=(0),
String name=wxPropertyGridManagerNameStr) -> PropertyGridManager | [
"__init__",
"(",
"self",
"Window",
"parent",
"int",
"id",
"=",
"ID_ANY",
"Point",
"pos",
"=",
"DefaultPosition",
"Size",
"size",
"=",
"DefaultSize",
"long",
"style",
"=",
"(",
"0",
")",
"String",
"name",
"=",
"wxPropertyGridManagerNameStr",
")",
"-",
">",
... | def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=ID_ANY, Point pos=DefaultPosition,
Size size=DefaultSize, long style=(0),
String name=wxPropertyGridManagerNameStr) -> PropertyGridManager
"""
_propgrid.PropertyGridManager_swiginit(self,_propgrid.new_PropertyGridManager(*args, **kwargs))
self._setOORInfo(self)
self.DoDefaultTypeMappings()
self.edited_objects = {}
self.DoDefaultValueTypeMappings()
if not hasattr(self.__class__,'_vt2setter'):
self.__class__._vt2setter = {} | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_propgrid",
".",
"PropertyGridManager_swiginit",
"(",
"self",
",",
"_propgrid",
".",
"new_PropertyGridManager",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"se... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/propgrid.py#L3405-L3418 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/func_graph.py | python | FuncGraph.capture_distributed_variable | (self, variable, placeholder) | Add given distributed variable to captures with given placeholder. | Add given distributed variable to captures with given placeholder. | [
"Add",
"given",
"distributed",
"variable",
"to",
"captures",
"with",
"given",
"placeholder",
"."
] | def capture_distributed_variable(self, variable, placeholder):
"""Add given distributed variable to captures with given placeholder."""
self._captures[ops.tensor_id(variable)] = (variable, placeholder)
tape.record_operation("captured_value", [placeholder], [variable],
lambda x: [x]) | [
"def",
"capture_distributed_variable",
"(",
"self",
",",
"variable",
",",
"placeholder",
")",
":",
"self",
".",
"_captures",
"[",
"ops",
".",
"tensor_id",
"(",
"variable",
")",
"]",
"=",
"(",
"variable",
",",
"placeholder",
")",
"tape",
".",
"record_operatio... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/func_graph.py#L659-L663 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/flatmenu.py | python | FMRendererVista.__init__ | (self) | Default class constructor. | Default class constructor. | [
"Default",
"class",
"constructor",
"."
] | def __init__(self):
""" Default class constructor. """
FMRendererMSOffice2007.__init__(self) | [
"def",
"__init__",
"(",
"self",
")",
":",
"FMRendererMSOffice2007",
".",
"__init__",
"(",
"self",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/flatmenu.py#L1694-L1697 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/pathlib.py | python | PurePath.with_name | (self, name) | return self._from_parsed_parts(self._drv, self._root,
self._parts[:-1] + [name]) | Return a new path with the file name changed. | Return a new path with the file name changed. | [
"Return",
"a",
"new",
"path",
"with",
"the",
"file",
"name",
"changed",
"."
] | def with_name(self, name):
"""Return a new path with the file name changed."""
if not self.name:
raise ValueError("%r has an empty name" % (self,))
drv, root, parts = self._flavour.parse_parts((name,))
if (not name or name[-1] in [self._flavour.sep, self._flavour.altsep]
or drv or root or len(parts) != 1):
raise ValueError("Invalid name %r" % (name))
return self._from_parsed_parts(self._drv, self._root,
self._parts[:-1] + [name]) | [
"def",
"with_name",
"(",
"self",
",",
"name",
")",
":",
"if",
"not",
"self",
".",
"name",
":",
"raise",
"ValueError",
"(",
"\"%r has an empty name\"",
"%",
"(",
"self",
",",
")",
")",
"drv",
",",
"root",
",",
"parts",
"=",
"self",
".",
"_flavour",
".... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/pathlib.py#L876-L885 | |
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | third_party/numpy/files/numpy/lib/_datasource.py | python | _FileOpeners.keys | (self) | return self._file_openers.keys() | Return the keys of currently supported file openers.
Parameters
----------
None
Returns
-------
keys : list
The keys are None for uncompressed files and the file extension
strings (i.e. ``'.gz'``, ``'.bz2'``) for supported compression
methods. | Return the keys of currently supported file openers. | [
"Return",
"the",
"keys",
"of",
"currently",
"supported",
"file",
"openers",
"."
] | def keys(self):
"""
Return the keys of currently supported file openers.
Parameters
----------
None
Returns
-------
keys : list
The keys are None for uncompressed files and the file extension
strings (i.e. ``'.gz'``, ``'.bz2'``) for supported compression
methods.
"""
self._load()
return self._file_openers.keys() | [
"def",
"keys",
"(",
"self",
")",
":",
"self",
".",
"_load",
"(",
")",
"return",
"self",
".",
"_file_openers",
".",
"keys",
"(",
")"
] | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/lib/_datasource.py#L88-L105 | |
gimli-org/gimli | 17aa2160de9b15ababd9ef99e89b1bc3277bbb23 | pygimli/physics/em/hemmodelling.py | python | HEMmodelling.response | (self, par) | return pg.cat(ip, op) | Compute response vector by pasting in-phase and out-phase data. | Compute response vector by pasting in-phase and out-phase data. | [
"Compute",
"response",
"vector",
"by",
"pasting",
"in",
"-",
"phase",
"and",
"out",
"-",
"phase",
"data",
"."
] | def response(self, par):
"""Compute response vector by pasting in-phase and out-phase data."""
ip, op = self.vmd_hem(self.height,
np.asarray(par)[self.nlay-1:self.nlay*2-1],
np.asarray(par)[:self.nlay-1])
# ip, op = self.vmd_hem(self.height,
# np.asarray(par(self.nlay-1, self.nlay*2-1)),
# np.asarray(par(0, self.nlay-1)))
return pg.cat(ip, op) | [
"def",
"response",
"(",
"self",
",",
"par",
")",
":",
"ip",
",",
"op",
"=",
"self",
".",
"vmd_hem",
"(",
"self",
".",
"height",
",",
"np",
".",
"asarray",
"(",
"par",
")",
"[",
"self",
".",
"nlay",
"-",
"1",
":",
"self",
".",
"nlay",
"*",
"2"... | https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/physics/em/hemmodelling.py#L85-L93 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/distributions/python/ops/mvn_tril.py | python | MultivariateNormalTriL.__init__ | (self,
loc=None,
scale_tril=None,
validate_args=False,
allow_nan_stats=True,
name="MultivariateNormalTriL") | Construct Multivariate Normal distribution on `R^k`.
The `batch_shape` is the broadcast shape between `loc` and `scale`
arguments.
The `event_shape` is given by last dimension of the matrix implied by
`scale`. The last dimension of `loc` (if provided) must broadcast with this.
Recall that `covariance = scale @ scale.T`. A (non-batch) `scale` matrix is:
```none
scale = scale_tril
```
where `scale_tril` is lower-triangular `k x k` matrix with non-zero
diagonal, i.e., `tf.diag_part(scale_tril) != 0`.
Additional leading dimensions (if any) will index batches.
Args:
loc: Floating-point `Tensor`. If this is set to `None`, `loc` is
implicitly `0`. When specified, may have shape `[B1, ..., Bb, k]` where
`b >= 0` and `k` is the event size.
scale_tril: Floating-point, lower-triangular `Tensor` with non-zero
diagonal elements. `scale_tril` has shape `[B1, ..., Bb, k, k]` where
`b >= 0` and `k` is the event size.
validate_args: Python `bool`, default `False`. When `True` distribution
parameters are checked for validity despite possibly degrading runtime
performance. When `False` invalid inputs may silently render incorrect
outputs.
allow_nan_stats: Python `bool`, default `True`. When `True`,
statistics (e.g., mean, mode, variance) use the value "`NaN`" to
indicate the result is undefined. When `False`, an exception is raised
if one or more of the statistic's batch members are undefined.
name: Python `str` name prefixed to Ops created by this class.
Raises:
ValueError: if neither `loc` nor `scale_tril` are specified. | Construct Multivariate Normal distribution on `R^k`. | [
"Construct",
"Multivariate",
"Normal",
"distribution",
"on",
"R^k",
"."
] | def __init__(self,
loc=None,
scale_tril=None,
validate_args=False,
allow_nan_stats=True,
name="MultivariateNormalTriL"):
"""Construct Multivariate Normal distribution on `R^k`.
The `batch_shape` is the broadcast shape between `loc` and `scale`
arguments.
The `event_shape` is given by last dimension of the matrix implied by
`scale`. The last dimension of `loc` (if provided) must broadcast with this.
Recall that `covariance = scale @ scale.T`. A (non-batch) `scale` matrix is:
```none
scale = scale_tril
```
where `scale_tril` is lower-triangular `k x k` matrix with non-zero
diagonal, i.e., `tf.diag_part(scale_tril) != 0`.
Additional leading dimensions (if any) will index batches.
Args:
loc: Floating-point `Tensor`. If this is set to `None`, `loc` is
implicitly `0`. When specified, may have shape `[B1, ..., Bb, k]` where
`b >= 0` and `k` is the event size.
scale_tril: Floating-point, lower-triangular `Tensor` with non-zero
diagonal elements. `scale_tril` has shape `[B1, ..., Bb, k, k]` where
`b >= 0` and `k` is the event size.
validate_args: Python `bool`, default `False`. When `True` distribution
parameters are checked for validity despite possibly degrading runtime
performance. When `False` invalid inputs may silently render incorrect
outputs.
allow_nan_stats: Python `bool`, default `True`. When `True`,
statistics (e.g., mean, mode, variance) use the value "`NaN`" to
indicate the result is undefined. When `False`, an exception is raised
if one or more of the statistic's batch members are undefined.
name: Python `str` name prefixed to Ops created by this class.
Raises:
ValueError: if neither `loc` nor `scale_tril` are specified.
"""
parameters = locals()
def _convert_to_tensor(x, name):
return None if x is None else ops.convert_to_tensor(x, name=name)
if loc is None and scale_tril is None:
raise ValueError("Must specify one or both of `loc`, `scale_tril`.")
with ops.name_scope(name):
with ops.name_scope("init", values=[loc, scale_tril]):
loc = _convert_to_tensor(loc, name="loc")
scale_tril = _convert_to_tensor(scale_tril, name="scale_tril")
if scale_tril is None:
scale = linalg.LinearOperatorIdentity(
num_rows=distribution_util.dimension_size(loc, -1),
dtype=loc.dtype,
is_self_adjoint=True,
is_positive_definite=True,
assert_proper_shapes=validate_args)
else:
# No need to validate that scale_tril is non-singular.
# LinearOperatorTriL has an assert_non_singular method that is called
# by the Bijector.
scale = linalg.LinearOperatorTriL(
scale_tril,
is_non_singular=True,
is_self_adjoint=False,
is_positive_definite=False)
super(MultivariateNormalTriL, self).__init__(
loc=loc,
scale=scale,
validate_args=validate_args,
allow_nan_stats=allow_nan_stats,
name=name)
self._parameters = parameters | [
"def",
"__init__",
"(",
"self",
",",
"loc",
"=",
"None",
",",
"scale_tril",
"=",
"None",
",",
"validate_args",
"=",
"False",
",",
"allow_nan_stats",
"=",
"True",
",",
"name",
"=",
"\"MultivariateNormalTriL\"",
")",
":",
"parameters",
"=",
"locals",
"(",
")... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/distributions/python/ops/mvn_tril.py#L128-L204 | ||
intel/llvm | e6d0547e9d99b5a56430c4749f6c7e328bf221ab | lldb/third_party/Python/module/pexpect-4.6/pexpect/pty_spawn.py | python | spawn.__interact_read | (self, fd) | return os.read(fd, 1000) | This is used by the interact() method. | This is used by the interact() method. | [
"This",
"is",
"used",
"by",
"the",
"interact",
"()",
"method",
"."
] | def __interact_read(self, fd):
'''This is used by the interact() method.
'''
return os.read(fd, 1000) | [
"def",
"__interact_read",
"(",
"self",
",",
"fd",
")",
":",
"return",
"os",
".",
"read",
"(",
"fd",
",",
"1000",
")"
] | https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/lldb/third_party/Python/module/pexpect-4.6/pexpect/pty_spawn.py#L778-L782 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/plotting/_core.py | python | PlotAccessor.box | (self, by=None, **kwargs) | return self(kind="box", by=by, **kwargs) | r"""
Make a box plot of the DataFrame columns.
A box plot is a method for graphically depicting groups of numerical
data through their quartiles.
The box extends from the Q1 to Q3 quartile values of the data,
with a line at the median (Q2). The whiskers extend from the edges
of box to show the range of the data. The position of the whiskers
is set by default to 1.5*IQR (IQR = Q3 - Q1) from the edges of the
box. Outlier points are those past the end of the whiskers.
For further details see Wikipedia's
entry for `boxplot <https://en.wikipedia.org/wiki/Box_plot>`__.
A consideration when using this chart is that the box and the whiskers
can overlap, which is very common when plotting small sets of data.
Parameters
----------
by : str or sequence
Column in the DataFrame to group by.
**kwargs
Additional keywords are documented in
:meth:`DataFrame.plot`.
Returns
-------
:class:`matplotlib.axes.Axes` or numpy.ndarray of them
See Also
--------
DataFrame.boxplot: Another method to draw a box plot.
Series.plot.box: Draw a box plot from a Series object.
matplotlib.pyplot.boxplot: Draw a box plot in matplotlib.
Examples
--------
Draw a box plot from a DataFrame with four columns of randomly
generated data.
.. plot::
:context: close-figs
>>> data = np.random.randn(25, 4)
>>> df = pd.DataFrame(data, columns=list('ABCD'))
>>> ax = df.plot.box() | r"""
Make a box plot of the DataFrame columns. | [
"r",
"Make",
"a",
"box",
"plot",
"of",
"the",
"DataFrame",
"columns",
"."
] | def box(self, by=None, **kwargs):
r"""
Make a box plot of the DataFrame columns.
A box plot is a method for graphically depicting groups of numerical
data through their quartiles.
The box extends from the Q1 to Q3 quartile values of the data,
with a line at the median (Q2). The whiskers extend from the edges
of box to show the range of the data. The position of the whiskers
is set by default to 1.5*IQR (IQR = Q3 - Q1) from the edges of the
box. Outlier points are those past the end of the whiskers.
For further details see Wikipedia's
entry for `boxplot <https://en.wikipedia.org/wiki/Box_plot>`__.
A consideration when using this chart is that the box and the whiskers
can overlap, which is very common when plotting small sets of data.
Parameters
----------
by : str or sequence
Column in the DataFrame to group by.
**kwargs
Additional keywords are documented in
:meth:`DataFrame.plot`.
Returns
-------
:class:`matplotlib.axes.Axes` or numpy.ndarray of them
See Also
--------
DataFrame.boxplot: Another method to draw a box plot.
Series.plot.box: Draw a box plot from a Series object.
matplotlib.pyplot.boxplot: Draw a box plot in matplotlib.
Examples
--------
Draw a box plot from a DataFrame with four columns of randomly
generated data.
.. plot::
:context: close-figs
>>> data = np.random.randn(25, 4)
>>> df = pd.DataFrame(data, columns=list('ABCD'))
>>> ax = df.plot.box()
"""
return self(kind="box", by=by, **kwargs) | [
"def",
"box",
"(",
"self",
",",
"by",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
"(",
"kind",
"=",
"\"box\"",
",",
"by",
"=",
"by",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/plotting/_core.py#L1218-L1266 | |
mhammond/pywin32 | 44afd86ba8485194df93234639243252deeb40d5 | win32/Demos/win32netdemo.py | python | SetInfo | (userName=None) | Attempts to change the current users comment, then set it back | Attempts to change the current users comment, then set it back | [
"Attempts",
"to",
"change",
"the",
"current",
"users",
"comment",
"then",
"set",
"it",
"back"
] | def SetInfo(userName=None):
"Attempts to change the current users comment, then set it back"
if userName is None:
userName = win32api.GetUserName()
oldData = win32net.NetUserGetInfo(server, userName, 3)
try:
d = oldData.copy()
d["usr_comment"] = "Test comment"
win32net.NetUserSetInfo(server, userName, 3, d)
new = win32net.NetUserGetInfo(server, userName, 3)["usr_comment"]
if str(new) != "Test comment":
raise RuntimeError("Could not read the same comment back - got %s" % new)
print("Changed the data for the user")
finally:
win32net.NetUserSetInfo(server, userName, 3, oldData) | [
"def",
"SetInfo",
"(",
"userName",
"=",
"None",
")",
":",
"if",
"userName",
"is",
"None",
":",
"userName",
"=",
"win32api",
".",
"GetUserName",
"(",
")",
"oldData",
"=",
"win32net",
".",
"NetUserGetInfo",
"(",
"server",
",",
"userName",
",",
"3",
")",
... | https://github.com/mhammond/pywin32/blob/44afd86ba8485194df93234639243252deeb40d5/win32/Demos/win32netdemo.py#L189-L203 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/training/supervisor.py | python | Supervisor._get_first_op_from_collection | (self, key) | return None | Returns the first `Operation` from a collection.
Args:
key: A string collection key.
Returns:
The first Op found in a collection, or `None` if the collection is empty. | Returns the first `Operation` from a collection. | [
"Returns",
"the",
"first",
"Operation",
"from",
"a",
"collection",
"."
] | def _get_first_op_from_collection(self, key):
"""Returns the first `Operation` from a collection.
Args:
key: A string collection key.
Returns:
The first Op found in a collection, or `None` if the collection is empty.
"""
try:
op_list = ops.get_collection(key)
if len(op_list) > 1:
logging.info("Found %d %s operations. Returning the first one.",
len(op_list), key)
if op_list:
return op_list[0]
except LookupError:
pass
return None | [
"def",
"_get_first_op_from_collection",
"(",
"self",
",",
"key",
")",
":",
"try",
":",
"op_list",
"=",
"ops",
".",
"get_collection",
"(",
"key",
")",
"if",
"len",
"(",
"op_list",
")",
">",
"1",
":",
"logging",
".",
"info",
"(",
"\"Found %d %s operations. R... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/training/supervisor.py#L351-L370 | |
randombit/botan | e068d80953469fc8a3ec1715d0f64756d972daba | configure.py | python | lex_me_harder | (infofile, allowed_groups, allowed_maps, name_val_pairs) | return out | Generic lexer function for info.txt and src/build-data files | Generic lexer function for info.txt and src/build-data files | [
"Generic",
"lexer",
"function",
"for",
"info",
".",
"txt",
"and",
"src",
"/",
"build",
"-",
"data",
"files"
] | def lex_me_harder(infofile, allowed_groups, allowed_maps, name_val_pairs):
"""
Generic lexer function for info.txt and src/build-data files
"""
out = LexResult()
# Format as a nameable Python variable
def py_var(group):
return group.replace(':', '_')
lexer = shlex.shlex(open(infofile), infofile, posix=True)
lexer.wordchars += '=:.<>/,-!?+*' # handle various funky chars in info.txt
groups = allowed_groups + allowed_maps
for group in groups:
out.__dict__[py_var(group)] = []
for (key, val) in name_val_pairs.items():
out.__dict__[key] = val
def lexed_tokens(): # Convert to an iterator
while True:
token = lexer.get_token()
if token != lexer.eof:
yield token
else:
return
for token in lexed_tokens():
match = re.match('<(.*)>', token)
# Check for a grouping
if match is not None:
group = match.group(1)
if group not in groups:
raise LexerError('Unknown group "%s"' % (group),
infofile, lexer.lineno)
end_marker = '</' + group + '>'
token = lexer.get_token()
while token != end_marker:
out.__dict__[py_var(group)].append(token)
token = lexer.get_token()
if token is None:
raise LexerError('Group "%s" not terminated' % (group),
infofile, lexer.lineno)
elif token in name_val_pairs.keys():
if isinstance(out.__dict__[token], list):
out.__dict__[token].append(lexer.get_token())
else:
out.__dict__[token] = lexer.get_token()
else: # No match -> error
raise LexerError('Bad token "%s"' % (token), infofile, lexer.lineno)
for group in allowed_maps:
out.__dict__[group] = parse_lex_dict(out.__dict__[group], group, infofile)
return out | [
"def",
"lex_me_harder",
"(",
"infofile",
",",
"allowed_groups",
",",
"allowed_maps",
",",
"name_val_pairs",
")",
":",
"out",
"=",
"LexResult",
"(",
")",
"# Format as a nameable Python variable",
"def",
"py_var",
"(",
"group",
")",
":",
"return",
"group",
".",
"r... | https://github.com/randombit/botan/blob/e068d80953469fc8a3ec1715d0f64756d972daba/configure.py#L722-L782 | |
TheImagingSource/tiscamera | baacb4cfaa7858c2e6cfb4f1a297b404c4e002f6 | tools/tcam-capture/tcam_capture/TcamScreen.py | python | TcamScreen.remove_roi | (self, roi_widget) | Remove given roi widget from the scene | Remove given roi widget from the scene | [
"Remove",
"given",
"roi",
"widget",
"from",
"the",
"scene"
] | def remove_roi(self, roi_widget):
"""
Remove given roi widget from the scene
"""
if not roi_widget:
return
roi_widget.hide()
try:
self.roi_widgets.remove(roi_widget)
except ValueError as e:
# This means the widget is not in the list
pass | [
"def",
"remove_roi",
"(",
"self",
",",
"roi_widget",
")",
":",
"if",
"not",
"roi_widget",
":",
"return",
"roi_widget",
".",
"hide",
"(",
")",
"try",
":",
"self",
".",
"roi_widgets",
".",
"remove",
"(",
"roi_widget",
")",
"except",
"ValueError",
"as",
"e"... | https://github.com/TheImagingSource/tiscamera/blob/baacb4cfaa7858c2e6cfb4f1a297b404c4e002f6/tools/tcam-capture/tcam_capture/TcamScreen.py#L328-L340 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/numbers.py | python | Integral.__rrshift__ | (self, other) | other >> self | other >> self | [
"other",
">>",
"self"
] | def __rrshift__(self, other):
"""other >> self"""
raise NotImplementedError | [
"def",
"__rrshift__",
"(",
"self",
",",
"other",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/numbers.py#L336-L338 | ||
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/summary/event_file_inspector.py | python | print_dict | (d, show_missing=True) | Prints a shallow dict to console.
Args:
d: Dict to print.
show_missing: Whether to show keys with empty values. | Prints a shallow dict to console. | [
"Prints",
"a",
"shallow",
"dict",
"to",
"console",
"."
] | def print_dict(d, show_missing=True):
"""Prints a shallow dict to console.
Args:
d: Dict to print.
show_missing: Whether to show keys with empty values.
"""
for k, v in sorted(d.items()):
if (not v) and show_missing:
# No instances of the key, so print missing symbol.
print('{} -'.format(k))
elif isinstance(v, list):
# Value is a list, so print each item of the list.
print(k)
for item in v:
print(' {}'.format(item))
elif isinstance(v, dict):
# Value is a dict, so print each (key, value) pair of the dict.
print(k)
for kk, vv in sorted(v.items()):
print(' {:<20} {}'.format(kk, vv)) | [
"def",
"print_dict",
"(",
"d",
",",
"show_missing",
"=",
"True",
")",
":",
"for",
"k",
",",
"v",
"in",
"sorted",
"(",
"d",
".",
"items",
"(",
")",
")",
":",
"if",
"(",
"not",
"v",
")",
"and",
"show_missing",
":",
"# No instances of the key, so print mi... | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/summary/event_file_inspector.py#L231-L251 | ||
MythTV/mythtv | d282a209cb8be85d036f85a62a8ec971b67d45f4 | mythplugins/mytharchive/mythburn/scripts/mythburn.py | python | write | (text, progress=True) | Simple place to channel all text output through | Simple place to channel all text output through | [
"Simple",
"place",
"to",
"channel",
"all",
"text",
"output",
"through"
] | def write(text, progress=True):
"""Simple place to channel all text output through"""
if sys.version_info == 2:
sys.stdout.write((text + "\n").encode("utf-8", "replace"))
else:
sys.stdout.write(text + "\n")
sys.stdout.flush()
if progress == True and progresslog != "":
progressfile.write(time.strftime("%Y-%m-%d %H:%M:%S ") + text + "\n")
progressfile.flush() | [
"def",
"write",
"(",
"text",
",",
"progress",
"=",
"True",
")",
":",
"if",
"sys",
".",
"version_info",
"==",
"2",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"(",
"text",
"+",
"\"\\n\"",
")",
".",
"encode",
"(",
"\"utf-8\"",
",",
"\"replace\"",
"... | https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythplugins/mytharchive/mythburn/scripts/mythburn.py#L308-L319 | ||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Draft/importDXF.py | python | drawLine | (line, forceShape=False) | return None | Return a Part shape (Wire or Edge) from a DXF line.
Parameters
----------
line : drawing.entities
The DXF object of type `'line'`.
forceShape : bool, optional
It defaults to `False`. If it is `True` it will produce a `Part.Edge`,
otherwise it produces a `Draft Wire`.
Returns
-------
Part::Part2DObject or Part::TopoShape ('Edge')
The returned object is normally a `Wire`, if the global
variables `dxfCreateDraft` or `dxfCreateSketch` are set,
and `forceShape` is `False`.
Otherwise it produces a `Part.Edge`.
It returns `None` if it fails.
See also
--------
drawBlock
To do
-----
Use local variables, not global variables. | Return a Part shape (Wire or Edge) from a DXF line. | [
"Return",
"a",
"Part",
"shape",
"(",
"Wire",
"or",
"Edge",
")",
"from",
"a",
"DXF",
"line",
"."
] | def drawLine(line, forceShape=False):
"""Return a Part shape (Wire or Edge) from a DXF line.
Parameters
----------
line : drawing.entities
The DXF object of type `'line'`.
forceShape : bool, optional
It defaults to `False`. If it is `True` it will produce a `Part.Edge`,
otherwise it produces a `Draft Wire`.
Returns
-------
Part::Part2DObject or Part::TopoShape ('Edge')
The returned object is normally a `Wire`, if the global
variables `dxfCreateDraft` or `dxfCreateSketch` are set,
and `forceShape` is `False`.
Otherwise it produces a `Part.Edge`.
It returns `None` if it fails.
See also
--------
drawBlock
To do
-----
Use local variables, not global variables.
"""
if len(line.points) > 1:
v1 = vec(line.points[0])
v2 = vec(line.points[1])
if not DraftVecUtils.equals(v1, v2):
try:
if (dxfCreateDraft or dxfCreateSketch) and (not forceShape):
return Draft.makeWire([v1, v2])
else:
return Part.LineSegment(v1, v2).toShape()
except Part.OCCError:
warn(line)
return None | [
"def",
"drawLine",
"(",
"line",
",",
"forceShape",
"=",
"False",
")",
":",
"if",
"len",
"(",
"line",
".",
"points",
")",
">",
"1",
":",
"v1",
"=",
"vec",
"(",
"line",
".",
"points",
"[",
"0",
"]",
")",
"v2",
"=",
"vec",
"(",
"line",
".",
"poi... | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/importDXF.py#L838-L879 | |
OkCupid/okws | 1c337392c676ccb4e9a4c92d11d5d2fada6427d2 | contrib/pub3-upgrade.py | python | Pub1Parser.p_binding | (self, p) | binding : bindkey equals arg | binding : bindkey equals arg | [
"binding",
":",
"bindkey",
"equals",
"arg"
] | def p_binding (self, p):
'''binding : bindkey equals arg'''
p[0] = (p[1], p[3]) | [
"def",
"p_binding",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"(",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"3",
"]",
")"
] | https://github.com/OkCupid/okws/blob/1c337392c676ccb4e9a4c92d11d5d2fada6427d2/contrib/pub3-upgrade.py#L1006-L1008 | ||
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/contrib/layers/python/layers/layers.py | python | softmax | (logits, scope=None) | Performs softmax on Nth dimension of N-dimensional logit tensor.
For two-dimensional logits this reduces to tf.nn.softmax. The N-th dimension
needs to have a specified number of elements (number of classes).
Args:
logits: N-dimensional `Tensor` with logits, where N > 1.
scope: Optional scope for variable_op_scope.
Returns:
a `Tensor` with same shape and type as logits. | Performs softmax on Nth dimension of N-dimensional logit tensor. | [
"Performs",
"softmax",
"on",
"Nth",
"dimension",
"of",
"N",
"-",
"dimensional",
"logit",
"tensor",
"."
] | def softmax(logits, scope=None):
"""Performs softmax on Nth dimension of N-dimensional logit tensor.
For two-dimensional logits this reduces to tf.nn.softmax. The N-th dimension
needs to have a specified number of elements (number of classes).
Args:
logits: N-dimensional `Tensor` with logits, where N > 1.
scope: Optional scope for variable_op_scope.
Returns:
a `Tensor` with same shape and type as logits.
"""
# TODO(jrru): Add axis argument which defaults to last dimension.
with variable_scope.variable_op_scope([logits], scope, 'softmax'):
num_logits = utils.last_dimension(logits.get_shape(), min_rank=2)
logits_2d = array_ops.reshape(logits, [-1, num_logits])
predictions = nn.softmax(logits_2d)
predictions = array_ops.reshape(predictions, array_ops.shape(logits))
predictions.set_shape(logits.get_shape())
return predictions | [
"def",
"softmax",
"(",
"logits",
",",
"scope",
"=",
"None",
")",
":",
"# TODO(jrru): Add axis argument which defaults to last dimension.",
"with",
"variable_scope",
".",
"variable_op_scope",
"(",
"[",
"logits",
"]",
",",
"scope",
",",
"'softmax'",
")",
":",
"num_log... | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/layers/python/layers/layers.py#L1088-L1108 | ||
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/ros_comm/roslaunch/src/roslaunch/launch.py | python | validate_master_launch | (m, is_core, is_rostest=False) | Validate the configuration of a master we are about to launch. Ths
validation already assumes that no existing master is running at
this configuration and merely checks configuration for a new
launch. | Validate the configuration of a master we are about to launch. Ths
validation already assumes that no existing master is running at
this configuration and merely checks configuration for a new
launch. | [
"Validate",
"the",
"configuration",
"of",
"a",
"master",
"we",
"are",
"about",
"to",
"launch",
".",
"Ths",
"validation",
"already",
"assumes",
"that",
"no",
"existing",
"master",
"is",
"running",
"at",
"this",
"configuration",
"and",
"merely",
"checks",
"confi... | def validate_master_launch(m, is_core, is_rostest=False):
"""
Validate the configuration of a master we are about to launch. Ths
validation already assumes that no existing master is running at
this configuration and merely checks configuration for a new
launch.
"""
# Before starting a master, we do some sanity check on the
# master configuration. There are two ways the user starts:
# roscore or roslaunch. If the user types roscore, we always
# will start a core if possible, but we warn about potential
# misconfigurations. If the user types roslaunch, we will
# auto-start a new master if it is achievable, i.e. if the
# master is local.
if not rosgraph.network.is_local_address(m.get_host()):
# The network configuration says that the intended
# hostname is not local, so...
if is_core:
# ...user is expecting to start a new master. Thus, we
# only warn if network configuration appears
# non-local.
try:
reverse_ips = [host[4][0] for host in socket.getaddrinfo(m.get_host(), 0, 0, 0, socket.SOL_TCP)]
local_addrs = rosgraph.network.get_local_addresses()
printerrlog("""WARNING: IP addresses %s for local hostname '%s' do not appear to match
any local IP address (%s). Your ROS nodes may fail to communicate.
Please use ROS_IP to set the correct IP address to use."""%(','.join(reverse_ips), m.get_host(), ','.join(local_addrs)))
except:
printerrlog("""WARNING: local hostname '%s' does not map to an IP address.
Your ROS nodes may fail to communicate.
Please use ROS_IP to set the correct IP address to use."""%(m.get_host()))
else:
# ... the remote master cannot be contacted, so we fail. #3097
raise RLException("ERROR: unable to contact ROS master at [%s]"%(m.uri))
if is_core and not is_rostest:
# User wants to start a master, and our configuration does
# point to the local host, and we're not running as rostest.
env_uri = rosgraph.get_master_uri()
env_host, env_port = rosgraph.network.parse_http_host_and_port(env_uri)
if not rosgraph.network.is_local_address(env_host):
# The ROS_MASTER_URI points to a different machine, warn user
printerrlog("WARNING: ROS_MASTER_URI [%s] host is not set to this machine"%(env_uri))
elif env_port != m.get_port():
# The ROS_MASTER_URI points to a master on a different port, warn user
printerrlog("WARNING: ROS_MASTER_URI port [%s] does not match this roscore [%s]"%(env_port, m.get_port())) | [
"def",
"validate_master_launch",
"(",
"m",
",",
"is_core",
",",
"is_rostest",
"=",
"False",
")",
":",
"# Before starting a master, we do some sanity check on the",
"# master configuration. There are two ways the user starts:",
"# roscore or roslaunch. If the user types roscore, we always... | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/roslaunch/src/roslaunch/launch.py#L69-L118 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/tornado/tornado-6/tornado/httputil.py | python | split_host_and_port | (netloc: str) | return (host, port) | Returns ``(host, port)`` tuple from ``netloc``.
Returned ``port`` will be ``None`` if not present.
.. versionadded:: 4.1 | Returns ``(host, port)`` tuple from ``netloc``. | [
"Returns",
"(",
"host",
"port",
")",
"tuple",
"from",
"netloc",
"."
] | def split_host_and_port(netloc: str) -> Tuple[str, Optional[int]]:
"""Returns ``(host, port)`` tuple from ``netloc``.
Returned ``port`` will be ``None`` if not present.
.. versionadded:: 4.1
"""
match = _netloc_re.match(netloc)
if match:
host = match.group(1)
port = int(match.group(2)) # type: Optional[int]
else:
host = netloc
port = None
return (host, port) | [
"def",
"split_host_and_port",
"(",
"netloc",
":",
"str",
")",
"->",
"Tuple",
"[",
"str",
",",
"Optional",
"[",
"int",
"]",
"]",
":",
"match",
"=",
"_netloc_re",
".",
"match",
"(",
"netloc",
")",
"if",
"match",
":",
"host",
"=",
"match",
".",
"group",... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/tornado/tornado-6/tornado/httputil.py#L1028-L1042 | |
apiaryio/drafter | 4634ebd07f6c6f257cc656598ccd535492fdfb55 | tools/gyp/pylib/gyp/msvs_emulation.py | python | MsvsSettings.GetRcflags | (self, config, gyp_to_ninja_path) | return rcflags | Returns the flags that need to be added to invocations of the resource
compiler. | Returns the flags that need to be added to invocations of the resource
compiler. | [
"Returns",
"the",
"flags",
"that",
"need",
"to",
"be",
"added",
"to",
"invocations",
"of",
"the",
"resource",
"compiler",
"."
] | def GetRcflags(self, config, gyp_to_ninja_path):
"""Returns the flags that need to be added to invocations of the resource
compiler."""
config = self._TargetConfig(config)
rcflags = []
rc = self._GetWrapper(self, self.msvs_settings[config],
'VCResourceCompilerTool', append=rcflags)
rc('AdditionalIncludeDirectories', map=gyp_to_ninja_path, prefix='/I')
rcflags.append('/I' + gyp_to_ninja_path('.'))
rc('PreprocessorDefinitions', prefix='/d')
# /l arg must be in hex without leading '0x'
rc('Culture', prefix='/l', map=lambda x: hex(int(x))[2:])
return rcflags | [
"def",
"GetRcflags",
"(",
"self",
",",
"config",
",",
"gyp_to_ninja_path",
")",
":",
"config",
"=",
"self",
".",
"_TargetConfig",
"(",
"config",
")",
"rcflags",
"=",
"[",
"]",
"rc",
"=",
"self",
".",
"_GetWrapper",
"(",
"self",
",",
"self",
".",
"msvs_... | https://github.com/apiaryio/drafter/blob/4634ebd07f6c6f257cc656598ccd535492fdfb55/tools/gyp/pylib/gyp/msvs_emulation.py#L777-L789 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/caching.py | python | CompileResultCacheImpl.check_cachable | (self, cres) | return True | Check cachability of the given compile result. | Check cachability of the given compile result. | [
"Check",
"cachability",
"of",
"the",
"given",
"compile",
"result",
"."
] | def check_cachable(self, cres):
"""
Check cachability of the given compile result.
"""
cannot_cache = None
if self._is_closure:
cannot_cache = "as it uses outer variables in a closure"
elif cres.lifted:
cannot_cache = "as it uses lifted loops"
elif cres.library.has_dynamic_globals:
cannot_cache = ("as it uses dynamic globals "
"(such as ctypes pointers and large global arrays)")
if cannot_cache:
msg = ('Cannot cache compiled function "%s" %s'
% (cres.fndesc.qualname.split('.')[-1], cannot_cache))
warnings.warn_explicit(msg, NumbaWarning,
self._locator._py_file, self._lineno)
return False
return True | [
"def",
"check_cachable",
"(",
"self",
",",
"cres",
")",
":",
"cannot_cache",
"=",
"None",
"if",
"self",
".",
"_is_closure",
":",
"cannot_cache",
"=",
"\"as it uses outer variables in a closure\"",
"elif",
"cres",
".",
"lifted",
":",
"cannot_cache",
"=",
"\"as it u... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/caching.py#L408-L426 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_windows.py | python | QueryLayoutInfoEvent.GetSize | (*args, **kwargs) | return _windows_.QueryLayoutInfoEvent_GetSize(*args, **kwargs) | GetSize(self) -> Size | GetSize(self) -> Size | [
"GetSize",
"(",
"self",
")",
"-",
">",
"Size"
] | def GetSize(*args, **kwargs):
"""GetSize(self) -> Size"""
return _windows_.QueryLayoutInfoEvent_GetSize(*args, **kwargs) | [
"def",
"GetSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"QueryLayoutInfoEvent_GetSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_windows.py#L1977-L1979 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/devil/devil/android/sdk/adb_wrapper.py | python | AdbWrapper.Shell | (self, command, expect_status=0, timeout=DEFAULT_TIMEOUT,
retries=DEFAULT_RETRIES) | return output | Runs a shell command on the device.
Args:
command: A string with the shell command to run.
expect_status: (optional) Check that the command's exit status matches
this value. Default is 0. If set to None the test is skipped.
timeout: (optional) Timeout per try in seconds.
retries: (optional) Number of retries to attempt.
Returns:
The output of the shell command as a string.
Raises:
device_errors.AdbCommandFailedError: If the exit status doesn't match
|expect_status|. | Runs a shell command on the device. | [
"Runs",
"a",
"shell",
"command",
"on",
"the",
"device",
"."
] | def Shell(self, command, expect_status=0, timeout=DEFAULT_TIMEOUT,
retries=DEFAULT_RETRIES):
"""Runs a shell command on the device.
Args:
command: A string with the shell command to run.
expect_status: (optional) Check that the command's exit status matches
this value. Default is 0. If set to None the test is skipped.
timeout: (optional) Timeout per try in seconds.
retries: (optional) Number of retries to attempt.
Returns:
The output of the shell command as a string.
Raises:
device_errors.AdbCommandFailedError: If the exit status doesn't match
|expect_status|.
"""
if expect_status is None:
args = ['shell', command]
else:
args = ['shell', '( %s );echo %%$?' % command.rstrip()]
output = self._RunDeviceAdbCmd(args, timeout, retries, check_error=False)
if expect_status is not None:
output_end = output.rfind('%')
if output_end < 0:
# causes the status string to become empty and raise a ValueError
output_end = len(output)
try:
status = int(output[output_end + 1:])
except ValueError:
logging.warning('exit status of shell command %r missing.', command)
raise device_errors.AdbShellCommandFailedError(
command, output, status=None, device_serial=self._device_serial)
output = output[:output_end]
if status != expect_status:
raise device_errors.AdbShellCommandFailedError(
command, output, status=status, device_serial=self._device_serial)
return output | [
"def",
"Shell",
"(",
"self",
",",
"command",
",",
"expect_status",
"=",
"0",
",",
"timeout",
"=",
"DEFAULT_TIMEOUT",
",",
"retries",
"=",
"DEFAULT_RETRIES",
")",
":",
"if",
"expect_status",
"is",
"None",
":",
"args",
"=",
"[",
"'shell'",
",",
"command",
... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/devil/devil/android/sdk/adb_wrapper.py#L454-L493 | |
weichengkuo/DeepBox | c4f8c065b6a51cf296540cc453a44f0519aaacc9 | caffe-fast-rcnn/scripts/cpp_lint.py | python | CheckForBadCharacters | (filename, lines, error) | Logs an error for each line containing bad characters.
Two kinds of bad characters:
1. Unicode replacement characters: These indicate that either the file
contained invalid UTF-8 (likely) or Unicode replacement characters (which
it shouldn't). Note that it's possible for this to throw off line
numbering if the invalid UTF-8 occurred adjacent to a newline.
2. NUL bytes. These are problematic for some tools.
Args:
filename: The name of the current file.
lines: An array of strings, each representing a line of the file.
error: The function to call with any errors found. | Logs an error for each line containing bad characters. | [
"Logs",
"an",
"error",
"for",
"each",
"line",
"containing",
"bad",
"characters",
"."
] | def CheckForBadCharacters(filename, lines, error):
"""Logs an error for each line containing bad characters.
Two kinds of bad characters:
1. Unicode replacement characters: These indicate that either the file
contained invalid UTF-8 (likely) or Unicode replacement characters (which
it shouldn't). Note that it's possible for this to throw off line
numbering if the invalid UTF-8 occurred adjacent to a newline.
2. NUL bytes. These are problematic for some tools.
Args:
filename: The name of the current file.
lines: An array of strings, each representing a line of the file.
error: The function to call with any errors found.
"""
for linenum, line in enumerate(lines):
if u'\ufffd' in line:
error(filename, linenum, 'readability/utf8', 5,
'Line contains invalid UTF-8 (or Unicode replacement character).')
if '\0' in line:
error(filename, linenum, 'readability/nul', 5, 'Line contains NUL byte.') | [
"def",
"CheckForBadCharacters",
"(",
"filename",
",",
"lines",
",",
"error",
")",
":",
"for",
"linenum",
",",
"line",
"in",
"enumerate",
"(",
"lines",
")",
":",
"if",
"u'\\ufffd'",
"in",
"line",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'reada... | https://github.com/weichengkuo/DeepBox/blob/c4f8c065b6a51cf296540cc453a44f0519aaacc9/caffe-fast-rcnn/scripts/cpp_lint.py#L1483-L1505 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/_grad/grad_math_ops.py | python | get_bprop_reciprocal | (self) | return bprop | Grad definition for `Reciprocal` operation. | Grad definition for `Reciprocal` operation. | [
"Grad",
"definition",
"for",
"Reciprocal",
"operation",
"."
] | def get_bprop_reciprocal(self):
"""Grad definition for `Reciprocal` operation."""
reciprocal_grad = G.ReciprocalGrad()
def bprop(x, out, dout):
dx = reciprocal_grad(out, dout)
return (dx,)
return bprop | [
"def",
"get_bprop_reciprocal",
"(",
"self",
")",
":",
"reciprocal_grad",
"=",
"G",
".",
"ReciprocalGrad",
"(",
")",
"def",
"bprop",
"(",
"x",
",",
"out",
",",
"dout",
")",
":",
"dx",
"=",
"reciprocal_grad",
"(",
"out",
",",
"dout",
")",
"return",
"(",
... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_grad/grad_math_ops.py#L534-L542 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/gradients_impl.py | python | gradients_v2 | (ys, # pylint: disable=invalid-name
xs,
grad_ys=None,
name="gradients",
gate_gradients=False,
aggregation_method=None,
stop_gradients=None,
unconnected_gradients=UnconnectedGradients.NONE) | Constructs symbolic derivatives of sum of `ys` w.r.t. x in `xs`.
`ys` and `xs` are each a `Tensor` or a list of tensors. `grad_ys`
is a list of `Tensor`, holding the gradients received by the
`ys`. The list must be the same length as `ys`.
`gradients()` adds ops to the graph to output the derivatives of `ys` with
respect to `xs`. It returns a list of `Tensor` of length `len(xs)` where
each tensor is the `sum(dy/dx)` for y in `ys`.
`grad_ys` is a list of tensors of the same length as `ys` that holds
the initial gradients for each y in `ys`. When `grad_ys` is None,
we fill in a tensor of '1's of the shape of y for each y in `ys`. A
user can provide their own initial `grad_ys` to compute the
derivatives using a different initial gradient for each y (e.g., if
one wanted to weight the gradient differently for each value in
each y).
`stop_gradients` is a `Tensor` or a list of tensors to be considered constant
with respect to all `xs`. These tensors will not be backpropagated through,
as though they had been explicitly disconnected using `stop_gradient`. Among
other things, this allows computation of partial derivatives as opposed to
total derivatives. For example:
```python
a = tf.constant(0.)
b = 2 * a
g = tf.gradients(a + b, [a, b], stop_gradients=[a, b])
```
Here the partial derivatives `g` evaluate to `[1.0, 1.0]`, compared to the
total derivatives `tf.gradients(a + b, [a, b])`, which take into account the
influence of `a` on `b` and evaluate to `[3.0, 1.0]`. Note that the above is
equivalent to:
```python
a = tf.stop_gradient(tf.constant(0.))
b = tf.stop_gradient(2 * a)
g = tf.gradients(a + b, [a, b])
```
`stop_gradients` provides a way of stopping gradient after the graph has
already been constructed, as compared to `tf.stop_gradient` which is used
during graph construction. When the two approaches are combined,
backpropagation stops at both `tf.stop_gradient` nodes and nodes in
`stop_gradients`, whichever is encountered first.
All integer tensors are considered constant with respect to all `xs`, as if
they were included in `stop_gradients`.
`unconnected_gradients` determines the value returned for each x in xs if it
is unconnected in the graph to ys. By default this is None to safeguard
against errors. Mathematically these gradients are zero which can be requested
using the `'zero'` option. `tf.UnconnectedGradients` provides the
following options and behaviors:
```python
a = tf.ones([1, 2])
b = tf.ones([3, 1])
g1 = tf.gradients([b], [a], unnconnected_gradients='none')
sess.run(g1) # [None]
g2 = tf.gradients([b], [a], unconnected_gradients='zero')
sess.run(g2) # [array([[0., 0.]], dtype=float32)]
```
Args:
ys: A `Tensor` or list of tensors to be differentiated.
xs: A `Tensor` or list of tensors to be used for differentiation.
grad_ys: Optional. A `Tensor` or list of tensors the same size as
`ys` and holding the gradients computed for each y in `ys`.
name: Optional name to use for grouping all the gradient ops together.
defaults to 'gradients'.
gate_gradients: If True, add a tuple around the gradients returned
for an operations. This avoids some race conditions.
aggregation_method: Specifies the method used to combine gradient terms.
Accepted values are constants defined in the class `AggregationMethod`.
stop_gradients: Optional. A `Tensor` or list of tensors not to differentiate
through.
unconnected_gradients: Optional. Specifies the gradient value returned when
the given input tensors are unconnected. Accepted values are constants
defined in the class `tf.UnconnectedGradients` and the default value is
`none`.
Returns:
A list of `sum(dy/dx)` for each x in `xs`.
Raises:
LookupError: if one of the operations between `x` and `y` does not
have a registered gradient function.
ValueError: if the arguments are invalid.
RuntimeError: if called in Eager mode. | Constructs symbolic derivatives of sum of `ys` w.r.t. x in `xs`. | [
"Constructs",
"symbolic",
"derivatives",
"of",
"sum",
"of",
"ys",
"w",
".",
"r",
".",
"t",
".",
"x",
"in",
"xs",
"."
] | def gradients_v2(ys, # pylint: disable=invalid-name
xs,
grad_ys=None,
name="gradients",
gate_gradients=False,
aggregation_method=None,
stop_gradients=None,
unconnected_gradients=UnconnectedGradients.NONE):
"""Constructs symbolic derivatives of sum of `ys` w.r.t. x in `xs`.
`ys` and `xs` are each a `Tensor` or a list of tensors. `grad_ys`
is a list of `Tensor`, holding the gradients received by the
`ys`. The list must be the same length as `ys`.
`gradients()` adds ops to the graph to output the derivatives of `ys` with
respect to `xs`. It returns a list of `Tensor` of length `len(xs)` where
each tensor is the `sum(dy/dx)` for y in `ys`.
`grad_ys` is a list of tensors of the same length as `ys` that holds
the initial gradients for each y in `ys`. When `grad_ys` is None,
we fill in a tensor of '1's of the shape of y for each y in `ys`. A
user can provide their own initial `grad_ys` to compute the
derivatives using a different initial gradient for each y (e.g., if
one wanted to weight the gradient differently for each value in
each y).
`stop_gradients` is a `Tensor` or a list of tensors to be considered constant
with respect to all `xs`. These tensors will not be backpropagated through,
as though they had been explicitly disconnected using `stop_gradient`. Among
other things, this allows computation of partial derivatives as opposed to
total derivatives. For example:
```python
a = tf.constant(0.)
b = 2 * a
g = tf.gradients(a + b, [a, b], stop_gradients=[a, b])
```
Here the partial derivatives `g` evaluate to `[1.0, 1.0]`, compared to the
total derivatives `tf.gradients(a + b, [a, b])`, which take into account the
influence of `a` on `b` and evaluate to `[3.0, 1.0]`. Note that the above is
equivalent to:
```python
a = tf.stop_gradient(tf.constant(0.))
b = tf.stop_gradient(2 * a)
g = tf.gradients(a + b, [a, b])
```
`stop_gradients` provides a way of stopping gradient after the graph has
already been constructed, as compared to `tf.stop_gradient` which is used
during graph construction. When the two approaches are combined,
backpropagation stops at both `tf.stop_gradient` nodes and nodes in
`stop_gradients`, whichever is encountered first.
All integer tensors are considered constant with respect to all `xs`, as if
they were included in `stop_gradients`.
`unconnected_gradients` determines the value returned for each x in xs if it
is unconnected in the graph to ys. By default this is None to safeguard
against errors. Mathematically these gradients are zero which can be requested
using the `'zero'` option. `tf.UnconnectedGradients` provides the
following options and behaviors:
```python
a = tf.ones([1, 2])
b = tf.ones([3, 1])
g1 = tf.gradients([b], [a], unnconnected_gradients='none')
sess.run(g1) # [None]
g2 = tf.gradients([b], [a], unconnected_gradients='zero')
sess.run(g2) # [array([[0., 0.]], dtype=float32)]
```
Args:
ys: A `Tensor` or list of tensors to be differentiated.
xs: A `Tensor` or list of tensors to be used for differentiation.
grad_ys: Optional. A `Tensor` or list of tensors the same size as
`ys` and holding the gradients computed for each y in `ys`.
name: Optional name to use for grouping all the gradient ops together.
defaults to 'gradients'.
gate_gradients: If True, add a tuple around the gradients returned
for an operations. This avoids some race conditions.
aggregation_method: Specifies the method used to combine gradient terms.
Accepted values are constants defined in the class `AggregationMethod`.
stop_gradients: Optional. A `Tensor` or list of tensors not to differentiate
through.
unconnected_gradients: Optional. Specifies the gradient value returned when
the given input tensors are unconnected. Accepted values are constants
defined in the class `tf.UnconnectedGradients` and the default value is
`none`.
Returns:
A list of `sum(dy/dx)` for each x in `xs`.
Raises:
LookupError: if one of the operations between `x` and `y` does not
have a registered gradient function.
ValueError: if the arguments are invalid.
RuntimeError: if called in Eager mode.
"""
# Creating the gradient graph for control flow mutates Operations.
# _mutation_lock ensures a Session.run call cannot occur between creating and
# mutating new ops.
# pylint: disable=protected-access
with ops.get_default_graph()._mutation_lock():
return gradients_util._GradientsHelper(
ys, xs, grad_ys, name, True, gate_gradients,
aggregation_method, stop_gradients,
unconnected_gradients) | [
"def",
"gradients_v2",
"(",
"ys",
",",
"# pylint: disable=invalid-name",
"xs",
",",
"grad_ys",
"=",
"None",
",",
"name",
"=",
"\"gradients\"",
",",
"gate_gradients",
"=",
"False",
",",
"aggregation_method",
"=",
"None",
",",
"stop_gradients",
"=",
"None",
",",
... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/gradients_impl.py#L163-L274 | ||
google/mozc | 7329757e1ad30e327c1ae823a8302c79482d6b9c | src/build_tools/mozc_version.py | python | MozcVersion.__init__ | (self, path) | Parses a version definition file.
Args:
path: A filename which has the version definition.
If the file is not existent, empty properties are prepared instead. | Parses a version definition file. | [
"Parses",
"a",
"version",
"definition",
"file",
"."
] | def __init__(self, path):
"""Parses a version definition file.
Args:
path: A filename which has the version definition.
If the file is not existent, empty properties are prepared instead.
"""
self._properties = {}
if not os.path.isfile(path):
return
for line in open(path):
matchobj = re.match(r'(\w+)=(.*)', line.strip())
if matchobj:
var = matchobj.group(1)
val = matchobj.group(2)
if var not in self._properties:
self._properties[var] = val
# Check mandatory properties.
for key in VERSION_PROPERTIES:
if key not in self._properties:
# Don't raise error nor exit.
# Error handling is the client's responsibility.
logging.warning('Mandatory key "%s" does not exist in %s', key, path) | [
"def",
"__init__",
"(",
"self",
",",
"path",
")",
":",
"self",
".",
"_properties",
"=",
"{",
"}",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"return",
"for",
"line",
"in",
"open",
"(",
"path",
")",
":",
"matchobj",
"=",... | https://github.com/google/mozc/blob/7329757e1ad30e327c1ae823a8302c79482d6b9c/src/build_tools/mozc_version.py#L274-L298 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/build/waf-1.7.13/lmbrwaflib/settings_manager.py | python | ConfigurationSettings.does_configuration_match | (self, match_name, check_base=True) | Test this configuration setting if it matches a configuration name.
:param match_name: The name to match
:param check_base: Flag to search the base config (if this is a derived custom config)
:return: Match result | Test this configuration setting if it matches a configuration name.
:param match_name: The name to match
:param check_base: Flag to search the base config (if this is a derived custom config)
:return: Match result | [
"Test",
"this",
"configuration",
"setting",
"if",
"it",
"matches",
"a",
"configuration",
"name",
".",
":",
"param",
"match_name",
":",
"The",
"name",
"to",
"match",
":",
"param",
"check_base",
":",
"Flag",
"to",
"search",
"the",
"base",
"config",
"(",
"if"... | def does_configuration_match(self, match_name, check_base=True):
"""
Test this configuration setting if it matches a configuration name.
:param match_name: The name to match
:param check_base: Flag to search the base config (if this is a derived custom config)
:return: Match result
"""
if self.name == match_name:
return True
elif self.base_config and check_base:
if self.base_config.name == match_name:
return True
else:
return False | [
"def",
"does_configuration_match",
"(",
"self",
",",
"match_name",
",",
"check_base",
"=",
"True",
")",
":",
"if",
"self",
".",
"name",
"==",
"match_name",
":",
"return",
"True",
"elif",
"self",
".",
"base_config",
"and",
"check_base",
":",
"if",
"self",
"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/lmbrwaflib/settings_manager.py#L441-L454 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | buildconfig/doxygen_to_sip.py | python | start_python_doc_section | (out, line, look_for, section_header) | return False | Modify the lines by adding a section like Args
@param out :: list of dosctring lines
@param line :: last line read, no spaces
@param look_for :: @string to look at
@param section_header :: line text
@return True if the section was added | Modify the lines by adding a section like Args | [
"Modify",
"the",
"lines",
"by",
"adding",
"a",
"section",
"like",
"Args"
] | def start_python_doc_section(out, line, look_for, section_header):
"""Modify the lines by adding a section like Args
@param out :: list of dosctring lines
@param line :: last line read, no spaces
@param look_for :: @string to look at
@param section_header :: line text
@return True if the section was added
"""
# Add the 'Args:' line.
if line.strip().startswith(look_for):
# Add a blank line if there isn't one
if len(out)>0:
if out[-1].strip() != "":
out.append(" ")
out.append(section_header)
return True
return False | [
"def",
"start_python_doc_section",
"(",
"out",
",",
"line",
",",
"look_for",
",",
"section_header",
")",
":",
"# Add the 'Args:' line.",
"if",
"line",
".",
"strip",
"(",
")",
".",
"startswith",
"(",
"look_for",
")",
":",
"# Add a blank line if there isn't one",
"i... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/buildconfig/doxygen_to_sip.py#L49-L66 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/debug/lib/dumping_callback.py | python | _get_id | () | return str(uuid.uuid4()) | Get a short unique ID. | Get a short unique ID. | [
"Get",
"a",
"short",
"unique",
"ID",
"."
] | def _get_id():
"""Get a short unique ID."""
return str(uuid.uuid4()) | [
"def",
"_get_id",
"(",
")",
":",
"return",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/debug/lib/dumping_callback.py#L70-L72 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/fluid/layers/detection.py | python | box_coder | (prior_box,
prior_box_var,
target_box,
code_type="encode_center_size",
box_normalized=True,
name=None,
axis=0) | return output_box | r"""
**Box Coder Layer**
Encode/Decode the target bounding box with the priorbox information.
The Encoding schema described below:
.. math::
ox = (tx - px) / pw / pxv
oy = (ty - py) / ph / pyv
ow = \log(\abs(tw / pw)) / pwv
oh = \log(\abs(th / ph)) / phv
The Decoding schema described below:
.. math::
ox = (pw * pxv * tx * + px) - tw / 2
oy = (ph * pyv * ty * + py) - th / 2
ow = \exp(pwv * tw) * pw + tw / 2
oh = \exp(phv * th) * ph + th / 2
where `tx`, `ty`, `tw`, `th` denote the target box's center coordinates,
width and height respectively. Similarly, `px`, `py`, `pw`, `ph` denote
the priorbox's (anchor) center coordinates, width and height. `pxv`,
`pyv`, `pwv`, `phv` denote the variance of the priorbox and `ox`, `oy`,
`ow`, `oh` denote the encoded/decoded coordinates, width and height.
During Box Decoding, two modes for broadcast are supported. Say target
box has shape [N, M, 4], and the shape of prior box can be [N, 4] or
[M, 4]. Then prior box will broadcast to target box along the
assigned axis.
Args:
prior_box(Variable): Box list prior_box is a 2-D Tensor with shape
[M, 4] holds M boxes and data type is float32 or float64. Each box
is represented as [xmin, ymin, xmax, ymax], [xmin, ymin] is the
left top coordinate of the anchor box, if the input is image feature
map, they are close to the origin of the coordinate system.
[xmax, ymax] is the right bottom coordinate of the anchor box.
prior_box_var(List|Variable|None): prior_box_var supports three types
of input. One is variable with shape [M, 4] which holds M group and
data type is float32 or float64. The second is list consist of
4 elements shared by all boxes and data type is float32 or float64.
Other is None and not involved in calculation.
target_box(Variable): This input can be a 2-D LoDTensor with shape
[N, 4] when code_type is 'encode_center_size'. This input also can
be a 3-D Tensor with shape [N, M, 4] when code_type is
'decode_center_size'. Each box is represented as
[xmin, ymin, xmax, ymax]. The data type is float32 or float64.
This tensor can contain LoD information to represent a batch of inputs.
code_type(str): The code type used with the target box. It can be
`encode_center_size` or `decode_center_size`. `encode_center_size`
by default.
box_normalized(bool): Whether treat the priorbox as a normalized box.
Set true by default.
name(str, optional): For detailed information, please refer
to :ref:`api_guide_Name`. Usually name is no need to set and
None by default.
axis(int): Which axis in PriorBox to broadcast for box decode,
for example, if axis is 0 and TargetBox has shape [N, M, 4] and
PriorBox has shape [M, 4], then PriorBox will broadcast to [N, M, 4]
for decoding. It is only valid when code type is
`decode_center_size`. Set 0 by default.
Returns:
Variable:
output_box(Variable): When code_type is 'encode_center_size', the
output tensor of box_coder_op with shape [N, M, 4] representing the
result of N target boxes encoded with M Prior boxes and variances.
When code_type is 'decode_center_size', N represents the batch size
and M represents the number of decoded boxes.
Examples:
.. code-block:: python
import paddle.fluid as fluid
import paddle
paddle.enable_static()
# For encode
prior_box_encode = fluid.data(name='prior_box_encode',
shape=[512, 4],
dtype='float32')
target_box_encode = fluid.data(name='target_box_encode',
shape=[81, 4],
dtype='float32')
output_encode = fluid.layers.box_coder(prior_box=prior_box_encode,
prior_box_var=[0.1,0.1,0.2,0.2],
target_box=target_box_encode,
code_type="encode_center_size")
# For decode
prior_box_decode = fluid.data(name='prior_box_decode',
shape=[512, 4],
dtype='float32')
target_box_decode = fluid.data(name='target_box_decode',
shape=[512, 81, 4],
dtype='float32')
output_decode = fluid.layers.box_coder(prior_box=prior_box_decode,
prior_box_var=[0.1,0.1,0.2,0.2],
target_box=target_box_decode,
code_type="decode_center_size",
box_normalized=False,
axis=1) | r""" | [
"r"
] | def box_coder(prior_box,
prior_box_var,
target_box,
code_type="encode_center_size",
box_normalized=True,
name=None,
axis=0):
r"""
**Box Coder Layer**
Encode/Decode the target bounding box with the priorbox information.
The Encoding schema described below:
.. math::
ox = (tx - px) / pw / pxv
oy = (ty - py) / ph / pyv
ow = \log(\abs(tw / pw)) / pwv
oh = \log(\abs(th / ph)) / phv
The Decoding schema described below:
.. math::
ox = (pw * pxv * tx * + px) - tw / 2
oy = (ph * pyv * ty * + py) - th / 2
ow = \exp(pwv * tw) * pw + tw / 2
oh = \exp(phv * th) * ph + th / 2
where `tx`, `ty`, `tw`, `th` denote the target box's center coordinates,
width and height respectively. Similarly, `px`, `py`, `pw`, `ph` denote
the priorbox's (anchor) center coordinates, width and height. `pxv`,
`pyv`, `pwv`, `phv` denote the variance of the priorbox and `ox`, `oy`,
`ow`, `oh` denote the encoded/decoded coordinates, width and height.
During Box Decoding, two modes for broadcast are supported. Say target
box has shape [N, M, 4], and the shape of prior box can be [N, 4] or
[M, 4]. Then prior box will broadcast to target box along the
assigned axis.
Args:
prior_box(Variable): Box list prior_box is a 2-D Tensor with shape
[M, 4] holds M boxes and data type is float32 or float64. Each box
is represented as [xmin, ymin, xmax, ymax], [xmin, ymin] is the
left top coordinate of the anchor box, if the input is image feature
map, they are close to the origin of the coordinate system.
[xmax, ymax] is the right bottom coordinate of the anchor box.
prior_box_var(List|Variable|None): prior_box_var supports three types
of input. One is variable with shape [M, 4] which holds M group and
data type is float32 or float64. The second is list consist of
4 elements shared by all boxes and data type is float32 or float64.
Other is None and not involved in calculation.
target_box(Variable): This input can be a 2-D LoDTensor with shape
[N, 4] when code_type is 'encode_center_size'. This input also can
be a 3-D Tensor with shape [N, M, 4] when code_type is
'decode_center_size'. Each box is represented as
[xmin, ymin, xmax, ymax]. The data type is float32 or float64.
This tensor can contain LoD information to represent a batch of inputs.
code_type(str): The code type used with the target box. It can be
`encode_center_size` or `decode_center_size`. `encode_center_size`
by default.
box_normalized(bool): Whether treat the priorbox as a normalized box.
Set true by default.
name(str, optional): For detailed information, please refer
to :ref:`api_guide_Name`. Usually name is no need to set and
None by default.
axis(int): Which axis in PriorBox to broadcast for box decode,
for example, if axis is 0 and TargetBox has shape [N, M, 4] and
PriorBox has shape [M, 4], then PriorBox will broadcast to [N, M, 4]
for decoding. It is only valid when code type is
`decode_center_size`. Set 0 by default.
Returns:
Variable:
output_box(Variable): When code_type is 'encode_center_size', the
output tensor of box_coder_op with shape [N, M, 4] representing the
result of N target boxes encoded with M Prior boxes and variances.
When code_type is 'decode_center_size', N represents the batch size
and M represents the number of decoded boxes.
Examples:
.. code-block:: python
import paddle.fluid as fluid
import paddle
paddle.enable_static()
# For encode
prior_box_encode = fluid.data(name='prior_box_encode',
shape=[512, 4],
dtype='float32')
target_box_encode = fluid.data(name='target_box_encode',
shape=[81, 4],
dtype='float32')
output_encode = fluid.layers.box_coder(prior_box=prior_box_encode,
prior_box_var=[0.1,0.1,0.2,0.2],
target_box=target_box_encode,
code_type="encode_center_size")
# For decode
prior_box_decode = fluid.data(name='prior_box_decode',
shape=[512, 4],
dtype='float32')
target_box_decode = fluid.data(name='target_box_decode',
shape=[512, 81, 4],
dtype='float32')
output_decode = fluid.layers.box_coder(prior_box=prior_box_decode,
prior_box_var=[0.1,0.1,0.2,0.2],
target_box=target_box_decode,
code_type="decode_center_size",
box_normalized=False,
axis=1)
"""
check_variable_and_dtype(prior_box, 'prior_box', ['float32', 'float64'],
'box_coder')
check_variable_and_dtype(target_box, 'target_box', ['float32', 'float64'],
'box_coder')
helper = LayerHelper("box_coder", **locals())
output_box = helper.create_variable_for_type_inference(
dtype=prior_box.dtype)
inputs = {"PriorBox": prior_box, "TargetBox": target_box}
attrs = {
"code_type": code_type,
"box_normalized": box_normalized,
"axis": axis
}
if isinstance(prior_box_var, Variable):
inputs['PriorBoxVar'] = prior_box_var
elif isinstance(prior_box_var, list):
attrs['variance'] = prior_box_var
else:
raise TypeError("Input variance of box_coder must be Variable or lisz")
helper.append_op(
type="box_coder",
inputs=inputs,
attrs=attrs,
outputs={"OutputBox": output_box})
return output_box | [
"def",
"box_coder",
"(",
"prior_box",
",",
"prior_box_var",
",",
"target_box",
",",
"code_type",
"=",
"\"encode_center_size\"",
",",
"box_normalized",
"=",
"True",
",",
"name",
"=",
"None",
",",
"axis",
"=",
"0",
")",
":",
"check_variable_and_dtype",
"(",
"pri... | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/layers/detection.py#L819-L966 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/controls.py | python | BufferControl.mouse_handler | (self, cli, mouse_event) | Mouse handler for this control. | Mouse handler for this control. | [
"Mouse",
"handler",
"for",
"this",
"control",
"."
] | def mouse_handler(self, cli, mouse_event):
"""
Mouse handler for this control.
"""
buffer = self._buffer(cli)
position = mouse_event.position
# Focus buffer when clicked.
if self.has_focus(cli):
if self._last_get_processed_line:
processed_line = self._last_get_processed_line(position.y)
# Translate coordinates back to the cursor position of the
# original input.
xpos = processed_line.display_to_source(position.x)
index = buffer.document.translate_row_col_to_index(position.y, xpos)
# Set the cursor position.
if mouse_event.event_type == MouseEventType.MOUSE_DOWN:
buffer.exit_selection()
buffer.cursor_position = index
elif mouse_event.event_type == MouseEventType.MOUSE_UP:
# When the cursor was moved to another place, select the text.
# (The >1 is actually a small but acceptable workaround for
# selecting text in Vi navigation mode. In navigation mode,
# the cursor can never be after the text, so the cursor
# will be repositioned automatically.)
if abs(buffer.cursor_position - index) > 1:
buffer.start_selection(selection_type=SelectionType.CHARACTERS)
buffer.cursor_position = index
# Select word around cursor on double click.
# Two MOUSE_UP events in a short timespan are considered a double click.
double_click = self._last_click_timestamp and time.time() - self._last_click_timestamp < .3
self._last_click_timestamp = time.time()
if double_click:
start, end = buffer.document.find_boundaries_of_current_word()
buffer.cursor_position += start
buffer.start_selection(selection_type=SelectionType.CHARACTERS)
buffer.cursor_position += end - start
else:
# Don't handle scroll events here.
return NotImplemented
# Not focussed, but focussing on click events.
else:
if self.focus_on_click(cli) and mouse_event.event_type == MouseEventType.MOUSE_UP:
# Focus happens on mouseup. (If we did this on mousedown, the
# up event will be received at the point where this widget is
# focussed and be handled anyway.)
cli.focus(self.buffer_name)
else:
return NotImplemented | [
"def",
"mouse_handler",
"(",
"self",
",",
"cli",
",",
"mouse_event",
")",
":",
"buffer",
"=",
"self",
".",
"_buffer",
"(",
"cli",
")",
"position",
"=",
"mouse_event",
".",
"position",
"# Focus buffer when clicked.",
"if",
"self",
".",
"has_focus",
"(",
"cli"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/controls.py#L668-L722 | ||
bairdzhang/smallhardface | 76fa1d87a9602d9b13d7a7fe693fc7aec91cab80 | caffe/scripts/cpp_lint.py | python | CheckSpacing | (filename, clean_lines, linenum, nesting_state, error) | Checks for the correctness of various spacing issues in the code.
Things we check for: spaces around operators, spaces after
if/for/while/switch, no spaces around parens in function calls, two
spaces between code and comment, don't start a block with a blank
line, don't end a function with a blank line, don't add a blank line
after public/protected/private, don't have too many blank lines in a row.
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. | Checks for the correctness of various spacing issues in the code. | [
"Checks",
"for",
"the",
"correctness",
"of",
"various",
"spacing",
"issues",
"in",
"the",
"code",
"."
] | def CheckSpacing(filename, clean_lines, linenum, nesting_state, error):
"""Checks for the correctness of various spacing issues in the code.
Things we check for: spaces around operators, spaces after
if/for/while/switch, no spaces around parens in function calls, two
spaces between code and comment, don't start a block with a blank
line, don't end a function with a blank line, don't add a blank line
after public/protected/private, don't have too many blank lines in a row.
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.
"""
# Don't use "elided" lines here, otherwise we can't check commented lines.
# Don't want to use "raw" either, because we don't want to check inside C++11
# raw strings,
raw = clean_lines.lines_without_raw_strings
line = raw[linenum]
# Before nixing comments, check if the line is blank for no good
# reason. This includes the first line after a block is opened, and
# blank lines at the end of a function (ie, right before a line like '}'
#
# Skip all the blank line checks if we are immediately inside a
# namespace body. In other words, don't issue blank line warnings
# for this block:
# namespace {
#
# }
#
# A warning about missing end of namespace comments will be issued instead.
if IsBlankLine(line) and not nesting_state.InNamespaceBody():
elided = clean_lines.elided
prev_line = elided[linenum - 1]
prevbrace = prev_line.rfind('{')
# TODO(unknown): Don't complain if line before blank line, and line after,
# both start with alnums and are indented the same amount.
# This ignores whitespace at the start of a namespace block
# because those are not usually indented.
if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1:
# OK, we have a blank line at the start of a code block. Before we
# complain, we check if it is an exception to the rule: The previous
# non-empty line has the parameters of a function header that are indented
# 4 spaces (because they did not fit in a 80 column line when placed on
# the same line as the function name). We also check for the case where
# the previous line is indented 6 spaces, which may happen when the
# initializers of a constructor do not fit into a 80 column line.
exception = False
if Match(r' {6}\w', prev_line): # Initializer list?
# We are looking for the opening column of initializer list, which
# should be indented 4 spaces to cause 6 space indentation afterwards.
search_position = linenum-2
while (search_position >= 0
and Match(r' {6}\w', elided[search_position])):
search_position -= 1
exception = (search_position >= 0
and elided[search_position][:5] == ' :')
else:
# Search for the function arguments or an initializer list. We use a
# simple heuristic here: If the line is indented 4 spaces; and we have a
# closing paren, without the opening paren, followed by an opening brace
# or colon (for initializer lists) we assume that it is the last line of
# a function header. If we have a colon indented 4 spaces, it is an
# initializer list.
exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)',
prev_line)
or Match(r' {4}:', prev_line))
if not exception:
error(filename, linenum, 'whitespace/blank_line', 2,
'Redundant blank line at the start of a code block '
'should be deleted.')
# Ignore blank lines at the end of a block in a long if-else
# chain, like this:
# if (condition1) {
# // Something followed by a blank line
#
# } else if (condition2) {
# // Something else
# }
if linenum + 1 < clean_lines.NumLines():
next_line = raw[linenum + 1]
if (next_line
and Match(r'\s*}', next_line)
and next_line.find('} else ') == -1):
error(filename, linenum, 'whitespace/blank_line', 3,
'Redundant blank line at the end of a code block '
'should be deleted.')
matched = Match(r'\s*(public|protected|private):', prev_line)
if matched:
error(filename, linenum, 'whitespace/blank_line', 3,
'Do not leave a blank line after "%s:"' % matched.group(1))
# Next, we complain if there's a comment too near the text
commentpos = line.find('//')
if commentpos != -1:
# Check if the // may be in quotes. If so, ignore it
# Comparisons made explicit for clarity -- pylint: disable=g-explicit-bool-comparison
if (line.count('"', 0, commentpos) -
line.count('\\"', 0, commentpos)) % 2 == 0: # not in quotes
# Allow one space for new scopes, two spaces otherwise:
if (not Match(r'^\s*{ //', line) and
((commentpos >= 1 and
line[commentpos-1] not in string.whitespace) or
(commentpos >= 2 and
line[commentpos-2] not in string.whitespace))):
error(filename, linenum, 'whitespace/comments', 2,
'At least two spaces is best between code and comments')
# There should always be a space between the // and the comment
commentend = commentpos + 2
if commentend < len(line) and not line[commentend] == ' ':
# but some lines are exceptions -- e.g. if they're big
# comment delimiters like:
# //----------------------------------------------------------
# or are an empty C++ style Doxygen comment, like:
# ///
# or C++ style Doxygen comments placed after the variable:
# ///< Header comment
# //!< Header comment
# or they begin with multiple slashes followed by a space:
# //////// Header comment
match = (Search(r'[=/-]{4,}\s*$', line[commentend:]) or
Search(r'^/$', line[commentend:]) or
Search(r'^!< ', line[commentend:]) or
Search(r'^/< ', line[commentend:]) or
Search(r'^/+ ', line[commentend:]))
if not match:
error(filename, linenum, 'whitespace/comments', 4,
'Should have a space between // and comment')
CheckComment(line[commentpos:], filename, linenum, error)
line = clean_lines.elided[linenum] # get rid of comments and strings
# Don't try to do spacing checks for operator methods
line = re.sub(r'operator(==|!=|<|<<|<=|>=|>>|>)\(', 'operator\(', line)
# We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )".
# Otherwise not. Note we only check for non-spaces on *both* sides;
# sometimes people put non-spaces on one side when aligning ='s among
# many lines (not that this is behavior that I approve of...)
if Search(r'[\w.]=[\w.]', line) and not Search(r'\b(if|while) ', line):
error(filename, linenum, 'whitespace/operators', 4,
'Missing spaces around =')
# It's ok not to have spaces around binary operators like + - * /, but if
# there's too little whitespace, we get concerned. It's hard to tell,
# though, so we punt on this one for now. TODO.
# You should always have whitespace around binary operators.
#
# Check <= and >= first to avoid false positives with < and >, then
# check non-include lines for spacing around < and >.
match = Search(r'[^<>=!\s](==|!=|<=|>=)[^<>=!\s]', line)
if match:
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around %s' % match.group(1))
# We allow no-spaces around << when used like this: 10<<20, but
# not otherwise (particularly, not when used as streams)
# Also ignore using ns::operator<<;
match = Search(r'(operator|\S)(?:L|UL|ULL|l|ul|ull)?<<(\S)', line)
if (match and
not (match.group(1).isdigit() and match.group(2).isdigit()) and
not (match.group(1) == 'operator' and match.group(2) == ';')):
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around <<')
elif not Match(r'#.*include', line):
# Avoid false positives on ->
reduced_line = line.replace('->', '')
# Look for < that is not surrounded by spaces. This is only
# triggered if both sides are missing spaces, even though
# technically should should flag if at least one side is missing a
# space. This is done to avoid some false positives with shifts.
match = Search(r'[^\s<]<([^\s=<].*)', reduced_line)
if (match and
not FindNextMatchingAngleBracket(clean_lines, linenum, match.group(1))):
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around <')
# Look for > that is not surrounded by spaces. Similar to the
# above, we only trigger if both sides are missing spaces to avoid
# false positives with shifts.
match = Search(r'^(.*[^\s>])>[^\s=>]', reduced_line)
if (match and
not FindPreviousMatchingAngleBracket(clean_lines, linenum,
match.group(1))):
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around >')
# We allow no-spaces around >> for almost anything. This is because
# C++11 allows ">>" to close nested templates, which accounts for
# most cases when ">>" is not followed by a space.
#
# We still warn on ">>" followed by alpha character, because that is
# likely due to ">>" being used for right shifts, e.g.:
# value >> alpha
#
# When ">>" is used to close templates, the alphanumeric letter that
# follows would be part of an identifier, and there should still be
# a space separating the template type and the identifier.
# type<type<type>> alpha
match = Search(r'>>[a-zA-Z_]', line)
if match:
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around >>')
# There shouldn't be space around unary operators
match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line)
if match:
error(filename, linenum, 'whitespace/operators', 4,
'Extra space for operator %s' % match.group(1))
# A pet peeve of mine: no spaces after an if, while, switch, or for
match = Search(r' (if\(|for\(|while\(|switch\()', line)
if match:
error(filename, linenum, 'whitespace/parens', 5,
'Missing space before ( in %s' % match.group(1))
# For if/for/while/switch, the left and right parens should be
# consistent about how many spaces are inside the parens, and
# there should either be zero or one spaces inside the parens.
# We don't want: "if ( foo)" or "if ( foo )".
# Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed.
match = Search(r'\b(if|for|while|switch)\s*'
r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$',
line)
if match:
if len(match.group(2)) != len(match.group(4)):
if not (match.group(3) == ';' and
len(match.group(2)) == 1 + len(match.group(4)) or
not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)):
error(filename, linenum, 'whitespace/parens', 5,
'Mismatching spaces inside () in %s' % match.group(1))
if len(match.group(2)) not in [0, 1]:
error(filename, linenum, 'whitespace/parens', 5,
'Should have zero or one spaces inside ( and ) in %s' %
match.group(1))
# You should always have a space after a comma (either as fn arg or operator)
#
# This does not apply when the non-space character following the
# comma is another comma, since the only time when that happens is
# for empty macro arguments.
#
# We run this check in two passes: first pass on elided lines to
# verify that lines contain missing whitespaces, second pass on raw
# lines to confirm that those missing whitespaces are not due to
# elided comments.
if Search(r',[^,\s]', line) and Search(r',[^,\s]', raw[linenum]):
error(filename, linenum, 'whitespace/comma', 3,
'Missing space after ,')
# You should always have a space after a semicolon
# except for few corner cases
# TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more
# space after ;
if Search(r';[^\s};\\)/]', line):
error(filename, linenum, 'whitespace/semicolon', 3,
'Missing space after ;')
# Next we will look for issues with function calls.
CheckSpacingForFunctionCall(filename, line, linenum, error)
# Except after an opening paren, or after another opening brace (in case of
# an initializer list, for instance), you should have spaces before your
# braces. And since you should never have braces at the beginning of a line,
# this is an easy test.
match = Match(r'^(.*[^ ({]){', line)
if match:
# Try a bit harder to check for brace initialization. This
# happens in one of the following forms:
# Constructor() : initializer_list_{} { ... }
# Constructor{}.MemberFunction()
# Type variable{};
# FunctionCall(type{}, ...);
# LastArgument(..., type{});
# LOG(INFO) << type{} << " ...";
# map_of_type[{...}] = ...;
#
# We check for the character following the closing brace, and
# silence the warning if it's one of those listed above, i.e.
# "{.;,)<]".
#
# To account for nested initializer list, we allow any number of
# closing braces up to "{;,)<". We can't simply silence the
# warning on first sight of closing brace, because that would
# cause false negatives for things that are not initializer lists.
# Silence this: But not this:
# Outer{ if (...) {
# Inner{...} if (...){ // Missing space before {
# }; }
#
# There is a false negative with this approach if people inserted
# spurious semicolons, e.g. "if (cond){};", but we will catch the
# spurious semicolon with a separate check.
(endline, endlinenum, endpos) = CloseExpression(
clean_lines, linenum, len(match.group(1)))
trailing_text = ''
if endpos > -1:
trailing_text = endline[endpos:]
for offset in xrange(endlinenum + 1,
min(endlinenum + 3, clean_lines.NumLines() - 1)):
trailing_text += clean_lines.elided[offset]
if not Match(r'^[\s}]*[{.;,)<\]]', trailing_text):
error(filename, linenum, 'whitespace/braces', 5,
'Missing space before {')
# Make sure '} else {' has spaces.
if Search(r'}else', line):
error(filename, linenum, 'whitespace/braces', 5,
'Missing space before else')
# You shouldn't have spaces before your brackets, except maybe after
# 'delete []' or 'new char * []'.
if Search(r'\w\s+\[', line) and not Search(r'delete\s+\[', line):
error(filename, linenum, 'whitespace/braces', 5,
'Extra space before [')
# You shouldn't have a space before a semicolon at the end of the line.
# There's a special case for "for" since the style guide allows space before
# the semicolon there.
if Search(r':\s*;\s*$', line):
error(filename, linenum, 'whitespace/semicolon', 5,
'Semicolon defining empty statement. Use {} instead.')
elif Search(r'^\s*;\s*$', line):
error(filename, linenum, 'whitespace/semicolon', 5,
'Line contains only semicolon. If this should be an empty statement, '
'use {} instead.')
elif (Search(r'\s+;\s*$', line) and
not Search(r'\bfor\b', line)):
error(filename, linenum, 'whitespace/semicolon', 5,
'Extra space before last semicolon. If this should be an empty '
'statement, use {} instead.')
# In range-based for, we wanted spaces before and after the colon, but
# not around "::" tokens that might appear.
if (Search('for *\(.*[^:]:[^: ]', line) or
Search('for *\(.*[^: ]:[^:]', line)):
error(filename, linenum, 'whitespace/forcolon', 2,
'Missing space around colon in range-based for loop') | [
"def",
"CheckSpacing",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"nesting_state",
",",
"error",
")",
":",
"# Don't use \"elided\" lines here, otherwise we can't check commented lines.",
"# Don't want to use \"raw\" either, because we don't want to check inside C++11",
... | https://github.com/bairdzhang/smallhardface/blob/76fa1d87a9602d9b13d7a7fe693fc7aec91cab80/caffe/scripts/cpp_lint.py#L2647-L2992 | ||
fengbingchun/NN_Test | d6305825d5273e4569ccd1eda9ffa2a9c72e18d2 | src/tiny-dnn/third_party/cpplint.py | python | _DropCommonSuffixes | (filename) | return os.path.splitext(filename)[0] | Drops common suffixes like _test.cc or -inl.h from filename.
For example:
>>> _DropCommonSuffixes('foo/foo-inl.h')
'foo/foo'
>>> _DropCommonSuffixes('foo/bar/foo.cc')
'foo/bar/foo'
>>> _DropCommonSuffixes('foo/foo_internal.h')
'foo/foo'
>>> _DropCommonSuffixes('foo/foo_unusualinternal.h')
'foo/foo_unusualinternal'
Args:
filename: The input filename.
Returns:
The filename with the common suffix removed. | Drops common suffixes like _test.cc or -inl.h from filename. | [
"Drops",
"common",
"suffixes",
"like",
"_test",
".",
"cc",
"or",
"-",
"inl",
".",
"h",
"from",
"filename",
"."
] | def _DropCommonSuffixes(filename):
"""Drops common suffixes like _test.cc or -inl.h from filename.
For example:
>>> _DropCommonSuffixes('foo/foo-inl.h')
'foo/foo'
>>> _DropCommonSuffixes('foo/bar/foo.cc')
'foo/bar/foo'
>>> _DropCommonSuffixes('foo/foo_internal.h')
'foo/foo'
>>> _DropCommonSuffixes('foo/foo_unusualinternal.h')
'foo/foo_unusualinternal'
Args:
filename: The input filename.
Returns:
The filename with the common suffix removed.
"""
for suffix in itertools.chain(
('%s.%s' % (test_suffix.lstrip('_'), ext)
for test_suffix, ext in itertools.product(_test_suffixes, GetNonHeaderExtensions())),
('%s.%s' % (suffix, ext)
for suffix, ext in itertools.product(['inl', 'imp', 'internal'], GetHeaderExtensions()))):
if (filename.endswith(suffix) and len(filename) > len(suffix) and
filename[-len(suffix) - 1] in ('-', '_')):
return filename[:-len(suffix) - 1]
return os.path.splitext(filename)[0] | [
"def",
"_DropCommonSuffixes",
"(",
"filename",
")",
":",
"for",
"suffix",
"in",
"itertools",
".",
"chain",
"(",
"(",
"'%s.%s'",
"%",
"(",
"test_suffix",
".",
"lstrip",
"(",
"'_'",
")",
",",
"ext",
")",
"for",
"test_suffix",
",",
"ext",
"in",
"itertools",... | https://github.com/fengbingchun/NN_Test/blob/d6305825d5273e4569ccd1eda9ffa2a9c72e18d2/src/tiny-dnn/third_party/cpplint.py#L4577-L4604 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | caffe2/python/core.py | python | IR.Play | (self, op) | Adds an op to the current IR, and update the internal states to
reflect the blobs and versions after the execution of the op. | Adds an op to the current IR, and update the internal states to
reflect the blobs and versions after the execution of the op. | [
"Adds",
"an",
"op",
"to",
"the",
"current",
"IR",
"and",
"update",
"the",
"internal",
"states",
"to",
"reflect",
"the",
"blobs",
"and",
"versions",
"after",
"the",
"execution",
"of",
"the",
"op",
"."
] | def Play(self, op):
""""Adds an op to the current IR, and update the internal states to
reflect the blobs and versions after the execution of the op.
"""
# For input, they are the current version in the dict.
in_versions = {}
for s in op.input:
in_versions[s] = self.frontier[s]
self.input_usages[s][self.frontier[s]].append(len(self.ssa))
self.in_version_history[s].append((op, self.frontier[s]))
# For output, they are the current version plus one. If this is a
# newly created blob, its version starts with zero.
out_versions = {}
for s in op.output:
if s in self.frontier:
self.frontier[s] += 1
out_versions[s] = self.frontier[s]
self.out_version_history[s].append((op, self.frontier[s]))
# Add to SSA for bookkeeping.
self.ssa.append(OpSSA(op, in_versions, out_versions)) | [
"def",
"Play",
"(",
"self",
",",
"op",
")",
":",
"# For input, they are the current version in the dict.",
"in_versions",
"=",
"{",
"}",
"for",
"s",
"in",
"op",
".",
"input",
":",
"in_versions",
"[",
"s",
"]",
"=",
"self",
".",
"frontier",
"[",
"s",
"]",
... | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/caffe2/python/core.py#L536-L555 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/Terminal/Standard_Suite.py | python | Standard_Suite_Events.save | (self, _object, _attributes={}, **_arguments) | save: Save an object.
Required argument: the object for the command
Keyword argument in_: The file in which to save the object.
Keyword argument as: The file type in which to save the data.
Keyword argument _attributes: AppleEvent attribute dictionary | save: Save an object.
Required argument: the object for the command
Keyword argument in_: The file in which to save the object.
Keyword argument as: The file type in which to save the data.
Keyword argument _attributes: AppleEvent attribute dictionary | [
"save",
":",
"Save",
"an",
"object",
".",
"Required",
"argument",
":",
"the",
"object",
"for",
"the",
"command",
"Keyword",
"argument",
"in_",
":",
"The",
"file",
"in",
"which",
"to",
"save",
"the",
"object",
".",
"Keyword",
"argument",
"as",
":",
"The",... | def save(self, _object, _attributes={}, **_arguments):
"""save: Save an object.
Required argument: the object for the command
Keyword argument in_: The file in which to save the object.
Keyword argument as: The file type in which to save the data.
Keyword argument _attributes: AppleEvent attribute dictionary
"""
_code = 'core'
_subcode = 'save'
aetools.keysubst(_arguments, self._argmap_save)
_arguments['----'] = _object
_reply, _arguments, _attributes = self.send(_code, _subcode,
_arguments, _attributes)
if _arguments.get('errn', 0):
raise aetools.Error, aetools.decodeerror(_arguments)
# XXXX Optionally decode result
if _arguments.has_key('----'):
return _arguments['----'] | [
"def",
"save",
"(",
"self",
",",
"_object",
",",
"_attributes",
"=",
"{",
"}",
",",
"*",
"*",
"_arguments",
")",
":",
"_code",
"=",
"'core'",
"_subcode",
"=",
"'save'",
"aetools",
".",
"keysubst",
"(",
"_arguments",
",",
"self",
".",
"_argmap_save",
")... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/Terminal/Standard_Suite.py#L285-L305 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/grit/grit/pseudo_rtl.py | python | PseudoRTLMessage | (message) | return transl | Returns a pseudo-RTL (aka Fake-Bidi) translation of the provided message.
Args:
message: tclib.Message()
Return:
tclib.Translation() | Returns a pseudo-RTL (aka Fake-Bidi) translation of the provided message. | [
"Returns",
"a",
"pseudo",
"-",
"RTL",
"(",
"aka",
"Fake",
"-",
"Bidi",
")",
"translation",
"of",
"the",
"provided",
"message",
"."
] | def PseudoRTLMessage(message):
'''Returns a pseudo-RTL (aka Fake-Bidi) translation of the provided message.
Args:
message: tclib.Message()
Return:
tclib.Translation()
'''
transl = tclib.Translation()
for part in message.GetContent():
if isinstance(part, tclib.Placeholder):
transl.AppendPlaceholder(part)
else:
transl.AppendText(PseudoRTLString(part))
return transl | [
"def",
"PseudoRTLMessage",
"(",
"message",
")",
":",
"transl",
"=",
"tclib",
".",
"Translation",
"(",
")",
"for",
"part",
"in",
"message",
".",
"GetContent",
"(",
")",
":",
"if",
"isinstance",
"(",
"part",
",",
"tclib",
".",
"Placeholder",
")",
":",
"t... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/grit/grit/pseudo_rtl.py#L87-L103 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/asyncio/tasks.py | python | Task.cancel | (self, msg=None) | return True | Request that this task cancel itself.
This arranges for a CancelledError to be thrown into the
wrapped coroutine on the next cycle through the event loop.
The coroutine then has a chance to clean up or even deny
the request using try/except/finally.
Unlike Future.cancel, this does not guarantee that the
task will be cancelled: the exception might be caught and
acted upon, delaying cancellation of the task or preventing
cancellation completely. The task may also return a value or
raise a different exception.
Immediately after this method is called, Task.cancelled() will
not return True (unless the task was already cancelled). A
task will be marked as cancelled when the wrapped coroutine
terminates with a CancelledError exception (even if cancel()
was not called). | Request that this task cancel itself. | [
"Request",
"that",
"this",
"task",
"cancel",
"itself",
"."
] | def cancel(self, msg=None):
"""Request that this task cancel itself.
This arranges for a CancelledError to be thrown into the
wrapped coroutine on the next cycle through the event loop.
The coroutine then has a chance to clean up or even deny
the request using try/except/finally.
Unlike Future.cancel, this does not guarantee that the
task will be cancelled: the exception might be caught and
acted upon, delaying cancellation of the task or preventing
cancellation completely. The task may also return a value or
raise a different exception.
Immediately after this method is called, Task.cancelled() will
not return True (unless the task was already cancelled). A
task will be marked as cancelled when the wrapped coroutine
terminates with a CancelledError exception (even if cancel()
was not called).
"""
self._log_traceback = False
if self.done():
return False
if self._fut_waiter is not None:
if self._fut_waiter.cancel(msg=msg):
# Leave self._fut_waiter; it may be a Task that
# catches and ignores the cancellation so we may have
# to cancel it again later.
return True
# It must be the case that self.__step is already scheduled.
self._must_cancel = True
self._cancel_message = msg
return True | [
"def",
"cancel",
"(",
"self",
",",
"msg",
"=",
"None",
")",
":",
"self",
".",
"_log_traceback",
"=",
"False",
"if",
"self",
".",
"done",
"(",
")",
":",
"return",
"False",
"if",
"self",
".",
"_fut_waiter",
"is",
"not",
"None",
":",
"if",
"self",
"."... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/asyncio/tasks.py#L205-L237 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/tkinter/ttk.py | python | Sizegrip.__init__ | (self, master=None, **kw) | Construct a Ttk Sizegrip with parent master.
STANDARD OPTIONS
class, cursor, state, style, takefocus | Construct a Ttk Sizegrip with parent master. | [
"Construct",
"a",
"Ttk",
"Sizegrip",
"with",
"parent",
"master",
"."
] | def __init__(self, master=None, **kw):
"""Construct a Ttk Sizegrip with parent master.
STANDARD OPTIONS
class, cursor, state, style, takefocus
"""
Widget.__init__(self, master, "ttk::sizegrip", kw) | [
"def",
"__init__",
"(",
"self",
",",
"master",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"Widget",
".",
"__init__",
"(",
"self",
",",
"master",
",",
"\"ttk::sizegrip\"",
",",
"kw",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tkinter/ttk.py#L1145-L1152 | ||
TheImagingSource/tiscamera | baacb4cfaa7858c2e6cfb4f1a297b404c4e002f6 | tools/tcam-capture/tcam_capture/TcamScreen.py | python | TcamScreen.is_scene_larger_than_image | (self) | return False | checks if the entire ViewItem is visible in the scene | checks if the entire ViewItem is visible in the scene | [
"checks",
"if",
"the",
"entire",
"ViewItem",
"is",
"visible",
"in",
"the",
"scene"
] | def is_scene_larger_than_image(self):
"""
checks if the entire ViewItem is visible in the scene
"""
port_rect = self.viewport().rect()
scene_rect = self.mapToScene(port_rect).boundingRect()
item_rect = self.pix.mapRectFromScene(scene_rect)
isec = item_rect.intersected(self.pix.boundingRect())
res = self.pix.get_resolution()
if (isec.size().width() >= QSizeF(res).width() and
isec.size().height() >= QSizeF(res).height()):
return True
return False | [
"def",
"is_scene_larger_than_image",
"(",
"self",
")",
":",
"port_rect",
"=",
"self",
".",
"viewport",
"(",
")",
".",
"rect",
"(",
")",
"scene_rect",
"=",
"self",
".",
"mapToScene",
"(",
"port_rect",
")",
".",
"boundingRect",
"(",
")",
"item_rect",
"=",
... | https://github.com/TheImagingSource/tiscamera/blob/baacb4cfaa7858c2e6cfb4f1a297b404c4e002f6/tools/tcam-capture/tcam_capture/TcamScreen.py#L222-L236 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/telemetry/internal/image_processing/screen_finder.py | python | ScreenFinder._GetTransform | (self, corners, border) | return transform, transform_w, transform_h | Gets the perspective transform of the screen.
Args:
corners: The corners of the detected screen.
border: The number of pixels of border to crop along with the screen.
Returns:
A perspective transform and the width and height of the target
transform.
Raises:
ScreenNotFoundError: Something went wrong in detecting the screen. | Gets the perspective transform of the screen. | [
"Gets",
"the",
"perspective",
"transform",
"of",
"the",
"screen",
"."
] | def _GetTransform(self, corners, border):
"""Gets the perspective transform of the screen.
Args:
corners: The corners of the detected screen.
border: The number of pixels of border to crop along with the screen.
Returns:
A perspective transform and the width and height of the target
transform.
Raises:
ScreenNotFoundError: Something went wrong in detecting the screen."""
if self._screen_size is None:
w = np.sqrt(cv_util.SqDistance(corners[1], corners[0]))
h = np.sqrt(cv_util.SqDistance(corners[1], corners[2]))
if w < 1 or h < 1:
raise self.ScreenNotFoundError(
'Screen detected improperly (bad corners)')
if min(w, h) < self.MIN_SCREEN_WIDTH:
raise self.ScreenNotFoundError('Detected screen was too small.')
self._screen_size = (w, h)
# Extend min line length, if we can, to reduce the number of extraneous
# lines the line finder finds.
self._min_line_length = max(self._min_line_length, min(w, h) / 1.75)
w = self._screen_size[0]
h = self._screen_size[1]
target = np.zeros((4, 2), np.float32)
width = w + border
height = h + border
target[0] = np.asfarray((width, border))
target[1] = np.asfarray((border, border))
target[2] = np.asfarray((border, height))
target[3] = np.asfarray((width, height))
transform_w = width + border
transform_h = height + border
transform = cv2.getPerspectiveTransform(corners, target)
return transform, transform_w, transform_h | [
"def",
"_GetTransform",
"(",
"self",
",",
"corners",
",",
"border",
")",
":",
"if",
"self",
".",
"_screen_size",
"is",
"None",
":",
"w",
"=",
"np",
".",
"sqrt",
"(",
"cv_util",
".",
"SqDistance",
"(",
"corners",
"[",
"1",
"]",
",",
"corners",
"[",
... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/internal/image_processing/screen_finder.py#L772-L811 | |
infinit/memo | 3a8394d0f647efe03ccb8bfe885a7279cb8be8a6 | elle/drake/src/drake/__init__.py | python | symlink | (sources, to, strip_prefix = None) | return __copy(
sources, to, strip_prefix, builder, None, None) | Convenience function to create Symlinker builders.
See documentation of copy. | Convenience function to create Symlinker builders. | [
"Convenience",
"function",
"to",
"create",
"Symlinker",
"builders",
"."
] | def symlink(sources, to, strip_prefix = None):
"""Convenience function to create Symlinker builders.
See documentation of copy.
"""
def builder(source, path, post_process, follow_symlinks):
return drake.Symlink(path, source).builder
return __copy(
sources, to, strip_prefix, builder, None, None) | [
"def",
"symlink",
"(",
"sources",
",",
"to",
",",
"strip_prefix",
"=",
"None",
")",
":",
"def",
"builder",
"(",
"source",
",",
"path",
",",
"post_process",
",",
"follow_symlinks",
")",
":",
"return",
"drake",
".",
"Symlink",
"(",
"path",
",",
"source",
... | https://github.com/infinit/memo/blob/3a8394d0f647efe03ccb8bfe885a7279cb8be8a6/elle/drake/src/drake/__init__.py#L3408-L3416 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/pbr/packaging.py | python | LocalEggInfo.find_sources | (self) | Generate SOURCES.txt only if there isn't one already.
If we are in an sdist command, then we always want to update
SOURCES.txt. If we are not in an sdist command, then it doesn't
matter one flip, and is actually destructive.
However, if we're in a git context, it's always the right thing to do
to recreate SOURCES.txt | Generate SOURCES.txt only if there isn't one already. | [
"Generate",
"SOURCES",
".",
"txt",
"only",
"if",
"there",
"isn",
"t",
"one",
"already",
"."
] | def find_sources(self):
"""Generate SOURCES.txt only if there isn't one already.
If we are in an sdist command, then we always want to update
SOURCES.txt. If we are not in an sdist command, then it doesn't
matter one flip, and is actually destructive.
However, if we're in a git context, it's always the right thing to do
to recreate SOURCES.txt
"""
manifest_filename = os.path.join(self.egg_info, "SOURCES.txt")
if (not os.path.exists(manifest_filename) or
os.path.exists('.git') or
'sdist' in sys.argv):
log.info("[pbr] Processing SOURCES.txt")
mm = LocalManifestMaker(self.distribution)
mm.manifest = manifest_filename
mm.run()
self.filelist = mm.filelist
else:
log.info("[pbr] Reusing existing SOURCES.txt")
self.filelist = egg_info.FileList()
for entry in open(manifest_filename, 'r').read().split('\n'):
self.filelist.append(entry) | [
"def",
"find_sources",
"(",
"self",
")",
":",
"manifest_filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"egg_info",
",",
"\"SOURCES.txt\"",
")",
"if",
"(",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"manifest_filename",
")",
"or",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/pbr/packaging.py#L507-L529 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/cython/Cython/Debugger/libpython.py | python | move_in_stack | (move_up) | Move up or down the stack (for the py-up/py-down command) | Move up or down the stack (for the py-up/py-down command) | [
"Move",
"up",
"or",
"down",
"the",
"stack",
"(",
"for",
"the",
"py",
"-",
"up",
"/",
"py",
"-",
"down",
"command",
")"
] | def move_in_stack(move_up):
'''Move up or down the stack (for the py-up/py-down command)'''
frame = Frame.get_selected_python_frame()
if not frame:
print('Unable to locate python frame')
return
while frame:
if move_up:
iter_frame = frame.older()
else:
iter_frame = frame.newer()
if not iter_frame:
break
if iter_frame.is_python_frame():
# Result:
if iter_frame.select():
iter_frame.print_summary()
return
frame = iter_frame
if move_up:
print('Unable to find an older python frame')
else:
print('Unable to find a newer python frame') | [
"def",
"move_in_stack",
"(",
"move_up",
")",
":",
"frame",
"=",
"Frame",
".",
"get_selected_python_frame",
"(",
")",
"if",
"not",
"frame",
":",
"print",
"(",
"'Unable to locate python frame'",
")",
"return",
"while",
"frame",
":",
"if",
"move_up",
":",
"iter_f... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/cython/Cython/Debugger/libpython.py#L1763-L1790 | ||
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/pip/req/req_install.py | python | InstallRequirement.check_if_exists | (self) | return True | Find an installed distribution that satisfies or conflicts
with this requirement, and set self.satisfied_by or
self.conflicts_with appropriately. | Find an installed distribution that satisfies or conflicts
with this requirement, and set self.satisfied_by or
self.conflicts_with appropriately. | [
"Find",
"an",
"installed",
"distribution",
"that",
"satisfies",
"or",
"conflicts",
"with",
"this",
"requirement",
"and",
"set",
"self",
".",
"satisfied_by",
"or",
"self",
".",
"conflicts_with",
"appropriately",
"."
] | def check_if_exists(self):
"""Find an installed distribution that satisfies or conflicts
with this requirement, and set self.satisfied_by or
self.conflicts_with appropriately.
"""
if self.req is None:
return False
try:
self.satisfied_by = pkg_resources.get_distribution(self.req)
except pkg_resources.DistributionNotFound:
return False
except pkg_resources.VersionConflict:
existing_dist = pkg_resources.get_distribution(
self.req.project_name
)
if self.use_user_site:
if dist_in_usersite(existing_dist):
self.conflicts_with = existing_dist
elif (running_under_virtualenv() and
dist_in_site_packages(existing_dist)):
raise InstallationError(
"Will not install to the user site because it will "
"lack sys.path precedence to %s in %s" %
(existing_dist.project_name, existing_dist.location)
)
else:
self.conflicts_with = existing_dist
return True | [
"def",
"check_if_exists",
"(",
"self",
")",
":",
"if",
"self",
".",
"req",
"is",
"None",
":",
"return",
"False",
"try",
":",
"self",
".",
"satisfied_by",
"=",
"pkg_resources",
".",
"get_distribution",
"(",
"self",
".",
"req",
")",
"except",
"pkg_resources"... | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/req/req_install.py#L963-L990 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/control_flow_ops.py | python | WhileContext.AddBackpropLoopCounter | (self, count, outer_grad_state) | return next_count | Add the backprop loop that controls the iterations.
This is added to the backprop loop. It is used to control the loop
termination of the backprop loop. Called in the outer context of
this grad context.
The pseudocode is:
`n = count; while (n >= 1) { n--; }`
Note that a control dependency is added to `final_zero` to ensure the
correct execution order of stack pop ops.
Args:
count: The number of iterations for backprop.
outer_grad_state: The outer grad state. None if not nested.
Returns:
The loop index. | Add the backprop loop that controls the iterations. | [
"Add",
"the",
"backprop",
"loop",
"that",
"controls",
"the",
"iterations",
"."
] | def AddBackpropLoopCounter(self, count, outer_grad_state):
"""Add the backprop loop that controls the iterations.
This is added to the backprop loop. It is used to control the loop
termination of the backprop loop. Called in the outer context of
this grad context.
The pseudocode is:
`n = count; while (n >= 1) { n--; }`
Note that a control dependency is added to `final_zero` to ensure the
correct execution order of stack pop ops.
Args:
count: The number of iterations for backprop.
outer_grad_state: The outer grad state. None if not nested.
Returns:
The loop index.
"""
in_separate_functions = count.graph is not ops.get_default_graph()
if in_separate_functions:
# Brings the count into this graph
count = array_ops.identity(count)
else:
# TODO(apassos) XLA expects this constant to be created outside the loop,
# so doing that for now.
one = constant_op.constant(1, name="b_count")
self.Enter()
self.AddName(count.name)
enter_count = _Enter(
count,
self._name,
is_constant=False,
parallel_iterations=self._parallel_iterations,
name="b_count")
self.loop_enters.append(enter_count)
merge_count = merge([enter_count, enter_count])[0]
self._pivot_for_pred = merge_count
if in_separate_functions:
one = constant_op.constant(1, name="b_count")
pred = math_ops.greater_equal(merge_count, one)
self._pivot = loop_cond(pred, name="b_count")
switch_count = switch(merge_count, self._pivot)
index = math_ops.subtract(switch_count[1], one)
self._pivot_for_body = index
next_count = _NextIteration(index)
merge_count.op._update_input(1, next_count)
final_zero = exit(switch_count[0], name="b_count")
self.loop_exits.append(final_zero)
if outer_grad_state is not None:
# Force the stack pops of i-th execution of an inner loop to be ordered
# before the pops of (i+1)-th execution of the same inner loop.
# pylint: disable=protected-access
outer_grad_state.grad_sync._add_control_input(final_zero.op)
# pylint: enable=protected-access
self.ExitResult([final_zero])
self.Exit()
return next_count | [
"def",
"AddBackpropLoopCounter",
"(",
"self",
",",
"count",
",",
"outer_grad_state",
")",
":",
"in_separate_functions",
"=",
"count",
".",
"graph",
"is",
"not",
"ops",
".",
"get_default_graph",
"(",
")",
"if",
"in_separate_functions",
":",
"# Brings the count into t... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/control_flow_ops.py#L1901-L1965 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_windows.py | python | TextEntryDialog.__init__ | (self, *args, **kwargs) | __init__(self, Window parent, String message, String caption=GetTextFromUserPromptStr,
String defaultValue=EmptyString,
long style=TextEntryDialogStyle, Point pos=DefaultPosition) -> TextEntryDialog
Constructor. Use ShowModal method to show the dialog. | __init__(self, Window parent, String message, String caption=GetTextFromUserPromptStr,
String defaultValue=EmptyString,
long style=TextEntryDialogStyle, Point pos=DefaultPosition) -> TextEntryDialog | [
"__init__",
"(",
"self",
"Window",
"parent",
"String",
"message",
"String",
"caption",
"=",
"GetTextFromUserPromptStr",
"String",
"defaultValue",
"=",
"EmptyString",
"long",
"style",
"=",
"TextEntryDialogStyle",
"Point",
"pos",
"=",
"DefaultPosition",
")",
"-",
">",... | def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, String message, String caption=GetTextFromUserPromptStr,
String defaultValue=EmptyString,
long style=TextEntryDialogStyle, Point pos=DefaultPosition) -> TextEntryDialog
Constructor. Use ShowModal method to show the dialog.
"""
_windows_.TextEntryDialog_swiginit(self,_windows_.new_TextEntryDialog(*args, **kwargs))
self._setOORInfo(self) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_windows_",
".",
"TextEntryDialog_swiginit",
"(",
"self",
",",
"_windows_",
".",
"new_TextEntryDialog",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"self",
"... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_windows.py#L3373-L3382 | ||
gemrb/gemrb | 730206eed8d1dd358ca5e69a62f9e099aa22ffc6 | gemrb/GUIScripts/LUProfsSelection.py | python | ProfsNullify | () | return | Resets all of the internal variables to 0. | Resets all of the internal variables to 0. | [
"Resets",
"all",
"of",
"the",
"internal",
"variables",
"to",
"0",
"."
] | def ProfsNullify ():
"""Resets all of the internal variables to 0."""
global ProfsTable
if not ProfsTable:
ProfsTable = GemRB.LoadTable ("weapprof")
for i in range (ProfsTable.GetRowCount()-ProfsTableOffset+1): #skip bg1 profs
GemRB.SetVar ("Prof "+str(i), 0)
GemRB.SetVar ("ProfBase "+str(i), 0)
return | [
"def",
"ProfsNullify",
"(",
")",
":",
"global",
"ProfsTable",
"if",
"not",
"ProfsTable",
":",
"ProfsTable",
"=",
"GemRB",
".",
"LoadTable",
"(",
"\"weapprof\"",
")",
"for",
"i",
"in",
"range",
"(",
"ProfsTable",
".",
"GetRowCount",
"(",
")",
"-",
"ProfsTab... | https://github.com/gemrb/gemrb/blob/730206eed8d1dd358ca5e69a62f9e099aa22ffc6/gemrb/GUIScripts/LUProfsSelection.py#L468-L477 | |
facebookincubator/BOLT | 88c70afe9d388ad430cc150cc158641701397f70 | clang/bindings/python/clang/cindex.py | python | Cursor.is_const_method | (self) | return conf.lib.clang_CXXMethod_isConst(self) | Returns True if the cursor refers to a C++ member function or member
function template that is declared 'const'. | Returns True if the cursor refers to a C++ member function or member
function template that is declared 'const'. | [
"Returns",
"True",
"if",
"the",
"cursor",
"refers",
"to",
"a",
"C",
"++",
"member",
"function",
"or",
"member",
"function",
"template",
"that",
"is",
"declared",
"const",
"."
] | def is_const_method(self):
"""Returns True if the cursor refers to a C++ member function or member
function template that is declared 'const'.
"""
return conf.lib.clang_CXXMethod_isConst(self) | [
"def",
"is_const_method",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_CXXMethod_isConst",
"(",
"self",
")"
] | https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/clang/bindings/python/clang/cindex.py#L1444-L1448 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/lib/io/file_io.py | python | read_file_to_string | (filename) | return f.read() | Reads the entire contents of a file to a string.
Args:
filename: string, path to a file
Returns:
contents of the file as a string
Raises:
errors.OpError: Raises variety of errors that are subtypes e.g.
NotFoundError etc. | Reads the entire contents of a file to a string. | [
"Reads",
"the",
"entire",
"contents",
"of",
"a",
"file",
"to",
"a",
"string",
"."
] | def read_file_to_string(filename):
"""Reads the entire contents of a file to a string.
Args:
filename: string, path to a file
Returns:
contents of the file as a string
Raises:
errors.OpError: Raises variety of errors that are subtypes e.g.
NotFoundError etc.
"""
f = FileIO(filename, mode="r")
return f.read() | [
"def",
"read_file_to_string",
"(",
"filename",
")",
":",
"f",
"=",
"FileIO",
"(",
"filename",
",",
"mode",
"=",
"\"r\"",
")",
"return",
"f",
".",
"read",
"(",
")"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/lib/io/file_io.py#L206-L220 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/framework/ops.py | python | Operation.name | (self) | The full name of this operation. | The full name of this operation. | [
"The",
"full",
"name",
"of",
"this",
"operation",
"."
] | def name(self):
"""The full name of this operation."""
if self._c_op:
# TODO(iga): Remove this assert after converting to C API by default.
# Just being a bit paranoid here.
assert self._node_def.name == c_api.TF_OperationName(self._c_op)
return c_api.TF_OperationName(self._c_op)
else:
return self._node_def.name | [
"def",
"name",
"(",
"self",
")",
":",
"if",
"self",
".",
"_c_op",
":",
"# TODO(iga): Remove this assert after converting to C API by default.",
"# Just being a bit paranoid here.",
"assert",
"self",
".",
"_node_def",
".",
"name",
"==",
"c_api",
".",
"TF_OperationName",
... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/framework/ops.py#L1647-L1655 | ||
polserver/polserver | b34a9de0e14cb16f1e0d358710a797ad4e42ebdc | clean.py | python | Cleaner.findCmake | (self) | return ret | Returns list of cmake-generated files | Returns list of cmake-generated files | [
"Returns",
"list",
"of",
"cmake",
"-",
"generated",
"files"
] | def findCmake(self):
''' Returns list of cmake-generated files '''
ret = []
def readFolder(path):
r = []
for f in os.listdir(path):
fp = os.path.join(path, f)
if os.path.isdir(fp):
if f == 'CMakeFiles':
ret.append(fp)
elif f != 'testsuite':
ret.extend(readFolder(fp))
else:
if f == 'FindSetEnv.cmake':
pass
elif f in ('Makefile', 'CMakeCache.txt', 'pol_global_config.h'):
ret.append(fp)
elif f.endswith('.cmake'):
ret.append(fp)
return r
ret.extend(readFolder(self.root))
return ret | [
"def",
"findCmake",
"(",
"self",
")",
":",
"ret",
"=",
"[",
"]",
"def",
"readFolder",
"(",
"path",
")",
":",
"r",
"=",
"[",
"]",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
":",
"fp",
"=",
"os",
".",
"path",
".",
"join",
"(",
... | https://github.com/polserver/polserver/blob/b34a9de0e14cb16f1e0d358710a797ad4e42ebdc/clean.py#L53-L74 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/debug/cli/curses_ui.py | python | CursesUI._erase_existing_command | (self) | Erase existing text in command textpad. | Erase existing text in command textpad. | [
"Erase",
"existing",
"text",
"in",
"command",
"textpad",
"."
] | def _erase_existing_command(self):
"""Erase existing text in command textpad."""
existing_len = len(self._command_textbox.gather())
for _ in xrange(existing_len):
self._command_textbox.do_command(self.BACKSPACE_KEY) | [
"def",
"_erase_existing_command",
"(",
"self",
")",
":",
"existing_len",
"=",
"len",
"(",
"self",
".",
"_command_textbox",
".",
"gather",
"(",
")",
")",
"for",
"_",
"in",
"xrange",
"(",
"existing_len",
")",
":",
"self",
".",
"_command_textbox",
".",
"do_co... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/debug/cli/curses_ui.py#L964-L969 | ||
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Node/__init__.py | python | Node.rexists | (self) | return _rexists_map[self._func_rexists](self) | Does this node exist locally or in a repositiory? | Does this node exist locally or in a repositiory? | [
"Does",
"this",
"node",
"exist",
"locally",
"or",
"in",
"a",
"repositiory?"
] | def rexists(self):
"""Does this node exist locally or in a repositiory?"""
# There are no repositories by default:
return _rexists_map[self._func_rexists](self) | [
"def",
"rexists",
"(",
"self",
")",
":",
"# There are no repositories by default:",
"return",
"_rexists_map",
"[",
"self",
".",
"_func_rexists",
"]",
"(",
"self",
")"
] | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Node/__init__.py#L1220-L1223 | |
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/MooseDocs/extensions/core.py | python | CoreExtension.extend | (self, reader, renderer) | Add the extension components. | Add the extension components. | [
"Add",
"the",
"extension",
"components",
"."
] | def extend(self, reader, renderer):
"""
Add the extension components.
"""
# Block tokenize components
reader.addBlock(CodeBlock())
reader.addBlock(QuoteBlock())
reader.addBlock(HeadingBlock())
reader.addBlock(OrderedListBlock())
reader.addBlock(UnorderedListBlock())
reader.addBlock(ShortcutBlock())
reader.addBlock(ParagraphBlock())
reader.addBlock(EndOfFileBlock())
# Inline tokenize components
reader.addInline(EscapeCharacter())
reader.addInline(FormatInline())
reader.addInline(LinkInline())
reader.addInline(ShortcutLinkInline())
reader.addInline(LineBreakInline())
reader.addInline(PunctuationInline())
reader.addInline(NumberInline())
reader.addInline(WordInline())
reader.addInline(BreakInline())
reader.addInline(SpaceInline())
# Render components
renderer.add('Heading', RenderHeading())
renderer.add('Code', RenderCode())
renderer.add('ShortcutLink', RenderShortcutLink())
renderer.add('Shortcut', RenderShortcut())
renderer.add('Monospace', RenderMonospace())
renderer.add('Break', RenderBreak())
renderer.add('LineBreak', RenderLineBreak())
renderer.add('ErrorToken', RenderError())
renderer.add('Link', RenderLink())
renderer.add('Paragraph', RenderParagraph())
renderer.add('UnorderedList', RenderUnorderedList())
renderer.add('OrderedList', RenderOrderedList())
renderer.add('ListItem', RenderListItem())
renderer.add('Quote', RenderQuote())
renderer.add('Strong', RenderStrong())
renderer.add('Underline', RenderUnderline())
renderer.add('Emphasis', RenderEmphasis())
renderer.add('Strikethrough', RenderStrikethrough())
renderer.add('Superscript', RenderSuperscript())
renderer.add('Subscript', RenderSubscript())
renderer.add('Punctuation', RenderPunctuation())
renderer.add('DisabledToken', RenderDisabled())
renderer.add('Space', RenderSpace())
renderer.add('Word', RenderString())
renderer.add('Number', RenderString())
renderer.add('String', RenderString())
#TODO: Make a generic preamble method?
if isinstance(renderer, renderers.LatexRenderer):
renderer.addPackage('amsmath')
renderer.addPackage('soul')
renderer.addPackage('hyperref',
linkcolor='blue',
citecolor='blue',
filecolor='blue',
urlcolor='blue',
colorlinks='true') | [
"def",
"extend",
"(",
"self",
",",
"reader",
",",
"renderer",
")",
":",
"# Block tokenize components",
"reader",
".",
"addBlock",
"(",
"CodeBlock",
"(",
")",
")",
"reader",
".",
"addBlock",
"(",
"QuoteBlock",
"(",
")",
")",
"reader",
".",
"addBlock",
"(",
... | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/MooseDocs/extensions/core.py#L68-L134 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py2/pkg_resources/_vendor/pyparsing.py | python | withAttribute | (*args,**attrDict) | return pa | Helper to create a validating parse action to be used with start tags created
with C{L{makeXMLTags}} or C{L{makeHTMLTags}}. Use C{withAttribute} to qualify a starting tag
with a required attribute value, to avoid false matches on common tags such as
C{<TD>} or C{<DIV>}.
Call C{withAttribute} with a series of attribute names and values. Specify the list
of filter attributes names and values as:
- keyword arguments, as in C{(align="right")}, or
- as an explicit dict with C{**} operator, when an attribute name is also a Python
reserved word, as in C{**{"class":"Customer", "align":"right"}}
- a list of name-value tuples, as in ( ("ns1:class", "Customer"), ("ns2:align","right") )
For attribute names with a namespace prefix, you must use the second form. Attribute
names are matched insensitive to upper/lower case.
If just testing for C{class} (with or without a namespace), use C{L{withClass}}.
To verify that the attribute exists, but without specifying a value, pass
C{withAttribute.ANY_VALUE} as the value.
Example::
html = '''
<div>
Some text
<div type="grid">1 4 0 1 0</div>
<div type="graph">1,3 2,3 1,1</div>
<div>this has no type</div>
</div>
'''
div,div_end = makeHTMLTags("div")
# only match div tag having a type attribute with value "grid"
div_grid = div().setParseAction(withAttribute(type="grid"))
grid_expr = div_grid + SkipTo(div | div_end)("body")
for grid_header in grid_expr.searchString(html):
print(grid_header.body)
# construct a match with any div tag having a type attribute, regardless of the value
div_any_type = div().setParseAction(withAttribute(type=withAttribute.ANY_VALUE))
div_expr = div_any_type + SkipTo(div | div_end)("body")
for div_header in div_expr.searchString(html):
print(div_header.body)
prints::
1 4 0 1 0
1 4 0 1 0
1,3 2,3 1,1 | Helper to create a validating parse action to be used with start tags created
with C{L{makeXMLTags}} or C{L{makeHTMLTags}}. Use C{withAttribute} to qualify a starting tag
with a required attribute value, to avoid false matches on common tags such as
C{<TD>} or C{<DIV>}. | [
"Helper",
"to",
"create",
"a",
"validating",
"parse",
"action",
"to",
"be",
"used",
"with",
"start",
"tags",
"created",
"with",
"C",
"{",
"L",
"{",
"makeXMLTags",
"}}",
"or",
"C",
"{",
"L",
"{",
"makeHTMLTags",
"}}",
".",
"Use",
"C",
"{",
"withAttribut... | def withAttribute(*args,**attrDict):
"""
Helper to create a validating parse action to be used with start tags created
with C{L{makeXMLTags}} or C{L{makeHTMLTags}}. Use C{withAttribute} to qualify a starting tag
with a required attribute value, to avoid false matches on common tags such as
C{<TD>} or C{<DIV>}.
Call C{withAttribute} with a series of attribute names and values. Specify the list
of filter attributes names and values as:
- keyword arguments, as in C{(align="right")}, or
- as an explicit dict with C{**} operator, when an attribute name is also a Python
reserved word, as in C{**{"class":"Customer", "align":"right"}}
- a list of name-value tuples, as in ( ("ns1:class", "Customer"), ("ns2:align","right") )
For attribute names with a namespace prefix, you must use the second form. Attribute
names are matched insensitive to upper/lower case.
If just testing for C{class} (with or without a namespace), use C{L{withClass}}.
To verify that the attribute exists, but without specifying a value, pass
C{withAttribute.ANY_VALUE} as the value.
Example::
html = '''
<div>
Some text
<div type="grid">1 4 0 1 0</div>
<div type="graph">1,3 2,3 1,1</div>
<div>this has no type</div>
</div>
'''
div,div_end = makeHTMLTags("div")
# only match div tag having a type attribute with value "grid"
div_grid = div().setParseAction(withAttribute(type="grid"))
grid_expr = div_grid + SkipTo(div | div_end)("body")
for grid_header in grid_expr.searchString(html):
print(grid_header.body)
# construct a match with any div tag having a type attribute, regardless of the value
div_any_type = div().setParseAction(withAttribute(type=withAttribute.ANY_VALUE))
div_expr = div_any_type + SkipTo(div | div_end)("body")
for div_header in div_expr.searchString(html):
print(div_header.body)
prints::
1 4 0 1 0
1 4 0 1 0
1,3 2,3 1,1
"""
if args:
attrs = args[:]
else:
attrs = attrDict.items()
attrs = [(k,v) for k,v in attrs]
def pa(s,l,tokens):
for attrName,attrValue in attrs:
if attrName not in tokens:
raise ParseException(s,l,"no matching attribute " + attrName)
if attrValue != withAttribute.ANY_VALUE and tokens[attrName] != attrValue:
raise ParseException(s,l,"attribute '%s' has value '%s', must be '%s'" %
(attrName, tokens[attrName], attrValue))
return pa | [
"def",
"withAttribute",
"(",
"*",
"args",
",",
"*",
"*",
"attrDict",
")",
":",
"if",
"args",
":",
"attrs",
"=",
"args",
"[",
":",
"]",
"else",
":",
"attrs",
"=",
"attrDict",
".",
"items",
"(",
")",
"attrs",
"=",
"[",
"(",
"k",
",",
"v",
")",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/pkg_resources/_vendor/pyparsing.py#L4932-L4994 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py2/numpy/lib/npyio.py | python | loadtxt | (fname, dtype=float, comments='#', delimiter=None,
converters=None, skiprows=0, usecols=None, unpack=False,
ndmin=0, encoding='bytes', max_rows=None) | Load data from a text file.
Each row in the text file must have the same number of values.
Parameters
----------
fname : file, str, or pathlib.Path
File, filename, or generator to read. If the filename extension is
``.gz`` or ``.bz2``, the file is first decompressed. Note that
generators should return byte strings for Python 3k.
dtype : data-type, optional
Data-type of the resulting array; default: float. If this is a
structured data-type, the resulting array will be 1-dimensional, and
each row will be interpreted as an element of the array. In this
case, the number of columns used must match the number of fields in
the data-type.
comments : str or sequence of str, optional
The characters or list of characters used to indicate the start of a
comment. None implies no comments. For backwards compatibility, byte
strings will be decoded as 'latin1'. The default is '#'.
delimiter : str, optional
The string used to separate values. For backwards compatibility, byte
strings will be decoded as 'latin1'. The default is whitespace.
converters : dict, optional
A dictionary mapping column number to a function that will parse the
column string into the desired value. E.g., if column 0 is a date
string: ``converters = {0: datestr2num}``. Converters can also be
used to provide a default value for missing data (but see also
`genfromtxt`): ``converters = {3: lambda s: float(s.strip() or 0)}``.
Default: None.
skiprows : int, optional
Skip the first `skiprows` lines; default: 0.
usecols : int or sequence, optional
Which columns to read, with 0 being the first. For example,
``usecols = (1,4,5)`` will extract the 2nd, 5th and 6th columns.
The default, None, results in all columns being read.
.. versionchanged:: 1.11.0
When a single column has to be read it is possible to use
an integer instead of a tuple. E.g ``usecols = 3`` reads the
fourth column the same way as ``usecols = (3,)`` would.
unpack : bool, optional
If True, the returned array is transposed, so that arguments may be
unpacked using ``x, y, z = loadtxt(...)``. When used with a structured
data-type, arrays are returned for each field. Default is False.
ndmin : int, optional
The returned array will have at least `ndmin` dimensions.
Otherwise mono-dimensional axes will be squeezed.
Legal values: 0 (default), 1 or 2.
.. versionadded:: 1.6.0
encoding : str, optional
Encoding used to decode the inputfile. Does not apply to input streams.
The special value 'bytes' enables backward compatibility workarounds
that ensures you receive byte arrays as results if possible and passes
'latin1' encoded strings to converters. Override this value to receive
unicode arrays and pass strings as input to converters. If set to None
the system default is used. The default value is 'bytes'.
.. versionadded:: 1.14.0
max_rows : int, optional
Read `max_rows` lines of content after `skiprows` lines. The default
is to read all the lines.
.. versionadded:: 1.16.0
Returns
-------
out : ndarray
Data read from the text file.
See Also
--------
load, fromstring, fromregex
genfromtxt : Load data with missing values handled as specified.
scipy.io.loadmat : reads MATLAB data files
Notes
-----
This function aims to be a fast reader for simply formatted files. The
`genfromtxt` function provides more sophisticated handling of, e.g.,
lines with missing values.
.. versionadded:: 1.10.0
The strings produced by the Python float.hex method can be used as
input for floats.
Examples
--------
>>> from io import StringIO # StringIO behaves like a file object
>>> c = StringIO(u"0 1\\n2 3")
>>> np.loadtxt(c)
array([[ 0., 1.],
[ 2., 3.]])
>>> d = StringIO(u"M 21 72\\nF 35 58")
>>> np.loadtxt(d, dtype={'names': ('gender', 'age', 'weight'),
... 'formats': ('S1', 'i4', 'f4')})
array([('M', 21, 72.0), ('F', 35, 58.0)],
dtype=[('gender', '|S1'), ('age', '<i4'), ('weight', '<f4')])
>>> c = StringIO(u"1,0,2\\n3,0,4")
>>> x, y = np.loadtxt(c, delimiter=',', usecols=(0, 2), unpack=True)
>>> x
array([ 1., 3.])
>>> y
array([ 2., 4.]) | Load data from a text file. | [
"Load",
"data",
"from",
"a",
"text",
"file",
"."
] | def loadtxt(fname, dtype=float, comments='#', delimiter=None,
converters=None, skiprows=0, usecols=None, unpack=False,
ndmin=0, encoding='bytes', max_rows=None):
"""
Load data from a text file.
Each row in the text file must have the same number of values.
Parameters
----------
fname : file, str, or pathlib.Path
File, filename, or generator to read. If the filename extension is
``.gz`` or ``.bz2``, the file is first decompressed. Note that
generators should return byte strings for Python 3k.
dtype : data-type, optional
Data-type of the resulting array; default: float. If this is a
structured data-type, the resulting array will be 1-dimensional, and
each row will be interpreted as an element of the array. In this
case, the number of columns used must match the number of fields in
the data-type.
comments : str or sequence of str, optional
The characters or list of characters used to indicate the start of a
comment. None implies no comments. For backwards compatibility, byte
strings will be decoded as 'latin1'. The default is '#'.
delimiter : str, optional
The string used to separate values. For backwards compatibility, byte
strings will be decoded as 'latin1'. The default is whitespace.
converters : dict, optional
A dictionary mapping column number to a function that will parse the
column string into the desired value. E.g., if column 0 is a date
string: ``converters = {0: datestr2num}``. Converters can also be
used to provide a default value for missing data (but see also
`genfromtxt`): ``converters = {3: lambda s: float(s.strip() or 0)}``.
Default: None.
skiprows : int, optional
Skip the first `skiprows` lines; default: 0.
usecols : int or sequence, optional
Which columns to read, with 0 being the first. For example,
``usecols = (1,4,5)`` will extract the 2nd, 5th and 6th columns.
The default, None, results in all columns being read.
.. versionchanged:: 1.11.0
When a single column has to be read it is possible to use
an integer instead of a tuple. E.g ``usecols = 3`` reads the
fourth column the same way as ``usecols = (3,)`` would.
unpack : bool, optional
If True, the returned array is transposed, so that arguments may be
unpacked using ``x, y, z = loadtxt(...)``. When used with a structured
data-type, arrays are returned for each field. Default is False.
ndmin : int, optional
The returned array will have at least `ndmin` dimensions.
Otherwise mono-dimensional axes will be squeezed.
Legal values: 0 (default), 1 or 2.
.. versionadded:: 1.6.0
encoding : str, optional
Encoding used to decode the inputfile. Does not apply to input streams.
The special value 'bytes' enables backward compatibility workarounds
that ensures you receive byte arrays as results if possible and passes
'latin1' encoded strings to converters. Override this value to receive
unicode arrays and pass strings as input to converters. If set to None
the system default is used. The default value is 'bytes'.
.. versionadded:: 1.14.0
max_rows : int, optional
Read `max_rows` lines of content after `skiprows` lines. The default
is to read all the lines.
.. versionadded:: 1.16.0
Returns
-------
out : ndarray
Data read from the text file.
See Also
--------
load, fromstring, fromregex
genfromtxt : Load data with missing values handled as specified.
scipy.io.loadmat : reads MATLAB data files
Notes
-----
This function aims to be a fast reader for simply formatted files. The
`genfromtxt` function provides more sophisticated handling of, e.g.,
lines with missing values.
.. versionadded:: 1.10.0
The strings produced by the Python float.hex method can be used as
input for floats.
Examples
--------
>>> from io import StringIO # StringIO behaves like a file object
>>> c = StringIO(u"0 1\\n2 3")
>>> np.loadtxt(c)
array([[ 0., 1.],
[ 2., 3.]])
>>> d = StringIO(u"M 21 72\\nF 35 58")
>>> np.loadtxt(d, dtype={'names': ('gender', 'age', 'weight'),
... 'formats': ('S1', 'i4', 'f4')})
array([('M', 21, 72.0), ('F', 35, 58.0)],
dtype=[('gender', '|S1'), ('age', '<i4'), ('weight', '<f4')])
>>> c = StringIO(u"1,0,2\\n3,0,4")
>>> x, y = np.loadtxt(c, delimiter=',', usecols=(0, 2), unpack=True)
>>> x
array([ 1., 3.])
>>> y
array([ 2., 4.])
"""
# Type conversions for Py3 convenience
if comments is not None:
if isinstance(comments, (basestring, bytes)):
comments = [comments]
comments = [_decode_line(x) for x in comments]
# Compile regex for comments beforehand
comments = (re.escape(comment) for comment in comments)
regex_comments = re.compile('|'.join(comments))
if delimiter is not None:
delimiter = _decode_line(delimiter)
user_converters = converters
if encoding == 'bytes':
encoding = None
byte_converters = True
else:
byte_converters = False
if usecols is not None:
# Allow usecols to be a single int or a sequence of ints
try:
usecols_as_list = list(usecols)
except TypeError:
usecols_as_list = [usecols]
for col_idx in usecols_as_list:
try:
opindex(col_idx)
except TypeError as e:
e.args = (
"usecols must be an int or a sequence of ints but "
"it contains at least one element of type %s" %
type(col_idx),
)
raise
# Fall back to existing code
usecols = usecols_as_list
fown = False
try:
if isinstance(fname, os_PathLike):
fname = os_fspath(fname)
if _is_string_like(fname):
fh = np.lib._datasource.open(fname, 'rt', encoding=encoding)
fencoding = getattr(fh, 'encoding', 'latin1')
fh = iter(fh)
fown = True
else:
fh = iter(fname)
fencoding = getattr(fname, 'encoding', 'latin1')
except TypeError:
raise ValueError('fname must be a string, file handle, or generator')
# input may be a python2 io stream
if encoding is not None:
fencoding = encoding
# we must assume local encoding
# TODO emit portability warning?
elif fencoding is None:
import locale
fencoding = locale.getpreferredencoding()
# not to be confused with the flatten_dtype we import...
@recursive
def flatten_dtype_internal(self, dt):
"""Unpack a structured data-type, and produce re-packing info."""
if dt.names is None:
# If the dtype is flattened, return.
# If the dtype has a shape, the dtype occurs
# in the list more than once.
shape = dt.shape
if len(shape) == 0:
return ([dt.base], None)
else:
packing = [(shape[-1], list)]
if len(shape) > 1:
for dim in dt.shape[-2::-1]:
packing = [(dim*packing[0][0], packing*dim)]
return ([dt.base] * int(np.prod(dt.shape)), packing)
else:
types = []
packing = []
for field in dt.names:
tp, bytes = dt.fields[field]
flat_dt, flat_packing = self(tp)
types.extend(flat_dt)
# Avoid extra nesting for subarrays
if tp.ndim > 0:
packing.extend(flat_packing)
else:
packing.append((len(flat_dt), flat_packing))
return (types, packing)
@recursive
def pack_items(self, items, packing):
"""Pack items into nested lists based on re-packing info."""
if packing is None:
return items[0]
elif packing is tuple:
return tuple(items)
elif packing is list:
return list(items)
else:
start = 0
ret = []
for length, subpacking in packing:
ret.append(self(items[start:start+length], subpacking))
start += length
return tuple(ret)
def split_line(line):
"""Chop off comments, strip, and split at delimiter. """
line = _decode_line(line, encoding=encoding)
if comments is not None:
line = regex_comments.split(line, maxsplit=1)[0]
line = line.strip('\r\n')
if line:
return line.split(delimiter)
else:
return []
def read_data(chunk_size):
"""Parse each line, including the first.
The file read, `fh`, is a global defined above.
Parameters
----------
chunk_size : int
At most `chunk_size` lines are read at a time, with iteration
until all lines are read.
"""
X = []
line_iter = itertools.chain([first_line], fh)
line_iter = itertools.islice(line_iter, max_rows)
for i, line in enumerate(line_iter):
vals = split_line(line)
if len(vals) == 0:
continue
if usecols:
vals = [vals[j] for j in usecols]
if len(vals) != N:
line_num = i + skiprows + 1
raise ValueError("Wrong number of columns at line %d"
% line_num)
# Convert each value according to its column and store
items = [conv(val) for (conv, val) in zip(converters, vals)]
# Then pack it according to the dtype's nesting
items = pack_items(items, packing)
X.append(items)
if len(X) > chunk_size:
yield X
X = []
if X:
yield X
try:
# Make sure we're dealing with a proper dtype
dtype = np.dtype(dtype)
defconv = _getconv(dtype)
# Skip the first `skiprows` lines
for i in range(skiprows):
next(fh)
# Read until we find a line with some values, and use
# it to estimate the number of columns, N.
first_vals = None
try:
while not first_vals:
first_line = next(fh)
first_vals = split_line(first_line)
except StopIteration:
# End of lines reached
first_line = ''
first_vals = []
warnings.warn('loadtxt: Empty input file: "%s"' % fname, stacklevel=2)
N = len(usecols or first_vals)
dtype_types, packing = flatten_dtype_internal(dtype)
if len(dtype_types) > 1:
# We're dealing with a structured array, each field of
# the dtype matches a column
converters = [_getconv(dt) for dt in dtype_types]
else:
# All fields have the same dtype
converters = [defconv for i in range(N)]
if N > 1:
packing = [(N, tuple)]
# By preference, use the converters specified by the user
for i, conv in (user_converters or {}).items():
if usecols:
try:
i = usecols.index(i)
except ValueError:
# Unused converter specified
continue
if byte_converters:
# converters may use decode to workaround numpy's old behaviour,
# so encode the string again before passing to the user converter
def tobytes_first(x, conv):
if type(x) is bytes:
return conv(x)
return conv(x.encode("latin1"))
import functools
converters[i] = functools.partial(tobytes_first, conv=conv)
else:
converters[i] = conv
converters = [conv if conv is not bytes else
lambda x: x.encode(fencoding) for conv in converters]
# read data in chunks and fill it into an array via resize
# over-allocating and shrinking the array later may be faster but is
# probably not relevant compared to the cost of actually reading and
# converting the data
X = None
for x in read_data(_loadtxt_chunksize):
if X is None:
X = np.array(x, dtype)
else:
nshape = list(X.shape)
pos = nshape[0]
nshape[0] += len(x)
X.resize(nshape, refcheck=False)
X[pos:, ...] = x
finally:
if fown:
fh.close()
if X is None:
X = np.array([], dtype)
# Multicolumn data are returned with shape (1, N, M), i.e.
# (1, 1, M) for a single row - remove the singleton dimension there
if X.ndim == 3 and X.shape[:2] == (1, 1):
X.shape = (1, -1)
# Verify that the array has at least dimensions `ndmin`.
# Check correctness of the values of `ndmin`
if ndmin not in [0, 1, 2]:
raise ValueError('Illegal value of ndmin keyword: %s' % ndmin)
# Tweak the size and shape of the arrays - remove extraneous dimensions
if X.ndim > ndmin:
X = np.squeeze(X)
# and ensure we have the minimum number of dimensions asked for
# - has to be in this order for the odd case ndmin=1, X.squeeze().ndim=0
if X.ndim < ndmin:
if ndmin == 1:
X = np.atleast_1d(X)
elif ndmin == 2:
X = np.atleast_2d(X).T
if unpack:
if len(dtype_types) > 1:
# For structured arrays, return an array for each field.
return [X[field] for field in dtype.names]
else:
return X.T
else:
return X | [
"def",
"loadtxt",
"(",
"fname",
",",
"dtype",
"=",
"float",
",",
"comments",
"=",
"'#'",
",",
"delimiter",
"=",
"None",
",",
"converters",
"=",
"None",
",",
"skiprows",
"=",
"0",
",",
"usecols",
"=",
"None",
",",
"unpack",
"=",
"False",
",",
"ndmin",... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/lib/npyio.py#L804-L1184 | ||
KhronosGroup/Vulkan-Headers | b32da5329b50e3cb96229aaecba9ded032fe29cc | registry/vkconventions.py | python | VulkanConventions.null | (self) | return '`NULL`' | Preferred spelling of NULL. | Preferred spelling of NULL. | [
"Preferred",
"spelling",
"of",
"NULL",
"."
] | def null(self):
"""Preferred spelling of NULL."""
return '`NULL`' | [
"def",
"null",
"(",
"self",
")",
":",
"return",
"'`NULL`'"
] | https://github.com/KhronosGroup/Vulkan-Headers/blob/b32da5329b50e3cb96229aaecba9ded032fe29cc/registry/vkconventions.py#L48-L50 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/gaussian_process/kernels.py | python | Exponentiation.hyperparameters | (self) | return r | Returns a list of all hyperparameter. | Returns a list of all hyperparameter. | [
"Returns",
"a",
"list",
"of",
"all",
"hyperparameter",
"."
] | def hyperparameters(self):
"""Returns a list of all hyperparameter."""
r = []
for hyperparameter in self.kernel.hyperparameters:
r.append(Hyperparameter("kernel__" + hyperparameter.name,
hyperparameter.value_type,
hyperparameter.bounds,
hyperparameter.n_elements))
return r | [
"def",
"hyperparameters",
"(",
"self",
")",
":",
"r",
"=",
"[",
"]",
"for",
"hyperparameter",
"in",
"self",
".",
"kernel",
".",
"hyperparameters",
":",
"r",
".",
"append",
"(",
"Hyperparameter",
"(",
"\"kernel__\"",
"+",
"hyperparameter",
".",
"name",
",",... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/gaussian_process/kernels.py#L825-L833 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/internals/construction.py | python | _finalize_columns_and_data | (
content: np.ndarray, # ndim == 2
columns: Index | None,
dtype: DtypeObj | None,
) | return contents, columns | Ensure we have valid columns, cast object dtypes if possible. | Ensure we have valid columns, cast object dtypes if possible. | [
"Ensure",
"we",
"have",
"valid",
"columns",
"cast",
"object",
"dtypes",
"if",
"possible",
"."
] | def _finalize_columns_and_data(
content: np.ndarray, # ndim == 2
columns: Index | None,
dtype: DtypeObj | None,
) -> tuple[list[ArrayLike], Index]:
"""
Ensure we have valid columns, cast object dtypes if possible.
"""
contents = list(content.T)
try:
columns = _validate_or_indexify_columns(contents, columns)
except AssertionError as err:
# GH#26429 do not raise user-facing AssertionError
raise ValueError(err) from err
if len(contents) and contents[0].dtype == np.object_:
contents = _convert_object_array(contents, dtype=dtype)
return contents, columns | [
"def",
"_finalize_columns_and_data",
"(",
"content",
":",
"np",
".",
"ndarray",
",",
"# ndim == 2",
"columns",
":",
"Index",
"|",
"None",
",",
"dtype",
":",
"DtypeObj",
"|",
"None",
",",
")",
"->",
"tuple",
"[",
"list",
"[",
"ArrayLike",
"]",
",",
"Index... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/internals/construction.py#L895-L914 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/distributed/fleet/meta_optimizers/sharding/utils.py | python | fuse_opt_broadcast_param_ops | (block,
ring_id,
shard,
op_role=OpRole.Optimize,
strategy=None) | fuse optimizer sharding broadcast param ops | fuse optimizer sharding broadcast param ops | [
"fuse",
"optimizer",
"sharding",
"broadcast",
"param",
"ops"
] | def fuse_opt_broadcast_param_ops(block,
ring_id,
shard,
op_role=OpRole.Optimize,
strategy=None):
"""
fuse optimizer sharding broadcast param ops
"""
if strategy is None or not strategy.fuse_all_reduce_ops:
return
fuse_size = strategy.fuse_grad_size_in_MB
nranks = shard.worker_num
device_to_vars = [[] for _ in range(nranks)]
for idx, op in reversed(list(enumerate(block.ops))):
if not is_optimizer_op(op) or op.type != 'c_broadcast':
break
var = op.input_arg_names[0]
root_id = op.attr('root')
device_to_vars[root_id].insert(0, var)
block._remove_op(idx, sync=False)
insert_idx = idx + 1
for root_id, vars_name in enumerate(device_to_vars):
vars_name = FuseHelper.sort_vars_by_dtype(block, vars_name)
groups = FuseHelper.get_fused_groups(block, vars_name, fuse_size)
fused_vars, insert_num = FuseHelper.insert_coalesce_tensor(
block, insert_idx, groups, op_role, prefix="Param")
for fused_var in fused_vars:
block._insert_op_without_sync(
insert_idx + insert_num,
type='c_broadcast',
inputs={'X': fused_var},
outputs={'Out': fused_var},
attrs={
'ring_id': ring_id,
'root': root_id,
'use_calc_stream': True,
OP_ROLE_KEY: op_role
})
block._sync_with_cpp() | [
"def",
"fuse_opt_broadcast_param_ops",
"(",
"block",
",",
"ring_id",
",",
"shard",
",",
"op_role",
"=",
"OpRole",
".",
"Optimize",
",",
"strategy",
"=",
"None",
")",
":",
"if",
"strategy",
"is",
"None",
"or",
"not",
"strategy",
".",
"fuse_all_reduce_ops",
":... | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/distributed/fleet/meta_optimizers/sharding/utils.py#L660-L705 | ||
google/llvm-propeller | 45c226984fe8377ebfb2ad7713c680d652ba678d | lldb/third_party/Python/module/ptyprocess-0.6.0/ptyprocess/ptyprocess.py | python | PtyProcess.getwinsize | (self) | return struct.unpack('HHHH', x)[0:2] | Return the window size of the pseudoterminal as a tuple (rows, cols). | Return the window size of the pseudoterminal as a tuple (rows, cols). | [
"Return",
"the",
"window",
"size",
"of",
"the",
"pseudoterminal",
"as",
"a",
"tuple",
"(",
"rows",
"cols",
")",
"."
] | def getwinsize(self):
"""Return the window size of the pseudoterminal as a tuple (rows, cols).
"""
TIOCGWINSZ = getattr(termios, 'TIOCGWINSZ', 1074295912)
s = struct.pack('HHHH', 0, 0, 0, 0)
x = fcntl.ioctl(self.fd, TIOCGWINSZ, s)
return struct.unpack('HHHH', x)[0:2] | [
"def",
"getwinsize",
"(",
"self",
")",
":",
"TIOCGWINSZ",
"=",
"getattr",
"(",
"termios",
",",
"'TIOCGWINSZ'",
",",
"1074295912",
")",
"s",
"=",
"struct",
".",
"pack",
"(",
"'HHHH'",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
")",
"x",
"=",
"fcntl",
... | https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/lldb/third_party/Python/module/ptyprocess-0.6.0/ptyprocess/ptyprocess.py#L774-L780 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/learn/python/learn/estimators/_sklearn.py | python | _BaseEstimator.get_params | (self, deep=True) | return out | Get parameters for this estimator.
Args:
deep: boolean, optional
If `True`, will return the parameters for this estimator and
contained subobjects that are estimators.
Returns:
params : mapping of string to any
Parameter names mapped to their values. | Get parameters for this estimator. | [
"Get",
"parameters",
"for",
"this",
"estimator",
"."
] | def get_params(self, deep=True):
"""Get parameters for this estimator.
Args:
deep: boolean, optional
If `True`, will return the parameters for this estimator and
contained subobjects that are estimators.
Returns:
params : mapping of string to any
Parameter names mapped to their values.
"""
out = dict()
param_names = [name for name in self.__dict__ if not name.startswith('_')]
for key in param_names:
value = getattr(self, key, None)
if isinstance(value, collections.Callable):
continue
# XXX: should we rather test if instance of estimator?
if deep and hasattr(value, 'get_params'):
deep_items = value.get_params().items()
out.update((key + '__' + k, val) for k, val in deep_items)
out[key] = value
return out | [
"def",
"get_params",
"(",
"self",
",",
"deep",
"=",
"True",
")",
":",
"out",
"=",
"dict",
"(",
")",
"param_names",
"=",
"[",
"name",
"for",
"name",
"in",
"self",
".",
"__dict__",
"if",
"not",
"name",
".",
"startswith",
"(",
"'_'",
")",
"]",
"for",
... | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/learn/python/learn/estimators/_sklearn.py#L40-L66 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/msvc.py | python | SystemInfo._find_latest_available_vs_ver | (self) | return sorted(vc_vers)[-1] | Find the latest VC version
Return
------
float
version | Find the latest VC version | [
"Find",
"the",
"latest",
"VC",
"version"
] | def _find_latest_available_vs_ver(self):
"""
Find the latest VC version
Return
------
float
version
"""
reg_vc_vers = self.find_reg_vs_vers()
if not (reg_vc_vers or self.known_vs_paths):
raise distutils.errors.DistutilsPlatformError(
'No Microsoft Visual C++ version found')
vc_vers = set(reg_vc_vers)
vc_vers.update(self.known_vs_paths)
return sorted(vc_vers)[-1] | [
"def",
"_find_latest_available_vs_ver",
"(",
"self",
")",
":",
"reg_vc_vers",
"=",
"self",
".",
"find_reg_vs_vers",
"(",
")",
"if",
"not",
"(",
"reg_vc_vers",
"or",
"self",
".",
"known_vs_paths",
")",
":",
"raise",
"distutils",
".",
"errors",
".",
"DistutilsPl... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/msvc.py#L692-L709 | |
pybox2d/pybox2d | 09643321fd363f0850087d1bde8af3f4afd82163 | library/Box2D/examples/framework.py | python | FrameworkBase.Step | (self, settings) | The main physics step.
Takes care of physics drawing (callbacks are executed after the world.Step() )
and drawing additional information. | The main physics step. | [
"The",
"main",
"physics",
"step",
"."
] | def Step(self, settings):
"""
The main physics step.
Takes care of physics drawing (callbacks are executed after the world.Step() )
and drawing additional information.
"""
self.stepCount += 1
# Don't do anything if the setting's Hz are <= 0
if settings.hz > 0.0:
timeStep = 1.0 / settings.hz
else:
timeStep = 0.0
renderer = self.renderer
# If paused, display so
if settings.pause:
if settings.singleStep:
settings.singleStep = False
else:
timeStep = 0.0
self.Print("****PAUSED****", (200, 0, 0))
# Set the flags based on what the settings show
if renderer:
# convertVertices is only applicable when using b2DrawExtended. It
# indicates that the C code should transform box2d coords to screen
# coordinates.
is_extended = isinstance(renderer, b2DrawExtended)
renderer.flags = dict(drawShapes=settings.drawShapes,
drawJoints=settings.drawJoints,
drawAABBs=settings.drawAABBs,
drawPairs=settings.drawPairs,
drawCOMs=settings.drawCOMs,
convertVertices=is_extended,
)
# Set the other settings that aren't contained in the flags
self.world.warmStarting = settings.enableWarmStarting
self.world.continuousPhysics = settings.enableContinuous
self.world.subStepping = settings.enableSubStepping
# Reset the collision points
self.points = []
# Tell Box2D to step
t_step = time()
self.world.Step(timeStep, settings.velocityIterations,
settings.positionIterations)
self.world.ClearForces()
t_step = time() - t_step
# Update the debug draw settings so that the vertices will be properly
# converted to screen coordinates
t_draw = time()
if renderer is not None:
renderer.StartDraw()
self.world.DrawDebugData()
# If the bomb is frozen, get rid of it.
if self.bomb and not self.bomb.awake:
self.world.DestroyBody(self.bomb)
self.bomb = None
# Take care of additional drawing (fps, mouse joint, slingshot bomb,
# contact points)
if renderer:
# If there's a mouse joint, draw the connection between the object
# and the current pointer position.
if self.mouseJoint:
p1 = renderer.to_screen(self.mouseJoint.anchorB)
p2 = renderer.to_screen(self.mouseJoint.target)
renderer.DrawPoint(p1, settings.pointSize,
self.colors['mouse_point'])
renderer.DrawPoint(p2, settings.pointSize,
self.colors['mouse_point'])
renderer.DrawSegment(p1, p2, self.colors['joint_line'])
# Draw the slingshot bomb
if self.bombSpawning:
renderer.DrawPoint(renderer.to_screen(self.bombSpawnPoint),
settings.pointSize, self.colors['bomb_center'])
renderer.DrawSegment(renderer.to_screen(self.bombSpawnPoint),
renderer.to_screen(self.mouseWorld),
self.colors['bomb_line'])
# Draw each of the contact points in different colors.
if self.settings.drawContactPoints:
for point in self.points:
if point['state'] == b2_addState:
renderer.DrawPoint(renderer.to_screen(point['position']),
settings.pointSize,
self.colors['contact_add'])
elif point['state'] == b2_persistState:
renderer.DrawPoint(renderer.to_screen(point['position']),
settings.pointSize,
self.colors['contact_persist'])
if settings.drawContactNormals:
for point in self.points:
p1 = renderer.to_screen(point['position'])
p2 = renderer.axisScale * point['normal'] + p1
renderer.DrawSegment(p1, p2, self.colors['contact_normal'])
renderer.EndDraw()
t_draw = time() - t_draw
t_draw = max(b2_epsilon, t_draw)
t_step = max(b2_epsilon, t_step)
try:
self.t_draws.append(1.0 / t_draw)
except:
pass
else:
if len(self.t_draws) > 2:
self.t_draws.pop(0)
try:
self.t_steps.append(1.0 / t_step)
except:
pass
else:
if len(self.t_steps) > 2:
self.t_steps.pop(0)
if settings.drawFPS:
self.Print("Combined FPS %d" % self.fps)
if settings.drawStats:
self.Print("bodies=%d contacts=%d joints=%d proxies=%d" %
(self.world.bodyCount, self.world.contactCount,
self.world.jointCount, self.world.proxyCount))
self.Print("hz %d vel/pos iterations %d/%d" %
(settings.hz, settings.velocityIterations,
settings.positionIterations))
if self.t_draws and self.t_steps:
self.Print("Potential draw rate: %.2f fps Step rate: %.2f Hz"
"" % (sum(self.t_draws) / len(self.t_draws),
sum(self.t_steps) / len(self.t_steps))
) | [
"def",
"Step",
"(",
"self",
",",
"settings",
")",
":",
"self",
".",
"stepCount",
"+=",
"1",
"# Don't do anything if the setting's Hz are <= 0",
"if",
"settings",
".",
"hz",
">",
"0.0",
":",
"timeStep",
"=",
"1.0",
"/",
"settings",
".",
"hz",
"else",
":",
"... | https://github.com/pybox2d/pybox2d/blob/09643321fd363f0850087d1bde8af3f4afd82163/library/Box2D/examples/framework.py#L139-L288 | ||
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBTypeCategory.__str__ | (self) | return _lldb.SBTypeCategory___str__(self) | __str__(self) -> PyObject | __str__(self) -> PyObject | [
"__str__",
"(",
"self",
")",
"-",
">",
"PyObject"
] | def __str__(self):
"""__str__(self) -> PyObject"""
return _lldb.SBTypeCategory___str__(self) | [
"def",
"__str__",
"(",
"self",
")",
":",
"return",
"_lldb",
".",
"SBTypeCategory___str__",
"(",
"self",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L10976-L10978 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.