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
may0324/DeepCompression-caffe
0aff6c1287bda4cfc7f378ed8a16524e1afabd8c
python/caffe/detector.py
python
Detector.detect_selective_search
(self, image_fnames)
return self.detect_windows(zip(image_fnames, windows_list))
Do windowed detection over Selective Search proposals by extracting the crop and warping to the input dimensions of the net. Parameters ---------- image_fnames: list Returns ------- detections: list of {filename: image filename, window: crop coordinates, predictions: prediction vector} dicts.
Do windowed detection over Selective Search proposals by extracting the crop and warping to the input dimensions of the net.
[ "Do", "windowed", "detection", "over", "Selective", "Search", "proposals", "by", "extracting", "the", "crop", "and", "warping", "to", "the", "input", "dimensions", "of", "the", "net", "." ]
def detect_selective_search(self, image_fnames): """ Do windowed detection over Selective Search proposals by extracting the crop and warping to the input dimensions of the net. Parameters ---------- image_fnames: list Returns ------- detections: list of {filename: image filename, window: crop coordinates, predictions: prediction vector} dicts. """ import selective_search_ijcv_with_python as selective_search # Make absolute paths so MATLAB can find the files. image_fnames = [os.path.abspath(f) for f in image_fnames] windows_list = selective_search.get_windows( image_fnames, cmd='selective_search_rcnn' ) # Run windowed detection on the selective search list. return self.detect_windows(zip(image_fnames, windows_list))
[ "def", "detect_selective_search", "(", "self", ",", "image_fnames", ")", ":", "import", "selective_search_ijcv_with_python", "as", "selective_search", "# Make absolute paths so MATLAB can find the files.", "image_fnames", "=", "[", "os", ".", "path", ".", "abspath", "(", "f", ")", "for", "f", "in", "image_fnames", "]", "windows_list", "=", "selective_search", ".", "get_windows", "(", "image_fnames", ",", "cmd", "=", "'selective_search_rcnn'", ")", "# Run windowed detection on the selective search list.", "return", "self", ".", "detect_windows", "(", "zip", "(", "image_fnames", ",", "windows_list", ")", ")" ]
https://github.com/may0324/DeepCompression-caffe/blob/0aff6c1287bda4cfc7f378ed8a16524e1afabd8c/python/caffe/detector.py#L101-L123
apache/arrow
af33dd1157eb8d7d9bfac25ebf61445b793b7943
dev/archery/archery/benchmark/runner.py
python
JavaBenchmarkRunner.suites
(self)
Returns all suite for a runner.
Returns all suite for a runner.
[ "Returns", "all", "suite", "for", "a", "runner", "." ]
def suites(self): """ Returns all suite for a runner. """ suite_name = "JavaBenchmark" suite = self.suite(suite_name) # Filter may exclude all benchmarks if not suite: logger.debug("Suite {} executed but no results" .format(suite_name)) return yield suite
[ "def", "suites", "(", "self", ")", ":", "suite_name", "=", "\"JavaBenchmark\"", "suite", "=", "self", ".", "suite", "(", "suite_name", ")", "# Filter may exclude all benchmarks", "if", "not", "suite", ":", "logger", ".", "debug", "(", "\"Suite {} executed but no results\"", ".", "format", "(", "suite_name", ")", ")", "return", "yield", "suite" ]
https://github.com/apache/arrow/blob/af33dd1157eb8d7d9bfac25ebf61445b793b7943/dev/archery/archery/benchmark/runner.py#L271-L282
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Node/__init__.py
python
Node.set_always_build
(self, always_build = 1)
Set the Node's always_build value.
Set the Node's always_build value.
[ "Set", "the", "Node", "s", "always_build", "value", "." ]
def set_always_build(self, always_build = 1): """Set the Node's always_build value.""" self.always_build = always_build
[ "def", "set_always_build", "(", "self", ",", "always_build", "=", "1", ")", ":", "self", ".", "always_build", "=", "always_build" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Node/__init__.py#L1245-L1247
devsisters/libquic
8954789a056d8e7d5fcb6452fd1572ca57eb5c4e
src/third_party/protobuf/third_party/six/six.py
python
_import_module
(name)
return sys.modules[name]
Import module, returning the module after the last dot.
Import module, returning the module after the last dot.
[ "Import", "module", "returning", "the", "module", "after", "the", "last", "dot", "." ]
def _import_module(name): """Import module, returning the module after the last dot.""" __import__(name) return sys.modules[name]
[ "def", "_import_module", "(", "name", ")", ":", "__import__", "(", "name", ")", "return", "sys", ".", "modules", "[", "name", "]" ]
https://github.com/devsisters/libquic/blob/8954789a056d8e7d5fcb6452fd1572ca57eb5c4e/src/third_party/protobuf/third_party/six/six.py#L80-L83
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/ogl/_basic.py
python
Shape.MakeMandatoryControlPoints
(self)
Make the mandatory control points. For example, the control point on a dividing line should appear even if the divided rectangle shape's handles should not appear (because it is the child of a composite, and children are not resizable).
Make the mandatory control points.
[ "Make", "the", "mandatory", "control", "points", "." ]
def MakeMandatoryControlPoints(self): """Make the mandatory control points. For example, the control point on a dividing line should appear even if the divided rectangle shape's handles should not appear (because it is the child of a composite, and children are not resizable). """ for child in self._children: child.MakeMandatoryControlPoints()
[ "def", "MakeMandatoryControlPoints", "(", "self", ")", ":", "for", "child", "in", "self", ".", "_children", ":", "child", ".", "MakeMandatoryControlPoints", "(", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/ogl/_basic.py#L1326-L1334
bigartm/bigartm
47e37f982de87aa67bfd475ff1f39da696b181b3
3rdparty/protobuf-3.0.0/python/google/protobuf/descriptor_database.py
python
_ExtractSymbols
(desc_proto, package)
Pulls out all the symbols from a descriptor proto. Args: desc_proto: The proto to extract symbols from. package: The package containing the descriptor type. Yields: The fully qualified name found in the descriptor.
Pulls out all the symbols from a descriptor proto.
[ "Pulls", "out", "all", "the", "symbols", "from", "a", "descriptor", "proto", "." ]
def _ExtractSymbols(desc_proto, package): """Pulls out all the symbols from a descriptor proto. Args: desc_proto: The proto to extract symbols from. package: The package containing the descriptor type. Yields: The fully qualified name found in the descriptor. """ message_name = '.'.join((package, desc_proto.name)) yield message_name for nested_type in desc_proto.nested_type: for symbol in _ExtractSymbols(nested_type, message_name): yield symbol for enum_type in desc_proto.enum_type: yield '.'.join((message_name, enum_type.name))
[ "def", "_ExtractSymbols", "(", "desc_proto", ",", "package", ")", ":", "message_name", "=", "'.'", ".", "join", "(", "(", "package", ",", "desc_proto", ".", "name", ")", ")", "yield", "message_name", "for", "nested_type", "in", "desc_proto", ".", "nested_type", ":", "for", "symbol", "in", "_ExtractSymbols", "(", "nested_type", ",", "message_name", ")", ":", "yield", "symbol", "for", "enum_type", "in", "desc_proto", ".", "enum_type", ":", "yield", "'.'", ".", "join", "(", "(", "message_name", ",", "enum_type", ".", "name", ")", ")" ]
https://github.com/bigartm/bigartm/blob/47e37f982de87aa67bfd475ff1f39da696b181b3/3rdparty/protobuf-3.0.0/python/google/protobuf/descriptor_database.py#L124-L141
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/ops/array_ops.py
python
shape
(input, name=None, out_type=dtypes.int32)
return shape_internal(input, name, optimize=True, out_type=out_type)
Returns the shape of a tensor. This operation returns a 1-D integer tensor representing the shape of `input`. For example: ```python # 't' is [[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]] shape(t) ==> [2, 2, 3] ``` Args: input: A `Tensor` or `SparseTensor`. name: A name for the operation (optional). out_type: (Optional) The specified output type of the operation (`int32` or `int64`). Defaults to `tf.int32`. Returns: A `Tensor` of type `out_type`.
Returns the shape of a tensor.
[ "Returns", "the", "shape", "of", "a", "tensor", "." ]
def shape(input, name=None, out_type=dtypes.int32): # pylint: disable=redefined-builtin """Returns the shape of a tensor. This operation returns a 1-D integer tensor representing the shape of `input`. For example: ```python # 't' is [[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]] shape(t) ==> [2, 2, 3] ``` Args: input: A `Tensor` or `SparseTensor`. name: A name for the operation (optional). out_type: (Optional) The specified output type of the operation (`int32` or `int64`). Defaults to `tf.int32`. Returns: A `Tensor` of type `out_type`. """ return shape_internal(input, name, optimize=True, out_type=out_type)
[ "def", "shape", "(", "input", ",", "name", "=", "None", ",", "out_type", "=", "dtypes", ".", "int32", ")", ":", "# pylint: disable=redefined-builtin", "return", "shape_internal", "(", "input", ",", "name", ",", "optimize", "=", "True", ",", "out_type", "=", "out_type", ")" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/ops/array_ops.py#L114-L136
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/eclib/ecpickers.py
python
PyFontPicker.OnChange
(self, evt)
Updates the text control using our custom stylings after the font is changed. @param evt: The event that called this handler
Updates the text control using our custom stylings after the font is changed. @param evt: The event that called this handler
[ "Updates", "the", "text", "control", "using", "our", "custom", "stylings", "after", "the", "font", "is", "changed", ".", "@param", "evt", ":", "The", "event", "that", "called", "this", "handler" ]
def OnChange(self, evt): """Updates the text control using our custom stylings after the font is changed. @param evt: The event that called this handler """ font = evt.GetFont() if font.IsNull(): return self._font = font self._text.SetFont(self._font) self._text.SetLabel(u"%s - %dpt" % (font.GetFaceName(), \ font.GetPointSize())) self.Layout() evt = FontChangeEvent(edEVT_FONT_CHANGED, self.GetId(), self._font, self) wx.PostEvent(self.GetParent(), evt)
[ "def", "OnChange", "(", "self", ",", "evt", ")", ":", "font", "=", "evt", ".", "GetFont", "(", ")", "if", "font", ".", "IsNull", "(", ")", ":", "return", "self", ".", "_font", "=", "font", "self", ".", "_text", ".", "SetFont", "(", "self", ".", "_font", ")", "self", ".", "_text", ".", "SetLabel", "(", "u\"%s - %dpt\"", "%", "(", "font", ".", "GetFaceName", "(", ")", ",", "font", ".", "GetPointSize", "(", ")", ")", ")", "self", ".", "Layout", "(", ")", "evt", "=", "FontChangeEvent", "(", "edEVT_FONT_CHANGED", ",", "self", ".", "GetId", "(", ")", ",", "self", ".", "_font", ",", "self", ")", "wx", ".", "PostEvent", "(", "self", ".", "GetParent", "(", ")", ",", "evt", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/eclib/ecpickers.py#L113-L128
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/ogl/_basic.py
python
Shape.GetLinePosition
(self, line)
Get the zero-based position of line in the list of lines for this shape.
Get the zero-based position of line in the list of lines for this shape.
[ "Get", "the", "zero", "-", "based", "position", "of", "line", "in", "the", "list", "of", "lines", "for", "this", "shape", "." ]
def GetLinePosition(self, line): """Get the zero-based position of line in the list of lines for this shape. """ try: return self._lines.index(line) except: return 0
[ "def", "GetLinePosition", "(", "self", ",", "line", ")", ":", "try", ":", "return", "self", ".", "_lines", ".", "index", "(", "line", ")", "except", ":", "return", "0" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/ogl/_basic.py#L1645-L1652
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
tools/coreml/converter/utils.py
python
create_module
(sym, data_shapes, label_shapes, label_names, gpus='')
return mod
Creates a new MXNet module. Parameters ---------- sym : Symbol An MXNet symbol. input_shape: tuple The shape of the input data in the form of (batch_size, channels, height, width) files: list of strings List of URLs pertaining to files that need to be downloaded in order to use the model. data_shapes: list of tuples. List of tuples where each tuple is a pair of input variable name and its shape. label_shapes: list of (str, tuple) Typically is ``data_iter.provide_label``. label_names: list of str Name of the output labels in the MXNet symbolic graph. gpus: str Comma separated string of gpu ids on which inferences are executed. E.g. 3,5,6 would refer to GPUs 3, 5 and 6. If empty, we use CPU. Returns ------- MXNet module
Creates a new MXNet module.
[ "Creates", "a", "new", "MXNet", "module", "." ]
def create_module(sym, data_shapes, label_shapes, label_names, gpus=''): """Creates a new MXNet module. Parameters ---------- sym : Symbol An MXNet symbol. input_shape: tuple The shape of the input data in the form of (batch_size, channels, height, width) files: list of strings List of URLs pertaining to files that need to be downloaded in order to use the model. data_shapes: list of tuples. List of tuples where each tuple is a pair of input variable name and its shape. label_shapes: list of (str, tuple) Typically is ``data_iter.provide_label``. label_names: list of str Name of the output labels in the MXNet symbolic graph. gpus: str Comma separated string of gpu ids on which inferences are executed. E.g. 3,5,6 would refer to GPUs 3, 5 and 6. If empty, we use CPU. Returns ------- MXNet module """ if gpus == '': devices = mx.cpu() else: devices = [mx.gpu(int(i)) for i in gpus.split(',')] data_names = [data_shape[0] for data_shape in data_shapes] mod = mx.mod.Module( symbol=sym, data_names=data_names, context=devices, label_names=label_names ) mod.bind( for_training=False, data_shapes=data_shapes, label_shapes=label_shapes ) return mod
[ "def", "create_module", "(", "sym", ",", "data_shapes", ",", "label_shapes", ",", "label_names", ",", "gpus", "=", "''", ")", ":", "if", "gpus", "==", "''", ":", "devices", "=", "mx", ".", "cpu", "(", ")", "else", ":", "devices", "=", "[", "mx", ".", "gpu", "(", "int", "(", "i", ")", ")", "for", "i", "in", "gpus", ".", "split", "(", "','", ")", "]", "data_names", "=", "[", "data_shape", "[", "0", "]", "for", "data_shape", "in", "data_shapes", "]", "mod", "=", "mx", ".", "mod", ".", "Module", "(", "symbol", "=", "sym", ",", "data_names", "=", "data_names", ",", "context", "=", "devices", ",", "label_names", "=", "label_names", ")", "mod", ".", "bind", "(", "for_training", "=", "False", ",", "data_shapes", "=", "data_shapes", ",", "label_shapes", "=", "label_shapes", ")", "return", "mod" ]
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/tools/coreml/converter/utils.py#L68-L117
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/contributed/sumopy/coremodules/demand/wxgui.py
python
WxGui.on_import_routes_overwrite_xml
(self, event=None)
Select xml file and import routes. Overwrite current routes of existing trips.
Select xml file and import routes. Overwrite current routes of existing trips.
[ "Select", "xml", "file", "and", "import", "routes", ".", "Overwrite", "current", "routes", "of", "existing", "trips", "." ]
def on_import_routes_overwrite_xml(self, event=None): """Select xml file and import routes. Overwrite current routes of existing trips. """ filepath = self._demand.trips.get_routefilepath() # defaultFile = = os.path.dirname(filepath) dirpath = os.path.dirname(filepath) wildcards_all = 'XML route files (*.rou.xml)|*.rou.xml|All files (*.*)|*.*' dlg = wx.FileDialog(None, message='Import trips and routes from SUMO xml', defaultDir=dirpath, # defaultFile = =# defaultFile = , wildcard=wildcards_all, style=wx.OPEN | wx.CHANGE_DIR ) if dlg.ShowModal() == wx.ID_OK: filepath = dlg.GetPath() else: return self._demand.trips.import_routes_xml(filepath, is_clear_trips=False, is_overwrite_only=True, is_generate_ids=False, is_add=False) self._mainframe.browse_obj(self._demand.trips)
[ "def", "on_import_routes_overwrite_xml", "(", "self", ",", "event", "=", "None", ")", ":", "filepath", "=", "self", ".", "_demand", ".", "trips", ".", "get_routefilepath", "(", ")", "# defaultFile = = os.path.dirname(filepath)", "dirpath", "=", "os", ".", "path", ".", "dirname", "(", "filepath", ")", "wildcards_all", "=", "'XML route files (*.rou.xml)|*.rou.xml|All files (*.*)|*.*'", "dlg", "=", "wx", ".", "FileDialog", "(", "None", ",", "message", "=", "'Import trips and routes from SUMO xml'", ",", "defaultDir", "=", "dirpath", ",", "# defaultFile = =# defaultFile = ,", "wildcard", "=", "wildcards_all", ",", "style", "=", "wx", ".", "OPEN", "|", "wx", ".", "CHANGE_DIR", ")", "if", "dlg", ".", "ShowModal", "(", ")", "==", "wx", ".", "ID_OK", ":", "filepath", "=", "dlg", ".", "GetPath", "(", ")", "else", ":", "return", "self", ".", "_demand", ".", "trips", ".", "import_routes_xml", "(", "filepath", ",", "is_clear_trips", "=", "False", ",", "is_overwrite_only", "=", "True", ",", "is_generate_ids", "=", "False", ",", "is_add", "=", "False", ")", "self", ".", "_mainframe", ".", "browse_obj", "(", "self", ".", "_demand", ".", "trips", ")" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/coremodules/demand/wxgui.py#L633-L657
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/dateutil/parser/isoparser.py
python
isoparser.parse_isotime
(self, timestr)
return time(*components)
Parse the time portion of an ISO string. :param timestr: The time portion of an ISO string, without a separator :return: Returns a :class:`datetime.time` object
Parse the time portion of an ISO string.
[ "Parse", "the", "time", "portion", "of", "an", "ISO", "string", "." ]
def parse_isotime(self, timestr): """ Parse the time portion of an ISO string. :param timestr: The time portion of an ISO string, without a separator :return: Returns a :class:`datetime.time` object """ components = self._parse_isotime(timestr) if components[0] == 24: components[0] = 0 return time(*components)
[ "def", "parse_isotime", "(", "self", ",", "timestr", ")", ":", "components", "=", "self", ".", "_parse_isotime", "(", "timestr", ")", "if", "components", "[", "0", "]", "==", "24", ":", "components", "[", "0", "]", "=", "0", "return", "time", "(", "*", "components", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/dateutil/parser/isoparser.py#L166-L179
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
src/pybind/mgr/orchestrator/_interface.py
python
handle_orch_error
(f: Callable[..., T])
return cast(Callable[..., OrchResult[T]], wrapper)
Decorator to make Orchestrator methods return an OrchResult.
Decorator to make Orchestrator methods return an OrchResult.
[ "Decorator", "to", "make", "Orchestrator", "methods", "return", "an", "OrchResult", "." ]
def handle_orch_error(f: Callable[..., T]) -> Callable[..., 'OrchResult[T]']: """ Decorator to make Orchestrator methods return an OrchResult. """ @wraps(f) def wrapper(*args: Any, **kwargs: Any) -> OrchResult[T]: try: return OrchResult(f(*args, **kwargs)) except Exception as e: logger.exception(e) import os if 'UNITTEST' in os.environ: raise # This makes debugging of Tracebacks from unittests a bit easier return OrchResult(None, exception=e) return cast(Callable[..., OrchResult[T]], wrapper)
[ "def", "handle_orch_error", "(", "f", ":", "Callable", "[", "...", ",", "T", "]", ")", "->", "Callable", "[", "...", ",", "'OrchResult[T]'", "]", ":", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ":", "Any", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "OrchResult", "[", "T", "]", ":", "try", ":", "return", "OrchResult", "(", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", "except", "Exception", "as", "e", ":", "logger", ".", "exception", "(", "e", ")", "import", "os", "if", "'UNITTEST'", "in", "os", ".", "environ", ":", "raise", "# This makes debugging of Tracebacks from unittests a bit easier", "return", "OrchResult", "(", "None", ",", "exception", "=", "e", ")", "return", "cast", "(", "Callable", "[", "...", ",", "OrchResult", "[", "T", "]", "]", ",", "wrapper", ")" ]
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/pybind/mgr/orchestrator/_interface.py#L116-L133
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/plugins/algorithms/ClipPeaks.py
python
ClipPeaks.PyExec
(self)
Creates a clone of the input workspace to be used for the output, then performs the peak clipping algorithm on each histogram using the specified options. The X and E data of the input remain unmodified in the output workspace.
Creates a clone of the input workspace to be used for the output, then performs the peak clipping algorithm on each histogram using the specified options. The X and E data of the input remain unmodified in the output workspace.
[ "Creates", "a", "clone", "of", "the", "input", "workspace", "to", "be", "used", "for", "the", "output", "then", "performs", "the", "peak", "clipping", "algorithm", "on", "each", "histogram", "using", "the", "specified", "options", ".", "The", "X", "and", "E", "data", "of", "the", "input", "remain", "unmodified", "in", "the", "output", "workspace", "." ]
def PyExec(self): """ Creates a clone of the input workspace to be used for the output, then performs the peak clipping algorithm on each histogram using the specified options. The X and E data of the input remain unmodified in the output workspace. """ input_ws = self.getProperty("InputWorkspace").value window = self.getProperty("WindowSize").value smooth_range = self.getProperty("SmoothingRange").value lls_set = self.getProperty("LLSCorrection").value decreasing = self.getProperty("IncreasingWindow").value n_histo = input_ws.getNumberHistograms() peak_clip_ws = CloneWorkspace(input_ws, OutputWorkspace=self.getPropertyValue("OutputWorkspace")) x = input_ws.extractX() y = input_ws.extractY() e = input_ws.extractE() for histogram in range(n_histo): peak_clip_ws.setX(histogram, x[histogram]) peak_clip_ws.setY( histogram, self.peak_clip(y[histogram], clip_window_size=window, decrease=decreasing, use_lls=lls_set, smooth_factor=smooth_range)) peak_clip_ws.setE(histogram, e[histogram]) self.setProperty("OutputWorkspace", peak_clip_ws)
[ "def", "PyExec", "(", "self", ")", ":", "input_ws", "=", "self", ".", "getProperty", "(", "\"InputWorkspace\"", ")", ".", "value", "window", "=", "self", ".", "getProperty", "(", "\"WindowSize\"", ")", ".", "value", "smooth_range", "=", "self", ".", "getProperty", "(", "\"SmoothingRange\"", ")", ".", "value", "lls_set", "=", "self", ".", "getProperty", "(", "\"LLSCorrection\"", ")", ".", "value", "decreasing", "=", "self", ".", "getProperty", "(", "\"IncreasingWindow\"", ")", ".", "value", "n_histo", "=", "input_ws", ".", "getNumberHistograms", "(", ")", "peak_clip_ws", "=", "CloneWorkspace", "(", "input_ws", ",", "OutputWorkspace", "=", "self", ".", "getPropertyValue", "(", "\"OutputWorkspace\"", ")", ")", "x", "=", "input_ws", ".", "extractX", "(", ")", "y", "=", "input_ws", ".", "extractY", "(", ")", "e", "=", "input_ws", ".", "extractE", "(", ")", "for", "histogram", "in", "range", "(", "n_histo", ")", ":", "peak_clip_ws", ".", "setX", "(", "histogram", ",", "x", "[", "histogram", "]", ")", "peak_clip_ws", ".", "setY", "(", "histogram", ",", "self", ".", "peak_clip", "(", "y", "[", "histogram", "]", ",", "clip_window_size", "=", "window", ",", "decrease", "=", "decreasing", ",", "use_lls", "=", "lls_set", ",", "smooth_factor", "=", "smooth_range", ")", ")", "peak_clip_ws", ".", "setE", "(", "histogram", ",", "e", "[", "histogram", "]", ")", "self", ".", "setProperty", "(", "\"OutputWorkspace\"", ",", "peak_clip_ws", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/ClipPeaks.py#L165-L201
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/stc.py
python
StyledTextCtrl.PageDownExtend
(*args, **kwargs)
return _stc.StyledTextCtrl_PageDownExtend(*args, **kwargs)
PageDownExtend(self) Move caret one page down extending selection to new caret position.
PageDownExtend(self)
[ "PageDownExtend", "(", "self", ")" ]
def PageDownExtend(*args, **kwargs): """ PageDownExtend(self) Move caret one page down extending selection to new caret position. """ return _stc.StyledTextCtrl_PageDownExtend(*args, **kwargs)
[ "def", "PageDownExtend", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_PageDownExtend", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L4514-L4520
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/feature_column/feature_column_v2.py
python
VocabularyListCategoricalColumn.num_buckets
(self)
return len(self.vocabulary_list) + self.num_oov_buckets
Returns number of buckets in this sparse feature.
Returns number of buckets in this sparse feature.
[ "Returns", "number", "of", "buckets", "in", "this", "sparse", "feature", "." ]
def num_buckets(self): """Returns number of buckets in this sparse feature.""" return len(self.vocabulary_list) + self.num_oov_buckets
[ "def", "num_buckets", "(", "self", ")", ":", "return", "len", "(", "self", ".", "vocabulary_list", ")", "+", "self", ".", "num_oov_buckets" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/feature_column/feature_column_v2.py#L3710-L3712
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/timeseries/python/timeseries/state_space_models/periodic.py
python
CycleStateSpaceModel.get_observation_model
(self, times)
return array_ops.concat( values=[ array_ops.ones([1], dtype=self.dtype), array_ops.zeros( [self._periodicity - 2], dtype=self.dtype) ], axis=0)
Observe only the first of the rotating latent values. See StateSpaceModel.get_observation_model. Args: times: Unused. See the parent class for details. Returns: A static, univariate observation model for later broadcasting.
Observe only the first of the rotating latent values.
[ "Observe", "only", "the", "first", "of", "the", "rotating", "latent", "values", "." ]
def get_observation_model(self, times): """Observe only the first of the rotating latent values. See StateSpaceModel.get_observation_model. Args: times: Unused. See the parent class for details. Returns: A static, univariate observation model for later broadcasting. """ del times # Does not rely on times. Uses broadcasting from the parent. return array_ops.concat( values=[ array_ops.ones([1], dtype=self.dtype), array_ops.zeros( [self._periodicity - 2], dtype=self.dtype) ], axis=0)
[ "def", "get_observation_model", "(", "self", ",", "times", ")", ":", "del", "times", "# Does not rely on times. Uses broadcasting from the parent.", "return", "array_ops", ".", "concat", "(", "values", "=", "[", "array_ops", ".", "ones", "(", "[", "1", "]", ",", "dtype", "=", "self", ".", "dtype", ")", ",", "array_ops", ".", "zeros", "(", "[", "self", ".", "_periodicity", "-", "2", "]", ",", "dtype", "=", "self", ".", "dtype", ")", "]", ",", "axis", "=", "0", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/timeseries/python/timeseries/state_space_models/periodic.py#L180-L195
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/jinja2/bccache.py
python
Bucket.load_bytecode
(self, f)
Loads bytecode from a file or file like object.
Loads bytecode from a file or file like object.
[ "Loads", "bytecode", "from", "a", "file", "or", "file", "like", "object", "." ]
def load_bytecode(self, f): """Loads bytecode from a file or file like object.""" # make sure the magic header is correct magic = f.read(len(bc_magic)) if magic != bc_magic: self.reset() return # the source code of the file changed, we need to reload checksum = pickle.load(f) if self.checksum != checksum: self.reset() return self.code = marshal_load(f)
[ "def", "load_bytecode", "(", "self", ",", "f", ")", ":", "# make sure the magic header is correct", "magic", "=", "f", ".", "read", "(", "len", "(", "bc_magic", ")", ")", "if", "magic", "!=", "bc_magic", ":", "self", ".", "reset", "(", ")", "return", "# the source code of the file changed, we need to reload", "checksum", "=", "pickle", ".", "load", "(", "f", ")", "if", "self", ".", "checksum", "!=", "checksum", ":", "self", ".", "reset", "(", ")", "return", "self", ".", "code", "=", "marshal_load", "(", "f", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/jinja2/bccache.py#L76-L88
wujixiu/helmet-detection
8eff5c59ddfba5a29e0b76aeb48babcb49246178
hardhat-wearing-detection/SSD-RPA/scripts/cpp_lint.py
python
_BlockInfo.CheckEnd
(self, filename, clean_lines, linenum, error)
Run checks that applies to text after the closing brace. This is mostly used for checking end of namespace comments. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Run checks that applies to text after the closing brace.
[ "Run", "checks", "that", "applies", "to", "text", "after", "the", "closing", "brace", "." ]
def CheckEnd(self, filename, clean_lines, linenum, error): """Run checks that applies to text after the closing brace. This is mostly used for checking end of namespace comments. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ pass
[ "def", "CheckEnd", "(", "self", ",", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "pass" ]
https://github.com/wujixiu/helmet-detection/blob/8eff5c59ddfba5a29e0b76aeb48babcb49246178/hardhat-wearing-detection/SSD-RPA/scripts/cpp_lint.py#L1782-L1793
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/flatnotebook.py
python
PageContainer.AddPage
(self, caption, selected=False, imgindex=-1)
Adds a page to the :class:`PageContainer`. :param `page`: specifies the new page; :param `text`: specifies the text for the new page; :param `select`: specifies whether the page should be selected; :param `imageId`: specifies the optional image index for the new page.
Adds a page to the :class:`PageContainer`.
[ "Adds", "a", "page", "to", "the", ":", "class", ":", "PageContainer", "." ]
def AddPage(self, caption, selected=False, imgindex=-1): """ Adds a page to the :class:`PageContainer`. :param `page`: specifies the new page; :param `text`: specifies the text for the new page; :param `select`: specifies whether the page should be selected; :param `imageId`: specifies the optional image index for the new page. """ if selected: self._iPreviousActivePage = self._iActivePage self._iActivePage = len(self._pagesInfoVec) # Create page info and add it to the vector pageInfo = PageInfo(caption, imgindex) self._pagesInfoVec.append(pageInfo) self.Refresh()
[ "def", "AddPage", "(", "self", ",", "caption", ",", "selected", "=", "False", ",", "imgindex", "=", "-", "1", ")", ":", "if", "selected", ":", "self", ".", "_iPreviousActivePage", "=", "self", ".", "_iActivePage", "self", ".", "_iActivePage", "=", "len", "(", "self", ".", "_pagesInfoVec", ")", "# Create page info and add it to the vector", "pageInfo", "=", "PageInfo", "(", "caption", ",", "imgindex", ")", "self", ".", "_pagesInfoVec", ".", "append", "(", "pageInfo", ")", "self", ".", "Refresh", "(", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/flatnotebook.py#L5214-L5232
nyuwireless-unipd/ns3-mmwave
4ff9e87e8079764e04cbeccd8e85bff15ae16fb3
utils/grid.py
python
TimelinesRenderer.draw_events
(self, ctx, events, x, y, width, height)
! Draw Event @param self this object @param ctx ctx @param events events @param x x @param y y @param width width @param height height @return none
! Draw Event
[ "!", "Draw", "Event" ]
def draw_events(self, ctx, events, x, y, width, height): """! Draw Event @param self this object @param ctx ctx @param events events @param x x @param y y @param width width @param height height @return none """ if (self.grey_background % 2) == 0: ctx.rectangle(x, y - self.padding / 2, width, height + self.padding) ctx.set_source_rgb(0.9, 0.9, 0.9) ctx.fill() last_x_drawn = int(x) (lo, hi) = events.get_events_bounds(self.start, self.end) for event in events.events[lo:hi]: real_x = int(x + (event.at - self.start) * width / (self.end - self.start)) if real_x > last_x_drawn + 2: ctx.rectangle(real_x, y, 1, 1) ctx.set_source_rgb(1, 0, 0) ctx.stroke() ctx.move_to(real_x, y + self.max_text_height) ctx.set_source_rgb(0, 0, 0) ctx.show_text(str(event.value)) last_x_drawn = real_x self.grey_background += 1
[ "def", "draw_events", "(", "self", ",", "ctx", ",", "events", ",", "x", ",", "y", ",", "width", ",", "height", ")", ":", "if", "(", "self", ".", "grey_background", "%", "2", ")", "==", "0", ":", "ctx", ".", "rectangle", "(", "x", ",", "y", "-", "self", ".", "padding", "/", "2", ",", "width", ",", "height", "+", "self", ".", "padding", ")", "ctx", ".", "set_source_rgb", "(", "0.9", ",", "0.9", ",", "0.9", ")", "ctx", ".", "fill", "(", ")", "last_x_drawn", "=", "int", "(", "x", ")", "(", "lo", ",", "hi", ")", "=", "events", ".", "get_events_bounds", "(", "self", ".", "start", ",", "self", ".", "end", ")", "for", "event", "in", "events", ".", "events", "[", "lo", ":", "hi", "]", ":", "real_x", "=", "int", "(", "x", "+", "(", "event", ".", "at", "-", "self", ".", "start", ")", "*", "width", "/", "(", "self", ".", "end", "-", "self", ".", "start", ")", ")", "if", "real_x", ">", "last_x_drawn", "+", "2", ":", "ctx", ".", "rectangle", "(", "real_x", ",", "y", ",", "1", ",", "1", ")", "ctx", ".", "set_source_rgb", "(", "1", ",", "0", ",", "0", ")", "ctx", ".", "stroke", "(", ")", "ctx", ".", "move_to", "(", "real_x", ",", "y", "+", "self", ".", "max_text_height", ")", "ctx", ".", "set_source_rgb", "(", "0", ",", "0", ",", "0", ")", "ctx", ".", "show_text", "(", "str", "(", "event", ".", "value", ")", ")", "last_x_drawn", "=", "real_x", "self", ".", "grey_background", "+=", "1" ]
https://github.com/nyuwireless-unipd/ns3-mmwave/blob/4ff9e87e8079764e04cbeccd8e85bff15ae16fb3/utils/grid.py#L728-L756
google/sandboxed-api
7004d59150c9fbfaa3e5fd1872affffd1ab14fe8
sandboxed_api/tools/generator2/code.py
python
get_header_guard
(path)
return path + '_'
Generates header guard string from path.
Generates header guard string from path.
[ "Generates", "header", "guard", "string", "from", "path", "." ]
def get_header_guard(path): # type: (Text) -> Text """Generates header guard string from path.""" # the output file will be most likely somewhere in genfiles, strip the # prefix in that case, also strip .gen if this is a step before clang-format if not path: raise ValueError('Cannot prepare header guard from path: {}'.format(path)) if 'genfiles/' in path: path = path.split('genfiles/')[1] if path.endswith('.gen'): path = path.split('.gen')[0] path = path.upper().replace('.', '_').replace('-', '_').replace('/', '_') return path + '_'
[ "def", "get_header_guard", "(", "path", ")", ":", "# type: (Text) -> Text", "# the output file will be most likely somewhere in genfiles, strip the", "# prefix in that case, also strip .gen if this is a step before clang-format", "if", "not", "path", ":", "raise", "ValueError", "(", "'Cannot prepare header guard from path: {}'", ".", "format", "(", "path", ")", ")", "if", "'genfiles/'", "in", "path", ":", "path", "=", "path", ".", "split", "(", "'genfiles/'", ")", "[", "1", "]", "if", "path", ".", "endswith", "(", "'.gen'", ")", ":", "path", "=", "path", ".", "split", "(", "'.gen'", ")", "[", "0", "]", "path", "=", "path", ".", "upper", "(", ")", ".", "replace", "(", "'.'", ",", "'_'", ")", ".", "replace", "(", "'-'", ",", "'_'", ")", ".", "replace", "(", "'/'", ",", "'_'", ")", "return", "path", "+", "'_'" ]
https://github.com/google/sandboxed-api/blob/7004d59150c9fbfaa3e5fd1872affffd1ab14fe8/sandboxed_api/tools/generator2/code.py#L51-L63
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py
python
NinjaWriter.ComputeMacBundleOutput
(self)
return self.ExpandSpecial( os.path.join(path, self.xcode_settings.GetWrapperName()) )
Return the 'output' (full output path) to a bundle output directory.
Return the 'output' (full output path) to a bundle output directory.
[ "Return", "the", "output", "(", "full", "output", "path", ")", "to", "a", "bundle", "output", "directory", "." ]
def ComputeMacBundleOutput(self): """Return the 'output' (full output path) to a bundle output directory.""" assert self.is_mac_bundle path = generator_default_variables["PRODUCT_DIR"] return self.ExpandSpecial( os.path.join(path, self.xcode_settings.GetWrapperName()) )
[ "def", "ComputeMacBundleOutput", "(", "self", ")", ":", "assert", "self", ".", "is_mac_bundle", "path", "=", "generator_default_variables", "[", "\"PRODUCT_DIR\"", "]", "return", "self", ".", "ExpandSpecial", "(", "os", ".", "path", ".", "join", "(", "path", ",", "self", ".", "xcode_settings", ".", "GetWrapperName", "(", ")", ")", ")" ]
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py#L1783-L1789
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/_op_impl/tbe/sqrt_ds.py
python
_sqrt_ds_tbe
()
return
Sqrt TBE register
Sqrt TBE register
[ "Sqrt", "TBE", "register" ]
def _sqrt_ds_tbe(): """Sqrt TBE register""" return
[ "def", "_sqrt_ds_tbe", "(", ")", ":", "return" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/tbe/sqrt_ds.py#L36-L38
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/plat-mac/lib-scriptpackages/CodeWarrior/Metrowerks_Shell_Suite.py
python
Metrowerks_Shell_Suite_Events.Is_In_Project
(self, _object, _attributes={}, **_arguments)
Is In Project: Whether or not the specified file(s) is in the current project Required argument: List of files to check for project membership Keyword argument _attributes: AppleEvent attribute dictionary Returns: Result code for each file
Is In Project: Whether or not the specified file(s) is in the current project Required argument: List of files to check for project membership Keyword argument _attributes: AppleEvent attribute dictionary Returns: Result code for each file
[ "Is", "In", "Project", ":", "Whether", "or", "not", "the", "specified", "file", "(", "s", ")", "is", "in", "the", "current", "project", "Required", "argument", ":", "List", "of", "files", "to", "check", "for", "project", "membership", "Keyword", "argument", "_attributes", ":", "AppleEvent", "attribute", "dictionary", "Returns", ":", "Result", "code", "for", "each", "file" ]
def Is_In_Project(self, _object, _attributes={}, **_arguments): """Is In Project: Whether or not the specified file(s) is in the current project Required argument: List of files to check for project membership Keyword argument _attributes: AppleEvent attribute dictionary Returns: Result code for each file """ _code = 'MMPR' _subcode = 'FInP' if _arguments: raise TypeError, 'No optional args expected' _arguments['----'] = _object _reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes) if _arguments.get('errn', 0): raise aetools.Error, aetools.decodeerror(_arguments) # XXXX Optionally decode result if _arguments.has_key('----'): return _arguments['----']
[ "def", "Is_In_Project", "(", "self", ",", "_object", ",", "_attributes", "=", "{", "}", ",", "*", "*", "_arguments", ")", ":", "_code", "=", "'MMPR'", "_subcode", "=", "'FInP'", "if", "_arguments", ":", "raise", "TypeError", ",", "'No optional args expected'", "_arguments", "[", "'----'", "]", "=", "_object", "_reply", ",", "_arguments", ",", "_attributes", "=", "self", ".", "send", "(", "_code", ",", "_subcode", ",", "_arguments", ",", "_attributes", ")", "if", "_arguments", ".", "get", "(", "'errn'", ",", "0", ")", ":", "raise", "aetools", ".", "Error", ",", "aetools", ".", "decodeerror", "(", "_arguments", ")", "# XXXX Optionally decode result", "if", "_arguments", ".", "has_key", "(", "'----'", ")", ":", "return", "_arguments", "[", "'----'", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/plat-mac/lib-scriptpackages/CodeWarrior/Metrowerks_Shell_Suite.py#L378-L397
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/roc/hsadrv/driver.py
python
Stream._get_last_signal
(self)
return self._signals[-1] if self._signals else None
Get the last signal.
Get the last signal.
[ "Get", "the", "last", "signal", "." ]
def _get_last_signal(self): """ Get the last signal. """ return self._signals[-1] if self._signals else None
[ "def", "_get_last_signal", "(", "self", ")", ":", "return", "self", ".", "_signals", "[", "-", "1", "]", "if", "self", ".", "_signals", "else", "None" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/roc/hsadrv/driver.py#L1365-L1369
QMCPACK/qmcpack
d0948ab455e38364458740cc8e2239600a14c5cd
src/QMCTools/PyscfToQmcpack_Spline.py
python
PwscfH5.system_from_cell
(h5_handle,cell)
return nelecs
create and fill the /supercell and /atoms groups Inputs: h5_handle: hdf5 handle generated by h5py.File cell: pyscf.pbc.gto.Cell class Outputs: species_id: a list of atomic numbers for each atom Effect: fill /supercell and /atoms group in 'h5_handle'
create and fill the /supercell and /atoms groups Inputs: h5_handle: hdf5 handle generated by h5py.File cell: pyscf.pbc.gto.Cell class Outputs: species_id: a list of atomic numbers for each atom Effect: fill /supercell and /atoms group in 'h5_handle'
[ "create", "and", "fill", "the", "/", "supercell", "and", "/", "atoms", "groups", "Inputs", ":", "h5_handle", ":", "hdf5", "handle", "generated", "by", "h5py", ".", "File", "cell", ":", "pyscf", ".", "pbc", ".", "gto", ".", "Cell", "class", "Outputs", ":", "species_id", ":", "a", "list", "of", "atomic", "numbers", "for", "each", "atom", "Effect", ":", "fill", "/", "supercell", "and", "/", "atoms", "group", "in", "h5_handle" ]
def system_from_cell(h5_handle,cell): """ create and fill the /supercell and /atoms groups Inputs: h5_handle: hdf5 handle generated by h5py.File cell: pyscf.pbc.gto.Cell class Outputs: species_id: a list of atomic numbers for each atom Effect: fill /supercell and /atoms group in 'h5_handle' """ # write lattice axes = cell.lattice_vectors() # always in bohr h5_handle.create_dataset('supercell/primitive_vectors',data=axes) # write atoms pos = cell.atom_coords() # always in bohr elem = [cell.atom_symbol(i) for i in range(cell.natm)] assert len(pos) == len(elem) h5_handle.create_dataset('atoms/number_of_atoms',data=[len(elem)]) h5_handle.create_dataset('atoms/positions',data=pos) # write species info species, indices = np.unique(elem, return_index=True) h5_handle.create_dataset('atoms/number_of_species',data=[len(species)]) atomic_number = {} number_of_electrons = {} species_map = {} nelecs = cell.nelec for ispec,name in enumerate(species): species_map[name] = ispec atomic_number[name] = cell.atom_nelec_core(indices[ispec]) + cell.atom_charge(indices[ispec]) number_of_electrons[name] = cell.atom_charge(indices[ispec]) spec_grp = h5_handle.create_group('atoms/species_%d'%ispec) # write name if name not in species_map.keys(): raise NotImplementedError('unknown element %s' % name) # end if spec_grp.create_dataset('name',data=[np.string_(name)]) # write atomic number and valence Zn = atomic_number[name] spec_grp.create_dataset('atomic_number',data=[Zn]) Zps = number_of_electrons[name] spec_grp.create_dataset('valence_charge',data=[Zps]) # end for ispec species_ids = [species_map[name] for name in elem] h5_handle.create_dataset('atoms/species_ids',data=species_ids) return nelecs
[ "def", "system_from_cell", "(", "h5_handle", ",", "cell", ")", ":", "# write lattice", "axes", "=", "cell", ".", "lattice_vectors", "(", ")", "# always in bohr", "h5_handle", ".", "create_dataset", "(", "'supercell/primitive_vectors'", ",", "data", "=", "axes", ")", "# write atoms", "pos", "=", "cell", ".", "atom_coords", "(", ")", "# always in bohr", "elem", "=", "[", "cell", ".", "atom_symbol", "(", "i", ")", "for", "i", "in", "range", "(", "cell", ".", "natm", ")", "]", "assert", "len", "(", "pos", ")", "==", "len", "(", "elem", ")", "h5_handle", ".", "create_dataset", "(", "'atoms/number_of_atoms'", ",", "data", "=", "[", "len", "(", "elem", ")", "]", ")", "h5_handle", ".", "create_dataset", "(", "'atoms/positions'", ",", "data", "=", "pos", ")", "# write species info", "species", ",", "indices", "=", "np", ".", "unique", "(", "elem", ",", "return_index", "=", "True", ")", "h5_handle", ".", "create_dataset", "(", "'atoms/number_of_species'", ",", "data", "=", "[", "len", "(", "species", ")", "]", ")", "atomic_number", "=", "{", "}", "number_of_electrons", "=", "{", "}", "species_map", "=", "{", "}", "nelecs", "=", "cell", ".", "nelec", "for", "ispec", ",", "name", "in", "enumerate", "(", "species", ")", ":", "species_map", "[", "name", "]", "=", "ispec", "atomic_number", "[", "name", "]", "=", "cell", ".", "atom_nelec_core", "(", "indices", "[", "ispec", "]", ")", "+", "cell", ".", "atom_charge", "(", "indices", "[", "ispec", "]", ")", "number_of_electrons", "[", "name", "]", "=", "cell", ".", "atom_charge", "(", "indices", "[", "ispec", "]", ")", "spec_grp", "=", "h5_handle", ".", "create_group", "(", "'atoms/species_%d'", "%", "ispec", ")", "# write name", "if", "name", "not", "in", "species_map", ".", "keys", "(", ")", ":", "raise", "NotImplementedError", "(", "'unknown element %s'", "%", "name", ")", "# end if", "spec_grp", ".", "create_dataset", "(", "'name'", ",", "data", "=", "[", "np", ".", "string_", "(", "name", ")", "]", ")", "# write atomic number and valence", "Zn", "=", "atomic_number", "[", "name", "]", "spec_grp", ".", "create_dataset", "(", "'atomic_number'", ",", "data", "=", "[", "Zn", "]", ")", "Zps", "=", "number_of_electrons", "[", "name", "]", "spec_grp", ".", "create_dataset", "(", "'valence_charge'", ",", "data", "=", "[", "Zps", "]", ")", "# end for ispec ", "species_ids", "=", "[", "species_map", "[", "name", "]", "for", "name", "in", "elem", "]", "h5_handle", ".", "create_dataset", "(", "'atoms/species_ids'", ",", "data", "=", "species_ids", ")", "return", "nelecs" ]
https://github.com/QMCPACK/qmcpack/blob/d0948ab455e38364458740cc8e2239600a14c5cd/src/QMCTools/PyscfToQmcpack_Spline.py#L479-L531
livecode/livecode
4606a10ea10b16d5071d0f9f263ccdd7ede8b31d
gyp/pylib/gyp/MSVSNew.py
python
MSVSProject.__init__
(self, path, name = None, dependencies = None, guid = None, spec = None, build_file = None, config_platform_overrides = None, fixpath_prefix = None)
Initializes the project. Args: path: Absolute path to the project file. name: Name of project. If None, the name will be the same as the base name of the project file. dependencies: List of other Project objects this project is dependent upon, if not None. guid: GUID to use for project, if not None. spec: Dictionary specifying how to build this project. build_file: Filename of the .gyp file that the vcproj file comes from. config_platform_overrides: optional dict of configuration platforms to used in place of the default for this target. fixpath_prefix: the path used to adjust the behavior of _fixpath
Initializes the project.
[ "Initializes", "the", "project", "." ]
def __init__(self, path, name = None, dependencies = None, guid = None, spec = None, build_file = None, config_platform_overrides = None, fixpath_prefix = None): """Initializes the project. Args: path: Absolute path to the project file. name: Name of project. If None, the name will be the same as the base name of the project file. dependencies: List of other Project objects this project is dependent upon, if not None. guid: GUID to use for project, if not None. spec: Dictionary specifying how to build this project. build_file: Filename of the .gyp file that the vcproj file comes from. config_platform_overrides: optional dict of configuration platforms to used in place of the default for this target. fixpath_prefix: the path used to adjust the behavior of _fixpath """ self.path = path self.guid = guid self.spec = spec self.build_file = build_file # Use project filename if name not specified self.name = name or os.path.splitext(os.path.basename(path))[0] # Copy passed lists (or set to empty lists) self.dependencies = list(dependencies or []) self.entry_type_guid = ENTRY_TYPE_GUIDS['project'] if config_platform_overrides: self.config_platform_overrides = config_platform_overrides else: self.config_platform_overrides = {} self.fixpath_prefix = fixpath_prefix self.msbuild_toolset = None
[ "def", "__init__", "(", "self", ",", "path", ",", "name", "=", "None", ",", "dependencies", "=", "None", ",", "guid", "=", "None", ",", "spec", "=", "None", ",", "build_file", "=", "None", ",", "config_platform_overrides", "=", "None", ",", "fixpath_prefix", "=", "None", ")", ":", "self", ".", "path", "=", "path", "self", ".", "guid", "=", "guid", "self", ".", "spec", "=", "spec", "self", ".", "build_file", "=", "build_file", "# Use project filename if name not specified", "self", ".", "name", "=", "name", "or", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "path", ")", ")", "[", "0", "]", "# Copy passed lists (or set to empty lists)", "self", ".", "dependencies", "=", "list", "(", "dependencies", "or", "[", "]", ")", "self", ".", "entry_type_guid", "=", "ENTRY_TYPE_GUIDS", "[", "'project'", "]", "if", "config_platform_overrides", ":", "self", ".", "config_platform_overrides", "=", "config_platform_overrides", "else", ":", "self", ".", "config_platform_overrides", "=", "{", "}", "self", ".", "fixpath_prefix", "=", "fixpath_prefix", "self", ".", "msbuild_toolset", "=", "None" ]
https://github.com/livecode/livecode/blob/4606a10ea10b16d5071d0f9f263ccdd7ede8b31d/gyp/pylib/gyp/MSVSNew.py#L112-L147
facebookincubator/BOLT
88c70afe9d388ad430cc150cc158641701397f70
openmp/runtime/tools/summarizeStats.py
python
readFile
(fname)
Read the statistics from the file. Return a dict with keys "timers", "counters"
Read the statistics from the file. Return a dict with keys "timers", "counters"
[ "Read", "the", "statistics", "from", "the", "file", ".", "Return", "a", "dict", "with", "keys", "timers", "counters" ]
def readFile(fname): """Read the statistics from the file. Return a dict with keys "timers", "counters" """ res = {} try: with open(fname) as f: res["timers"] = readTimers(f) res["counters"] = readCounters(f) return res except (OSError, IOError): print "Cannot open " + fname return None
[ "def", "readFile", "(", "fname", ")", ":", "res", "=", "{", "}", "try", ":", "with", "open", "(", "fname", ")", "as", "f", ":", "res", "[", "\"timers\"", "]", "=", "readTimers", "(", "f", ")", "res", "[", "\"counters\"", "]", "=", "readCounters", "(", "f", ")", "return", "res", "except", "(", "OSError", ",", "IOError", ")", ":", "print", "\"Cannot open \"", "+", "fname", "return", "None" ]
https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/openmp/runtime/tools/summarizeStats.py#L137-L147
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py2/setuptools/dist.py
python
read_pkg_file
(self, file)
Reads the metadata values from a file object.
Reads the metadata values from a file object.
[ "Reads", "the", "metadata", "values", "from", "a", "file", "object", "." ]
def read_pkg_file(self, file): """Reads the metadata values from a file object.""" msg = message_from_file(file) def _read_field(name): value = msg[name] if value == 'UNKNOWN': return None return value def _read_list(name): values = msg.get_all(name, None) if values == []: return None return values self.metadata_version = StrictVersion(msg['metadata-version']) self.name = _read_field('name') self.version = _read_field('version') self.description = _read_field('summary') # we are filling author only. self.author = _read_field('author') self.maintainer = None self.author_email = _read_field('author-email') self.maintainer_email = None self.url = _read_field('home-page') self.license = _read_field('license') if 'download-url' in msg: self.download_url = _read_field('download-url') else: self.download_url = None self.long_description = _read_field('description') self.description = _read_field('summary') if 'keywords' in msg: self.keywords = _read_field('keywords').split(',') self.platforms = _read_list('platform') self.classifiers = _read_list('classifier') # PEP 314 - these fields only exist in 1.1 if self.metadata_version == StrictVersion('1.1'): self.requires = _read_list('requires') self.provides = _read_list('provides') self.obsoletes = _read_list('obsoletes') else: self.requires = None self.provides = None self.obsoletes = None
[ "def", "read_pkg_file", "(", "self", ",", "file", ")", ":", "msg", "=", "message_from_file", "(", "file", ")", "def", "_read_field", "(", "name", ")", ":", "value", "=", "msg", "[", "name", "]", "if", "value", "==", "'UNKNOWN'", ":", "return", "None", "return", "value", "def", "_read_list", "(", "name", ")", ":", "values", "=", "msg", ".", "get_all", "(", "name", ",", "None", ")", "if", "values", "==", "[", "]", ":", "return", "None", "return", "values", "self", ".", "metadata_version", "=", "StrictVersion", "(", "msg", "[", "'metadata-version'", "]", ")", "self", ".", "name", "=", "_read_field", "(", "'name'", ")", "self", ".", "version", "=", "_read_field", "(", "'version'", ")", "self", ".", "description", "=", "_read_field", "(", "'summary'", ")", "# we are filling author only.", "self", ".", "author", "=", "_read_field", "(", "'author'", ")", "self", ".", "maintainer", "=", "None", "self", ".", "author_email", "=", "_read_field", "(", "'author-email'", ")", "self", ".", "maintainer_email", "=", "None", "self", ".", "url", "=", "_read_field", "(", "'home-page'", ")", "self", ".", "license", "=", "_read_field", "(", "'license'", ")", "if", "'download-url'", "in", "msg", ":", "self", ".", "download_url", "=", "_read_field", "(", "'download-url'", ")", "else", ":", "self", ".", "download_url", "=", "None", "self", ".", "long_description", "=", "_read_field", "(", "'description'", ")", "self", ".", "description", "=", "_read_field", "(", "'summary'", ")", "if", "'keywords'", "in", "msg", ":", "self", ".", "keywords", "=", "_read_field", "(", "'keywords'", ")", ".", "split", "(", "','", ")", "self", ".", "platforms", "=", "_read_list", "(", "'platform'", ")", "self", ".", "classifiers", "=", "_read_list", "(", "'classifier'", ")", "# PEP 314 - these fields only exist in 1.1", "if", "self", ".", "metadata_version", "==", "StrictVersion", "(", "'1.1'", ")", ":", "self", ".", "requires", "=", "_read_list", "(", "'requires'", ")", "self", ".", "provides", "=", "_read_list", "(", "'provides'", ")", "self", ".", "obsoletes", "=", "_read_list", "(", "'obsoletes'", ")", "else", ":", "self", ".", "requires", "=", "None", "self", ".", "provides", "=", "None", "self", ".", "obsoletes", "=", "None" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/setuptools/dist.py#L72-L122
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/ultimatelistctrl.py
python
UltimateListItem.SetShown
(self, shown=True)
Sets an item as shown/hidden. :param `shown`: ``True`` to show the item, ``False`` to hide it.
Sets an item as shown/hidden.
[ "Sets", "an", "item", "as", "shown", "/", "hidden", "." ]
def SetShown(self, shown=True): """ Sets an item as shown/hidden. :param `shown`: ``True`` to show the item, ``False`` to hide it. """ self._mask |= ULC_MASK_SHOWN self._isColumnShown = shown
[ "def", "SetShown", "(", "self", ",", "shown", "=", "True", ")", ":", "self", ".", "_mask", "|=", "ULC_MASK_SHOWN", "self", ".", "_isColumnShown", "=", "shown" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L1892-L1900
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/grid.py
python
Grid.SetColumnsOrder
(*args, **kwargs)
return _grid.Grid_SetColumnsOrder(*args, **kwargs)
SetColumnsOrder(self, wxArrayInt order)
SetColumnsOrder(self, wxArrayInt order)
[ "SetColumnsOrder", "(", "self", "wxArrayInt", "order", ")" ]
def SetColumnsOrder(*args, **kwargs): """SetColumnsOrder(self, wxArrayInt order)""" return _grid.Grid_SetColumnsOrder(*args, **kwargs)
[ "def", "SetColumnsOrder", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "Grid_SetColumnsOrder", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/grid.py#L1862-L1864
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/combotreebox.py
python
BaseComboTreeBox.SetStringSelection
(self, string)
Selects the item with the provided string in the control. Returns True if the provided string has been selected, False if it wasn't found in the control. :param string `string`: try to select the item with this string :return: True if an item has been selected :rtype: boolean
Selects the item with the provided string in the control. Returns True if the provided string has been selected, False if it wasn't found in the control. :param string `string`: try to select the item with this string :return: True if an item has been selected :rtype: boolean
[ "Selects", "the", "item", "with", "the", "provided", "string", "in", "the", "control", ".", "Returns", "True", "if", "the", "provided", "string", "has", "been", "selected", "False", "if", "it", "wasn", "t", "found", "in", "the", "control", ".", ":", "param", "string", "string", ":", "try", "to", "select", "the", "item", "with", "this", "string", ":", "return", ":", "True", "if", "an", "item", "has", "been", "selected", ":", "rtype", ":", "boolean" ]
def SetStringSelection(self, string): """ Selects the item with the provided string in the control. Returns True if the provided string has been selected, False if it wasn't found in the control. :param string `string`: try to select the item with this string :return: True if an item has been selected :rtype: boolean """ item = self.FindString(string) if item: if self._text.GetValue() != string: self._text.SetValue(string) self._tree.SelectItem(item) return True else: return False
[ "def", "SetStringSelection", "(", "self", ",", "string", ")", ":", "item", "=", "self", ".", "FindString", "(", "string", ")", "if", "item", ":", "if", "self", ".", "_text", ".", "GetValue", "(", ")", "!=", "string", ":", "self", ".", "_text", ".", "SetValue", "(", "string", ")", "self", ".", "_tree", ".", "SelectItem", "(", "item", ")", "return", "True", "else", ":", "return", "False" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/combotreebox.py#L680-L698
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/grit/grit/util.py
python
FixupNamedParam
(function, param_name, param_value)
return FixupClosure
Returns a closure that is identical to 'function' but ensures that the named parameter 'param_name' is always set to 'param_value' unless explicitly set by the caller. Args: function: callable param_name: 'bingo' param_value: 'bongo' (any type) Return: callable
Returns a closure that is identical to 'function' but ensures that the named parameter 'param_name' is always set to 'param_value' unless explicitly set by the caller.
[ "Returns", "a", "closure", "that", "is", "identical", "to", "function", "but", "ensures", "that", "the", "named", "parameter", "param_name", "is", "always", "set", "to", "param_value", "unless", "explicitly", "set", "by", "the", "caller", "." ]
def FixupNamedParam(function, param_name, param_value): '''Returns a closure that is identical to 'function' but ensures that the named parameter 'param_name' is always set to 'param_value' unless explicitly set by the caller. Args: function: callable param_name: 'bingo' param_value: 'bongo' (any type) Return: callable ''' def FixupClosure(*args, **kw): if not param_name in kw: kw[param_name] = param_value return function(*args, **kw) return FixupClosure
[ "def", "FixupNamedParam", "(", "function", ",", "param_name", ",", "param_value", ")", ":", "def", "FixupClosure", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "if", "not", "param_name", "in", "kw", ":", "kw", "[", "param_name", "]", "=", "param_value", "return", "function", "(", "*", "args", ",", "*", "*", "kw", ")", "return", "FixupClosure" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/grit/grit/util.py#L288-L305
nasa/fprime
595cf3682d8365943d86c1a6fe7c78f0a116acf0
Autocoders/Python/src/fprime_ac/generators/writers/ImplCppWriter.py
python
ImplCppWriter.write
(self, obj)
Calls all of the write methods so that full file is made
Calls all of the write methods so that full file is made
[ "Calls", "all", "of", "the", "write", "methods", "so", "that", "full", "file", "is", "made" ]
def write(self, obj): """ Calls all of the write methods so that full file is made """ self.setFileName(obj) self.initFilesWrite(obj) self._startSourceFilesWrite(obj) self.includes1Write(obj) self.includes2Write(obj) self.namespaceWrite(obj) self.publicWrite(obj) self.protectedWrite(obj) self.privateWrite(obj) self.finishSourceFilesWrite(obj)
[ "def", "write", "(", "self", ",", "obj", ")", ":", "self", ".", "setFileName", "(", "obj", ")", "self", ".", "initFilesWrite", "(", "obj", ")", "self", ".", "_startSourceFilesWrite", "(", "obj", ")", "self", ".", "includes1Write", "(", "obj", ")", "self", ".", "includes2Write", "(", "obj", ")", "self", ".", "namespaceWrite", "(", "obj", ")", "self", ".", "publicWrite", "(", "obj", ")", "self", ".", "protectedWrite", "(", "obj", ")", "self", ".", "privateWrite", "(", "obj", ")", "self", ".", "finishSourceFilesWrite", "(", "obj", ")" ]
https://github.com/nasa/fprime/blob/595cf3682d8365943d86c1a6fe7c78f0a116acf0/Autocoders/Python/src/fprime_ac/generators/writers/ImplCppWriter.py#L51-L64
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/Paste/paste/httpexceptions.py
python
HTTPNotModified.html
(self, environ)
return ''
text/html representation of the exception
text/html representation of the exception
[ "text", "/", "html", "representation", "of", "the", "exception" ]
def html(self, environ): """ text/html representation of the exception """ return ''
[ "def", "html", "(", "self", ",", "environ", ")", ":", "return", "''" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/Paste/paste/httpexceptions.py#L386-L388
forkineye/ESPixelStick
22926f1c0d1131f1369fc7cad405689a095ae3cb
dist/bin/esptool/serial/tools/miniterm.py
python
Miniterm.reader
(self)
loop and copy serial->console
loop and copy serial->console
[ "loop", "and", "copy", "serial", "-", ">", "console" ]
def reader(self): """loop and copy serial->console""" try: while self.alive and self._reader_alive: # read all that is there or wait for one byte data = self.serial.read(self.serial.in_waiting or 1) if data: if self.raw: self.console.write_bytes(data) else: text = self.rx_decoder.decode(data) for transformation in self.rx_transformations: text = transformation.rx(text) self.console.write(text) except serial.SerialException: self.alive = False self.console.cancel() raise
[ "def", "reader", "(", "self", ")", ":", "try", ":", "while", "self", ".", "alive", "and", "self", ".", "_reader_alive", ":", "# read all that is there or wait for one byte", "data", "=", "self", ".", "serial", ".", "read", "(", "self", ".", "serial", ".", "in_waiting", "or", "1", ")", "if", "data", ":", "if", "self", ".", "raw", ":", "self", ".", "console", ".", "write_bytes", "(", "data", ")", "else", ":", "text", "=", "self", ".", "rx_decoder", ".", "decode", "(", "data", ")", "for", "transformation", "in", "self", ".", "rx_transformations", ":", "text", "=", "transformation", ".", "rx", "(", "text", ")", "self", ".", "console", ".", "write", "(", "text", ")", "except", "serial", ".", "SerialException", ":", "self", ".", "alive", "=", "False", "self", ".", "console", ".", "cancel", "(", ")", "raise" ]
https://github.com/forkineye/ESPixelStick/blob/22926f1c0d1131f1369fc7cad405689a095ae3cb/dist/bin/esptool/serial/tools/miniterm.py#L440-L457
nmslib/hnswlib
21e20f3d696e6ad54f37ad537725424f8990082e
python_bindings/setup.py
python
has_flag
(compiler, flagname)
return True
Return a boolean indicating whether a flag name is supported on the specified compiler.
Return a boolean indicating whether a flag name is supported on the specified compiler.
[ "Return", "a", "boolean", "indicating", "whether", "a", "flag", "name", "is", "supported", "on", "the", "specified", "compiler", "." ]
def has_flag(compiler, flagname): """Return a boolean indicating whether a flag name is supported on the specified compiler. """ import tempfile with tempfile.NamedTemporaryFile('w', suffix='.cpp') as f: f.write('int main (int argc, char **argv) { return 0; }') try: compiler.compile([f.name], extra_postargs=[flagname]) except setuptools.distutils.errors.CompileError: return False return True
[ "def", "has_flag", "(", "compiler", ",", "flagname", ")", ":", "import", "tempfile", "with", "tempfile", ".", "NamedTemporaryFile", "(", "'w'", ",", "suffix", "=", "'.cpp'", ")", "as", "f", ":", "f", ".", "write", "(", "'int main (int argc, char **argv) { return 0; }'", ")", "try", ":", "compiler", ".", "compile", "(", "[", "f", ".", "name", "]", ",", "extra_postargs", "=", "[", "flagname", "]", ")", "except", "setuptools", ".", "distutils", ".", "errors", ".", "CompileError", ":", "return", "False", "return", "True" ]
https://github.com/nmslib/hnswlib/blob/21e20f3d696e6ad54f37ad537725424f8990082e/python_bindings/setup.py#L46-L57
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/coverage/control.py
python
coverage.erase
(self)
Erase previously-collected coverage data. This removes the in-memory data collected in this session as well as discarding the data file.
Erase previously-collected coverage data.
[ "Erase", "previously", "-", "collected", "coverage", "data", "." ]
def erase(self): """Erase previously-collected coverage data. This removes the in-memory data collected in this session as well as discarding the data file. """ self.collector.reset() self.data.erase()
[ "def", "erase", "(", "self", ")", ":", "self", ".", "collector", ".", "reset", "(", ")", "self", ".", "data", ".", "erase", "(", ")" ]
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/coverage/control.py#L392-L400
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/distutils/ccompiler.py
python
CCompiler._compile
(self, obj, src, ext, cc_args, extra_postargs, pp_opts)
Compile 'src' to product 'obj'.
Compile 'src' to product 'obj'.
[ "Compile", "src", "to", "product", "obj", "." ]
def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts): """Compile 'src' to product 'obj'.""" # A concrete compiler class that does not override compile() # should implement _compile(). pass
[ "def", "_compile", "(", "self", ",", "obj", ",", "src", ",", "ext", ",", "cc_args", ",", "extra_postargs", ",", "pp_opts", ")", ":", "# A concrete compiler class that does not override compile()", "# should implement _compile().", "pass" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/distutils/ccompiler.py#L579-L583
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/combo.py
python
ComboCtrl.__init__
(self, *args, **kwargs)
__init__(self, Window parent, int id=ID_ANY, String value=wxEmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, Validator validator=DefaultValidator, String name=ComboBoxNameStr) -> ComboCtrl
__init__(self, Window parent, int id=ID_ANY, String value=wxEmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, Validator validator=DefaultValidator, String name=ComboBoxNameStr) -> ComboCtrl
[ "__init__", "(", "self", "Window", "parent", "int", "id", "=", "ID_ANY", "String", "value", "=", "wxEmptyString", "Point", "pos", "=", "DefaultPosition", "Size", "size", "=", "DefaultSize", "long", "style", "=", "0", "Validator", "validator", "=", "DefaultValidator", "String", "name", "=", "ComboBoxNameStr", ")", "-", ">", "ComboCtrl" ]
def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=ID_ANY, String value=wxEmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, Validator validator=DefaultValidator, String name=ComboBoxNameStr) -> ComboCtrl """ _combo.ComboCtrl_swiginit(self,_combo.new_ComboCtrl(*args, **kwargs)) self._setOORInfo(self);ComboCtrl._setCallbackInfo(self, self, ComboCtrl)
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_combo", ".", "ComboCtrl_swiginit", "(", "self", ",", "_combo", ".", "new_ComboCtrl", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", "self", ".", "_setOORInfo", "(", "self", ")", "ComboCtrl", ".", "_setCallbackInfo", "(", "self", ",", "self", ",", "ComboCtrl", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/combo.py#L110-L118
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/robotparser.py
python
Entry.applies_to
(self, useragent)
return False
check if this entry applies to the specified agent
check if this entry applies to the specified agent
[ "check", "if", "this", "entry", "applies", "to", "the", "specified", "agent" ]
def applies_to(self, useragent): """check if this entry applies to the specified agent""" # split the name token and make it lower case useragent = useragent.split("/")[0].lower() for agent in self.useragents: if agent == '*': # we have the catch-all agent return True agent = agent.lower() if agent in useragent: return True return False
[ "def", "applies_to", "(", "self", ",", "useragent", ")", ":", "# split the name token and make it lower case", "useragent", "=", "useragent", ".", "split", "(", "\"/\"", ")", "[", "0", "]", ".", "lower", "(", ")", "for", "agent", "in", "self", ".", "useragents", ":", "if", "agent", "==", "'*'", ":", "# we have the catch-all agent", "return", "True", "agent", "=", "agent", ".", "lower", "(", ")", "if", "agent", "in", "useragent", ":", "return", "True", "return", "False" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/robotparser.py#L187-L198
Komnomnomnom/swigibpy
cfd307fdbfaffabc69a2dc037538d7e34a8b8daf
swigibpy.py
python
SwigPyIterator.value
(self)
return _swigibpy.SwigPyIterator_value(self)
value(SwigPyIterator self) -> PyObject *
value(SwigPyIterator self) -> PyObject *
[ "value", "(", "SwigPyIterator", "self", ")", "-", ">", "PyObject", "*" ]
def value(self): """value(SwigPyIterator self) -> PyObject *""" return _swigibpy.SwigPyIterator_value(self)
[ "def", "value", "(", "self", ")", ":", "return", "_swigibpy", ".", "SwigPyIterator_value", "(", "self", ")" ]
https://github.com/Komnomnomnom/swigibpy/blob/cfd307fdbfaffabc69a2dc037538d7e34a8b8daf/swigibpy.py#L133-L135
esa/pykep
b410363653623730b577de257c04b0e0289f2014
pykep/trajopt/gym/_tandem.py
python
_tandem_udp.pretty
(self, x)
prob.plot(x) - x: encoded trajectory Prints human readable information on the trajectory represented by the decision vector x Example:: print(prob.pretty(x))
prob.plot(x)
[ "prob", ".", "plot", "(", "x", ")" ]
def pretty(self, x): """ prob.plot(x) - x: encoded trajectory Prints human readable information on the trajectory represented by the decision vector x Example:: print(prob.pretty(x)) """ super().pretty(x) T, Vinfx, Vinfy, Vinfz = self._decode_times_and_vinf(x) # We transform it (only the needed component) to an equatorial system rotating along x # (this is an approximation, assuming vernal equinox is roughly x and the ecliptic plane is roughly xy) earth_axis_inclination = 0.409072975 # This is different from the GTOP tanmEM problem, I think it was bugged there as the rotation was in the wrong direction. Vinfz = - Vinfy * sin(earth_axis_inclination) + Vinfz * cos(earth_axis_inclination) # And we find the vinf declination (in degrees) sindelta = Vinfz / x[3] declination = asin(sindelta) / np.pi * 180. m_initial = launchers.atlas501(x[3] / 1000., declination) # And we can evaluate the final mass via Tsiolkowsky Isp = 312. g0 = 9.80665 DV = super().fitness(x)[0] DV = DV + 165. # losses for 3 swgbys + insertion m_final = m_initial * exp(-DV / Isp / g0) print("\nInitial mass:", m_initial) print("Final mass:", m_final) print("Declination:", declination)
[ "def", "pretty", "(", "self", ",", "x", ")", ":", "super", "(", ")", ".", "pretty", "(", "x", ")", "T", ",", "Vinfx", ",", "Vinfy", ",", "Vinfz", "=", "self", ".", "_decode_times_and_vinf", "(", "x", ")", "# We transform it (only the needed component) to an equatorial system rotating along x ", "# (this is an approximation, assuming vernal equinox is roughly x and the ecliptic plane is roughly xy)", "earth_axis_inclination", "=", "0.409072975", "# This is different from the GTOP tanmEM problem, I think it was bugged there as the rotation was in the wrong direction.", "Vinfz", "=", "-", "Vinfy", "*", "sin", "(", "earth_axis_inclination", ")", "+", "Vinfz", "*", "cos", "(", "earth_axis_inclination", ")", "# And we find the vinf declination (in degrees)", "sindelta", "=", "Vinfz", "/", "x", "[", "3", "]", "declination", "=", "asin", "(", "sindelta", ")", "/", "np", ".", "pi", "*", "180.", "m_initial", "=", "launchers", ".", "atlas501", "(", "x", "[", "3", "]", "/", "1000.", ",", "declination", ")", "# And we can evaluate the final mass via Tsiolkowsky", "Isp", "=", "312.", "g0", "=", "9.80665", "DV", "=", "super", "(", ")", ".", "fitness", "(", "x", ")", "[", "0", "]", "DV", "=", "DV", "+", "165.", "# losses for 3 swgbys + insertion", "m_final", "=", "m_initial", "*", "exp", "(", "-", "DV", "/", "Isp", "/", "g0", ")", "print", "(", "\"\\nInitial mass:\"", ",", "m_initial", ")", "print", "(", "\"Final mass:\"", ",", "m_final", ")", "print", "(", "\"Declination:\"", ",", "declination", ")" ]
https://github.com/esa/pykep/blob/b410363653623730b577de257c04b0e0289f2014/pykep/trajopt/gym/_tandem.py#L149-L180
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/robotsim.py
python
WorldModel.remove
(self, *args)
return _robotsim.WorldModel_remove(self, *args)
r""" Removes a robot, rigid object, or terrain from the world. It must be in this world or an exception is raised. remove (robot) remove (object) remove (terrain) Args: robot (:class:`~klampt.RobotModel`, optional): object (:class:`~klampt.RigidObjectModel`, optional): terrain (:class:`~klampt.TerrainModel`, optional): IMPORTANT: All other RobotModel, RigidObjectModel, or TerrainModel references will be invalidated.
r""" Removes a robot, rigid object, or terrain from the world. It must be in this world or an exception is raised.
[ "r", "Removes", "a", "robot", "rigid", "object", "or", "terrain", "from", "the", "world", ".", "It", "must", "be", "in", "this", "world", "or", "an", "exception", "is", "raised", "." ]
def remove(self, *args) ->None: r""" Removes a robot, rigid object, or terrain from the world. It must be in this world or an exception is raised. remove (robot) remove (object) remove (terrain) Args: robot (:class:`~klampt.RobotModel`, optional): object (:class:`~klampt.RigidObjectModel`, optional): terrain (:class:`~klampt.TerrainModel`, optional): IMPORTANT: All other RobotModel, RigidObjectModel, or TerrainModel references will be invalidated. """ return _robotsim.WorldModel_remove(self, *args)
[ "def", "remove", "(", "self", ",", "*", "args", ")", "->", "None", ":", "return", "_robotsim", ".", "WorldModel_remove", "(", "self", ",", "*", "args", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/robotsim.py#L5903-L5926
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py2/numpy/core/multiarray.py
python
ravel_multi_index
(multi_index, dims, mode=None, order=None)
return multi_index
ravel_multi_index(multi_index, dims, mode='raise', order='C') Converts a tuple of index arrays into an array of flat indices, applying boundary modes to the multi-index. Parameters ---------- multi_index : tuple of array_like A tuple of integer arrays, one array for each dimension. dims : tuple of ints The shape of array into which the indices from ``multi_index`` apply. mode : {'raise', 'wrap', 'clip'}, optional Specifies how out-of-bounds indices are handled. Can specify either one mode or a tuple of modes, one mode per index. * 'raise' -- raise an error (default) * 'wrap' -- wrap around * 'clip' -- clip to the range In 'clip' mode, a negative index which would normally wrap will clip to 0 instead. order : {'C', 'F'}, optional Determines whether the multi-index should be viewed as indexing in row-major (C-style) or column-major (Fortran-style) order. Returns ------- raveled_indices : ndarray An array of indices into the flattened version of an array of dimensions ``dims``. See Also -------- unravel_index Notes ----- .. versionadded:: 1.6.0 Examples -------- >>> arr = np.array([[3,6,6],[4,5,1]]) >>> np.ravel_multi_index(arr, (7,6)) array([22, 41, 37]) >>> np.ravel_multi_index(arr, (7,6), order='F') array([31, 41, 13]) >>> np.ravel_multi_index(arr, (4,6), mode='clip') array([22, 23, 19]) >>> np.ravel_multi_index(arr, (4,4), mode=('clip','wrap')) array([12, 13, 13]) >>> np.ravel_multi_index((3,1,4,1), (6,7,8,9)) 1621
ravel_multi_index(multi_index, dims, mode='raise', order='C')
[ "ravel_multi_index", "(", "multi_index", "dims", "mode", "=", "raise", "order", "=", "C", ")" ]
def ravel_multi_index(multi_index, dims, mode=None, order=None): """ ravel_multi_index(multi_index, dims, mode='raise', order='C') Converts a tuple of index arrays into an array of flat indices, applying boundary modes to the multi-index. Parameters ---------- multi_index : tuple of array_like A tuple of integer arrays, one array for each dimension. dims : tuple of ints The shape of array into which the indices from ``multi_index`` apply. mode : {'raise', 'wrap', 'clip'}, optional Specifies how out-of-bounds indices are handled. Can specify either one mode or a tuple of modes, one mode per index. * 'raise' -- raise an error (default) * 'wrap' -- wrap around * 'clip' -- clip to the range In 'clip' mode, a negative index which would normally wrap will clip to 0 instead. order : {'C', 'F'}, optional Determines whether the multi-index should be viewed as indexing in row-major (C-style) or column-major (Fortran-style) order. Returns ------- raveled_indices : ndarray An array of indices into the flattened version of an array of dimensions ``dims``. See Also -------- unravel_index Notes ----- .. versionadded:: 1.6.0 Examples -------- >>> arr = np.array([[3,6,6],[4,5,1]]) >>> np.ravel_multi_index(arr, (7,6)) array([22, 41, 37]) >>> np.ravel_multi_index(arr, (7,6), order='F') array([31, 41, 13]) >>> np.ravel_multi_index(arr, (4,6), mode='clip') array([22, 23, 19]) >>> np.ravel_multi_index(arr, (4,4), mode=('clip','wrap')) array([12, 13, 13]) >>> np.ravel_multi_index((3,1,4,1), (6,7,8,9)) 1621 """ return multi_index
[ "def", "ravel_multi_index", "(", "multi_index", ",", "dims", ",", "mode", "=", "None", ",", "order", "=", "None", ")", ":", "return", "multi_index" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/core/multiarray.py#L923-L980
MegEngine/MegEngine
ce9ad07a27ec909fb8db4dd67943d24ba98fb93a
imperative/python/megengine/functional/nn.py
python
relu
(x)
return _elwise(x, mode=Elemwise.Mode.RELU)
r"""Element-wise `max(x, 0)`.
r"""Element-wise `max(x, 0)`.
[ "r", "Element", "-", "wise", "max", "(", "x", "0", ")", "." ]
def relu(x): r"""Element-wise `max(x, 0)`.""" return _elwise(x, mode=Elemwise.Mode.RELU)
[ "def", "relu", "(", "x", ")", ":", "return", "_elwise", "(", "x", ",", "mode", "=", "Elemwise", ".", "Mode", ".", "RELU", ")" ]
https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/functional/nn.py#L832-L834
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/Inelastic/Direct/PropertyManager.py
python
PropertyManager.find_files_to_sum
(self,num_files=None)
return (ok,not_found_list,found_list)
method searches for run files in run list to sum and returns list of runs with run-files missing or ok and empty list if all files are there if num_files is not None, find specified number of files out of total file list to sum
method searches for run files in run list to sum and returns list of runs with run-files missing or ok and empty list if all files are there
[ "method", "searches", "for", "run", "files", "in", "run", "list", "to", "sum", "and", "returns", "list", "of", "runs", "with", "run", "-", "files", "missing", "or", "ok", "and", "empty", "list", "if", "all", "files", "are", "there" ]
def find_files_to_sum(self,num_files=None): """ method searches for run files in run list to sum and returns list of runs with run-files missing or ok and empty list if all files are there if num_files is not None, find specified number of files out of total file list to sum """ # this returns only runs, left to sum with current sample_run sum settings #pylint: disable=unused-variable runs,sum_ws,added = PropertyManager.sample_run.get_runs_to_sum(None,num_files) if len(runs) == 0: return (True,[],[]) ok,not_found_list,found_list = PropertyManager.sample_run.find_run_files(runs) return (ok,not_found_list,found_list)
[ "def", "find_files_to_sum", "(", "self", ",", "num_files", "=", "None", ")", ":", "# this returns only runs, left to sum with current sample_run sum settings", "#pylint: disable=unused-variable", "runs", ",", "sum_ws", ",", "added", "=", "PropertyManager", ".", "sample_run", ".", "get_runs_to_sum", "(", "None", ",", "num_files", ")", "if", "len", "(", "runs", ")", "==", "0", ":", "return", "(", "True", ",", "[", "]", ",", "[", "]", ")", "ok", ",", "not_found_list", ",", "found_list", "=", "PropertyManager", ".", "sample_run", ".", "find_run_files", "(", "runs", ")", "return", "(", "ok", ",", "not_found_list", ",", "found_list", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/Inelastic/Direct/PropertyManager.py#L605-L620
tpfister/caffe-heatmap
4db69ef53e6b8a0b3b4ebb29328b0ab3dbf67c4e
scripts/cpp_lint.py
python
Error
(filename, linenum, category, confidence, message)
Logs the fact we've found a lint error. We log where the error was found, and also our confidence in the error, that is, how certain we are this is a legitimate style regression, and not a misidentification or a use that's sometimes justified. False positives can be suppressed by the use of "cpplint(category)" comments on the offending line. These are parsed into _error_suppressions. Args: filename: The name of the file containing the error. linenum: The number of the line containing the error. category: A string used to describe the "category" this bug falls under: "whitespace", say, or "runtime". Categories may have a hierarchy separated by slashes: "whitespace/indent". confidence: A number from 1-5 representing a confidence score for the error, with 5 meaning that we are certain of the problem, and 1 meaning that it could be a legitimate construct. message: The error message.
Logs the fact we've found a lint error.
[ "Logs", "the", "fact", "we", "ve", "found", "a", "lint", "error", "." ]
def Error(filename, linenum, category, confidence, message): """Logs the fact we've found a lint error. We log where the error was found, and also our confidence in the error, that is, how certain we are this is a legitimate style regression, and not a misidentification or a use that's sometimes justified. False positives can be suppressed by the use of "cpplint(category)" comments on the offending line. These are parsed into _error_suppressions. Args: filename: The name of the file containing the error. linenum: The number of the line containing the error. category: A string used to describe the "category" this bug falls under: "whitespace", say, or "runtime". Categories may have a hierarchy separated by slashes: "whitespace/indent". confidence: A number from 1-5 representing a confidence score for the error, with 5 meaning that we are certain of the problem, and 1 meaning that it could be a legitimate construct. message: The error message. """ if _ShouldPrintError(category, confidence, linenum): _cpplint_state.IncrementErrorCount(category) if _cpplint_state.output_format == 'vs7': sys.stderr.write('%s(%s): %s [%s] [%d]\n' % ( filename, linenum, message, category, confidence)) elif _cpplint_state.output_format == 'eclipse': sys.stderr.write('%s:%s: warning: %s [%s] [%d]\n' % ( filename, linenum, message, category, confidence)) else: sys.stderr.write('%s:%s: %s [%s] [%d]\n' % ( filename, linenum, message, category, confidence))
[ "def", "Error", "(", "filename", ",", "linenum", ",", "category", ",", "confidence", ",", "message", ")", ":", "if", "_ShouldPrintError", "(", "category", ",", "confidence", ",", "linenum", ")", ":", "_cpplint_state", ".", "IncrementErrorCount", "(", "category", ")", "if", "_cpplint_state", ".", "output_format", "==", "'vs7'", ":", "sys", ".", "stderr", ".", "write", "(", "'%s(%s): %s [%s] [%d]\\n'", "%", "(", "filename", ",", "linenum", ",", "message", ",", "category", ",", "confidence", ")", ")", "elif", "_cpplint_state", ".", "output_format", "==", "'eclipse'", ":", "sys", ".", "stderr", ".", "write", "(", "'%s:%s: warning: %s [%s] [%d]\\n'", "%", "(", "filename", ",", "linenum", ",", "message", ",", "category", ",", "confidence", ")", ")", "else", ":", "sys", ".", "stderr", ".", "write", "(", "'%s:%s: %s [%s] [%d]\\n'", "%", "(", "filename", ",", "linenum", ",", "message", ",", "category", ",", "confidence", ")", ")" ]
https://github.com/tpfister/caffe-heatmap/blob/4db69ef53e6b8a0b3b4ebb29328b0ab3dbf67c4e/scripts/cpp_lint.py#L988-L1020
bigartm/bigartm
47e37f982de87aa67bfd475ff1f39da696b181b3
3rdparty/protobuf-3.0.0/python/google/protobuf/internal/decoder.py
python
_ModifiedDecoder
(wire_type, decode_value, modify_value)
return _SimpleDecoder(wire_type, InnerDecode)
Like SimpleDecoder but additionally invokes modify_value on every value before storing it. Usually modify_value is ZigZagDecode.
Like SimpleDecoder but additionally invokes modify_value on every value before storing it. Usually modify_value is ZigZagDecode.
[ "Like", "SimpleDecoder", "but", "additionally", "invokes", "modify_value", "on", "every", "value", "before", "storing", "it", ".", "Usually", "modify_value", "is", "ZigZagDecode", "." ]
def _ModifiedDecoder(wire_type, decode_value, modify_value): """Like SimpleDecoder but additionally invokes modify_value on every value before storing it. Usually modify_value is ZigZagDecode. """ # Reusing _SimpleDecoder is slightly slower than copying a bunch of code, but # not enough to make a significant difference. def InnerDecode(buffer, pos): (result, new_pos) = decode_value(buffer, pos) return (modify_value(result), new_pos) return _SimpleDecoder(wire_type, InnerDecode)
[ "def", "_ModifiedDecoder", "(", "wire_type", ",", "decode_value", ",", "modify_value", ")", ":", "# Reusing _SimpleDecoder is slightly slower than copying a bunch of code, but", "# not enough to make a significant difference.", "def", "InnerDecode", "(", "buffer", ",", "pos", ")", ":", "(", "result", ",", "new_pos", ")", "=", "decode_value", "(", "buffer", ",", "pos", ")", "return", "(", "modify_value", "(", "result", ")", ",", "new_pos", ")", "return", "_SimpleDecoder", "(", "wire_type", ",", "InnerDecode", ")" ]
https://github.com/bigartm/bigartm/blob/47e37f982de87aa67bfd475ff1f39da696b181b3/3rdparty/protobuf-3.0.0/python/google/protobuf/internal/decoder.py#L249-L260
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/manage/cmdshell.py
python
LocalClient.listdir
(self, path)
return os.listdir(path)
List all of the files and subdirectories at the specified path. :rtype: list :return: Return a list containing the names of the entries in the directory given by path.
List all of the files and subdirectories at the specified path. :rtype: list :return: Return a list containing the names of the entries in the directory given by path.
[ "List", "all", "of", "the", "files", "and", "subdirectories", "at", "the", "specified", "path", ".", ":", "rtype", ":", "list", ":", "return", ":", "Return", "a", "list", "containing", "the", "names", "of", "the", "entries", "in", "the", "directory", "given", "by", "path", "." ]
def listdir(self, path): """ List all of the files and subdirectories at the specified path. :rtype: list :return: Return a list containing the names of the entries in the directory given by path. """ return os.listdir(path)
[ "def", "listdir", "(", "self", ",", "path", ")", ":", "return", "os", ".", "listdir", "(", "path", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/manage/cmdshell.py#L294-L302
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/framework/dtypes.py
python
as_dtype
(type_value)
Converts the given `type_value` to a `DType`. Args: type_value: A value that can be converted to a `tf.DType` object. This may currently be a `tf.DType` object, a [`DataType` enum](https://www.tensorflow.org/code/tensorflow/core/framework/types.proto), a string type name, or a `numpy.dtype`. Returns: A `DType` corresponding to `type_value`. Raises: TypeError: If `type_value` cannot be converted to a `DType`.
Converts the given `type_value` to a `DType`.
[ "Converts", "the", "given", "type_value", "to", "a", "DType", "." ]
def as_dtype(type_value): """Converts the given `type_value` to a `DType`. Args: type_value: A value that can be converted to a `tf.DType` object. This may currently be a `tf.DType` object, a [`DataType` enum](https://www.tensorflow.org/code/tensorflow/core/framework/types.proto), a string type name, or a `numpy.dtype`. Returns: A `DType` corresponding to `type_value`. Raises: TypeError: If `type_value` cannot be converted to a `DType`. """ if isinstance(type_value, DType): return type_value try: return _INTERN_TABLE[type_value] except KeyError: pass try: return _STRING_TO_TF[type_value] except KeyError: pass if isinstance(type_value, np.dtype): # The numpy dtype for strings is variable length. We can not compare # dtype with a single constant (np.string does not exist) to decide # dtype is a "string" type. We need to compare the dtype.type to be # sure it's a string type. if type_value.type == np.string_ or type_value.type == np.unicode_: return string for key, val in _NP_TO_TF: if key == type_value: return val raise TypeError( "Cannot convert value %r to a TensorFlow DType." % type_value)
[ "def", "as_dtype", "(", "type_value", ")", ":", "if", "isinstance", "(", "type_value", ",", "DType", ")", ":", "return", "type_value", "try", ":", "return", "_INTERN_TABLE", "[", "type_value", "]", "except", "KeyError", ":", "pass", "try", ":", "return", "_STRING_TO_TF", "[", "type_value", "]", "except", "KeyError", ":", "pass", "if", "isinstance", "(", "type_value", ",", "np", ".", "dtype", ")", ":", "# The numpy dtype for strings is variable length. We can not compare", "# dtype with a single constant (np.string does not exist) to decide", "# dtype is a \"string\" type. We need to compare the dtype.type to be", "# sure it's a string type.", "if", "type_value", ".", "type", "==", "np", ".", "string_", "or", "type_value", ".", "type", "==", "np", ".", "unicode_", ":", "return", "string", "for", "key", ",", "val", "in", "_NP_TO_TF", ":", "if", "key", "==", "type_value", ":", "return", "val", "raise", "TypeError", "(", "\"Cannot convert value %r to a TensorFlow DType.\"", "%", "type_value", ")" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/framework/dtypes.py#L500-L541
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/decimal.py
python
Decimal.compare_total
(self, other)
return _Zero
Compares self to other using the abstract representations. This is not like the standard compare, which use their numerical value. Note that a total ordering is defined for all possible abstract representations.
Compares self to other using the abstract representations.
[ "Compares", "self", "to", "other", "using", "the", "abstract", "representations", "." ]
def compare_total(self, other): """Compares self to other using the abstract representations. This is not like the standard compare, which use their numerical value. Note that a total ordering is defined for all possible abstract representations. """ other = _convert_other(other, raiseit=True) # if one is negative and the other is positive, it's easy if self._sign and not other._sign: return _NegativeOne if not self._sign and other._sign: return _One sign = self._sign # let's handle both NaN types self_nan = self._isnan() other_nan = other._isnan() if self_nan or other_nan: if self_nan == other_nan: # compare payloads as though they're integers self_key = len(self._int), self._int other_key = len(other._int), other._int if self_key < other_key: if sign: return _One else: return _NegativeOne if self_key > other_key: if sign: return _NegativeOne else: return _One return _Zero if sign: if self_nan == 1: return _NegativeOne if other_nan == 1: return _One if self_nan == 2: return _NegativeOne if other_nan == 2: return _One else: if self_nan == 1: return _One if other_nan == 1: return _NegativeOne if self_nan == 2: return _One if other_nan == 2: return _NegativeOne if self < other: return _NegativeOne if self > other: return _One if self._exp < other._exp: if sign: return _One else: return _NegativeOne if self._exp > other._exp: if sign: return _NegativeOne else: return _One return _Zero
[ "def", "compare_total", "(", "self", ",", "other", ")", ":", "other", "=", "_convert_other", "(", "other", ",", "raiseit", "=", "True", ")", "# if one is negative and the other is positive, it's easy", "if", "self", ".", "_sign", "and", "not", "other", ".", "_sign", ":", "return", "_NegativeOne", "if", "not", "self", ".", "_sign", "and", "other", ".", "_sign", ":", "return", "_One", "sign", "=", "self", ".", "_sign", "# let's handle both NaN types", "self_nan", "=", "self", ".", "_isnan", "(", ")", "other_nan", "=", "other", ".", "_isnan", "(", ")", "if", "self_nan", "or", "other_nan", ":", "if", "self_nan", "==", "other_nan", ":", "# compare payloads as though they're integers", "self_key", "=", "len", "(", "self", ".", "_int", ")", ",", "self", ".", "_int", "other_key", "=", "len", "(", "other", ".", "_int", ")", ",", "other", ".", "_int", "if", "self_key", "<", "other_key", ":", "if", "sign", ":", "return", "_One", "else", ":", "return", "_NegativeOne", "if", "self_key", ">", "other_key", ":", "if", "sign", ":", "return", "_NegativeOne", "else", ":", "return", "_One", "return", "_Zero", "if", "sign", ":", "if", "self_nan", "==", "1", ":", "return", "_NegativeOne", "if", "other_nan", "==", "1", ":", "return", "_One", "if", "self_nan", "==", "2", ":", "return", "_NegativeOne", "if", "other_nan", "==", "2", ":", "return", "_One", "else", ":", "if", "self_nan", "==", "1", ":", "return", "_One", "if", "other_nan", "==", "1", ":", "return", "_NegativeOne", "if", "self_nan", "==", "2", ":", "return", "_One", "if", "other_nan", "==", "2", ":", "return", "_NegativeOne", "if", "self", "<", "other", ":", "return", "_NegativeOne", "if", "self", ">", "other", ":", "return", "_One", "if", "self", ".", "_exp", "<", "other", ".", "_exp", ":", "if", "sign", ":", "return", "_One", "else", ":", "return", "_NegativeOne", "if", "self", ".", "_exp", ">", "other", ".", "_exp", ":", "if", "sign", ":", "return", "_NegativeOne", "else", ":", "return", "_One", "return", "_Zero" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/decimal.py#L2831-L2901
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/dynamodb/types.py
python
Dynamizer.decode
(self, attr)
return decoder(attr[dynamodb_type])
Takes the format returned by DynamoDB and constructs the appropriate python type.
Takes the format returned by DynamoDB and constructs the appropriate python type.
[ "Takes", "the", "format", "returned", "by", "DynamoDB", "and", "constructs", "the", "appropriate", "python", "type", "." ]
def decode(self, attr): """ Takes the format returned by DynamoDB and constructs the appropriate python type. """ if len(attr) > 1 or not attr: return attr dynamodb_type = list(attr.keys())[0] if dynamodb_type.lower() == dynamodb_type: # It's not an actual type, just a single character attr that # overlaps with the DDB types. Return it. return attr try: decoder = getattr(self, '_decode_%s' % dynamodb_type.lower()) except AttributeError: return attr return decoder(attr[dynamodb_type])
[ "def", "decode", "(", "self", ",", "attr", ")", ":", "if", "len", "(", "attr", ")", ">", "1", "or", "not", "attr", ":", "return", "attr", "dynamodb_type", "=", "list", "(", "attr", ".", "keys", "(", ")", ")", "[", "0", "]", "if", "dynamodb_type", ".", "lower", "(", ")", "==", "dynamodb_type", ":", "# It's not an actual type, just a single character attr that", "# overlaps with the DDB types. Return it.", "return", "attr", "try", ":", "decoder", "=", "getattr", "(", "self", ",", "'_decode_%s'", "%", "dynamodb_type", ".", "lower", "(", ")", ")", "except", "AttributeError", ":", "return", "attr", "return", "decoder", "(", "attr", "[", "dynamodb_type", "]", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/dynamodb/types.py#L330-L347
SFTtech/openage
d6a08c53c48dc1e157807471df92197f6ca9e04d
openage/util/fslike/abstract.py
python
FSLikeObject.mtime
(self, parts)
Shall determine the last modification time (UNIX timestamp), and return None if unknown.
Shall determine the last modification time (UNIX timestamp), and return None if unknown.
[ "Shall", "determine", "the", "last", "modification", "time", "(", "UNIX", "timestamp", ")", "and", "return", "None", "if", "unknown", "." ]
def mtime(self, parts): """ Shall determine the last modification time (UNIX timestamp), and return None if unknown. """
[ "def", "mtime", "(", "self", ",", "parts", ")", ":" ]
https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/util/fslike/abstract.py#L114-L118
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/protobuf/python/google/protobuf/text_format.py
python
_Printer.PrintMessage
(self, message)
Convert protobuf message to text format. Args: message: The protocol buffers message.
Convert protobuf message to text format.
[ "Convert", "protobuf", "message", "to", "text", "format", "." ]
def PrintMessage(self, message): """Convert protobuf message to text format. Args: message: The protocol buffers message. """ fields = message.ListFields() if self.use_index_order: fields.sort(key=lambda x: x[0].index) for field, value in fields: if _IsMapEntry(field): for key in sorted(value): # This is slow for maps with submessage entires because it copies the # entire tree. Unfortunately this would take significant refactoring # of this file to work around. # # TODO(haberman): refactor and optimize if this becomes an issue. entry_submsg = field.message_type._concrete_class( key=key, value=value[key]) self.PrintField(field, entry_submsg) elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED: for element in value: self.PrintField(field, element) else: self.PrintField(field, value)
[ "def", "PrintMessage", "(", "self", ",", "message", ")", ":", "fields", "=", "message", ".", "ListFields", "(", ")", "if", "self", ".", "use_index_order", ":", "fields", ".", "sort", "(", "key", "=", "lambda", "x", ":", "x", "[", "0", "]", ".", "index", ")", "for", "field", ",", "value", "in", "fields", ":", "if", "_IsMapEntry", "(", "field", ")", ":", "for", "key", "in", "sorted", "(", "value", ")", ":", "# This is slow for maps with submessage entires because it copies the", "# entire tree. Unfortunately this would take significant refactoring", "# of this file to work around.", "#", "# TODO(haberman): refactor and optimize if this becomes an issue.", "entry_submsg", "=", "field", ".", "message_type", ".", "_concrete_class", "(", "key", "=", "key", ",", "value", "=", "value", "[", "key", "]", ")", "self", ".", "PrintField", "(", "field", ",", "entry_submsg", ")", "elif", "field", ".", "label", "==", "descriptor", ".", "FieldDescriptor", ".", "LABEL_REPEATED", ":", "for", "element", "in", "value", ":", "self", ".", "PrintField", "(", "field", ",", "element", ")", "else", ":", "self", ".", "PrintField", "(", "field", ",", "value", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/protobuf/python/google/protobuf/text_format.py#L208-L232
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TFlt.GetInRng
(*args)
return _snap.TFlt_GetInRng(*args)
GetInRng(double const & Val, double const & Mn, double const & Mx) -> double Parameters: Val: double const & Mn: double const & Mx: double const &
GetInRng(double const & Val, double const & Mn, double const & Mx) -> double
[ "GetInRng", "(", "double", "const", "&", "Val", "double", "const", "&", "Mn", "double", "const", "&", "Mx", ")", "-", ">", "double" ]
def GetInRng(*args): """ GetInRng(double const & Val, double const & Mn, double const & Mx) -> double Parameters: Val: double const & Mn: double const & Mx: double const & """ return _snap.TFlt_GetInRng(*args)
[ "def", "GetInRng", "(", "*", "args", ")", ":", "return", "_snap", ".", "TFlt_GetInRng", "(", "*", "args", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L14485-L14495
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py
python
Target.PreCompileInput
(self)
return self.actions_stamp or self.precompile_stamp
Return the path, if any, that should be used as a dependency of any dependent compile step.
Return the path, if any, that should be used as a dependency of any dependent compile step.
[ "Return", "the", "path", "if", "any", "that", "should", "be", "used", "as", "a", "dependency", "of", "any", "dependent", "compile", "step", "." ]
def PreCompileInput(self): """Return the path, if any, that should be used as a dependency of any dependent compile step.""" return self.actions_stamp or self.precompile_stamp
[ "def", "PreCompileInput", "(", "self", ")", ":", "return", "self", ".", "actions_stamp", "or", "self", ".", "precompile_stamp" ]
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py#L173-L176
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_misc.py
python
Log_Resume
(*args)
return _misc_.Log_Resume(*args)
Log_Resume()
Log_Resume()
[ "Log_Resume", "()" ]
def Log_Resume(*args): """Log_Resume()""" return _misc_.Log_Resume(*args)
[ "def", "Log_Resume", "(", "*", "args", ")", ":", "return", "_misc_", ".", "Log_Resume", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L1676-L1678
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_gdi.py
python
DC.GetClippingBox
(*args, **kwargs)
return _gdi_.DC_GetClippingBox(*args, **kwargs)
GetClippingBox() -> (x, y, width, height) Gets the rectangle surrounding the current clipping region.
GetClippingBox() -> (x, y, width, height)
[ "GetClippingBox", "()", "-", ">", "(", "x", "y", "width", "height", ")" ]
def GetClippingBox(*args, **kwargs): """ GetClippingBox() -> (x, y, width, height) Gets the rectangle surrounding the current clipping region. """ return _gdi_.DC_GetClippingBox(*args, **kwargs)
[ "def", "GetClippingBox", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "DC_GetClippingBox", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_gdi.py#L4084-L4090
nasa/fprime
595cf3682d8365943d86c1a6fe7c78f0a116acf0
Autocoders/Python/src/fprime_ac/utils/DiffAndRename.py
python
renameAsErroneous
(fileName, script=None)
fileName argument represents the name of the target file, e.g., mod_ac_evr_ids.h. If the generation of the new file (named mod_ac_evr_ids.h.new by convention in all actools scripts) has some problems, then rather than ever replacing the old file with the new flawed file, the new flawed file will be named with a time-stamp and '.error', for example: mod_ac_evr_ids.h.20071101T003932.errors
fileName argument represents the name of the target file, e.g., mod_ac_evr_ids.h. If the generation of the new file (named mod_ac_evr_ids.h.new by convention in all actools scripts) has some problems, then rather than ever replacing the old file with the new flawed file, the new flawed file will be named with a time-stamp and '.error', for example: mod_ac_evr_ids.h.20071101T003932.errors
[ "fileName", "argument", "represents", "the", "name", "of", "the", "target", "file", "e", ".", "g", ".", "mod_ac_evr_ids", ".", "h", ".", "If", "the", "generation", "of", "the", "new", "file", "(", "named", "mod_ac_evr_ids", ".", "h", ".", "new", "by", "convention", "in", "all", "actools", "scripts", ")", "has", "some", "problems", "then", "rather", "than", "ever", "replacing", "the", "old", "file", "with", "the", "new", "flawed", "file", "the", "new", "flawed", "file", "will", "be", "named", "with", "a", "time", "-", "stamp", "and", ".", "error", "for", "example", ":", "mod_ac_evr_ids", ".", "h", ".", "20071101T003932", ".", "errors" ]
def renameAsErroneous(fileName, script=None): """ fileName argument represents the name of the target file, e.g., mod_ac_evr_ids.h. If the generation of the new file (named mod_ac_evr_ids.h.new by convention in all actools scripts) has some problems, then rather than ever replacing the old file with the new flawed file, the new flawed file will be named with a time-stamp and '.error', for example: mod_ac_evr_ids.h.20071101T003932.errors """ origfileName = fileName + ".new" timeTag = fileTimeTag(origfileName) errfileName = fileName + timeTag + ".errors" os.rename(origfileName, errfileName) if script: PRINT.error( "{}: this generated file is invalid: {}".format(script, errfileName) ) else: PRINT.error("This generated file is invalid: %s" % errfileName)
[ "def", "renameAsErroneous", "(", "fileName", ",", "script", "=", "None", ")", ":", "origfileName", "=", "fileName", "+", "\".new\"", "timeTag", "=", "fileTimeTag", "(", "origfileName", ")", "errfileName", "=", "fileName", "+", "timeTag", "+", "\".errors\"", "os", ".", "rename", "(", "origfileName", ",", "errfileName", ")", "if", "script", ":", "PRINT", ".", "error", "(", "\"{}: this generated file is invalid: {}\"", ".", "format", "(", "script", ",", "errfileName", ")", ")", "else", ":", "PRINT", ".", "error", "(", "\"This generated file is invalid: %s\"", "%", "errfileName", ")" ]
https://github.com/nasa/fprime/blob/595cf3682d8365943d86c1a6fe7c78f0a116acf0/Autocoders/Python/src/fprime_ac/utils/DiffAndRename.py#L208-L227
NREL/EnergyPlus
fadc5973b85c70e8cc923efb69c144e808a26078
src/EnergyPlus/api/func.py
python
Glycol.__init__
(self, state: c_void_p, api: cdll, glycol_name: bytes)
Creates a new Glycol instance, should almost certainly always be called from the API's Functional class, not directly from user code. To get a Glycol instance from client code, call api.functional.glycol(state, "name"), where state is an active EnergyPlus state returned from a call to `api.state_manager.new_state()`. :param state: An active EnergyPlus "state" that is returned from a call to `api.state_manager.new_state()` :param api: An active CTYPES CDLL instance :param glycol_name: The name of the glycol to instantiate -- currently only "water" is supported.
Creates a new Glycol instance, should almost certainly always be called from the API's Functional class, not directly from user code. To get a Glycol instance from client code, call api.functional.glycol(state, "name"), where state is an active EnergyPlus state returned from a call to `api.state_manager.new_state()`.
[ "Creates", "a", "new", "Glycol", "instance", "should", "almost", "certainly", "always", "be", "called", "from", "the", "API", "s", "Functional", "class", "not", "directly", "from", "user", "code", ".", "To", "get", "a", "Glycol", "instance", "from", "client", "code", "call", "api", ".", "functional", ".", "glycol", "(", "state", "name", ")", "where", "state", "is", "an", "active", "EnergyPlus", "state", "returned", "from", "a", "call", "to", "api", ".", "state_manager", ".", "new_state", "()", "." ]
def __init__(self, state: c_void_p, api: cdll, glycol_name: bytes): """ Creates a new Glycol instance, should almost certainly always be called from the API's Functional class, not directly from user code. To get a Glycol instance from client code, call api.functional.glycol(state, "name"), where state is an active EnergyPlus state returned from a call to `api.state_manager.new_state()`. :param state: An active EnergyPlus "state" that is returned from a call to `api.state_manager.new_state()` :param api: An active CTYPES CDLL instance :param glycol_name: The name of the glycol to instantiate -- currently only "water" is supported. """ self.api = api self.api.glycolNew.argtypes = [c_void_p, c_char_p] self.api.glycolNew.restype = c_void_p self.api.glycolDelete.argtypes = [c_void_p, c_void_p] self.api.glycolDelete.restype = c_void_p self.api.glycolSpecificHeat.argtypes = [c_void_p, c_void_p, RealEP] self.api.glycolSpecificHeat.restype = RealEP self.api.glycolDensity.argtypes = [c_void_p, c_void_p, RealEP] self.api.glycolDensity.restype = RealEP self.api.glycolConductivity.argtypes = [c_void_p, c_void_p, RealEP] self.api.glycolConductivity.restype = RealEP self.api.glycolViscosity.argtypes = [c_void_p, c_void_p, RealEP] self.api.glycolViscosity.restype = RealEP self.instance = self.api.glycolNew(state, glycol_name)
[ "def", "__init__", "(", "self", ",", "state", ":", "c_void_p", ",", "api", ":", "cdll", ",", "glycol_name", ":", "bytes", ")", ":", "self", ".", "api", "=", "api", "self", ".", "api", ".", "glycolNew", ".", "argtypes", "=", "[", "c_void_p", ",", "c_char_p", "]", "self", ".", "api", ".", "glycolNew", ".", "restype", "=", "c_void_p", "self", ".", "api", ".", "glycolDelete", ".", "argtypes", "=", "[", "c_void_p", ",", "c_void_p", "]", "self", ".", "api", ".", "glycolDelete", ".", "restype", "=", "c_void_p", "self", ".", "api", ".", "glycolSpecificHeat", ".", "argtypes", "=", "[", "c_void_p", ",", "c_void_p", ",", "RealEP", "]", "self", ".", "api", ".", "glycolSpecificHeat", ".", "restype", "=", "RealEP", "self", ".", "api", ".", "glycolDensity", ".", "argtypes", "=", "[", "c_void_p", ",", "c_void_p", ",", "RealEP", "]", "self", ".", "api", ".", "glycolDensity", ".", "restype", "=", "RealEP", "self", ".", "api", ".", "glycolConductivity", ".", "argtypes", "=", "[", "c_void_p", ",", "c_void_p", ",", "RealEP", "]", "self", ".", "api", ".", "glycolConductivity", ".", "restype", "=", "RealEP", "self", ".", "api", ".", "glycolViscosity", ".", "argtypes", "=", "[", "c_void_p", ",", "c_void_p", ",", "RealEP", "]", "self", ".", "api", ".", "glycolViscosity", ".", "restype", "=", "RealEP", "self", ".", "instance", "=", "self", ".", "api", ".", "glycolNew", "(", "state", ",", "glycol_name", ")" ]
https://github.com/NREL/EnergyPlus/blob/fadc5973b85c70e8cc923efb69c144e808a26078/src/EnergyPlus/api/func.py#L77-L100
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/queue.py
python
_PySimpleQueue.put
(self, item, block=True, timeout=None)
Put the item on the queue. The optional 'block' and 'timeout' arguments are ignored, as this method never blocks. They are provided for compatibility with the Queue class.
Put the item on the queue.
[ "Put", "the", "item", "on", "the", "queue", "." ]
def put(self, item, block=True, timeout=None): '''Put the item on the queue. The optional 'block' and 'timeout' arguments are ignored, as this method never blocks. They are provided for compatibility with the Queue class. ''' self._queue.append(item) self._count.release()
[ "def", "put", "(", "self", ",", "item", ",", "block", "=", "True", ",", "timeout", "=", "None", ")", ":", "self", ".", "_queue", ".", "append", "(", "item", ")", "self", ".", "_count", ".", "release", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/queue.py#L269-L276
apache/mesos
97d9a4063332aae3825d78de71611657e05cf5e2
src/python/lib/setup.py
python
find_version
(*relative_path_parts)
Find the version string in a file relative to the current directory. :param relative_path_parts: list of path parts relative to the current directory where the file containing the __version__ string lives :type relative_path_parts: list[str] :rtype: str
Find the version string in a file relative to the current directory.
[ "Find", "the", "version", "string", "in", "a", "file", "relative", "to", "the", "current", "directory", "." ]
def find_version(*relative_path_parts): """ Find the version string in a file relative to the current directory. :param relative_path_parts: list of path parts relative to the current directory where the file containing the __version__ string lives :type relative_path_parts: list[str] :rtype: str """ currdir = os.path.abspath(os.path.dirname(__file__)) version_file = os.path.join(currdir, *relative_path_parts) with open(version_file, 'r') as f: match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", f.read(), re.M) if not match: raise RuntimeError("Unable to find version string.") return match.group(1)
[ "def", "find_version", "(", "*", "relative_path_parts", ")", ":", "currdir", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ")", "version_file", "=", "os", ".", "path", ".", "join", "(", "currdir", ",", "*", "relative_path_parts", ")", "with", "open", "(", "version_file", ",", "'r'", ")", "as", "f", ":", "match", "=", "re", ".", "search", "(", "r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\"", ",", "f", ".", "read", "(", ")", ",", "re", ".", "M", ")", "if", "not", "match", ":", "raise", "RuntimeError", "(", "\"Unable to find version string.\"", ")", "return", "match", ".", "group", "(", "1", ")" ]
https://github.com/apache/mesos/blob/97d9a4063332aae3825d78de71611657e05cf5e2/src/python/lib/setup.py#L38-L56
artyom-beilis/cppcms
463a9a68e0bc15e2d01e8b8d72cc4fcc7f2b3264
contrib/integration/session/python/cppcms.py
python
Session.clear
(self)
Clear entire session
Clear entire session
[ "Clear", "entire", "session" ]
def clear(self): """Clear entire session""" Loader.capi.cppcms_capi_session_clear(self.d) self.check()
[ "def", "clear", "(", "self", ")", ":", "Loader", ".", "capi", ".", "cppcms_capi_session_clear", "(", "self", ".", "d", ")", "self", ".", "check", "(", ")" ]
https://github.com/artyom-beilis/cppcms/blob/463a9a68e0bc15e2d01e8b8d72cc4fcc7f2b3264/contrib/integration/session/python/cppcms.py#L263-L266
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/richtext.py
python
TextBoxAttr.GetPadding
(*args)
return _richtext.TextBoxAttr_GetPadding(*args)
GetPadding(self) -> TextAttrDimensions GetPadding(self) -> TextAttrDimensions
GetPadding(self) -> TextAttrDimensions GetPadding(self) -> TextAttrDimensions
[ "GetPadding", "(", "self", ")", "-", ">", "TextAttrDimensions", "GetPadding", "(", "self", ")", "-", ">", "TextAttrDimensions" ]
def GetPadding(*args): """ GetPadding(self) -> TextAttrDimensions GetPadding(self) -> TextAttrDimensions """ return _richtext.TextBoxAttr_GetPadding(*args)
[ "def", "GetPadding", "(", "*", "args", ")", ":", "return", "_richtext", ".", "TextBoxAttr_GetPadding", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L698-L703
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/variables.py
python
Variable._OverloadAllOperators
()
Register overloads for all operators.
Register overloads for all operators.
[ "Register", "overloads", "for", "all", "operators", "." ]
def _OverloadAllOperators(): # pylint: disable=invalid-name """Register overloads for all operators.""" for operator in ops.Tensor.OVERLOADABLE_OPERATORS: Variable._OverloadOperator(operator) # For slicing, bind getitem differently than a tensor (use SliceHelperVar # instead) # pylint: disable=protected-access setattr(Variable, "__getitem__", array_ops._SliceHelperVar)
[ "def", "_OverloadAllOperators", "(", ")", ":", "# pylint: disable=invalid-name", "for", "operator", "in", "ops", ".", "Tensor", ".", "OVERLOADABLE_OPERATORS", ":", "Variable", ".", "_OverloadOperator", "(", "operator", ")", "# For slicing, bind getitem differently than a tensor (use SliceHelperVar", "# instead)", "# pylint: disable=protected-access", "setattr", "(", "Variable", ",", "\"__getitem__\"", ",", "array_ops", ".", "_SliceHelperVar", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/variables.py#L738-L745
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/tools/ci_build/update_version.py
python
Version.__init__
(self, major, minor, patch, identifier_string, version_type)
Constructor. Args: major: major string eg. (1) minor: minor string eg. (3) patch: patch string eg. (1) identifier_string: extension string eg. (-rc0) version_type: version parameter ((REGULAR|NIGHTLY)_VERSION)
Constructor.
[ "Constructor", "." ]
def __init__(self, major, minor, patch, identifier_string, version_type): """Constructor. Args: major: major string eg. (1) minor: minor string eg. (3) patch: patch string eg. (1) identifier_string: extension string eg. (-rc0) version_type: version parameter ((REGULAR|NIGHTLY)_VERSION) """ self.string = "%s.%s.%s%s" % (major, minor, patch, identifier_string) self.major = major self.minor = minor self.patch = patch self.identifier_string = identifier_string self.version_type = version_type
[ "def", "__init__", "(", "self", ",", "major", ",", "minor", ",", "patch", ",", "identifier_string", ",", "version_type", ")", ":", "self", ".", "string", "=", "\"%s.%s.%s%s\"", "%", "(", "major", ",", "minor", ",", "patch", ",", "identifier_string", ")", "self", ".", "major", "=", "major", "self", ".", "minor", "=", "minor", "self", ".", "patch", "=", "patch", "self", ".", "identifier_string", "=", "identifier_string", "self", ".", "version_type", "=", "version_type" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/tools/ci_build/update_version.py#L80-L98
MythTV/mythtv
d282a209cb8be85d036f85a62a8ec971b67d45f4
mythtv/contrib/imports/mirobridge/mirobridge/mirobridge_interpreter_6_0_0.py
python
MiroInterpreter.is_punct_char
(self, char)
return char in string.punctuation
check if char is punctuation char return True if char is punctuation return False if char is not punctuation
check if char is punctuation char return True if char is punctuation return False if char is not punctuation
[ "check", "if", "char", "is", "punctuation", "char", "return", "True", "if", "char", "is", "punctuation", "return", "False", "if", "char", "is", "not", "punctuation" ]
def is_punct_char(self, char): '''check if char is punctuation char return True if char is punctuation return False if char is not punctuation ''' return char in string.punctuation
[ "def", "is_punct_char", "(", "self", ",", "char", ")", ":", "return", "char", "in", "string", ".", "punctuation" ]
https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/contrib/imports/mirobridge/mirobridge/mirobridge_interpreter_6_0_0.py#L527-L532
Tencent/Pebble
68315f176d9e328a233ace29b7579a829f89879f
thirdparty/gflags/gflags.py
python
DocToHelp
(doc)
return doc
Takes a __doc__ string and reformats it as help.
Takes a __doc__ string and reformats it as help.
[ "Takes", "a", "__doc__", "string", "and", "reformats", "it", "as", "help", "." ]
def DocToHelp(doc): """Takes a __doc__ string and reformats it as help.""" # Get rid of starting and ending white space. Using lstrip() or even # strip() could drop more than maximum of first line and right space # of last line. doc = doc.strip() # Get rid of all empty lines whitespace_only_line = re.compile('^[ \t]+$', re.M) doc = whitespace_only_line.sub('', doc) # Cut out common space at line beginnings doc = CutCommonSpacePrefix(doc) # Just like this module's comment, comments tend to be aligned somehow. # In other words they all start with the same amount of white space # 1) keep double new lines # 2) keep ws after new lines if not empty line # 3) all other new lines shall be changed to a space # Solution: Match new lines between non white space and replace with space. doc = re.sub('(?<=\S)\n(?=\S)', ' ', doc, re.M) return doc
[ "def", "DocToHelp", "(", "doc", ")", ":", "# Get rid of starting and ending white space. Using lstrip() or even", "# strip() could drop more than maximum of first line and right space", "# of last line.", "doc", "=", "doc", ".", "strip", "(", ")", "# Get rid of all empty lines", "whitespace_only_line", "=", "re", ".", "compile", "(", "'^[ \\t]+$'", ",", "re", ".", "M", ")", "doc", "=", "whitespace_only_line", ".", "sub", "(", "''", ",", "doc", ")", "# Cut out common space at line beginnings", "doc", "=", "CutCommonSpacePrefix", "(", "doc", ")", "# Just like this module's comment, comments tend to be aligned somehow.", "# In other words they all start with the same amount of white space", "# 1) keep double new lines", "# 2) keep ws after new lines if not empty line", "# 3) all other new lines shall be changed to a space", "# Solution: Match new lines between non white space and replace with space.", "doc", "=", "re", ".", "sub", "(", "'(?<=\\S)\\n(?=\\S)'", ",", "' '", ",", "doc", ",", "re", ".", "M", ")", "return", "doc" ]
https://github.com/Tencent/Pebble/blob/68315f176d9e328a233ace29b7579a829f89879f/thirdparty/gflags/gflags.py#L694-L717
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/prompt-toolkit/py3/prompt_toolkit/formatted_text/ansi.py
python
ANSI._create_style_string
(self)
return " ".join(result)
Turn current style flags into a string for usage in a formatted text.
Turn current style flags into a string for usage in a formatted text.
[ "Turn", "current", "style", "flags", "into", "a", "string", "for", "usage", "in", "a", "formatted", "text", "." ]
def _create_style_string(self) -> str: """ Turn current style flags into a string for usage in a formatted text. """ result = [] if self._color: result.append(self._color) if self._bgcolor: result.append("bg:" + self._bgcolor) if self._bold: result.append("bold") if self._underline: result.append("underline") if self._strike: result.append("strike") if self._italic: result.append("italic") if self._blink: result.append("blink") if self._reverse: result.append("reverse") if self._hidden: result.append("hidden") return " ".join(result)
[ "def", "_create_style_string", "(", "self", ")", "->", "str", ":", "result", "=", "[", "]", "if", "self", ".", "_color", ":", "result", ".", "append", "(", "self", ".", "_color", ")", "if", "self", ".", "_bgcolor", ":", "result", ".", "append", "(", "\"bg:\"", "+", "self", ".", "_bgcolor", ")", "if", "self", ".", "_bold", ":", "result", ".", "append", "(", "\"bold\"", ")", "if", "self", ".", "_underline", ":", "result", ".", "append", "(", "\"underline\"", ")", "if", "self", ".", "_strike", ":", "result", ".", "append", "(", "\"strike\"", ")", "if", "self", ".", "_italic", ":", "result", ".", "append", "(", "\"italic\"", ")", "if", "self", ".", "_blink", ":", "result", ".", "append", "(", "\"blink\"", ")", "if", "self", ".", "_reverse", ":", "result", ".", "append", "(", "\"reverse\"", ")", "if", "self", ".", "_hidden", ":", "result", ".", "append", "(", "\"hidden\"", ")", "return", "\" \"", ".", "join", "(", "result", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py3/prompt_toolkit/formatted_text/ansi.py#L223-L247
rdiankov/openrave
d1a23023fd4b58f077d2ca949ceaf1b91f3f13d7
python/ikfast.py
python
IKFastSolver.SolveAllEquations
(self,AllEquations,curvars,othersolvedvars,solsubs,endbranchtree,currentcases=None,unknownvars=None, currentcasesubs=None, canguessvars=True)
:param canguessvars: if True, can guess the variables given internal conditions are satisified
:param canguessvars: if True, can guess the variables given internal conditions are satisified
[ ":", "param", "canguessvars", ":", "if", "True", "can", "guess", "the", "variables", "given", "internal", "conditions", "are", "satisified" ]
def SolveAllEquations(self,AllEquations,curvars,othersolvedvars,solsubs,endbranchtree,currentcases=None,unknownvars=None, currentcasesubs=None, canguessvars=True): """ :param canguessvars: if True, can guess the variables given internal conditions are satisified """ self._CheckPreemptFn(progress=0.15+(0.3-0.3*100/(self._scopecounter+100))) # go from 0.15 - 0.45. usually scope counters go to several hundred if len(curvars) == 0: return endbranchtree if unknownvars is None: unknownvars = [] self._scopecounter+=1 scopecounter = int(self._scopecounter) log.info('depth=%d c=%d, %s %s: cases=%r', len(currentcases) if currentcases is not None else 0, self._scopecounter, othersolvedvars,curvars, currentcases) solsubs = solsubs[:] freevarinvsubs = [(f[1],f[0]) for f in self.freevarsubs] solinvsubs = [(f[1],f[0]) for f in solsubs] # single variable solutions solutions = [] for curvar in curvars: othervars = unknownvars+[var for var in curvars if var != curvar] curvarsym = self.Variable(curvar) raweqns = [] for e in AllEquations: if (len(othervars) == 0 or not e.has(*othervars)) and e.has(curvar,curvarsym.htvar,curvarsym.cvar,curvarsym.svar): eq = e.subs(self.freevarsubs+solsubs) if self.CheckExpressionUnique(raweqns,eq): raweqns.append(eq) if len(raweqns) > 0: try: rawsolutions=self.solveSingleVariable(self.sortComplexity(raweqns),curvar,othersolvedvars, unknownvars=curvars+unknownvars) for solution in rawsolutions: self.ComputeSolutionComplexity(solution,othersolvedvars,curvars) if solution.numsolutions()>0: solutions.append((solution,curvar)) else: log.warn('solution did not have any equations') except self.CannotSolveError: pass # only return here if a solution was found that perfectly determines the unknown # otherwise, the pairwise solver could come up with something.. # There is still a problem with this: (bertold robot) # Sometimes an equation like atan2(y,x) evaluates to atan2(0,0) during runtime. # This cannot be known at compile time, so the equation is selected and any other possibilities are rejected. # In the bertold robot case, the next possibility is a pair-wise solution involving two variables if any([s[0].numsolutions()==1 for s in solutions]): return self.AddSolution(solutions,AllEquations,curvars,othersolvedvars,solsubs,endbranchtree,currentcases=currentcases, currentcasesubs=currentcasesubs, unknownvars=unknownvars) curvarsubssol = [] for var0,var1 in combinations(curvars,2): othervars = unknownvars+[var for var in curvars if var != var0 and var != var1] raweqns = [] complexity = 0 for e in AllEquations: if (len(othervars) == 0 or not e.has(*othervars)) and e.has(var0,var1): eq = e.subs(self.freevarsubs+solsubs) if self.CheckExpressionUnique(raweqns,eq): raweqns.append(eq) complexity += self.codeComplexity(eq) if len(raweqns) > 1: curvarsubssol.append((var0,var1,raweqns,complexity)) curvarsubssol.sort(key=lambda e: e[3]) if len(curvars) == 2 and self.IsHinge(curvars[0].name) and self.IsHinge(curvars[1].name) and len(curvarsubssol) > 0: # there's only two variables left, it might be the case that the axes are aligning and the two variables are dependent on each other # note that the axes's anchors also have to be along the direction! var0,var1,raweqns,complexity = curvarsubssol[0] dummyvar = Symbol('dummy') dummyvalue = var0 + var1 NewEquations = [] NewEquationsAll = [] hasExtraConstraints = False for eq in raweqns: neweq = self.trigsimp(eq.subs(var0,dummyvar-var1).expand(trig=True),curvars) eq = neweq.subs(self.freevarsubs+solsubs) if self.CheckExpressionUnique(NewEquationsAll,eq): NewEquationsAll.append(eq) if neweq.has(dummyvar): if neweq.has(*(othervars+curvars)): hasExtraConstraints = True #break # don't know why breaking here... sometimes equations can be too complex but that doesn't mean variables are not dependent else: eq = neweq.subs(self.freevarsubs+solsubs) if self.CheckExpressionUnique(NewEquations,eq): NewEquations.append(eq) if len(NewEquations) < 2 and hasExtraConstraints: # try subtracting NewEquations = [] NewEquationsAll = [] hasExtraConstraints = False dummyvalue = var0 - var1 for eq in raweqns: neweq = self.trigsimp(eq.subs(var0,dummyvar+var1).expand(trig=True),curvars) eq = neweq.subs(self.freevarsubs+solsubs) if self.CheckExpressionUnique(NewEquationsAll,eq): NewEquationsAll.append(eq) if neweq.has(dummyvar): if neweq.has(*(othervars+curvars)): hasExtraConstraints = True #break # don't know why breaking here... sometimes equations can be too complex but that doesn't mean variables are not dependent else: eq = neweq.subs(self.freevarsubs+solsubs) if self.CheckExpressionUnique(NewEquations,eq): NewEquations.append(eq) if len(NewEquations) >= 2: dummysolutions = [] try: rawsolutions=self.solveSingleVariable(NewEquations,dummyvar,othersolvedvars, unknownvars=curvars+unknownvars) for solution in rawsolutions: self.ComputeSolutionComplexity(solution,othersolvedvars,curvars) dummysolutions.append(solution) except self.CannotSolveError: pass if any([s.numsolutions()==1 for s in dummysolutions]): # two axes are aligning, so modify the solutions to reflect the original variables and add a free variable log.info('found two aligning axes %s: %r',dummyvalue, NewEquations) solutions = [] for dummysolution in dummysolutions: if dummysolution.numsolutions() != 1: continue if dummysolution.jointevalsin is not None or dummysolution.jointevalcos is not None: log.warn('dummy solution should not have sin/cos parts!') sindummyvarsols = [] cosdummyvarsols = [] for eq in NewEquations: sols = solve(eq, sin(dummyvar)) sindummyvarsols += sols sols = solve(eq, cos(dummyvar)) cosdummyvarsols += sols # double check with NewEquationsAll that everything evluates to 0 newsubs = [(value, sin(dummyvar)) for value in sindummyvarsols] + [(value, cos(dummyvar)) for value in cosdummyvarsols] + [(-value, -sin(dummyvar)) for value in sindummyvarsols] + [(-value, -cos(dummyvar)) for value in cosdummyvarsols] allzeros = True for eq in NewEquationsAll: if trigsimp(eq.subs(newsubs)) != S.Zero: allzeros = False break if allzeros: solution=AST.SolverSolution(curvars[0].name, isHinge=self.IsHinge(curvars[0].name)) solution.jointeval = [dummysolution.jointeval[0] - dummyvalue + curvars[0]] self.ComputeSolutionComplexity(solution,othersolvedvars,curvars) solutions.append((solution,curvars[0])) else: log.warn('not all equations zero, so %s vars are not collinear', curvars) if len(solutions) > 0: tree = self.AddSolution(solutions,raweqns,curvars[0:1],othersolvedvars+curvars[1:2],solsubs+self.Variable(curvars[1]).subs,endbranchtree,currentcases=currentcases, currentcasesubs=currentcasesubs, unknownvars=unknownvars) if tree is not None: return [AST.SolverFreeParameter(curvars[1].name, tree)] else: log.warn('almost found two axes but num solutions was: %r', [s.numsolutions()==1 for s in dummysolutions]) for var0,var1,raweqns,complexity in curvarsubssol: try: rawsolutions=self.SolvePrismaticHingePairVariables(raweqns,var0,var1,othersolvedvars,unknownvars=curvars+unknownvars) for solution in rawsolutions: #solution.subs(freevarinvsubs) self.ComputeSolutionComplexity(solution,othersolvedvars,curvars) solutions.append((solution,Symbol(solution.jointname))) if len(rawsolutions) > 0: # solving a pair is rare, so any solution will do break except self.CannotSolveError: pass for var0,var1,raweqns,complexity in curvarsubssol: try: rawsolutions=self.SolvePairVariables(raweqns,var0,var1,othersolvedvars,unknownvars=curvars+unknownvars) except self.CannotSolveError as e: log.debug(e) # try: # rawsolutions=self.SolvePrismaticHingePairVariables(raweqns,var0,var1,othersolvedvars,unknownvars=curvars+unknownvars) # except self.CannotSolveError as e: # log.debug(e) rawsolutions = [] for solution in rawsolutions: #solution.subs(freevarinvsubs) try: self.ComputeSolutionComplexity(solution,othersolvedvars,curvars) solutions.append((solution,Symbol(solution.jointname))) except self.CannotSolveError as e: log.warn(u'equation failed to compute solution complexity: %s', solution.jointeval) if len(rawsolutions) > 0: # solving a pair is rare, so any solution will do break # take the least complex solution and go on if len(solutions) > 0: return self.AddSolution(solutions,AllEquations,curvars,othersolvedvars,solsubs,endbranchtree,currentcases=currentcases, currentcasesubs=currentcasesubs, unknownvars=unknownvars) # test with higher degrees, necessary? for curvar in curvars: othervars = unknownvars+[var for var in curvars if var != curvar] raweqns = [] for e in AllEquations: if (len(othervars) == 0 or not e.has(*othervars)) and e.has(curvar): eq = e.subs(self.freevarsubs+solsubs) if self.CheckExpressionUnique(raweqns,eq): raweqns.append(eq) for raweqn in raweqns: try: log.debug('testing with higher degrees') solution=self.solveHighDegreeEquationsHalfAngle([raweqn],self.Variable(curvar)) self.ComputeSolutionComplexity(solution,othersolvedvars,curvars) solutions.append((solution,curvar)) except self.CannotSolveError: pass if len(solutions) > 0: return self.AddSolution(solutions,AllEquations,curvars,othersolvedvars,solsubs,endbranchtree,currentcases=currentcases, currentcasesubs=currentcasesubs, unknownvars=unknownvars) # solve with all 3 variables together? # htvars = [self.Variable(varsym).htvar for varsym in curvars] # reducedeqs = [] # for eq in AllEquations: # if eq.has(*curvars): # num, denom, htvarsubsinv = self.ConvertSinCosEquationToHalfTan(eq, curvars) # reducedeqs.append(Poly(num, *htvars)) # # only guess if final joint to be solved, or there exists current cases and at least one joint has been solved already. # don't want to start guessing when no joints have been solved yet, this is an indication of bad equations if canguessvars and len(othersolvedvars)+len(curvars) == len(self.freejointvars)+len(self._solvejointvars) and (len(curvars) == 1 or (len(curvars) < len(self._solvejointvars) and currentcases is not None and len(currentcases) > 0)): # only estimate when deep in the hierarchy, do not want the guess to be executed all the time # perhaps there's a degree of freedom that is not trivial to compute? # take the highest hinge variable and set it log.info('trying to guess variable from %r', curvars) return self.GuessValuesAndSolveEquations(AllEquations, curvars, othersolvedvars, solsubs, endbranchtree, currentcases, unknownvars, currentcasesubs) # have got this far, so perhaps two axes are aligned? raise self.CannotSolveError('SolveAllEquations failed to find a variable to solve')
[ "def", "SolveAllEquations", "(", "self", ",", "AllEquations", ",", "curvars", ",", "othersolvedvars", ",", "solsubs", ",", "endbranchtree", ",", "currentcases", "=", "None", ",", "unknownvars", "=", "None", ",", "currentcasesubs", "=", "None", ",", "canguessvars", "=", "True", ")", ":", "self", ".", "_CheckPreemptFn", "(", "progress", "=", "0.15", "+", "(", "0.3", "-", "0.3", "*", "100", "/", "(", "self", ".", "_scopecounter", "+", "100", ")", ")", ")", "# go from 0.15 - 0.45. usually scope counters go to several hundred", "if", "len", "(", "curvars", ")", "==", "0", ":", "return", "endbranchtree", "if", "unknownvars", "is", "None", ":", "unknownvars", "=", "[", "]", "self", ".", "_scopecounter", "+=", "1", "scopecounter", "=", "int", "(", "self", ".", "_scopecounter", ")", "log", ".", "info", "(", "'depth=%d c=%d, %s %s: cases=%r'", ",", "len", "(", "currentcases", ")", "if", "currentcases", "is", "not", "None", "else", "0", ",", "self", ".", "_scopecounter", ",", "othersolvedvars", ",", "curvars", ",", "currentcases", ")", "solsubs", "=", "solsubs", "[", ":", "]", "freevarinvsubs", "=", "[", "(", "f", "[", "1", "]", ",", "f", "[", "0", "]", ")", "for", "f", "in", "self", ".", "freevarsubs", "]", "solinvsubs", "=", "[", "(", "f", "[", "1", "]", ",", "f", "[", "0", "]", ")", "for", "f", "in", "solsubs", "]", "# single variable solutions", "solutions", "=", "[", "]", "for", "curvar", "in", "curvars", ":", "othervars", "=", "unknownvars", "+", "[", "var", "for", "var", "in", "curvars", "if", "var", "!=", "curvar", "]", "curvarsym", "=", "self", ".", "Variable", "(", "curvar", ")", "raweqns", "=", "[", "]", "for", "e", "in", "AllEquations", ":", "if", "(", "len", "(", "othervars", ")", "==", "0", "or", "not", "e", ".", "has", "(", "*", "othervars", ")", ")", "and", "e", ".", "has", "(", "curvar", ",", "curvarsym", ".", "htvar", ",", "curvarsym", ".", "cvar", ",", "curvarsym", ".", "svar", ")", ":", "eq", "=", "e", ".", "subs", "(", "self", ".", "freevarsubs", "+", "solsubs", ")", "if", "self", ".", "CheckExpressionUnique", "(", "raweqns", ",", "eq", ")", ":", "raweqns", ".", "append", "(", "eq", ")", "if", "len", "(", "raweqns", ")", ">", "0", ":", "try", ":", "rawsolutions", "=", "self", ".", "solveSingleVariable", "(", "self", ".", "sortComplexity", "(", "raweqns", ")", ",", "curvar", ",", "othersolvedvars", ",", "unknownvars", "=", "curvars", "+", "unknownvars", ")", "for", "solution", "in", "rawsolutions", ":", "self", ".", "ComputeSolutionComplexity", "(", "solution", ",", "othersolvedvars", ",", "curvars", ")", "if", "solution", ".", "numsolutions", "(", ")", ">", "0", ":", "solutions", ".", "append", "(", "(", "solution", ",", "curvar", ")", ")", "else", ":", "log", ".", "warn", "(", "'solution did not have any equations'", ")", "except", "self", ".", "CannotSolveError", ":", "pass", "# only return here if a solution was found that perfectly determines the unknown", "# otherwise, the pairwise solver could come up with something..", "# There is still a problem with this: (bertold robot)", "# Sometimes an equation like atan2(y,x) evaluates to atan2(0,0) during runtime.", "# This cannot be known at compile time, so the equation is selected and any other possibilities are rejected.", "# In the bertold robot case, the next possibility is a pair-wise solution involving two variables", "if", "any", "(", "[", "s", "[", "0", "]", ".", "numsolutions", "(", ")", "==", "1", "for", "s", "in", "solutions", "]", ")", ":", "return", "self", ".", "AddSolution", "(", "solutions", ",", "AllEquations", ",", "curvars", ",", "othersolvedvars", ",", "solsubs", ",", "endbranchtree", ",", "currentcases", "=", "currentcases", ",", "currentcasesubs", "=", "currentcasesubs", ",", "unknownvars", "=", "unknownvars", ")", "curvarsubssol", "=", "[", "]", "for", "var0", ",", "var1", "in", "combinations", "(", "curvars", ",", "2", ")", ":", "othervars", "=", "unknownvars", "+", "[", "var", "for", "var", "in", "curvars", "if", "var", "!=", "var0", "and", "var", "!=", "var1", "]", "raweqns", "=", "[", "]", "complexity", "=", "0", "for", "e", "in", "AllEquations", ":", "if", "(", "len", "(", "othervars", ")", "==", "0", "or", "not", "e", ".", "has", "(", "*", "othervars", ")", ")", "and", "e", ".", "has", "(", "var0", ",", "var1", ")", ":", "eq", "=", "e", ".", "subs", "(", "self", ".", "freevarsubs", "+", "solsubs", ")", "if", "self", ".", "CheckExpressionUnique", "(", "raweqns", ",", "eq", ")", ":", "raweqns", ".", "append", "(", "eq", ")", "complexity", "+=", "self", ".", "codeComplexity", "(", "eq", ")", "if", "len", "(", "raweqns", ")", ">", "1", ":", "curvarsubssol", ".", "append", "(", "(", "var0", ",", "var1", ",", "raweqns", ",", "complexity", ")", ")", "curvarsubssol", ".", "sort", "(", "key", "=", "lambda", "e", ":", "e", "[", "3", "]", ")", "if", "len", "(", "curvars", ")", "==", "2", "and", "self", ".", "IsHinge", "(", "curvars", "[", "0", "]", ".", "name", ")", "and", "self", ".", "IsHinge", "(", "curvars", "[", "1", "]", ".", "name", ")", "and", "len", "(", "curvarsubssol", ")", ">", "0", ":", "# there's only two variables left, it might be the case that the axes are aligning and the two variables are dependent on each other", "# note that the axes's anchors also have to be along the direction!", "var0", ",", "var1", ",", "raweqns", ",", "complexity", "=", "curvarsubssol", "[", "0", "]", "dummyvar", "=", "Symbol", "(", "'dummy'", ")", "dummyvalue", "=", "var0", "+", "var1", "NewEquations", "=", "[", "]", "NewEquationsAll", "=", "[", "]", "hasExtraConstraints", "=", "False", "for", "eq", "in", "raweqns", ":", "neweq", "=", "self", ".", "trigsimp", "(", "eq", ".", "subs", "(", "var0", ",", "dummyvar", "-", "var1", ")", ".", "expand", "(", "trig", "=", "True", ")", ",", "curvars", ")", "eq", "=", "neweq", ".", "subs", "(", "self", ".", "freevarsubs", "+", "solsubs", ")", "if", "self", ".", "CheckExpressionUnique", "(", "NewEquationsAll", ",", "eq", ")", ":", "NewEquationsAll", ".", "append", "(", "eq", ")", "if", "neweq", ".", "has", "(", "dummyvar", ")", ":", "if", "neweq", ".", "has", "(", "*", "(", "othervars", "+", "curvars", ")", ")", ":", "hasExtraConstraints", "=", "True", "#break # don't know why breaking here... sometimes equations can be too complex but that doesn't mean variables are not dependent", "else", ":", "eq", "=", "neweq", ".", "subs", "(", "self", ".", "freevarsubs", "+", "solsubs", ")", "if", "self", ".", "CheckExpressionUnique", "(", "NewEquations", ",", "eq", ")", ":", "NewEquations", ".", "append", "(", "eq", ")", "if", "len", "(", "NewEquations", ")", "<", "2", "and", "hasExtraConstraints", ":", "# try subtracting", "NewEquations", "=", "[", "]", "NewEquationsAll", "=", "[", "]", "hasExtraConstraints", "=", "False", "dummyvalue", "=", "var0", "-", "var1", "for", "eq", "in", "raweqns", ":", "neweq", "=", "self", ".", "trigsimp", "(", "eq", ".", "subs", "(", "var0", ",", "dummyvar", "+", "var1", ")", ".", "expand", "(", "trig", "=", "True", ")", ",", "curvars", ")", "eq", "=", "neweq", ".", "subs", "(", "self", ".", "freevarsubs", "+", "solsubs", ")", "if", "self", ".", "CheckExpressionUnique", "(", "NewEquationsAll", ",", "eq", ")", ":", "NewEquationsAll", ".", "append", "(", "eq", ")", "if", "neweq", ".", "has", "(", "dummyvar", ")", ":", "if", "neweq", ".", "has", "(", "*", "(", "othervars", "+", "curvars", ")", ")", ":", "hasExtraConstraints", "=", "True", "#break # don't know why breaking here... sometimes equations can be too complex but that doesn't mean variables are not dependent", "else", ":", "eq", "=", "neweq", ".", "subs", "(", "self", ".", "freevarsubs", "+", "solsubs", ")", "if", "self", ".", "CheckExpressionUnique", "(", "NewEquations", ",", "eq", ")", ":", "NewEquations", ".", "append", "(", "eq", ")", "if", "len", "(", "NewEquations", ")", ">=", "2", ":", "dummysolutions", "=", "[", "]", "try", ":", "rawsolutions", "=", "self", ".", "solveSingleVariable", "(", "NewEquations", ",", "dummyvar", ",", "othersolvedvars", ",", "unknownvars", "=", "curvars", "+", "unknownvars", ")", "for", "solution", "in", "rawsolutions", ":", "self", ".", "ComputeSolutionComplexity", "(", "solution", ",", "othersolvedvars", ",", "curvars", ")", "dummysolutions", ".", "append", "(", "solution", ")", "except", "self", ".", "CannotSolveError", ":", "pass", "if", "any", "(", "[", "s", ".", "numsolutions", "(", ")", "==", "1", "for", "s", "in", "dummysolutions", "]", ")", ":", "# two axes are aligning, so modify the solutions to reflect the original variables and add a free variable", "log", ".", "info", "(", "'found two aligning axes %s: %r'", ",", "dummyvalue", ",", "NewEquations", ")", "solutions", "=", "[", "]", "for", "dummysolution", "in", "dummysolutions", ":", "if", "dummysolution", ".", "numsolutions", "(", ")", "!=", "1", ":", "continue", "if", "dummysolution", ".", "jointevalsin", "is", "not", "None", "or", "dummysolution", ".", "jointevalcos", "is", "not", "None", ":", "log", ".", "warn", "(", "'dummy solution should not have sin/cos parts!'", ")", "sindummyvarsols", "=", "[", "]", "cosdummyvarsols", "=", "[", "]", "for", "eq", "in", "NewEquations", ":", "sols", "=", "solve", "(", "eq", ",", "sin", "(", "dummyvar", ")", ")", "sindummyvarsols", "+=", "sols", "sols", "=", "solve", "(", "eq", ",", "cos", "(", "dummyvar", ")", ")", "cosdummyvarsols", "+=", "sols", "# double check with NewEquationsAll that everything evluates to 0", "newsubs", "=", "[", "(", "value", ",", "sin", "(", "dummyvar", ")", ")", "for", "value", "in", "sindummyvarsols", "]", "+", "[", "(", "value", ",", "cos", "(", "dummyvar", ")", ")", "for", "value", "in", "cosdummyvarsols", "]", "+", "[", "(", "-", "value", ",", "-", "sin", "(", "dummyvar", ")", ")", "for", "value", "in", "sindummyvarsols", "]", "+", "[", "(", "-", "value", ",", "-", "cos", "(", "dummyvar", ")", ")", "for", "value", "in", "cosdummyvarsols", "]", "allzeros", "=", "True", "for", "eq", "in", "NewEquationsAll", ":", "if", "trigsimp", "(", "eq", ".", "subs", "(", "newsubs", ")", ")", "!=", "S", ".", "Zero", ":", "allzeros", "=", "False", "break", "if", "allzeros", ":", "solution", "=", "AST", ".", "SolverSolution", "(", "curvars", "[", "0", "]", ".", "name", ",", "isHinge", "=", "self", ".", "IsHinge", "(", "curvars", "[", "0", "]", ".", "name", ")", ")", "solution", ".", "jointeval", "=", "[", "dummysolution", ".", "jointeval", "[", "0", "]", "-", "dummyvalue", "+", "curvars", "[", "0", "]", "]", "self", ".", "ComputeSolutionComplexity", "(", "solution", ",", "othersolvedvars", ",", "curvars", ")", "solutions", ".", "append", "(", "(", "solution", ",", "curvars", "[", "0", "]", ")", ")", "else", ":", "log", ".", "warn", "(", "'not all equations zero, so %s vars are not collinear'", ",", "curvars", ")", "if", "len", "(", "solutions", ")", ">", "0", ":", "tree", "=", "self", ".", "AddSolution", "(", "solutions", ",", "raweqns", ",", "curvars", "[", "0", ":", "1", "]", ",", "othersolvedvars", "+", "curvars", "[", "1", ":", "2", "]", ",", "solsubs", "+", "self", ".", "Variable", "(", "curvars", "[", "1", "]", ")", ".", "subs", ",", "endbranchtree", ",", "currentcases", "=", "currentcases", ",", "currentcasesubs", "=", "currentcasesubs", ",", "unknownvars", "=", "unknownvars", ")", "if", "tree", "is", "not", "None", ":", "return", "[", "AST", ".", "SolverFreeParameter", "(", "curvars", "[", "1", "]", ".", "name", ",", "tree", ")", "]", "else", ":", "log", ".", "warn", "(", "'almost found two axes but num solutions was: %r'", ",", "[", "s", ".", "numsolutions", "(", ")", "==", "1", "for", "s", "in", "dummysolutions", "]", ")", "for", "var0", ",", "var1", ",", "raweqns", ",", "complexity", "in", "curvarsubssol", ":", "try", ":", "rawsolutions", "=", "self", ".", "SolvePrismaticHingePairVariables", "(", "raweqns", ",", "var0", ",", "var1", ",", "othersolvedvars", ",", "unknownvars", "=", "curvars", "+", "unknownvars", ")", "for", "solution", "in", "rawsolutions", ":", "#solution.subs(freevarinvsubs)", "self", ".", "ComputeSolutionComplexity", "(", "solution", ",", "othersolvedvars", ",", "curvars", ")", "solutions", ".", "append", "(", "(", "solution", ",", "Symbol", "(", "solution", ".", "jointname", ")", ")", ")", "if", "len", "(", "rawsolutions", ")", ">", "0", ":", "# solving a pair is rare, so any solution will do", "break", "except", "self", ".", "CannotSolveError", ":", "pass", "for", "var0", ",", "var1", ",", "raweqns", ",", "complexity", "in", "curvarsubssol", ":", "try", ":", "rawsolutions", "=", "self", ".", "SolvePairVariables", "(", "raweqns", ",", "var0", ",", "var1", ",", "othersolvedvars", ",", "unknownvars", "=", "curvars", "+", "unknownvars", ")", "except", "self", ".", "CannotSolveError", "as", "e", ":", "log", ".", "debug", "(", "e", ")", "# try:", "# rawsolutions=self.SolvePrismaticHingePairVariables(raweqns,var0,var1,othersolvedvars,unknownvars=curvars+unknownvars)", "# except self.CannotSolveError as e:", "# log.debug(e)", "rawsolutions", "=", "[", "]", "for", "solution", "in", "rawsolutions", ":", "#solution.subs(freevarinvsubs)", "try", ":", "self", ".", "ComputeSolutionComplexity", "(", "solution", ",", "othersolvedvars", ",", "curvars", ")", "solutions", ".", "append", "(", "(", "solution", ",", "Symbol", "(", "solution", ".", "jointname", ")", ")", ")", "except", "self", ".", "CannotSolveError", "as", "e", ":", "log", ".", "warn", "(", "u'equation failed to compute solution complexity: %s'", ",", "solution", ".", "jointeval", ")", "if", "len", "(", "rawsolutions", ")", ">", "0", ":", "# solving a pair is rare, so any solution will do", "break", "# take the least complex solution and go on", "if", "len", "(", "solutions", ")", ">", "0", ":", "return", "self", ".", "AddSolution", "(", "solutions", ",", "AllEquations", ",", "curvars", ",", "othersolvedvars", ",", "solsubs", ",", "endbranchtree", ",", "currentcases", "=", "currentcases", ",", "currentcasesubs", "=", "currentcasesubs", ",", "unknownvars", "=", "unknownvars", ")", "# test with higher degrees, necessary?", "for", "curvar", "in", "curvars", ":", "othervars", "=", "unknownvars", "+", "[", "var", "for", "var", "in", "curvars", "if", "var", "!=", "curvar", "]", "raweqns", "=", "[", "]", "for", "e", "in", "AllEquations", ":", "if", "(", "len", "(", "othervars", ")", "==", "0", "or", "not", "e", ".", "has", "(", "*", "othervars", ")", ")", "and", "e", ".", "has", "(", "curvar", ")", ":", "eq", "=", "e", ".", "subs", "(", "self", ".", "freevarsubs", "+", "solsubs", ")", "if", "self", ".", "CheckExpressionUnique", "(", "raweqns", ",", "eq", ")", ":", "raweqns", ".", "append", "(", "eq", ")", "for", "raweqn", "in", "raweqns", ":", "try", ":", "log", ".", "debug", "(", "'testing with higher degrees'", ")", "solution", "=", "self", ".", "solveHighDegreeEquationsHalfAngle", "(", "[", "raweqn", "]", ",", "self", ".", "Variable", "(", "curvar", ")", ")", "self", ".", "ComputeSolutionComplexity", "(", "solution", ",", "othersolvedvars", ",", "curvars", ")", "solutions", ".", "append", "(", "(", "solution", ",", "curvar", ")", ")", "except", "self", ".", "CannotSolveError", ":", "pass", "if", "len", "(", "solutions", ")", ">", "0", ":", "return", "self", ".", "AddSolution", "(", "solutions", ",", "AllEquations", ",", "curvars", ",", "othersolvedvars", ",", "solsubs", ",", "endbranchtree", ",", "currentcases", "=", "currentcases", ",", "currentcasesubs", "=", "currentcasesubs", ",", "unknownvars", "=", "unknownvars", ")", "# solve with all 3 variables together?", "# htvars = [self.Variable(varsym).htvar for varsym in curvars]", "# reducedeqs = []", "# for eq in AllEquations:", "# if eq.has(*curvars):", "# num, denom, htvarsubsinv = self.ConvertSinCosEquationToHalfTan(eq, curvars)", "# reducedeqs.append(Poly(num, *htvars))", "# ", "# only guess if final joint to be solved, or there exists current cases and at least one joint has been solved already.", "# don't want to start guessing when no joints have been solved yet, this is an indication of bad equations", "if", "canguessvars", "and", "len", "(", "othersolvedvars", ")", "+", "len", "(", "curvars", ")", "==", "len", "(", "self", ".", "freejointvars", ")", "+", "len", "(", "self", ".", "_solvejointvars", ")", "and", "(", "len", "(", "curvars", ")", "==", "1", "or", "(", "len", "(", "curvars", ")", "<", "len", "(", "self", ".", "_solvejointvars", ")", "and", "currentcases", "is", "not", "None", "and", "len", "(", "currentcases", ")", ">", "0", ")", ")", ":", "# only estimate when deep in the hierarchy, do not want the guess to be executed all the time", "# perhaps there's a degree of freedom that is not trivial to compute?", "# take the highest hinge variable and set it", "log", ".", "info", "(", "'trying to guess variable from %r'", ",", "curvars", ")", "return", "self", ".", "GuessValuesAndSolveEquations", "(", "AllEquations", ",", "curvars", ",", "othersolvedvars", ",", "solsubs", ",", "endbranchtree", ",", "currentcases", ",", "unknownvars", ",", "currentcasesubs", ")", "# have got this far, so perhaps two axes are aligned?", "raise", "self", ".", "CannotSolveError", "(", "'SolveAllEquations failed to find a variable to solve'", ")" ]
https://github.com/rdiankov/openrave/blob/d1a23023fd4b58f077d2ca949ceaf1b91f3f13d7/python/ikfast.py#L6762-L6990
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/telemetry/telemetry/core/platform/__init__.py
python
Platform.GetOSVersionName
(self)
return self._platform_backend.GetOSVersionName()
Returns a logically sortable, string-like description of the Platform OS version. Examples: VISTA, WIN7, LION, MOUNTAINLION
Returns a logically sortable, string-like description of the Platform OS version.
[ "Returns", "a", "logically", "sortable", "string", "-", "like", "description", "of", "the", "Platform", "OS", "version", "." ]
def GetOSVersionName(self): """Returns a logically sortable, string-like description of the Platform OS version. Examples: VISTA, WIN7, LION, MOUNTAINLION""" return self._platform_backend.GetOSVersionName()
[ "def", "GetOSVersionName", "(", "self", ")", ":", "return", "self", ".", "_platform_backend", ".", "GetOSVersionName", "(", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/telemetry/telemetry/core/platform/__init__.py#L82-L87
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/boost_1_66_0/tools/build/src/build/configure.py
python
log_component_configuration
(component, message)
Report something about component configuration that the user should better know.
Report something about component configuration that the user should better know.
[ "Report", "something", "about", "component", "configuration", "that", "the", "user", "should", "better", "know", "." ]
def log_component_configuration(component, message): """Report something about component configuration that the user should better know.""" assert isinstance(component, basestring) assert isinstance(message, basestring) __component_logs.setdefault(component, []).append(message)
[ "def", "log_component_configuration", "(", "component", ",", "message", ")", ":", "assert", "isinstance", "(", "component", ",", "basestring", ")", "assert", "isinstance", "(", "message", ",", "basestring", ")", "__component_logs", ".", "setdefault", "(", "component", ",", "[", "]", ")", ".", "append", "(", "message", ")" ]
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/boost_1_66_0/tools/build/src/build/configure.py#L52-L56
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/lookup_ops.py
python
TableInitializerBase.value_dtype
(self)
return self._value_dtype
The expected table value dtype.
The expected table value dtype.
[ "The", "expected", "table", "value", "dtype", "." ]
def value_dtype(self): """The expected table value dtype.""" return self._value_dtype
[ "def", "value_dtype", "(", "self", ")", ":", "return", "self", ".", "_value_dtype" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/lookup_ops.py#L394-L396
panda3d/panda3d
833ad89ebad58395d0af0b7ec08538e5e4308265
direct/src/showbase/Loader.py
python
Loader.loadModelOnce
(self, modelPath)
return self.loadModel(modelPath, noCache = False)
modelPath is a string. Attempt to load a model from modelPool, if not present then attempt to load it from disk. Return a nodepath to the model if successful or None otherwise
modelPath is a string.
[ "modelPath", "is", "a", "string", "." ]
def loadModelOnce(self, modelPath): """ modelPath is a string. Attempt to load a model from modelPool, if not present then attempt to load it from disk. Return a nodepath to the model if successful or None otherwise """ if __debug__: warnings.warn("loader.loadModelOnce() is deprecated; use loader.loadModel() instead.", DeprecationWarning, stacklevel=2) return self.loadModel(modelPath, noCache = False)
[ "def", "loadModelOnce", "(", "self", ",", "modelPath", ")", ":", "if", "__debug__", ":", "warnings", ".", "warn", "(", "\"loader.loadModelOnce() is deprecated; use loader.loadModel() instead.\"", ",", "DeprecationWarning", ",", "stacklevel", "=", "2", ")", "return", "self", ".", "loadModel", "(", "modelPath", ",", "noCache", "=", "False", ")" ]
https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/showbase/Loader.py#L313-L324
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/propgrid.py
python
PropertyGridManager.SetDescBoxHeight
(*args, **kwargs)
return _propgrid.PropertyGridManager_SetDescBoxHeight(*args, **kwargs)
SetDescBoxHeight(self, int ht, bool refresh=True)
SetDescBoxHeight(self, int ht, bool refresh=True)
[ "SetDescBoxHeight", "(", "self", "int", "ht", "bool", "refresh", "=", "True", ")" ]
def SetDescBoxHeight(*args, **kwargs): """SetDescBoxHeight(self, int ht, bool refresh=True)""" return _propgrid.PropertyGridManager_SetDescBoxHeight(*args, **kwargs)
[ "def", "SetDescBoxHeight", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PropertyGridManager_SetDescBoxHeight", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/propgrid.py#L3579-L3581
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/learn/python/learn/learn_io/pandas_io.py
python
pandas_input_fn
(x, y=None, batch_size=128, num_epochs=1, shuffle=True, queue_capacity=1000, num_threads=1, target_column='target')
return core_pandas_input_fn(x=x, y=y, batch_size=batch_size, shuffle=shuffle, num_epochs=num_epochs, queue_capacity=queue_capacity, num_threads=num_threads, target_column=target_column)
This input_fn diffs from the core version with default `shuffle`.
This input_fn diffs from the core version with default `shuffle`.
[ "This", "input_fn", "diffs", "from", "the", "core", "version", "with", "default", "shuffle", "." ]
def pandas_input_fn(x, y=None, batch_size=128, num_epochs=1, shuffle=True, queue_capacity=1000, num_threads=1, target_column='target'): """This input_fn diffs from the core version with default `shuffle`.""" return core_pandas_input_fn(x=x, y=y, batch_size=batch_size, shuffle=shuffle, num_epochs=num_epochs, queue_capacity=queue_capacity, num_threads=num_threads, target_column=target_column)
[ "def", "pandas_input_fn", "(", "x", ",", "y", "=", "None", ",", "batch_size", "=", "128", ",", "num_epochs", "=", "1", ",", "shuffle", "=", "True", ",", "queue_capacity", "=", "1000", ",", "num_threads", "=", "1", ",", "target_column", "=", "'target'", ")", ":", "return", "core_pandas_input_fn", "(", "x", "=", "x", ",", "y", "=", "y", ",", "batch_size", "=", "batch_size", ",", "shuffle", "=", "shuffle", ",", "num_epochs", "=", "num_epochs", ",", "queue_capacity", "=", "queue_capacity", ",", "num_threads", "=", "num_threads", ",", "target_column", "=", "target_column", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/learn/python/learn/learn_io/pandas_io.py#L50-L66
google/certificate-transparency
2588562fd306a447958471b6f06c1069619c1641
python/ct/crypto/verify_rsa.py
python
RsaVerifier.verify
(self, signature_input, signature)
return True
Verifies the signature was created by the owner of the public key. Args: - signature_input: The data that was originally signed. - signature: An RSA SHA256 signature. Returns: - True if the signature verifies. Raises: - error.SignatureError: If the signature fails verification.
Verifies the signature was created by the owner of the public key.
[ "Verifies", "the", "signature", "was", "created", "by", "the", "owner", "of", "the", "public", "key", "." ]
def verify(self, signature_input, signature): """Verifies the signature was created by the owner of the public key. Args: - signature_input: The data that was originally signed. - signature: An RSA SHA256 signature. Returns: - True if the signature verifies. Raises: - error.SignatureError: If the signature fails verification. """ try: self.__key.verify(signature, signature_input, padding.PKCS1v15(), hashes.SHA256()) except cryptography.exceptions.InvalidSignature: raise error.SignatureError("Signature did not verify: %s" % signature.encode("hex")) return True
[ "def", "verify", "(", "self", ",", "signature_input", ",", "signature", ")", ":", "try", ":", "self", ".", "__key", ".", "verify", "(", "signature", ",", "signature_input", ",", "padding", ".", "PKCS1v15", "(", ")", ",", "hashes", ".", "SHA256", "(", ")", ")", "except", "cryptography", ".", "exceptions", ".", "InvalidSignature", ":", "raise", "error", ".", "SignatureError", "(", "\"Signature did not verify: %s\"", "%", "signature", ".", "encode", "(", "\"hex\"", ")", ")", "return", "True" ]
https://github.com/google/certificate-transparency/blob/2588562fd306a447958471b6f06c1069619c1641/python/ct/crypto/verify_rsa.py#L50-L70
hfinkel/llvm-project-cxxjit
91084ef018240bbb8e24235ff5cd8c355a9c1a1e
llvm/examples/Kaleidoscope/MCJIT/complete/genk-timing.py
python
TimingScriptGenerator.writeTimingCall
(self, filename, numFuncs, funcsCalled, totalCalls)
Echo some comments and invoke both versions of toy
Echo some comments and invoke both versions of toy
[ "Echo", "some", "comments", "and", "invoke", "both", "versions", "of", "toy" ]
def writeTimingCall(self, filename, numFuncs, funcsCalled, totalCalls): """Echo some comments and invoke both versions of toy""" rootname = filename if '.' in filename: rootname = filename[:filename.rfind('.')] self.shfile.write("echo \"%s: Calls %d of %d functions, %d total\" >> %s\n" % (filename, funcsCalled, numFuncs, totalCalls, self.timeFile)) self.shfile.write("echo \"\" >> %s\n" % self.timeFile) self.shfile.write("echo \"With MCJIT (original)\" >> %s\n" % self.timeFile) self.shfile.write("/usr/bin/time -f \"Command %C\\n\\tuser time: %U s\\n\\tsytem time: %S s\\n\\tmax set: %M kb\"") self.shfile.write(" -o %s -a " % self.timeFile) self.shfile.write("./toy -suppress-prompts -use-mcjit=true -enable-lazy-compilation=false < %s > %s-mcjit.out 2> %s-mcjit.err\n" % (filename, rootname, rootname)) self.shfile.write("echo \"\" >> %s\n" % self.timeFile) self.shfile.write("echo \"With MCJIT (lazy)\" >> %s\n" % self.timeFile) self.shfile.write("/usr/bin/time -f \"Command %C\\n\\tuser time: %U s\\n\\tsytem time: %S s\\n\\tmax set: %M kb\"") self.shfile.write(" -o %s -a " % self.timeFile) self.shfile.write("./toy -suppress-prompts -use-mcjit=true -enable-lazy-compilation=true < %s > %s-mcjit-lazy.out 2> %s-mcjit-lazy.err\n" % (filename, rootname, rootname)) self.shfile.write("echo \"\" >> %s\n" % self.timeFile) self.shfile.write("echo \"With JIT\" >> %s\n" % self.timeFile) self.shfile.write("/usr/bin/time -f \"Command %C\\n\\tuser time: %U s\\n\\tsytem time: %S s\\n\\tmax set: %M kb\"") self.shfile.write(" -o %s -a " % self.timeFile) self.shfile.write("./toy -suppress-prompts -use-mcjit=false < %s > %s-jit.out 2> %s-jit.err\n" % (filename, rootname, rootname)) self.shfile.write("echo \"\" >> %s\n" % self.timeFile) self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
[ "def", "writeTimingCall", "(", "self", ",", "filename", ",", "numFuncs", ",", "funcsCalled", ",", "totalCalls", ")", ":", "rootname", "=", "filename", "if", "'.'", "in", "filename", ":", "rootname", "=", "filename", "[", ":", "filename", ".", "rfind", "(", "'.'", ")", "]", "self", ".", "shfile", ".", "write", "(", "\"echo \\\"%s: Calls %d of %d functions, %d total\\\" >> %s\\n\"", "%", "(", "filename", ",", "funcsCalled", ",", "numFuncs", ",", "totalCalls", ",", "self", ".", "timeFile", ")", ")", "self", ".", "shfile", ".", "write", "(", "\"echo \\\"\\\" >> %s\\n\"", "%", "self", ".", "timeFile", ")", "self", ".", "shfile", ".", "write", "(", "\"echo \\\"With MCJIT (original)\\\" >> %s\\n\"", "%", "self", ".", "timeFile", ")", "self", ".", "shfile", ".", "write", "(", "\"/usr/bin/time -f \\\"Command %C\\\\n\\\\tuser time: %U s\\\\n\\\\tsytem time: %S s\\\\n\\\\tmax set: %M kb\\\"\"", ")", "self", ".", "shfile", ".", "write", "(", "\" -o %s -a \"", "%", "self", ".", "timeFile", ")", "self", ".", "shfile", ".", "write", "(", "\"./toy -suppress-prompts -use-mcjit=true -enable-lazy-compilation=false < %s > %s-mcjit.out 2> %s-mcjit.err\\n\"", "%", "(", "filename", ",", "rootname", ",", "rootname", ")", ")", "self", ".", "shfile", ".", "write", "(", "\"echo \\\"\\\" >> %s\\n\"", "%", "self", ".", "timeFile", ")", "self", ".", "shfile", ".", "write", "(", "\"echo \\\"With MCJIT (lazy)\\\" >> %s\\n\"", "%", "self", ".", "timeFile", ")", "self", ".", "shfile", ".", "write", "(", "\"/usr/bin/time -f \\\"Command %C\\\\n\\\\tuser time: %U s\\\\n\\\\tsytem time: %S s\\\\n\\\\tmax set: %M kb\\\"\"", ")", "self", ".", "shfile", ".", "write", "(", "\" -o %s -a \"", "%", "self", ".", "timeFile", ")", "self", ".", "shfile", ".", "write", "(", "\"./toy -suppress-prompts -use-mcjit=true -enable-lazy-compilation=true < %s > %s-mcjit-lazy.out 2> %s-mcjit-lazy.err\\n\"", "%", "(", "filename", ",", "rootname", ",", "rootname", ")", ")", "self", ".", "shfile", ".", "write", "(", "\"echo \\\"\\\" >> %s\\n\"", "%", "self", ".", "timeFile", ")", "self", ".", "shfile", ".", "write", "(", "\"echo \\\"With JIT\\\" >> %s\\n\"", "%", "self", ".", "timeFile", ")", "self", ".", "shfile", ".", "write", "(", "\"/usr/bin/time -f \\\"Command %C\\\\n\\\\tuser time: %U s\\\\n\\\\tsytem time: %S s\\\\n\\\\tmax set: %M kb\\\"\"", ")", "self", ".", "shfile", ".", "write", "(", "\" -o %s -a \"", "%", "self", ".", "timeFile", ")", "self", ".", "shfile", ".", "write", "(", "\"./toy -suppress-prompts -use-mcjit=false < %s > %s-jit.out 2> %s-jit.err\\n\"", "%", "(", "filename", ",", "rootname", ",", "rootname", ")", ")", "self", ".", "shfile", ".", "write", "(", "\"echo \\\"\\\" >> %s\\n\"", "%", "self", ".", "timeFile", ")", "self", ".", "shfile", ".", "write", "(", "\"echo \\\"\\\" >> %s\\n\"", "%", "self", ".", "timeFile", ")" ]
https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/llvm/examples/Kaleidoscope/MCJIT/complete/genk-timing.py#L15-L37
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/eager/backprop.py
python
implicit_val_and_grad
(f)
return grad_fn
Returns a function which differentiates f with respect to variables. The wrapped function returns the value and the gradient of f when called with the same arguments. The gradient is with respect to all trainable TFE variables accessed by `f`. This function is useful when the exact set of variables to differentiate with is not known ahead of time. Example: ```python dense_layer = tf.compat.v1.layers.Dense(1) def loss(x, y): return tf.reduce_sum(tf.square(dense_layer(x) - y)) # Obtain the gradient function. val_grad_fn = tfe.implicit_value_and_gradients(loss) # Invoke the gradient function with concrete values of x and y. x = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) y = tf.constant([[10.0], [20.0]]) value, grads_and_vars = val_grad_fn(x, y) print('Value of loss: %s' % value) # Apply the gradients to Variables. optimizer = tf.compat.v1.train.GradientDescentOptimizer(0.1) optimizer.apply_gradients(grads_and_vars) ``` Args: f: function to be differentiated. If `f` returns a scalar, this scalar will be differentiated. If `f` returns a tensor or list of tensors, by default a scalar will be computed by adding all their values to produce a single scalar. Returns: A function which, when called, returns a tuple pair. Its first element is the value to which the function evaluates. Its second element is list of (gradient, variable) pairs. Raises: ValueError: if `f` returns None.
Returns a function which differentiates f with respect to variables.
[ "Returns", "a", "function", "which", "differentiates", "f", "with", "respect", "to", "variables", "." ]
def implicit_val_and_grad(f): """Returns a function which differentiates f with respect to variables. The wrapped function returns the value and the gradient of f when called with the same arguments. The gradient is with respect to all trainable TFE variables accessed by `f`. This function is useful when the exact set of variables to differentiate with is not known ahead of time. Example: ```python dense_layer = tf.compat.v1.layers.Dense(1) def loss(x, y): return tf.reduce_sum(tf.square(dense_layer(x) - y)) # Obtain the gradient function. val_grad_fn = tfe.implicit_value_and_gradients(loss) # Invoke the gradient function with concrete values of x and y. x = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) y = tf.constant([[10.0], [20.0]]) value, grads_and_vars = val_grad_fn(x, y) print('Value of loss: %s' % value) # Apply the gradients to Variables. optimizer = tf.compat.v1.train.GradientDescentOptimizer(0.1) optimizer.apply_gradients(grads_and_vars) ``` Args: f: function to be differentiated. If `f` returns a scalar, this scalar will be differentiated. If `f` returns a tensor or list of tensors, by default a scalar will be computed by adding all their values to produce a single scalar. Returns: A function which, when called, returns a tuple pair. Its first element is the value to which the function evaluates. Its second element is list of (gradient, variable) pairs. Raises: ValueError: if `f` returns None. """ # TODO(cais): Remove calls to tf.constant() once the gradients functions # accept lists and np.ndarrays. def grad_fn(*args, **kwds): """Computes the gradient of the wrapped function.""" this_tape = tape.push_new_tape() try: end_node = f(*args, **kwds) if end_node is None: raise ValueError("Cannot differentiate a function that returns None; " "did you forget to return a value from {}?".format( f.__name__)) finally: tape.pop_tape(this_tape) # Note: variables are returned in construction order. This ensures unique # order across executions. variables = this_tape.watched_variables() if not variables: raise ValueError("No trainable variables were accessed while the " "function was being computed.") sources = [v.handle for v in variables] grad = imperative_grad.imperative_grad(this_tape, nest.flatten(end_node), sources) return end_node, list(zip(grad, variables)) return grad_fn
[ "def", "implicit_val_and_grad", "(", "f", ")", ":", "# TODO(cais): Remove calls to tf.constant() once the gradients functions", "# accept lists and np.ndarrays.", "def", "grad_fn", "(", "*", "args", ",", "*", "*", "kwds", ")", ":", "\"\"\"Computes the gradient of the wrapped function.\"\"\"", "this_tape", "=", "tape", ".", "push_new_tape", "(", ")", "try", ":", "end_node", "=", "f", "(", "*", "args", ",", "*", "*", "kwds", ")", "if", "end_node", "is", "None", ":", "raise", "ValueError", "(", "\"Cannot differentiate a function that returns None; \"", "\"did you forget to return a value from {}?\"", ".", "format", "(", "f", ".", "__name__", ")", ")", "finally", ":", "tape", ".", "pop_tape", "(", "this_tape", ")", "# Note: variables are returned in construction order. This ensures unique", "# order across executions.", "variables", "=", "this_tape", ".", "watched_variables", "(", ")", "if", "not", "variables", ":", "raise", "ValueError", "(", "\"No trainable variables were accessed while the \"", "\"function was being computed.\"", ")", "sources", "=", "[", "v", ".", "handle", "for", "v", "in", "variables", "]", "grad", "=", "imperative_grad", ".", "imperative_grad", "(", "this_tape", ",", "nest", ".", "flatten", "(", "end_node", ")", ",", "sources", ")", "return", "end_node", ",", "list", "(", "zip", "(", "grad", ",", "variables", ")", ")", "return", "grad_fn" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/eager/backprop.py#L152-L223
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/Diffraction/isis_powder/routines/common.py
python
run_normalise_by_current
(ws)
return ws
Runs the Normalise By Current algorithm on the input workspace. If the workspace has no current, return it unchanged :param ws: The workspace to run normalise by current on :return: The current normalised workspace
Runs the Normalise By Current algorithm on the input workspace. If the workspace has no current, return it unchanged :param ws: The workspace to run normalise by current on :return: The current normalised workspace
[ "Runs", "the", "Normalise", "By", "Current", "algorithm", "on", "the", "input", "workspace", ".", "If", "the", "workspace", "has", "no", "current", "return", "it", "unchanged", ":", "param", "ws", ":", "The", "workspace", "to", "run", "normalise", "by", "current", "on", ":", "return", ":", "The", "current", "normalised", "workspace" ]
def run_normalise_by_current(ws): """ Runs the Normalise By Current algorithm on the input workspace. If the workspace has no current, return it unchanged :param ws: The workspace to run normalise by current on :return: The current normalised workspace """ if workspace_has_current(ws): ws = mantid.NormaliseByCurrent(InputWorkspace=ws, OutputWorkspace=ws) else: warnings.warn( "Run {} had no current. NormaliseByCurrent will not be run on it, and empty will not be subtracted". format(ws.getRunNumber())) return ws
[ "def", "run_normalise_by_current", "(", "ws", ")", ":", "if", "workspace_has_current", "(", "ws", ")", ":", "ws", "=", "mantid", ".", "NormaliseByCurrent", "(", "InputWorkspace", "=", "ws", ",", "OutputWorkspace", "=", "ws", ")", "else", ":", "warnings", ".", "warn", "(", "\"Run {} had no current. NormaliseByCurrent will not be run on it, and empty will not be subtracted\"", ".", "format", "(", "ws", ".", "getRunNumber", "(", ")", ")", ")", "return", "ws" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/Diffraction/isis_powder/routines/common.py#L444-L456
dmlc/nnvm
dab5ce8ab6adbf4edd8bd2fa89f1a99f343b6e38
python/nnvm/compiler/graph_util.py
python
infer_shape
(graph, **shape)
return input_shape, output_shape
Infer the shape given the shape of inputs. Parameters ---------- graph : Graph The graph to perform shape inference from shape : dict of str to tuple The specific input shape. Returns ------- in_shape : list of tuple Shape of inputs out_shape: list of tuple Shape of outputs
Infer the shape given the shape of inputs.
[ "Infer", "the", "shape", "given", "the", "shape", "of", "inputs", "." ]
def infer_shape(graph, **shape): """Infer the shape given the shape of inputs. Parameters ---------- graph : Graph The graph to perform shape inference from shape : dict of str to tuple The specific input shape. Returns ------- in_shape : list of tuple Shape of inputs out_shape: list of tuple Shape of outputs """ graph = graph_attr.set_shape_inputs(graph, shape) graph = graph.apply("InferShape") shape = graph.json_attr("shape") index = graph.index input_shape = [shape[index.entry_id(x)] for x in index.input_names] output_shape = [shape[index.entry_id(x)] for x in index.output_entries] return input_shape, output_shape
[ "def", "infer_shape", "(", "graph", ",", "*", "*", "shape", ")", ":", "graph", "=", "graph_attr", ".", "set_shape_inputs", "(", "graph", ",", "shape", ")", "graph", "=", "graph", ".", "apply", "(", "\"InferShape\"", ")", "shape", "=", "graph", ".", "json_attr", "(", "\"shape\"", ")", "index", "=", "graph", ".", "index", "input_shape", "=", "[", "shape", "[", "index", ".", "entry_id", "(", "x", ")", "]", "for", "x", "in", "index", ".", "input_names", "]", "output_shape", "=", "[", "shape", "[", "index", ".", "entry_id", "(", "x", ")", "]", "for", "x", "in", "index", ".", "output_entries", "]", "return", "input_shape", ",", "output_shape" ]
https://github.com/dmlc/nnvm/blob/dab5ce8ab6adbf4edd8bd2fa89f1a99f343b6e38/python/nnvm/compiler/graph_util.py#L11-L36
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
GridSizer.SetCols
(*args, **kwargs)
return _core_.GridSizer_SetCols(*args, **kwargs)
SetCols(self, int cols) Sets the number of columns in the sizer.
SetCols(self, int cols)
[ "SetCols", "(", "self", "int", "cols", ")" ]
def SetCols(*args, **kwargs): """ SetCols(self, int cols) Sets the number of columns in the sizer. """ return _core_.GridSizer_SetCols(*args, **kwargs)
[ "def", "SetCols", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "GridSizer_SetCols", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L15205-L15211
cmu-db/noisepage
79276e68fe83322f1249e8a8be96bd63c583ae56
build-support/cpplint.py
python
CheckForMultilineCommentsAndStrings
(filename, clean_lines, linenum, error)
Logs an error if we see /* ... */ or "..." that extend past one line. /* ... */ comments are legit inside macros, for one line. Otherwise, we prefer // comments, so it's ok to warn about the other. Likewise, it's ok for strings to extend across multiple lines, as long as a line continuation character (backslash) terminates each line. Although not currently prohibited by the C++ style guide, it's ugly and unnecessary. We don't do well with either in this lint program, so we warn about both. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Logs an error if we see /* ... */ or "..." that extend past one line.
[ "Logs", "an", "error", "if", "we", "see", "/", "*", "...", "*", "/", "or", "...", "that", "extend", "past", "one", "line", "." ]
def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error): """Logs an error if we see /* ... */ or "..." that extend past one line. /* ... */ comments are legit inside macros, for one line. Otherwise, we prefer // comments, so it's ok to warn about the other. Likewise, it's ok for strings to extend across multiple lines, as long as a line continuation character (backslash) terminates each line. Although not currently prohibited by the C++ style guide, it's ugly and unnecessary. We don't do well with either in this lint program, so we warn about both. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Remove all \\ (escaped backslashes) from the line. They are OK, and the # second (escaped) slash may trigger later \" detection erroneously. line = line.replace('\\\\', '') if line.count('/*') > line.count('*/'): error(filename, linenum, 'readability/multiline_comment', 5, 'Complex multi-line /*...*/-style comment found. ' 'Lint may give bogus warnings. ' 'Consider replacing these with //-style comments, ' 'with #if 0...#endif, ' 'or with more clearly structured multi-line comments.') if (line.count('"') - line.count('\\"')) % 2: error(filename, linenum, 'readability/multiline_string', 5, 'Multi-line string ("...") found. This lint script doesn\'t ' 'do well with such strings, and may give bogus warnings. ' 'Use C++11 raw strings or concatenation instead.')
[ "def", "CheckForMultilineCommentsAndStrings", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# Remove all \\\\ (escaped backslashes) from the line. They are OK, and the", "# second (escaped) slash may trigger later \\\" detection erroneously.", "line", "=", "line", ".", "replace", "(", "'\\\\\\\\'", ",", "''", ")", "if", "line", ".", "count", "(", "'/*'", ")", ">", "line", ".", "count", "(", "'*/'", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/multiline_comment'", ",", "5", ",", "'Complex multi-line /*...*/-style comment found. '", "'Lint may give bogus warnings. '", "'Consider replacing these with //-style comments, '", "'with #if 0...#endif, '", "'or with more clearly structured multi-line comments.'", ")", "if", "(", "line", ".", "count", "(", "'\"'", ")", "-", "line", ".", "count", "(", "'\\\\\"'", ")", ")", "%", "2", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/multiline_string'", ",", "5", ",", "'Multi-line string (\"...\") found. This lint script doesn\\'t '", "'do well with such strings, and may give bogus warnings. '", "'Use C++11 raw strings or concatenation instead.'", ")" ]
https://github.com/cmu-db/noisepage/blob/79276e68fe83322f1249e8a8be96bd63c583ae56/build-support/cpplint.py#L2283-L2318
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/Jinja2/py3/jinja2/compiler.py
python
CodeGenerator.pop_assign_tracking
(self, frame: Frame)
Pops the topmost level for assignment tracking and updates the context variables if necessary.
Pops the topmost level for assignment tracking and updates the context variables if necessary.
[ "Pops", "the", "topmost", "level", "for", "assignment", "tracking", "and", "updates", "the", "context", "variables", "if", "necessary", "." ]
def pop_assign_tracking(self, frame: Frame) -> None: """Pops the topmost level for assignment tracking and updates the context variables if necessary. """ vars = self._assign_stack.pop() if ( not frame.block_frame and not frame.loop_frame and not frame.toplevel or not vars ): return public_names = [x for x in vars if x[:1] != "_"] if len(vars) == 1: name = next(iter(vars)) ref = frame.symbols.ref(name) if frame.loop_frame: self.writeline(f"_loop_vars[{name!r}] = {ref}") return if frame.block_frame: self.writeline(f"_block_vars[{name!r}] = {ref}") return self.writeline(f"context.vars[{name!r}] = {ref}") else: if frame.loop_frame: self.writeline("_loop_vars.update({") elif frame.block_frame: self.writeline("_block_vars.update({") else: self.writeline("context.vars.update({") for idx, name in enumerate(vars): if idx: self.write(", ") ref = frame.symbols.ref(name) self.write(f"{name!r}: {ref}") self.write("})") if not frame.block_frame and not frame.loop_frame and public_names: if len(public_names) == 1: self.writeline(f"context.exported_vars.add({public_names[0]!r})") else: names_str = ", ".join(map(repr, public_names)) self.writeline(f"context.exported_vars.update(({names_str}))")
[ "def", "pop_assign_tracking", "(", "self", ",", "frame", ":", "Frame", ")", "->", "None", ":", "vars", "=", "self", ".", "_assign_stack", ".", "pop", "(", ")", "if", "(", "not", "frame", ".", "block_frame", "and", "not", "frame", ".", "loop_frame", "and", "not", "frame", ".", "toplevel", "or", "not", "vars", ")", ":", "return", "public_names", "=", "[", "x", "for", "x", "in", "vars", "if", "x", "[", ":", "1", "]", "!=", "\"_\"", "]", "if", "len", "(", "vars", ")", "==", "1", ":", "name", "=", "next", "(", "iter", "(", "vars", ")", ")", "ref", "=", "frame", ".", "symbols", ".", "ref", "(", "name", ")", "if", "frame", ".", "loop_frame", ":", "self", ".", "writeline", "(", "f\"_loop_vars[{name!r}] = {ref}\"", ")", "return", "if", "frame", ".", "block_frame", ":", "self", ".", "writeline", "(", "f\"_block_vars[{name!r}] = {ref}\"", ")", "return", "self", ".", "writeline", "(", "f\"context.vars[{name!r}] = {ref}\"", ")", "else", ":", "if", "frame", ".", "loop_frame", ":", "self", ".", "writeline", "(", "\"_loop_vars.update({\"", ")", "elif", "frame", ".", "block_frame", ":", "self", ".", "writeline", "(", "\"_block_vars.update({\"", ")", "else", ":", "self", ".", "writeline", "(", "\"context.vars.update({\"", ")", "for", "idx", ",", "name", "in", "enumerate", "(", "vars", ")", ":", "if", "idx", ":", "self", ".", "write", "(", "\", \"", ")", "ref", "=", "frame", ".", "symbols", ".", "ref", "(", "name", ")", "self", ".", "write", "(", "f\"{name!r}: {ref}\"", ")", "self", ".", "write", "(", "\"})\"", ")", "if", "not", "frame", ".", "block_frame", "and", "not", "frame", ".", "loop_frame", "and", "public_names", ":", "if", "len", "(", "public_names", ")", "==", "1", ":", "self", ".", "writeline", "(", "f\"context.exported_vars.add({public_names[0]!r})\"", ")", "else", ":", "names_str", "=", "\", \"", ".", "join", "(", "map", "(", "repr", ",", "public_names", ")", ")", "self", ".", "writeline", "(", "f\"context.exported_vars.update(({names_str}))\"", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Jinja2/py3/jinja2/compiler.py#L780-L821
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/WebKit/Tools/Scripts/webkitpy/style/checkers/cpp.py
python
_classify_include
(filename, include, is_system, include_state)
return _OTHER_HEADER
Figures out what kind of header 'include' is. Args: filename: The current file cpp_style is running over. include: The path to a #included file. is_system: True if the #include used <> rather than "". include_state: An _IncludeState instance in which the headers are inserted. Returns: One of the _XXX_HEADER constants. For example: >>> _classify_include('foo.cpp', 'config.h', False) _CONFIG_HEADER >>> _classify_include('foo.cpp', 'foo.h', False) _PRIMARY_HEADER >>> _classify_include('foo.cpp', 'bar.h', False) _OTHER_HEADER
Figures out what kind of header 'include' is.
[ "Figures", "out", "what", "kind", "of", "header", "include", "is", "." ]
def _classify_include(filename, include, is_system, include_state): """Figures out what kind of header 'include' is. Args: filename: The current file cpp_style is running over. include: The path to a #included file. is_system: True if the #include used <> rather than "". include_state: An _IncludeState instance in which the headers are inserted. Returns: One of the _XXX_HEADER constants. For example: >>> _classify_include('foo.cpp', 'config.h', False) _CONFIG_HEADER >>> _classify_include('foo.cpp', 'foo.h', False) _PRIMARY_HEADER >>> _classify_include('foo.cpp', 'bar.h', False) _OTHER_HEADER """ # If it is a system header we know it is classified as _OTHER_HEADER. if is_system and not include.startswith('public/'): return _OTHER_HEADER # If the include is named config.h then this is WebCore/config.h. if include == "config.h": return _CONFIG_HEADER # There cannot be primary includes in header files themselves. Only an # include exactly matches the header filename will be is flagged as # primary, so that it triggers the "don't include yourself" check. if filename.endswith('.h') and filename != include: return _OTHER_HEADER; # Qt's moc files do not follow the naming and ordering rules, so they should be skipped if include.startswith('moc_') and include.endswith('.cpp'): return _MOC_HEADER if include.endswith('.moc'): return _MOC_HEADER # If the target file basename starts with the include we're checking # then we consider it the primary header. target_base = FileInfo(filename).base_name() include_base = FileInfo(include).base_name() # If we haven't encountered a primary header, then be lenient in checking. if not include_state.visited_primary_section(): if target_base.find(include_base) != -1: return _PRIMARY_HEADER # Qt private APIs use _p.h suffix. if include_base.find(target_base) != -1 and include_base.endswith('_p'): return _PRIMARY_HEADER # If we already encountered a primary header, perform a strict comparison. # In case the two filename bases are the same then the above lenient check # probably was a false positive. elif include_state.visited_primary_section() and target_base == include_base: if include == "ResourceHandleWin.h": # FIXME: Thus far, we've only seen one example of these, but if we # start to see more, please consider generalizing this check # somehow. return _OTHER_HEADER return _PRIMARY_HEADER return _OTHER_HEADER
[ "def", "_classify_include", "(", "filename", ",", "include", ",", "is_system", ",", "include_state", ")", ":", "# If it is a system header we know it is classified as _OTHER_HEADER.", "if", "is_system", "and", "not", "include", ".", "startswith", "(", "'public/'", ")", ":", "return", "_OTHER_HEADER", "# If the include is named config.h then this is WebCore/config.h.", "if", "include", "==", "\"config.h\"", ":", "return", "_CONFIG_HEADER", "# There cannot be primary includes in header files themselves. Only an", "# include exactly matches the header filename will be is flagged as", "# primary, so that it triggers the \"don't include yourself\" check.", "if", "filename", ".", "endswith", "(", "'.h'", ")", "and", "filename", "!=", "include", ":", "return", "_OTHER_HEADER", "# Qt's moc files do not follow the naming and ordering rules, so they should be skipped", "if", "include", ".", "startswith", "(", "'moc_'", ")", "and", "include", ".", "endswith", "(", "'.cpp'", ")", ":", "return", "_MOC_HEADER", "if", "include", ".", "endswith", "(", "'.moc'", ")", ":", "return", "_MOC_HEADER", "# If the target file basename starts with the include we're checking", "# then we consider it the primary header.", "target_base", "=", "FileInfo", "(", "filename", ")", ".", "base_name", "(", ")", "include_base", "=", "FileInfo", "(", "include", ")", ".", "base_name", "(", ")", "# If we haven't encountered a primary header, then be lenient in checking.", "if", "not", "include_state", ".", "visited_primary_section", "(", ")", ":", "if", "target_base", ".", "find", "(", "include_base", ")", "!=", "-", "1", ":", "return", "_PRIMARY_HEADER", "# Qt private APIs use _p.h suffix.", "if", "include_base", ".", "find", "(", "target_base", ")", "!=", "-", "1", "and", "include_base", ".", "endswith", "(", "'_p'", ")", ":", "return", "_PRIMARY_HEADER", "# If we already encountered a primary header, perform a strict comparison.", "# In case the two filename bases are the same then the above lenient check", "# probably was a false positive.", "elif", "include_state", ".", "visited_primary_section", "(", ")", "and", "target_base", "==", "include_base", ":", "if", "include", "==", "\"ResourceHandleWin.h\"", ":", "# FIXME: Thus far, we've only seen one example of these, but if we", "# start to see more, please consider generalizing this check", "# somehow.", "return", "_OTHER_HEADER", "return", "_PRIMARY_HEADER", "return", "_OTHER_HEADER" ]
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/style/checkers/cpp.py#L2917-L2983
gem5/gem5
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
src/mem/slicc/parser.py
python
SLICC.p_statements_inner__one
(self, p)
statements_inner : statement
statements_inner : statement
[ "statements_inner", ":", "statement" ]
def p_statements_inner__one(self, p): "statements_inner : statement" p[0] = [ p[1] ]
[ "def", "p_statements_inner__one", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "[", "p", "[", "1", "]", "]" ]
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/src/mem/slicc/parser.py#L580-L582
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/linalg/_interpolative_backend.py
python
idz_id2svd
(B, idx, proj)
return U, V, S
Convert complex ID to SVD. :param B: Skeleton matrix. :type B: :class:`numpy.ndarray` :param idx: Column index array. :type idx: :class:`numpy.ndarray` :param proj: Interpolation coefficients. :type proj: :class:`numpy.ndarray` :return: Left singular vectors. :rtype: :class:`numpy.ndarray` :return: Right singular vectors. :rtype: :class:`numpy.ndarray` :return: Singular values. :rtype: :class:`numpy.ndarray`
Convert complex ID to SVD.
[ "Convert", "complex", "ID", "to", "SVD", "." ]
def idz_id2svd(B, idx, proj): """ Convert complex ID to SVD. :param B: Skeleton matrix. :type B: :class:`numpy.ndarray` :param idx: Column index array. :type idx: :class:`numpy.ndarray` :param proj: Interpolation coefficients. :type proj: :class:`numpy.ndarray` :return: Left singular vectors. :rtype: :class:`numpy.ndarray` :return: Right singular vectors. :rtype: :class:`numpy.ndarray` :return: Singular values. :rtype: :class:`numpy.ndarray` """ B = np.asfortranarray(B) U, V, S, ier = _id.idz_id2svd(B, idx, proj) if ier: raise _RETCODE_ERROR return U, V, S
[ "def", "idz_id2svd", "(", "B", ",", "idx", ",", "proj", ")", ":", "B", "=", "np", ".", "asfortranarray", "(", "B", ")", "U", ",", "V", ",", "S", ",", "ier", "=", "_id", ".", "idz_id2svd", "(", "B", ",", "idx", ",", "proj", ")", "if", "ier", ":", "raise", "_RETCODE_ERROR", "return", "U", ",", "V", ",", "S" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/linalg/_interpolative_backend.py#L1101-L1129
rsummers11/CADLab
976ed959a0b5208bb4173127a7ef732ac73a9b6f
panreas_hnn/hed-globalweight/python/caffe/detector.py
python
Detector.detect_selective_search
(self, image_fnames)
return self.detect_windows(zip(image_fnames, windows_list))
Do windowed detection over Selective Search proposals by extracting the crop and warping to the input dimensions of the net. Parameters ---------- image_fnames: list Returns ------- detections: list of {filename: image filename, window: crop coordinates, predictions: prediction vector} dicts.
Do windowed detection over Selective Search proposals by extracting the crop and warping to the input dimensions of the net.
[ "Do", "windowed", "detection", "over", "Selective", "Search", "proposals", "by", "extracting", "the", "crop", "and", "warping", "to", "the", "input", "dimensions", "of", "the", "net", "." ]
def detect_selective_search(self, image_fnames): """ Do windowed detection over Selective Search proposals by extracting the crop and warping to the input dimensions of the net. Parameters ---------- image_fnames: list Returns ------- detections: list of {filename: image filename, window: crop coordinates, predictions: prediction vector} dicts. """ import selective_search_ijcv_with_python as selective_search # Make absolute paths so MATLAB can find the files. image_fnames = [os.path.abspath(f) for f in image_fnames] windows_list = selective_search.get_windows( image_fnames, cmd='selective_search_rcnn' ) # Run windowed detection on the selective search list. return self.detect_windows(zip(image_fnames, windows_list))
[ "def", "detect_selective_search", "(", "self", ",", "image_fnames", ")", ":", "import", "selective_search_ijcv_with_python", "as", "selective_search", "# Make absolute paths so MATLAB can find the files.", "image_fnames", "=", "[", "os", ".", "path", ".", "abspath", "(", "f", ")", "for", "f", "in", "image_fnames", "]", "windows_list", "=", "selective_search", ".", "get_windows", "(", "image_fnames", ",", "cmd", "=", "'selective_search_rcnn'", ")", "# Run windowed detection on the selective search list.", "return", "self", ".", "detect_windows", "(", "zip", "(", "image_fnames", ",", "windows_list", ")", ")" ]
https://github.com/rsummers11/CADLab/blob/976ed959a0b5208bb4173127a7ef732ac73a9b6f/panreas_hnn/hed-globalweight/python/caffe/detector.py#L101-L123
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/framework/subscribe.py
python
subscribe
(tensors, side_effects)
return result
Subscribe to a tensor. This method will attach side effect graphs to a given set of tensors. Set of tensors follows from session.run and supports single `Tensor`, `list`, nested `list`, `tuple`, `namedtuple`, or `dict`. It returns the tensors in the same passed in structure, but as clones with side effects applied. The supplied side effect graphs are specified as a constructor function which takes the target tensor and constructs a side effect graph and returns a list of ops that should be control dependencies on fetching the tensor. It will append 'subscription' to the name scope of the tensor for every node in the side effect graph. These control dependencies are what trigger the side effects. Subscribe will construct the additions to your graph and return the created identity tensor downstream of the control dependencies. Use these tensors as you would normally in the rest of your tensorflow code. If a given tensor has already been subscribed or a tensor returned by a call to subscribe is passed, the previously created identity tensor will be reused and the side effect graphs will be added to the existing ones. Args: tensors: `Tensor` or set of tensors to subscribe to. Set of tensors format follows from `Session.run` and supports single `Tensor`, `list`, nested `list`, `tuple`, `namedtuple`, or `dict`. side_effects: Function(s) that takes a `Tensor`, construct a subgraph, and return a nonempty list of control dependencies. This can be a single function or list of functions. Returns: Subscribed tensors, which are identity copies of the passed in tensors in the same passed in structure, but the graph has been modified such that these are downstream of the control dependencies for the side effect graphs. Use these functionally equivalent tensors instead of the passed in tensors for further construction or running.
Subscribe to a tensor.
[ "Subscribe", "to", "a", "tensor", "." ]
def subscribe(tensors, side_effects): """Subscribe to a tensor. This method will attach side effect graphs to a given set of tensors. Set of tensors follows from session.run and supports single `Tensor`, `list`, nested `list`, `tuple`, `namedtuple`, or `dict`. It returns the tensors in the same passed in structure, but as clones with side effects applied. The supplied side effect graphs are specified as a constructor function which takes the target tensor and constructs a side effect graph and returns a list of ops that should be control dependencies on fetching the tensor. It will append 'subscription' to the name scope of the tensor for every node in the side effect graph. These control dependencies are what trigger the side effects. Subscribe will construct the additions to your graph and return the created identity tensor downstream of the control dependencies. Use these tensors as you would normally in the rest of your tensorflow code. If a given tensor has already been subscribed or a tensor returned by a call to subscribe is passed, the previously created identity tensor will be reused and the side effect graphs will be added to the existing ones. Args: tensors: `Tensor` or set of tensors to subscribe to. Set of tensors format follows from `Session.run` and supports single `Tensor`, `list`, nested `list`, `tuple`, `namedtuple`, or `dict`. side_effects: Function(s) that takes a `Tensor`, construct a subgraph, and return a nonempty list of control dependencies. This can be a single function or list of functions. Returns: Subscribed tensors, which are identity copies of the passed in tensors in the same passed in structure, but the graph has been modified such that these are downstream of the control dependencies for the side effect graphs. Use these functionally equivalent tensors instead of the passed in tensors for further construction or running. """ if not hasattr(side_effects, '__iter__'): side_effects = [side_effects] control_outputs = _ControlOutputCache() result = _recursive_apply( tensors, lambda t: _scoped_subscribe(t, side_effects, control_outputs)) return result
[ "def", "subscribe", "(", "tensors", ",", "side_effects", ")", ":", "if", "not", "hasattr", "(", "side_effects", ",", "'__iter__'", ")", ":", "side_effects", "=", "[", "side_effects", "]", "control_outputs", "=", "_ControlOutputCache", "(", ")", "result", "=", "_recursive_apply", "(", "tensors", ",", "lambda", "t", ":", "_scoped_subscribe", "(", "t", ",", "side_effects", ",", "control_outputs", ")", ")", "return", "result" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/framework/subscribe.py#L309-L351
SIPp/sipp
f44d0cf5dec0013eff8fd7b4da885d455aa82e0e
cpplint.py
python
IsCppString
(line)
return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1
Does line terminate so, that the next symbol is in string constant. This function does not consider single-line nor multi-line comments. Args: line: is a partial line of code starting from the 0..n. Returns: True, if next character appended to 'line' is inside a string constant.
Does line terminate so, that the next symbol is in string constant.
[ "Does", "line", "terminate", "so", "that", "the", "next", "symbol", "is", "in", "string", "constant", "." ]
def IsCppString(line): """Does line terminate so, that the next symbol is in string constant. This function does not consider single-line nor multi-line comments. Args: line: is a partial line of code starting from the 0..n. Returns: True, if next character appended to 'line' is inside a string constant. """ line = line.replace(r'\\', 'XX') # after this, \\" does not match to \" return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1
[ "def", "IsCppString", "(", "line", ")", ":", "line", "=", "line", ".", "replace", "(", "r'\\\\'", ",", "'XX'", ")", "# after this, \\\\\" does not match to \\\"", "return", "(", "(", "line", ".", "count", "(", "'\"'", ")", "-", "line", ".", "count", "(", "r'\\\"'", ")", "-", "line", ".", "count", "(", "\"'\\\"'\"", ")", ")", "&", "1", ")", "==", "1" ]
https://github.com/SIPp/sipp/blob/f44d0cf5dec0013eff8fd7b4da885d455aa82e0e/cpplint.py#L909-L923
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
Configuration/Applications/python/ConfigBuilder.py
python
ConfigBuilder.prepare_POSTRECO
(self, sequence = None)
return
Enrich the schedule with the postreco step
Enrich the schedule with the postreco step
[ "Enrich", "the", "schedule", "with", "the", "postreco", "step" ]
def prepare_POSTRECO(self, sequence = None): """ Enrich the schedule with the postreco step """ self.loadAndRemember(self.POSTRECODefaultCFF) self.scheduleSequence('postreco_generator','postreco_step') return
[ "def", "prepare_POSTRECO", "(", "self", ",", "sequence", "=", "None", ")", ":", "self", ".", "loadAndRemember", "(", "self", ".", "POSTRECODefaultCFF", ")", "self", ".", "scheduleSequence", "(", "'postreco_generator'", ",", "'postreco_step'", ")", "return" ]
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Configuration/Applications/python/ConfigBuilder.py#L1788-L1792
astra-toolbox/astra-toolbox
1e7ec8af702e595b76654f2e500f4c00344b273f
python/astra/data2d.py
python
get
(i)
return d.get(i)
Get a 2D object. :param i: ID of object to get. :type i: :class:`int` :returns: :class:`numpy.ndarray` -- The object data.
Get a 2D object. :param i: ID of object to get. :type i: :class:`int` :returns: :class:`numpy.ndarray` -- The object data.
[ "Get", "a", "2D", "object", ".", ":", "param", "i", ":", "ID", "of", "object", "to", "get", ".", ":", "type", "i", ":", ":", "class", ":", "int", ":", "returns", ":", ":", "class", ":", "numpy", ".", "ndarray", "--", "The", "object", "data", "." ]
def get(i): """Get a 2D object. :param i: ID of object to get. :type i: :class:`int` :returns: :class:`numpy.ndarray` -- The object data. """ return d.get(i)
[ "def", "get", "(", "i", ")", ":", "return", "d", ".", "get", "(", "i", ")" ]
https://github.com/astra-toolbox/astra-toolbox/blob/1e7ec8af702e595b76654f2e500f4c00344b273f/python/astra/data2d.py#L105-L113
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/ndimage/morphology.py
python
binary_closing
(input, structure=None, iterations=1, output=None, origin=0, mask=None, border_value=0, brute_force=False)
return binary_erosion(tmp, structure, iterations, mask, output, border_value, origin, brute_force)
Multi-dimensional binary closing with the given structuring element. The *closing* of an input image by a structuring element is the *erosion* of the *dilation* of the image by the structuring element. Parameters ---------- input : array_like Binary array_like to be closed. Non-zero (True) elements form the subset to be closed. structure : array_like, optional Structuring element used for the closing. Non-zero elements are considered True. If no structuring element is provided an element is generated with a square connectivity equal to one (i.e., only nearest neighbors are connected to the center, diagonally-connected elements are not considered neighbors). iterations : {int, float}, optional The dilation step of the closing, then the erosion step are each repeated `iterations` times (one, by default). If iterations is less than 1, each operations is repeated until the result does not change anymore. output : ndarray, optional Array of the same shape as input, into which the output is placed. By default, a new array is created. origin : int or tuple of ints, optional Placement of the filter, by default 0. mask : array_like, optional If a mask is given, only those elements with a True value at the corresponding mask element are modified at each iteration. .. versionadded:: 1.1.0 border_value : int (cast to 0 or 1), optional Value at the border in the output array. .. versionadded:: 1.1.0 brute_force : boolean, optional Memory condition: if False, only the pixels whose value was changed in the last iteration are tracked as candidates to be updated in the current iteration; if true al pixels are considered as candidates for update, regardless of what happened in the previous iteration. False by default. .. versionadded:: 1.1.0 Returns ------- binary_closing : ndarray of bools Closing of the input by the structuring element. See also -------- grey_closing, binary_opening, binary_dilation, binary_erosion, generate_binary_structure Notes ----- *Closing* [1]_ is a mathematical morphology operation [2]_ that consists in the succession of a dilation and an erosion of the input with the same structuring element. Closing therefore fills holes smaller than the structuring element. Together with *opening* (`binary_opening`), closing can be used for noise removal. References ---------- .. [1] https://en.wikipedia.org/wiki/Closing_%28morphology%29 .. [2] https://en.wikipedia.org/wiki/Mathematical_morphology Examples -------- >>> from scipy import ndimage >>> a = np.zeros((5,5), dtype=int) >>> a[1:-1, 1:-1] = 1; a[2,2] = 0 >>> a array([[0, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 1, 0, 1, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 0]]) >>> # Closing removes small holes >>> ndimage.binary_closing(a).astype(int) array([[0, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 0]]) >>> # Closing is the erosion of the dilation of the input >>> ndimage.binary_dilation(a).astype(int) array([[0, 1, 1, 1, 0], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [0, 1, 1, 1, 0]]) >>> ndimage.binary_erosion(ndimage.binary_dilation(a)).astype(int) array([[0, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 0]]) >>> a = np.zeros((7,7), dtype=int) >>> a[1:6, 2:5] = 1; a[1:3,3] = 0 >>> a array([[0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 1, 0, 0], [0, 0, 1, 0, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0]]) >>> # In addition to removing holes, closing can also >>> # coarsen boundaries with fine hollows. >>> ndimage.binary_closing(a).astype(int) array([[0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0]]) >>> ndimage.binary_closing(a, structure=np.ones((2,2))).astype(int) array([[0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0]])
Multi-dimensional binary closing with the given structuring element.
[ "Multi", "-", "dimensional", "binary", "closing", "with", "the", "given", "structuring", "element", "." ]
def binary_closing(input, structure=None, iterations=1, output=None, origin=0, mask=None, border_value=0, brute_force=False): """ Multi-dimensional binary closing with the given structuring element. The *closing* of an input image by a structuring element is the *erosion* of the *dilation* of the image by the structuring element. Parameters ---------- input : array_like Binary array_like to be closed. Non-zero (True) elements form the subset to be closed. structure : array_like, optional Structuring element used for the closing. Non-zero elements are considered True. If no structuring element is provided an element is generated with a square connectivity equal to one (i.e., only nearest neighbors are connected to the center, diagonally-connected elements are not considered neighbors). iterations : {int, float}, optional The dilation step of the closing, then the erosion step are each repeated `iterations` times (one, by default). If iterations is less than 1, each operations is repeated until the result does not change anymore. output : ndarray, optional Array of the same shape as input, into which the output is placed. By default, a new array is created. origin : int or tuple of ints, optional Placement of the filter, by default 0. mask : array_like, optional If a mask is given, only those elements with a True value at the corresponding mask element are modified at each iteration. .. versionadded:: 1.1.0 border_value : int (cast to 0 or 1), optional Value at the border in the output array. .. versionadded:: 1.1.0 brute_force : boolean, optional Memory condition: if False, only the pixels whose value was changed in the last iteration are tracked as candidates to be updated in the current iteration; if true al pixels are considered as candidates for update, regardless of what happened in the previous iteration. False by default. .. versionadded:: 1.1.0 Returns ------- binary_closing : ndarray of bools Closing of the input by the structuring element. See also -------- grey_closing, binary_opening, binary_dilation, binary_erosion, generate_binary_structure Notes ----- *Closing* [1]_ is a mathematical morphology operation [2]_ that consists in the succession of a dilation and an erosion of the input with the same structuring element. Closing therefore fills holes smaller than the structuring element. Together with *opening* (`binary_opening`), closing can be used for noise removal. References ---------- .. [1] https://en.wikipedia.org/wiki/Closing_%28morphology%29 .. [2] https://en.wikipedia.org/wiki/Mathematical_morphology Examples -------- >>> from scipy import ndimage >>> a = np.zeros((5,5), dtype=int) >>> a[1:-1, 1:-1] = 1; a[2,2] = 0 >>> a array([[0, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 1, 0, 1, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 0]]) >>> # Closing removes small holes >>> ndimage.binary_closing(a).astype(int) array([[0, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 0]]) >>> # Closing is the erosion of the dilation of the input >>> ndimage.binary_dilation(a).astype(int) array([[0, 1, 1, 1, 0], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [0, 1, 1, 1, 0]]) >>> ndimage.binary_erosion(ndimage.binary_dilation(a)).astype(int) array([[0, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 0]]) >>> a = np.zeros((7,7), dtype=int) >>> a[1:6, 2:5] = 1; a[1:3,3] = 0 >>> a array([[0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 1, 0, 0], [0, 0, 1, 0, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0]]) >>> # In addition to removing holes, closing can also >>> # coarsen boundaries with fine hollows. >>> ndimage.binary_closing(a).astype(int) array([[0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0]]) >>> ndimage.binary_closing(a, structure=np.ones((2,2))).astype(int) array([[0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0]]) """ input = numpy.asarray(input) if structure is None: rank = input.ndim structure = generate_binary_structure(rank, 1) tmp = binary_dilation(input, structure, iterations, mask, None, border_value, origin, brute_force) return binary_erosion(tmp, structure, iterations, mask, output, border_value, origin, brute_force)
[ "def", "binary_closing", "(", "input", ",", "structure", "=", "None", ",", "iterations", "=", "1", ",", "output", "=", "None", ",", "origin", "=", "0", ",", "mask", "=", "None", ",", "border_value", "=", "0", ",", "brute_force", "=", "False", ")", ":", "input", "=", "numpy", ".", "asarray", "(", "input", ")", "if", "structure", "is", "None", ":", "rank", "=", "input", ".", "ndim", "structure", "=", "generate_binary_structure", "(", "rank", ",", "1", ")", "tmp", "=", "binary_dilation", "(", "input", ",", "structure", ",", "iterations", ",", "mask", ",", "None", ",", "border_value", ",", "origin", ",", "brute_force", ")", "return", "binary_erosion", "(", "tmp", ",", "structure", ",", "iterations", ",", "mask", ",", "output", ",", "border_value", ",", "origin", ",", "brute_force", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/ndimage/morphology.py#L633-L776
psi4/psi4
be533f7f426b6ccc263904e55122899b16663395
psi4/driver/p4util/python_helpers.py
python
_multipole_compressor
(complete, order)
return np.array(compressed)
Form flat unique components multipole array from complete Cartesian array. Parameters ---------- order : int Multipole order. e.g., 1 for dipole, 4 for hexadecapole. complete : ndarray Multipole array, order-dimensional Cartesian array expanded to complete components. Returns ------- compressed : ndarray Multipole array, length (order + 1) * (order + 2) / 2 compressed to unique components.
Form flat unique components multipole array from complete Cartesian array.
[ "Form", "flat", "unique", "components", "multipole", "array", "from", "complete", "Cartesian", "array", "." ]
def _multipole_compressor(complete, order): """Form flat unique components multipole array from complete Cartesian array. Parameters ---------- order : int Multipole order. e.g., 1 for dipole, 4 for hexadecapole. complete : ndarray Multipole array, order-dimensional Cartesian array expanded to complete components. Returns ------- compressed : ndarray Multipole array, length (order + 1) * (order + 2) / 2 compressed to unique components. """ compressed = [] for ii in range(order + 1): lx = order - ii for lz in range(ii + 1): ly = ii - lz np_index = [] for xval in range(lx): np_index.append(0) for yval in range(ly): np_index.append(1) for zval in range(lz): np_index.append(2) compressed.append(complete[tuple(np_index)]) assert len(compressed) == ((order + 1) * (order + 2) / 2) return np.array(compressed)
[ "def", "_multipole_compressor", "(", "complete", ",", "order", ")", ":", "compressed", "=", "[", "]", "for", "ii", "in", "range", "(", "order", "+", "1", ")", ":", "lx", "=", "order", "-", "ii", "for", "lz", "in", "range", "(", "ii", "+", "1", ")", ":", "ly", "=", "ii", "-", "lz", "np_index", "=", "[", "]", "for", "xval", "in", "range", "(", "lx", ")", ":", "np_index", ".", "append", "(", "0", ")", "for", "yval", "in", "range", "(", "ly", ")", ":", "np_index", ".", "append", "(", "1", ")", "for", "zval", "in", "range", "(", "lz", ")", ":", "np_index", ".", "append", "(", "2", ")", "compressed", ".", "append", "(", "complete", "[", "tuple", "(", "np_index", ")", "]", ")", "assert", "len", "(", "compressed", ")", "==", "(", "(", "order", "+", "1", ")", "*", "(", "order", "+", "2", ")", "/", "2", ")", "return", "np", ".", "array", "(", "compressed", ")" ]
https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/p4util/python_helpers.py#L746-L778
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/multiprocessing/connection.py
python
arbitrary_address
(family)
Return an arbitrary free address for the given family
Return an arbitrary free address for the given family
[ "Return", "an", "arbitrary", "free", "address", "for", "the", "given", "family" ]
def arbitrary_address(family): ''' Return an arbitrary free address for the given family ''' if family == 'AF_INET': return ('localhost', 0) elif family == 'AF_UNIX': return tempfile.mktemp(prefix='listener-', dir=get_temp_dir()) elif family == 'AF_PIPE': return tempfile.mktemp(prefix=r'\\.\pipe\pyc-%d-%d-' % (os.getpid(), _mmap_counter.next())) else: raise ValueError('unrecognized family')
[ "def", "arbitrary_address", "(", "family", ")", ":", "if", "family", "==", "'AF_INET'", ":", "return", "(", "'localhost'", ",", "0", ")", "elif", "family", "==", "'AF_UNIX'", ":", "return", "tempfile", ".", "mktemp", "(", "prefix", "=", "'listener-'", ",", "dir", "=", "get_temp_dir", "(", ")", ")", "elif", "family", "==", "'AF_PIPE'", ":", "return", "tempfile", ".", "mktemp", "(", "prefix", "=", "r'\\\\.\\pipe\\pyc-%d-%d-'", "%", "(", "os", ".", "getpid", "(", ")", ",", "_mmap_counter", ".", "next", "(", ")", ")", ")", "else", ":", "raise", "ValueError", "(", "'unrecognized family'", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/multiprocessing/connection.py#L83-L95
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/OpenSSL/crypto.py
python
X509.add_extensions
(self, extensions)
Add extensions to the certificate. :param extensions: The extensions to add. :type extensions: An iterable of :py:class:`X509Extension` objects. :return: ``None``
Add extensions to the certificate.
[ "Add", "extensions", "to", "the", "certificate", "." ]
def add_extensions(self, extensions): """ Add extensions to the certificate. :param extensions: The extensions to add. :type extensions: An iterable of :py:class:`X509Extension` objects. :return: ``None`` """ for ext in extensions: if not isinstance(ext, X509Extension): raise ValueError("One of the elements is not an X509Extension") add_result = _lib.X509_add_ext(self._x509, ext._extension, -1) if not add_result: _raise_current_error()
[ "def", "add_extensions", "(", "self", ",", "extensions", ")", ":", "for", "ext", "in", "extensions", ":", "if", "not", "isinstance", "(", "ext", ",", "X509Extension", ")", ":", "raise", "ValueError", "(", "\"One of the elements is not an X509Extension\"", ")", "add_result", "=", "_lib", ".", "X509_add_ext", "(", "self", ".", "_x509", ",", "ext", ".", "_extension", ",", "-", "1", ")", "if", "not", "add_result", ":", "_raise_current_error", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/OpenSSL/crypto.py#L1477-L1491
CMU-Perceptual-Computing-Lab/caffe_rtpose
a4778bb1c3eb74d7250402016047216f77b4dba6
scripts/cpp_lint.py
python
CheckSpacingForFunctionCall
(filename, line, linenum, error)
Checks for the correctness of various spacing around function calls. Args: filename: The name of the current file. line: The text of the line to check. linenum: The number of the line to check. error: The function to call with any errors found.
Checks for the correctness of various spacing around function calls.
[ "Checks", "for", "the", "correctness", "of", "various", "spacing", "around", "function", "calls", "." ]
def CheckSpacingForFunctionCall(filename, line, linenum, error): """Checks for the correctness of various spacing around function calls. Args: filename: The name of the current file. line: The text of the line to check. linenum: The number of the line to check. error: The function to call with any errors found. """ # Since function calls often occur inside if/for/while/switch # expressions - which have their own, more liberal conventions - we # first see if we should be looking inside such an expression for a # function call, to which we can apply more strict standards. fncall = line # if there's no control flow construct, look at whole line for pattern in (r'\bif\s*\((.*)\)\s*{', r'\bfor\s*\((.*)\)\s*{', r'\bwhile\s*\((.*)\)\s*[{;]', r'\bswitch\s*\((.*)\)\s*{'): match = Search(pattern, line) if match: fncall = match.group(1) # look inside the parens for function calls break # Except in if/for/while/switch, there should never be space # immediately inside parens (eg "f( 3, 4 )"). We make an exception # for nested parens ( (a+b) + c ). Likewise, there should never be # a space before a ( when it's a function argument. I assume it's a # function argument when the char before the whitespace is legal in # a function name (alnum + _) and we're not starting a macro. Also ignore # pointers and references to arrays and functions coz they're too tricky: # we use a very simple way to recognize these: # " (something)(maybe-something)" or # " (something)(maybe-something," or # " (something)[something]" # Note that we assume the contents of [] to be short enough that # they'll never need to wrap. if ( # Ignore control structures. not Search(r'\b(if|for|while|switch|return|new|delete|catch|sizeof)\b', fncall) and # Ignore pointers/references to functions. not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and # Ignore pointers/references to arrays. not Search(r' \([^)]+\)\[[^\]]+\]', fncall)): if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call error(filename, linenum, 'whitespace/parens', 4, 'Extra space after ( in function call') elif Search(r'\(\s+(?!(\s*\\)|\()', fncall): error(filename, linenum, 'whitespace/parens', 2, 'Extra space after (') if (Search(r'\w\s+\(', fncall) and not Search(r'#\s*define|typedef', fncall) and not Search(r'\w\s+\((\w+::)*\*\w+\)\(', fncall)): error(filename, linenum, 'whitespace/parens', 4, 'Extra space before ( in function call') # If the ) is followed only by a newline or a { + newline, assume it's # part of a control statement (if/while/etc), and don't complain if Search(r'[^)]\s+\)\s*[^{\s]', fncall): # If the closing parenthesis is preceded by only whitespaces, # try to give a more descriptive error message. if Search(r'^\s+\)', fncall): error(filename, linenum, 'whitespace/parens', 2, 'Closing ) should be moved to the previous line') else: error(filename, linenum, 'whitespace/parens', 2, 'Extra space before )')
[ "def", "CheckSpacingForFunctionCall", "(", "filename", ",", "line", ",", "linenum", ",", "error", ")", ":", "# Since function calls often occur inside if/for/while/switch", "# expressions - which have their own, more liberal conventions - we", "# first see if we should be looking inside such an expression for a", "# function call, to which we can apply more strict standards.", "fncall", "=", "line", "# if there's no control flow construct, look at whole line", "for", "pattern", "in", "(", "r'\\bif\\s*\\((.*)\\)\\s*{'", ",", "r'\\bfor\\s*\\((.*)\\)\\s*{'", ",", "r'\\bwhile\\s*\\((.*)\\)\\s*[{;]'", ",", "r'\\bswitch\\s*\\((.*)\\)\\s*{'", ")", ":", "match", "=", "Search", "(", "pattern", ",", "line", ")", "if", "match", ":", "fncall", "=", "match", ".", "group", "(", "1", ")", "# look inside the parens for function calls", "break", "# Except in if/for/while/switch, there should never be space", "# immediately inside parens (eg \"f( 3, 4 )\"). We make an exception", "# for nested parens ( (a+b) + c ). Likewise, there should never be", "# a space before a ( when it's a function argument. I assume it's a", "# function argument when the char before the whitespace is legal in", "# a function name (alnum + _) and we're not starting a macro. Also ignore", "# pointers and references to arrays and functions coz they're too tricky:", "# we use a very simple way to recognize these:", "# \" (something)(maybe-something)\" or", "# \" (something)(maybe-something,\" or", "# \" (something)[something]\"", "# Note that we assume the contents of [] to be short enough that", "# they'll never need to wrap.", "if", "(", "# Ignore control structures.", "not", "Search", "(", "r'\\b(if|for|while|switch|return|new|delete|catch|sizeof)\\b'", ",", "fncall", ")", "and", "# Ignore pointers/references to functions.", "not", "Search", "(", "r' \\([^)]+\\)\\([^)]*(\\)|,$)'", ",", "fncall", ")", "and", "# Ignore pointers/references to arrays.", "not", "Search", "(", "r' \\([^)]+\\)\\[[^\\]]+\\]'", ",", "fncall", ")", ")", ":", "if", "Search", "(", "r'\\w\\s*\\(\\s(?!\\s*\\\\$)'", ",", "fncall", ")", ":", "# a ( used for a fn call", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "4", ",", "'Extra space after ( in function call'", ")", "elif", "Search", "(", "r'\\(\\s+(?!(\\s*\\\\)|\\()'", ",", "fncall", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "2", ",", "'Extra space after ('", ")", "if", "(", "Search", "(", "r'\\w\\s+\\('", ",", "fncall", ")", "and", "not", "Search", "(", "r'#\\s*define|typedef'", ",", "fncall", ")", "and", "not", "Search", "(", "r'\\w\\s+\\((\\w+::)*\\*\\w+\\)\\('", ",", "fncall", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "4", ",", "'Extra space before ( in function call'", ")", "# If the ) is followed only by a newline or a { + newline, assume it's", "# part of a control statement (if/while/etc), and don't complain", "if", "Search", "(", "r'[^)]\\s+\\)\\s*[^{\\s]'", ",", "fncall", ")", ":", "# If the closing parenthesis is preceded by only whitespaces,", "# try to give a more descriptive error message.", "if", "Search", "(", "r'^\\s+\\)'", ",", "fncall", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "2", ",", "'Closing ) should be moved to the previous line'", ")", "else", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "2", ",", "'Extra space before )'", ")" ]
https://github.com/CMU-Perceptual-Computing-Lab/caffe_rtpose/blob/a4778bb1c3eb74d7250402016047216f77b4dba6/scripts/cpp_lint.py#L2301-L2366
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_windows.py
python
PyPreviewFrame.InitializeWithModality
(*args, **kwargs)
return _windows_.PyPreviewFrame_InitializeWithModality(*args, **kwargs)
InitializeWithModality(self, int kind)
InitializeWithModality(self, int kind)
[ "InitializeWithModality", "(", "self", "int", "kind", ")" ]
def InitializeWithModality(*args, **kwargs): """InitializeWithModality(self, int kind)""" return _windows_.PyPreviewFrame_InitializeWithModality(*args, **kwargs)
[ "def", "InitializeWithModality", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "PyPreviewFrame_InitializeWithModality", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_windows.py#L5760-L5762