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
sonyxperiadev/WebGL
0299b38196f78c6d5f74bcf6fa312a3daee6de60
Tools/Scripts/webkitpy/common/system/autoinstall.py
python
AutoInstaller._is_downloaded
(self, target_name, url)
return version.strip() == url.strip()
Return whether a package version has been downloaded.
Return whether a package version has been downloaded.
[ "Return", "whether", "a", "package", "version", "has", "been", "downloaded", "." ]
def _is_downloaded(self, target_name, url): """Return whether a package version has been downloaded.""" version_path = self._url_downloaded_path(target_name) _log.debug('Checking %s URL downloaded...' % target_name) _log.debug(' "%s"' % version_path) if not os.path.exists(version_path): # Then no package version has been downloaded. _log.debug("No URL file found.") return False with codecs.open(version_path, "r", "utf-8") as file: version = file.read() return version.strip() == url.strip()
[ "def", "_is_downloaded", "(", "self", ",", "target_name", ",", "url", ")", ":", "version_path", "=", "self", ".", "_url_downloaded_path", "(", "target_name", ")", "_log", ".", "debug", "(", "'Checking %s URL downloaded...'", "%", "target_name", ")", "_log", ".",...
https://github.com/sonyxperiadev/WebGL/blob/0299b38196f78c6d5f74bcf6fa312a3daee6de60/Tools/Scripts/webkitpy/common/system/autoinstall.py#L208-L223
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/vendor/distlib/_backport/tarfile.py
python
TarFile.addfile
(self, tarinfo, fileobj=None)
Add the TarInfo object `tarinfo' to the archive. If `fileobj' is given, tarinfo.size bytes are read from it and added to the archive. You can create TarInfo objects using gettarinfo(). On Windows platforms, `fileobj' should always be opened with mode 'rb' to avoid irritation about the file size.
Add the TarInfo object `tarinfo' to the archive. If `fileobj' is given, tarinfo.size bytes are read from it and added to the archive. You can create TarInfo objects using gettarinfo(). On Windows platforms, `fileobj' should always be opened with mode 'rb' to avoid irritation about the file size.
[ "Add", "the", "TarInfo", "object", "tarinfo", "to", "the", "archive", ".", "If", "fileobj", "is", "given", "tarinfo", ".", "size", "bytes", "are", "read", "from", "it", "and", "added", "to", "the", "archive", ".", "You", "can", "create", "TarInfo", "obje...
def addfile(self, tarinfo, fileobj=None): """Add the TarInfo object `tarinfo' to the archive. If `fileobj' is given, tarinfo.size bytes are read from it and added to the archive. You can create TarInfo objects using gettarinfo(). On Windows platforms, `fileobj' should always be opened with mode 'rb' to avoid irritation about the file size. """ self._check("aw") tarinfo = copy.copy(tarinfo) buf = tarinfo.tobuf(self.format, self.encoding, self.errors) self.fileobj.write(buf) self.offset += len(buf) # If there's data to follow, append it. if fileobj is not None: copyfileobj(fileobj, self.fileobj, tarinfo.size) blocks, remainder = divmod(tarinfo.size, BLOCKSIZE) if remainder > 0: self.fileobj.write(NUL * (BLOCKSIZE - remainder)) blocks += 1 self.offset += blocks * BLOCKSIZE self.members.append(tarinfo)
[ "def", "addfile", "(", "self", ",", "tarinfo", ",", "fileobj", "=", "None", ")", ":", "self", ".", "_check", "(", "\"aw\"", ")", "tarinfo", "=", "copy", ".", "copy", "(", "tarinfo", ")", "buf", "=", "tarinfo", ".", "tobuf", "(", "self", ".", "forma...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/vendor/distlib/_backport/tarfile.py#L2100-L2124
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/signal/_peak_finding.py
python
peak_prominences
(x, peaks, wlen=None)
return _peak_prominences(x, peaks, wlen)
Calculate the prominence of each peak in a signal. The prominence of a peak measures how much a peak stands out from the surrounding baseline of the signal and is defined as the vertical distance between the peak and its lowest contour line. Parameters ---------- x : sequence A signal with peaks. peaks : sequence Indices of peaks in `x`. wlen : int, optional A window length in samples that optionally limits the evaluated area for each peak to a subset of `x`. The peak is always placed in the middle of the window therefore the given length is rounded up to the next odd integer. This parameter can speed up the calculation (see Notes). Returns ------- prominences : ndarray The calculated prominences for each peak in `peaks`. left_bases, right_bases : ndarray The peaks' bases as indices in `x` to the left and right of each peak. The higher base of each pair is a peak's lowest contour line. Raises ------ ValueError If a value in `peaks` is an invalid index for `x`. Warns ----- PeakPropertyWarning For indices in `peaks` that don't point to valid local maxima in `x` the returned prominence will be 0 and this warning is raised. This also happens if `wlen` is smaller than the plateau size of a peak. Warnings -------- This function may return unexpected results for data containing NaNs. To avoid this, NaNs should either be removed or replaced. See Also -------- find_peaks Find peaks inside a signal based on peak properties. peak_widths Calculate the width of peaks. Notes ----- Strategy to compute a peak's prominence: 1. Extend a horizontal line from the current peak to the left and right until the line either reaches the window border (see `wlen`) or intersects the signal again at the slope of a higher peak. An intersection with a peak of the same height is ignored. 2. On each side find the minimal signal value within the interval defined above. These points are the peak's bases. 3. The higher one of the two bases marks the peak's lowest contour line. The prominence can then be calculated as the vertical difference between the peaks height itself and its lowest contour line. Searching for the peak's bases can be slow for large `x` with periodic behavior because large chunks or even the full signal need to be evaluated for the first algorithmic step. This evaluation area can be limited with the parameter `wlen` which restricts the algorithm to a window around the current peak and can shorten the calculation time if the window length is short in relation to `x`. However this may stop the algorithm from finding the true global contour line if the peak's true bases are outside this window. Instead a higher contour line is found within the restricted window leading to a smaller calculated prominence. In practice this is only relevant for the highest set of peaks in `x`. This behavior may even be used intentionally to calculate "local" prominences. .. versionadded:: 1.1.0 References ---------- .. [1] Wikipedia Article for Topographic Prominence: https://en.wikipedia.org/wiki/Topographic_prominence Examples -------- >>> from scipy.signal import find_peaks, peak_prominences >>> import matplotlib.pyplot as plt Create a test signal with two overlayed harmonics >>> x = np.linspace(0, 6 * np.pi, 1000) >>> x = np.sin(x) + 0.6 * np.sin(2.6 * x) Find all peaks and calculate prominences >>> peaks, _ = find_peaks(x) >>> prominences = peak_prominences(x, peaks)[0] >>> prominences array([1.24159486, 0.47840168, 0.28470524, 3.10716793, 0.284603 , 0.47822491, 2.48340261, 0.47822491]) Calculate the height of each peak's contour line and plot the results >>> contour_heights = x[peaks] - prominences >>> plt.plot(x) >>> plt.plot(peaks, x[peaks], "x") >>> plt.vlines(x=peaks, ymin=contour_heights, ymax=x[peaks]) >>> plt.show() Let's evaluate a second example that demonstrates several edge cases for one peak at index 5. >>> x = np.array([0, 1, 0, 3, 1, 3, 0, 4, 0]) >>> peaks = np.array([5]) >>> plt.plot(x) >>> plt.plot(peaks, x[peaks], "x") >>> plt.show() >>> peak_prominences(x, peaks) # -> (prominences, left_bases, right_bases) (array([3.]), array([2]), array([6])) Note how the peak at index 3 of the same height is not considered as a border while searching for the left base. Instead two minima at 0 and 2 are found in which case the one closer to the evaluated peak is always chosen. On the right side however the base must be placed at 6 because the higher peak represents the right border to the evaluated area. >>> peak_prominences(x, peaks, wlen=3.1) (array([2.]), array([4]), array([6])) Here we restricted the algorithm to a window from 3 to 7 (the length is 5 samples because `wlen` was rounded up to the next odd integer). Thus the only two candidates in the evaluated area are the two neighbouring samples and a smaller prominence is calculated.
Calculate the prominence of each peak in a signal.
[ "Calculate", "the", "prominence", "of", "each", "peak", "in", "a", "signal", "." ]
def peak_prominences(x, peaks, wlen=None): """ Calculate the prominence of each peak in a signal. The prominence of a peak measures how much a peak stands out from the surrounding baseline of the signal and is defined as the vertical distance between the peak and its lowest contour line. Parameters ---------- x : sequence A signal with peaks. peaks : sequence Indices of peaks in `x`. wlen : int, optional A window length in samples that optionally limits the evaluated area for each peak to a subset of `x`. The peak is always placed in the middle of the window therefore the given length is rounded up to the next odd integer. This parameter can speed up the calculation (see Notes). Returns ------- prominences : ndarray The calculated prominences for each peak in `peaks`. left_bases, right_bases : ndarray The peaks' bases as indices in `x` to the left and right of each peak. The higher base of each pair is a peak's lowest contour line. Raises ------ ValueError If a value in `peaks` is an invalid index for `x`. Warns ----- PeakPropertyWarning For indices in `peaks` that don't point to valid local maxima in `x` the returned prominence will be 0 and this warning is raised. This also happens if `wlen` is smaller than the plateau size of a peak. Warnings -------- This function may return unexpected results for data containing NaNs. To avoid this, NaNs should either be removed or replaced. See Also -------- find_peaks Find peaks inside a signal based on peak properties. peak_widths Calculate the width of peaks. Notes ----- Strategy to compute a peak's prominence: 1. Extend a horizontal line from the current peak to the left and right until the line either reaches the window border (see `wlen`) or intersects the signal again at the slope of a higher peak. An intersection with a peak of the same height is ignored. 2. On each side find the minimal signal value within the interval defined above. These points are the peak's bases. 3. The higher one of the two bases marks the peak's lowest contour line. The prominence can then be calculated as the vertical difference between the peaks height itself and its lowest contour line. Searching for the peak's bases can be slow for large `x` with periodic behavior because large chunks or even the full signal need to be evaluated for the first algorithmic step. This evaluation area can be limited with the parameter `wlen` which restricts the algorithm to a window around the current peak and can shorten the calculation time if the window length is short in relation to `x`. However this may stop the algorithm from finding the true global contour line if the peak's true bases are outside this window. Instead a higher contour line is found within the restricted window leading to a smaller calculated prominence. In practice this is only relevant for the highest set of peaks in `x`. This behavior may even be used intentionally to calculate "local" prominences. .. versionadded:: 1.1.0 References ---------- .. [1] Wikipedia Article for Topographic Prominence: https://en.wikipedia.org/wiki/Topographic_prominence Examples -------- >>> from scipy.signal import find_peaks, peak_prominences >>> import matplotlib.pyplot as plt Create a test signal with two overlayed harmonics >>> x = np.linspace(0, 6 * np.pi, 1000) >>> x = np.sin(x) + 0.6 * np.sin(2.6 * x) Find all peaks and calculate prominences >>> peaks, _ = find_peaks(x) >>> prominences = peak_prominences(x, peaks)[0] >>> prominences array([1.24159486, 0.47840168, 0.28470524, 3.10716793, 0.284603 , 0.47822491, 2.48340261, 0.47822491]) Calculate the height of each peak's contour line and plot the results >>> contour_heights = x[peaks] - prominences >>> plt.plot(x) >>> plt.plot(peaks, x[peaks], "x") >>> plt.vlines(x=peaks, ymin=contour_heights, ymax=x[peaks]) >>> plt.show() Let's evaluate a second example that demonstrates several edge cases for one peak at index 5. >>> x = np.array([0, 1, 0, 3, 1, 3, 0, 4, 0]) >>> peaks = np.array([5]) >>> plt.plot(x) >>> plt.plot(peaks, x[peaks], "x") >>> plt.show() >>> peak_prominences(x, peaks) # -> (prominences, left_bases, right_bases) (array([3.]), array([2]), array([6])) Note how the peak at index 3 of the same height is not considered as a border while searching for the left base. Instead two minima at 0 and 2 are found in which case the one closer to the evaluated peak is always chosen. On the right side however the base must be placed at 6 because the higher peak represents the right border to the evaluated area. >>> peak_prominences(x, peaks, wlen=3.1) (array([2.]), array([4]), array([6])) Here we restricted the algorithm to a window from 3 to 7 (the length is 5 samples because `wlen` was rounded up to the next odd integer). Thus the only two candidates in the evaluated area are the two neighbouring samples and a smaller prominence is calculated. """ x = _arg_x_as_expected(x) peaks = _arg_peaks_as_expected(peaks) wlen = _arg_wlen_as_expected(wlen) return _peak_prominences(x, peaks, wlen)
[ "def", "peak_prominences", "(", "x", ",", "peaks", ",", "wlen", "=", "None", ")", ":", "x", "=", "_arg_x_as_expected", "(", "x", ")", "peaks", "=", "_arg_peaks_as_expected", "(", "peaks", ")", "wlen", "=", "_arg_wlen_as_expected", "(", "wlen", ")", "return...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/signal/_peak_finding.py#L322-L462
panda3d/panda3d
833ad89ebad58395d0af0b7ec08538e5e4308265
direct/src/showbase/VFSImporter.py
python
VFSLoader._compile
(self, filename, source)
return code
Compiles the Python source code to a code object and attempts to write it to an appropriate .pyc file. May raise SyntaxError or other errors generated by the compiler.
Compiles the Python source code to a code object and attempts to write it to an appropriate .pyc file. May raise SyntaxError or other errors generated by the compiler.
[ "Compiles", "the", "Python", "source", "code", "to", "a", "code", "object", "and", "attempts", "to", "write", "it", "to", "an", "appropriate", ".", "pyc", "file", ".", "May", "raise", "SyntaxError", "or", "other", "errors", "generated", "by", "the", "compi...
def _compile(self, filename, source): """ Compiles the Python source code to a code object and attempts to write it to an appropriate .pyc file. May raise SyntaxError or other errors generated by the compiler. """ if source and source[-1] != '\n': source = source + '\n' code = compile(source, filename.toOsSpecific(), 'exec') # try to cache the compiled code pycFilename = Filename(filename) pycFilename.setExtension(compiledExtensions[0]) try: f = open(pycFilename.toOsSpecific(), 'wb') except IOError: pass else: f.write(imp.get_magic()) f.write((self.timestamp & 0xffffffff).to_bytes(4, 'little')) f.write(b'\0\0\0\0') f.write(marshal.dumps(code)) f.close() return code
[ "def", "_compile", "(", "self", ",", "filename", ",", "source", ")", ":", "if", "source", "and", "source", "[", "-", "1", "]", "!=", "'\\n'", ":", "source", "=", "source", "+", "'\\n'", "code", "=", "compile", "(", "source", ",", "filename", ".", "...
https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/showbase/VFSImporter.py#L302-L325
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/ao/quantization/fx/quantization_patterns.py
python
QuantizeHandler.should_insert_observer_for_output
( self, qconfig: Any, model_is_training: bool, )
return self.all_node_args_are_tensors and self.input_output_observed()
Returns true if an observer should be inserted for the output of the pattern matched to this QuantizeHandler instance during the prepare step.
Returns true if an observer should be inserted for the output of the pattern matched to this QuantizeHandler instance during the prepare step.
[ "Returns", "true", "if", "an", "observer", "should", "be", "inserted", "for", "the", "output", "of", "the", "pattern", "matched", "to", "this", "QuantizeHandler", "instance", "during", "the", "prepare", "step", "." ]
def should_insert_observer_for_output( self, qconfig: Any, model_is_training: bool, ) -> bool: """ Returns true if an observer should be inserted for the output of the pattern matched to this QuantizeHandler instance during the prepare step. """ # TODO(future PR): potentially clean up and deduplicate these # mappings. return self.all_node_args_are_tensors and self.input_output_observed()
[ "def", "should_insert_observer_for_output", "(", "self", ",", "qconfig", ":", "Any", ",", "model_is_training", ":", "bool", ",", ")", "->", "bool", ":", "# TODO(future PR): potentially clean up and deduplicate these", "# mappings.", "return", "self", ".", "all_node_args_a...
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/ao/quantization/fx/quantization_patterns.py#L122-L134
plumonito/dtslam
5994bb9cf7a11981b830370db206bceb654c085d
3rdparty/opencv-git/3rdparty/jinja2/compiler.py
python
CodeGenerator.macro_body
(self, node, frame, children=None)
return frame
Dump the function def of a macro or call block.
Dump the function def of a macro or call block.
[ "Dump", "the", "function", "def", "of", "a", "macro", "or", "call", "block", "." ]
def macro_body(self, node, frame, children=None): """Dump the function def of a macro or call block.""" frame = self.function_scoping(node, frame, children) # macros are delayed, they never require output checks frame.require_output_check = False args = frame.arguments # XXX: this is an ugly fix for the loop nesting bug # (tests.test_old_bugs.test_loop_call_bug). This works around # a identifier nesting problem we have in general. It's just more # likely to happen in loops which is why we work around it. The # real solution would be "nonlocal" all the identifiers that are # leaking into a new python frame and might be used both unassigned # and assigned. if 'loop' in frame.identifiers.declared: args = args + ['l_loop=l_loop'] self.writeline('def macro(%s):' % ', '.join(args), node) self.indent() self.buffer(frame) self.pull_locals(frame) self.blockvisit(node.body, frame) self.return_buffer_contents(frame) self.outdent() return frame
[ "def", "macro_body", "(", "self", ",", "node", ",", "frame", ",", "children", "=", "None", ")", ":", "frame", "=", "self", ".", "function_scoping", "(", "node", ",", "frame", ",", "children", ")", "# macros are delayed, they never require output checks", "frame"...
https://github.com/plumonito/dtslam/blob/5994bb9cf7a11981b830370db206bceb654c085d/3rdparty/opencv-git/3rdparty/jinja2/compiler.py#L707-L729
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/models/rnn/ptb/reader.py
python
ptb_iterator
(raw_data, batch_size, num_steps)
Iterate on the raw PTB data. This generates batch_size pointers into the raw PTB data, and allows minibatch iteration along these pointers. Args: raw_data: one of the raw data outputs from ptb_raw_data. batch_size: int, the batch size. num_steps: int, the number of unrolls. Yields: Pairs of the batched data, each a matrix of shape [batch_size, num_steps]. The second element of the tuple is the same data time-shifted to the right by one. Raises: ValueError: if batch_size or num_steps are too high.
Iterate on the raw PTB data.
[ "Iterate", "on", "the", "raw", "PTB", "data", "." ]
def ptb_iterator(raw_data, batch_size, num_steps): """Iterate on the raw PTB data. This generates batch_size pointers into the raw PTB data, and allows minibatch iteration along these pointers. Args: raw_data: one of the raw data outputs from ptb_raw_data. batch_size: int, the batch size. num_steps: int, the number of unrolls. Yields: Pairs of the batched data, each a matrix of shape [batch_size, num_steps]. The second element of the tuple is the same data time-shifted to the right by one. Raises: ValueError: if batch_size or num_steps are too high. """ raw_data = np.array(raw_data, dtype=np.int32) data_len = len(raw_data) batch_len = data_len // batch_size data = np.zeros([batch_size, batch_len], dtype=np.int32) for i in range(batch_size): data[i] = raw_data[batch_len * i:batch_len * (i + 1)] epoch_size = (batch_len - 1) // num_steps if epoch_size == 0: raise ValueError("epoch_size == 0, decrease batch_size or num_steps") for i in range(epoch_size): x = data[:, i*num_steps:(i+1)*num_steps] y = data[:, i*num_steps+1:(i+1)*num_steps+1] yield (x, y)
[ "def", "ptb_iterator", "(", "raw_data", ",", "batch_size", ",", "num_steps", ")", ":", "raw_data", "=", "np", ".", "array", "(", "raw_data", ",", "dtype", "=", "np", ".", "int32", ")", "data_len", "=", "len", "(", "raw_data", ")", "batch_len", "=", "da...
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/models/rnn/ptb/reader.py#L82-L117
nyuwireless-unipd/ns3-mmwave
4ff9e87e8079764e04cbeccd8e85bff15ae16fb3
utils/check-style.py
python
PatchChunkLine.write
(self, f)
! Write to file @param self The current class @param f file @return exception if invalid type
! Write to file
[ "!", "Write", "to", "file" ]
def write(self, f): """! Write to file @param self The current class @param f file @return exception if invalid type """ if self.__type == self.SRC: f.write('-%s\n' % self.__line) elif self.__type == self.DST: f.write('+%s\n' % self.__line) elif self.__type == self.BOTH: f.write(' %s\n' % self.__line) else: raise Exception('invalid patch')
[ "def", "write", "(", "self", ",", "f", ")", ":", "if", "self", ".", "__type", "==", "self", ".", "SRC", ":", "f", ".", "write", "(", "'-%s\\n'", "%", "self", ".", "__line", ")", "elif", "self", ".", "__type", "==", "self", ".", "DST", ":", "f",...
https://github.com/nyuwireless-unipd/ns3-mmwave/blob/4ff9e87e8079764e04cbeccd8e85bff15ae16fb3/utils/check-style.py#L204-L217
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/inspect.py
python
getabsfile
(object, _filename=None)
return os.path.normcase(os.path.abspath(_filename))
Return an absolute path to the source or compiled file for an object. The idea is for each object to have a unique origin, so this routine normalizes the result as much as possible.
Return an absolute path to the source or compiled file for an object.
[ "Return", "an", "absolute", "path", "to", "the", "source", "or", "compiled", "file", "for", "an", "object", "." ]
def getabsfile(object, _filename=None): """Return an absolute path to the source or compiled file for an object. The idea is for each object to have a unique origin, so this routine normalizes the result as much as possible.""" if _filename is None: _filename = getsourcefile(object) or getfile(object) return os.path.normcase(os.path.abspath(_filename))
[ "def", "getabsfile", "(", "object", ",", "_filename", "=", "None", ")", ":", "if", "_filename", "is", "None", ":", "_filename", "=", "getsourcefile", "(", "object", ")", "or", "getfile", "(", "object", ")", "return", "os", ".", "path", ".", "normcase", ...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/inspect.py#L460-L467
bigtreetech/BIGTREETECH-SKR-V1.3
b238aa402753e81d551b7d34a181a262a138ae9e
BTT SKR V1.4/Firmware/Marlin-bugfix-2.0.x-SKR-V1.4/Marlin/src/lcd/extui/lib/ftdi_eve_touch_ui/ftdi_eve_lib/extras/svg2cpp.py
python
Parser.process_svg_path_data
(self, id, d)
Breaks up the "d" attribute into individual commands and calls "process_svg_path_data_cmd" for each
Breaks up the "d" attribute into individual commands and calls "process_svg_path_data_cmd" for each
[ "Breaks", "up", "the", "d", "attribute", "into", "individual", "commands", "and", "calls", "process_svg_path_data_cmd", "for", "each" ]
def process_svg_path_data(self, id, d): """Breaks up the "d" attribute into individual commands and calls "process_svg_path_data_cmd" for each""" self.d = d while (self.d): if self.eat_token('\s+'): pass # Just eat the spaces elif self.eat_token('([LMHVZlmhvz])'): cmd = self.m.group(1) # The following commands take no arguments if cmd == "Z" or cmd == "z": self.process_svg_path_data_cmd(id, cmd, 0, 0) elif self.eat_token('([CScsQqTtAa])'): print("Unsupported path data command:", self.m.group(1), "in path", id, "\n", file=sys.stderr) quit() elif self.eat_token('([ ,]*[-0-9e.]+)+'): # Process list of coordinates following command coords = re.split('[ ,]+', self.m.group(0)) # The following commands take two arguments if cmd == "L" or cmd == "l": while coords: self.process_svg_path_data_cmd(id, cmd, float(coords.pop(0)), float(coords.pop(0))) elif cmd == "M": while coords: self.process_svg_path_data_cmd(id, cmd, float(coords.pop(0)), float(coords.pop(0))) # If a MOVETO has multiple points, the subsequent ones are assumed to be LINETO cmd = "L" elif cmd == "m": while coords: self.process_svg_path_data_cmd(id, cmd, float(coords.pop(0)), float(coords.pop(0))) # If a MOVETO has multiple points, the subsequent ones are assumed to be LINETO cmd = "l" # Assume all other commands are single argument else: while coords: self.process_svg_path_data_cmd(id, cmd, float(coords.pop(0)), 0) else: print("Syntax error:", d, "in path", id, "\n", file=sys.stderr) quit()
[ "def", "process_svg_path_data", "(", "self", ",", "id", ",", "d", ")", ":", "self", ".", "d", "=", "d", "while", "(", "self", ".", "d", ")", ":", "if", "self", ".", "eat_token", "(", "'\\s+'", ")", ":", "pass", "# Just eat the spaces", "elif", "self"...
https://github.com/bigtreetech/BIGTREETECH-SKR-V1.3/blob/b238aa402753e81d551b7d34a181a262a138ae9e/BTT SKR V1.4/Firmware/Marlin-bugfix-2.0.x-SKR-V1.4/Marlin/src/lcd/extui/lib/ftdi_eve_touch_ui/ftdi_eve_lib/extras/svg2cpp.py#L198-L240
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/email/feedparser.py
python
FeedParser.__init__
(self, _factory=message.Message)
_factory is called with no arguments to create a new message obj
_factory is called with no arguments to create a new message obj
[ "_factory", "is", "called", "with", "no", "arguments", "to", "create", "a", "new", "message", "obj" ]
def __init__(self, _factory=message.Message): """_factory is called with no arguments to create a new message obj""" self._factory = _factory self._input = BufferedSubFile() self._msgstack = [] self._parse = self._parsegen().next self._cur = None self._last = None self._headersonly = False
[ "def", "__init__", "(", "self", ",", "_factory", "=", "message", ".", "Message", ")", ":", "self", ".", "_factory", "=", "_factory", "self", ".", "_input", "=", "BufferedSubFile", "(", ")", "self", ".", "_msgstack", "=", "[", "]", "self", ".", "_parse"...
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/email/feedparser.py#L136-L144
thpatch/thcrap
9a0ebc52ebc775d93a44ddfe19d1bed0c512958f
scripts/repo_update.py
python
patch_files_walk
(repo_top, path, ignored)
Yields string for every valid patch file in [path] whose file name does not match the wildmatch patterns in [ignored], treated relative to [repo_top]. If another `thcrap_ignore.txt` is found along the directory hierarchy, its contents are added to a copy of [ignored], which is then used for this directory and its subdirectories.
Yields string for every valid patch file in [path] whose file name does not match the wildmatch patterns in [ignored], treated relative to [repo_top]. If another `thcrap_ignore.txt` is found along the directory hierarchy, its contents are added to a copy of [ignored], which is then used for this directory and its subdirectories.
[ "Yields", "string", "for", "every", "valid", "patch", "file", "in", "[", "path", "]", "whose", "file", "name", "does", "not", "match", "the", "wildmatch", "patterns", "in", "[", "ignored", "]", "treated", "relative", "to", "[", "repo_top", "]", ".", "If"...
def patch_files_walk(repo_top, path, ignored): """Yields string for every valid patch file in [path] whose file name does not match the wildmatch patterns in [ignored], treated relative to [repo_top]. If another `thcrap_ignore.txt` is found along the directory hierarchy, its contents are added to a copy of [ignored], which is then used for this directory and its subdirectories.""" local_ignore = thcrap_ignore_get(path) if len(local_ignore) >= 1: ignored = set(ignored).union(local_ignore) spec = PathSpec.from_lines('gitwildmatch', ignored) for i in os.scandir(path): if spec.match_file(os.path.relpath(i.path, repo_top)) == False: if i.is_dir(): yield from patch_files_walk(repo_top, i.path, ignored) else: yield i.path
[ "def", "patch_files_walk", "(", "repo_top", ",", "path", ",", "ignored", ")", ":", "local_ignore", "=", "thcrap_ignore_get", "(", "path", ")", "if", "len", "(", "local_ignore", ")", ">=", "1", ":", "ignored", "=", "set", "(", "ignored", ")", ".", "union"...
https://github.com/thpatch/thcrap/blob/9a0ebc52ebc775d93a44ddfe19d1bed0c512958f/scripts/repo_update.py#L79-L96
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/client/session.py
python
SessionInterface.partial_run
(self, handle, fetches, feed_dict=None)
Continues the execution with additional feeds and fetches.
Continues the execution with additional feeds and fetches.
[ "Continues", "the", "execution", "with", "additional", "feeds", "and", "fetches", "." ]
def partial_run(self, handle, fetches, feed_dict=None): """Continues the execution with additional feeds and fetches.""" raise NotImplementedError('partial_run')
[ "def", "partial_run", "(", "self", ",", "handle", ",", "fetches", ",", "feed_dict", "=", "None", ")", ":", "raise", "NotImplementedError", "(", "'partial_run'", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/client/session.py#L72-L74
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/framework/config.py
python
get_logical_device_configuration
(device)
return context.context().get_logical_device_configuration(device)
Get the virtual device configuration for a `tf.config.PhysicalDevice`. Returns the list of `tf.config.LogicalDeviceConfiguration` objects previously configured by a call to `tf.config.set_logical_device_configuration`. For example: >>> physical_devices = tf.config.list_physical_devices('CPU') >>> assert len(physical_devices) == 1, "No CPUs found" >>> configs = tf.config.get_logical_device_configuration( ... physical_devices[0]) >>> try: ... assert configs is None ... tf.config.set_logical_device_configuration( ... physical_devices[0], ... [tf.config.LogicalDeviceConfiguration(), ... tf.config.LogicalDeviceConfiguration()]) ... configs = tf.config.get_logical_device_configuration( ... physical_devices[0]) ... assert len(configs) == 2 ... except: ... # Cannot modify virtual devices once initialized. ... pass Args: device: `PhysicalDevice` to query Returns: List of `tf.config.LogicalDeviceConfiguration` objects or `None` if no virtual device configuration has been set for this physical device.
Get the virtual device configuration for a `tf.config.PhysicalDevice`.
[ "Get", "the", "virtual", "device", "configuration", "for", "a", "tf", ".", "config", ".", "PhysicalDevice", "." ]
def get_logical_device_configuration(device): """Get the virtual device configuration for a `tf.config.PhysicalDevice`. Returns the list of `tf.config.LogicalDeviceConfiguration` objects previously configured by a call to `tf.config.set_logical_device_configuration`. For example: >>> physical_devices = tf.config.list_physical_devices('CPU') >>> assert len(physical_devices) == 1, "No CPUs found" >>> configs = tf.config.get_logical_device_configuration( ... physical_devices[0]) >>> try: ... assert configs is None ... tf.config.set_logical_device_configuration( ... physical_devices[0], ... [tf.config.LogicalDeviceConfiguration(), ... tf.config.LogicalDeviceConfiguration()]) ... configs = tf.config.get_logical_device_configuration( ... physical_devices[0]) ... assert len(configs) == 2 ... except: ... # Cannot modify virtual devices once initialized. ... pass Args: device: `PhysicalDevice` to query Returns: List of `tf.config.LogicalDeviceConfiguration` objects or `None` if no virtual device configuration has been set for this physical device. """ return context.context().get_logical_device_configuration(device)
[ "def", "get_logical_device_configuration", "(", "device", ")", ":", "return", "context", ".", "context", "(", ")", ".", "get_logical_device_configuration", "(", "device", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/framework/config.py#L765-L799
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/richtext.py
python
RichTextParagraph.MoveToList
(*args, **kwargs)
return _richtext.RichTextParagraph_MoveToList(*args, **kwargs)
MoveToList(self, RichTextObject obj, wxList list)
MoveToList(self, RichTextObject obj, wxList list)
[ "MoveToList", "(", "self", "RichTextObject", "obj", "wxList", "list", ")" ]
def MoveToList(*args, **kwargs): """MoveToList(self, RichTextObject obj, wxList list)""" return _richtext.RichTextParagraph_MoveToList(*args, **kwargs)
[ "def", "MoveToList", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextParagraph_MoveToList", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L2007-L2009
casadi/casadi
8d0f80a4d0fe2054384bfb9748f7a0f6bae540ff
misc/cpplint.py
python
_NestingState.CheckCompletedBlocks
(self, filename, error)
Checks that all classes and namespaces have been completely parsed. Call this when all lines in a file have been processed. Args: filename: The name of the current file. error: The function to call with any errors found.
Checks that all classes and namespaces have been completely parsed.
[ "Checks", "that", "all", "classes", "and", "namespaces", "have", "been", "completely", "parsed", "." ]
def CheckCompletedBlocks(self, filename, error): """Checks that all classes and namespaces have been completely parsed. Call this when all lines in a file have been processed. Args: filename: The name of the current file. error: The function to call with any errors found. """ # Note: This test can result in false positives if #ifdef constructs # get in the way of brace matching. See the testBuildClass test in # cpplint_unittest.py for an example of this. for obj in self.stack: if isinstance(obj, _ClassInfo): error(filename, obj.starting_linenum, 'build/class', 5, 'Failed to find complete declaration of class %s' % obj.name) elif isinstance(obj, _NamespaceInfo): error(filename, obj.starting_linenum, 'build/namespaces', 5, 'Failed to find complete declaration of namespace %s' % obj.name)
[ "def", "CheckCompletedBlocks", "(", "self", ",", "filename", ",", "error", ")", ":", "# Note: This test can result in false positives if #ifdef constructs", "# get in the way of brace matching. See the testBuildClass test in", "# cpplint_unittest.py for an example of this.", "for", "obj"...
https://github.com/casadi/casadi/blob/8d0f80a4d0fe2054384bfb9748f7a0f6bae540ff/misc/cpplint.py#L2065-L2084
nsnam/ns-3-dev-git
efdb2e21f45c0a87a60b47c547b68fa140a7b686
utils/grid.py
python
GraphicRenderer.get_data_rectangle
(self)
return(x_start, y_start, self.__width - x_start, self.__data.get_height())
! Get Data Rectangle @param self this object @return rectangle
! Get Data Rectangle
[ "!", "Get", "Data", "Rectangle" ]
def get_data_rectangle(self): """! Get Data Rectangle @param self this object @return rectangle """ y_start = self.__top_legend.get_height() x_start = self.__data.get_data_x_start() return(x_start, y_start, self.__width - x_start, self.__data.get_height())
[ "def", "get_data_rectangle", "(", "self", ")", ":", "y_start", "=", "self", ".", "__top_legend", ".", "get_height", "(", ")", "x_start", "=", "self", ".", "__data", ".", "get_data_x_start", "(", ")", "return", "(", "x_start", ",", "y_start", ",", "self", ...
https://github.com/nsnam/ns-3-dev-git/blob/efdb2e21f45c0a87a60b47c547b68fa140a7b686/utils/grid.py#L1021-L1028
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
BookCtrlBase.HitTest
(*args, **kwargs)
return _core_.BookCtrlBase_HitTest(*args, **kwargs)
HitTest(Point pt) -> (tab, where) Returns the page/tab which is hit, and flags indicating where using wx.NB_HITTEST flags.
HitTest(Point pt) -> (tab, where)
[ "HitTest", "(", "Point", "pt", ")", "-", ">", "(", "tab", "where", ")" ]
def HitTest(*args, **kwargs): """ HitTest(Point pt) -> (tab, where) Returns the page/tab which is hit, and flags indicating where using wx.NB_HITTEST flags. """ return _core_.BookCtrlBase_HitTest(*args, **kwargs)
[ "def", "HitTest", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "BookCtrlBase_HitTest", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L13645-L13652
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/urllib3/util/timeout.py
python
Timeout.clone
(self)
return Timeout(connect=self._connect, read=self._read, total=self.total)
Create a copy of the timeout object Timeout properties are stored per-pool but each request needs a fresh Timeout object to ensure each one has its own start/stop configured. :return: a copy of the timeout object :rtype: :class:`Timeout`
Create a copy of the timeout object
[ "Create", "a", "copy", "of", "the", "timeout", "object" ]
def clone(self): """ Create a copy of the timeout object Timeout properties are stored per-pool but each request needs a fresh Timeout object to ensure each one has its own start/stop configured. :return: a copy of the timeout object :rtype: :class:`Timeout` """ # We can't use copy.deepcopy because that will also create a new object # for _GLOBAL_DEFAULT_TIMEOUT, which socket.py uses as a sentinel to # detect the user default. return Timeout(connect=self._connect, read=self._read, total=self.total)
[ "def", "clone", "(", "self", ")", ":", "# We can't use copy.deepcopy because that will also create a new object", "# for _GLOBAL_DEFAULT_TIMEOUT, which socket.py uses as a sentinel to", "# detect the user default.", "return", "Timeout", "(", "connect", "=", "self", ".", "_connect", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/urllib3/util/timeout.py#L156-L169
netket/netket
0d534e54ecbf25b677ea72af6b85947979420652
netket/optimizer/qgt/qgt_jacobian_dense_logic.py
python
stack_jacobian_tuple
(ok_re_im)
return res
stack the real and imaginary parts of ΔOⱼₖ along a new axis. First all the real part then the imaginary part. Re[S] = Re[(ΔOᵣ + i ΔOᵢ)ᴴ(ΔOᵣ + i ΔOᵢ)] = ΔOᵣᵀ ΔOᵣ + ΔOᵢᵀ ΔOᵢ = [ΔOᵣ ΔOᵢ]ᵀ [ΔOᵣ ΔOᵢ] Args: ok_re_im : a tuple (ΔOᵣ, ΔOᵢ) of two PyTrees representing the real and imag part of ΔOⱼₖ
stack the real and imaginary parts of ΔOⱼₖ along a new axis. First all the real part then the imaginary part.
[ "stack", "the", "real", "and", "imaginary", "parts", "of", "ΔOⱼₖ", "along", "a", "new", "axis", ".", "First", "all", "the", "real", "part", "then", "the", "imaginary", "part", "." ]
def stack_jacobian_tuple(ok_re_im): """ stack the real and imaginary parts of ΔOⱼₖ along a new axis. First all the real part then the imaginary part. Re[S] = Re[(ΔOᵣ + i ΔOᵢ)ᴴ(ΔOᵣ + i ΔOᵢ)] = ΔOᵣᵀ ΔOᵣ + ΔOᵢᵀ ΔOᵢ = [ΔOᵣ ΔOᵢ]ᵀ [ΔOᵣ ΔOᵢ] Args: ok_re_im : a tuple (ΔOᵣ, ΔOᵢ) of two PyTrees representing the real and imag part of ΔOⱼₖ """ re, im = ok_re_im re_dense = ravel(re) im_dense = ravel(im) res = jnp.stack([re_dense, im_dense], axis=0) return res
[ "def", "stack_jacobian_tuple", "(", "ok_re_im", ")", ":", "re", ",", "im", "=", "ok_re_im", "re_dense", "=", "ravel", "(", "re", ")", "im_dense", "=", "ravel", "(", "im", ")", "res", "=", "jnp", ".", "stack", "(", "[", "re_dense", ",", "im_dense", "]...
https://github.com/netket/netket/blob/0d534e54ecbf25b677ea72af6b85947979420652/netket/optimizer/qgt/qgt_jacobian_dense_logic.py#L157-L173
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/perf_insights/third_party/cloudstorage/storage_api.py
python
ReadBuffer._get_segment
(self, start, request_size, check_response=True)
Get a segment of the file from Google Storage. Args: start: start offset of the segment. Inclusive. Have to be within the range of the file. request_size: number of bytes to request. Have to be small enough for a single urlfetch request. May go over the logical range of the file. check_response: True to check the validity of GCS response automatically before the future returns. False otherwise. See Yields section. Yields: If check_response is True, the segment [start, start + request_size) of the file. Otherwise, a tuple. The first element is the unverified file segment. The second element is a closure that checks response. Caller should first invoke the closure before consuing the file segment. Raises: ValueError: if the file has changed while reading.
Get a segment of the file from Google Storage.
[ "Get", "a", "segment", "of", "the", "file", "from", "Google", "Storage", "." ]
def _get_segment(self, start, request_size, check_response=True): """Get a segment of the file from Google Storage. Args: start: start offset of the segment. Inclusive. Have to be within the range of the file. request_size: number of bytes to request. Have to be small enough for a single urlfetch request. May go over the logical range of the file. check_response: True to check the validity of GCS response automatically before the future returns. False otherwise. See Yields section. Yields: If check_response is True, the segment [start, start + request_size) of the file. Otherwise, a tuple. The first element is the unverified file segment. The second element is a closure that checks response. Caller should first invoke the closure before consuing the file segment. Raises: ValueError: if the file has changed while reading. """ end = start + request_size - 1 content_range = '%d-%d' % (start, end) headers = {'Range': 'bytes=' + content_range} status, resp_headers, content = yield self._api.get_object_async( self._path, headers=headers) def _checker(): errors.check_status(status, [200, 206], self._path, headers, resp_headers, body=content) self._check_etag(resp_headers.get('etag')) if check_response: _checker() raise ndb.Return(content) raise ndb.Return(content, _checker)
[ "def", "_get_segment", "(", "self", ",", "start", ",", "request_size", ",", "check_response", "=", "True", ")", ":", "end", "=", "start", "+", "request_size", "-", "1", "content_range", "=", "'%d-%d'", "%", "(", "start", ",", "end", ")", "headers", "=", ...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/perf_insights/third_party/cloudstorage/storage_api.py#L418-L452
commaai/openpilot
4416c21b1e738ab7d04147c5ae52b5135e0cdb40
common/logging_extra.py
python
SwagLogger.findCaller
(self, stack_info=False, stacklevel=1)
return rv
Find the stack frame of the caller so that we can note the source file name, line number and function name.
Find the stack frame of the caller so that we can note the source file name, line number and function name.
[ "Find", "the", "stack", "frame", "of", "the", "caller", "so", "that", "we", "can", "note", "the", "source", "file", "name", "line", "number", "and", "function", "name", "." ]
def findCaller(self, stack_info=False, stacklevel=1): """ Find the stack frame of the caller so that we can note the source file name, line number and function name. """ f = sys._getframe(3) #On some versions of IronPython, currentframe() returns None if #IronPython isn't run with -X:Frames. if f is not None: f = f.f_back orig_f = f while f and stacklevel > 1: f = f.f_back stacklevel -= 1 if not f: f = orig_f rv = "(unknown file)", 0, "(unknown function)", None while hasattr(f, "f_code"): co = f.f_code filename = os.path.normcase(co.co_filename) # TODO: is this pylint exception correct? if filename == _srcfile: # pylint: disable=comparison-with-callable f = f.f_back continue sinfo = None if stack_info: sio = io.StringIO() sio.write('Stack (most recent call last):\n') traceback.print_stack(f, file=sio) sinfo = sio.getvalue() if sinfo[-1] == '\n': sinfo = sinfo[:-1] sio.close() rv = (co.co_filename, f.f_lineno, co.co_name, sinfo) break return rv
[ "def", "findCaller", "(", "self", ",", "stack_info", "=", "False", ",", "stacklevel", "=", "1", ")", ":", "f", "=", "sys", ".", "_getframe", "(", "3", ")", "#On some versions of IronPython, currentframe() returns None if", "#IronPython isn't run with -X:Frames.", "if"...
https://github.com/commaai/openpilot/blob/4416c21b1e738ab7d04147c5ae52b5135e0cdb40/common/logging_extra.py#L166-L202
xhzdeng/crpn
a5aef0f80dbe486103123f740c634fb01e6cc9a1
lib/transform/torch_image_transform_layer.py
python
TorchImageTransformLayer.reshape
(self, bottom, top)
Reshaping happens during the call to forward.
Reshaping happens during the call to forward.
[ "Reshaping", "happens", "during", "the", "call", "to", "forward", "." ]
def reshape(self, bottom, top): """Reshaping happens during the call to forward.""" pass
[ "def", "reshape", "(", "self", ",", "bottom", ",", "top", ")", ":", "pass" ]
https://github.com/xhzdeng/crpn/blob/a5aef0f80dbe486103123f740c634fb01e6cc9a1/lib/transform/torch_image_transform_layer.py#L62-L64
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/aui/auibook.py
python
CommandNotebookEvent.SetDispatched
(self, b)
Sets the event as dispatched (used for automatic :class:`AuiNotebook` ). :param `b`: whether the event was dispatched or not.
Sets the event as dispatched (used for automatic :class:`AuiNotebook` ).
[ "Sets", "the", "event", "as", "dispatched", "(", "used", "for", "automatic", ":", "class", ":", "AuiNotebook", ")", "." ]
def SetDispatched(self, b): """ Sets the event as dispatched (used for automatic :class:`AuiNotebook` ). :param `b`: whether the event was dispatched or not. """ self.dispatched = b
[ "def", "SetDispatched", "(", "self", ",", "b", ")", ":", "self", ".", "dispatched", "=", "b" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/auibook.py#L448-L455
qgis/QGIS
15a77662d4bb712184f6aa60d0bd663010a76a75
python/plugins/processing/gui/wrappers.py
python
EnumWidgetWrapper.__init__
(self, *args, **kwargs)
.. deprecated:: 3.4 Do not use, will be removed in QGIS 4.0
.. deprecated:: 3.4 Do not use, will be removed in QGIS 4.0
[ "..", "deprecated", "::", "3", ".", "4", "Do", "not", "use", "will", "be", "removed", "in", "QGIS", "4", ".", "0" ]
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) """ .. deprecated:: 3.4 Do not use, will be removed in QGIS 4.0 """ from warnings import warn warn("EnumWidgetWrapper is deprecated and will be removed in QGIS 4.0", DeprecationWarning)
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "super", "(", ")", ".", "__init__", "(", "*", "args", ",", "*", "*", "kwargs", ")", "from", "warnings", "import", "warn", "warn", "(", "\"EnumWidgetWrapper is deprecat...
https://github.com/qgis/QGIS/blob/15a77662d4bb712184f6aa60d0bd663010a76a75/python/plugins/processing/gui/wrappers.py#L1109-L1117
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/distlib/util.py
python
parse_name_and_version
(p)
return d['name'].strip().lower(), d['ver']
A utility method used to get name and version from a string. From e.g. a Provides-Dist value. :param p: A value in a form 'foo (1.0)' :return: The name and version as a tuple.
A utility method used to get name and version from a string.
[ "A", "utility", "method", "used", "to", "get", "name", "and", "version", "from", "a", "string", "." ]
def parse_name_and_version(p): """ A utility method used to get name and version from a string. From e.g. a Provides-Dist value. :param p: A value in a form 'foo (1.0)' :return: The name and version as a tuple. """ m = NAME_VERSION_RE.match(p) if not m: raise DistlibException('Ill-formed name/version string: \'%s\'' % p) d = m.groupdict() return d['name'].strip().lower(), d['ver']
[ "def", "parse_name_and_version", "(", "p", ")", ":", "m", "=", "NAME_VERSION_RE", ".", "match", "(", "p", ")", "if", "not", "m", ":", "raise", "DistlibException", "(", "'Ill-formed name/version string: \\'%s\\''", "%", "p", ")", "d", "=", "m", ".", "groupdic...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/distlib/util.py#L867-L880
CaoWGG/TensorRT-CenterNet
f949252e37b51e60f873808f46d3683f15735e79
onnx-tensorrt/third_party/onnx/third_party/pybind11/tools/clang/cindex.py
python
Cursor.enum_type
(self)
return self._enum_type
Return the integer type of an enum declaration. Returns a Type corresponding to an integer. If the cursor is not for an enum, this raises.
Return the integer type of an enum declaration.
[ "Return", "the", "integer", "type", "of", "an", "enum", "declaration", "." ]
def enum_type(self): """Return the integer type of an enum declaration. Returns a Type corresponding to an integer. If the cursor is not for an enum, this raises. """ if not hasattr(self, '_enum_type'): assert self.kind == CursorKind.ENUM_DECL self._enum_type = conf.lib.clang_getEnumDeclIntegerType(self) return self._enum_type
[ "def", "enum_type", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_enum_type'", ")", ":", "assert", "self", ".", "kind", "==", "CursorKind", ".", "ENUM_DECL", "self", ".", "_enum_type", "=", "conf", ".", "lib", ".", "clang_getEnumDec...
https://github.com/CaoWGG/TensorRT-CenterNet/blob/f949252e37b51e60f873808f46d3683f15735e79/onnx-tensorrt/third_party/onnx/third_party/pybind11/tools/clang/cindex.py#L1518-L1528
bigartm/bigartm
47e37f982de87aa67bfd475ff1f39da696b181b3
3rdparty/protobuf-3.0.0/python/mox.py
python
MockMethod._CheckAndCreateNewGroup
(self, group_name, group_class)
return self
Checks if the last method (a possible group) is an instance of our group_class. Adds the current method to this group or creates a new one. Args: group_name: the name of the group. group_class: the class used to create instance of this new group
Checks if the last method (a possible group) is an instance of our group_class. Adds the current method to this group or creates a new one.
[ "Checks", "if", "the", "last", "method", "(", "a", "possible", "group", ")", "is", "an", "instance", "of", "our", "group_class", ".", "Adds", "the", "current", "method", "to", "this", "group", "or", "creates", "a", "new", "one", "." ]
def _CheckAndCreateNewGroup(self, group_name, group_class): """Checks if the last method (a possible group) is an instance of our group_class. Adds the current method to this group or creates a new one. Args: group_name: the name of the group. group_class: the class used to create instance of this new group """ group = self.GetPossibleGroup() # If this is a group, and it is the correct group, add the method. if isinstance(group, group_class) and group.group_name() == group_name: group.AddMethod(self) return self # Create a new group and add the method. new_group = group_class(group_name) new_group.AddMethod(self) self._call_queue.append(new_group) return self
[ "def", "_CheckAndCreateNewGroup", "(", "self", ",", "group_name", ",", "group_class", ")", ":", "group", "=", "self", ".", "GetPossibleGroup", "(", ")", "# If this is a group, and it is the correct group, add the method.", "if", "isinstance", "(", "group", ",", "group_c...
https://github.com/bigartm/bigartm/blob/47e37f982de87aa67bfd475ff1f39da696b181b3/3rdparty/protobuf-3.0.0/python/mox.py#L664-L684
Samsung/veles
95ed733c2e49bc011ad98ccf2416ecec23fbf352
veles/external/pydev/reload.py
python
Reload._update
(self, namespace, name, oldobj, newobj, is_class_namespace=False)
Update oldobj, if possible in place, with newobj. If oldobj is immutable, this simply returns newobj. Args: oldobj: the object to be updated newobj: the object used as the source for the update
Update oldobj, if possible in place, with newobj.
[ "Update", "oldobj", "if", "possible", "in", "place", "with", "newobj", "." ]
def _update(self, namespace, name, oldobj, newobj, is_class_namespace=False): """Update oldobj, if possible in place, with newobj. If oldobj is immutable, this simply returns newobj. Args: oldobj: the object to be updated newobj: the object used as the source for the update """ try: notify_info2('Updating: ', oldobj) if oldobj is newobj: # Probably something imported return if type(oldobj) is not type(newobj): # Cop-out: if the type changed, give up notify_error('Type of: %s changed... Skipping.' % (oldobj,)) return if isinstance(newobj, types.FunctionType): self._update_function(oldobj, newobj) return if isinstance(newobj, types.MethodType): self._update_method(oldobj, newobj) return if isinstance(newobj, classmethod): self._update_classmethod(oldobj, newobj) return if isinstance(newobj, staticmethod): self._update_staticmethod(oldobj, newobj) return if hasattr(types, 'ClassType'): classtype = (types.ClassType, type) #object is not instance of types.ClassType. else: classtype = type if isinstance(newobj, classtype): self._update_class(oldobj, newobj) return # New: dealing with metaclasses. if hasattr(newobj, '__metaclass__') and hasattr(newobj, '__class__') and newobj.__metaclass__ == newobj.__class__: self._update_class(oldobj, newobj) return if namespace is not None: if oldobj != newobj and str(oldobj) != str(newobj) and repr(oldobj) != repr(newobj): xreload_old_new = None if is_class_namespace: xreload_old_new = getattr(namespace, '__xreload_old_new__', None) if xreload_old_new is not None: self.found_change = True xreload_old_new(name, oldobj, newobj) elif '__xreload_old_new__' in namespace: xreload_old_new = namespace['__xreload_old_new__'] xreload_old_new(namespace, name, oldobj, newobj) self.found_change = True # Too much information to the user... # else: # notify_info0('%s NOT updated. Create __xreload_old_new__(name, old, new) for custom reload' % (name,)) except: notify_error('Exception found when updating %s. Proceeding for other items.' % (name,)) traceback.print_exc()
[ "def", "_update", "(", "self", ",", "namespace", ",", "name", ",", "oldobj", ",", "newobj", ",", "is_class_namespace", "=", "False", ")", ":", "try", ":", "notify_info2", "(", "'Updating: '", ",", "oldobj", ")", "if", "oldobj", "is", "newobj", ":", "# Pr...
https://github.com/Samsung/veles/blob/95ed733c2e49bc011ad98ccf2416ecec23fbf352/veles/external/pydev/reload.py#L297-L368
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/framework/ops.py
python
Tensor.consumers
(self)
return self._consumers
Returns a list of `Operation`s that consume this tensor. Returns: A list of `Operation`s.
Returns a list of `Operation`s that consume this tensor.
[ "Returns", "a", "list", "of", "Operation", "s", "that", "consume", "this", "tensor", "." ]
def consumers(self): """Returns a list of `Operation`s that consume this tensor. Returns: A list of `Operation`s. """ return self._consumers
[ "def", "consumers", "(", "self", ")", ":", "return", "self", ".", "_consumers" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/framework/ops.py#L415-L421
trilinos/Trilinos
6168be6dd51e35e1cd681e9c4b24433e709df140
packages/seacas/libraries/ioss/src/visualization/catalyst/phactori/PhactoriDriver.py
python
FigureBlockIndicesFromBlockListRecurse1
(includeIndexList, includeBlockList, inCsdata, inMetaData, ioFlatIndexCounter, inForceSetting)
recursively go through multiblock dataset to determine flat indices\n of blocks to be included; we are assuming only leaf blocks are\n actually named
recursively go through multiblock dataset to determine flat indices\n of blocks to be included; we are assuming only leaf blocks are\n actually named
[ "recursively", "go", "through", "multiblock", "dataset", "to", "determine", "flat", "indices", "\\", "n", "of", "blocks", "to", "be", "included", ";", "we", "are", "assuming", "only", "leaf", "blocks", "are", "\\", "n", "actually", "named" ]
def FigureBlockIndicesFromBlockListRecurse1(includeIndexList, includeBlockList, inCsdata, inMetaData, ioFlatIndexCounter, inForceSetting): "recursively go through multiblock dataset to determine flat indices\n of blocks to be included; we are assuming only leaf blocks are\n actually named" icsdClassname = inCsdata.GetClassName() if PhactoriDbg(100): if inMetaData == None: thisBlockName = None else: thisBlockName = inMetaData.Get(vtk.vtkCompositeDataSet.NAME()) myDebugPrint3("FigureBlockIndicesFromBlockListRecurse1 " + \ str(thisBlockName) + " index: " + str(int(ioFlatIndexCounter[0])) + \ " inForceSetting: " + str(inForceSetting) + " classname: " + \ str(icsdClassname) + "\n") ioFlatIndexCounter[0] += 1 if icsdClassname == "vtkMultiBlockDataSet": thisIsLeaf = False nonLeafType = 0 elif icsdClassname == "vtkExodusIIMultiBlockDataSet": thisIsLeaf = False nonLeafType = 1 elif icsdClassname == "vtkMultiPieceDataSet": thisIsLeaf = False nonLeafType = 2 elif icsdClassname == "vtkPartitionedDataSet": thisIsLeaf = False nonLeafType = 3 else: thisIsLeaf = True nonLeafType = -1 if not thisIsLeaf: if inForceSetting == 1: includeIndexList.append(int(ioFlatIndexCounter[0]) - 1) includeOrExcludeAllSubBlocks = 1 if PhactoriDbg(100): myDebugPrint3("this non-leaf block added inForceSetting == 1\n") elif inForceSetting == -1: includeOrExcludeAllSubBlocks = -1 if PhactoriDbg(100): myDebugPrint3("this non-leaf block not added inForceSetting == -1\n") else: includeOrExcludeAllSubBlocks = 0 #this is a non-leaf node, but we want to add it (or not) depending on #the filter settings if inMetaData == None: thisBlockName = None else: thisBlockName = inMetaData.Get(vtk.vtkCompositeDataSet.NAME()) if (thisBlockName != None) and (thisBlockName in includeBlockList): if PhactoriDbg(100): myDebugPrint3("include list, append nonleaf " + str(thisBlockName) + \ " ndx " + str(int(ioFlatIndexCounter[0]) - 1) + "\n") includeIndexList.append(int(ioFlatIndexCounter[0]) - 1) includeOrExcludeAllSubBlocks = 1 if PhactoriDbg(100): myDebugPrint3("includeOrExcludeAllSubBlocks set to 1\n") else: if PhactoriDbg(100): myDebugPrint3("include list, exclude nonleaf " + str(thisBlockName) + \ " ndx " + str(int(ioFlatIndexCounter[0]) - 1) + "\n") if nonLeafType == 2: numBlocks = inCsdata.GetNumberOfPieces() elif nonLeafType == 3: numBlocks = inCsdata.GetNumberOfPartitions() else: numBlocks = inCsdata.GetNumberOfBlocks() if PhactoriDbg(100): myDebugPrint3("recursing, flat index: " + \ str(ioFlatIndexCounter[0]) + \ " num blocks: " + \ str(numBlocks) + "\n") for ii in range(0, numBlocks): if nonLeafType == 2: oneBlock = inCsdata.GetPiece(ii) elif nonLeafType == 3: oneBlock = inCsdata.GetPartition(ii) else: oneBlock = inCsdata.GetBlock(ii) oneBlockMetaData = inCsdata.GetMetaData(ii) if PhactoriDbg(100): myDebugPrint3("oneBlockMetaData: " + str(oneBlockMetaData) + "\n") #myDebugPrint3("name: " + \ # oneBlockMetaData.Get(vtk.vtkCompositeDataSet.NAME()) + "\n") if oneBlock != None: if oneBlockMetaData != None: theBlockName = oneBlockMetaData.Get(vtk.vtkCompositeDataSet.NAME()) if PhactoriDbg(100): myDebugPrint3("name for block " + str(ii) + ": " + \ str(theBlockName) + "\n") else: if PhactoriDbg(100): myDebugPrint3("block " + str(ii) + " meta data was None\n") FigureBlockIndicesFromBlockListRecurse1(includeIndexList, includeBlockList, oneBlock, oneBlockMetaData, ioFlatIndexCounter, includeOrExcludeAllSubBlocks) else: #I think we need to count here to be okay with pruned stuff; maybe #we need to set extract block to no pruning (?) ioFlatIndexCounter[0] += 1 if includeOrExcludeAllSubBlocks == 1: if PhactoriDbg(100): myDebugPrint3("leaf block None index " + \ str(int(ioFlatIndexCounter[0]) - 1) + \ " appended due to includeOrExcludeAllSubBlocks == 1\n\n") includeIndexList.append(int(ioFlatIndexCounter[0]) - 1) else: if PhactoriDbg(100): myDebugPrint3("force include is not on, so check include list\n") includeThisBlock = False if (includeBlockList != None) and (oneBlockMetaData != None): thisBlockName = oneBlockMetaData.Get(vtk.vtkCompositeDataSet.NAME()) if PhactoriDbg(100): myDebugPrint3("include list not None, thisBlockName " + str(thisBlockName) + "\n" "includeBlockList " + str(includeBlockList) + "\n") if (thisBlockName != None) and (thisBlockName in includeBlockList): includeThisBlock = True if PhactoriDbg(100): myDebugPrint3("leaf block None index " + \ str(int(ioFlatIndexCounter[0]) - 1) + \ " included due to name being in includeBlockList\n") includeIndexList.append(int(ioFlatIndexCounter[0]) - 1) if includeThisBlock == False: if PhactoriDbg(100): myDebugPrint3("leaf block None index " + \ str(int(ioFlatIndexCounter[0]) - 1) + \ " excluded due to includeOrExcludeAllSubBlocks != 1\n") else: if inForceSetting != -1: if inForceSetting == 1: if PhactoriDbg(100): myDebugPrint3("this leaf block will be added inForceSetting == 1\n") FigureBlockIndicesFromBlockListOneBlock(includeIndexList, includeBlockList, inMetaData, ioFlatIndexCounter, inCsdata, inForceSetting) else: if PhactoriDbg(100): myDebugPrint3("this leaf block not added inForceSetting == -1\n")
[ "def", "FigureBlockIndicesFromBlockListRecurse1", "(", "includeIndexList", ",", "includeBlockList", ",", "inCsdata", ",", "inMetaData", ",", "ioFlatIndexCounter", ",", "inForceSetting", ")", ":", "icsdClassname", "=", "inCsdata", ".", "GetClassName", "(", ")", "if", "...
https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/libraries/ioss/src/visualization/catalyst/phactori/PhactoriDriver.py#L15385-L15527
SequoiaDB/SequoiaDB
2894ed7e5bd6fe57330afc900cf76d0ff0df9f64
tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py
python
parserCtxt.parserHandleReference
(self)
TODO: Remove, now deprecated ... the test is done directly in the content parsing routines. [67] Reference ::= EntityRef | CharRef [68] EntityRef ::= '&' Name ';' [ WFC: Entity Declared ] the Name given in the entity reference must match that in an entity declaration, except that well-formed documents need not declare any of the following entities: amp, lt, gt, apos, quot. [ WFC: Parsed Entity ] An entity reference must not contain the name of an unparsed entity [66] CharRef ::= '&#' [0-9]+ ';' | '&#x' [0-9a-fA-F]+ ';' A PEReference may have been detected in the current input stream the handling is done accordingly to http://www.w3.org/TR/REC-xml#entproc
TODO: Remove, now deprecated ... the test is done directly in the content parsing routines. [67] Reference ::= EntityRef | CharRef [68] EntityRef ::= '&' Name ';' [ WFC: Entity Declared ] the Name given in the entity reference must match that in an entity declaration, except that well-formed documents need not declare any of the following entities: amp, lt, gt, apos, quot. [ WFC: Parsed Entity ] An entity reference must not contain the name of an unparsed entity [66] CharRef ::= '&#' [0-9]+ ';' | '&#x' [0-9a-fA-F]+ ';' A PEReference may have been detected in the current input stream the handling is done accordingly to http://www.w3.org/TR/REC-xml#entproc
[ "TODO", ":", "Remove", "now", "deprecated", "...", "the", "test", "is", "done", "directly", "in", "the", "content", "parsing", "routines", ".", "[", "67", "]", "Reference", "::", "=", "EntityRef", "|", "CharRef", "[", "68", "]", "EntityRef", "::", "=", ...
def parserHandleReference(self): """TODO: Remove, now deprecated ... the test is done directly in the content parsing routines. [67] Reference ::= EntityRef | CharRef [68] EntityRef ::= '&' Name ';' [ WFC: Entity Declared ] the Name given in the entity reference must match that in an entity declaration, except that well-formed documents need not declare any of the following entities: amp, lt, gt, apos, quot. [ WFC: Parsed Entity ] An entity reference must not contain the name of an unparsed entity [66] CharRef ::= '&#' [0-9]+ ';' | '&#x' [0-9a-fA-F]+ ';' A PEReference may have been detected in the current input stream the handling is done accordingly to http://www.w3.org/TR/REC-xml#entproc """ libxml2mod.xmlParserHandleReference(self._o)
[ "def", "parserHandleReference", "(", "self", ")", ":", "libxml2mod", ".", "xmlParserHandleReference", "(", "self", ".", "_o", ")" ]
https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L5451-L5464
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/idlelib/AutoComplete.py
python
AutoComplete.autocomplete_event
(self, event)
Happens when the user wants to complete his word, and if necessary, open a completion list after that (if there is more than one completion)
Happens when the user wants to complete his word, and if necessary, open a completion list after that (if there is more than one completion)
[ "Happens", "when", "the", "user", "wants", "to", "complete", "his", "word", "and", "if", "necessary", "open", "a", "completion", "list", "after", "that", "(", "if", "there", "is", "more", "than", "one", "completion", ")" ]
def autocomplete_event(self, event): """Happens when the user wants to complete his word, and if necessary, open a completion list after that (if there is more than one completion) """ if hasattr(event, "mc_state") and event.mc_state: # A modifier was pressed along with the tab, continue as usual. return if self.autocompletewindow and self.autocompletewindow.is_active(): self.autocompletewindow.complete() return "break" else: opened = self.open_completions(False, True, True) if opened: return "break"
[ "def", "autocomplete_event", "(", "self", ",", "event", ")", ":", "if", "hasattr", "(", "event", ",", "\"mc_state\"", ")", "and", "event", ".", "mc_state", ":", "# A modifier was pressed along with the tab, continue as usual.", "return", "if", "self", ".", "autocomp...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/idlelib/AutoComplete.py#L81-L95
rapidsai/cudf
d5b2448fc69f17509304d594f029d0df56984962
python/cudf/cudf/core/column/numerical.py
python
NumericalColumn.can_cast_safely
(self, to_dtype: DtypeObj)
return False
Returns true if all the values in self can be safely cast to dtype
Returns true if all the values in self can be safely cast to dtype
[ "Returns", "true", "if", "all", "the", "values", "in", "self", "can", "be", "safely", "cast", "to", "dtype" ]
def can_cast_safely(self, to_dtype: DtypeObj) -> bool: """ Returns true if all the values in self can be safely cast to dtype """ if self.dtype.kind == to_dtype.kind: if self.dtype <= to_dtype: return True else: # Kinds are the same but to_dtype is smaller if "float" in to_dtype.name: finfo = np.finfo(to_dtype) lower_, upper_ = finfo.min, finfo.max elif "int" in to_dtype.name: iinfo = np.iinfo(to_dtype) lower_, upper_ = iinfo.min, iinfo.max if self.dtype.kind == "f": # Exclude 'np.inf', '-np.inf' s = cudf.Series(self) # TODO: replace np.inf with cudf scalar when # https://github.com/rapidsai/cudf/pull/6297 merges non_infs = s[ ((s == np.inf) | (s == -np.inf)).logical_not() ] col = non_infs._column else: col = self min_ = col.min() # TODO: depending on implementation of cudf scalar and future # refactor of min/max, change the test method if np.isnan(min_): # Column contains only infs return True return (min_ >= lower_) and (col.max() < upper_) # want to cast int to uint elif self.dtype.kind == "i" and to_dtype.kind == "u": i_max_ = np.iinfo(self.dtype).max u_max_ = np.iinfo(to_dtype).max return (self.min() >= 0) and ( (i_max_ <= u_max_) or (self.max() < u_max_) ) # want to cast uint to int elif self.dtype.kind == "u" and to_dtype.kind == "i": u_max_ = np.iinfo(self.dtype).max i_max_ = np.iinfo(to_dtype).max return (u_max_ <= i_max_) or (self.max() < i_max_) # want to cast int to float elif self.dtype.kind in {"i", "u"} and to_dtype.kind == "f": info = np.finfo(to_dtype) biggest_exact_int = 2 ** (info.nmant + 1) if (self.min() >= -biggest_exact_int) and ( self.max() <= biggest_exact_int ): return True else: filled = self.fillna(0) return ( cudf.Series(filled).astype(to_dtype).astype(filled.dtype) == cudf.Series(filled) ).all() # want to cast float to int: elif self.dtype.kind == "f" and to_dtype.kind in {"i", "u"}: iinfo = np.iinfo(to_dtype) min_, max_ = iinfo.min, iinfo.max # best we can do is hope to catch it here and avoid compare if (self.min() >= min_) and (self.max() <= max_): filled = self.fillna(0, fill_nan=False) return (cudf.Series(filled) % 1 == 0).all() else: return False return False
[ "def", "can_cast_safely", "(", "self", ",", "to_dtype", ":", "DtypeObj", ")", "->", "bool", ":", "if", "self", ".", "dtype", ".", "kind", "==", "to_dtype", ".", "kind", ":", "if", "self", ".", "dtype", "<=", "to_dtype", ":", "return", "True", "else", ...
https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/core/column/numerical.py#L535-L617
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/keras/distribute/distributed_file_utils.py
python
remove_temp_dir_with_filepath
(filepath, strategy)
Removes the temp path for file after writing is finished. Args: filepath: Original filepath that would be used without distribution. strategy: The tf.distribute strategy object currently used.
Removes the temp path for file after writing is finished.
[ "Removes", "the", "temp", "path", "for", "file", "after", "writing", "is", "finished", "." ]
def remove_temp_dir_with_filepath(filepath, strategy): """Removes the temp path for file after writing is finished. Args: filepath: Original filepath that would be used without distribution. strategy: The tf.distribute strategy object currently used. """ remove_temp_dirpath(os.path.dirname(filepath), strategy)
[ "def", "remove_temp_dir_with_filepath", "(", "filepath", ",", "strategy", ")", ":", "remove_temp_dirpath", "(", "os", ".", "path", ".", "dirname", "(", "filepath", ")", ",", "strategy", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/distribute/distributed_file_utils.py#L139-L146
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py2/numpy/distutils/system_info.py
python
system_info.check_libs
(self, lib_dirs, libs, opt_libs=[])
return info
If static or shared libraries are available then return their info dictionary. Checks for all libraries as shared libraries first, then static (or vice versa if self.search_static_first is True).
If static or shared libraries are available then return their info dictionary.
[ "If", "static", "or", "shared", "libraries", "are", "available", "then", "return", "their", "info", "dictionary", "." ]
def check_libs(self, lib_dirs, libs, opt_libs=[]): """If static or shared libraries are available then return their info dictionary. Checks for all libraries as shared libraries first, then static (or vice versa if self.search_static_first is True). """ exts = self.library_extensions() info = None for ext in exts: info = self._check_libs(lib_dirs, libs, opt_libs, [ext]) if info is not None: break if not info: log.info(' libraries %s not found in %s', ','.join(libs), lib_dirs) return info
[ "def", "check_libs", "(", "self", ",", "lib_dirs", ",", "libs", ",", "opt_libs", "=", "[", "]", ")", ":", "exts", "=", "self", ".", "library_extensions", "(", ")", "info", "=", "None", "for", "ext", "in", "exts", ":", "info", "=", "self", ".", "_ch...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/distutils/system_info.py#L771-L787
hifiberry/hifiberry-os
88c05213fb3e6230645cb4bf8eb8fceda8bd07d4
buildroot/package/lmsmpris/src/audiocontrol2.py
python
print_state
(signalNumber=None, frame=None)
Display state on USR2
Display state on USR2
[ "Display", "state", "on", "USR2" ]
def print_state(signalNumber=None, frame=None): """ Display state on USR2 """ if mpris is not None: print("\n" + str(mpris))
[ "def", "print_state", "(", "signalNumber", "=", "None", ",", "frame", "=", "None", ")", ":", "if", "mpris", "is", "not", "None", ":", "print", "(", "\"\\n\"", "+", "str", "(", "mpris", ")", ")" ]
https://github.com/hifiberry/hifiberry-os/blob/88c05213fb3e6230645cb4bf8eb8fceda8bd07d4/buildroot/package/lmsmpris/src/audiocontrol2.py#L21-L26
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/mailbox.py
python
MH._dump_sequences
(self, message, key)
Inspect a new MHMessage and update sequences appropriately.
Inspect a new MHMessage and update sequences appropriately.
[ "Inspect", "a", "new", "MHMessage", "and", "update", "sequences", "appropriately", "." ]
def _dump_sequences(self, message, key): """Inspect a new MHMessage and update sequences appropriately.""" pending_sequences = message.get_sequences() all_sequences = self.get_sequences() for name, key_list in all_sequences.iteritems(): if name in pending_sequences: key_list.append(key) elif key in key_list: del key_list[key_list.index(key)] for sequence in pending_sequences: if sequence not in all_sequences: all_sequences[sequence] = [key] self.set_sequences(all_sequences)
[ "def", "_dump_sequences", "(", "self", ",", "message", ",", "key", ")", ":", "pending_sequences", "=", "message", ".", "get_sequences", "(", ")", "all_sequences", "=", "self", ".", "get_sequences", "(", ")", "for", "name", ",", "key_list", "in", "all_sequenc...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/mailbox.py#L1203-L1215
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/jinja2/compiler.py
python
CodeGenerator.position
(self, node)
return rv
Return a human readable position for the node.
Return a human readable position for the node.
[ "Return", "a", "human", "readable", "position", "for", "the", "node", "." ]
def position(self, node): """Return a human readable position for the node.""" rv = 'line %d' % node.lineno if self.name is not None: rv += ' in ' + repr(self.name) return rv
[ "def", "position", "(", "self", ",", "node", ")", ":", "rv", "=", "'line %d'", "%", "node", ".", "lineno", "if", "self", ".", "name", "is", "not", "None", ":", "rv", "+=", "' in '", "+", "repr", "(", "self", ".", "name", ")", "return", "rv" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/jinja2/compiler.py#L748-L753
kristjankorjus/Replicating-DeepMind
68539394e792b34a4d6b430a2eb73b8b8f91d8db
Hybrid/tools/scoreanalyzer.py
python
ScoreAnalyzer.sandbox
(self)
The main place to try out things
The main place to try out things
[ "The", "main", "place", "to", "try", "out", "things" ]
def sandbox(self): """ The main place to try out things """ print self.scores.keys() print self.scores[1]
[ "def", "sandbox", "(", "self", ")", ":", "print", "self", ".", "scores", ".", "keys", "(", ")", "print", "self", ".", "scores", "[", "1", "]" ]
https://github.com/kristjankorjus/Replicating-DeepMind/blob/68539394e792b34a4d6b430a2eb73b8b8f91d8db/Hybrid/tools/scoreanalyzer.py#L44-L47
opengm/opengm
decdacf4caad223b0ab5478d38a855f8767a394f
src/interfaces/python/opengm/opengmcore/__init__.py
python
getStartingPointMasked
(imgArg, mask, maskIdx=1)
return points.astype(label_type)
maps 3d starting points to gm indices
maps 3d starting points to gm indices
[ "maps", "3d", "starting", "points", "to", "gm", "indices" ]
def getStartingPointMasked(imgArg, mask, maskIdx=1): """ maps 3d starting points to gm indices """ points = numpy.zeros(mask[mask==maskIdx].shape, dtype=numpy.uint32) _opengmcore._getStartingPointMasked(mask, imgArg, points) return points.astype(label_type)
[ "def", "getStartingPointMasked", "(", "imgArg", ",", "mask", ",", "maskIdx", "=", "1", ")", ":", "points", "=", "numpy", ".", "zeros", "(", "mask", "[", "mask", "==", "maskIdx", "]", ".", "shape", ",", "dtype", "=", "numpy", ".", "uint32", ")", "_ope...
https://github.com/opengm/opengm/blob/decdacf4caad223b0ab5478d38a855f8767a394f/src/interfaces/python/opengm/opengmcore/__init__.py#L335-L341
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
models/AI-Model-Zoo/caffe-xilinx/python/caffe/draw.py
python
get_edge_label
(layer)
return edge_label
Define edge label based on layer type.
Define edge label based on layer type.
[ "Define", "edge", "label", "based", "on", "layer", "type", "." ]
def get_edge_label(layer): """Define edge label based on layer type. """ if layer.type == 'Data': edge_label = 'Batch ' + str(layer.data_param.batch_size) elif layer.type == 'Convolution' or layer.type == 'Deconvolution': edge_label = str(layer.convolution_param.num_output) elif layer.type == 'InnerProduct': edge_label = str(layer.inner_product_param.num_output) else: edge_label = '""' return edge_label
[ "def", "get_edge_label", "(", "layer", ")", ":", "if", "layer", ".", "type", "==", "'Data'", ":", "edge_label", "=", "'Batch '", "+", "str", "(", "layer", ".", "data_param", ".", "batch_size", ")", "elif", "layer", ".", "type", "==", "'Convolution'", "or...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/models/AI-Model-Zoo/caffe-xilinx/python/caffe/draw.py#L46-L59
redpony/cdec
f7c4899b174d86bc70b40b1cae68dcad364615cb
python/cdec/configobj.py
python
Section.iterkeys
(self)
return iter((self.scalars + self.sections))
D.iterkeys() -> an iterator over the keys of D
D.iterkeys() -> an iterator over the keys of D
[ "D", ".", "iterkeys", "()", "-", ">", "an", "iterator", "over", "the", "keys", "of", "D" ]
def iterkeys(self): """D.iterkeys() -> an iterator over the keys of D""" return iter((self.scalars + self.sections))
[ "def", "iterkeys", "(", "self", ")", ":", "return", "iter", "(", "(", "self", ".", "scalars", "+", "self", ".", "sections", ")", ")" ]
https://github.com/redpony/cdec/blob/f7c4899b174d86bc70b40b1cae68dcad364615cb/python/cdec/configobj.py#L742-L744
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
chrome/tools/webforms_extractor.py
python
FormsExtractor.__init__
(self, input_dir=_REGISTRATION_PAGES_DIR, output_dir=_EXTRACTED_FORMS_DIR, logging_level=None)
Creates a FormsExtractor object. Args: input_dir: the directory of HTML files. output_dir: the directory where the registration form files will be saved. logging_level: verbosity level, default is None. Raises: IOError exception if input directory doesn't exist.
Creates a FormsExtractor object.
[ "Creates", "a", "FormsExtractor", "object", "." ]
def __init__(self, input_dir=_REGISTRATION_PAGES_DIR, output_dir=_EXTRACTED_FORMS_DIR, logging_level=None): """Creates a FormsExtractor object. Args: input_dir: the directory of HTML files. output_dir: the directory where the registration form files will be saved. logging_level: verbosity level, default is None. Raises: IOError exception if input directory doesn't exist. """ if logging_level: if not self.log_handlers['StreamHandler']: console = logging.StreamHandler() console.setLevel(logging.DEBUG) self.log_handlers['StreamHandler'] = console self.logger.addHandler(console) self.logger.setLevel(logging_level) else: if self.log_handlers['StreamHandler']: self.logger.removeHandler(self.log_handlers['StreamHandler']) self.log_handlers['StreamHandler'] = None self._input_dir = input_dir self._output_dir = output_dir if not os.path.isdir(self._input_dir): error_msg = 'Directory "%s" doesn\'t exist.' % self._input_dir self.logger.error('Error: %s', error_msg) raise IOError(error_msg) if not os.path.isdir(output_dir): os.makedirs(output_dir) self._form_location_comment = ''
[ "def", "__init__", "(", "self", ",", "input_dir", "=", "_REGISTRATION_PAGES_DIR", ",", "output_dir", "=", "_EXTRACTED_FORMS_DIR", ",", "logging_level", "=", "None", ")", ":", "if", "logging_level", ":", "if", "not", "self", ".", "log_handlers", "[", "'StreamHand...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/chrome/tools/webforms_extractor.py#L128-L161
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/calendar.py
python
monthrange
(year, month)
return day1, ndays
Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for year, month.
Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for year, month.
[ "Return", "weekday", "(", "0", "-", "6", "~", "Mon", "-", "Sun", ")", "and", "number", "of", "days", "(", "28", "-", "31", ")", "for", "year", "month", "." ]
def monthrange(year, month): """Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for year, month.""" if not 1 <= month <= 12: raise IllegalMonthError(month) day1 = weekday(year, month, 1) ndays = mdays[month] + (month == February and isleap(year)) return day1, ndays
[ "def", "monthrange", "(", "year", ",", "month", ")", ":", "if", "not", "1", "<=", "month", "<=", "12", ":", "raise", "IllegalMonthError", "(", "month", ")", "day1", "=", "weekday", "(", "year", ",", "month", ",", "1", ")", "ndays", "=", "mdays", "[...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/calendar.py#L116-L123
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/fluid/framework.py
python
IrNode.remove_input
(self, node)
Remove a node from inputs. Args: node(IrNode): the node being removed.
Remove a node from inputs.
[ "Remove", "a", "node", "from", "inputs", "." ]
def remove_input(self, node): """ Remove a node from inputs. Args: node(IrNode): the node being removed. """ self.node.remove_input(node.node)
[ "def", "remove_input", "(", "self", ",", "node", ")", ":", "self", ".", "node", ".", "remove_input", "(", "node", ".", "node", ")" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/framework.py#L3890-L3897
macchina-io/macchina.io
ef24ba0e18379c3dd48fb84e6dbf991101cb8db0
platform/JS/V8/tools/gyp/tools/graphviz.py
python
WriteGraph
(edges)
Print a graphviz graph to stdout. |edges| is a map of target to a list of other targets it depends on.
Print a graphviz graph to stdout. |edges| is a map of target to a list of other targets it depends on.
[ "Print", "a", "graphviz", "graph", "to", "stdout", ".", "|edges|", "is", "a", "map", "of", "target", "to", "a", "list", "of", "other", "targets", "it", "depends", "on", "." ]
def WriteGraph(edges): """Print a graphviz graph to stdout. |edges| is a map of target to a list of other targets it depends on.""" # Bucket targets by file. files = collections.defaultdict(list) for src, dst in edges.items(): build_file, target_name, toolset = ParseTarget(src) files[build_file].append(src) print 'digraph D {' print ' fontsize=8' # Used by subgraphs. print ' node [fontsize=8]' # Output nodes by file. We must first write out each node within # its file grouping before writing out any edges that may refer # to those nodes. for filename, targets in files.items(): if len(targets) == 1: # If there's only one node for this file, simplify # the display by making it a box without an internal node. target = targets[0] build_file, target_name, toolset = ParseTarget(target) print ' "%s" [shape=box, label="%s\\n%s"]' % (target, filename, target_name) else: # Group multiple nodes together in a subgraph. print ' subgraph "cluster_%s" {' % filename print ' label = "%s"' % filename for target in targets: build_file, target_name, toolset = ParseTarget(target) print ' "%s" [label="%s"]' % (target, target_name) print ' }' # Now that we've placed all the nodes within subgraphs, output all # the edges between nodes. for src, dsts in edges.items(): for dst in dsts: print ' "%s" -> "%s"' % (src, dst) print '}'
[ "def", "WriteGraph", "(", "edges", ")", ":", "# Bucket targets by file.", "files", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", "src", ",", "dst", "in", "edges", ".", "items", "(", ")", ":", "build_file", ",", "target_name", ",", "tools...
https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/tools/gyp/tools/graphviz.py#L43-L83
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/WebKit/Tools/Scripts/webkitpy/common/checkout/scm/git.py
python
Git.create_patch
(self, git_commit=None, changed_files=None)
return self._prepend_svn_revision(self._run(command, decode_output=False, cwd=self.checkout_root))
Returns a byte array (str()) representing the patch file. Patch files are effectively binary since they may contain files of multiple different encodings.
Returns a byte array (str()) representing the patch file. Patch files are effectively binary since they may contain files of multiple different encodings.
[ "Returns", "a", "byte", "array", "(", "str", "()", ")", "representing", "the", "patch", "file", ".", "Patch", "files", "are", "effectively", "binary", "since", "they", "may", "contain", "files", "of", "multiple", "different", "encodings", "." ]
def create_patch(self, git_commit=None, changed_files=None): """Returns a byte array (str()) representing the patch file. Patch files are effectively binary since they may contain files of multiple different encodings.""" # Put code changes at the top of the patch and layout tests # at the bottom, this makes for easier reviewing. config_path = self._filesystem.dirname(self._filesystem.path_to_module('webkitpy.common.config')) order_file = self._filesystem.join(config_path, 'orderfile') order = "" if self._filesystem.exists(order_file): order = "-O%s" % order_file command = [self.executable_name, 'diff', '--binary', '--no-color', "--no-ext-diff", "--full-index", "--no-renames", order, self._merge_base(git_commit), "--"] if changed_files: command += changed_files return self._prepend_svn_revision(self._run(command, decode_output=False, cwd=self.checkout_root))
[ "def", "create_patch", "(", "self", ",", "git_commit", "=", "None", ",", "changed_files", "=", "None", ")", ":", "# Put code changes at the top of the patch and layout tests", "# at the bottom, this makes for easier reviewing.", "config_path", "=", "self", ".", "_filesystem",...
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/common/checkout/scm/git.py#L216-L232
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/internals/blocks.py
python
DatetimeBlock.to_native_types
(self, slicer=None, na_rep=None, date_format=None, quoting=None, **kwargs)
return np.atleast_2d(result)
convert to our native types format, slicing if desired
convert to our native types format, slicing if desired
[ "convert", "to", "our", "native", "types", "format", "slicing", "if", "desired" ]
def to_native_types(self, slicer=None, na_rep=None, date_format=None, quoting=None, **kwargs): """ convert to our native types format, slicing if desired """ values = self.values i8values = self.values.view('i8') if slicer is not None: i8values = i8values[..., slicer] from pandas.io.formats.format import _get_format_datetime64_from_values fmt = _get_format_datetime64_from_values(values, date_format) result = tslib.format_array_from_datetime( i8values.ravel(), tz=getattr(self.values, 'tz', None), format=fmt, na_rep=na_rep).reshape(i8values.shape) return np.atleast_2d(result)
[ "def", "to_native_types", "(", "self", ",", "slicer", "=", "None", ",", "na_rep", "=", "None", ",", "date_format", "=", "None", ",", "quoting", "=", "None", ",", "*", "*", "kwargs", ")", ":", "values", "=", "self", ".", "values", "i8values", "=", "se...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/internals/blocks.py#L2200-L2216
sc0ty/subsync
be5390d00ff475b6543eb0140c7e65b34317d95b
subsync/__init__.py
python
synchronize
(sub, ref, out, *, onError=None, options={}, offline=False, updateAssets=True)
return res
Synchronize single subtitle file. This is simplified high level synchronization API. For finer-grained control use `SyncController` object. Parameters ---------- sub: SubFile or InputFile or dict Input subtitle description, proper object instance or `dict` with fields same as arguments to `InputFile` constructor. ref: RefFile or InputFile or dict Reference description, proper object instance or `dict` with fields same as arguments to `InputFile` constructor. out: OutputFile or dict Output subtitle description, proper object instance or `dict` with fields same as arguments to `OutputFile` constructor. onError: callable, optional Error callback for non-terminal errors. Terminal errors will raise exception. For details see `SyncController` constructor. options: dict, optional Override default synchronization options, see `SyncController.configure`. offline: bool, optional Prevent any communication with asset server. If required assets are missing, they will not be downloaded and synchronization will fail. updateAssets: bool, optional Whether to update existing assets if update is available online. Has no effect with `offline`=`True`. Returns ------- tuple of (subsync.synchro.controller.SyncJobResult, subsync.synchro.controller.SyncStatus) Synchronization result. Notes ----- This function runs synchronously - it will block until synchronization finishes. For non-blocking synchronization use `SyncController` instead. Example ------- >>> sub = { 'path': './sub.srt', 'lang': 'rus' } >>> ref = { 'path': './movie.avi', 'stream': 2, 'lang': 'eng' } >>> out = { 'path': './out.srt' } >>> subsync.synchronize(sub, ref, out) (SyncJobResult(success=True, terminated=False, path='out.srt'), SyncStatus(correlated=True, maxChange=0.010168457031248579, progress=0.5212266710947953, factor=0.9999998222916713, points=289, formula=1.0000x+0.010, effort=0.5004523633099243))
Synchronize single subtitle file.
[ "Synchronize", "single", "subtitle", "file", "." ]
def synchronize(sub, ref, out, *, onError=None, options={}, offline=False, updateAssets=True): """Synchronize single subtitle file. This is simplified high level synchronization API. For finer-grained control use `SyncController` object. Parameters ---------- sub: SubFile or InputFile or dict Input subtitle description, proper object instance or `dict` with fields same as arguments to `InputFile` constructor. ref: RefFile or InputFile or dict Reference description, proper object instance or `dict` with fields same as arguments to `InputFile` constructor. out: OutputFile or dict Output subtitle description, proper object instance or `dict` with fields same as arguments to `OutputFile` constructor. onError: callable, optional Error callback for non-terminal errors. Terminal errors will raise exception. For details see `SyncController` constructor. options: dict, optional Override default synchronization options, see `SyncController.configure`. offline: bool, optional Prevent any communication with asset server. If required assets are missing, they will not be downloaded and synchronization will fail. updateAssets: bool, optional Whether to update existing assets if update is available online. Has no effect with `offline`=`True`. Returns ------- tuple of (subsync.synchro.controller.SyncJobResult, subsync.synchro.controller.SyncStatus) Synchronization result. Notes ----- This function runs synchronously - it will block until synchronization finishes. For non-blocking synchronization use `SyncController` instead. Example ------- >>> sub = { 'path': './sub.srt', 'lang': 'rus' } >>> ref = { 'path': './movie.avi', 'stream': 2, 'lang': 'eng' } >>> out = { 'path': './out.srt' } >>> subsync.synchronize(sub, ref, out) (SyncJobResult(success=True, terminated=False, path='out.srt'), SyncStatus(correlated=True, maxChange=0.010168457031248579, progress=0.5212266710947953, factor=0.9999998222916713, points=289, formula=1.0000x+0.010, effort=0.5004523633099243)) """ task = SyncTask(sub, ref, out) assets = assetManager().getAssetsForTasks([ task ]) if not offline and (assets.missing() or updateAssets): listUpdater = assetManager().getAssetListUpdater() if not listUpdater.isRunning() and not listUpdater.isUpdated(): listUpdater.run() listUpdater.wait() assets.validate() if not offline: if updateAssets: downloadAssets = assets.hasUpdate() else: downloadAssets = assets.notInstalled() for asset in downloadAssets: downloader = asset.downloader() try: downloader.run() downloader.wait(reraise=True) except: downloader.terminate() raise assets.validate(localOnly=True) res = (None, None) def onJobEnd(task, status, result): nonlocal res res = (result, status) sync = SyncController(onJobEnd=onJobEnd, onError=onError) try: sync.configure(**options) sync.synchronize(task) sync.wait() except: sync.terminate() raise return res
[ "def", "synchronize", "(", "sub", ",", "ref", ",", "out", ",", "*", ",", "onError", "=", "None", ",", "options", "=", "{", "}", ",", "offline", "=", "False", ",", "updateAssets", "=", "True", ")", ":", "task", "=", "SyncTask", "(", "sub", ",", "r...
https://github.com/sc0ty/subsync/blob/be5390d00ff475b6543eb0140c7e65b34317d95b/subsync/__init__.py#L24-L114
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/contexts/fitting_contexts/model_fitting_context.py
python
ModelFittingContext.y_parameters
(self)
return self._y_parameters
Returns the available y parameters for the selected results table.
Returns the available y parameters for the selected results table.
[ "Returns", "the", "available", "y", "parameters", "for", "the", "selected", "results", "table", "." ]
def y_parameters(self) -> dict: """Returns the available y parameters for the selected results table.""" return self._y_parameters
[ "def", "y_parameters", "(", "self", ")", "->", "dict", ":", "return", "self", ".", "_y_parameters" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/contexts/fitting_contexts/model_fitting_context.py#L87-L89
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib2to3/fixer_util.py
python
Attr
(obj, attr)
return [obj, Node(syms.trailer, [Dot(), attr])]
A node tuple for obj.attr
A node tuple for obj.attr
[ "A", "node", "tuple", "for", "obj", ".", "attr" ]
def Attr(obj, attr): """A node tuple for obj.attr""" return [obj, Node(syms.trailer, [Dot(), attr])]
[ "def", "Attr", "(", "obj", ",", "attr", ")", ":", "return", "[", "obj", ",", "Node", "(", "syms", ".", "trailer", ",", "[", "Dot", "(", ")", ",", "attr", "]", ")", "]" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib2to3/fixer_util.py#L42-L44
generalized-intelligence/GAAS
29ab17d3e8a4ba18edef3a57c36d8db6329fac73
algorithms/src/LocalizationAndMapping/icp_lidar_localization/fast_gicp/thirdparty/Sophus/py/sophus/se3.py
python
Se3.__mul__
(self, right)
left-multiplication either rotation concatenation or point-transform
left-multiplication either rotation concatenation or point-transform
[ "left", "-", "multiplication", "either", "rotation", "concatenation", "or", "point", "-", "transform" ]
def __mul__(self, right): """ left-multiplication either rotation concatenation or point-transform """ if isinstance(right, sympy.Matrix): assert right.shape == (3, 1), right.shape return self.so3 * right + self.t elif isinstance(right, Se3): r = self.so3 * right.so3 t = self.t + self.so3 * right.t return Se3(r, t) assert False, "unsupported type: {0}".format(type(right))
[ "def", "__mul__", "(", "self", ",", "right", ")", ":", "if", "isinstance", "(", "right", ",", "sympy", ".", "Matrix", ")", ":", "assert", "right", ".", "shape", "==", "(", "3", ",", "1", ")", ",", "right", ".", "shape", "return", "self", ".", "so...
https://github.com/generalized-intelligence/GAAS/blob/29ab17d3e8a4ba18edef3a57c36d8db6329fac73/algorithms/src/LocalizationAndMapping/icp_lidar_localization/fast_gicp/thirdparty/Sophus/py/sophus/se3.py#L84-L94
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_windows.py
python
SplitterEvent.GetSashPosition
(*args, **kwargs)
return _windows_.SplitterEvent_GetSashPosition(*args, **kwargs)
GetSashPosition(self) -> int Returns the new sash position while in EVT_SPLITTER_SASH_POS_CHANGING and EVT_SPLITTER_SASH_POS_CHANGED events.
GetSashPosition(self) -> int
[ "GetSashPosition", "(", "self", ")", "-", ">", "int" ]
def GetSashPosition(*args, **kwargs): """ GetSashPosition(self) -> int Returns the new sash position while in EVT_SPLITTER_SASH_POS_CHANGING and EVT_SPLITTER_SASH_POS_CHANGED events. """ return _windows_.SplitterEvent_GetSashPosition(*args, **kwargs)
[ "def", "GetSashPosition", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "SplitterEvent_GetSashPosition", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L1722-L1729
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReflectometryILLPreprocess.py
python
ReflectometryILLPreprocess.version
(self)
return 1
Return the version of the algorithm.
Return the version of the algorithm.
[ "Return", "the", "version", "of", "the", "algorithm", "." ]
def version(self): """Return the version of the algorithm.""" return 1
[ "def", "version", "(", "self", ")", ":", "return", "1" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReflectometryILLPreprocess.py#L93-L95
QMCPACK/qmcpack
d0948ab455e38364458740cc8e2239600a14c5cd
utils/afqmctools/afqmctools/wavefunction/mol.py
python
write_nomsd_single
(fh5, psi, idet)
Write single component of NOMSD to hdf. Parameters ---------- fh5 : h5py group Wavefunction group to write to file. psi : :class:`scipy.sparse.csr_matrix` Sparse representation of trial wavefunction. idet : int Determinant number.
Write single component of NOMSD to hdf.
[ "Write", "single", "component", "of", "NOMSD", "to", "hdf", "." ]
def write_nomsd_single(fh5, psi, idet): """Write single component of NOMSD to hdf. Parameters ---------- fh5 : h5py group Wavefunction group to write to file. psi : :class:`scipy.sparse.csr_matrix` Sparse representation of trial wavefunction. idet : int Determinant number. """ base = 'PsiT_{:d}/'.format(idet) dims = [psi.shape[0], psi.shape[1], psi.nnz] fh5[base+'dims'] = numpy.array(dims, dtype=numpy.int32) fh5[base+'data_'] = to_qmcpack_complex(psi.data) fh5[base+'jdata_'] = psi.indices fh5[base+'pointers_begin_'] = psi.indptr[:-1] fh5[base+'pointers_end_'] = psi.indptr[1:]
[ "def", "write_nomsd_single", "(", "fh5", ",", "psi", ",", "idet", ")", ":", "base", "=", "'PsiT_{:d}/'", ".", "format", "(", "idet", ")", "dims", "=", "[", "psi", ".", "shape", "[", "0", "]", ",", "psi", ".", "shape", "[", "1", "]", ",", "psi", ...
https://github.com/QMCPACK/qmcpack/blob/d0948ab455e38364458740cc8e2239600a14c5cd/utils/afqmctools/afqmctools/wavefunction/mol.py#L160-L178
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distlib/_backport/tarfile.py
python
TarFile.gzopen
(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs)
return t
Open gzip compressed tar archive name for reading or writing. Appending is not allowed.
Open gzip compressed tar archive name for reading or writing.
[ "Open", "gzip", "compressed", "tar", "archive", "name", "for", "reading", "or", "writing", "." ]
def gzopen(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs): """Open gzip compressed tar archive name for reading or writing. Appending is not allowed. """ if len(mode) > 1 or mode not in "rw": raise ValueError("mode must be 'r' or 'w'") try: import gzip gzip.GzipFile except (ImportError, AttributeError): raise CompressionError("gzip module is not available") extfileobj = fileobj is not None try: fileobj = gzip.GzipFile(name, mode + "b", compresslevel, fileobj) t = cls.taropen(name, mode, fileobj, **kwargs) except IOError: if not extfileobj and fileobj is not None: fileobj.close() if fileobj is None: raise raise ReadError("not a gzip file") except: if not extfileobj and fileobj is not None: fileobj.close() raise t._extfileobj = extfileobj return t
[ "def", "gzopen", "(", "cls", ",", "name", ",", "mode", "=", "\"r\"", ",", "fileobj", "=", "None", ",", "compresslevel", "=", "9", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "mode", ")", ">", "1", "or", "mode", "not", "in", "\"rw\"", "...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distlib/_backport/tarfile.py#L3595-L3651
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/tree.py
python
wheel_event
(event, widget=None)
return 'break'
Handle scrollwheel event. For wheel up, event.delta = 120*n on Windows, -1*n on darwin, where n can be > 1 if one scrolls fast. Flicking the wheel generates up to maybe 20 events with n up to 10 or more 1. Macs use wheel down (delta = 1*n) to scroll up, so positive delta means to scroll up on both systems. X-11 sends Control-Button-4,5 events instead. The widget parameter is needed so browser label bindings can pass the underlying canvas. This function depends on widget.yview to not be overridden by a subclass.
Handle scrollwheel event.
[ "Handle", "scrollwheel", "event", "." ]
def wheel_event(event, widget=None): """Handle scrollwheel event. For wheel up, event.delta = 120*n on Windows, -1*n on darwin, where n can be > 1 if one scrolls fast. Flicking the wheel generates up to maybe 20 events with n up to 10 or more 1. Macs use wheel down (delta = 1*n) to scroll up, so positive delta means to scroll up on both systems. X-11 sends Control-Button-4,5 events instead. The widget parameter is needed so browser label bindings can pass the underlying canvas. This function depends on widget.yview to not be overridden by a subclass. """ up = {EventType.MouseWheel: event.delta > 0, EventType.ButtonPress: event.num == 4} lines = -5 if up[event.type] else 5 widget = event.widget if widget is None else widget widget.yview(SCROLL, lines, 'units') return 'break'
[ "def", "wheel_event", "(", "event", ",", "widget", "=", "None", ")", ":", "up", "=", "{", "EventType", ".", "MouseWheel", ":", "event", ".", "delta", ">", "0", ",", "EventType", ".", "ButtonPress", ":", "event", ".", "num", "==", "4", "}", "lines", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/tree.py#L59-L81
Ewenwan/MVision
97b394dfa48cb21c82cd003b1a952745e413a17f
vSLAM/矩阵变换python函数.py
python
random_quaternion
(rand=None)
return numpy.array((numpy.sin(t1)*r1, numpy.cos(t1)*r1, numpy.sin(t2)*r2, numpy.cos(t2)*r2), dtype=numpy.float64)
Return uniform random unit quaternion. rand: array like or None Three independent random variables that are uniformly distributed between 0 and 1. >>> q = random_quaternion() >>> numpy.allclose(1.0, vector_norm(q)) True >>> q = random_quaternion(numpy.random.random(3)) >>> q.shape (4,)
Return uniform random unit quaternion. rand: array like or None Three independent random variables that are uniformly distributed between 0 and 1. >>> q = random_quaternion() >>> numpy.allclose(1.0, vector_norm(q)) True >>> q = random_quaternion(numpy.random.random(3)) >>> q.shape (4,)
[ "Return", "uniform", "random", "unit", "quaternion", ".", "rand", ":", "array", "like", "or", "None", "Three", "independent", "random", "variables", "that", "are", "uniformly", "distributed", "between", "0", "and", "1", ".", ">>>", "q", "=", "random_quaternion...
def random_quaternion(rand=None): """Return uniform random unit quaternion. rand: array like or None Three independent random variables that are uniformly distributed between 0 and 1. >>> q = random_quaternion() >>> numpy.allclose(1.0, vector_norm(q)) True >>> q = random_quaternion(numpy.random.random(3)) >>> q.shape (4,) """ if rand is None: rand = numpy.random.rand(3) else: assert len(rand) == 3 r1 = numpy.sqrt(1.0 - rand[0]) r2 = numpy.sqrt(rand[0]) pi2 = math.pi * 2.0 t1 = pi2 * rand[1] t2 = pi2 * rand[2] return numpy.array((numpy.sin(t1)*r1, numpy.cos(t1)*r1, numpy.sin(t2)*r2, numpy.cos(t2)*r2), dtype=numpy.float64)
[ "def", "random_quaternion", "(", "rand", "=", "None", ")", ":", "if", "rand", "is", "None", ":", "rand", "=", "numpy", ".", "random", ".", "rand", "(", "3", ")", "else", ":", "assert", "len", "(", "rand", ")", "==", "3", "r1", "=", "numpy", ".", ...
https://github.com/Ewenwan/MVision/blob/97b394dfa48cb21c82cd003b1a952745e413a17f/vSLAM/矩阵变换python函数.py#L1208-L1232
google/syzygy
8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5
third_party/numpy/files/numpy/polynomial/laguerre.py
python
poly2lag
(pol)
return res
poly2lag(pol) Convert a polynomial to a Laguerre series. Convert an array representing the coefficients of a polynomial (relative to the "standard" basis) ordered from lowest degree to highest, to an array of the coefficients of the equivalent Laguerre series, ordered from lowest to highest degree. Parameters ---------- pol : array_like 1-d array containing the polynomial coefficients Returns ------- cs : ndarray 1-d array containing the coefficients of the equivalent Laguerre series. See Also -------- lag2poly Notes ----- The easy way to do conversions between polynomial basis sets is to use the convert method of a class instance. Examples -------- >>> from numpy.polynomial.laguerre import poly2lag >>> poly2lag(np.arange(4)) array([ 23., -63., 58., -18.])
poly2lag(pol)
[ "poly2lag", "(", "pol", ")" ]
def poly2lag(pol) : """ poly2lag(pol) Convert a polynomial to a Laguerre series. Convert an array representing the coefficients of a polynomial (relative to the "standard" basis) ordered from lowest degree to highest, to an array of the coefficients of the equivalent Laguerre series, ordered from lowest to highest degree. Parameters ---------- pol : array_like 1-d array containing the polynomial coefficients Returns ------- cs : ndarray 1-d array containing the coefficients of the equivalent Laguerre series. See Also -------- lag2poly Notes ----- The easy way to do conversions between polynomial basis sets is to use the convert method of a class instance. Examples -------- >>> from numpy.polynomial.laguerre import poly2lag >>> poly2lag(np.arange(4)) array([ 23., -63., 58., -18.]) """ [pol] = pu.as_series([pol]) deg = len(pol) - 1 res = 0 for i in range(deg, -1, -1) : res = lagadd(lagmulx(res), pol[i]) return res
[ "def", "poly2lag", "(", "pol", ")", ":", "[", "pol", "]", "=", "pu", ".", "as_series", "(", "[", "pol", "]", ")", "deg", "=", "len", "(", "pol", ")", "-", "1", "res", "=", "0", "for", "i", "in", "range", "(", "deg", ",", "-", "1", ",", "-...
https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/polynomial/laguerre.py#L66-L109
tfwu/FaceDetection-ConvNet-3D
f9251c48eb40c5aec8fba7455115c355466555be
example/model-parallel-lstm/lstm.py
python
lstm
(num_hidden, indata, prev_state, param, seqidx, layeridx, dropout=0.)
return LSTMState(c=next_c, h=next_h)
LSTM Cell symbol
LSTM Cell symbol
[ "LSTM", "Cell", "symbol" ]
def lstm(num_hidden, indata, prev_state, param, seqidx, layeridx, dropout=0.): """LSTM Cell symbol""" if dropout > 0.: indata = mx.sym.Dropout(data=indata, p=dropout) i2h = mx.sym.FullyConnected(data=indata, weight=param.i2h_weight, bias=param.i2h_bias, num_hidden=num_hidden * 4, name="t%d_l%d_i2h" % (seqidx, layeridx)) h2h = mx.sym.FullyConnected(data=prev_state.h, weight=param.h2h_weight, bias=param.h2h_bias, num_hidden=num_hidden * 4, name="t%d_l%d_h2h" % (seqidx, layeridx)) gates = i2h + h2h slice_gates = mx.sym.SliceChannel(gates, num_outputs=4, name="t%d_l%d_slice" % (seqidx, layeridx)) in_gate = mx.sym.Activation(slice_gates[0], act_type="sigmoid") in_transform = mx.sym.Activation(slice_gates[1], act_type="tanh") forget_gate = mx.sym.Activation(slice_gates[2], act_type="sigmoid") out_gate = mx.sym.Activation(slice_gates[3], act_type="sigmoid") next_c = (forget_gate * prev_state.c) + (in_gate * in_transform) next_h = out_gate * mx.sym.Activation(next_c, act_type="tanh") return LSTMState(c=next_c, h=next_h)
[ "def", "lstm", "(", "num_hidden", ",", "indata", ",", "prev_state", ",", "param", ",", "seqidx", ",", "layeridx", ",", "dropout", "=", "0.", ")", ":", "if", "dropout", ">", "0.", ":", "indata", "=", "mx", ".", "sym", ".", "Dropout", "(", "data", "=...
https://github.com/tfwu/FaceDetection-ConvNet-3D/blob/f9251c48eb40c5aec8fba7455115c355466555be/example/model-parallel-lstm/lstm.py#L17-L40
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py3/numpy/polynomial/laguerre.py
python
lagadd
(c1, c2)
return pu._add(c1, c2)
Add one Laguerre series to another. Returns the sum of two Laguerre series `c1` + `c2`. The arguments are sequences of coefficients ordered from lowest order term to highest, i.e., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``. Parameters ---------- c1, c2 : array_like 1-D arrays of Laguerre series coefficients ordered from low to high. Returns ------- out : ndarray Array representing the Laguerre series of their sum. See Also -------- lagsub, lagmulx, lagmul, lagdiv, lagpow Notes ----- Unlike multiplication, division, etc., the sum of two Laguerre series is a Laguerre series (without having to "reproject" the result onto the basis set) so addition, just like that of "standard" polynomials, is simply "component-wise." Examples -------- >>> from numpy.polynomial.laguerre import lagadd >>> lagadd([1, 2, 3], [1, 2, 3, 4]) array([2., 4., 6., 4.])
Add one Laguerre series to another.
[ "Add", "one", "Laguerre", "series", "to", "another", "." ]
def lagadd(c1, c2): """ Add one Laguerre series to another. Returns the sum of two Laguerre series `c1` + `c2`. The arguments are sequences of coefficients ordered from lowest order term to highest, i.e., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``. Parameters ---------- c1, c2 : array_like 1-D arrays of Laguerre series coefficients ordered from low to high. Returns ------- out : ndarray Array representing the Laguerre series of their sum. See Also -------- lagsub, lagmulx, lagmul, lagdiv, lagpow Notes ----- Unlike multiplication, division, etc., the sum of two Laguerre series is a Laguerre series (without having to "reproject" the result onto the basis set) so addition, just like that of "standard" polynomials, is simply "component-wise." Examples -------- >>> from numpy.polynomial.laguerre import lagadd >>> lagadd([1, 2, 3], [1, 2, 3, 4]) array([2., 4., 6., 4.]) """ return pu._add(c1, c2)
[ "def", "lagadd", "(", "c1", ",", "c2", ")", ":", "return", "pu", ".", "_add", "(", "c1", ",", "c2", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/polynomial/laguerre.py#L307-L345
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/dynamodb2/table.py
python
Table.query_count
(self, index=None, consistent=False, conditional_operator=None, query_filter=None, scan_index_forward=True, limit=None, exclusive_start_key=None, **filter_kwargs)
return count_buffer
Queries the exact count of matching items in a DynamoDB table. Queries can be performed against a hash key, a hash+range key or against any data stored in your local secondary indexes. Query filters can be used to filter on arbitrary fields. To specify the filters of the items you'd like to get, you can specify the filters as kwargs. Each filter kwarg should follow the pattern ``<fieldname>__<filter_operation>=<value_to_look_for>``. Query filters are specified in the same way. Optionally accepts an ``index`` parameter, which should be a string of name of the local secondary index you want to query against. (Default: ``None``) Optionally accepts a ``consistent`` parameter, which should be a boolean. If you provide ``True``, it will force a consistent read of the data (more expensive). (Default: ``False`` - use eventually consistent reads) Optionally accepts a ``query_filter`` which is a dictionary of filter conditions against any arbitrary field in the returned data. Optionally accepts a ``conditional_operator`` which applies to the query filter conditions: + `AND` - True if all filter conditions evaluate to true (default) + `OR` - True if at least one filter condition evaluates to true Optionally accept a ``exclusive_start_key`` which is used to get the remaining items when a query cannot return the complete count. Returns an integer which represents the exact amount of matched items. :type scan_index_forward: boolean :param scan_index_forward: Specifies ascending (true) or descending (false) traversal of the index. DynamoDB returns results reflecting the requested order determined by the range key. If the data type is Number, the results are returned in numeric order. For String, the results are returned in order of ASCII character code values. For Binary, DynamoDB treats each byte of the binary data as unsigned when it compares binary values. If ScanIndexForward is not specified, the results are returned in ascending order. :type limit: integer :param limit: The maximum number of items to evaluate (not necessarily the number of matching items). Example:: # Look for last names equal to "Doe". >>> users.query_count(last_name__eq='Doe') 5 # Use an LSI & a consistent read. >>> users.query_count( ... date_joined__gte=1236451000, ... owner__eq=1, ... index='DateJoinedIndex', ... consistent=True ... ) 2
Queries the exact count of matching items in a DynamoDB table.
[ "Queries", "the", "exact", "count", "of", "matching", "items", "in", "a", "DynamoDB", "table", "." ]
def query_count(self, index=None, consistent=False, conditional_operator=None, query_filter=None, scan_index_forward=True, limit=None, exclusive_start_key=None, **filter_kwargs): """ Queries the exact count of matching items in a DynamoDB table. Queries can be performed against a hash key, a hash+range key or against any data stored in your local secondary indexes. Query filters can be used to filter on arbitrary fields. To specify the filters of the items you'd like to get, you can specify the filters as kwargs. Each filter kwarg should follow the pattern ``<fieldname>__<filter_operation>=<value_to_look_for>``. Query filters are specified in the same way. Optionally accepts an ``index`` parameter, which should be a string of name of the local secondary index you want to query against. (Default: ``None``) Optionally accepts a ``consistent`` parameter, which should be a boolean. If you provide ``True``, it will force a consistent read of the data (more expensive). (Default: ``False`` - use eventually consistent reads) Optionally accepts a ``query_filter`` which is a dictionary of filter conditions against any arbitrary field in the returned data. Optionally accepts a ``conditional_operator`` which applies to the query filter conditions: + `AND` - True if all filter conditions evaluate to true (default) + `OR` - True if at least one filter condition evaluates to true Optionally accept a ``exclusive_start_key`` which is used to get the remaining items when a query cannot return the complete count. Returns an integer which represents the exact amount of matched items. :type scan_index_forward: boolean :param scan_index_forward: Specifies ascending (true) or descending (false) traversal of the index. DynamoDB returns results reflecting the requested order determined by the range key. If the data type is Number, the results are returned in numeric order. For String, the results are returned in order of ASCII character code values. For Binary, DynamoDB treats each byte of the binary data as unsigned when it compares binary values. If ScanIndexForward is not specified, the results are returned in ascending order. :type limit: integer :param limit: The maximum number of items to evaluate (not necessarily the number of matching items). Example:: # Look for last names equal to "Doe". >>> users.query_count(last_name__eq='Doe') 5 # Use an LSI & a consistent read. >>> users.query_count( ... date_joined__gte=1236451000, ... owner__eq=1, ... index='DateJoinedIndex', ... consistent=True ... ) 2 """ key_conditions = self._build_filters( filter_kwargs, using=QUERY_OPERATORS ) built_query_filter = self._build_filters( query_filter, using=FILTER_OPERATORS ) count_buffer = 0 last_evaluated_key = exclusive_start_key while True: raw_results = self.connection.query( self.table_name, index_name=index, consistent_read=consistent, select='COUNT', key_conditions=key_conditions, query_filter=built_query_filter, conditional_operator=conditional_operator, limit=limit, scan_index_forward=scan_index_forward, exclusive_start_key=last_evaluated_key ) count_buffer += int(raw_results.get('Count', 0)) last_evaluated_key = raw_results.get('LastEvaluatedKey') if not last_evaluated_key or count_buffer < 1: break return count_buffer
[ "def", "query_count", "(", "self", ",", "index", "=", "None", ",", "consistent", "=", "False", ",", "conditional_operator", "=", "None", ",", "query_filter", "=", "None", ",", "scan_index_forward", "=", "True", ",", "limit", "=", "None", ",", "exclusive_star...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/dynamodb2/table.py#L1205-L1308
macchina-io/macchina.io
ef24ba0e18379c3dd48fb84e6dbf991101cb8db0
platform/JS/V8/tools/gyp/pylib/gyp/generator/analyzer.py
python
_GetCompileTargets
(matching_targets, supplied_targets)
return result
Returns the set of Targets that require a build. matching_targets: targets that changed and need to be built. supplied_targets: set of targets supplied to analyzer to search from.
Returns the set of Targets that require a build. matching_targets: targets that changed and need to be built. supplied_targets: set of targets supplied to analyzer to search from.
[ "Returns", "the", "set", "of", "Targets", "that", "require", "a", "build", ".", "matching_targets", ":", "targets", "that", "changed", "and", "need", "to", "be", "built", ".", "supplied_targets", ":", "set", "of", "targets", "supplied", "to", "analyzer", "to...
def _GetCompileTargets(matching_targets, supplied_targets): """Returns the set of Targets that require a build. matching_targets: targets that changed and need to be built. supplied_targets: set of targets supplied to analyzer to search from.""" result = set() for target in matching_targets: print 'finding compile targets for match', target.name _AddCompileTargets(target, supplied_targets, True, result) return result
[ "def", "_GetCompileTargets", "(", "matching_targets", ",", "supplied_targets", ")", ":", "result", "=", "set", "(", ")", "for", "target", "in", "matching_targets", ":", "print", "'finding compile targets for match'", ",", "target", ".", "name", "_AddCompileTargets", ...
https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/tools/gyp/pylib/gyp/generator/analyzer.py#L497-L505
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/data/util/nest.py
python
assert_same_structure
(nest1, nest2, check_types=True)
Asserts that two structures are nested in the same way. Args: nest1: an arbitrarily nested structure. nest2: an arbitrarily nested structure. check_types: if `True` (default) types of sequences should be same as well. For dictionary, "type" of dictionary is considered to include its keys. In other words, two dictionaries with different keys are considered to have a different "type". If set to `False`, two iterables are considered same as long as they yield the elements that have same structures. Raises: ValueError: If the two structures do not have the same number of elements or if the two structures are not nested in the same way. TypeError: If the two structures differ in the type of sequence in any of their substructures. Only possible if `check_types` is `True`.
Asserts that two structures are nested in the same way.
[ "Asserts", "that", "two", "structures", "are", "nested", "in", "the", "same", "way", "." ]
def assert_same_structure(nest1, nest2, check_types=True): """Asserts that two structures are nested in the same way. Args: nest1: an arbitrarily nested structure. nest2: an arbitrarily nested structure. check_types: if `True` (default) types of sequences should be same as well. For dictionary, "type" of dictionary is considered to include its keys. In other words, two dictionaries with different keys are considered to have a different "type". If set to `False`, two iterables are considered same as long as they yield the elements that have same structures. Raises: ValueError: If the two structures do not have the same number of elements or if the two structures are not nested in the same way. TypeError: If the two structures differ in the type of sequence in any of their substructures. Only possible if `check_types` is `True`. """ _pywrap_tensorflow.AssertSameStructureForData(nest1, nest2, check_types)
[ "def", "assert_same_structure", "(", "nest1", ",", "nest2", ",", "check_types", "=", "True", ")", ":", "_pywrap_tensorflow", ".", "AssertSameStructureForData", "(", "nest1", ",", "nest2", ",", "check_types", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/data/util/nest.py#L104-L123
facebookincubator/BOLT
88c70afe9d388ad430cc150cc158641701397f70
clang/tools/scan-build-py/lib/libscanbuild/clang.py
python
get_arguments
(command, cwd)
return decode(last_line)
Capture Clang invocation. :param command: the compilation command :param cwd: the current working directory :return: the detailed front-end invocation command
Capture Clang invocation.
[ "Capture", "Clang", "invocation", "." ]
def get_arguments(command, cwd): """ Capture Clang invocation. :param command: the compilation command :param cwd: the current working directory :return: the detailed front-end invocation command """ cmd = command[:] cmd.insert(1, '-###') cmd.append('-fno-color-diagnostics') output = run_command(cmd, cwd=cwd) # The relevant information is in the last line of the output. # Don't check if finding last line fails, would throw exception anyway. last_line = output[-1] if re.search(r'clang(.*): error:', last_line): raise ClangErrorException(last_line) return decode(last_line)
[ "def", "get_arguments", "(", "command", ",", "cwd", ")", ":", "cmd", "=", "command", "[", ":", "]", "cmd", ".", "insert", "(", "1", ",", "'-###'", ")", "cmd", ".", "append", "(", "'-fno-color-diagnostics'", ")", "output", "=", "run_command", "(", "cmd"...
https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/clang/tools/scan-build-py/lib/libscanbuild/clang.py#L38-L55
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/session_ops.py
python
_get_handle_mover
(graph, feeder, handle)
return result
Return a move subgraph for this pair of feeder and handle.
Return a move subgraph for this pair of feeder and handle.
[ "Return", "a", "move", "subgraph", "for", "this", "pair", "of", "feeder", "and", "handle", "." ]
def _get_handle_mover(graph, feeder, handle): """Return a move subgraph for this pair of feeder and handle.""" dtype = _get_handle_feeder(graph, feeder) if dtype is None: return None handle_device = TensorHandle._get_device_name(handle) if feeder.op.device == handle_device: return None # Now we know we have to move the tensor. graph_key = TensorHandle._get_mover_key(feeder, handle) result = graph._handle_movers.get(graph_key) if result is None: # Create mover if we haven't done it. holder, reader = _get_handle_reader(graph, handle, dtype) with graph.as_default(), graph.device(feeder.op.device): mover = gen_data_flow_ops.get_session_handle(reader) result = (holder, mover) graph._handle_movers[graph_key] = result return result
[ "def", "_get_handle_mover", "(", "graph", ",", "feeder", ",", "handle", ")", ":", "dtype", "=", "_get_handle_feeder", "(", "graph", ",", "feeder", ")", "if", "dtype", "is", "None", ":", "return", "None", "handle_device", "=", "TensorHandle", ".", "_get_devic...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/session_ops.py#L266-L284
cybermaggedon/cyberprobe
f826dbc35ad3a79019cb871c0bc3fb1236130b3e
indicators/cyberprobe/indicators.py
python
load_indicator
(obj)
return ii
Loads an indicator from a Python dict object
Loads an indicator from a Python dict object
[ "Loads", "an", "indicator", "from", "a", "Python", "dict", "object" ]
def load_indicator(obj): """ Loads an indicator from a Python dict object """ des = load_descriptor(obj["descriptor"]) ii = Indicator(des, id = obj["id"]) ii.value = load_value(obj) return ii
[ "def", "load_indicator", "(", "obj", ")", ":", "des", "=", "load_descriptor", "(", "obj", "[", "\"descriptor\"", "]", ")", "ii", "=", "Indicator", "(", "des", ",", "id", "=", "obj", "[", "\"id\"", "]", ")", "ii", ".", "value", "=", "load_value", "(",...
https://github.com/cybermaggedon/cyberprobe/blob/f826dbc35ad3a79019cb871c0bc3fb1236130b3e/indicators/cyberprobe/indicators.py#L134-L139
HyeonwooNoh/caffe
d9e8494a2832d67b25dee37194c7bcb9d52d0e42
scripts/cpp_lint.py
python
CheckCStyleCast
(filename, linenum, line, raw_line, cast_type, pattern, error)
return True
Checks for a C-style cast by looking for the pattern. Args: filename: The name of the current file. linenum: The number of the line to check. line: The line of code to check. raw_line: The raw line of code to check, with comments. cast_type: The string for the C++ cast to recommend. This is either reinterpret_cast, static_cast, or const_cast, depending. pattern: The regular expression used to find C-style casts. error: The function to call with any errors found. Returns: True if an error was emitted. False otherwise.
Checks for a C-style cast by looking for the pattern.
[ "Checks", "for", "a", "C", "-", "style", "cast", "by", "looking", "for", "the", "pattern", "." ]
def CheckCStyleCast(filename, linenum, line, raw_line, cast_type, pattern, error): """Checks for a C-style cast by looking for the pattern. Args: filename: The name of the current file. linenum: The number of the line to check. line: The line of code to check. raw_line: The raw line of code to check, with comments. cast_type: The string for the C++ cast to recommend. This is either reinterpret_cast, static_cast, or const_cast, depending. pattern: The regular expression used to find C-style casts. error: The function to call with any errors found. Returns: True if an error was emitted. False otherwise. """ match = Search(pattern, line) if not match: return False # Exclude lines with sizeof, since sizeof looks like a cast. sizeof_match = Match(r'.*sizeof\s*$', line[0:match.start(1) - 1]) if sizeof_match: return False # operator++(int) and operator--(int) if (line[0:match.start(1) - 1].endswith(' operator++') or line[0:match.start(1) - 1].endswith(' operator--')): return False # A single unnamed argument for a function tends to look like old # style cast. If we see those, don't issue warnings for deprecated # casts, instead issue warnings for unnamed arguments where # appropriate. # # These are things that we want warnings for, since the style guide # explicitly require all parameters to be named: # Function(int); # Function(int) { # ConstMember(int) const; # ConstMember(int) const { # ExceptionMember(int) throw (...); # ExceptionMember(int) throw (...) { # PureVirtual(int) = 0; # # These are functions of some sort, where the compiler would be fine # if they had named parameters, but people often omit those # identifiers to reduce clutter: # (FunctionPointer)(int); # (FunctionPointer)(int) = value; # Function((function_pointer_arg)(int)) # <TemplateArgument(int)>; # <(FunctionPointerTemplateArgument)(int)>; remainder = line[match.end(0):] if Match(r'^\s*(?:;|const\b|throw\b|=|>|\{|\))', remainder): # Looks like an unnamed parameter. # Don't warn on any kind of template arguments. if Match(r'^\s*>', remainder): return False # Don't warn on assignments to function pointers, but keep warnings for # unnamed parameters to pure virtual functions. Note that this pattern # will also pass on assignments of "0" to function pointers, but the # preferred values for those would be "nullptr" or "NULL". matched_zero = Match(r'^\s=\s*(\S+)\s*;', remainder) if matched_zero and matched_zero.group(1) != '0': return False # Don't warn on function pointer declarations. For this we need # to check what came before the "(type)" string. if Match(r'.*\)\s*$', line[0:match.start(0)]): return False # Don't warn if the parameter is named with block comments, e.g.: # Function(int /*unused_param*/); if '/*' in raw_line: return False # Passed all filters, issue warning here. error(filename, linenum, 'readability/function', 3, 'All parameters should be named in a function') return True # At this point, all that should be left is actual casts. error(filename, linenum, 'readability/casting', 4, 'Using C-style cast. Use %s<%s>(...) instead' % (cast_type, match.group(1))) return True
[ "def", "CheckCStyleCast", "(", "filename", ",", "linenum", ",", "line", ",", "raw_line", ",", "cast_type", ",", "pattern", ",", "error", ")", ":", "match", "=", "Search", "(", "pattern", ",", "line", ")", "if", "not", "match", ":", "return", "False", "...
https://github.com/HyeonwooNoh/caffe/blob/d9e8494a2832d67b25dee37194c7bcb9d52d0e42/scripts/cpp_lint.py#L4247-L4338
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/onnx/mx2onnx/_op_translations/_op_translations_opset12.py
python
convert_mul_scalar
(node, **kwargs)
return scalar_op_helper(node, 'Mul', **kwargs)
Map MXNet's _mul_scalar operator attributes to onnx's Mul operator. Creates a new node for the input scalar value, adds it to the initializer and return multiple created nodes.
Map MXNet's _mul_scalar operator attributes to onnx's Mul operator. Creates a new node for the input scalar value, adds it to the initializer and return multiple created nodes.
[ "Map", "MXNet", "s", "_mul_scalar", "operator", "attributes", "to", "onnx", "s", "Mul", "operator", ".", "Creates", "a", "new", "node", "for", "the", "input", "scalar", "value", "adds", "it", "to", "the", "initializer", "and", "return", "multiple", "created"...
def convert_mul_scalar(node, **kwargs): """Map MXNet's _mul_scalar operator attributes to onnx's Mul operator. Creates a new node for the input scalar value, adds it to the initializer and return multiple created nodes. """ return scalar_op_helper(node, 'Mul', **kwargs)
[ "def", "convert_mul_scalar", "(", "node", ",", "*", "*", "kwargs", ")", ":", "return", "scalar_op_helper", "(", "node", ",", "'Mul'", ",", "*", "*", "kwargs", ")" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/onnx/mx2onnx/_op_translations/_op_translations_opset12.py#L1314-L1319
echronos/echronos
c996f1d2c8af6c6536205eb319c1bf1d4d84569c
external_tools/ply_info/example/yply/yparse.py
python
p_rules
(p)
rules : rules rule | rule
rules : rules rule | rule
[ "rules", ":", "rules", "rule", "|", "rule" ]
def p_rules(p): '''rules : rules rule | rule''' if len(p) == 2: rule = p[1] else: rule = p[2] # Print out a Python equivalent of this rule embedded = [ ] # Embedded actions (a mess) embed_count = 0 rulename = rule[0] rulecount = 1 for r in rule[1]: # r contains one of the rule possibilities print "def p_%s_%d(p):" % (rulename,rulecount) prod = [] prodcode = "" for i in range(len(r)): item = r[i] if item[0] == '{': # A code block if i == len(r) - 1: prodcode = item break else: # an embedded action embed_name = "_embed%d_%s" % (embed_count,rulename) prod.append(embed_name) embedded.append((embed_name,item)) embed_count += 1 else: prod.append(item) print " '''%s : %s'''" % (rulename, " ".join(prod)) # Emit code print_code(prodcode,4) print rulecount += 1 for e,code in embedded: print "def p_%s(p):" % e print " '''%s : '''" % e print_code(code,4) print
[ "def", "p_rules", "(", "p", ")", ":", "if", "len", "(", "p", ")", "==", "2", ":", "rule", "=", "p", "[", "1", "]", "else", ":", "rule", "=", "p", "[", "2", "]", "# Print out a Python equivalent of this rule", "embedded", "=", "[", "]", "# Embedded ac...
https://github.com/echronos/echronos/blob/c996f1d2c8af6c6536205eb319c1bf1d4d84569c/external_tools/ply_info/example/yply/yparse.py#L107-L151
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib2to3/pytree.py
python
Base.__eq__
(self, other)
return self._eq(other)
Compare two nodes for equality. This calls the method _eq().
Compare two nodes for equality.
[ "Compare", "two", "nodes", "for", "equality", "." ]
def __eq__(self, other): """ Compare two nodes for equality. This calls the method _eq(). """ if self.__class__ is not other.__class__: return NotImplemented return self._eq(other)
[ "def", "__eq__", "(", "self", ",", "other", ")", ":", "if", "self", ".", "__class__", "is", "not", "other", ".", "__class__", ":", "return", "NotImplemented", "return", "self", ".", "_eq", "(", "other", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib2to3/pytree.py#L55-L63
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/pydoc.py
python
TextDoc.docother
(self, object, name=None, mod=None, parent=None, maxlen=None, doc=None)
return line
Produce text documentation for a data object.
Produce text documentation for a data object.
[ "Produce", "text", "documentation", "for", "a", "data", "object", "." ]
def docother(self, object, name=None, mod=None, parent=None, maxlen=None, doc=None): """Produce text documentation for a data object.""" repr = self.repr(object) if maxlen: line = (name and name + ' = ' or '') + repr chop = maxlen - len(line) if chop < 0: repr = repr[:chop] + '...' line = (name and self.bold(name) + ' = ' or '') + repr if doc is not None: line += '\n' + self.indent(str(doc)) return line
[ "def", "docother", "(", "self", ",", "object", ",", "name", "=", "None", ",", "mod", "=", "None", ",", "parent", "=", "None", ",", "maxlen", "=", "None", ",", "doc", "=", "None", ")", ":", "repr", "=", "self", ".", "repr", "(", "object", ")", "...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/pydoc.py#L1358-L1368
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/buildscripts/idl/idl/writer.py
python
EmptyBlock.__exit__
(self, *args)
Do nothing.
Do nothing.
[ "Do", "nothing", "." ]
def __exit__(self, *args): # type: (*str) -> None """Do nothing.""" pass
[ "def", "__exit__", "(", "self", ",", "*", "args", ")", ":", "# type: (*str) -> None", "pass" ]
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/idl/idl/writer.py#L181-L184
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/contrib/distributions/python/ops/bijector.py
python
_Bijector.inverse
(self, x, name='inverse')
Returns the inverse bijector evaluation, i.e., X = g^{-1}(Y). Args: x: `Tensor`. The input to the "inverse" evaluation. name: The name to give this op. Returns: `Tensor`.
Returns the inverse bijector evaluation, i.e., X = g^{-1}(Y).
[ "Returns", "the", "inverse", "bijector", "evaluation", "i", ".", "e", ".", "X", "=", "g^", "{", "-", "1", "}", "(", "Y", ")", "." ]
def inverse(self, x, name='inverse'): """Returns the inverse bijector evaluation, i.e., X = g^{-1}(Y). Args: x: `Tensor`. The input to the "inverse" evaluation. name: The name to give this op. Returns: `Tensor`. """ with ops.name_scope(self.name): with ops.op_scope([x], name): x = ops.convert_to_tensor(x) try: return self._inverse(x) except NotImplementedError: return self._inverse_and_inverse_log_det_jacobian(x)[0]
[ "def", "inverse", "(", "self", ",", "x", ",", "name", "=", "'inverse'", ")", ":", "with", "ops", ".", "name_scope", "(", "self", ".", "name", ")", ":", "with", "ops", ".", "op_scope", "(", "[", "x", "]", ",", "name", ")", ":", "x", "=", "ops", ...
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/bijector.py#L166-L182
musescore/MuseScore
a817fea23e3c2be30847b7fde5b01746222c252e
thirdparty/freetype/src/tools/glnames.py
python
dump_array
( the_array, write, array_name )
dumps a given encoding
dumps a given encoding
[ "dumps", "a", "given", "encoding" ]
def dump_array( the_array, write, array_name ): """dumps a given encoding""" write( " static const unsigned char " + array_name + "[" + repr( len( the_array ) ) + "L] =\n" ) write( " {\n" ) line = "" comma = " " col = 0 for value in the_array: line += comma line += "%3d" % ord( value ) comma = "," col += 1 if col == 16: col = 0 comma = ",\n " if len( line ) > 1024: write( line ) line = "" write( line + "\n };\n\n\n" )
[ "def", "dump_array", "(", "the_array", ",", "write", ",", "array_name", ")", ":", "write", "(", "\" static const unsigned char \"", "+", "array_name", "+", "\"[\"", "+", "repr", "(", "len", "(", "the_array", ")", ")", "+", "\"L] =\\n\"", ")", "write", "(",...
https://github.com/musescore/MuseScore/blob/a817fea23e3c2be30847b7fde5b01746222c252e/thirdparty/freetype/src/tools/glnames.py#L5210-L5235
protocolbuffers/protobuf
b5ab0b7a18b7336c60130f4ddb2d97c51792f896
python/setup.py
python
GetVersion
()
Gets the version from google/protobuf/__init__.py Do not import google.protobuf.__init__ directly, because an installed protobuf library may be loaded instead.
Gets the version from google/protobuf/__init__.py
[ "Gets", "the", "version", "from", "google", "/", "protobuf", "/", "__init__", ".", "py" ]
def GetVersion(): """Gets the version from google/protobuf/__init__.py Do not import google.protobuf.__init__ directly, because an installed protobuf library may be loaded instead.""" with open(os.path.join('google', 'protobuf', '__init__.py')) as version_file: exec(version_file.read(), globals()) global __version__ return __version__
[ "def", "GetVersion", "(", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "'google'", ",", "'protobuf'", ",", "'__init__.py'", ")", ")", "as", "version_file", ":", "exec", "(", "version_file", ".", "read", "(", ")", ",", "globals", ...
https://github.com/protocolbuffers/protobuf/blob/b5ab0b7a18b7336c60130f4ddb2d97c51792f896/python/setup.py#L39-L48
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/dtypes/common.py
python
ensure_python_int
(value: int | np.integer)
return new_value
Ensure that a value is a python int. Parameters ---------- value: int or numpy.integer Returns ------- int Raises ------ TypeError: if the value isn't an int or can't be converted to one.
Ensure that a value is a python int.
[ "Ensure", "that", "a", "value", "is", "a", "python", "int", "." ]
def ensure_python_int(value: int | np.integer) -> int: """ Ensure that a value is a python int. Parameters ---------- value: int or numpy.integer Returns ------- int Raises ------ TypeError: if the value isn't an int or can't be converted to one. """ if not is_scalar(value): raise TypeError( f"Value needs to be a scalar value, was type {type(value).__name__}" ) try: new_value = int(value) assert new_value == value except (TypeError, ValueError, AssertionError) as err: raise TypeError(f"Wrong type {type(value)} for value {value}") from err return new_value
[ "def", "ensure_python_int", "(", "value", ":", "int", "|", "np", ".", "integer", ")", "->", "int", ":", "if", "not", "is_scalar", "(", "value", ")", ":", "raise", "TypeError", "(", "f\"Value needs to be a scalar value, was type {type(value).__name__}\"", ")", "try...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/dtypes/common.py#L116-L141
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/psutil/_pswindows.py
python
net_if_addrs
()
return ret
Return the addresses associated to each NIC.
Return the addresses associated to each NIC.
[ "Return", "the", "addresses", "associated", "to", "each", "NIC", "." ]
def net_if_addrs(): """Return the addresses associated to each NIC.""" ret = [] for items in cext.net_if_addrs(): items = list(items) items[0] = py2_strencode(items[0]) ret.append(items) return ret
[ "def", "net_if_addrs", "(", ")", ":", "ret", "=", "[", "]", "for", "items", "in", "cext", ".", "net_if_addrs", "(", ")", ":", "items", "=", "list", "(", "items", ")", "items", "[", "0", "]", "=", "py2_strencode", "(", "items", "[", "0", "]", ")",...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/psutil/_pswindows.py#L392-L399
facebook/hermes
b1b1a00ab468ec1b397b31b71587110044830970
lldb/Stack.py
python
_heuristic_search_ip_in_stack
(leaf_frame)
return 0
Heuristically unwind native stack frames to search for local variable ip if available
Heuristically unwind native stack frames to search for local variable ip if available
[ "Heuristically", "unwind", "native", "stack", "frames", "to", "search", "for", "local", "variable", "ip", "if", "available" ]
def _heuristic_search_ip_in_stack(leaf_frame): """Heuristically unwind native stack frames to search for local variable ip if available""" frame = leaf_frame while frame is not None: ip = frame.FindVariable("ip") if ip is not None: return ip.GetValueAsUnsigned() frame = frame.get_parent_frame() return 0
[ "def", "_heuristic_search_ip_in_stack", "(", "leaf_frame", ")", ":", "frame", "=", "leaf_frame", "while", "frame", "is", "not", "None", ":", "ip", "=", "frame", ".", "FindVariable", "(", "\"ip\"", ")", "if", "ip", "is", "not", "None", ":", "return", "ip", ...
https://github.com/facebook/hermes/blob/b1b1a00ab468ec1b397b31b71587110044830970/lldb/Stack.py#L95-L104
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_misc.py
python
Caret.MoveXY
(*args, **kwargs)
return _misc_.Caret_MoveXY(*args, **kwargs)
MoveXY(self, int x, int y)
MoveXY(self, int x, int y)
[ "MoveXY", "(", "self", "int", "x", "int", "y", ")" ]
def MoveXY(*args, **kwargs): """MoveXY(self, int x, int y)""" return _misc_.Caret_MoveXY(*args, **kwargs)
[ "def", "MoveXY", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "Caret_MoveXY", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L774-L776
SmileiPIC/Smilei
07dcb51200029e10f626e1546558c1ae7599c8b1
validation/easi/machines/irene.py
python
MachineIrene.run
(self, arguments, dir)
Run a simulation
Run a simulation
[ "Run", "a", "simulation" ]
def run(self, arguments, dir): """ Run a simulation """ from math import ceil command = self.RUN_COMMAND % arguments if self.options.nodes: self.NODES = self.options.nodes else: self.NODES = int(ceil(self.options.mpi/2.)) ppn = 24 with open(self.smilei_path.exec_script, 'w') as f: f.write( self.script.format(command=command, env=self.env, account=self.options.account, nodes=NODES, ppn=ppn, max_time=self.options.max_time, mpi=self.options.mpi, omp=self.options.omp, dir=dir) ) self.launch_job(command, self.JOB, dir, self.options.max_time_seconds, self.smilei_path.output_file, repeat=2)
[ "def", "run", "(", "self", ",", "arguments", ",", "dir", ")", ":", "from", "math", "import", "ceil", "command", "=", "self", ".", "RUN_COMMAND", "%", "arguments", "if", "self", ".", "options", ".", "nodes", ":", "self", ".", "NODES", "=", "self", "."...
https://github.com/SmileiPIC/Smilei/blob/07dcb51200029e10f626e1546558c1ae7599c8b1/validation/easi/machines/irene.py#L98-L112
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/genpy/src/genpy/generator.py
python
string_serializer_generator
(package, type_, name, serialize)
Generator for string types. similar to arrays, but with more efficient call to struct.pack. :param name: spec field name, ``str`` :param serialize: if ``True``, generate code for serialization. Other, generate code for deserialization, ``bool``
Generator for string types. similar to arrays, but with more efficient call to struct.pack.
[ "Generator", "for", "string", "types", ".", "similar", "to", "arrays", "but", "with", "more", "efficient", "call", "to", "struct", ".", "pack", "." ]
def string_serializer_generator(package, type_, name, serialize): """ Generator for string types. similar to arrays, but with more efficient call to struct.pack. :param name: spec field name, ``str`` :param serialize: if ``True``, generate code for serialization. Other, generate code for deserialization, ``bool`` """ # don't optimize in deserialization case as assignment doesn't # work if _serial_context and serialize: # optimize as string serialization accesses field twice yield "_x = %s%s"%(_serial_context, name) var = "_x" else: var = _serial_context+name # the length generator is a noop if serialize is True as we # optimize the serialization call. base_type, is_array, array_len = genmsg.msgs.parse_type(type_) # - don't serialize length for fixed-length arrays of bytes if base_type not in ['uint8', 'char'] or array_len is None: for y in len_serializer_generator(var, True, serialize): yield y #serialize string length if serialize: #serialize length and string together #check to see if its a uint8/byte type, in which case we need to convert to string before serializing base_type, is_array, array_len = genmsg.msgs.parse_type(type_) if base_type in ['uint8', 'char']: yield "# - if encoded as a list instead, serialize as bytes instead of string" if array_len is None: yield "if type(%s) in [list, tuple]:"%var yield INDENT+pack2("'<I%sB'%length", "length, *%s"%var) yield "else:" yield INDENT+pack2("'<I%ss'%length", "length, %s"%var) else: yield "if type(%s) in [list, tuple]:"%var yield INDENT+pack('%sB'%array_len, "*%s"%var) yield "else:" yield INDENT+pack('%ss'%array_len, var) else: # FIXME: for py3k, this needs to be w/ encode(), but this interferes with actual byte data yield "if python3 or type(%s) == unicode:"%(var) yield INDENT+"%s = %s.encode('utf-8')"%(var,var) #For unicode-strings in Python2, encode using utf-8 yield INDENT+"length = len(%s)"%(var) # Update the length after utf-8 conversion yield "if python3:" yield INDENT+pack2("'<I%sB'%length", "length, *%s"%var) yield "else:" yield INDENT+pack2("'<I%ss'%length", "length, %s"%var) else: yield "start = end" if array_len is not None: yield "end += %s" % array_len yield "%s = str[start:end]" % var else: yield "end += length" if base_type in ['uint8', 'char']: yield "%s = str[start:end]" % (var) else: yield "if python3:" yield INDENT+"%s = str[start:end].decode('utf-8')" % (var) #If messages are python3-decode back to unicode yield "else:" yield INDENT+"%s = str[start:end]" % (var)
[ "def", "string_serializer_generator", "(", "package", ",", "type_", ",", "name", ",", "serialize", ")", ":", "# don't optimize in deserialization case as assignment doesn't", "# work", "if", "_serial_context", "and", "serialize", ":", "# optimize as string serialization accesse...
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/genpy/src/genpy/generator.py#L383-L449
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/peak_integration_utility.py
python
gaussian_peak_intensity
(parameter_dict, error_dict)
return peak_intensity, intensity_error
calculate peak intensity as a Gaussian the equation to calculate Gaussian from -infinity to +infinity is I = A\times s\times\\sqrt{2\\pi} :param parameter_dict: :param error_dict: :return:
calculate peak intensity as a Gaussian the equation to calculate Gaussian from -infinity to +infinity is I = A\times s\times\\sqrt{2\\pi} :param parameter_dict: :param error_dict: :return:
[ "calculate", "peak", "intensity", "as", "a", "Gaussian", "the", "equation", "to", "calculate", "Gaussian", "from", "-", "infinity", "to", "+", "infinity", "is", "I", "=", "A", "\\", "times", "s", "\\", "times", "\\\\", "sqrt", "{", "2", "\\\\", "pi", "...
def gaussian_peak_intensity(parameter_dict, error_dict): """ calculate peak intensity as a Gaussian the equation to calculate Gaussian from -infinity to +infinity is I = A\times s\times\\sqrt{2\\pi} :param parameter_dict: :param error_dict: :return: """ # check input assert isinstance(parameter_dict, dict), 'Parameters {0} must be given as a dictionary but not a {1}.' \ ''.format(parameter_dict, type(parameter_dict)) assert isinstance(error_dict, dict), 'Errors {0} must be given as a dictionary but not a {1}.' \ ''.format(error_dict, type(error_dict)) # get the parameters from the dictionary try: gauss_a = parameter_dict['A'] gauss_sigma = parameter_dict['s'] except KeyError as key_err: raise RuntimeError('Parameter dictionary must have "A", "s" (for sigma) but now only {0}. Error message: {1}' ''.format(parameter_dict.keys(), key_err)) # I = A\times s\times\sqrt{2 pi} peak_intensity = gauss_a * gauss_sigma * numpy.sqrt(2. * numpy.pi) # calculate error # \sigma_I^2 = 2\pi (A^2\cdot \sigma_s^2 + \sigma_A^2\cdot s^2 + 2\cdot A\cdot s\cdot \sigma_{As}) try: error_a_sq = error_dict['A2'] error_s_sq = error_dict['s2'] error_a_s = error_dict['A_s'] except KeyError as key_err: raise RuntimeError('Error dictionary must have "A2", "s2", "A_s" but not only found {0}. FYI: {1}' ''.format(error_dict.keys(), key_err)) intensity_error = numpy.sqrt(2/numpy.pi * (gauss_a**2 * error_s_sq + error_a_sq * gauss_sigma**2 + 2 * gauss_a * gauss_sigma * error_a_s)) return peak_intensity, intensity_error
[ "def", "gaussian_peak_intensity", "(", "parameter_dict", ",", "error_dict", ")", ":", "# check input", "assert", "isinstance", "(", "parameter_dict", ",", "dict", ")", ",", "'Parameters {0} must be given as a dictionary but not a {1}.'", "''", ".", "format", "(", "paramet...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/peak_integration_utility.py#L514-L552
yyzybb537/libgo
4af17b7c67643c4d54aa354dcc77963ea07847d0
third_party/boost.context/tools/build/src/build/feature.py
python
validate_value_string
(f, value_string)
Checks that value-string is a valid value-string for the given feature.
Checks that value-string is a valid value-string for the given feature.
[ "Checks", "that", "value", "-", "string", "is", "a", "valid", "value", "-", "string", "for", "the", "given", "feature", "." ]
def validate_value_string (f, value_string): """ Checks that value-string is a valid value-string for the given feature. """ assert isinstance(f, Feature) assert isinstance(value_string, basestring) if f.free() or value_string in f.values(): return values = [value_string] if f.subfeatures(): if not value_string in f.values() and \ not value_string in f.subfeatures(): values = value_string.split('-') # An empty value is allowed for optional features if not values[0] in f.values() and \ (values[0] or not f.optional()): raise InvalidValue ("'%s' is not a known value of feature '%s'\nlegal values: '%s'" % (values [0], f.name(), f.values())) for v in values [1:]: # this will validate any subfeature values in value-string implied_subfeature(f, v, values[0])
[ "def", "validate_value_string", "(", "f", ",", "value_string", ")", ":", "assert", "isinstance", "(", "f", ",", "Feature", ")", "assert", "isinstance", "(", "value_string", ",", "basestring", ")", "if", "f", ".", "free", "(", ")", "or", "value_string", "in...
https://github.com/yyzybb537/libgo/blob/4af17b7c67643c4d54aa354dcc77963ea07847d0/third_party/boost.context/tools/build/src/build/feature.py#L447-L469
Yelp/MOE
5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c
moe/optimal_learning/python/interfaces/log_likelihood_interface.py
python
GaussianProcessLogLikelihoodInterface.get_hyperparameters
(self)
Get the hyperparameters (array of float64 with shape (num_hyperparameters)) of this covariance.
Get the hyperparameters (array of float64 with shape (num_hyperparameters)) of this covariance.
[ "Get", "the", "hyperparameters", "(", "array", "of", "float64", "with", "shape", "(", "num_hyperparameters", "))", "of", "this", "covariance", "." ]
def get_hyperparameters(self): """Get the hyperparameters (array of float64 with shape (num_hyperparameters)) of this covariance.""" pass
[ "def", "get_hyperparameters", "(", "self", ")", ":", "pass" ]
https://github.com/Yelp/MOE/blob/5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c/moe/optimal_learning/python/interfaces/log_likelihood_interface.py#L118-L120
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_controls.py
python
ToolBarBase.AddSimpleTool
(self, id, bitmap, shortHelpString = '', longHelpString = '', isToggle = 0)
return self.DoAddTool(id, '', bitmap, wx.NullBitmap, kind, shortHelpString, longHelpString, None)
Old style method to add a tool to the toolbar.
Old style method to add a tool to the toolbar.
[ "Old", "style", "method", "to", "add", "a", "tool", "to", "the", "toolbar", "." ]
def AddSimpleTool(self, id, bitmap, shortHelpString = '', longHelpString = '', isToggle = 0): '''Old style method to add a tool to the toolbar.''' kind = wx.ITEM_NORMAL if isToggle: kind = wx.ITEM_CHECK return self.DoAddTool(id, '', bitmap, wx.NullBitmap, kind, shortHelpString, longHelpString, None)
[ "def", "AddSimpleTool", "(", "self", ",", "id", ",", "bitmap", ",", "shortHelpString", "=", "''", ",", "longHelpString", "=", "''", ",", "isToggle", "=", "0", ")", ":", "kind", "=", "wx", ".", "ITEM_NORMAL", "if", "isToggle", ":", "kind", "=", "wx", ...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L3627-L3635
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/richtext.py
python
RichTextFileHandler.CanLoad
(*args, **kwargs)
return _richtext.RichTextFileHandler_CanLoad(*args, **kwargs)
CanLoad(self) -> bool
CanLoad(self) -> bool
[ "CanLoad", "(", "self", ")", "-", ">", "bool" ]
def CanLoad(*args, **kwargs): """CanLoad(self) -> bool""" return _richtext.RichTextFileHandler_CanLoad(*args, **kwargs)
[ "def", "CanLoad", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextFileHandler_CanLoad", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L2776-L2778
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
GridSizer.GetEffectiveRowsCount
(*args, **kwargs)
return _core_.GridSizer_GetEffectiveRowsCount(*args, **kwargs)
GetEffectiveRowsCount(self) -> int
GetEffectiveRowsCount(self) -> int
[ "GetEffectiveRowsCount", "(", "self", ")", "-", ">", "int" ]
def GetEffectiveRowsCount(*args, **kwargs): """GetEffectiveRowsCount(self) -> int""" return _core_.GridSizer_GetEffectiveRowsCount(*args, **kwargs)
[ "def", "GetEffectiveRowsCount", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "GridSizer_GetEffectiveRowsCount", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L15273-L15275
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/grid.py
python
GridCellAttr.__init__
(self, *args, **kwargs)
__init__(self, GridCellAttr attrDefault=None) -> GridCellAttr
__init__(self, GridCellAttr attrDefault=None) -> GridCellAttr
[ "__init__", "(", "self", "GridCellAttr", "attrDefault", "=", "None", ")", "-", ">", "GridCellAttr" ]
def __init__(self, *args, **kwargs): """__init__(self, GridCellAttr attrDefault=None) -> GridCellAttr""" _grid.GridCellAttr_swiginit(self,_grid.new_GridCellAttr(*args, **kwargs)) self._setOORInfo(self)
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_grid", ".", "GridCellAttr_swiginit", "(", "self", ",", "_grid", ".", "new_GridCellAttr", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", "self", ".", "_setOOR...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/grid.py#L528-L531
fnplus/interview-techdev-guide
eaca1b6db4b27e9813aaec25a199b1baa4f9439b
Algorithms/Searching & Sorting/Exponential Search/exponential_search.py
python
binary_search
(arr, s, e, x)
return -1
#arr: the array in which we need to find an element (sorted, increasing order) #s: start index #e: end index #x: element we are looking for
#arr: the array in which we need to find an element (sorted, increasing order) #s: start index #e: end index #x: element we are looking for
[ "#arr", ":", "the", "array", "in", "which", "we", "need", "to", "find", "an", "element", "(", "sorted", "increasing", "order", ")", "#s", ":", "start", "index", "#e", ":", "end", "index", "#x", ":", "element", "we", "are", "looking", "for" ]
def binary_search(arr, s, e, x): ''' #arr: the array in which we need to find an element (sorted, increasing order) #s: start index #e: end index #x: element we are looking for ''' #search until arr becomes empty [] while (e>=s): m = s + int((e-s)/2) #middle index if x==arr[m]: #if found at mid return index return m elif x>arr[m]: #if x>arr[m] search only in the right array s = m+1 elif x<arr[m]: #if x<arr[m] search only in the left array e = m-1 return -1
[ "def", "binary_search", "(", "arr", ",", "s", ",", "e", ",", "x", ")", ":", "#search until arr becomes empty []", "while", "(", "e", ">=", "s", ")", ":", "m", "=", "s", "+", "int", "(", "(", "e", "-", "s", ")", "/", "2", ")", "#middle index", "if...
https://github.com/fnplus/interview-techdev-guide/blob/eaca1b6db4b27e9813aaec25a199b1baa4f9439b/Algorithms/Searching & Sorting/Exponential Search/exponential_search.py#L10-L28
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/framework/function.py
python
_get_kwarg_as_str_attr
(attr_name, value)
Creates an AttrValue for a python object.
Creates an AttrValue for a python object.
[ "Creates", "an", "AttrValue", "for", "a", "python", "object", "." ]
def _get_kwarg_as_str_attr(attr_name, value): """Creates an AttrValue for a python object.""" if isinstance(value, str): return attr_value_pb2.AttrValue(s=compat.as_bytes(value)) else: raise ValueError(f"Attribute {attr_name} must be str. Got {type(value)}.")
[ "def", "_get_kwarg_as_str_attr", "(", "attr_name", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "str", ")", ":", "return", "attr_value_pb2", ".", "AttrValue", "(", "s", "=", "compat", ".", "as_bytes", "(", "value", ")", ")", "else", ":"...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/framework/function.py#L1212-L1217
nasa/fprime
595cf3682d8365943d86c1a6fe7c78f0a116acf0
Autocoders/Python/src/fprime_ac/generators/visitors/SerialCppVisitor.py
python
SerialCppVisitor.publicVisit
(self, obj)
Defined to generate public stuff within a class. @param args: the instance of the concrete element to operation on.
Defined to generate public stuff within a class.
[ "Defined", "to", "generate", "public", "stuff", "within", "a", "class", "." ]
def publicVisit(self, obj): """ Defined to generate public stuff within a class. @param args: the instance of the concrete element to operation on. """ c = publicSerialCpp.publicSerialCpp() c.name = obj.get_name() c.args_proto_string = self._get_args_proto_string(obj) c.args_string = self._get_args_string(obj) c.args_mstring = self._get_args_string(obj, "src.m_") c.args_mstring_ptr = self._get_args_string(obj, "src->m_") c.args_scalar_array_string = self._get_args_proto_string_scalar_init(obj) c.members = self._get_conv_mem_list(obj) self._writeTmpl(c, "publicVisit")
[ "def", "publicVisit", "(", "self", ",", "obj", ")", ":", "c", "=", "publicSerialCpp", ".", "publicSerialCpp", "(", ")", "c", ".", "name", "=", "obj", ".", "get_name", "(", ")", "c", ".", "args_proto_string", "=", "self", ".", "_get_args_proto_string", "(...
https://github.com/nasa/fprime/blob/595cf3682d8365943d86c1a6fe7c78f0a116acf0/Autocoders/Python/src/fprime_ac/generators/visitors/SerialCppVisitor.py#L314-L327
pisa-engine/pisa
0efb7926d4928c8aae672ba4d7a1419891f2676d
script/ext/baker.py
python
Baker.apply
(self, scriptname, cmd, args, kwargs, instance=None)
return cmd.fn(*newargs, **newkwargs)
Calls the command function.
Calls the command function.
[ "Calls", "the", "command", "function", "." ]
def apply(self, scriptname, cmd, args, kwargs, instance=None): """ Calls the command function. """ # Create a list of positional arguments: arguments that are either # required (not in keywords), or where the default is None (taken to be # an optional positional argument). This is different from the Python # calling convention, which will fill in keyword arguments with extra # positional arguments. # Rearrange the arguments into the order Python expects newargs = [] newkwargs = kwargs.copy() for name in cmd.argnames: if name in cmd.keywords: if not args: break # keyword arg if cmd.has_varargs: # keyword params are not replaced by bare args if the func # also has varags but they must be specified as positional # args for proper processing of varargs value = cmd.keywords[name] if name in newkwargs: value = newkwargs[name] del newkwargs[name] newargs.append(value) elif not name in newkwargs: newkwargs[name] = args.pop(0) else: # positional arg if name in newkwargs: newargs.append(newkwargs[name]) del newkwargs[name] else: if args: newargs.append(args.pop(0)) else: # This argument is required but we don't have a bare # arg to fill it msg = "Required argument %r not given" raise CommandError(msg % (name), scriptname, cmd) if args: if cmd.has_varargs: newargs.extend(args) else: msg = "Too many arguments to %r: %s" raise CommandError(msg % (cmd.name, args), scriptname, cmd) if not cmd.has_kwargs: for k in newkwargs: if k not in cmd.keywords: raise CommandError("Unknown option --%s" % k, scriptname, cmd) if cmd.is_method and instance is not None: return cmd.fn(instance, *newargs, **newkwargs) return cmd.fn(*newargs, **newkwargs)
[ "def", "apply", "(", "self", ",", "scriptname", ",", "cmd", ",", "args", ",", "kwargs", ",", "instance", "=", "None", ")", ":", "# Create a list of positional arguments: arguments that are either", "# required (not in keywords), or where the default is None (taken to be", "# ...
https://github.com/pisa-engine/pisa/blob/0efb7926d4928c8aae672ba4d7a1419891f2676d/script/ext/baker.py#L807-L866
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/stc.py
python
StyledTextCtrl.GetPunctuationChars
(*args, **kwargs)
return _stc.StyledTextCtrl_GetPunctuationChars(*args, **kwargs)
GetPunctuationChars(self) -> String
GetPunctuationChars(self) -> String
[ "GetPunctuationChars", "(", "self", ")", "-", ">", "String" ]
def GetPunctuationChars(*args, **kwargs): """GetPunctuationChars(self) -> String""" return _stc.StyledTextCtrl_GetPunctuationChars(*args, **kwargs)
[ "def", "GetPunctuationChars", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_GetPunctuationChars", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/stc.py#L5522-L5524
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
DQMServices/Components/python/HTTP.py
python
RequestManager.put
(self, task)
Add a new task. The task object should be a tuple and is passed to ``request_init`` callback passed to the constructor.
Add a new task. The task object should be a tuple and is passed to ``request_init`` callback passed to the constructor.
[ "Add", "a", "new", "task", ".", "The", "task", "object", "should", "be", "a", "tuple", "and", "is", "passed", "to", "request_init", "callback", "passed", "to", "the", "constructor", "." ]
def put(self, task): """Add a new task. The task object should be a tuple and is passed to ``request_init`` callback passed to the constructor.""" self.queue.append(task)
[ "def", "put", "(", "self", ",", "task", ")", ":", "self", ".", "queue", ".", "append", "(", "task", ")" ]
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/DQMServices/Components/python/HTTP.py#L86-L89
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/idl/idl/syntax.py
python
SymbolTable.add_struct
(self, ctxt, struct)
Add an IDL struct to the symbol table and check for duplicates.
Add an IDL struct to the symbol table and check for duplicates.
[ "Add", "an", "IDL", "struct", "to", "the", "symbol", "table", "and", "check", "for", "duplicates", "." ]
def add_struct(self, ctxt, struct): # type: (errors.ParserContext, Struct) -> None """Add an IDL struct to the symbol table and check for duplicates.""" if not self._is_duplicate(ctxt, struct, struct.name, "struct"): self.structs.append(struct)
[ "def", "add_struct", "(", "self", ",", "ctxt", ",", "struct", ")", ":", "# type: (errors.ParserContext, Struct) -> None", "if", "not", "self", ".", "_is_duplicate", "(", "ctxt", ",", "struct", ",", "struct", ".", "name", ",", "\"struct\"", ")", ":", "self", ...
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/idl/idl/syntax.py#L147-L151
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/robotsim.py
python
Simulator.getStatus
(self)
return _robotsim.Simulator_getStatus(self)
getStatus(Simulator self) -> int Returns an indicator code for the simulator status. The return result is one of the STATUS_X flags. (Technically, this returns the *worst* status over the last simulate() call)
getStatus(Simulator self) -> int
[ "getStatus", "(", "Simulator", "self", ")", "-", ">", "int" ]
def getStatus(self): """ getStatus(Simulator self) -> int Returns an indicator code for the simulator status. The return result is one of the STATUS_X flags. (Technically, this returns the *worst* status over the last simulate() call) """ return _robotsim.Simulator_getStatus(self)
[ "def", "getStatus", "(", "self", ")", ":", "return", "_robotsim", ".", "Simulator_getStatus", "(", "self", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/robotsim.py#L8184-L8195
SequoiaDB/SequoiaDB
2894ed7e5bd6fe57330afc900cf76d0ff0df9f64
tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py
python
xpathParserContext.xpathNamespaceURIFunction
(self, nargs)
Implement the namespace-uri() XPath function string namespace-uri(node-set?) The namespace-uri function returns a string containing the namespace URI of the expanded name of the node in the argument node-set that is first in document order. If the node-set is empty, the first node has no name, or the expanded name has no namespace URI, an empty string is returned. If the argument is omitted it defaults to the context node.
Implement the namespace-uri() XPath function string namespace-uri(node-set?) The namespace-uri function returns a string containing the namespace URI of the expanded name of the node in the argument node-set that is first in document order. If the node-set is empty, the first node has no name, or the expanded name has no namespace URI, an empty string is returned. If the argument is omitted it defaults to the context node.
[ "Implement", "the", "namespace", "-", "uri", "()", "XPath", "function", "string", "namespace", "-", "uri", "(", "node", "-", "set?", ")", "The", "namespace", "-", "uri", "function", "returns", "a", "string", "containing", "the", "namespace", "URI", "of", "...
def xpathNamespaceURIFunction(self, nargs): """Implement the namespace-uri() XPath function string namespace-uri(node-set?) The namespace-uri function returns a string containing the namespace URI of the expanded name of the node in the argument node-set that is first in document order. If the node-set is empty, the first node has no name, or the expanded name has no namespace URI, an empty string is returned. If the argument is omitted it defaults to the context node. """ libxml2mod.xmlXPathNamespaceURIFunction(self._o, nargs)
[ "def", "xpathNamespaceURIFunction", "(", "self", ",", "nargs", ")", ":", "libxml2mod", ".", "xmlXPathNamespaceURIFunction", "(", "self", ".", "_o", ",", "nargs", ")" ]
https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L7528-L7537
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/lib2to3/pgen2/driver.py
python
Driver.parse_tokens
(self, tokens, debug=False)
return p.rootnode
Parse a series of tokens and return the syntax tree.
Parse a series of tokens and return the syntax tree.
[ "Parse", "a", "series", "of", "tokens", "and", "return", "the", "syntax", "tree", "." ]
def parse_tokens(self, tokens, debug=False): """Parse a series of tokens and return the syntax tree.""" # XXX Move the prefix computation into a wrapper around tokenize. p = parse.Parser(self.grammar, self.convert) p.setup() lineno = 1 column = 0 type = value = start = end = line_text = None prefix = u"" for quintuple in tokens: type, value, start, end, line_text = quintuple if start != (lineno, column): assert (lineno, column) <= start, ((lineno, column), start) s_lineno, s_column = start if lineno < s_lineno: prefix += "\n" * (s_lineno - lineno) lineno = s_lineno column = 0 if column < s_column: prefix += line_text[column:s_column] column = s_column if type in (tokenize.COMMENT, tokenize.NL): prefix += value lineno, column = end if value.endswith("\n"): lineno += 1 column = 0 continue if type == token.OP: type = grammar.opmap[value] if debug: self.logger.debug("%s %r (prefix=%r)", token.tok_name[type], value, prefix) if p.addtoken(type, value, (prefix, start)): if debug: self.logger.debug("Stop.") break prefix = "" lineno, column = end if value.endswith("\n"): lineno += 1 column = 0 else: # We never broke out -- EOF is too soon (how can this happen???) raise parse.ParseError("incomplete input", type, value, (prefix, start)) return p.rootnode
[ "def", "parse_tokens", "(", "self", ",", "tokens", ",", "debug", "=", "False", ")", ":", "# XXX Move the prefix computation into a wrapper around tokenize.", "p", "=", "parse", ".", "Parser", "(", "self", ".", "grammar", ",", "self", ".", "convert", ")", "p", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib2to3/pgen2/driver.py#L39-L85