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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
gromacs/gromacs | 7dec3a3f99993cf5687a122de3e12de31c21c399 | scripts/make_gromos_rtp.py | python | Cin.getNBA | (self, res) | Get bond angles | Get bond angles | [
"Get",
"bond",
"angles"
] | def getNBA(self, res):
" Get bond angles"
self.ba = []
ind = self.gets(res, NBA)
self.nba = atoi(split(res[ind+1])[0])
j = 0
for i in range(self.nba):
line = split(res[ind+i+j+3])
if line[0] == '#':
line = split(res[ind+i+j+4])
j = j + 1
self.ba.append(line) | [
"def",
"getNBA",
"(",
"self",
",",
"res",
")",
":",
"self",
".",
"ba",
"=",
"[",
"]",
"ind",
"=",
"self",
".",
"gets",
"(",
"res",
",",
"NBA",
")",
"self",
".",
"nba",
"=",
"atoi",
"(",
"split",
"(",
"res",
"[",
"ind",
"+",
"1",
"]",
")",
... | https://github.com/gromacs/gromacs/blob/7dec3a3f99993cf5687a122de3e12de31c21c399/scripts/make_gromos_rtp.py#L192-L203 | ||
SequoiaDB/SequoiaDB | 2894ed7e5bd6fe57330afc900cf76d0ff0df9f64 | tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py | python | xmlDoc.dump | (self, f) | return ret | Dump an XML document to an open FILE. | Dump an XML document to an open FILE. | [
"Dump",
"an",
"XML",
"document",
"to",
"an",
"open",
"FILE",
"."
] | def dump(self, f):
"""Dump an XML document to an open FILE. """
ret = libxml2mod.xmlDocDump(f, self._o)
return ret | [
"def",
"dump",
"(",
"self",
",",
"f",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlDocDump",
"(",
"f",
",",
"self",
".",
"_o",
")",
"return",
"ret"
] | https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L4206-L4209 | |
wywu/LAB | 4b6debd302ae109fd104d4dd04dccc3418ae7471 | python/caffe/coord_map.py | python | conv_params | (fn) | return (axis, np.array(params.get('stride', 1), ndmin=1),
(ks - 1) * dilation + 1,
np.array(params.get('pad', 0), ndmin=1)) | Extract the spatial parameters that determine the coordinate mapping:
kernel size, stride, padding, and dilation.
Implementation detail: Convolution, Deconvolution, and Im2col layers
define these in the convolution_param message, while Pooling has its
own fields in pooling_param. This method deals with these details to
extract canonical parameters. | Extract the spatial parameters that determine the coordinate mapping:
kernel size, stride, padding, and dilation. | [
"Extract",
"the",
"spatial",
"parameters",
"that",
"determine",
"the",
"coordinate",
"mapping",
":",
"kernel",
"size",
"stride",
"padding",
"and",
"dilation",
"."
] | def conv_params(fn):
"""
Extract the spatial parameters that determine the coordinate mapping:
kernel size, stride, padding, and dilation.
Implementation detail: Convolution, Deconvolution, and Im2col layers
define these in the convolution_param message, while Pooling has its
own fields in pooling_param. This method deals with these details to
extract canonical parameters.
"""
params = fn.params.get('convolution_param', fn.params)
axis = params.get('axis', 1)
ks = np.array(params['kernel_size'], ndmin=1)
dilation = np.array(params.get('dilation', 1), ndmin=1)
assert len({'pad_h', 'pad_w', 'kernel_h', 'kernel_w', 'stride_h',
'stride_w'} & set(fn.params)) == 0, \
'cropping does not support legacy _h/_w params'
return (axis, np.array(params.get('stride', 1), ndmin=1),
(ks - 1) * dilation + 1,
np.array(params.get('pad', 0), ndmin=1)) | [
"def",
"conv_params",
"(",
"fn",
")",
":",
"params",
"=",
"fn",
".",
"params",
".",
"get",
"(",
"'convolution_param'",
",",
"fn",
".",
"params",
")",
"axis",
"=",
"params",
".",
"get",
"(",
"'axis'",
",",
"1",
")",
"ks",
"=",
"np",
".",
"array",
... | https://github.com/wywu/LAB/blob/4b6debd302ae109fd104d4dd04dccc3418ae7471/python/caffe/coord_map.py#L18-L37 | |
facebookincubator/BOLT | 88c70afe9d388ad430cc150cc158641701397f70 | lldb/utils/lui/lldbutil.py | python | run_break_set_by_symbol | (
test,
symbol,
extra_options=None,
num_expected_locations=-1,
sym_exact=False,
module_name=None) | return get_bpno_from_match(break_results) | Set a breakpoint by symbol name. Common options are the same as run_break_set_by_file_and_line.
If sym_exact is true, then the output symbol must match the input exactly, otherwise we do a substring match. | Set a breakpoint by symbol name. Common options are the same as run_break_set_by_file_and_line. | [
"Set",
"a",
"breakpoint",
"by",
"symbol",
"name",
".",
"Common",
"options",
"are",
"the",
"same",
"as",
"run_break_set_by_file_and_line",
"."
] | def run_break_set_by_symbol(
test,
symbol,
extra_options=None,
num_expected_locations=-1,
sym_exact=False,
module_name=None):
"""Set a breakpoint by symbol name. Common options are the same as run_break_set_by_file_and_line.
If sym_exact is true, then the output symbol must match the input exactly, otherwise we do a substring match."""
command = 'breakpoint set -n "%s"' % (symbol)
if module_name:
command += " --shlib '%s'" % (module_name)
if extra_options:
command += " " + extra_options
break_results = run_break_set_command(test, command)
if num_expected_locations == 1 and sym_exact:
check_breakpoint_result(
test,
break_results,
num_locations=num_expected_locations,
symbol_name=symbol,
module_name=module_name)
else:
check_breakpoint_result(
test,
break_results,
num_locations=num_expected_locations)
return get_bpno_from_match(break_results) | [
"def",
"run_break_set_by_symbol",
"(",
"test",
",",
"symbol",
",",
"extra_options",
"=",
"None",
",",
"num_expected_locations",
"=",
"-",
"1",
",",
"sym_exact",
"=",
"False",
",",
"module_name",
"=",
"None",
")",
":",
"command",
"=",
"'breakpoint set -n \"%s\"'"... | https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/lldb/utils/lui/lldbutil.py#L367-L400 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/lib-tk/Tkinter.py | python | Menu.index | (self, index) | return getint(i) | Return the index of a menu item identified by INDEX. | Return the index of a menu item identified by INDEX. | [
"Return",
"the",
"index",
"of",
"a",
"menu",
"item",
"identified",
"by",
"INDEX",
"."
] | def index(self, index):
"""Return the index of a menu item identified by INDEX."""
i = self.tk.call(self._w, 'index', index)
if i == 'none': return None
return getint(i) | [
"def",
"index",
"(",
"self",
",",
"index",
")",
":",
"i",
"=",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_w",
",",
"'index'",
",",
"index",
")",
"if",
"i",
"==",
"'none'",
":",
"return",
"None",
"return",
"getint",
"(",
"i",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/Tkinter.py#L2797-L2801 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/externals/joblib/_parallel_backends.py | python | AutoBatchingMixin.batch_completed | (self, batch_size, duration) | Callback indicate how long it took to run a batch | Callback indicate how long it took to run a batch | [
"Callback",
"indicate",
"how",
"long",
"it",
"took",
"to",
"run",
"a",
"batch"
] | def batch_completed(self, batch_size, duration):
"""Callback indicate how long it took to run a batch"""
if batch_size == self._effective_batch_size:
# Update the smoothed streaming estimate of the duration of a batch
# from dispatch to completion
old_duration = self._smoothed_batch_duration
if old_duration == 0:
# First record of duration for this batch size after the last
# reset.
new_duration = duration
else:
# Update the exponentially weighted average of the duration of
# batch for the current effective size.
new_duration = 0.8 * old_duration + 0.2 * duration
self._smoothed_batch_duration = new_duration | [
"def",
"batch_completed",
"(",
"self",
",",
"batch_size",
",",
"duration",
")",
":",
"if",
"batch_size",
"==",
"self",
".",
"_effective_batch_size",
":",
"# Update the smoothed streaming estimate of the duration of a batch",
"# from dispatch to completion",
"old_duration",
"=... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/externals/joblib/_parallel_backends.py#L212-L226 | ||
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | client.py | python | toggle_trailing_blank_line | (depname) | If the trailing line is empty, then we'll delete it.
Otherwise we'll add a blank line. | If the trailing line is empty, then we'll delete it.
Otherwise we'll add a blank line. | [
"If",
"the",
"trailing",
"line",
"is",
"empty",
"then",
"we",
"ll",
"delete",
"it",
".",
"Otherwise",
"we",
"ll",
"add",
"a",
"blank",
"line",
"."
] | def toggle_trailing_blank_line(depname):
"""If the trailing line is empty, then we'll delete it.
Otherwise we'll add a blank line."""
lines = open(depname, "r").readlines()
if not lines:
print >>sys.stderr, "unexpected short file"
return
if not lines[-1].strip():
# trailing line is blank, removing it
open(depname, "wb").writelines(lines[:-1])
else:
# adding blank line
open(depname, "ab").write("\n") | [
"def",
"toggle_trailing_blank_line",
"(",
"depname",
")",
":",
"lines",
"=",
"open",
"(",
"depname",
",",
"\"r\"",
")",
".",
"readlines",
"(",
")",
"if",
"not",
"lines",
":",
"print",
">>",
"sys",
".",
"stderr",
",",
"\"unexpected short file\"",
"return",
... | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/client.py#L80-L93 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/ttk.py | python | Style.theme_create | (self, themename, parent=None, settings=None) | Creates a new theme.
It is an error if themename already exists. If parent is
specified, the new theme will inherit styles, elements and
layouts from the specified parent theme. If settings are present,
they are expected to have the same syntax used for theme_settings. | Creates a new theme. | [
"Creates",
"a",
"new",
"theme",
"."
] | def theme_create(self, themename, parent=None, settings=None):
"""Creates a new theme.
It is an error if themename already exists. If parent is
specified, the new theme will inherit styles, elements and
layouts from the specified parent theme. If settings are present,
they are expected to have the same syntax used for theme_settings."""
script = _script_from_settings(settings) if settings else ''
if parent:
self.tk.call(self._name, "theme", "create", themename,
"-parent", parent, "-settings", script)
else:
self.tk.call(self._name, "theme", "create", themename,
"-settings", script) | [
"def",
"theme_create",
"(",
"self",
",",
"themename",
",",
"parent",
"=",
"None",
",",
"settings",
"=",
"None",
")",
":",
"script",
"=",
"_script_from_settings",
"(",
"settings",
")",
"if",
"settings",
"else",
"''",
"if",
"parent",
":",
"self",
".",
"tk"... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/ttk.py#L479-L493 | ||
deepmind/open_spiel | 4ca53bea32bb2875c7385d215424048ae92f78c8 | open_spiel/python/algorithms/adidas_utils/solvers/symmetric/ate_anneal.py | python | mirror_project | (dist, y) | return dist, y | Project variables onto their feasible sets (softmax for dist).
Args:
dist: 1-d np.array, current estimate of nash distribution
y: 1-d np.array (same shape as dist), current estimate of payoff gradient
Returns:
projected variables (dist, y) as tuple | Project variables onto their feasible sets (softmax for dist). | [
"Project",
"variables",
"onto",
"their",
"feasible",
"sets",
"(",
"softmax",
"for",
"dist",
")",
"."
] | def mirror_project(dist, y):
"""Project variables onto their feasible sets (softmax for dist).
Args:
dist: 1-d np.array, current estimate of nash distribution
y: 1-d np.array (same shape as dist), current estimate of payoff gradient
Returns:
projected variables (dist, y) as tuple
"""
dist = special.softmax(dist)
y = np.clip(y, 0., np.inf)
return dist, y | [
"def",
"mirror_project",
"(",
"dist",
",",
"y",
")",
":",
"dist",
"=",
"special",
".",
"softmax",
"(",
"dist",
")",
"y",
"=",
"np",
".",
"clip",
"(",
"y",
",",
"0.",
",",
"np",
".",
"inf",
")",
"return",
"dist",
",",
"y"
] | https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/algorithms/adidas_utils/solvers/symmetric/ate_anneal.py#L373-L385 | |
trilinos/Trilinos | 6168be6dd51e35e1cd681e9c4b24433e709df140 | packages/seacas/scripts/exodus3.in.py | python | exodus.put_polyhedra_elem_blk | (self, blkID,
num_elems_this_blk,
num_faces,
num_attr_per_elem) | return True | put in an element block with polyhedral elements
>>> status = exo.put_polyhedra_elem_blk(blkID, num_elems_this_blk,
... num_faces, num_attr_per_elem)
Parameters
----------
<int> blkID id of the block to be added
<int> num_elems_this_blk
<int> num_faces total number of faces in this block
<int> num_attr_per_elem
Returns
-------
status : bool
True = successful execution | put in an element block with polyhedral elements | [
"put",
"in",
"an",
"element",
"block",
"with",
"polyhedral",
"elements"
] | def put_polyhedra_elem_blk(self, blkID,
num_elems_this_blk,
num_faces,
num_attr_per_elem):
"""
put in an element block with polyhedral elements
>>> status = exo.put_polyhedra_elem_blk(blkID, num_elems_this_blk,
... num_faces, num_attr_per_elem)
Parameters
----------
<int> blkID id of the block to be added
<int> num_elems_this_blk
<int> num_faces total number of faces in this block
<int> num_attr_per_elem
Returns
-------
status : bool
True = successful execution
"""
ebType = ctypes.c_int(get_entity_type('EX_ELEM_BLOCK'))
EXODUS_LIB.ex_put_block(self.fileId, ebType, ctypes.c_longlong(blkID),
ctypes.create_string_buffer(b"NFACED"),
ctypes.c_longlong(num_elems_this_blk),
ctypes.c_longlong(0),
ctypes.c_longlong(0),
ctypes.c_longlong(num_faces),
ctypes.c_longlong(num_attr_per_elem))
return True | [
"def",
"put_polyhedra_elem_blk",
"(",
"self",
",",
"blkID",
",",
"num_elems_this_blk",
",",
"num_faces",
",",
"num_attr_per_elem",
")",
":",
"ebType",
"=",
"ctypes",
".",
"c_int",
"(",
"get_entity_type",
"(",
"'EX_ELEM_BLOCK'",
")",
")",
"EXODUS_LIB",
".",
"ex_p... | https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exodus3.in.py#L4564-L4595 | |
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/contributed/sumopy/coremodules/demand/origin_to_destination_wxgui.py | python | AddODflowTool.on_execute_selection | (self, event) | return True | Definively execute operation on currently selected drawobjects. | Definively execute operation on currently selected drawobjects. | [
"Definively",
"execute",
"operation",
"on",
"currently",
"selected",
"drawobjects",
"."
] | def on_execute_selection(self, event):
"""
Definively execute operation on currently selected drawobjects.
"""
# print 'AddODflowTool.on_execute_selection',self.get_netelement_current()
# self.set_objbrowser()
# self.highlight_current()
self.unhighlight_current()
self.unhighlight_zones()
netelement_current = self.get_netelement_current()
if netelement_current is not None:
(zones, id_zone) = netelement_current
if zones.get_ident() == 'zones':
# print ' check',self.name_orig.get_value(),'*',self.name_orig.get_value() is ''
if self.id_orig.get_value() < 0:
# print ' set name_orig',zones.ids_sumo[id_zone]
self.id_orig.set_value(id_zone)
else:
# print ' set name_dest',zones.ids_sumo[id_zone]
self.id_dest.set_value(id_zone)
self.unselect_all() # includes unhighlight
self.highlight_zones()
self.parent.refresh_optionspanel(self)
return True | [
"def",
"on_execute_selection",
"(",
"self",
",",
"event",
")",
":",
"# print 'AddODflowTool.on_execute_selection',self.get_netelement_current()",
"# self.set_objbrowser()",
"# self.highlight_current()",
"self",
".",
"unhighlight_current",
"(",
")",
"self",
".",
"unhighlight_zones... | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/coremodules/demand/origin_to_destination_wxgui.py#L380-L405 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/generator.py | python | CssItem.GetFont | (self) | return self._font | Returns the Font Name
@return: font name attribute | Returns the Font Name
@return: font name attribute | [
"Returns",
"the",
"Font",
"Name",
"@return",
":",
"font",
"name",
"attribute"
] | def GetFont(self):
"""Returns the Font Name
@return: font name attribute
"""
return self._font | [
"def",
"GetFont",
"(",
"self",
")",
":",
"return",
"self",
".",
"_font"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/generator.py#L442-L447 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/numpy/array_creations.py | python | zeros_like | (a, dtype=None, shape=None) | return _x_like(a, dtype, shape, zeros) | Returns an array of zeros with the same shape and type as a given array.
Note:
Input array must have the same size across a dimension.
If `a` is not a Tensor, dtype is float32 by default if not provided.
Args:
a (Union[Tensor, list, tuple]): The shape and data-type of a define these same
attributes of the returned array.
dtype (:class:`mindspore.dtype`, optional): Overrides the data type of the
result.
shape (int or sequence of ints, optional): Overrides the shape
of the result.
Returns:
Tensor, array of zeros with the same shape and type as `a`.
Raises:
ValueError: If `a` is not a Tensor, list or tuple.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> import mindspore.numpy as np
>>> a = np.ones((4,1,2))
>>> output = np.zeros_like(a)
>>> print(output)
[[[0. 0.]]
[[0. 0.]]
[[0. 0.]]
[[0. 0.]]] | Returns an array of zeros with the same shape and type as a given array. | [
"Returns",
"an",
"array",
"of",
"zeros",
"with",
"the",
"same",
"shape",
"and",
"type",
"as",
"a",
"given",
"array",
"."
] | def zeros_like(a, dtype=None, shape=None):
"""
Returns an array of zeros with the same shape and type as a given array.
Note:
Input array must have the same size across a dimension.
If `a` is not a Tensor, dtype is float32 by default if not provided.
Args:
a (Union[Tensor, list, tuple]): The shape and data-type of a define these same
attributes of the returned array.
dtype (:class:`mindspore.dtype`, optional): Overrides the data type of the
result.
shape (int or sequence of ints, optional): Overrides the shape
of the result.
Returns:
Tensor, array of zeros with the same shape and type as `a`.
Raises:
ValueError: If `a` is not a Tensor, list or tuple.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> import mindspore.numpy as np
>>> a = np.ones((4,1,2))
>>> output = np.zeros_like(a)
>>> print(output)
[[[0. 0.]]
[[0. 0.]]
[[0. 0.]]
[[0. 0.]]]
"""
return _x_like(a, dtype, shape, zeros) | [
"def",
"zeros_like",
"(",
"a",
",",
"dtype",
"=",
"None",
",",
"shape",
"=",
"None",
")",
":",
"return",
"_x_like",
"(",
"a",
",",
"dtype",
",",
"shape",
",",
"zeros",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/numpy/array_creations.py#L896-L931 | |
hfinkel/llvm-project-cxxjit | 91084ef018240bbb8e24235ff5cd8c355a9c1a1e | clang/tools/scan-build-py/libscanbuild/__init__.py | python | wrapper_environment | (args) | return {
ENVIRONMENT_KEY: json.dumps({
'verbose': args.verbose,
'cc': shlex.split(args.cc),
'cxx': shlex.split(args.cxx)
})
} | Set up environment for interpose compiler wrapper. | Set up environment for interpose compiler wrapper. | [
"Set",
"up",
"environment",
"for",
"interpose",
"compiler",
"wrapper",
"."
] | def wrapper_environment(args):
""" Set up environment for interpose compiler wrapper."""
return {
ENVIRONMENT_KEY: json.dumps({
'verbose': args.verbose,
'cc': shlex.split(args.cc),
'cxx': shlex.split(args.cxx)
})
} | [
"def",
"wrapper_environment",
"(",
"args",
")",
":",
"return",
"{",
"ENVIRONMENT_KEY",
":",
"json",
".",
"dumps",
"(",
"{",
"'verbose'",
":",
"args",
".",
"verbose",
",",
"'cc'",
":",
"shlex",
".",
"split",
"(",
"args",
".",
"cc",
")",
",",
"'cxx'",
... | https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/clang/tools/scan-build-py/libscanbuild/__init__.py#L198-L207 | |
tensorflow/ngraph-bridge | ea6422491ec75504e78a63db029e7f74ec3479a5 | examples/retrain_ngraph.py | python | run_bottleneck_on_image | (sess, image_data, image_data_tensor,
decoded_image_tensor, resized_input_tensor,
bottleneck_tensor) | return bottleneck_values | Runs inference on an image to extract the 'bottleneck' summary layer.
Args:
sess: Current active TensorFlow Session.
image_data: String of raw JPEG data.
image_data_tensor: Input data layer in the graph.
decoded_image_tensor: Output of initial image resizing and preprocessing.
resized_input_tensor: The input node of the recognition graph.
bottleneck_tensor: Layer before the final softmax.
Returns:
Numpy array of bottleneck values. | Runs inference on an image to extract the 'bottleneck' summary layer. | [
"Runs",
"inference",
"on",
"an",
"image",
"to",
"extract",
"the",
"bottleneck",
"summary",
"layer",
"."
] | def run_bottleneck_on_image(sess, image_data, image_data_tensor,
decoded_image_tensor, resized_input_tensor,
bottleneck_tensor):
"""Runs inference on an image to extract the 'bottleneck' summary layer.
Args:
sess: Current active TensorFlow Session.
image_data: String of raw JPEG data.
image_data_tensor: Input data layer in the graph.
decoded_image_tensor: Output of initial image resizing and preprocessing.
resized_input_tensor: The input node of the recognition graph.
bottleneck_tensor: Layer before the final softmax.
Returns:
Numpy array of bottleneck values.
"""
# First decode the JPEG image, resize it, and rescale the pixel values.
resized_input_values = sess.run(decoded_image_tensor,
{image_data_tensor: image_data})
# Then run it through the recognition network.
bottleneck_values = sess.run(bottleneck_tensor,
{resized_input_tensor: resized_input_values})
bottleneck_values = np.squeeze(bottleneck_values)
return bottleneck_values | [
"def",
"run_bottleneck_on_image",
"(",
"sess",
",",
"image_data",
",",
"image_data_tensor",
",",
"decoded_image_tensor",
",",
"resized_input_tensor",
",",
"bottleneck_tensor",
")",
":",
"# First decode the JPEG image, resize it, and rescale the pixel values.",
"resized_input_values... | https://github.com/tensorflow/ngraph-bridge/blob/ea6422491ec75504e78a63db029e7f74ec3479a5/examples/retrain_ngraph.py#L345-L368 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/cloudsearch/layer1.py | python | Layer1.describe_service_access_policies | (self, domain_name) | return self.get_response(doc_path, 'DescribeServiceAccessPolicies',
params, verb='POST') | Describes the resource-based policies controlling access to
the services in this search domain.
:type domain_name: string
:param domain_name: A string that represents the name of a
domain. Domain names must be unique across the domains
owned by an account within an AWS region. Domain names
must start with a letter or number and can contain the
following characters: a-z (lowercase), 0-9, and -
(hyphen). Uppercase letters and underscores are not
allowed.
:raises: BaseException, InternalException, ResourceNotFoundException | Describes the resource-based policies controlling access to
the services in this search domain. | [
"Describes",
"the",
"resource",
"-",
"based",
"policies",
"controlling",
"access",
"to",
"the",
"services",
"in",
"this",
"search",
"domain",
"."
] | def describe_service_access_policies(self, domain_name):
"""
Describes the resource-based policies controlling access to
the services in this search domain.
:type domain_name: string
:param domain_name: A string that represents the name of a
domain. Domain names must be unique across the domains
owned by an account within an AWS region. Domain names
must start with a letter or number and can contain the
following characters: a-z (lowercase), 0-9, and -
(hyphen). Uppercase letters and underscores are not
allowed.
:raises: BaseException, InternalException, ResourceNotFoundException
"""
doc_path = ('describe_service_access_policies_response',
'describe_service_access_policies_result',
'access_policies')
params = {'DomainName': domain_name}
return self.get_response(doc_path, 'DescribeServiceAccessPolicies',
params, verb='POST') | [
"def",
"describe_service_access_policies",
"(",
"self",
",",
"domain_name",
")",
":",
"doc_path",
"=",
"(",
"'describe_service_access_policies_response'",
",",
"'describe_service_access_policies_result'",
",",
"'access_policies'",
")",
"params",
"=",
"{",
"'DomainName'",
":... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/cloudsearch/layer1.py#L479-L500 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/dataview.py | python | DataViewIndexListModel.SetValueByRow | (*args, **kwargs) | return _dataview.DataViewIndexListModel_SetValueByRow(*args, **kwargs) | SetValueByRow(self, wxVariant variant, unsigned int row, unsigned int col) -> bool
This is called in order to set a value in the data model. | SetValueByRow(self, wxVariant variant, unsigned int row, unsigned int col) -> bool | [
"SetValueByRow",
"(",
"self",
"wxVariant",
"variant",
"unsigned",
"int",
"row",
"unsigned",
"int",
"col",
")",
"-",
">",
"bool"
] | def SetValueByRow(*args, **kwargs):
"""
SetValueByRow(self, wxVariant variant, unsigned int row, unsigned int col) -> bool
This is called in order to set a value in the data model.
"""
return _dataview.DataViewIndexListModel_SetValueByRow(*args, **kwargs) | [
"def",
"SetValueByRow",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewIndexListModel_SetValueByRow",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/dataview.py#L807-L813 | |
llvm/llvm-project | ffa6262cb4e2a335d26416fad39a581b4f98c5f4 | mlir/python/mlir/dialects/linalg/opdsl/ops/core_named_ops.py | python | conv_1d_nwc_wcf | (
I=TensorDef(T1, S.N, S.OW * S.SW + S.KW * S.DW, S.C),
K=TensorDef(T2, S.KW, S.C, S.F),
O=TensorDef(U, S.N, S.OW, S.F, output=True),
strides=IndexAttrDef(S.SW),
dilations=IndexAttrDef(S.DW)) | Performs 1-D convolution.
Numeric casting is performed on the operands to the inner multiply, promoting
them to the same data type as the accumulator/output. | Performs 1-D convolution. | [
"Performs",
"1",
"-",
"D",
"convolution",
"."
] | def conv_1d_nwc_wcf(
I=TensorDef(T1, S.N, S.OW * S.SW + S.KW * S.DW, S.C),
K=TensorDef(T2, S.KW, S.C, S.F),
O=TensorDef(U, S.N, S.OW, S.F, output=True),
strides=IndexAttrDef(S.SW),
dilations=IndexAttrDef(S.DW)):
"""Performs 1-D convolution.
Numeric casting is performed on the operands to the inner multiply, promoting
them to the same data type as the accumulator/output.
"""
implements(ConvolutionOpInterface)
domain(D.n, D.ow, D.f, D.kw, D.c)
O[D.n, D.ow,
D.f] += TypeFn.cast(U, I[D.n, D.ow * S.SW + D.kw * S.DW,
D.c]) * TypeFn.cast(U, K[D.kw, D.c, D.f]) | [
"def",
"conv_1d_nwc_wcf",
"(",
"I",
"=",
"TensorDef",
"(",
"T1",
",",
"S",
".",
"N",
",",
"S",
".",
"OW",
"*",
"S",
".",
"SW",
"+",
"S",
".",
"KW",
"*",
"S",
".",
"DW",
",",
"S",
".",
"C",
")",
",",
"K",
"=",
"TensorDef",
"(",
"T2",
",",
... | https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/mlir/python/mlir/dialects/linalg/opdsl/ops/core_named_ops.py#L223-L238 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_gdi.py | python | FontEnumerator.__init__ | (self, *args, **kwargs) | __init__(self) -> FontEnumerator | __init__(self) -> FontEnumerator | [
"__init__",
"(",
"self",
")",
"-",
">",
"FontEnumerator"
] | def __init__(self, *args, **kwargs):
"""__init__(self) -> FontEnumerator"""
_gdi_.FontEnumerator_swiginit(self,_gdi_.new_FontEnumerator(*args, **kwargs))
FontEnumerator._setCallbackInfo(self, self, FontEnumerator) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_gdi_",
".",
"FontEnumerator_swiginit",
"(",
"self",
",",
"_gdi_",
".",
"new_FontEnumerator",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"FontEnumerator",
"... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L2739-L2742 | ||
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/deps/v8/tools/stats-viewer.py | python | SharedDataAccess.CharAt | (self, index) | return self.data[index] | Return the ascii character at the specified byte index. | Return the ascii character at the specified byte index. | [
"Return",
"the",
"ascii",
"character",
"at",
"the",
"specified",
"byte",
"index",
"."
] | def CharAt(self, index):
"""Return the ascii character at the specified byte index."""
return self.data[index] | [
"def",
"CharAt",
"(",
"self",
",",
"index",
")",
":",
"return",
"self",
".",
"data",
"[",
"index",
"]"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/deps/v8/tools/stats-viewer.py#L325-L327 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/dataview.py | python | DataViewCtrl.GetSelectedItemsCount | (*args, **kwargs) | return _dataview.DataViewCtrl_GetSelectedItemsCount(*args, **kwargs) | GetSelectedItemsCount(self) -> int | GetSelectedItemsCount(self) -> int | [
"GetSelectedItemsCount",
"(",
"self",
")",
"-",
">",
"int"
] | def GetSelectedItemsCount(*args, **kwargs):
"""GetSelectedItemsCount(self) -> int"""
return _dataview.DataViewCtrl_GetSelectedItemsCount(*args, **kwargs) | [
"def",
"GetSelectedItemsCount",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewCtrl_GetSelectedItemsCount",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/dataview.py#L1755-L1757 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Path/PathScripts/PathJobGui.py | python | Create | (base, template=None) | Create(base, template) ... creates a job instance for the given base object
using template to configure it. | Create(base, template) ... creates a job instance for the given base object
using template to configure it. | [
"Create",
"(",
"base",
"template",
")",
"...",
"creates",
"a",
"job",
"instance",
"for",
"the",
"given",
"base",
"object",
"using",
"template",
"to",
"configure",
"it",
"."
] | def Create(base, template=None):
"""Create(base, template) ... creates a job instance for the given base object
using template to configure it."""
FreeCADGui.addModule("PathScripts.PathJob")
FreeCAD.ActiveDocument.openTransaction("Create Job")
try:
obj = PathJob.Create("Job", base, template)
obj.ViewObject.Proxy = ViewProvider(obj.ViewObject)
FreeCAD.ActiveDocument.commitTransaction()
obj.Document.recompute()
obj.ViewObject.Proxy.editObject(obj.Stock)
return obj
except Exception as exc:
PathLog.error(exc)
traceback.print_exc()
FreeCAD.ActiveDocument.abortTransaction() | [
"def",
"Create",
"(",
"base",
",",
"template",
"=",
"None",
")",
":",
"FreeCADGui",
".",
"addModule",
"(",
"\"PathScripts.PathJob\"",
")",
"FreeCAD",
".",
"ActiveDocument",
".",
"openTransaction",
"(",
"\"Create Job\"",
")",
"try",
":",
"obj",
"=",
"PathJob",
... | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Path/PathScripts/PathJobGui.py#L1576-L1591 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/email/utils.py | python | getaddresses | (fieldvalues) | return a.addresslist | Return a list of (REALNAME, EMAIL) for each fieldvalue. | Return a list of (REALNAME, EMAIL) for each fieldvalue. | [
"Return",
"a",
"list",
"of",
"(",
"REALNAME",
"EMAIL",
")",
"for",
"each",
"fieldvalue",
"."
] | def getaddresses(fieldvalues):
"""Return a list of (REALNAME, EMAIL) for each fieldvalue."""
all = COMMASPACE.join(fieldvalues)
a = _AddressList(all)
return a.addresslist | [
"def",
"getaddresses",
"(",
"fieldvalues",
")",
":",
"all",
"=",
"COMMASPACE",
".",
"join",
"(",
"fieldvalues",
")",
"a",
"=",
"_AddressList",
"(",
"all",
")",
"return",
"a",
".",
"addresslist"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/email/utils.py#L104-L108 | |
microsoft/onnxruntime | f92e47e95b13a240e37caf7b36577983544f98fc | orttraining/orttraining/python/training/ortmodule/_torch_module_ort.py | python | TorchModuleORT.named_children | (self) | Override original method to delegate execution to the original PyTorch user module | Override original method to delegate execution to the original PyTorch user module | [
"Override",
"original",
"method",
"to",
"delegate",
"execution",
"to",
"the",
"original",
"PyTorch",
"user",
"module"
] | def named_children(self) -> Iterator[Tuple[str, T]]:
"""Override original method to delegate execution to the original PyTorch user module"""
yield from self._original_module.named_children() | [
"def",
"named_children",
"(",
"self",
")",
"->",
"Iterator",
"[",
"Tuple",
"[",
"str",
",",
"T",
"]",
"]",
":",
"yield",
"from",
"self",
".",
"_original_module",
".",
"named_children",
"(",
")"
] | https://github.com/microsoft/onnxruntime/blob/f92e47e95b13a240e37caf7b36577983544f98fc/orttraining/orttraining/python/training/ortmodule/_torch_module_ort.py#L123-L126 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/grid.py | python | Grid.GetSortingColumn | (*args, **kwargs) | return _grid.Grid_GetSortingColumn(*args, **kwargs) | GetSortingColumn(self) -> int | GetSortingColumn(self) -> int | [
"GetSortingColumn",
"(",
"self",
")",
"-",
">",
"int"
] | def GetSortingColumn(*args, **kwargs):
"""GetSortingColumn(self) -> int"""
return _grid.Grid_GetSortingColumn(*args, **kwargs) | [
"def",
"GetSortingColumn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"Grid_GetSortingColumn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/grid.py#L2169-L2171 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/wsgiref/headers.py | python | Headers.items | (self) | return self._headers[:] | Get all the header fields and values.
These will be sorted in the order they were in the original header
list, or were added to this instance, and may contain duplicates.
Any fields deleted and re-inserted are always appended to the header
list. | Get all the header fields and values. | [
"Get",
"all",
"the",
"header",
"fields",
"and",
"values",
"."
] | def items(self):
"""Get all the header fields and values.
These will be sorted in the order they were in the original header
list, or were added to this instance, and may contain duplicates.
Any fields deleted and re-inserted are always appended to the header
list.
"""
return self._headers[:] | [
"def",
"items",
"(",
"self",
")",
":",
"return",
"self",
".",
"_headers",
"[",
":",
"]"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/wsgiref/headers.py#L115-L123 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/webbrowser.py | python | get | (using=None) | Return a browser launcher instance appropriate for the environment. | Return a browser launcher instance appropriate for the environment. | [
"Return",
"a",
"browser",
"launcher",
"instance",
"appropriate",
"for",
"the",
"environment",
"."
] | def get(using=None):
"""Return a browser launcher instance appropriate for the environment."""
if using is not None:
alternatives = [using]
else:
alternatives = _tryorder
for browser in alternatives:
if '%s' in browser:
# User gave us a command line, split it into name and args
browser = shlex.split(browser)
if browser[-1] == '&':
return BackgroundBrowser(browser[:-1])
else:
return GenericBrowser(browser)
else:
# User gave us a browser name or path.
try:
command = _browsers[browser.lower()]
except KeyError:
command = _synthesize(browser)
if command[1] is not None:
return command[1]
elif command[0] is not None:
return command[0]()
raise Error("could not locate runnable browser") | [
"def",
"get",
"(",
"using",
"=",
"None",
")",
":",
"if",
"using",
"is",
"not",
"None",
":",
"alternatives",
"=",
"[",
"using",
"]",
"else",
":",
"alternatives",
"=",
"_tryorder",
"for",
"browser",
"in",
"alternatives",
":",
"if",
"'%s'",
"in",
"browser... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/webbrowser.py#L28-L52 | ||
trilinos/Trilinos | 6168be6dd51e35e1cd681e9c4b24433e709df140 | packages/seacas/scripts/exomerge3.py | python | ExodusModel._values_match | (value, list_of_values) | return not any(not math.isnan(x) for x in list_of_values) | Return True if the list contains no items apart from the given value.
Example:
>>> _values_match(0, [0, 0, 0])
True
>>> _values_match(1, [0, 1, 0])
False | Return True if the list contains no items apart from the given value. | [
"Return",
"True",
"if",
"the",
"list",
"contains",
"no",
"items",
"apart",
"from",
"the",
"given",
"value",
"."
] | def _values_match(value, list_of_values):
"""
Return True if the list contains no items apart from the given value.
Example:
>>> _values_match(0, [0, 0, 0])
True
>>> _values_match(1, [0, 1, 0])
False
"""
if not isinstance(value, float) or not math.isnan(value):
return not any(x != value for x in list_of_values)
return not any(not math.isnan(x) for x in list_of_values) | [
"def",
"_values_match",
"(",
"value",
",",
"list_of_values",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"float",
")",
"or",
"not",
"math",
".",
"isnan",
"(",
"value",
")",
":",
"return",
"not",
"any",
"(",
"x",
"!=",
"value",
"for",
"x",... | https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exomerge3.py#L6827-L6840 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/grit/grit/node/misc.py | python | GritNode.SetShouldOutputAllResourceDefines | (self, value) | Overrides the value of output_all_resource_defines found in the grd file. | Overrides the value of output_all_resource_defines found in the grd file. | [
"Overrides",
"the",
"value",
"of",
"output_all_resource_defines",
"found",
"in",
"the",
"grd",
"file",
"."
] | def SetShouldOutputAllResourceDefines(self, value):
"""Overrides the value of output_all_resource_defines found in the grd file.
"""
self.attrs['output_all_resource_defines'] = 'true' if value else 'false' | [
"def",
"SetShouldOutputAllResourceDefines",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"attrs",
"[",
"'output_all_resource_defines'",
"]",
"=",
"'true'",
"if",
"value",
"else",
"'false'"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/grit/grit/node/misc.py#L295-L298 | ||
bairdzhang/smallhardface | 76fa1d87a9602d9b13d7a7fe693fc7aec91cab80 | caffe/scripts/cpp_lint.py | python | _GetTextInside | (text, start_pattern) | return text[start_position:position - 1] | r"""Retrieves all the text between matching open and close parentheses.
Given a string of lines and a regular expression string, retrieve all the text
following the expression and between opening punctuation symbols like
(, [, or {, and the matching close-punctuation symbol. This properly nested
occurrences of the punctuations, so for the text like
printf(a(), b(c()));
a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'.
start_pattern must match string having an open punctuation symbol at the end.
Args:
text: The lines to extract text. Its comments and strings must be elided.
It can be single line and can span multiple lines.
start_pattern: The regexp string indicating where to start extracting
the text.
Returns:
The extracted text.
None if either the opening string or ending punctuation could not be found. | r"""Retrieves all the text between matching open and close parentheses. | [
"r",
"Retrieves",
"all",
"the",
"text",
"between",
"matching",
"open",
"and",
"close",
"parentheses",
"."
] | def _GetTextInside(text, start_pattern):
r"""Retrieves all the text between matching open and close parentheses.
Given a string of lines and a regular expression string, retrieve all the text
following the expression and between opening punctuation symbols like
(, [, or {, and the matching close-punctuation symbol. This properly nested
occurrences of the punctuations, so for the text like
printf(a(), b(c()));
a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'.
start_pattern must match string having an open punctuation symbol at the end.
Args:
text: The lines to extract text. Its comments and strings must be elided.
It can be single line and can span multiple lines.
start_pattern: The regexp string indicating where to start extracting
the text.
Returns:
The extracted text.
None if either the opening string or ending punctuation could not be found.
"""
# TODO(sugawarayu): Audit cpplint.py to see what places could be profitably
# rewritten to use _GetTextInside (and use inferior regexp matching today).
# Give opening punctuations to get the matching close-punctuations.
matching_punctuation = {'(': ')', '{': '}', '[': ']'}
closing_punctuation = set(itervalues(matching_punctuation))
# Find the position to start extracting text.
match = re.search(start_pattern, text, re.M)
if not match: # start_pattern not found in text.
return None
start_position = match.end(0)
assert start_position > 0, (
'start_pattern must ends with an opening punctuation.')
assert text[start_position - 1] in matching_punctuation, (
'start_pattern must ends with an opening punctuation.')
# Stack of closing punctuations we expect to have in text after position.
punctuation_stack = [matching_punctuation[text[start_position - 1]]]
position = start_position
while punctuation_stack and position < len(text):
if text[position] == punctuation_stack[-1]:
punctuation_stack.pop()
elif text[position] in closing_punctuation:
# A closing punctuation without matching opening punctuations.
return None
elif text[position] in matching_punctuation:
punctuation_stack.append(matching_punctuation[text[position]])
position += 1
if punctuation_stack:
# Opening punctuations left without matching close-punctuations.
return None
# punctuations match.
return text[start_position:position - 1] | [
"def",
"_GetTextInside",
"(",
"text",
",",
"start_pattern",
")",
":",
"# TODO(sugawarayu): Audit cpplint.py to see what places could be profitably",
"# rewritten to use _GetTextInside (and use inferior regexp matching today).",
"# Give opening punctuations to get the matching close-punctuations.... | https://github.com/bairdzhang/smallhardface/blob/76fa1d87a9602d9b13d7a7fe693fc7aec91cab80/caffe/scripts/cpp_lint.py#L3756-L3809 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/ed_stc.py | python | EditraStc.WordPartLeft | (self) | Move the caret left to the next change in capitalization/punctuation
@note: overrides default function to not count whitespace as words | Move the caret left to the next change in capitalization/punctuation
@note: overrides default function to not count whitespace as words | [
"Move",
"the",
"caret",
"left",
"to",
"the",
"next",
"change",
"in",
"capitalization",
"/",
"punctuation",
"@note",
":",
"overrides",
"default",
"function",
"to",
"not",
"count",
"whitespace",
"as",
"words"
] | def WordPartLeft(self): # pylint: disable-msg=W0221
"""Move the caret left to the next change in capitalization/punctuation
@note: overrides default function to not count whitespace as words
"""
super(EditraStc, self).WordPartLeft()
cpos = self.GetCurrentPos()
if self.GetTextRange(cpos, cpos + 1) in SPACECHARS:
super(EditraStc, self).WordPartLeft() | [
"def",
"WordPartLeft",
"(",
"self",
")",
":",
"# pylint: disable-msg=W0221",
"super",
"(",
"EditraStc",
",",
"self",
")",
".",
"WordPartLeft",
"(",
")",
"cpos",
"=",
"self",
".",
"GetCurrentPos",
"(",
")",
"if",
"self",
".",
"GetTextRange",
"(",
"cpos",
",... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_stc.py#L1707-L1715 | ||
nasa/fprime | 595cf3682d8365943d86c1a6fe7c78f0a116acf0 | Autocoders/Python/src/fprime_ac/utils/XmlParser.py | python | Parser.dump | (self) | Dump from root over the tree. | Dump from root over the tree. | [
"Dump",
"from",
"root",
"over",
"the",
"tree",
"."
] | def dump(self):
"""
Dump from root over the tree.
"""
if self.__root is None:
return
elist = self.__root.getElements()
if len(elist) > 0:
for e in elist:
print("Element: %s" % e.getName())
print("Data: %s" % e.getData())
print("Attr:")
for attr in list(e.getAttr().keys()):
print(" {} = {}".format(attr, e.getAttr(attr)))
child = e.getElements()
self.dump2(child) | [
"def",
"dump",
"(",
"self",
")",
":",
"if",
"self",
".",
"__root",
"is",
"None",
":",
"return",
"elist",
"=",
"self",
".",
"__root",
".",
"getElements",
"(",
")",
"if",
"len",
"(",
"elist",
")",
">",
"0",
":",
"for",
"e",
"in",
"elist",
":",
"p... | https://github.com/nasa/fprime/blob/595cf3682d8365943d86c1a6fe7c78f0a116acf0/Autocoders/Python/src/fprime_ac/utils/XmlParser.py#L389-L405 | ||
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/android.py | python | AndroidMkWriter.WriteCopies | (self, copies, extra_outputs) | Write Makefile code for any 'copies' from the gyp input.
extra_outputs: a list that will be filled in with any outputs of this action
(used to make other pieces dependent on this action) | Write Makefile code for any 'copies' from the gyp input. | [
"Write",
"Makefile",
"code",
"for",
"any",
"copies",
"from",
"the",
"gyp",
"input",
"."
] | def WriteCopies(self, copies, extra_outputs):
"""Write Makefile code for any 'copies' from the gyp input.
extra_outputs: a list that will be filled in with any outputs of this action
(used to make other pieces dependent on this action)
"""
self.WriteLn('### Generated for copy rule.')
variable = make.StringToMakefileVariable(self.relative_target + '_copies')
outputs = []
for copy in copies:
for path in copy['files']:
# The Android build system does not allow generation of files into the
# source tree. The destination should start with a variable, which will
# typically be $(gyp_intermediate_dir) or
# $(gyp_shared_intermediate_dir). Note that we can't use an assertion
# because some of the gyp tests depend on this.
if not copy['destination'].startswith('$'):
print('WARNING: Copy rule for target %s writes output to '
'local path %s' % (self.target, copy['destination']))
# LocalPathify() calls normpath, stripping trailing slashes.
path = Sourceify(self.LocalPathify(path))
filename = os.path.split(path)[1]
output = Sourceify(self.LocalPathify(os.path.join(copy['destination'],
filename)))
self.WriteLn('%s: %s $(GYP_TARGET_DEPENDENCIES) | $(ACP)' %
(output, path))
self.WriteLn('\t@echo Copying: $@')
self.WriteLn('\t$(hide) mkdir -p $(dir $@)')
self.WriteLn('\t$(hide) $(ACP) -rpf $< $@')
self.WriteLn()
outputs.append(output)
self.WriteLn('%s = %s' % (variable,
' '.join(map(make.QuoteSpaces, outputs))))
extra_outputs.append('$(%s)' % variable)
self.WriteLn() | [
"def",
"WriteCopies",
"(",
"self",
",",
"copies",
",",
"extra_outputs",
")",
":",
"self",
".",
"WriteLn",
"(",
"'### Generated for copy rule.'",
")",
"variable",
"=",
"make",
".",
"StringToMakefileVariable",
"(",
"self",
".",
"relative_target",
"+",
"'_copies'",
... | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/android.py#L416-L453 | ||
etotheipi/BitcoinArmory | 2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98 | urllib3/util.py | python | Timeout.clone | (self) | return Timeout(connect=self._connect, read=self._read,
total=self.total) | Create a copy of the timeout object
Timeout properties are stored per-pool but each request needs a fresh
Timeout object to ensure each one has its own start/stop configured.
:return: a copy of the timeout object
:rtype: :class:`Timeout` | Create a copy of the timeout object | [
"Create",
"a",
"copy",
"of",
"the",
"timeout",
"object"
] | def clone(self):
""" Create a copy of the timeout object
Timeout properties are stored per-pool but each request needs a fresh
Timeout object to ensure each one has its own start/stop configured.
:return: a copy of the timeout object
:rtype: :class:`Timeout`
"""
# We can't use copy.deepcopy because that will also create a new object
# for _GLOBAL_DEFAULT_TIMEOUT, which socket.py uses as a sentinel to
# detect the user default.
return Timeout(connect=self._connect, read=self._read,
total=self.total) | [
"def",
"clone",
"(",
"self",
")",
":",
"# We can't use copy.deepcopy because that will also create a new object",
"# for _GLOBAL_DEFAULT_TIMEOUT, which socket.py uses as a sentinel to",
"# detect the user default.",
"return",
"Timeout",
"(",
"connect",
"=",
"self",
".",
"_connect",
... | https://github.com/etotheipi/BitcoinArmory/blob/2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98/urllib3/util.py#L180-L193 | |
Tencent/CMONGO | c40380caa14e05509f46993aa8b8da966b09b0b5 | src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/swig.py | python | generate | (env) | Add Builders and construction variables for swig to an Environment. | Add Builders and construction variables for swig to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"swig",
"to",
"an",
"Environment",
"."
] | def generate(env):
"""Add Builders and construction variables for swig to an Environment."""
c_file, cxx_file = SCons.Tool.createCFileBuilders(env)
c_file.suffix['.i'] = swigSuffixEmitter
cxx_file.suffix['.i'] = swigSuffixEmitter
c_file.add_action('.i', SwigAction)
c_file.add_emitter('.i', _swigEmitter)
cxx_file.add_action('.i', SwigAction)
cxx_file.add_emitter('.i', _swigEmitter)
java_file = SCons.Tool.CreateJavaFileBuilder(env)
java_file.suffix['.i'] = swigSuffixEmitter
java_file.add_action('.i', SwigAction)
java_file.add_emitter('.i', _swigEmitter)
if 'SWIG' not in env:
env['SWIG'] = env.Detect(swigs) or swigs[0]
env['SWIGVERSION'] = _get_swig_version(env, env['SWIG'])
env['SWIGFLAGS'] = SCons.Util.CLVar('')
env['SWIGDIRECTORSUFFIX'] = '_wrap.h'
env['SWIGCFILESUFFIX'] = '_wrap$CFILESUFFIX'
env['SWIGCXXFILESUFFIX'] = '_wrap$CXXFILESUFFIX'
env['_SWIGOUTDIR'] = r'${"-outdir \"%s\"" % SWIGOUTDIR}'
env['SWIGPATH'] = []
env['SWIGINCPREFIX'] = '-I'
env['SWIGINCSUFFIX'] = ''
env['_SWIGINCFLAGS'] = '$( ${_concat(SWIGINCPREFIX, SWIGPATH, SWIGINCSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)'
env['SWIGCOM'] = '$SWIG -o $TARGET ${_SWIGOUTDIR} ${_SWIGINCFLAGS} $SWIGFLAGS $SOURCES' | [
"def",
"generate",
"(",
"env",
")",
":",
"c_file",
",",
"cxx_file",
"=",
"SCons",
".",
"Tool",
".",
"createCFileBuilders",
"(",
"env",
")",
"c_file",
".",
"suffix",
"[",
"'.i'",
"]",
"=",
"swigSuffixEmitter",
"cxx_file",
".",
"suffix",
"[",
"'.i'",
"]",
... | https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/swig.py#L151-L182 | ||
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | TPML_AC_CAPABILITIES.fromBytes | (buffer) | return TpmBuffer(buffer).createObj(TPML_AC_CAPABILITIES) | Returns new TPML_AC_CAPABILITIES object constructed from its
marshaled representation in the given byte buffer | Returns new TPML_AC_CAPABILITIES object constructed from its
marshaled representation in the given byte buffer | [
"Returns",
"new",
"TPML_AC_CAPABILITIES",
"object",
"constructed",
"from",
"its",
"marshaled",
"representation",
"in",
"the",
"given",
"byte",
"buffer"
] | def fromBytes(buffer):
""" Returns new TPML_AC_CAPABILITIES object constructed from its
marshaled representation in the given byte buffer
"""
return TpmBuffer(buffer).createObj(TPML_AC_CAPABILITIES) | [
"def",
"fromBytes",
"(",
"buffer",
")",
":",
"return",
"TpmBuffer",
"(",
"buffer",
")",
".",
"createObj",
"(",
"TPML_AC_CAPABILITIES",
")"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L9044-L9048 | |
deepmind/multidim-image-augmentation | 7a180ec02fba2aac98f89cfff6fa6b647484d7cc | multidim_image_augmentation/deformation_utils.py | python | create_2x2_shearing_matrix | (shearing_coefs) | return shearing | Creates a 2D shearing matrix.
Args:
shearing_coefs: 2-element list with the shearing coefficients
(off-diagonal elements of the matrix: s01, s10) to create the matrix
[[ 1 , s01],
[s10, 1 ]]
Returns:
2-D Tensor with 2x2 elements, the shearing matrix | Creates a 2D shearing matrix. | [
"Creates",
"a",
"2D",
"shearing",
"matrix",
"."
] | def create_2x2_shearing_matrix(shearing_coefs):
"""Creates a 2D shearing matrix.
Args:
shearing_coefs: 2-element list with the shearing coefficients
(off-diagonal elements of the matrix: s01, s10) to create the matrix
[[ 1 , s01],
[s10, 1 ]]
Returns:
2-D Tensor with 2x2 elements, the shearing matrix
"""
shearing = [[1, shearing_coefs[0]], [shearing_coefs[1], 1]]
shearing = tf.convert_to_tensor(shearing, name="shearing_matrix")
return shearing | [
"def",
"create_2x2_shearing_matrix",
"(",
"shearing_coefs",
")",
":",
"shearing",
"=",
"[",
"[",
"1",
",",
"shearing_coefs",
"[",
"0",
"]",
"]",
",",
"[",
"shearing_coefs",
"[",
"1",
"]",
",",
"1",
"]",
"]",
"shearing",
"=",
"tf",
".",
"convert_to_tensor... | https://github.com/deepmind/multidim-image-augmentation/blob/7a180ec02fba2aac98f89cfff6fa6b647484d7cc/multidim_image_augmentation/deformation_utils.py#L130-L144 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_misc.py | python | DateTime.ToGMT | (*args, **kwargs) | return _misc_.DateTime_ToGMT(*args, **kwargs) | ToGMT(self, bool noDST=False) -> DateTime | ToGMT(self, bool noDST=False) -> DateTime | [
"ToGMT",
"(",
"self",
"bool",
"noDST",
"=",
"False",
")",
"-",
">",
"DateTime"
] | def ToGMT(*args, **kwargs):
"""ToGMT(self, bool noDST=False) -> DateTime"""
return _misc_.DateTime_ToGMT(*args, **kwargs) | [
"def",
"ToGMT",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"DateTime_ToGMT",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L3946-L3948 | |
arkenthera/electron-vibrancy | 383153ef9ccb23a6c7517150d6bb0794dff3115e | scripts/cpplint.py | python | CheckRValueReference | (filename, clean_lines, linenum, nesting_state, error) | Check for rvalue references.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found. | Check for rvalue references. | [
"Check",
"for",
"rvalue",
"references",
"."
] | def CheckRValueReference(filename, clean_lines, linenum, nesting_state, error):
"""Check for rvalue references.
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.
"""
# Find lines missing spaces around &&.
# TODO(unknown): currently we don't check for rvalue references
# with spaces surrounding the && to avoid false positives with
# boolean expressions.
line = clean_lines.elided[linenum]
match = Match(r'^(.*\S)&&', line)
if not match:
match = Match(r'(.*)&&\S', line)
if (not match) or '(&&)' in line or Search(r'\boperator\s*$', match.group(1)):
return
# Either poorly formed && or an rvalue reference, check the context
# to get a more accurate error message. Mostly we want to determine
# if what's to the left of "&&" is a type or not.
and_pos = len(match.group(1))
if IsRValueType(clean_lines, nesting_state, linenum, and_pos):
if not IsRValueAllowed(clean_lines, linenum):
error(filename, linenum, 'build/c++11', 3,
'RValue references are an unapproved C++ feature.')
else:
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around &&') | [
"def",
"CheckRValueReference",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"nesting_state",
",",
"error",
")",
":",
"# Find lines missing spaces around &&.",
"# TODO(unknown): currently we don't check for rvalue references",
"# with spaces surrounding the && to avoid fa... | https://github.com/arkenthera/electron-vibrancy/blob/383153ef9ccb23a6c7517150d6bb0794dff3115e/scripts/cpplint.py#L3307-L3339 | ||
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | tools/update-packaging/make_incremental_updates.py | python | bunzip_file | (filename) | Bzip's the file in palce. The original file is replaced with a bunzip'd version of itself.
doesn't matter if the filename ends in .bz2 or not | Bzip's the file in palce. The original file is replaced with a bunzip'd version of itself.
doesn't matter if the filename ends in .bz2 or not | [
"Bzip",
"s",
"the",
"file",
"in",
"palce",
".",
"The",
"original",
"file",
"is",
"replaced",
"with",
"a",
"bunzip",
"d",
"version",
"of",
"itself",
".",
"doesn",
"t",
"matter",
"if",
"the",
"filename",
"ends",
"in",
".",
"bz2",
"or",
"not"
] | def bunzip_file(filename):
""" Bzip's the file in palce. The original file is replaced with a bunzip'd version of itself.
doesn't matter if the filename ends in .bz2 or not"""
if not filename.endswith(".bz2"):
os.rename(filename, filename+".bz2")
filename=filename+".bz2"
exec_shell_cmd('bzip2 -d "' + filename+'"') | [
"def",
"bunzip_file",
"(",
"filename",
")",
":",
"if",
"not",
"filename",
".",
"endswith",
"(",
"\".bz2\"",
")",
":",
"os",
".",
"rename",
"(",
"filename",
",",
"filename",
"+",
"\".bz2\"",
")",
"filename",
"=",
"filename",
"+",
"\".bz2\"",
"exec_shell_cmd... | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/tools/update-packaging/make_incremental_updates.py#L208-L214 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py2/numpy/polynomial/hermite_e.py | python | hermevander2d | (x, y, deg) | return v.reshape(v.shape[:-2] + (-1,)) | Pseudo-Vandermonde matrix of given degrees.
Returns the pseudo-Vandermonde matrix of degrees `deg` and sample
points `(x, y)`. The pseudo-Vandermonde matrix is defined by
.. math:: V[..., (deg[1] + 1)*i + j] = He_i(x) * He_j(y),
where `0 <= i <= deg[0]` and `0 <= j <= deg[1]`. The leading indices of
`V` index the points `(x, y)` and the last index encodes the degrees of
the HermiteE polynomials.
If ``V = hermevander2d(x, y, [xdeg, ydeg])``, then the columns of `V`
correspond to the elements of a 2-D coefficient array `c` of shape
(xdeg + 1, ydeg + 1) in the order
.. math:: c_{00}, c_{01}, c_{02} ... , c_{10}, c_{11}, c_{12} ...
and ``np.dot(V, c.flat)`` and ``hermeval2d(x, y, c)`` will be the same
up to roundoff. This equivalence is useful both for least squares
fitting and for the evaluation of a large number of 2-D HermiteE
series of the same degrees and sample points.
Parameters
----------
x, y : array_like
Arrays of point coordinates, all of the same shape. The dtypes
will be converted to either float64 or complex128 depending on
whether any of the elements are complex. Scalars are converted to
1-D arrays.
deg : list of ints
List of maximum degrees of the form [x_deg, y_deg].
Returns
-------
vander2d : ndarray
The shape of the returned matrix is ``x.shape + (order,)``, where
:math:`order = (deg[0]+1)*(deg([1]+1)`. The dtype will be the same
as the converted `x` and `y`.
See Also
--------
hermevander, hermevander3d. hermeval2d, hermeval3d
Notes
-----
.. versionadded:: 1.7.0 | Pseudo-Vandermonde matrix of given degrees. | [
"Pseudo",
"-",
"Vandermonde",
"matrix",
"of",
"given",
"degrees",
"."
] | def hermevander2d(x, y, deg):
"""Pseudo-Vandermonde matrix of given degrees.
Returns the pseudo-Vandermonde matrix of degrees `deg` and sample
points `(x, y)`. The pseudo-Vandermonde matrix is defined by
.. math:: V[..., (deg[1] + 1)*i + j] = He_i(x) * He_j(y),
where `0 <= i <= deg[0]` and `0 <= j <= deg[1]`. The leading indices of
`V` index the points `(x, y)` and the last index encodes the degrees of
the HermiteE polynomials.
If ``V = hermevander2d(x, y, [xdeg, ydeg])``, then the columns of `V`
correspond to the elements of a 2-D coefficient array `c` of shape
(xdeg + 1, ydeg + 1) in the order
.. math:: c_{00}, c_{01}, c_{02} ... , c_{10}, c_{11}, c_{12} ...
and ``np.dot(V, c.flat)`` and ``hermeval2d(x, y, c)`` will be the same
up to roundoff. This equivalence is useful both for least squares
fitting and for the evaluation of a large number of 2-D HermiteE
series of the same degrees and sample points.
Parameters
----------
x, y : array_like
Arrays of point coordinates, all of the same shape. The dtypes
will be converted to either float64 or complex128 depending on
whether any of the elements are complex. Scalars are converted to
1-D arrays.
deg : list of ints
List of maximum degrees of the form [x_deg, y_deg].
Returns
-------
vander2d : ndarray
The shape of the returned matrix is ``x.shape + (order,)``, where
:math:`order = (deg[0]+1)*(deg([1]+1)`. The dtype will be the same
as the converted `x` and `y`.
See Also
--------
hermevander, hermevander3d. hermeval2d, hermeval3d
Notes
-----
.. versionadded:: 1.7.0
"""
ideg = [int(d) for d in deg]
is_valid = [id == d and id >= 0 for id, d in zip(ideg, deg)]
if is_valid != [1, 1]:
raise ValueError("degrees must be non-negative integers")
degx, degy = ideg
x, y = np.array((x, y), copy=0) + 0.0
vx = hermevander(x, degx)
vy = hermevander(y, degy)
v = vx[..., None]*vy[..., None,:]
return v.reshape(v.shape[:-2] + (-1,)) | [
"def",
"hermevander2d",
"(",
"x",
",",
"y",
",",
"deg",
")",
":",
"ideg",
"=",
"[",
"int",
"(",
"d",
")",
"for",
"d",
"in",
"deg",
"]",
"is_valid",
"=",
"[",
"id",
"==",
"d",
"and",
"id",
">=",
"0",
"for",
"id",
",",
"d",
"in",
"zip",
"(",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/polynomial/hermite_e.py#L1237-L1297 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/difflib.py | python | SequenceMatcher.real_quick_ratio | (self) | return _calculate_ratio(min(la, lb), la + lb) | Return an upper bound on ratio() very quickly.
This isn't defined beyond that it is an upper bound on .ratio(), and
is faster to compute than either .ratio() or .quick_ratio(). | Return an upper bound on ratio() very quickly. | [
"Return",
"an",
"upper",
"bound",
"on",
"ratio",
"()",
"very",
"quickly",
"."
] | def real_quick_ratio(self):
"""Return an upper bound on ratio() very quickly.
This isn't defined beyond that it is an upper bound on .ratio(), and
is faster to compute than either .ratio() or .quick_ratio().
"""
la, lb = len(self.a), len(self.b)
# can't have more matches than the number of elements in the
# shorter sequence
return _calculate_ratio(min(la, lb), la + lb) | [
"def",
"real_quick_ratio",
"(",
"self",
")",
":",
"la",
",",
"lb",
"=",
"len",
"(",
"self",
".",
"a",
")",
",",
"len",
"(",
"self",
".",
"b",
")",
"# can't have more matches than the number of elements in the",
"# shorter sequence",
"return",
"_calculate_ratio",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/difflib.py#L676-L686 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py3/setuptools/_distutils/command/install.py | python | install.get_outputs | (self) | return outputs | Assembles the outputs of all the sub-commands. | Assembles the outputs of all the sub-commands. | [
"Assembles",
"the",
"outputs",
"of",
"all",
"the",
"sub",
"-",
"commands",
"."
] | def get_outputs(self):
"""Assembles the outputs of all the sub-commands."""
outputs = []
for cmd_name in self.get_sub_commands():
cmd = self.get_finalized_command(cmd_name)
# Add the contents of cmd.get_outputs(), ensuring
# that outputs doesn't contain duplicate entries
for filename in cmd.get_outputs():
if filename not in outputs:
outputs.append(filename)
if self.path_file and self.install_path_file:
outputs.append(os.path.join(self.install_libbase,
self.path_file + ".pth"))
return outputs | [
"def",
"get_outputs",
"(",
"self",
")",
":",
"outputs",
"=",
"[",
"]",
"for",
"cmd_name",
"in",
"self",
".",
"get_sub_commands",
"(",
")",
":",
"cmd",
"=",
"self",
".",
"get_finalized_command",
"(",
"cmd_name",
")",
"# Add the contents of cmd.get_outputs(), ensu... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/_distutils/command/install.py#L664-L679 | |
microsoft/checkedc-clang | a173fefde5d7877b7750e7ce96dd08cf18baebf2 | compiler-rt/lib/sanitizer_common/scripts/cpplint.py | python | GetHeaderGuardCPPVariable | (filename) | return re.sub(r'[^a-zA-Z0-9]', '_', file_path_from_root).upper() + '_' | Returns the CPP variable that should be used as a header guard.
Args:
filename: The name of a C++ header file.
Returns:
The CPP variable that should be used as a header guard in the
named file. | Returns the CPP variable that should be used as a header guard. | [
"Returns",
"the",
"CPP",
"variable",
"that",
"should",
"be",
"used",
"as",
"a",
"header",
"guard",
"."
] | def GetHeaderGuardCPPVariable(filename):
"""Returns the CPP variable that should be used as a header guard.
Args:
filename: The name of a C++ header file.
Returns:
The CPP variable that should be used as a header guard in the
named file.
"""
# Restores original filename in case that cpplint is invoked from Emacs's
# flymake.
filename = re.sub(r'_flymake\.h$', '.h', filename)
filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename)
# Replace 'c++' with 'cpp'.
filename = filename.replace('C++', 'cpp').replace('c++', 'cpp')
fileinfo = FileInfo(filename)
file_path_from_root = fileinfo.RepositoryName()
def FixupPathFromRoot():
if _root_debug:
sys.stderr.write("\n_root fixup, _root = '%s', repository name = '%s'\n"
%(_root, fileinfo.RepositoryName()))
# Process the file path with the --root flag if it was set.
if not _root:
if _root_debug:
sys.stderr.write("_root unspecified\n")
return file_path_from_root
def StripListPrefix(lst, prefix):
# f(['x', 'y'], ['w, z']) -> None (not a valid prefix)
if lst[:len(prefix)] != prefix:
return None
# f(['a, 'b', 'c', 'd'], ['a', 'b']) -> ['c', 'd']
return lst[(len(prefix)):]
# root behavior:
# --root=subdir , lstrips subdir from the header guard
maybe_path = StripListPrefix(PathSplitToList(file_path_from_root),
PathSplitToList(_root))
if _root_debug:
sys.stderr.write(("_root lstrip (maybe_path=%s, file_path_from_root=%s," +
" _root=%s)\n") %(maybe_path, file_path_from_root, _root))
if maybe_path:
return os.path.join(*maybe_path)
# --root=.. , will prepend the outer directory to the header guard
full_path = fileinfo.FullName()
root_abspath = os.path.abspath(_root)
maybe_path = StripListPrefix(PathSplitToList(full_path),
PathSplitToList(root_abspath))
if _root_debug:
sys.stderr.write(("_root prepend (maybe_path=%s, full_path=%s, " +
"root_abspath=%s)\n") %(maybe_path, full_path, root_abspath))
if maybe_path:
return os.path.join(*maybe_path)
if _root_debug:
sys.stderr.write("_root ignore, returning %s\n" %(file_path_from_root))
# --root=FAKE_DIR is ignored
return file_path_from_root
file_path_from_root = FixupPathFromRoot()
return re.sub(r'[^a-zA-Z0-9]', '_', file_path_from_root).upper() + '_' | [
"def",
"GetHeaderGuardCPPVariable",
"(",
"filename",
")",
":",
"# Restores original filename in case that cpplint is invoked from Emacs's",
"# flymake.",
"filename",
"=",
"re",
".",
"sub",
"(",
"r'_flymake\\.h$'",
",",
"'.h'",
",",
"filename",
")",
"filename",
"=",
"re",
... | https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L1809-L1882 | |
rapidsai/cudf | d5b2448fc69f17509304d594f029d0df56984962 | python/cudf_kafka/versioneer.py | python | get_version | () | return get_versions()["version"] | Get the short version string for this project. | Get the short version string for this project. | [
"Get",
"the",
"short",
"version",
"string",
"for",
"this",
"project",
"."
] | def get_version():
"""Get the short version string for this project."""
return get_versions()["version"] | [
"def",
"get_version",
"(",
")",
":",
"return",
"get_versions",
"(",
")",
"[",
"\"version\"",
"]"
] | https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf_kafka/versioneer.py#L1535-L1537 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/urllib3/packages/ssl_match_hostname/_implementation.py | python | _dnsname_match | (dn, hostname, max_wildcards=1) | return pat.match(hostname) | Matching according to RFC 6125, section 6.4.3
http://tools.ietf.org/html/rfc6125#section-6.4.3 | Matching according to RFC 6125, section 6.4.3 | [
"Matching",
"according",
"to",
"RFC",
"6125",
"section",
"6",
".",
"4",
".",
"3"
] | def _dnsname_match(dn, hostname, max_wildcards=1):
"""Matching according to RFC 6125, section 6.4.3
http://tools.ietf.org/html/rfc6125#section-6.4.3
"""
pats = []
if not dn:
return False
# Ported from python3-syntax:
# leftmost, *remainder = dn.split(r'.')
parts = dn.split(r".")
leftmost = parts[0]
remainder = parts[1:]
wildcards = leftmost.count("*")
if wildcards > max_wildcards:
# Issue #17980: avoid denials of service by refusing more
# than one wildcard per fragment. A survey of established
# policy among SSL implementations showed it to be a
# reasonable choice.
raise CertificateError(
"too many wildcards in certificate DNS name: " + repr(dn)
)
# speed up common case w/o wildcards
if not wildcards:
return dn.lower() == hostname.lower()
# RFC 6125, section 6.4.3, subitem 1.
# The client SHOULD NOT attempt to match a presented identifier in which
# the wildcard character comprises a label other than the left-most label.
if leftmost == "*":
# When '*' is a fragment by itself, it matches a non-empty dotless
# fragment.
pats.append("[^.]+")
elif leftmost.startswith("xn--") or hostname.startswith("xn--"):
# RFC 6125, section 6.4.3, subitem 3.
# The client SHOULD NOT attempt to match a presented identifier
# where the wildcard character is embedded within an A-label or
# U-label of an internationalized domain name.
pats.append(re.escape(leftmost))
else:
# Otherwise, '*' matches any dotless string, e.g. www*
pats.append(re.escape(leftmost).replace(r"\*", "[^.]*"))
# add the remaining fragments, ignore any wildcards
for frag in remainder:
pats.append(re.escape(frag))
pat = re.compile(r"\A" + r"\.".join(pats) + r"\Z", re.IGNORECASE)
return pat.match(hostname) | [
"def",
"_dnsname_match",
"(",
"dn",
",",
"hostname",
",",
"max_wildcards",
"=",
"1",
")",
":",
"pats",
"=",
"[",
"]",
"if",
"not",
"dn",
":",
"return",
"False",
"# Ported from python3-syntax:",
"# leftmost, *remainder = dn.split(r'.')",
"parts",
"=",
"dn",
".",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/urllib3/packages/ssl_match_hostname/_implementation.py#L25-L76 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/botocore/vendored/requests/utils.py | python | from_key_val_list | (value) | return OrderedDict(value) | Take an object and test to see if it can be represented as a
dictionary. Unless it can not be represented as such, return an
OrderedDict, e.g.,
::
>>> from_key_val_list([('key', 'val')])
OrderedDict([('key', 'val')])
>>> from_key_val_list('string')
ValueError: need more than 1 value to unpack
>>> from_key_val_list({'key': 'val'})
OrderedDict([('key', 'val')]) | Take an object and test to see if it can be represented as a
dictionary. Unless it can not be represented as such, return an
OrderedDict, e.g., | [
"Take",
"an",
"object",
"and",
"test",
"to",
"see",
"if",
"it",
"can",
"be",
"represented",
"as",
"a",
"dictionary",
".",
"Unless",
"it",
"can",
"not",
"be",
"represented",
"as",
"such",
"return",
"an",
"OrderedDict",
"e",
".",
"g",
"."
] | def from_key_val_list(value):
"""Take an object and test to see if it can be represented as a
dictionary. Unless it can not be represented as such, return an
OrderedDict, e.g.,
::
>>> from_key_val_list([('key', 'val')])
OrderedDict([('key', 'val')])
>>> from_key_val_list('string')
ValueError: need more than 1 value to unpack
>>> from_key_val_list({'key': 'val'})
OrderedDict([('key', 'val')])
"""
if value is None:
return None
if isinstance(value, (str, bytes, bool, int)):
raise ValueError('cannot encode objects that are not 2-tuples')
return OrderedDict(value) | [
"def",
"from_key_val_list",
"(",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"value",
",",
"(",
"str",
",",
"bytes",
",",
"bool",
",",
"int",
")",
")",
":",
"raise",
"ValueError",
"(",
"'cannot encode... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/botocore/vendored/requests/utils.py#L124-L144 | |
fengbingchun/NN_Test | d6305825d5273e4569ccd1eda9ffa2a9c72e18d2 | src/tiny-dnn/third_party/cpplint.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.
#
# Also skip blank line checks for 'extern "C"' blocks, which are formatted
# like namespaces.
if (IsBlankLine(line) and
not nesting_state.InNamespaceBody() and
not nesting_state.InExternC()):
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, check comments
next_line_start = 0
if linenum + 1 < clean_lines.NumLines():
next_line = raw[linenum + 1]
next_line_start = len(next_line) - len(next_line.lstrip())
CheckComment(line, filename, linenum, next_line_start, error)
# get rid of comments and strings
line = clean_lines.elided[linenum]
# You shouldn't have spaces before your brackets, except maybe after
# 'delete []' or 'return []() {};'
if Search(r'\w\s+\[', line) and not Search(r'(?:delete|return)\s+\[', line):
error(filename, linenum, 'whitespace/braces', 5,
'Extra space before [')
# In range-based for, we wanted spaces before and after the colon, but
# not around "::" tokens that might appear.
if (Search(r'for *\(.*[^:]:[^: ]', line) or
Search(r'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/fengbingchun/NN_Test/blob/d6305825d5273e4569ccd1eda9ffa2a9c72e18d2/src/tiny-dnn/third_party/cpplint.py#L3312-L3437 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | FlexGridSizer.AddGrowableCol | (*args, **kwargs) | return _core_.FlexGridSizer_AddGrowableCol(*args, **kwargs) | AddGrowableCol(self, size_t idx, int proportion=0)
Specifies that column *idx* (starting from zero) should be grown if
there is extra space available to the sizer.
The *proportion* parameter has the same meaning as the stretch factor
for the box sizers except that if all proportions are 0, then all
columns are resized equally (instead of not being resized at all). | AddGrowableCol(self, size_t idx, int proportion=0) | [
"AddGrowableCol",
"(",
"self",
"size_t",
"idx",
"int",
"proportion",
"=",
"0",
")"
] | def AddGrowableCol(*args, **kwargs):
"""
AddGrowableCol(self, size_t idx, int proportion=0)
Specifies that column *idx* (starting from zero) should be grown if
there is extra space available to the sizer.
The *proportion* parameter has the same meaning as the stretch factor
for the box sizers except that if all proportions are 0, then all
columns are resized equally (instead of not being resized at all).
"""
return _core_.FlexGridSizer_AddGrowableCol(*args, **kwargs) | [
"def",
"AddGrowableCol",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"FlexGridSizer_AddGrowableCol",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L15361-L15372 | |
RLBot/RLBot | 34332b12cf158b3ef8dbf174ae67c53683368a9d | src/main/python/rlbot/utils/class_importer.py | python | ExternalClassWrapper.get_loaded_class | (self) | return self.loaded_class | Guaranteed to return a valid class that extends base_class. | Guaranteed to return a valid class that extends base_class. | [
"Guaranteed",
"to",
"return",
"a",
"valid",
"class",
"that",
"extends",
"base_class",
"."
] | def get_loaded_class(self):
"""
Guaranteed to return a valid class that extends base_class.
"""
return self.loaded_class | [
"def",
"get_loaded_class",
"(",
"self",
")",
":",
"return",
"self",
".",
"loaded_class"
] | https://github.com/RLBot/RLBot/blob/34332b12cf158b3ef8dbf174ae67c53683368a9d/src/main/python/rlbot/utils/class_importer.py#L42-L46 | |
NVIDIA/TensorRT | 42805f078052daad1a98bc5965974fcffaad0960 | tools/pytorch-quantization/pytorch_quantization/calib/histogram.py | python | HistogramCalibrator.collect | (self, x) | Collect histogram | Collect histogram | [
"Collect",
"histogram"
] | def collect(self, x):
"""Collect histogram"""
if torch.min(x) < 0.:
logging.log_first_n(
logging.INFO,
("Calibrator encountered negative values. It shouldn't happen after ReLU. "
"Make sure this is the right tensor to calibrate."),
1)
x = x.abs()
x = x.float()
if not self._torch_hist:
x_np = x.cpu().detach().numpy()
if self._skip_zeros:
x_np = x_np[np.where(x_np != 0)]
if self._calib_bin_edges is None and self._calib_hist is None:
# first time it uses num_bins to compute histogram.
self._calib_hist, self._calib_bin_edges = np.histogram(x_np, bins=self._num_bins)
else:
temp_amax = np.max(x_np)
if temp_amax > self._calib_bin_edges[-1]:
# increase the number of bins
width = self._calib_bin_edges[1] - self._calib_bin_edges[0]
# NOTE: np.arange may create an extra bin after the one containing temp_amax
new_bin_edges = np.arange(self._calib_bin_edges[-1] + width, temp_amax + width, width)
self._calib_bin_edges = np.hstack((self._calib_bin_edges, new_bin_edges))
hist, self._calib_bin_edges = np.histogram(x_np, bins=self._calib_bin_edges)
hist[:len(self._calib_hist)] += self._calib_hist
self._calib_hist = hist
else:
# This branch of code is designed to match numpy version as close as possible
with torch.no_grad():
if self._skip_zeros:
x = x[torch.where(x != 0)]
# Because we collect histogram on absolute value, setting min=0 simplifying the rare case where
# minimum value is not exactly 0 and first batch collected has larger min value than later batches
x_max = x.max()
if self._calib_bin_edges is None and self._calib_hist is None:
self._calib_hist = torch.histc(x, bins=self._num_bins, min=0, max=x_max)
self._calib_bin_edges = torch.linspace(0, x_max, self._num_bins + 1)
else:
if x_max > self._calib_bin_edges[-1]:
width = self._calib_bin_edges[1] - self._calib_bin_edges[0]
self._num_bins = int((x_max / width).ceil().item())
self._calib_bin_edges = torch.arange(0, x_max + width, width, device=x.device)
hist = torch.histc(x, bins=self._num_bins, min=0, max=self._calib_bin_edges[-1])
hist[:self._calib_hist.numel()] += self._calib_hist
self._calib_hist = hist | [
"def",
"collect",
"(",
"self",
",",
"x",
")",
":",
"if",
"torch",
".",
"min",
"(",
"x",
")",
"<",
"0.",
":",
"logging",
".",
"log_first_n",
"(",
"logging",
".",
"INFO",
",",
"(",
"\"Calibrator encountered negative values. It shouldn't happen after ReLU. \"",
"... | https://github.com/NVIDIA/TensorRT/blob/42805f078052daad1a98bc5965974fcffaad0960/tools/pytorch-quantization/pytorch_quantization/calib/histogram.py#L66-L118 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_controls.py | python | ListCtrl.InsertStringItem | (*args, **kwargs) | return _controls_.ListCtrl_InsertStringItem(*args, **kwargs) | InsertStringItem(self, long index, String label, int imageIndex=-1) -> long | InsertStringItem(self, long index, String label, int imageIndex=-1) -> long | [
"InsertStringItem",
"(",
"self",
"long",
"index",
"String",
"label",
"int",
"imageIndex",
"=",
"-",
"1",
")",
"-",
">",
"long"
] | def InsertStringItem(*args, **kwargs):
"""InsertStringItem(self, long index, String label, int imageIndex=-1) -> long"""
return _controls_.ListCtrl_InsertStringItem(*args, **kwargs) | [
"def",
"InsertStringItem",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"ListCtrl_InsertStringItem",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L4704-L4706 | |
eerolanguage/clang | 91360bee004a1cbdb95fe5eb605ef243152da41b | bindings/python/clang/cindex.py | python | Cursor.raw_comment | (self) | return conf.lib.clang_Cursor_getRawCommentText(self) | Returns the raw comment text associated with that Cursor | Returns the raw comment text associated with that Cursor | [
"Returns",
"the",
"raw",
"comment",
"text",
"associated",
"with",
"that",
"Cursor"
] | def raw_comment(self):
"""Returns the raw comment text associated with that Cursor"""
return conf.lib.clang_Cursor_getRawCommentText(self) | [
"def",
"raw_comment",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_Cursor_getRawCommentText",
"(",
"self",
")"
] | https://github.com/eerolanguage/clang/blob/91360bee004a1cbdb95fe5eb605ef243152da41b/bindings/python/clang/cindex.py#L1348-L1350 | |
microsoft/clang | 86d4513d3e0daa4d5a29b0b1de7c854ca15f9fe5 | bindings/python/clang/cindex.py | python | Token.spelling | (self) | return conf.lib.clang_getTokenSpelling(self._tu, self) | The spelling of this token.
This is the textual representation of the token in source. | The spelling of this token. | [
"The",
"spelling",
"of",
"this",
"token",
"."
] | def spelling(self):
"""The spelling of this token.
This is the textual representation of the token in source.
"""
return conf.lib.clang_getTokenSpelling(self._tu, self) | [
"def",
"spelling",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_getTokenSpelling",
"(",
"self",
".",
"_tu",
",",
"self",
")"
] | https://github.com/microsoft/clang/blob/86d4513d3e0daa4d5a29b0b1de7c854ca15f9fe5/bindings/python/clang/cindex.py#L3270-L3275 | |
gnuradio/gnuradio | 09c3c4fa4bfb1a02caac74cb5334dfe065391e3b | grc/gui/canvas/flowgraph.py | python | FlowGraph.copy_to_clipboard | (self) | return clipboard | Copy the selected blocks and connections into the clipboard.
Returns:
the clipboard | Copy the selected blocks and connections into the clipboard. | [
"Copy",
"the",
"selected",
"blocks",
"and",
"connections",
"into",
"the",
"clipboard",
"."
] | def copy_to_clipboard(self):
"""
Copy the selected blocks and connections into the clipboard.
Returns:
the clipboard
"""
# get selected blocks
blocks = list(self.selected_blocks())
if not blocks:
return None
# calc x and y min
x_min, y_min = blocks[0].coordinate
for block in blocks:
x, y = block.coordinate
x_min = min(x, x_min)
y_min = min(y, y_min)
# get connections between selected blocks
connections = list(filter(
lambda c: c.source_block in blocks and c.sink_block in blocks,
self.connections,
))
clipboard = (
(x_min, y_min),
[block.export_data() for block in blocks],
[connection.export_data() for connection in connections],
)
return clipboard | [
"def",
"copy_to_clipboard",
"(",
"self",
")",
":",
"# get selected blocks",
"blocks",
"=",
"list",
"(",
"self",
".",
"selected_blocks",
"(",
")",
")",
"if",
"not",
"blocks",
":",
"return",
"None",
"# calc x and y min",
"x_min",
",",
"y_min",
"=",
"blocks",
"... | https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/grc/gui/canvas/flowgraph.py#L218-L245 | |
mapnik/mapnik | f3da900c355e1d15059c4a91b00203dcc9d9f0ef | scons/scons-local-4.1.0/SCons/Subst.py | python | scons_subst | (strSubst, env, mode=SUBST_RAW, target=None, source=None, gvars={}, lvars={}, conv=None) | return result | Expand a string or list containing construction variable
substitutions.
This is the work-horse function for substitutions in file names
and the like. The companion scons_subst_list() function (below)
handles separating command lines into lists of arguments, so see
that function if that's what you're looking for. | Expand a string or list containing construction variable
substitutions. | [
"Expand",
"a",
"string",
"or",
"list",
"containing",
"construction",
"variable",
"substitutions",
"."
] | def scons_subst(strSubst, env, mode=SUBST_RAW, target=None, source=None, gvars={}, lvars={}, conv=None):
"""Expand a string or list containing construction variable
substitutions.
This is the work-horse function for substitutions in file names
and the like. The companion scons_subst_list() function (below)
handles separating command lines into lists of arguments, so see
that function if that's what you're looking for.
"""
if (isinstance(strSubst, str) and '$' not in strSubst) or isinstance(strSubst, CmdStringHolder):
return strSubst
if conv is None:
conv = _strconv[mode]
# Doing this every time is a bit of a waste, since the Executor
# has typically already populated the OverrideEnvironment with
# $TARGET/$SOURCE variables. We're keeping this (for now), though,
# because it supports existing behavior that allows us to call
# an Action directly with an arbitrary target+source pair, which
# we use in Tool/tex.py to handle calling $BIBTEX when necessary.
# If we dropped that behavior (or found another way to cover it),
# we could get rid of this call completely and just rely on the
# Executor setting the variables.
if 'TARGET' not in lvars:
d = subst_dict(target, source)
if d:
lvars = lvars.copy()
lvars.update(d)
# We're (most likely) going to eval() things. If Python doesn't
# find a __builtins__ value in the global dictionary used for eval(),
# it copies the current global values for you. Avoid this by
# setting it explicitly and then deleting, so we don't pollute the
# construction environment Dictionary(ies) that are typically used
# for expansion.
gvars['__builtins__'] = __builtins__
ss = StringSubber(env, mode, conv, gvars)
result = ss.substitute(strSubst, lvars)
try:
del gvars['__builtins__']
except KeyError:
pass
res = result
if is_String(result):
# Remove $(-$) pairs and any stuff in between,
# if that's appropriate.
remove = _regex_remove[mode]
if remove:
if mode == SUBST_SIG:
result = _list_remove[mode](remove.split(result))
if result is None:
raise SCons.Errors.UserError("Unbalanced $(/$) in: " + res)
result = ' '.join(result)
else:
result = remove.sub('', result)
if mode != SUBST_RAW:
# Compress strings of white space characters into
# a single space.
result = _space_sep.sub(' ', result).strip()
# Now replace escaped $'s currently "$$"
# This is needed because we now retain $$ instead of
# replacing them during substition to avoid
# improperly trying to escape "$$(" as being "$("
result = result.replace('$$','$')
elif is_Sequence(result):
remove = _list_remove[mode]
if remove:
result = remove(result)
if result is None:
raise SCons.Errors.UserError("Unbalanced $(/$) in: " + str(res))
return result | [
"def",
"scons_subst",
"(",
"strSubst",
",",
"env",
",",
"mode",
"=",
"SUBST_RAW",
",",
"target",
"=",
"None",
",",
"source",
"=",
"None",
",",
"gvars",
"=",
"{",
"}",
",",
"lvars",
"=",
"{",
"}",
",",
"conv",
"=",
"None",
")",
":",
"if",
"(",
"... | https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Subst.py#L800-L876 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/labeled_tensor/python/ops/_typecheck.py | python | register_type_abbreviation | (name, alias) | Register an abbreviation for a type in typecheck tracebacks.
This makes otherwise very long typecheck errors much more readable.
Example:
typecheck.register_type_abbreviation(tf.Dimension, 'tf.Dimension')
Args:
name: type or class to abbreviate.
alias: string alias to substitute. | Register an abbreviation for a type in typecheck tracebacks. | [
"Register",
"an",
"abbreviation",
"for",
"a",
"type",
"in",
"typecheck",
"tracebacks",
"."
] | def register_type_abbreviation(name, alias):
"""Register an abbreviation for a type in typecheck tracebacks.
This makes otherwise very long typecheck errors much more readable.
Example:
typecheck.register_type_abbreviation(tf.Dimension, 'tf.Dimension')
Args:
name: type or class to abbreviate.
alias: string alias to substitute.
"""
_TYPE_ABBREVIATIONS[name] = alias | [
"def",
"register_type_abbreviation",
"(",
"name",
",",
"alias",
")",
":",
"_TYPE_ABBREVIATIONS",
"[",
"name",
"]",
"=",
"alias"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/labeled_tensor/python/ops/_typecheck.py#L187-L199 | ||
SequoiaDB/SequoiaDB | 2894ed7e5bd6fe57330afc900cf76d0ff0df9f64 | tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py | python | uCSIsMiscellaneousTechnical | (code) | return ret | Check whether the character is part of
MiscellaneousTechnical UCS Block | Check whether the character is part of
MiscellaneousTechnical UCS Block | [
"Check",
"whether",
"the",
"character",
"is",
"part",
"of",
"MiscellaneousTechnical",
"UCS",
"Block"
] | def uCSIsMiscellaneousTechnical(code):
"""Check whether the character is part of
MiscellaneousTechnical UCS Block """
ret = libxml2mod.xmlUCSIsMiscellaneousTechnical(code)
return ret | [
"def",
"uCSIsMiscellaneousTechnical",
"(",
"code",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlUCSIsMiscellaneousTechnical",
"(",
"code",
")",
"return",
"ret"
] | https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L2714-L2718 | |
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | snapx/snapx/classes/digraph.py | python | DiGraph.pred | (self) | PORTED FROM NETWORKX
Graph adjacency object holding the predecessors of each node.
This object is a read-only dict-like structure with node keys
and neighbor-dict values. The neighbor-dict is keyed by neighbor
to the edge-data-dict. So `G.pred[2][3]['color'] = 'blue'` sets
the color of the edge `(3, 2)` to `"blue"`.
Iterating over G.pred behaves like a dict. Useful idioms include
`for nbr, datadict in G.pred[n].items():`. A data-view not provided
by dicts also exists: `for nbr, foovalue in G.pred[node].data('foo'):`
A default can be set via a `default` argument to the `data` method. | PORTED FROM NETWORKX
Graph adjacency object holding the predecessors of each node. | [
"PORTED",
"FROM",
"NETWORKX",
"Graph",
"adjacency",
"object",
"holding",
"the",
"predecessors",
"of",
"each",
"node",
"."
] | def pred(self):
"""PORTED FROM NETWORKX
Graph adjacency object holding the predecessors of each node.
This object is a read-only dict-like structure with node keys
and neighbor-dict values. The neighbor-dict is keyed by neighbor
to the edge-data-dict. So `G.pred[2][3]['color'] = 'blue'` sets
the color of the edge `(3, 2)` to `"blue"`.
Iterating over G.pred behaves like a dict. Useful idioms include
`for nbr, datadict in G.pred[n].items():`. A data-view not provided
by dicts also exists: `for nbr, foovalue in G.pred[node].data('foo'):`
A default can be set via a `default` argument to the `data` method.
"""
raise NotImplementedError("TODO") | [
"def",
"pred",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"TODO\"",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/snapx/snapx/classes/digraph.py#L383-L397 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqt/mantidqt/widgets/superplot/presenter.py | python | SuperplotPresenter._on_hold | (self) | Add the selected ws, sp pair to the plot. | Add the selected ws, sp pair to the plot. | [
"Add",
"the",
"selected",
"ws",
"sp",
"pair",
"to",
"the",
"plot",
"."
] | def _on_hold(self):
"""
Add the selected ws, sp pair to the plot.
"""
if self._view.is_spectrum_selection_disabled():
return
selection = self._view.get_selection()
spectrum_index = self._view.get_spectrum_slider_position()
mode = self._view.get_mode()
for ws_name in selection:
self._model.add_data(ws_name, spectrum_index)
selection[ws_name] = [spectrum_index]
if mode == self.SPECTRUM_MODE_TEXT:
self._model.set_spectrum_mode()
self._view.set_available_modes([self.SPECTRUM_MODE_TEXT])
else:
self._model.set_bin_mode()
self._view.set_available_modes([self.BIN_MODE_TEXT])
self._view.set_hold_button_text(self.HOLD_BUTTON_TEXT_CHECKED)
self._update_list()
self._view.set_selection(selection)
self._update_plot() | [
"def",
"_on_hold",
"(",
"self",
")",
":",
"if",
"self",
".",
"_view",
".",
"is_spectrum_selection_disabled",
"(",
")",
":",
"return",
"selection",
"=",
"self",
".",
"_view",
".",
"get_selection",
"(",
")",
"spectrum_index",
"=",
"self",
".",
"_view",
".",
... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/widgets/superplot/presenter.py#L498-L519 | ||
espressomd/espresso | 7e29f9052e710fe1ebf0f5d2a8076b32921fbc6a | samples/gibbs_ensemble/run_sim.py | python | perform_move_particle | (boxes) | return True | Perform a particle move, check and revert if necessary | Perform a particle move, check and revert if necessary | [
"Perform",
"a",
"particle",
"move",
"check",
"and",
"revert",
"if",
"necessary"
] | def perform_move_particle(boxes):
""" Perform a particle move, check and revert if necessary """
# Choose random box
box = boxes[choose_random_box(boxes)]
# Send message to Client
box.send_data([MessageID.MOVE_PART, DX_MAX])
box.recv_energy()
# Debug
logging.debug(f"Performing particle move in {box.box_name}.")
# ---- Check move ----
# Check move probability (see (8.3.1) in Frenkel, Smit)
acc = np.exp(- 1. / kT * box.diff_energy)
# Draw random number
rand = np.random.random()
# Check if move was valid
if rand > acc:
# Reject move, restore old configuration
box.send_data([MessageID.MOVE_PART_REVERT])
box.energy = box.old_energy
return False
# Debug
logging.debug("Particle move accepted.")
# Only if rand < acc
return True | [
"def",
"perform_move_particle",
"(",
"boxes",
")",
":",
"# Choose random box",
"box",
"=",
"boxes",
"[",
"choose_random_box",
"(",
"boxes",
")",
"]",
"# Send message to Client",
"box",
".",
"send_data",
"(",
"[",
"MessageID",
".",
"MOVE_PART",
",",
"DX_MAX",
"]"... | https://github.com/espressomd/espresso/blob/7e29f9052e710fe1ebf0f5d2a8076b32921fbc6a/samples/gibbs_ensemble/run_sim.py#L239-L271 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/layers/python/layers/feature_column.py | python | _RealValuedColumn.key | (self) | return self._key_without_properties(["normalizer"]) | Returns a string which will be used as a key when we do sorting. | Returns a string which will be used as a key when we do sorting. | [
"Returns",
"a",
"string",
"which",
"will",
"be",
"used",
"as",
"a",
"key",
"when",
"we",
"do",
"sorting",
"."
] | def key(self):
"""Returns a string which will be used as a key when we do sorting."""
return self._key_without_properties(["normalizer"]) | [
"def",
"key",
"(",
"self",
")",
":",
"return",
"self",
".",
"_key_without_properties",
"(",
"[",
"\"normalizer\"",
"]",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/layers/python/layers/feature_column.py#L1864-L1866 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/seq2seq/python/ops/helper.py | python | GreedyEmbeddingHelper.__init__ | (self, embedding, start_tokens, end_token) | Initializer.
Args:
embedding: A callable that takes a vector tensor of `ids` (argmax ids),
or the `params` argument for `embedding_lookup`. The returned tensor
will be passed to the decoder input.
start_tokens: `int32` vector shaped `[batch_size]`, the start tokens.
end_token: `int32` scalar, the token that marks end of decoding.
Raises:
ValueError: if `start_tokens` is not a 1D tensor or `end_token` is not a
scalar. | Initializer. | [
"Initializer",
"."
] | def __init__(self, embedding, start_tokens, end_token):
"""Initializer.
Args:
embedding: A callable that takes a vector tensor of `ids` (argmax ids),
or the `params` argument for `embedding_lookup`. The returned tensor
will be passed to the decoder input.
start_tokens: `int32` vector shaped `[batch_size]`, the start tokens.
end_token: `int32` scalar, the token that marks end of decoding.
Raises:
ValueError: if `start_tokens` is not a 1D tensor or `end_token` is not a
scalar.
"""
if callable(embedding):
self._embedding_fn = embedding
else:
self._embedding_fn = (
lambda ids: embedding_ops.embedding_lookup(embedding, ids))
self._start_tokens = ops.convert_to_tensor(
start_tokens, dtype=dtypes.int32, name="start_tokens")
self._end_token = ops.convert_to_tensor(
end_token, dtype=dtypes.int32, name="end_token")
if self._start_tokens.get_shape().ndims != 1:
raise ValueError("start_tokens must be a vector")
self._batch_size = array_ops.size(start_tokens)
if self._end_token.get_shape().ndims != 0:
raise ValueError("end_token must be a scalar")
self._start_inputs = self._embedding_fn(self._start_tokens) | [
"def",
"__init__",
"(",
"self",
",",
"embedding",
",",
"start_tokens",
",",
"end_token",
")",
":",
"if",
"callable",
"(",
"embedding",
")",
":",
"self",
".",
"_embedding_fn",
"=",
"embedding",
"else",
":",
"self",
".",
"_embedding_fn",
"=",
"(",
"lambda",
... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/seq2seq/python/ops/helper.py#L489-L518 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/configparser/backports/configparser/__init__.py | python | ConfigParser.add_section | (self, section) | Create a new section in the configuration. Extends
RawConfigParser.add_section by validating if the section name is
a string. | Create a new section in the configuration. Extends
RawConfigParser.add_section by validating if the section name is
a string. | [
"Create",
"a",
"new",
"section",
"in",
"the",
"configuration",
".",
"Extends",
"RawConfigParser",
".",
"add_section",
"by",
"validating",
"if",
"the",
"section",
"name",
"is",
"a",
"string",
"."
] | def add_section(self, section):
"""Create a new section in the configuration. Extends
RawConfigParser.add_section by validating if the section name is
a string."""
section, _, _ = self._validate_value_types(section=section)
super(ConfigParser, self).add_section(section) | [
"def",
"add_section",
"(",
"self",
",",
"section",
")",
":",
"section",
",",
"_",
",",
"_",
"=",
"self",
".",
"_validate_value_types",
"(",
"section",
"=",
"section",
")",
"super",
"(",
"ConfigParser",
",",
"self",
")",
".",
"add_section",
"(",
"section"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/configparser/backports/configparser/__init__.py#L1307-L1312 | ||
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/external/coremltools_wrap/coremltools/coremltools/converters/mil/input_types.py | python | Shape.__init__ | (self, shape, default=None) | The basic shape class to be set in InputType.
Attribute:
shape: list of (int), symbolic values, RangeDim object
The valid shape of the input
default: tuple of int or None
The default shape that is used for initiating the model, and set in
the metadata of the model file.
If None, then `shape` would be used. | The basic shape class to be set in InputType. | [
"The",
"basic",
"shape",
"class",
"to",
"be",
"set",
"in",
"InputType",
"."
] | def __init__(self, shape, default=None):
"""
The basic shape class to be set in InputType.
Attribute:
shape: list of (int), symbolic values, RangeDim object
The valid shape of the input
default: tuple of int or None
The default shape that is used for initiating the model, and set in
the metadata of the model file.
If None, then `shape` would be used.
"""
from coremltools.converters.mil.mil import get_new_symbol
if not isinstance(shape, (list, tuple)):
raise ValueError(
"Shape should be list or tuple, got type {} instead".format(type(shape))
)
self.symbolic_shape = []
shape = list(shape)
for idx, s in enumerate(shape):
if s is None or s == -1 or isinstance(s, RangeDim):
sym = get_new_symbol()
self.symbolic_shape.append(sym)
if s is None or s == -1:
shape[idx] = sym
elif isinstance(s, (np.generic, six.integer_types)) or is_symbolic(s):
self.symbolic_shape.append(s)
else:
raise ValueError(
"Unknown type {} to build symbolic shape.".format(type(s))
)
self.shape = tuple(shape)
if default is not None:
if not isinstance(default, (list, tuple)):
raise ValueError(
"Default shape should be list or tuple, got type {} instead".format(
type(default)
)
)
for idx, s in enumerate(default):
if not isinstance(
s, (np.generic, six.integer_types)
) and not is_symbolic(s):
raise ValueError(
"Default shape invalid, got error at index {} which is {}".format(
idx, s
)
)
else:
default = []
for idx, s in enumerate(self.shape):
if isinstance(s, RangeDim):
default.append(s.default)
elif s is None or s == -1:
default.append(self.symbolic_shape[idx])
else:
default.append(s)
self.default = tuple(default) | [
"def",
"__init__",
"(",
"self",
",",
"shape",
",",
"default",
"=",
"None",
")",
":",
"from",
"coremltools",
".",
"converters",
".",
"mil",
".",
"mil",
"import",
"get_new_symbol",
"if",
"not",
"isinstance",
"(",
"shape",
",",
"(",
"list",
",",
"tuple",
... | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/coremltools/converters/mil/input_types.py#L177-L237 | ||
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Code/Tools/waf-1.7.13/waflib/ConfigSet.py | python | ConfigSet.detach | (self) | Detach self from its parent (if existing)
Modifying the parent :py:class:`ConfigSet` will not change the current object
Modifying this :py:class:`ConfigSet` will not modify the parent one. | Detach self from its parent (if existing) | [
"Detach",
"self",
"from",
"its",
"parent",
"(",
"if",
"existing",
")"
] | def detach(self):
"""
Detach self from its parent (if existing)
Modifying the parent :py:class:`ConfigSet` will not change the current object
Modifying this :py:class:`ConfigSet` will not modify the parent one.
"""
tbl = self.get_merged_dict()
try:
delattr(self, 'parent')
except AttributeError:
pass
else:
keys = tbl.keys()
for x in keys:
tbl[x] = copy.deepcopy(tbl[x])
self.table = tbl | [
"def",
"detach",
"(",
"self",
")",
":",
"tbl",
"=",
"self",
".",
"get_merged_dict",
"(",
")",
"try",
":",
"delattr",
"(",
"self",
",",
"'parent'",
")",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"keys",
"=",
"tbl",
".",
"keys",
"(",
")",
... | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/ConfigSet.py#L153-L169 | ||
RcppCore/RcppParallel | ff49e84602a1771c06bc39fdea995447564f2b7f | src/tbb/python/tbb/pool.py | python | CollectorIterator.next | (self, timeout=None) | return apply_result.get(0) | Return the next result value in the sequence. Raise
StopIteration at the end. Can raise the exception raised by
the Job | Return the next result value in the sequence. Raise
StopIteration at the end. Can raise the exception raised by
the Job | [
"Return",
"the",
"next",
"result",
"value",
"in",
"the",
"sequence",
".",
"Raise",
"StopIteration",
"at",
"the",
"end",
".",
"Can",
"raise",
"the",
"exception",
"raised",
"by",
"the",
"Job"
] | def next(self, timeout=None):
"""Return the next result value in the sequence. Raise
StopIteration at the end. Can raise the exception raised by
the Job"""
try:
apply_result = self._collector._get_result(self._idx, timeout)
except IndexError:
# Reset for next time
self._idx = 0
raise StopIteration
except:
self._idx = 0
raise
self._idx += 1
assert apply_result.ready()
return apply_result.get(0) | [
"def",
"next",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"try",
":",
"apply_result",
"=",
"self",
".",
"_collector",
".",
"_get_result",
"(",
"self",
".",
"_idx",
",",
"timeout",
")",
"except",
"IndexError",
":",
"# Reset for next time",
"self",
... | https://github.com/RcppCore/RcppParallel/blob/ff49e84602a1771c06bc39fdea995447564f2b7f/src/tbb/python/tbb/pool.py#L465-L480 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/XRCed/attribute.py | python | Attribute.add | (parentNode, attribute, value) | Store attribute value in DOM as a text node.
@param attribute: Attribute name.
@param value: Attribute value (Python string). | Store attribute value in DOM as a text node. | [
"Store",
"attribute",
"value",
"in",
"DOM",
"as",
"a",
"text",
"node",
"."
] | def add(parentNode, attribute, value):
'''Store attribute value in DOM as a text node.
@param attribute: Attribute name.
@param value: Attribute value (Python string).
'''
if attribute == '':
elem = parentNode
else:
elem = Model.dom.createElement(attribute)
parentNode.appendChild(elem)
text = Model.dom.createTextNode(value)
elem.appendChild(text) | [
"def",
"add",
"(",
"parentNode",
",",
"attribute",
",",
"value",
")",
":",
"if",
"attribute",
"==",
"''",
":",
"elem",
"=",
"parentNode",
"else",
":",
"elem",
"=",
"Model",
".",
"dom",
".",
"createElement",
"(",
"attribute",
")",
"parentNode",
".",
"ap... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/XRCed/attribute.py#L21-L33 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/index/package_finder.py | python | CandidateEvaluator.__init__ | (
self,
project_name, # type: str
supported_tags, # type: List[Tag]
specifier, # type: specifiers.BaseSpecifier
prefer_binary=False, # type: bool
allow_all_prereleases=False, # type: bool
hashes=None, # type: Optional[Hashes]
) | :param supported_tags: The PEP 425 tags supported by the target
Python in order of preference (most preferred first). | [] | def __init__(
self,
project_name, # type: str
supported_tags, # type: List[Tag]
specifier, # type: specifiers.BaseSpecifier
prefer_binary=False, # type: bool
allow_all_prereleases=False, # type: bool
hashes=None, # type: Optional[Hashes]
):
# type: (...) -> None
"""
:param supported_tags: The PEP 425 tags supported by the target
Python in order of preference (most preferred first).
"""
self._allow_all_prereleases = allow_all_prereleases
self._hashes = hashes
self._prefer_binary = prefer_binary
self._project_name = project_name
self._specifier = specifier
self._supported_tags = supported_tags | [
"def",
"__init__",
"(",
"self",
",",
"project_name",
",",
"# type: str",
"supported_tags",
",",
"# type: List[Tag]",
"specifier",
",",
"# type: specifiers.BaseSpecifier",
"prefer_binary",
"=",
"False",
",",
"# type: bool",
"allow_all_prereleases",
"=",
"False",
",",
"# ... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/index/package_finder.py#L845-L883 | |||
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | TPMS_SCHEME_RSAPSS.__init__ | (self, hashAlg = TPM_ALG_ID.NULL) | These are the RSA schemes that only need a hash algorithm as a
scheme parameter.
Attributes:
hashAlg (TPM_ALG_ID): The hash algorithm used to digest the message | These are the RSA schemes that only need a hash algorithm as a
scheme parameter. | [
"These",
"are",
"the",
"RSA",
"schemes",
"that",
"only",
"need",
"a",
"hash",
"algorithm",
"as",
"a",
"scheme",
"parameter",
"."
] | def __init__(self, hashAlg = TPM_ALG_ID.NULL):
""" These are the RSA schemes that only need a hash algorithm as a
scheme parameter.
Attributes:
hashAlg (TPM_ALG_ID): The hash algorithm used to digest the message
"""
super(TPMS_SCHEME_RSAPSS, self).__init__(hashAlg) | [
"def",
"__init__",
"(",
"self",
",",
"hashAlg",
"=",
"TPM_ALG_ID",
".",
"NULL",
")",
":",
"super",
"(",
"TPMS_SCHEME_RSAPSS",
",",
"self",
")",
".",
"__init__",
"(",
"hashAlg",
")"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L17688-L17695 | ||
sailing-pmls/bosen | 06cb58902d011fbea5f9428f10ce30e621492204 | style_script/cpplint.py | python | NestingState.UpdatePreprocessor | (self, line) | Update preprocessor stack.
We need to handle preprocessors due to classes like this:
#ifdef SWIG
struct ResultDetailsPageElementExtensionPoint {
#else
struct ResultDetailsPageElementExtensionPoint : public Extension {
#endif
We make the following assumptions (good enough for most files):
- Preprocessor condition evaluates to true from #if up to first
#else/#elif/#endif.
- Preprocessor condition evaluates to false from #else/#elif up
to #endif. We still perform lint checks on these lines, but
these do not affect nesting stack.
Args:
line: current line to check. | Update preprocessor stack. | [
"Update",
"preprocessor",
"stack",
"."
] | def UpdatePreprocessor(self, line):
"""Update preprocessor stack.
We need to handle preprocessors due to classes like this:
#ifdef SWIG
struct ResultDetailsPageElementExtensionPoint {
#else
struct ResultDetailsPageElementExtensionPoint : public Extension {
#endif
We make the following assumptions (good enough for most files):
- Preprocessor condition evaluates to true from #if up to first
#else/#elif/#endif.
- Preprocessor condition evaluates to false from #else/#elif up
to #endif. We still perform lint checks on these lines, but
these do not affect nesting stack.
Args:
line: current line to check.
"""
if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line):
# Beginning of #if block, save the nesting stack here. The saved
# stack will allow us to restore the parsing state in the #else case.
self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack)))
elif Match(r'^\s*#\s*(else|elif)\b', line):
# Beginning of #else block
if self.pp_stack:
if not self.pp_stack[-1].seen_else:
# This is the first #else or #elif block. Remember the
# whole nesting stack up to this point. This is what we
# keep after the #endif.
self.pp_stack[-1].seen_else = True
self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack)
# Restore the stack to how it was before the #if
self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if)
else:
# TODO(unknown): unexpected #else, issue warning?
pass
elif Match(r'^\s*#\s*endif\b', line):
# End of #if or #else blocks.
if self.pp_stack:
# If we saw an #else, we will need to restore the nesting
# stack to its former state before the #else, otherwise we
# will just continue from where we left off.
if self.pp_stack[-1].seen_else:
# Here we can just use a shallow copy since we are the last
# reference to it.
self.stack = self.pp_stack[-1].stack_before_else
# Drop the corresponding #if
self.pp_stack.pop()
else:
# TODO(unknown): unexpected #endif, issue warning?
pass | [
"def",
"UpdatePreprocessor",
"(",
"self",
",",
"line",
")",
":",
"if",
"Match",
"(",
"r'^\\s*#\\s*(if|ifdef|ifndef)\\b'",
",",
"line",
")",
":",
"# Beginning of #if block, save the nesting stack here. The saved",
"# stack will allow us to restore the parsing state in the #else cas... | https://github.com/sailing-pmls/bosen/blob/06cb58902d011fbea5f9428f10ce30e621492204/style_script/cpplint.py#L2318-L2372 | ||
makefile/frcnn | 8d9b9ebf8be8315ba2f374d460121b0adf1df29c | examples/pycaffe/layers/pascal_multilabel_datalayers.py | python | load_pascal_annotation | (index, pascal_root) | return {'boxes': boxes,
'gt_classes': gt_classes,
'gt_overlaps': overlaps,
'flipped': False,
'index': index} | This code is borrowed from Ross Girshick's FAST-RCNN code
(https://github.com/rbgirshick/fast-rcnn).
It parses the PASCAL .xml metadata files.
See publication for further details: (http://arxiv.org/abs/1504.08083).
Thanks Ross! | This code is borrowed from Ross Girshick's FAST-RCNN code
(https://github.com/rbgirshick/fast-rcnn).
It parses the PASCAL .xml metadata files.
See publication for further details: (http://arxiv.org/abs/1504.08083). | [
"This",
"code",
"is",
"borrowed",
"from",
"Ross",
"Girshick",
"s",
"FAST",
"-",
"RCNN",
"code",
"(",
"https",
":",
"//",
"github",
".",
"com",
"/",
"rbgirshick",
"/",
"fast",
"-",
"rcnn",
")",
".",
"It",
"parses",
"the",
"PASCAL",
".",
"xml",
"metada... | def load_pascal_annotation(index, pascal_root):
"""
This code is borrowed from Ross Girshick's FAST-RCNN code
(https://github.com/rbgirshick/fast-rcnn).
It parses the PASCAL .xml metadata files.
See publication for further details: (http://arxiv.org/abs/1504.08083).
Thanks Ross!
"""
classes = ('__background__', # always index 0
'aeroplane', 'bicycle', 'bird', 'boat',
'bottle', 'bus', 'car', 'cat', 'chair',
'cow', 'diningtable', 'dog', 'horse',
'motorbike', 'person', 'pottedplant',
'sheep', 'sofa', 'train', 'tvmonitor')
class_to_ind = dict(zip(classes, xrange(21)))
filename = osp.join(pascal_root, 'Annotations', index + '.xml')
# print 'Loading: {}'.format(filename)
def get_data_from_tag(node, tag):
return node.getElementsByTagName(tag)[0].childNodes[0].data
with open(filename) as f:
data = minidom.parseString(f.read())
objs = data.getElementsByTagName('object')
num_objs = len(objs)
boxes = np.zeros((num_objs, 4), dtype=np.uint16)
gt_classes = np.zeros((num_objs), dtype=np.int32)
overlaps = np.zeros((num_objs, 21), dtype=np.float32)
# Load object bounding boxes into a data frame.
for ix, obj in enumerate(objs):
# Make pixel indexes 0-based
x1 = float(get_data_from_tag(obj, 'xmin')) - 1
y1 = float(get_data_from_tag(obj, 'ymin')) - 1
x2 = float(get_data_from_tag(obj, 'xmax')) - 1
y2 = float(get_data_from_tag(obj, 'ymax')) - 1
cls = class_to_ind[
str(get_data_from_tag(obj, "name")).lower().strip()]
boxes[ix, :] = [x1, y1, x2, y2]
gt_classes[ix] = cls
overlaps[ix, cls] = 1.0
overlaps = scipy.sparse.csr_matrix(overlaps)
return {'boxes': boxes,
'gt_classes': gt_classes,
'gt_overlaps': overlaps,
'flipped': False,
'index': index} | [
"def",
"load_pascal_annotation",
"(",
"index",
",",
"pascal_root",
")",
":",
"classes",
"=",
"(",
"'__background__'",
",",
"# always index 0",
"'aeroplane'",
",",
"'bicycle'",
",",
"'bird'",
",",
"'boat'",
",",
"'bottle'",
",",
"'bus'",
",",
"'car'",
",",
"'ca... | https://github.com/makefile/frcnn/blob/8d9b9ebf8be8315ba2f374d460121b0adf1df29c/examples/pycaffe/layers/pascal_multilabel_datalayers.py#L140-L193 | |
mxmssh/manul | f525df9e16dc4533b39537c8443d6301eb30234f | dbi_clients_src/pin/pin-3.6-97554-g31f0a167d-gcc-linux/source/tools/Debugger/launch-pin-attach-debugger.py | python | PrintCommand | (cmd) | Print an informational message about a command that is executed.
@param cmd: The command.
@type cmd: List of String. | Print an informational message about a command that is executed. | [
"Print",
"an",
"informational",
"message",
"about",
"a",
"command",
"that",
"is",
"executed",
"."
] | def PrintCommand(cmd):
"""
Print an informational message about a command that is executed.
@param cmd: The command.
@type cmd: List of String.
"""
mesg = "Launching: " + " ".join(cmd)
print mesg | [
"def",
"PrintCommand",
"(",
"cmd",
")",
":",
"mesg",
"=",
"\"Launching: \"",
"+",
"\" \"",
".",
"join",
"(",
"cmd",
")",
"print",
"mesg"
] | https://github.com/mxmssh/manul/blob/f525df9e16dc4533b39537c8443d6301eb30234f/dbi_clients_src/pin/pin-3.6-97554-g31f0a167d-gcc-linux/source/tools/Debugger/launch-pin-attach-debugger.py#L202-L211 | ||
dmtcp/dmtcp | 48a23686e1ce6784829b783ced9c62a14d620507 | util/cpplint.py | python | ReplaceAll | (pattern, rep, s) | return _regexp_compile_cache[pattern].sub(rep, s) | Replaces instances of pattern in a string with a replacement.
The compiled regex is kept in a cache shared by Match and Search.
Args:
pattern: regex pattern
rep: replacement text
s: search string
Returns:
string with replacements made (or original string if no replacements) | Replaces instances of pattern in a string with a replacement. | [
"Replaces",
"instances",
"of",
"pattern",
"in",
"a",
"string",
"with",
"a",
"replacement",
"."
] | def ReplaceAll(pattern, rep, s):
"""Replaces instances of pattern in a string with a replacement.
The compiled regex is kept in a cache shared by Match and Search.
Args:
pattern: regex pattern
rep: replacement text
s: search string
Returns:
string with replacements made (or original string if no replacements)
"""
if pattern not in _regexp_compile_cache:
_regexp_compile_cache[pattern] = sre_compile.compile(pattern)
return _regexp_compile_cache[pattern].sub(rep, s) | [
"def",
"ReplaceAll",
"(",
"pattern",
",",
"rep",
",",
"s",
")",
":",
"if",
"pattern",
"not",
"in",
"_regexp_compile_cache",
":",
"_regexp_compile_cache",
"[",
"pattern",
"]",
"=",
"sre_compile",
".",
"compile",
"(",
"pattern",
")",
"return",
"_regexp_compile_c... | https://github.com/dmtcp/dmtcp/blob/48a23686e1ce6784829b783ced9c62a14d620507/util/cpplint.py#L655-L670 | |
NREL/EnergyPlus | fadc5973b85c70e8cc923efb69c144e808a26078 | scripts/dev/check_for_malformed_enums.py | python | find_enums | (search_path: Path) | return num_errors | Checks for malformed enums, returns the number of errors found | Checks for malformed enums, returns the number of errors found | [
"Checks",
"for",
"malformed",
"enums",
"returns",
"the",
"number",
"of",
"errors",
"found"
] | def find_enums(search_path: Path) -> int:
"""Checks for malformed enums, returns the number of errors found"""
num_errors = 0
files_to_search = []
for p in [search_path]:
for root, dirs, files in os.walk(p):
for file in files:
f_path = Path(root) / Path(file)
f_extension = f_path.suffix
if f_extension == ".hh":
files_to_search.append(f_path)
elif f_extension == ".cc":
files_to_search.append(f_path)
files_to_search.sort()
for file in files_to_search:
with open(file, "r") as f:
lines = f.readlines()
lines = [x.strip() for x in lines]
start_found = False
start_line = 0
end_found = False
enum_str = ""
for idx, line in enumerate(lines):
# skip blank lines
if line == "":
continue
# skip comment lines
if line[0:2] == "//":
continue
# strip trailing comments
if "//" in line:
tokens = line.split("//")
line = tokens[0].strip()
if "enum class" in line:
start_found = True
start_line = idx + 1
if start_found and (";" in line):
end_found = True
if start_found:
enum_str += line
if end_found:
num_errors += process_enum_str(enum_str, file.name, start_line)
start_found = False
end_found = False
enum_str = ""
return num_errors | [
"def",
"find_enums",
"(",
"search_path",
":",
"Path",
")",
"->",
"int",
":",
"num_errors",
"=",
"0",
"files_to_search",
"=",
"[",
"]",
"for",
"p",
"in",
"[",
"search_path",
"]",
":",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
... | https://github.com/NREL/EnergyPlus/blob/fadc5973b85c70e8cc923efb69c144e808a26078/scripts/dev/check_for_malformed_enums.py#L175-L235 | |
scylladb/scylla | 00a6fda7b98438184024fc4683b0accf1852e30c | scylla-gdb.py | python | all_tables | (db) | Returns pointers to table objects which exist on current shard | Returns pointers to table objects which exist on current shard | [
"Returns",
"pointers",
"to",
"table",
"objects",
"which",
"exist",
"on",
"current",
"shard"
] | def all_tables(db):
"""Returns pointers to table objects which exist on current shard"""
for (key, value) in unordered_map(db['_column_families']):
yield seastar_lw_shared_ptr(value).get() | [
"def",
"all_tables",
"(",
"db",
")",
":",
"for",
"(",
"key",
",",
"value",
")",
"in",
"unordered_map",
"(",
"db",
"[",
"'_column_families'",
"]",
")",
":",
"yield",
"seastar_lw_shared_ptr",
"(",
"value",
")",
".",
"get",
"(",
")"
] | https://github.com/scylladb/scylla/blob/00a6fda7b98438184024fc4683b0accf1852e30c/scylla-gdb.py#L1477-L1481 | ||
macchina-io/macchina.io | ef24ba0e18379c3dd48fb84e6dbf991101cb8db0 | platform/JS/V8/tools/gyp/pylib/gyp/generator/make.py | python | _ValidateSourcesForOSX | (spec, all_sources) | Makes sure if duplicate basenames are not specified in the source list.
Arguments:
spec: The target dictionary containing the properties of the target. | Makes sure if duplicate basenames are not specified in the source list. | [
"Makes",
"sure",
"if",
"duplicate",
"basenames",
"are",
"not",
"specified",
"in",
"the",
"source",
"list",
"."
] | def _ValidateSourcesForOSX(spec, all_sources):
"""Makes sure if duplicate basenames are not specified in the source list.
Arguments:
spec: The target dictionary containing the properties of the target.
"""
if spec.get('type', None) != 'static_library':
return
basenames = {}
for source in all_sources:
name, ext = os.path.splitext(source)
is_compiled_file = ext in [
'.c', '.cc', '.cpp', '.cxx', '.m', '.mm', '.s', '.S']
if not is_compiled_file:
continue
basename = os.path.basename(name) # Don't include extension.
basenames.setdefault(basename, []).append(source)
error = ''
for basename, files in basenames.iteritems():
if len(files) > 1:
error += ' %s: %s\n' % (basename, ' '.join(files))
if error:
print('static library %s has several files with the same basename:\n' %
spec['target_name'] + error + 'libtool on OS X will generate' +
' warnings for them.')
raise GypError('Duplicate basenames in sources section, see list above') | [
"def",
"_ValidateSourcesForOSX",
"(",
"spec",
",",
"all_sources",
")",
":",
"if",
"spec",
".",
"get",
"(",
"'type'",
",",
"None",
")",
"!=",
"'static_library'",
":",
"return",
"basenames",
"=",
"{",
"}",
"for",
"source",
"in",
"all_sources",
":",
"name",
... | https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/tools/gyp/pylib/gyp/generator/make.py#L633-L661 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/numpy_ops/np_utils.py | python | logical_or | (a, b) | A version of tf.logical_or that eagerly evaluates if possible. | A version of tf.logical_or that eagerly evaluates if possible. | [
"A",
"version",
"of",
"tf",
".",
"logical_or",
"that",
"eagerly",
"evaluates",
"if",
"possible",
"."
] | def logical_or(a, b):
"""A version of tf.logical_or that eagerly evaluates if possible."""
a_value = get_static_value(a)
if a_value is not None:
if np.isscalar(a_value):
if a_value:
return a_value
else:
return _maybe_static(b)
else:
return a_value | _maybe_static(b)
else:
return a | _maybe_static(b) | [
"def",
"logical_or",
"(",
"a",
",",
"b",
")",
":",
"a_value",
"=",
"get_static_value",
"(",
"a",
")",
"if",
"a_value",
"is",
"not",
"None",
":",
"if",
"np",
".",
"isscalar",
"(",
"a_value",
")",
":",
"if",
"a_value",
":",
"return",
"a_value",
"else",... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/numpy_ops/np_utils.py#L647-L659 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/sparse_grad.py | python | _SparseReorderGrad | (op, unused_output_indices_grad, output_values_grad) | return (None, array_ops.gather(output_values_grad,
inverted_permutation), None) | Gradients for the SparseReorder op.
Args:
op: the SparseReorder op
unused_output_indices_grad: the incoming gradients of the output indices
output_values_grad: the incoming gradients of the output values
Returns:
Gradient for each of the 3 input tensors:
(input_indices, input_values, input_shape)
The gradients for input_indices and input_shape is None. | Gradients for the SparseReorder op. | [
"Gradients",
"for",
"the",
"SparseReorder",
"op",
"."
] | def _SparseReorderGrad(op, unused_output_indices_grad, output_values_grad):
"""Gradients for the SparseReorder op.
Args:
op: the SparseReorder op
unused_output_indices_grad: the incoming gradients of the output indices
output_values_grad: the incoming gradients of the output values
Returns:
Gradient for each of the 3 input tensors:
(input_indices, input_values, input_shape)
The gradients for input_indices and input_shape is None.
"""
input_indices = op.inputs[0]
input_shape = op.inputs[2]
num_entries = array_ops.shape(input_indices)[0]
entry_indices = math_ops.range(num_entries)
sp_unordered = sparse_tensor.SparseTensor(input_indices, entry_indices,
input_shape)
sp_ordered = sparse_ops.sparse_reorder(sp_unordered)
inverted_permutation = array_ops.invert_permutation(sp_ordered.values)
return (None, array_ops.gather(output_values_grad,
inverted_permutation), None) | [
"def",
"_SparseReorderGrad",
"(",
"op",
",",
"unused_output_indices_grad",
",",
"output_values_grad",
")",
":",
"input_indices",
"=",
"op",
".",
"inputs",
"[",
"0",
"]",
"input_shape",
"=",
"op",
".",
"inputs",
"[",
"2",
"]",
"num_entries",
"=",
"array_ops",
... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/sparse_grad.py#L31-L55 | |
ideawu/ssdb-rocks | a3cbb322cafb2f493252829c608e2239df98c9ac | deps/cpy/antlr3/recognizers.py | python | BaseRecognizer.getTokenErrorDisplay | (self, t) | return repr(s) | How should a token be displayed in an error message? The default
is to display just the text, but during development you might
want to have a lot of information spit out. Override in that case
to use t.toString() (which, for CommonToken, dumps everything about
the token). This is better than forcing you to override a method in
your token objects because you don't have to go modify your lexer
so that it creates a new Java type. | How should a token be displayed in an error message? The default
is to display just the text, but during development you might
want to have a lot of information spit out. Override in that case
to use t.toString() (which, for CommonToken, dumps everything about
the token). This is better than forcing you to override a method in
your token objects because you don't have to go modify your lexer
so that it creates a new Java type. | [
"How",
"should",
"a",
"token",
"be",
"displayed",
"in",
"an",
"error",
"message?",
"The",
"default",
"is",
"to",
"display",
"just",
"the",
"text",
"but",
"during",
"development",
"you",
"might",
"want",
"to",
"have",
"a",
"lot",
"of",
"information",
"spit"... | def getTokenErrorDisplay(self, t):
"""
How should a token be displayed in an error message? The default
is to display just the text, but during development you might
want to have a lot of information spit out. Override in that case
to use t.toString() (which, for CommonToken, dumps everything about
the token). This is better than forcing you to override a method in
your token objects because you don't have to go modify your lexer
so that it creates a new Java type.
"""
s = t.text
if s is None:
if t.type == EOF:
s = "<EOF>"
else:
s = "<"+t.type+">"
return repr(s) | [
"def",
"getTokenErrorDisplay",
"(",
"self",
",",
"t",
")",
":",
"s",
"=",
"t",
".",
"text",
"if",
"s",
"is",
"None",
":",
"if",
"t",
".",
"type",
"==",
"EOF",
":",
"s",
"=",
"\"<EOF>\"",
"else",
":",
"s",
"=",
"\"<\"",
"+",
"t",
".",
"type",
... | https://github.com/ideawu/ssdb-rocks/blob/a3cbb322cafb2f493252829c608e2239df98c9ac/deps/cpy/antlr3/recognizers.py#L468-L486 | |
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/idl/idl_compatibility_errors.py | python | IDLCompatibilityContext.add_removed_access_check_field_error | (self, command_name: str, file: str) | Add an error the new command removing the access_check field. | Add an error the new command removing the access_check field. | [
"Add",
"an",
"error",
"the",
"new",
"command",
"removing",
"the",
"access_check",
"field",
"."
] | def add_removed_access_check_field_error(self, command_name: str, file: str) -> None:
"""Add an error the new command removing the access_check field."""
self._add_error(ERROR_ID_REMOVED_ACCESS_CHECK_FIELD, command_name, (
"'%s' has removed the access_check field in the new command when it exists in the old command"
) % (command_name), file) | [
"def",
"add_removed_access_check_field_error",
"(",
"self",
",",
"command_name",
":",
"str",
",",
"file",
":",
"str",
")",
"->",
"None",
":",
"self",
".",
"_add_error",
"(",
"ERROR_ID_REMOVED_ACCESS_CHECK_FIELD",
",",
"command_name",
",",
"(",
"\"'%s' has removed th... | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/idl/idl_compatibility_errors.py#L998-L1002 | ||
kevinlin311tw/Caffe-DeepBinaryCode | 9eaa7662be47d49f475ecbeea2bd51be105270d2 | python/draw_net.py | python | parse_args | () | return args | Parse input arguments | Parse input arguments | [
"Parse",
"input",
"arguments"
] | def parse_args():
"""Parse input arguments
"""
parser = ArgumentParser(description=__doc__,
formatter_class=ArgumentDefaultsHelpFormatter)
parser.add_argument('input_net_proto_file',
help='Input network prototxt file')
parser.add_argument('output_image_file',
help='Output image file')
parser.add_argument('--rankdir',
help=('One of TB (top-bottom, i.e., vertical), '
'RL (right-left, i.e., horizontal), or another '
'valid dot option; see '
'http://www.graphviz.org/doc/info/'
'attrs.html#k:rankdir'),
default='LR')
args = parser.parse_args()
return args | [
"def",
"parse_args",
"(",
")",
":",
"parser",
"=",
"ArgumentParser",
"(",
"description",
"=",
"__doc__",
",",
"formatter_class",
"=",
"ArgumentDefaultsHelpFormatter",
")",
"parser",
".",
"add_argument",
"(",
"'input_net_proto_file'",
",",
"help",
"=",
"'Input networ... | https://github.com/kevinlin311tw/Caffe-DeepBinaryCode/blob/9eaa7662be47d49f475ecbeea2bd51be105270d2/python/draw_net.py#L13-L33 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | contrib/gizmos/osx_carbon/gizmos.py | python | TreeListColumnInfo.SetImage | (*args, **kwargs) | return _gizmos.TreeListColumnInfo_SetImage(*args, **kwargs) | SetImage(self, int image) | SetImage(self, int image) | [
"SetImage",
"(",
"self",
"int",
"image",
")"
] | def SetImage(*args, **kwargs):
"""SetImage(self, int image)"""
return _gizmos.TreeListColumnInfo_SetImage(*args, **kwargs) | [
"def",
"SetImage",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gizmos",
".",
"TreeListColumnInfo_SetImage",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/gizmos/osx_carbon/gizmos.py#L440-L442 | |
facebookincubator/BOLT | 88c70afe9d388ad430cc150cc158641701397f70 | mlir/python/mlir/dialects/_builtin_ops_ext.py | python | FuncOp.add_entry_block | (self) | return self.body.blocks[0] | Add an entry block to the function body using the function signature to
infer block arguments.
Returns the newly created block | Add an entry block to the function body using the function signature to
infer block arguments.
Returns the newly created block | [
"Add",
"an",
"entry",
"block",
"to",
"the",
"function",
"body",
"using",
"the",
"function",
"signature",
"to",
"infer",
"block",
"arguments",
".",
"Returns",
"the",
"newly",
"created",
"block"
] | def add_entry_block(self):
"""
Add an entry block to the function body using the function signature to
infer block arguments.
Returns the newly created block
"""
if not self.is_external:
raise IndexError('The function already has an entry block!')
self.body.blocks.append(*self.type.inputs)
return self.body.blocks[0] | [
"def",
"add_entry_block",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_external",
":",
"raise",
"IndexError",
"(",
"'The function already has an entry block!'",
")",
"self",
".",
"body",
".",
"blocks",
".",
"append",
"(",
"*",
"self",
".",
"type",
".... | https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/mlir/python/mlir/dialects/_builtin_ops_ext.py#L94-L103 | |
taichi-dev/taichi | 973c04d6ba40f34e9e3bd5a28ae0ee0802f136a6 | python/taichi/profiler/scoped_profiler.py | python | print_scoped_profiler_info | () | Print time elapsed on the host tasks in a hierarchical format.
This profiler is automatically on.
Call function imports from C++ : _ti_core.print_profile_info()
Example::
>>> import taichi as ti
>>> ti.init(arch=ti.cpu)
>>> var = ti.field(ti.f32, shape=1)
>>> @ti.kernel
>>> def compute():
>>> var[0] = 1.0
>>> print("Setting var[0] =", var[0])
>>> compute()
>>> ti.profiler.print_scoped_profiler_info() | Print time elapsed on the host tasks in a hierarchical format. | [
"Print",
"time",
"elapsed",
"on",
"the",
"host",
"tasks",
"in",
"a",
"hierarchical",
"format",
"."
] | def print_scoped_profiler_info():
"""Print time elapsed on the host tasks in a hierarchical format.
This profiler is automatically on.
Call function imports from C++ : _ti_core.print_profile_info()
Example::
>>> import taichi as ti
>>> ti.init(arch=ti.cpu)
>>> var = ti.field(ti.f32, shape=1)
>>> @ti.kernel
>>> def compute():
>>> var[0] = 1.0
>>> print("Setting var[0] =", var[0])
>>> compute()
>>> ti.profiler.print_scoped_profiler_info()
"""
_ti_core.print_profile_info() | [
"def",
"print_scoped_profiler_info",
"(",
")",
":",
"_ti_core",
".",
"print_profile_info",
"(",
")"
] | https://github.com/taichi-dev/taichi/blob/973c04d6ba40f34e9e3bd5a28ae0ee0802f136a6/python/taichi/profiler/scoped_profiler.py#L4-L23 | ||
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/pkg_resources/_vendor/pyparsing.py | python | ParserElement.setDebug | ( self, flag=True ) | return self | Enable display of debugging messages while doing pattern matching.
Set C{flag} to True to enable, False to disable.
Example::
wd = Word(alphas).setName("alphaword")
integer = Word(nums).setName("numword")
term = wd | integer
# turn on debugging for wd
wd.setDebug()
OneOrMore(term).parseString("abc 123 xyz 890")
prints::
Match alphaword at loc 0(1,1)
Matched alphaword -> ['abc']
Match alphaword at loc 3(1,4)
Exception raised:Expected alphaword (at char 4), (line:1, col:5)
Match alphaword at loc 7(1,8)
Matched alphaword -> ['xyz']
Match alphaword at loc 11(1,12)
Exception raised:Expected alphaword (at char 12), (line:1, col:13)
Match alphaword at loc 15(1,16)
Exception raised:Expected alphaword (at char 15), (line:1, col:16)
The output shown is that produced by the default debug actions - custom debug actions can be
specified using L{setDebugActions}. Prior to attempting
to match the C{wd} expression, the debugging message C{"Match <exprname> at loc <n>(<line>,<col>)"}
is shown. Then if the parse succeeds, a C{"Matched"} message is shown, or an C{"Exception raised"}
message is shown. Also note the use of L{setName} to assign a human-readable name to the expression,
which makes debugging and exception messages easier to understand - for instance, the default
name created for the C{Word} expression without calling C{setName} is C{"W:(ABCD...)"}. | Enable display of debugging messages while doing pattern matching.
Set C{flag} to True to enable, False to disable. | [
"Enable",
"display",
"of",
"debugging",
"messages",
"while",
"doing",
"pattern",
"matching",
".",
"Set",
"C",
"{",
"flag",
"}",
"to",
"True",
"to",
"enable",
"False",
"to",
"disable",
"."
] | def setDebug( self, flag=True ):
"""
Enable display of debugging messages while doing pattern matching.
Set C{flag} to True to enable, False to disable.
Example::
wd = Word(alphas).setName("alphaword")
integer = Word(nums).setName("numword")
term = wd | integer
# turn on debugging for wd
wd.setDebug()
OneOrMore(term).parseString("abc 123 xyz 890")
prints::
Match alphaword at loc 0(1,1)
Matched alphaword -> ['abc']
Match alphaword at loc 3(1,4)
Exception raised:Expected alphaword (at char 4), (line:1, col:5)
Match alphaword at loc 7(1,8)
Matched alphaword -> ['xyz']
Match alphaword at loc 11(1,12)
Exception raised:Expected alphaword (at char 12), (line:1, col:13)
Match alphaword at loc 15(1,16)
Exception raised:Expected alphaword (at char 15), (line:1, col:16)
The output shown is that produced by the default debug actions - custom debug actions can be
specified using L{setDebugActions}. Prior to attempting
to match the C{wd} expression, the debugging message C{"Match <exprname> at loc <n>(<line>,<col>)"}
is shown. Then if the parse succeeds, a C{"Matched"} message is shown, or an C{"Exception raised"}
message is shown. Also note the use of L{setName} to assign a human-readable name to the expression,
which makes debugging and exception messages easier to understand - for instance, the default
name created for the C{Word} expression without calling C{setName} is C{"W:(ABCD...)"}.
"""
if flag:
self.setDebugActions( _defaultStartDebugAction, _defaultSuccessDebugAction, _defaultExceptionDebugAction )
else:
self.debug = False
return self | [
"def",
"setDebug",
"(",
"self",
",",
"flag",
"=",
"True",
")",
":",
"if",
"flag",
":",
"self",
".",
"setDebugActions",
"(",
"_defaultStartDebugAction",
",",
"_defaultSuccessDebugAction",
",",
"_defaultExceptionDebugAction",
")",
"else",
":",
"self",
".",
"debug"... | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pkg_resources/_vendor/pyparsing.py#L2112-L2151 | |
p4lang/behavioral-model | 81ce0163f0770c6b9d6056a28ce2e0cc035bb6e9 | tools/cpplint.py | python | _OutputFormat | () | return _cpplint_state.output_format | Gets the module's output format. | Gets the module's output format. | [
"Gets",
"the",
"module",
"s",
"output",
"format",
"."
] | def _OutputFormat():
"""Gets the module's output format."""
return _cpplint_state.output_format | [
"def",
"_OutputFormat",
"(",
")",
":",
"return",
"_cpplint_state",
".",
"output_format"
] | https://github.com/p4lang/behavioral-model/blob/81ce0163f0770c6b9d6056a28ce2e0cc035bb6e9/tools/cpplint.py#L1416-L1418 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/grid.py | python | GridCellFloatRenderer.SetPrecision | (*args, **kwargs) | return _grid.GridCellFloatRenderer_SetPrecision(*args, **kwargs) | SetPrecision(self, int precision) | SetPrecision(self, int precision) | [
"SetPrecision",
"(",
"self",
"int",
"precision",
")"
] | def SetPrecision(*args, **kwargs):
"""SetPrecision(self, int precision)"""
return _grid.GridCellFloatRenderer_SetPrecision(*args, **kwargs) | [
"def",
"SetPrecision",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"GridCellFloatRenderer_SetPrecision",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/grid.py#L199-L201 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/fluid/dygraph/dygraph_to_static/program_translator.py | python | StaticFunction.concrete_program_specify_input_spec | (self, input_spec=None) | return concrete_program | Returns recent ConcreteProgram instance of decorated function while
specifying input_spec. If the self._function_spec already has
input_spce, it will check the compatibility of input input_spec and
the self._function_spec.input_spec. If input input_spec=None, then
this method uses self._function_spec.input_spec
args:
input_spec (list[InputSpec], optional): Describes the input of
the translate function. | Returns recent ConcreteProgram instance of decorated function while
specifying input_spec. If the self._function_spec already has
input_spce, it will check the compatibility of input input_spec and
the self._function_spec.input_spec. If input input_spec=None, then
this method uses self._function_spec.input_spec | [
"Returns",
"recent",
"ConcreteProgram",
"instance",
"of",
"decorated",
"function",
"while",
"specifying",
"input_spec",
".",
"If",
"the",
"self",
".",
"_function_spec",
"already",
"has",
"input_spce",
"it",
"will",
"check",
"the",
"compatibility",
"of",
"input",
"... | def concrete_program_specify_input_spec(self, input_spec=None):
"""
Returns recent ConcreteProgram instance of decorated function while
specifying input_spec. If the self._function_spec already has
input_spce, it will check the compatibility of input input_spec and
the self._function_spec.input_spec. If input input_spec=None, then
this method uses self._function_spec.input_spec
args:
input_spec (list[InputSpec], optional): Describes the input of
the translate function.
"""
# if specific the `input_spec`, the length of program_cache will always 1,
# else, return the last one.
cached_program_len = len(self._program_cache)
# If specific `input_spec`, apply convertion from dygraph layers into static Program.
if cached_program_len == 0:
desired_input_spec = input_spec
if self._function_spec.input_spec is not None:
if input_spec is not None and not input_specs_compatible(
flatten(input_spec),
flatten(self._function_spec.input_spec)):
raise ValueError(
"The `input_spec`: {} used to construct concrete_program is conflict with the `input_spec`: {} in `@paddle.jit.to_static`".
format(input_spec, self._function_spec.input_spec))
# NOTE(chenweihang): we should always translated program based on the `input_spec`
# decorated on forward if it is valid
desired_input_spec = self._function_spec.input_spec
if input_spec is not None:
logging_utils.warn(
"\n\nYou have specified `input_spec` both in function definition (higher priority) and `paddle.jit.save` (will be ignored.)\n\n\t Using: {}\n\n\t Ignore: {}\n".
format(desired_input_spec, input_spec))
has_input_spec = (desired_input_spec is not None)
if has_input_spec:
concrete_program, _ = self.get_concrete_program(
*desired_input_spec)
return concrete_program
else:
raise ValueError(
"No valid transformed program for {}.\n\t Please specific `input_spec` in `@paddle.jit.to_static` or feed input tensor to call the decorated function at once.\n".
format(self._function_spec))
# If more than one programs have been cached, return the recent converted program by default.
elif cached_program_len > 1:
logging_utils.warn(
"Current {} has more than one cached programs: {}, the last traced progam will be return by default.".
format(self._function_spec, cached_program_len))
cache_key, (concrete_program,
partial_layer) = self._program_cache.last()
return concrete_program | [
"def",
"concrete_program_specify_input_spec",
"(",
"self",
",",
"input_spec",
"=",
"None",
")",
":",
"# if specific the `input_spec`, the length of program_cache will always 1,",
"# else, return the last one.",
"cached_program_len",
"=",
"len",
"(",
"self",
".",
"_program_cache",... | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/dygraph/dygraph_to_static/program_translator.py#L483-L533 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/multiprocessing/__init__.py | python | Condition | (lock=None) | return Condition(lock) | Returns a condition object | Returns a condition object | [
"Returns",
"a",
"condition",
"object"
] | def Condition(lock=None):
'''
Returns a condition object
'''
from multiprocessing.synchronize import Condition
return Condition(lock) | [
"def",
"Condition",
"(",
"lock",
"=",
"None",
")",
":",
"from",
"multiprocessing",
".",
"synchronize",
"import",
"Condition",
"return",
"Condition",
"(",
"lock",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/multiprocessing/__init__.py#L185-L190 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/debug/cli/analyzer_cli.py | python | DebugAnalyzer.print_tensor | (self, args, screen_info=None) | return output | Command handler for print_tensor.
Print value of a given dumped tensor.
Args:
args: Command-line arguments, excluding the command prefix, as a list of
str.
screen_info: Optional dict input containing screen information such as
cols.
Returns:
Output text lines as a RichTextLines object. | Command handler for print_tensor. | [
"Command",
"handler",
"for",
"print_tensor",
"."
] | def print_tensor(self, args, screen_info=None):
"""Command handler for print_tensor.
Print value of a given dumped tensor.
Args:
args: Command-line arguments, excluding the command prefix, as a list of
str.
screen_info: Optional dict input containing screen information such as
cols.
Returns:
Output text lines as a RichTextLines object.
"""
parsed = self._arg_parsers["print_tensor"].parse_args(args)
np_printoptions = cli_shared.numpy_printoptions_from_screen_info(
screen_info)
# Determine if any range-highlighting is required.
highlight_options = cli_shared.parse_ranges_highlight(parsed.ranges)
tensor_name, tensor_slicing = (
command_parser.parse_tensor_name_with_slicing(parsed.tensor_name))
node_name, output_slot = debug_graphs.parse_node_or_tensor_name(tensor_name)
if (self._debug_dump.loaded_partition_graphs() and
not self._debug_dump.node_exists(node_name)):
output = cli_shared.error(
"Node \"%s\" does not exist in partition graphs" % node_name)
_add_main_menu(
output,
node_name=None,
enable_list_tensors=True,
enable_print_tensor=False)
return output
watch_keys = self._debug_dump.debug_watch_keys(node_name)
if output_slot is None:
output_slots = set()
for watch_key in watch_keys:
output_slots.add(int(watch_key.split(":")[1]))
if len(output_slots) == 1:
# There is only one dumped tensor from this node, so there is no
# ambiguity. Proceed to show the only dumped tensor.
output_slot = list(output_slots)[0]
else:
# There are more than one dumped tensors from this node. Indicate as
# such.
# TODO(cais): Provide an output screen with command links for
# convenience.
lines = [
"Node \"%s\" generated debug dumps from %s output slots:" %
(node_name, len(output_slots)),
"Please specify the output slot: %s:x." % node_name
]
output = debugger_cli_common.RichTextLines(lines)
_add_main_menu(
output,
node_name=node_name,
enable_list_tensors=True,
enable_print_tensor=False)
return output
# Find debug dump data that match the tensor name (node name + output
# slot).
matching_data = []
for watch_key in watch_keys:
debug_tensor_data = self._debug_dump.watch_key_to_data(watch_key)
for datum in debug_tensor_data:
if datum.output_slot == output_slot:
matching_data.append(datum)
if not matching_data:
# No dump for this tensor.
output = cli_shared.error("Tensor \"%s\" did not generate any dumps." %
parsed.tensor_name)
elif len(matching_data) == 1:
# There is only one dump for this tensor.
if parsed.number <= 0:
output = cli_shared.format_tensor(
matching_data[0].get_tensor(),
matching_data[0].watch_key,
np_printoptions,
print_all=parsed.print_all,
tensor_slicing=tensor_slicing,
highlight_options=highlight_options,
include_numeric_summary=parsed.numeric_summary,
write_path=parsed.write_path)
else:
output = cli_shared.error(
"Invalid number (%d) for tensor %s, which generated one dump." %
(parsed.number, parsed.tensor_name))
_add_main_menu(output, node_name=node_name, enable_print_tensor=False)
else:
# There are more than one dumps for this tensor.
if parsed.number < 0:
lines = [
"Tensor \"%s\" generated %d dumps:" % (parsed.tensor_name,
len(matching_data))
]
font_attr_segs = {}
for i, datum in enumerate(matching_data):
rel_time = (datum.timestamp - self._debug_dump.t0) / 1000.0
lines.append("#%d [%.3f ms] %s" % (i, rel_time, datum.watch_key))
command = "print_tensor %s -n %d" % (parsed.tensor_name, i)
font_attr_segs[len(lines) - 1] = [(
len(lines[-1]) - len(datum.watch_key), len(lines[-1]),
debugger_cli_common.MenuItem(None, command))]
lines.append("")
lines.append(
"You can use the -n (--number) flag to specify which dump to "
"print.")
lines.append("For example:")
lines.append(" print_tensor %s -n 0" % parsed.tensor_name)
output = debugger_cli_common.RichTextLines(
lines, font_attr_segs=font_attr_segs)
elif parsed.number >= len(matching_data):
output = cli_shared.error(
"Specified number (%d) exceeds the number of available dumps "
"(%d) for tensor %s" %
(parsed.number, len(matching_data), parsed.tensor_name))
else:
output = cli_shared.format_tensor(
matching_data[parsed.number].get_tensor(),
matching_data[parsed.number].watch_key + " (dump #%d)" %
parsed.number,
np_printoptions,
print_all=parsed.print_all,
tensor_slicing=tensor_slicing,
highlight_options=highlight_options,
write_path=parsed.write_path)
_add_main_menu(output, node_name=node_name, enable_print_tensor=False)
return output | [
"def",
"print_tensor",
"(",
"self",
",",
"args",
",",
"screen_info",
"=",
"None",
")",
":",
"parsed",
"=",
"self",
".",
"_arg_parsers",
"[",
"\"print_tensor\"",
"]",
".",
"parse_args",
"(",
"args",
")",
"np_printoptions",
"=",
"cli_shared",
".",
"numpy_print... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/debug/cli/analyzer_cli.py#L910-L1050 | |
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/common.py | python | DeepDependencyTargets | (target_dicts, roots) | return list(dependencies - set(roots)) | Returns the recursive list of target dependencies. | Returns the recursive list of target dependencies. | [
"Returns",
"the",
"recursive",
"list",
"of",
"target",
"dependencies",
"."
] | def DeepDependencyTargets(target_dicts, roots):
"""Returns the recursive list of target dependencies."""
dependencies = set()
pending = set(roots)
while pending:
# Pluck out one.
r = pending.pop()
# Skip if visited already.
if r in dependencies:
continue
# Add it.
dependencies.add(r)
# Add its children.
spec = target_dicts[r]
pending.update(set(spec.get("dependencies", [])))
pending.update(set(spec.get("dependencies_original", [])))
return list(dependencies - set(roots)) | [
"def",
"DeepDependencyTargets",
"(",
"target_dicts",
",",
"roots",
")",
":",
"dependencies",
"=",
"set",
"(",
")",
"pending",
"=",
"set",
"(",
"roots",
")",
"while",
"pending",
":",
"# Pluck out one.",
"r",
"=",
"pending",
".",
"pop",
"(",
")",
"# Skip if ... | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/common.py#L303-L319 | |
casadi/casadi | 8d0f80a4d0fe2054384bfb9748f7a0f6bae540ff | docs/api/extra/doxy2swig.py | python | Doxy2SWIG.parse | (self, node) | Parse a given node. This function in turn calls the
`parse_<nodeType>` functions which handle the respective
nodes. | Parse a given node. This function in turn calls the
`parse_<nodeType>` functions which handle the respective
nodes. | [
"Parse",
"a",
"given",
"node",
".",
"This",
"function",
"in",
"turn",
"calls",
"the",
"parse_<nodeType",
">",
"functions",
"which",
"handle",
"the",
"respective",
"nodes",
"."
] | def parse(self, node):
"""Parse a given node. This function in turn calls the
`parse_<nodeType>` functions which handle the respective
nodes.
"""
pm = getattr(self, "parse_%s"%node.__class__.__name__)
pm(node) | [
"def",
"parse",
"(",
"self",
",",
"node",
")",
":",
"pm",
"=",
"getattr",
"(",
"self",
",",
"\"parse_%s\"",
"%",
"node",
".",
"__class__",
".",
"__name__",
")",
"pm",
"(",
"node",
")"
] | https://github.com/casadi/casadi/blob/8d0f80a4d0fe2054384bfb9748f7a0f6bae540ff/docs/api/extra/doxy2swig.py#L105-L112 | ||
sdhash/sdhash | b9eff63e4e5867e910f41fd69032bbb1c94a2a5e | sdhash-ui/jinja2/filters.py | python | do_mark_safe | (value) | return Markup(value) | Mark the value as safe which means that in an environment with automatic
escaping enabled this variable will not be escaped. | Mark the value as safe which means that in an environment with automatic
escaping enabled this variable will not be escaped. | [
"Mark",
"the",
"value",
"as",
"safe",
"which",
"means",
"that",
"in",
"an",
"environment",
"with",
"automatic",
"escaping",
"enabled",
"this",
"variable",
"will",
"not",
"be",
"escaped",
"."
] | def do_mark_safe(value):
"""Mark the value as safe which means that in an environment with automatic
escaping enabled this variable will not be escaped.
"""
return Markup(value) | [
"def",
"do_mark_safe",
"(",
"value",
")",
":",
"return",
"Markup",
"(",
"value",
")"
] | https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-ui/jinja2/filters.py#L701-L705 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | media/tools/constrained_network_server/traffic_control.py | python | TearDown | (config) | Deletes the root qdisc and all iptables rules.
Args:
config: Constraint configuration dictionary, format:
interface: Network interface name (string).
Raises:
TrafficControlError: If any operation fails. The message in the exception
describes what failed. | Deletes the root qdisc and all iptables rules. | [
"Deletes",
"the",
"root",
"qdisc",
"and",
"all",
"iptables",
"rules",
"."
] | def TearDown(config):
"""Deletes the root qdisc and all iptables rules.
Args:
config: Constraint configuration dictionary, format:
interface: Network interface name (string).
Raises:
TrafficControlError: If any operation fails. The message in the exception
describes what failed.
"""
_CheckArgsExist(config, 'interface')
command = ['sudo', 'tc', 'qdisc', 'del', 'dev', config['interface'], 'root']
try:
_Exec(command, msg='Could not delete root qdisc.')
finally:
_DeleteAllIpTableRules() | [
"def",
"TearDown",
"(",
"config",
")",
":",
"_CheckArgsExist",
"(",
"config",
",",
"'interface'",
")",
"command",
"=",
"[",
"'sudo'",
",",
"'tc'",
",",
"'qdisc'",
",",
"'del'",
",",
"'dev'",
",",
"config",
"[",
"'interface'",
"]",
",",
"'root'",
"]",
"... | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/media/tools/constrained_network_server/traffic_control.py#L125-L142 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | build/mac/tweak_info_plist.py | python | _ApplyVersionOverrides | (version, keys, overrides, separator='.') | return separator.join(version_values) | Applies version overrides.
Given a |version| string as "a.b.c.d" (assuming a default separator) with
version components named by |keys| then overrides any value that is present
in |overrides|.
>>> _ApplyVersionOverrides('a.b', ['major', 'minor'], {'minor': 'd'})
'a.d' | Applies version overrides. | [
"Applies",
"version",
"overrides",
"."
] | def _ApplyVersionOverrides(version, keys, overrides, separator='.'):
"""Applies version overrides.
Given a |version| string as "a.b.c.d" (assuming a default separator) with
version components named by |keys| then overrides any value that is present
in |overrides|.
>>> _ApplyVersionOverrides('a.b', ['major', 'minor'], {'minor': 'd'})
'a.d'
"""
if not overrides:
return version
version_values = version.split(separator)
for i, (key, value) in enumerate(zip(keys, version_values)):
if key in overrides:
version_values[i] = overrides[key]
return separator.join(version_values) | [
"def",
"_ApplyVersionOverrides",
"(",
"version",
",",
"keys",
",",
"overrides",
",",
"separator",
"=",
"'.'",
")",
":",
"if",
"not",
"overrides",
":",
"return",
"version",
"version_values",
"=",
"version",
".",
"split",
"(",
"separator",
")",
"for",
"i",
"... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/build/mac/tweak_info_plist.py#L70-L86 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/distributions/python/ops/kumaraswamy.py | python | Kumaraswamy._moment | (self, n) | return math_ops.exp(log_moment) | Compute the n'th (uncentered) moment. | Compute the n'th (uncentered) moment. | [
"Compute",
"the",
"n",
"th",
"(",
"uncentered",
")",
"moment",
"."
] | def _moment(self, n):
"""Compute the n'th (uncentered) moment."""
total_concentration = self.concentration1 + self.concentration0
expanded_concentration1 = array_ops.ones_like(
total_concentration, dtype=self.dtype) * self.concentration1
expanded_concentration0 = array_ops.ones_like(
total_concentration, dtype=self.dtype) * self.concentration0
beta_arg0 = 1 + n / expanded_concentration1
beta_arg = array_ops.stack([beta_arg0, expanded_concentration0], -1)
log_moment = math_ops.log(expanded_concentration0) + special_math_ops.lbeta(
beta_arg)
return math_ops.exp(log_moment) | [
"def",
"_moment",
"(",
"self",
",",
"n",
")",
":",
"total_concentration",
"=",
"self",
".",
"concentration1",
"+",
"self",
".",
"concentration0",
"expanded_concentration1",
"=",
"array_ops",
".",
"ones_like",
"(",
"total_concentration",
",",
"dtype",
"=",
"self"... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/distributions/python/ops/kumaraswamy.py#L203-L214 | |
swift/swift | 12d031cf8177fdec0137f9aa7e2912fa23c4416b | 3rdParty/SCons/scons-3.0.1/engine/SCons/Executor.py | python | rfile | (node) | A function to return the results of a Node's rfile() method,
if it exists, and the Node itself otherwise (if it's a Value
Node, e.g.). | A function to return the results of a Node's rfile() method,
if it exists, and the Node itself otherwise (if it's a Value
Node, e.g.). | [
"A",
"function",
"to",
"return",
"the",
"results",
"of",
"a",
"Node",
"s",
"rfile",
"()",
"method",
"if",
"it",
"exists",
"and",
"the",
"Node",
"itself",
"otherwise",
"(",
"if",
"it",
"s",
"a",
"Value",
"Node",
"e",
".",
"g",
".",
")",
"."
] | def rfile(node):
"""
A function to return the results of a Node's rfile() method,
if it exists, and the Node itself otherwise (if it's a Value
Node, e.g.).
"""
try:
rfile = node.rfile
except AttributeError:
return node
else:
return rfile() | [
"def",
"rfile",
"(",
"node",
")",
":",
"try",
":",
"rfile",
"=",
"node",
".",
"rfile",
"except",
"AttributeError",
":",
"return",
"node",
"else",
":",
"return",
"rfile",
"(",
")"
] | https://github.com/swift/swift/blob/12d031cf8177fdec0137f9aa7e2912fa23c4416b/3rdParty/SCons/scons-3.0.1/engine/SCons/Executor.py#L103-L114 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/stc.py | python | StyledTextEvent.SetLength | (*args, **kwargs) | return _stc.StyledTextEvent_SetLength(*args, **kwargs) | SetLength(self, int len) | SetLength(self, int len) | [
"SetLength",
"(",
"self",
"int",
"len",
")"
] | def SetLength(*args, **kwargs):
"""SetLength(self, int len)"""
return _stc.StyledTextEvent_SetLength(*args, **kwargs) | [
"def",
"SetLength",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextEvent_SetLength",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/stc.py#L7046-L7048 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py3/numpy/polynomial/polyutils.py | python | _sub | (c1, c2) | return trimseq(ret) | Helper function used to implement the ``<type>sub`` functions. | Helper function used to implement the ``<type>sub`` functions. | [
"Helper",
"function",
"used",
"to",
"implement",
"the",
"<type",
">",
"sub",
"functions",
"."
] | def _sub(c1, c2):
""" Helper function used to implement the ``<type>sub`` functions. """
# c1, c2 are trimmed copies
[c1, c2] = as_series([c1, c2])
if len(c1) > len(c2):
c1[:c2.size] -= c2
ret = c1
else:
c2 = -c2
c2[:c1.size] += c1
ret = c2
return trimseq(ret) | [
"def",
"_sub",
"(",
"c1",
",",
"c2",
")",
":",
"# c1, c2 are trimmed copies",
"[",
"c1",
",",
"c2",
"]",
"=",
"as_series",
"(",
"[",
"c1",
",",
"c2",
"]",
")",
"if",
"len",
"(",
"c1",
")",
">",
"len",
"(",
"c2",
")",
":",
"c1",
"[",
":",
"c2"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/polynomial/polyutils.py#L581-L592 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.