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
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/botocore/credentials.py
python
EnvProvider.load
(self)
Search for credentials in explicit environment variables.
Search for credentials in explicit environment variables.
[ "Search", "for", "credentials", "in", "explicit", "environment", "variables", "." ]
def load(self): """ Search for credentials in explicit environment variables. """ access_key = self.environ.get(self._mapping['access_key'], '') if access_key: logger.info('Found credentials in environment variables.') fetcher = self._create_credentials_fetcher() credentials = fetcher(require_expiry=False) expiry_time = credentials['expiry_time'] if expiry_time is not None: expiry_time = parse(expiry_time) return RefreshableCredentials( credentials['access_key'], credentials['secret_key'], credentials['token'], expiry_time, refresh_using=fetcher, method=self.METHOD ) return Credentials( credentials['access_key'], credentials['secret_key'], credentials['token'], method=self.METHOD ) else: return None
[ "def", "load", "(", "self", ")", ":", "access_key", "=", "self", ".", "environ", ".", "get", "(", "self", ".", "_mapping", "[", "'access_key'", "]", ",", "''", ")", "if", "access_key", ":", "logger", ".", "info", "(", "'Found credentials in environment variables.'", ")", "fetcher", "=", "self", ".", "_create_credentials_fetcher", "(", ")", "credentials", "=", "fetcher", "(", "require_expiry", "=", "False", ")", "expiry_time", "=", "credentials", "[", "'expiry_time'", "]", "if", "expiry_time", "is", "not", "None", ":", "expiry_time", "=", "parse", "(", "expiry_time", ")", "return", "RefreshableCredentials", "(", "credentials", "[", "'access_key'", "]", ",", "credentials", "[", "'secret_key'", "]", ",", "credentials", "[", "'token'", "]", ",", "expiry_time", ",", "refresh_using", "=", "fetcher", ",", "method", "=", "self", ".", "METHOD", ")", "return", "Credentials", "(", "credentials", "[", "'access_key'", "]", ",", "credentials", "[", "'secret_key'", "]", ",", "credentials", "[", "'token'", "]", ",", "method", "=", "self", ".", "METHOD", ")", "else", ":", "return", "None" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/botocore/credentials.py#L1065-L1091
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Draft/draftguitools/gui_circulararray.py
python
CircularArray.click
(self, event_cb=None)
Execute as a callback when the pointer clicks on the 3D view. It should act as if the Enter key was pressed, or the OK button was pressed in the task panel.
Execute as a callback when the pointer clicks on the 3D view.
[ "Execute", "as", "a", "callback", "when", "the", "pointer", "clicks", "on", "the", "3D", "view", "." ]
def click(self, event_cb=None): """Execute as a callback when the pointer clicks on the 3D view. It should act as if the Enter key was pressed, or the OK button was pressed in the task panel. """ if event_cb: event = event_cb.getEvent() if (event.getState() != coin.SoMouseButtonEvent.DOWN or event.getButton() != coin.SoMouseButtonEvent.BUTTON1): return if self.ui and self.point: # The accept function of the interface # should call the completed function # of the calling class (this one). self.ui.accept()
[ "def", "click", "(", "self", ",", "event_cb", "=", "None", ")", ":", "if", "event_cb", ":", "event", "=", "event_cb", ".", "getEvent", "(", ")", "if", "(", "event", ".", "getState", "(", ")", "!=", "coin", ".", "SoMouseButtonEvent", ".", "DOWN", "or", "event", ".", "getButton", "(", ")", "!=", "coin", ".", "SoMouseButtonEvent", ".", "BUTTON1", ")", ":", "return", "if", "self", ".", "ui", "and", "self", ".", "point", ":", "# The accept function of the interface", "# should call the completed function", "# of the calling class (this one).", "self", ".", "ui", ".", "accept", "(", ")" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_circulararray.py#L106-L121
google/nucleus
68d3947fafba1337f294c0668a6e1c7f3f1273e3
nucleus/util/genomics_math.py
python
log10sumexp
(log10_probs)
return m + math.log10(sum(pow(10.0, x - m) for x in log10_probs))
Returns log10(sum(10^log10_probs)) computed in a numerically-stable way. Args: log10_probs: array-like of floats. An array of log10 probabilties. Returns: Float.
Returns log10(sum(10^log10_probs)) computed in a numerically-stable way.
[ "Returns", "log10", "(", "sum", "(", "10^log10_probs", "))", "computed", "in", "a", "numerically", "-", "stable", "way", "." ]
def log10sumexp(log10_probs): """Returns log10(sum(10^log10_probs)) computed in a numerically-stable way. Args: log10_probs: array-like of floats. An array of log10 probabilties. Returns: Float. """ m = max(log10_probs) return m + math.log10(sum(pow(10.0, x - m) for x in log10_probs))
[ "def", "log10sumexp", "(", "log10_probs", ")", ":", "m", "=", "max", "(", "log10_probs", ")", "return", "m", "+", "math", ".", "log10", "(", "sum", "(", "pow", "(", "10.0", ",", "x", "-", "m", ")", "for", "x", "in", "log10_probs", ")", ")" ]
https://github.com/google/nucleus/blob/68d3947fafba1337f294c0668a6e1c7f3f1273e3/nucleus/util/genomics_math.py#L168-L178
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py
python
uCSIsCatZl
(code)
return ret
Check whether the character is part of Zl UCS Category
Check whether the character is part of Zl UCS Category
[ "Check", "whether", "the", "character", "is", "part", "of", "Zl", "UCS", "Category" ]
def uCSIsCatZl(code): """Check whether the character is part of Zl UCS Category """ ret = libxml2mod.xmlUCSIsCatZl(code) return ret
[ "def", "uCSIsCatZl", "(", "code", ")", ":", "ret", "=", "libxml2mod", ".", "xmlUCSIsCatZl", "(", "code", ")", "return", "ret" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L1623-L1626
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
deps/src/libxml2-2.9.1/python/libxml2class.py
python
uCSIsGurmukhi
(code)
return ret
Check whether the character is part of Gurmukhi UCS Block
Check whether the character is part of Gurmukhi UCS Block
[ "Check", "whether", "the", "character", "is", "part", "of", "Gurmukhi", "UCS", "Block" ]
def uCSIsGurmukhi(code): """Check whether the character is part of Gurmukhi UCS Block """ ret = libxml2mod.xmlUCSIsGurmukhi(code) return ret
[ "def", "uCSIsGurmukhi", "(", "code", ")", ":", "ret", "=", "libxml2mod", ".", "xmlUCSIsGurmukhi", "(", "code", ")", "return", "ret" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2class.py#L1772-L1775
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/OpenSSL/crypto.py
python
get_elliptic_curves
()
return _EllipticCurve._get_elliptic_curves(_lib)
Return a set of objects representing the elliptic curves supported in the OpenSSL build in use. The curve objects have a :py:class:`unicode` ``name`` attribute by which they identify themselves. The curve objects are useful as values for the argument accepted by :py:meth:`Context.set_tmp_ecdh` to specify which elliptical curve should be used for ECDHE key exchange.
Return a set of objects representing the elliptic curves supported in the OpenSSL build in use.
[ "Return", "a", "set", "of", "objects", "representing", "the", "elliptic", "curves", "supported", "in", "the", "OpenSSL", "build", "in", "use", "." ]
def get_elliptic_curves(): """ Return a set of objects representing the elliptic curves supported in the OpenSSL build in use. The curve objects have a :py:class:`unicode` ``name`` attribute by which they identify themselves. The curve objects are useful as values for the argument accepted by :py:meth:`Context.set_tmp_ecdh` to specify which elliptical curve should be used for ECDHE key exchange. """ return _EllipticCurve._get_elliptic_curves(_lib)
[ "def", "get_elliptic_curves", "(", ")", ":", "return", "_EllipticCurve", ".", "_get_elliptic_curves", "(", "_lib", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/OpenSSL/crypto.py#L475-L487
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/tensor/linalg.py
python
cholesky
(x, upper=False, name=None)
return out
r""" Computes the Cholesky decomposition of one symmetric positive-definite matrix or batches of symmetric positive-definite matrice. If `upper` is `True`, the decomposition has the form :math:`A = U^{T}U` , and the returned matrix :math:`U` is upper-triangular. Otherwise, the decomposition has the form :math:`A = LL^{T}` , and the returned matrix :math:`L` is lower-triangular. Args: x (Tensor): The input tensor. Its shape should be `[*, M, M]`, where * is zero or more batch dimensions, and matrices on the inner-most 2 dimensions all should be symmetric positive-definite. Its data type should be float32 or float64. upper (bool): The flag indicating whether to return upper or lower triangular matrices. Default: False. Returns: Tensor: A Tensor with same shape and data type as `x`. It represents \ triangular matrices generated by Cholesky decomposition. Examples: .. code-block:: python import paddle import numpy as np a = np.random.rand(3, 3) a_t = np.transpose(a, [1, 0]) x_data = np.matmul(a, a_t) + 1e-03 x = paddle.to_tensor(x_data) out = paddle.linalg.cholesky(x, upper=False) print(out) # [[1.190523 0. 0. ] # [0.9906703 0.27676893 0. ] # [1.25450498 0.05600871 0.06400121]]
r""" Computes the Cholesky decomposition of one symmetric positive-definite matrix or batches of symmetric positive-definite matrice.
[ "r", "Computes", "the", "Cholesky", "decomposition", "of", "one", "symmetric", "positive", "-", "definite", "matrix", "or", "batches", "of", "symmetric", "positive", "-", "definite", "matrice", "." ]
def cholesky(x, upper=False, name=None): r""" Computes the Cholesky decomposition of one symmetric positive-definite matrix or batches of symmetric positive-definite matrice. If `upper` is `True`, the decomposition has the form :math:`A = U^{T}U` , and the returned matrix :math:`U` is upper-triangular. Otherwise, the decomposition has the form :math:`A = LL^{T}` , and the returned matrix :math:`L` is lower-triangular. Args: x (Tensor): The input tensor. Its shape should be `[*, M, M]`, where * is zero or more batch dimensions, and matrices on the inner-most 2 dimensions all should be symmetric positive-definite. Its data type should be float32 or float64. upper (bool): The flag indicating whether to return upper or lower triangular matrices. Default: False. Returns: Tensor: A Tensor with same shape and data type as `x`. It represents \ triangular matrices generated by Cholesky decomposition. Examples: .. code-block:: python import paddle import numpy as np a = np.random.rand(3, 3) a_t = np.transpose(a, [1, 0]) x_data = np.matmul(a, a_t) + 1e-03 x = paddle.to_tensor(x_data) out = paddle.linalg.cholesky(x, upper=False) print(out) # [[1.190523 0. 0. ] # [0.9906703 0.27676893 0. ] # [1.25450498 0.05600871 0.06400121]] """ if in_dygraph_mode(): return _C_ops.cholesky(x, "upper", upper) check_variable_and_dtype(x, 'dtype', ['float32', 'float64'], 'cholesky') check_type(upper, 'upper', bool, 'cholesky') helper = LayerHelper('cholesky', **locals()) out = helper.create_variable_for_type_inference(dtype=x.dtype) helper.append_op( type='cholesky', inputs={'X': [x]}, outputs={'Out': out}, attrs={'upper': upper}) return out
[ "def", "cholesky", "(", "x", ",", "upper", "=", "False", ",", "name", "=", "None", ")", ":", "if", "in_dygraph_mode", "(", ")", ":", "return", "_C_ops", ".", "cholesky", "(", "x", ",", "\"upper\"", ",", "upper", ")", "check_variable_and_dtype", "(", "x", ",", "'dtype'", ",", "[", "'float32'", ",", "'float64'", "]", ",", "'cholesky'", ")", "check_type", "(", "upper", ",", "'upper'", ",", "bool", ",", "'cholesky'", ")", "helper", "=", "LayerHelper", "(", "'cholesky'", ",", "*", "*", "locals", "(", ")", ")", "out", "=", "helper", ".", "create_variable_for_type_inference", "(", "dtype", "=", "x", ".", "dtype", ")", "helper", ".", "append_op", "(", "type", "=", "'cholesky'", ",", "inputs", "=", "{", "'X'", ":", "[", "x", "]", "}", ",", "outputs", "=", "{", "'Out'", ":", "out", "}", ",", "attrs", "=", "{", "'upper'", ":", "upper", "}", ")", "return", "out" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/tensor/linalg.py#L1167-L1217
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/_vendor/packaging/specifiers.py
python
BaseSpecifier.filter
(self, iterable, prereleases=None)
Takes an iterable of items and filters them so that only items which are contained within this specifier are allowed in it.
Takes an iterable of items and filters them so that only items which are contained within this specifier are allowed in it.
[ "Takes", "an", "iterable", "of", "items", "and", "filters", "them", "so", "that", "only", "items", "which", "are", "contained", "within", "this", "specifier", "are", "allowed", "in", "it", "." ]
def filter(self, iterable, prereleases=None): """ Takes an iterable of items and filters them so that only items which are contained within this specifier are allowed in it. """
[ "def", "filter", "(", "self", ",", "iterable", ",", "prereleases", "=", "None", ")", ":" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/_vendor/packaging/specifiers.py#L70-L74
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/pty.py
python
spawn
(argv, master_read=_read, stdin_read=_read)
Create a spawned process.
Create a spawned process.
[ "Create", "a", "spawned", "process", "." ]
def spawn(argv, master_read=_read, stdin_read=_read): """Create a spawned process.""" if type(argv) == type(''): argv = (argv,) pid, master_fd = fork() if pid == CHILD: os.execlp(argv[0], *argv) try: mode = tty.tcgetattr(STDIN_FILENO) tty.setraw(STDIN_FILENO) restore = 1 except tty.error: # This is the same as termios.error restore = 0 try: _copy(master_fd, master_read, stdin_read) except (IOError, OSError): if restore: tty.tcsetattr(STDIN_FILENO, tty.TCSAFLUSH, mode) os.close(master_fd)
[ "def", "spawn", "(", "argv", ",", "master_read", "=", "_read", ",", "stdin_read", "=", "_read", ")", ":", "if", "type", "(", "argv", ")", "==", "type", "(", "''", ")", ":", "argv", "=", "(", "argv", ",", ")", "pid", ",", "master_fd", "=", "fork", "(", ")", "if", "pid", "==", "CHILD", ":", "os", ".", "execlp", "(", "argv", "[", "0", "]", ",", "*", "argv", ")", "try", ":", "mode", "=", "tty", ".", "tcgetattr", "(", "STDIN_FILENO", ")", "tty", ".", "setraw", "(", "STDIN_FILENO", ")", "restore", "=", "1", "except", "tty", ".", "error", ":", "# This is the same as termios.error", "restore", "=", "0", "try", ":", "_copy", "(", "master_fd", ",", "master_read", ",", "stdin_read", ")", "except", "(", "IOError", ",", "OSError", ")", ":", "if", "restore", ":", "tty", ".", "tcsetattr", "(", "STDIN_FILENO", ",", "tty", ".", "TCSAFLUSH", ",", "mode", ")", "os", ".", "close", "(", "master_fd", ")" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/pty.py#L155-L174
sdhash/sdhash
b9eff63e4e5867e910f41fd69032bbb1c94a2a5e
sdhash-ui/cherrypy/lib/gctools.py
python
ReferrerTree.ascend
(self, obj, depth=1)
return parents
Return a nested list containing referrers of the given object.
Return a nested list containing referrers of the given object.
[ "Return", "a", "nested", "list", "containing", "referrers", "of", "the", "given", "object", "." ]
def ascend(self, obj, depth=1): """Return a nested list containing referrers of the given object.""" depth += 1 parents = [] # Gather all referrers in one step to minimize # cascading references due to repr() logic. refs = gc.get_referrers(obj) self.ignore.append(refs) if len(refs) > self.maxparents: return [("[%s referrers]" % len(refs), [])] try: ascendcode = self.ascend.__code__ except AttributeError: ascendcode = self.ascend.im_func.func_code for parent in refs: if inspect.isframe(parent) and parent.f_code is ascendcode: continue if parent in self.ignore: continue if depth <= self.maxdepth: parents.append((parent, self.ascend(parent, depth))) else: parents.append((parent, [])) return parents
[ "def", "ascend", "(", "self", ",", "obj", ",", "depth", "=", "1", ")", ":", "depth", "+=", "1", "parents", "=", "[", "]", "# Gather all referrers in one step to minimize", "# cascading references due to repr() logic.", "refs", "=", "gc", ".", "get_referrers", "(", "obj", ")", "self", ".", "ignore", ".", "append", "(", "refs", ")", "if", "len", "(", "refs", ")", ">", "self", ".", "maxparents", ":", "return", "[", "(", "\"[%s referrers]\"", "%", "len", "(", "refs", ")", ",", "[", "]", ")", "]", "try", ":", "ascendcode", "=", "self", ".", "ascend", ".", "__code__", "except", "AttributeError", ":", "ascendcode", "=", "self", ".", "ascend", ".", "im_func", ".", "func_code", "for", "parent", "in", "refs", ":", "if", "inspect", ".", "isframe", "(", "parent", ")", "and", "parent", ".", "f_code", "is", "ascendcode", ":", "continue", "if", "parent", "in", "self", ".", "ignore", ":", "continue", "if", "depth", "<=", "self", ".", "maxdepth", ":", "parents", ".", "append", "(", "(", "parent", ",", "self", ".", "ascend", "(", "parent", ",", "depth", ")", ")", ")", "else", ":", "parents", ".", "append", "(", "(", "parent", ",", "[", "]", ")", ")", "return", "parents" ]
https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-ui/cherrypy/lib/gctools.py#L28-L54
jackaudio/jack2
21b293dbc37d42446141a08922cdec0d2550c6a0
waflib/Tools/gxx.py
python
find_gxx
(conf)
Finds the program g++, and if present, try to detect its version number
Finds the program g++, and if present, try to detect its version number
[ "Finds", "the", "program", "g", "++", "and", "if", "present", "try", "to", "detect", "its", "version", "number" ]
def find_gxx(conf): """ Finds the program g++, and if present, try to detect its version number """ cxx = conf.find_program(['g++', 'c++'], var='CXX') conf.get_cc_version(cxx, gcc=True) conf.env.CXX_NAME = 'gcc'
[ "def", "find_gxx", "(", "conf", ")", ":", "cxx", "=", "conf", ".", "find_program", "(", "[", "'g++'", ",", "'c++'", "]", ",", "var", "=", "'CXX'", ")", "conf", ".", "get_cc_version", "(", "cxx", ",", "gcc", "=", "True", ")", "conf", ".", "env", ".", "CXX_NAME", "=", "'gcc'" ]
https://github.com/jackaudio/jack2/blob/21b293dbc37d42446141a08922cdec0d2550c6a0/waflib/Tools/gxx.py#L15-L21
wenwei202/caffe
f54a74abaf6951d8485cbdcfa1d74a4c37839466
python/caffe/detector.py
python
Detector.detect_windows
(self, images_windows)
return detections
Do windowed detection over given images and windows. Windows are extracted then warped to the input dimensions of the net. Parameters ---------- images_windows: (image filename, window list) iterable. context_crop: size of context border to crop in pixels. Returns ------- detections: list of {filename: image filename, window: crop coordinates, predictions: prediction vector} dicts.
Do windowed detection over given images and windows. Windows are extracted then warped to the input dimensions of the net.
[ "Do", "windowed", "detection", "over", "given", "images", "and", "windows", ".", "Windows", "are", "extracted", "then", "warped", "to", "the", "input", "dimensions", "of", "the", "net", "." ]
def detect_windows(self, images_windows): """ Do windowed detection over given images and windows. Windows are extracted then warped to the input dimensions of the net. Parameters ---------- images_windows: (image filename, window list) iterable. context_crop: size of context border to crop in pixels. Returns ------- detections: list of {filename: image filename, window: crop coordinates, predictions: prediction vector} dicts. """ # Extract windows. window_inputs = [] for image_fname, windows in images_windows: image = caffe.io.load_image(image_fname).astype(np.float32) for window in windows: window_inputs.append(self.crop(image, window)) # Run through the net (warping windows to input dimensions). in_ = self.inputs[0] caffe_in = np.zeros((len(window_inputs), window_inputs[0].shape[2]) + self.blobs[in_].data.shape[2:], dtype=np.float32) for ix, window_in in enumerate(window_inputs): caffe_in[ix] = self.transformer.preprocess(in_, window_in) out = self.forward_all(**{in_: caffe_in}) predictions = out[self.outputs[0]] # Package predictions with images and windows. detections = [] ix = 0 for image_fname, windows in images_windows: for window in windows: detections.append({ 'window': window, 'prediction': predictions[ix], 'filename': image_fname }) ix += 1 return detections
[ "def", "detect_windows", "(", "self", ",", "images_windows", ")", ":", "# Extract windows.", "window_inputs", "=", "[", "]", "for", "image_fname", ",", "windows", "in", "images_windows", ":", "image", "=", "caffe", ".", "io", ".", "load_image", "(", "image_fname", ")", ".", "astype", "(", "np", ".", "float32", ")", "for", "window", "in", "windows", ":", "window_inputs", ".", "append", "(", "self", ".", "crop", "(", "image", ",", "window", ")", ")", "# Run through the net (warping windows to input dimensions).", "in_", "=", "self", ".", "inputs", "[", "0", "]", "caffe_in", "=", "np", ".", "zeros", "(", "(", "len", "(", "window_inputs", ")", ",", "window_inputs", "[", "0", "]", ".", "shape", "[", "2", "]", ")", "+", "self", ".", "blobs", "[", "in_", "]", ".", "data", ".", "shape", "[", "2", ":", "]", ",", "dtype", "=", "np", ".", "float32", ")", "for", "ix", ",", "window_in", "in", "enumerate", "(", "window_inputs", ")", ":", "caffe_in", "[", "ix", "]", "=", "self", ".", "transformer", ".", "preprocess", "(", "in_", ",", "window_in", ")", "out", "=", "self", ".", "forward_all", "(", "*", "*", "{", "in_", ":", "caffe_in", "}", ")", "predictions", "=", "out", "[", "self", ".", "outputs", "[", "0", "]", "]", "# Package predictions with images and windows.", "detections", "=", "[", "]", "ix", "=", "0", "for", "image_fname", ",", "windows", "in", "images_windows", ":", "for", "window", "in", "windows", ":", "detections", ".", "append", "(", "{", "'window'", ":", "window", ",", "'prediction'", ":", "predictions", "[", "ix", "]", ",", "'filename'", ":", "image_fname", "}", ")", "ix", "+=", "1", "return", "detections" ]
https://github.com/wenwei202/caffe/blob/f54a74abaf6951d8485cbdcfa1d74a4c37839466/python/caffe/detector.py#L56-L99
borglab/gtsam
a5bee157efce6a0563704bce6a5d188c29817f39
wrap/gtwrap/pybind_wrapper.py
python
PybindWrapper.wrap_operators
(self, operators, cpp_class, prefix='\n' + ' ' * 8)
return res
Wrap all the overloaded operators in the `cpp_class`.
Wrap all the overloaded operators in the `cpp_class`.
[ "Wrap", "all", "the", "overloaded", "operators", "in", "the", "cpp_class", "." ]
def wrap_operators(self, operators, cpp_class, prefix='\n' + ' ' * 8): """Wrap all the overloaded operators in the `cpp_class`.""" res = "" template = "{prefix}.def({{0}})".format(prefix=prefix) for op in operators: if op.operator == "[]": # __getitem__ res += "{prefix}.def(\"__getitem__\", &{cpp_class}::operator[])".format( prefix=prefix, cpp_class=cpp_class) elif op.operator == "()": # __call__ res += "{prefix}.def(\"__call__\", &{cpp_class}::operator())".format( prefix=prefix, cpp_class=cpp_class) elif op.is_unary: res += template.format("{0}py::self".format(op.operator)) else: res += template.format("py::self {0} py::self".format( op.operator)) return res
[ "def", "wrap_operators", "(", "self", ",", "operators", ",", "cpp_class", ",", "prefix", "=", "'\\n'", "+", "' '", "*", "8", ")", ":", "res", "=", "\"\"", "template", "=", "\"{prefix}.def({{0}})\"", ".", "format", "(", "prefix", "=", "prefix", ")", "for", "op", "in", "operators", ":", "if", "op", ".", "operator", "==", "\"[]\"", ":", "# __getitem__", "res", "+=", "\"{prefix}.def(\\\"__getitem__\\\", &{cpp_class}::operator[])\"", ".", "format", "(", "prefix", "=", "prefix", ",", "cpp_class", "=", "cpp_class", ")", "elif", "op", ".", "operator", "==", "\"()\"", ":", "# __call__", "res", "+=", "\"{prefix}.def(\\\"__call__\\\", &{cpp_class}::operator())\"", ".", "format", "(", "prefix", "=", "prefix", ",", "cpp_class", "=", "cpp_class", ")", "elif", "op", ".", "is_unary", ":", "res", "+=", "template", ".", "format", "(", "\"{0}py::self\"", ".", "format", "(", "op", ".", "operator", ")", ")", "else", ":", "res", "+=", "template", ".", "format", "(", "\"py::self {0} py::self\"", ".", "format", "(", "op", ".", "operator", ")", ")", "return", "res" ]
https://github.com/borglab/gtsam/blob/a5bee157efce6a0563704bce6a5d188c29817f39/wrap/gtwrap/pybind_wrapper.py#L303-L319
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/extern/decorlib.py
python
anythread
(func)
return invoker
Method decorator allowing call from any thread. The method is replaced by one that posts a MethodInvocationEvent to the object, then blocks waiting for it to be completed. The target object if automatically connected to the _EVT_INVOKE_METHOD event if it wasn't alread connected.
Method decorator allowing call from any thread. The method is replaced by one that posts a MethodInvocationEvent to the object, then blocks waiting for it to be completed. The target object if automatically connected to the _EVT_INVOKE_METHOD event if it wasn't alread connected.
[ "Method", "decorator", "allowing", "call", "from", "any", "thread", ".", "The", "method", "is", "replaced", "by", "one", "that", "posts", "a", "MethodInvocationEvent", "to", "the", "object", "then", "blocks", "waiting", "for", "it", "to", "be", "completed", ".", "The", "target", "object", "if", "automatically", "connected", "to", "the", "_EVT_INVOKE_METHOD", "event", "if", "it", "wasn", "t", "alread", "connected", "." ]
def anythread(func): """Method decorator allowing call from any thread. The method is replaced by one that posts a MethodInvocationEvent to the object, then blocks waiting for it to be completed. The target object if automatically connected to the _EVT_INVOKE_METHOD event if it wasn't alread connected. """ def invoker(*args, **kwds): if wx.Thread_IsMain(): return func(*args, **kwds) else: self = args[0] if not hasattr(self, "_AnyThread__connected"): self.Connect(-1, -1, _EVT_INVOKE_METHOD,handler) self._AnyThread__connected = True evt = MethodInvocationEvent(func, args, kwds) return evt.invoke() invoker.__name__ = func.__name__ invoker.__doc__ = func.__doc__ return invoker
[ "def", "anythread", "(", "func", ")", ":", "def", "invoker", "(", "*", "args", ",", "*", "*", "kwds", ")", ":", "if", "wx", ".", "Thread_IsMain", "(", ")", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kwds", ")", "else", ":", "self", "=", "args", "[", "0", "]", "if", "not", "hasattr", "(", "self", ",", "\"_AnyThread__connected\"", ")", ":", "self", ".", "Connect", "(", "-", "1", ",", "-", "1", ",", "_EVT_INVOKE_METHOD", ",", "handler", ")", "self", ".", "_AnyThread__connected", "=", "True", "evt", "=", "MethodInvocationEvent", "(", "func", ",", "args", ",", "kwds", ")", "return", "evt", ".", "invoke", "(", ")", "invoker", ".", "__name__", "=", "func", ".", "__name__", "invoker", ".", "__doc__", "=", "func", ".", "__doc__", "return", "invoker" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/decorlib.py#L82-L103
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/lib/scimath.py
python
_fix_real_abs_gt_1
(x)
return x
Convert `x` to complex if it has real components x_i with abs(x_i)>1. Otherwise, output is just the array version of the input (via asarray). Parameters ---------- x : array_like Returns ------- array Examples -------- >>> np.lib.scimath._fix_real_abs_gt_1([0,1]) array([0, 1]) >>> np.lib.scimath._fix_real_abs_gt_1([0,2]) array([0.+0.j, 2.+0.j])
Convert `x` to complex if it has real components x_i with abs(x_i)>1.
[ "Convert", "x", "to", "complex", "if", "it", "has", "real", "components", "x_i", "with", "abs", "(", "x_i", ")", ">", "1", "." ]
def _fix_real_abs_gt_1(x): """Convert `x` to complex if it has real components x_i with abs(x_i)>1. Otherwise, output is just the array version of the input (via asarray). Parameters ---------- x : array_like Returns ------- array Examples -------- >>> np.lib.scimath._fix_real_abs_gt_1([0,1]) array([0, 1]) >>> np.lib.scimath._fix_real_abs_gt_1([0,2]) array([0.+0.j, 2.+0.j]) """ x = asarray(x) if any(isreal(x) & (abs(x) > 1)): x = _tocomplex(x) return x
[ "def", "_fix_real_abs_gt_1", "(", "x", ")", ":", "x", "=", "asarray", "(", "x", ")", "if", "any", "(", "isreal", "(", "x", ")", "&", "(", "abs", "(", "x", ")", ">", "1", ")", ")", ":", "x", "=", "_tocomplex", "(", "x", ")", "return", "x" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/lib/scimath.py#L154-L178
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/_vendor/pyparsing.py
python
_makeTags
(tagStr, xml)
return openTag, closeTag
Internal helper to construct opening and closing tag expressions, given a tag name
Internal helper to construct opening and closing tag expressions, given a tag name
[ "Internal", "helper", "to", "construct", "opening", "and", "closing", "tag", "expressions", "given", "a", "tag", "name" ]
def _makeTags(tagStr, xml): """Internal helper to construct opening and closing tag expressions, given a tag name""" if isinstance(tagStr,basestring): resname = tagStr tagStr = Keyword(tagStr, caseless=not xml) else: resname = tagStr.name tagAttrName = Word(alphas,alphanums+"_-:") if (xml): tagAttrValue = dblQuotedString.copy().setParseAction( removeQuotes ) openTag = Suppress("<") + tagStr("tag") + \ Dict(ZeroOrMore(Group( tagAttrName + Suppress("=") + tagAttrValue ))) + \ Optional("/",default=[False]).setResultsName("empty").setParseAction(lambda s,l,t:t[0]=='/') + Suppress(">") else: printablesLessRAbrack = "".join(c for c in printables if c not in ">") tagAttrValue = quotedString.copy().setParseAction( removeQuotes ) | Word(printablesLessRAbrack) openTag = Suppress("<") + tagStr("tag") + \ Dict(ZeroOrMore(Group( tagAttrName.setParseAction(downcaseTokens) + \ Optional( Suppress("=") + tagAttrValue ) ))) + \ Optional("/",default=[False]).setResultsName("empty").setParseAction(lambda s,l,t:t[0]=='/') + Suppress(">") closeTag = Combine(_L("</") + tagStr + ">") openTag = openTag.setResultsName("start"+"".join(resname.replace(":"," ").title().split())).setName("<%s>" % resname) closeTag = closeTag.setResultsName("end"+"".join(resname.replace(":"," ").title().split())).setName("</%s>" % resname) openTag.tag = resname closeTag.tag = resname return openTag, closeTag
[ "def", "_makeTags", "(", "tagStr", ",", "xml", ")", ":", "if", "isinstance", "(", "tagStr", ",", "basestring", ")", ":", "resname", "=", "tagStr", "tagStr", "=", "Keyword", "(", "tagStr", ",", "caseless", "=", "not", "xml", ")", "else", ":", "resname", "=", "tagStr", ".", "name", "tagAttrName", "=", "Word", "(", "alphas", ",", "alphanums", "+", "\"_-:\"", ")", "if", "(", "xml", ")", ":", "tagAttrValue", "=", "dblQuotedString", ".", "copy", "(", ")", ".", "setParseAction", "(", "removeQuotes", ")", "openTag", "=", "Suppress", "(", "\"<\"", ")", "+", "tagStr", "(", "\"tag\"", ")", "+", "Dict", "(", "ZeroOrMore", "(", "Group", "(", "tagAttrName", "+", "Suppress", "(", "\"=\"", ")", "+", "tagAttrValue", ")", ")", ")", "+", "Optional", "(", "\"/\"", ",", "default", "=", "[", "False", "]", ")", ".", "setResultsName", "(", "\"empty\"", ")", ".", "setParseAction", "(", "lambda", "s", ",", "l", ",", "t", ":", "t", "[", "0", "]", "==", "'/'", ")", "+", "Suppress", "(", "\">\"", ")", "else", ":", "printablesLessRAbrack", "=", "\"\"", ".", "join", "(", "c", "for", "c", "in", "printables", "if", "c", "not", "in", "\">\"", ")", "tagAttrValue", "=", "quotedString", ".", "copy", "(", ")", ".", "setParseAction", "(", "removeQuotes", ")", "|", "Word", "(", "printablesLessRAbrack", ")", "openTag", "=", "Suppress", "(", "\"<\"", ")", "+", "tagStr", "(", "\"tag\"", ")", "+", "Dict", "(", "ZeroOrMore", "(", "Group", "(", "tagAttrName", ".", "setParseAction", "(", "downcaseTokens", ")", "+", "Optional", "(", "Suppress", "(", "\"=\"", ")", "+", "tagAttrValue", ")", ")", ")", ")", "+", "Optional", "(", "\"/\"", ",", "default", "=", "[", "False", "]", ")", ".", "setResultsName", "(", "\"empty\"", ")", ".", "setParseAction", "(", "lambda", "s", ",", "l", ",", "t", ":", "t", "[", "0", "]", "==", "'/'", ")", "+", "Suppress", "(", "\">\"", ")", "closeTag", "=", "Combine", "(", "_L", "(", "\"</\"", ")", "+", "tagStr", "+", "\">\"", ")", "openTag", "=", "openTag", ".", "setResultsName", "(", "\"start\"", "+", "\"\"", ".", "join", "(", "resname", ".", "replace", "(", "\":\"", ",", "\" \"", ")", ".", "title", "(", ")", ".", "split", "(", ")", ")", ")", ".", "setName", "(", "\"<%s>\"", "%", "resname", ")", "closeTag", "=", "closeTag", ".", "setResultsName", "(", "\"end\"", "+", "\"\"", ".", "join", "(", "resname", ".", "replace", "(", "\":\"", ",", "\" \"", ")", ".", "title", "(", ")", ".", "split", "(", ")", ")", ")", ".", "setName", "(", "\"</%s>\"", "%", "resname", ")", "openTag", ".", "tag", "=", "resname", "closeTag", ".", "tag", "=", "resname", "return", "openTag", ",", "closeTag" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/_vendor/pyparsing.py#L4875-L4902
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_windows.py
python
FontData.SetRange
(*args, **kwargs)
return _windows_.FontData_SetRange(*args, **kwargs)
SetRange(self, int min, int max) Sets the valid range for the font point size (Windows only). The default is 0, 0 (unrestricted range).
SetRange(self, int min, int max)
[ "SetRange", "(", "self", "int", "min", "int", "max", ")" ]
def SetRange(*args, **kwargs): """ SetRange(self, int min, int max) Sets the valid range for the font point size (Windows only). The default is 0, 0 (unrestricted range). """ return _windows_.FontData_SetRange(*args, **kwargs)
[ "def", "SetRange", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "FontData_SetRange", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L3554-L3561
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/posix_utils.py
python
PosixStdinReader.read
(self, count=1024)
return self._stdin_decoder.decode(data)
Read the input and return it as a string. Return the text. Note that this can return an empty string, even when the input stream was not yet closed. This means that something went wrong during the decoding.
Read the input and return it as a string.
[ "Read", "the", "input", "and", "return", "it", "as", "a", "string", "." ]
def read(self, count=1024): # By default we choose a rather small chunk size, because reading # big amounts of input at once, causes the event loop to process # all these key bindings also at once without going back to the # loop. This will make the application feel unresponsive. """ Read the input and return it as a string. Return the text. Note that this can return an empty string, even when the input stream was not yet closed. This means that something went wrong during the decoding. """ if self.closed: return b'' # Note: the following works better than wrapping `self.stdin` like # `codecs.getreader('utf-8')(stdin)` and doing `read(1)`. # Somehow that causes some latency when the escape # character is pressed. (Especially on combination with the `select`.) try: data = os.read(self.stdin_fd, count) # Nothing more to read, stream is closed. if data == b'': self.closed = True return '' except OSError: # In case of SIGWINCH data = b'' return self._stdin_decoder.decode(data)
[ "def", "read", "(", "self", ",", "count", "=", "1024", ")", ":", "# By default we choose a rather small chunk size, because reading", "# big amounts of input at once, causes the event loop to process", "# all these key bindings also at once without going back to the", "# loop. This will make the application feel unresponsive.", "if", "self", ".", "closed", ":", "return", "b''", "# Note: the following works better than wrapping `self.stdin` like", "# `codecs.getreader('utf-8')(stdin)` and doing `read(1)`.", "# Somehow that causes some latency when the escape", "# character is pressed. (Especially on combination with the `select`.)", "try", ":", "data", "=", "os", ".", "read", "(", "self", ".", "stdin_fd", ",", "count", ")", "# Nothing more to read, stream is closed.", "if", "data", "==", "b''", ":", "self", ".", "closed", "=", "True", "return", "''", "except", "OSError", ":", "# In case of SIGWINCH", "data", "=", "b''", "return", "self", ".", "_stdin_decoder", ".", "decode", "(", "data", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py2/prompt_toolkit/eventloop/posix_utils.py#L52-L82
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/oauthlib/oauth2/rfc6749/request_validator.py
python
RequestValidator.save_token
(self, token, request, *args, **kwargs)
return self.save_bearer_token(token, request, *args, **kwargs)
Persist the token with a token type specific method. Currently, only save_bearer_token is supported.
Persist the token with a token type specific method.
[ "Persist", "the", "token", "with", "a", "token", "type", "specific", "method", "." ]
def save_token(self, token, request, *args, **kwargs): """Persist the token with a token type specific method. Currently, only save_bearer_token is supported. """ return self.save_bearer_token(token, request, *args, **kwargs)
[ "def", "save_token", "(", "self", ",", "token", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "save_bearer_token", "(", "token", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/oauthlib/oauth2/rfc6749/request_validator.py#L241-L246
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_controls.py
python
ListItem.GetFont
(*args, **kwargs)
return _controls_.ListItem_GetFont(*args, **kwargs)
GetFont(self) -> Font
GetFont(self) -> Font
[ "GetFont", "(", "self", ")", "-", ">", "Font" ]
def GetFont(*args, **kwargs): """GetFont(self) -> Font""" return _controls_.ListItem_GetFont(*args, **kwargs)
[ "def", "GetFont", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "ListItem_GetFont", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L4264-L4266
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/stc.py
python
StyledTextCtrl.ChooseCaretX
(*args, **kwargs)
return _stc.StyledTextCtrl_ChooseCaretX(*args, **kwargs)
ChooseCaretX(self) Set the last x chosen value to be the caret x position.
ChooseCaretX(self)
[ "ChooseCaretX", "(", "self", ")" ]
def ChooseCaretX(*args, **kwargs): """ ChooseCaretX(self) Set the last x chosen value to be the caret x position. """ return _stc.StyledTextCtrl_ChooseCaretX(*args, **kwargs)
[ "def", "ChooseCaretX", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_ChooseCaretX", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/stc.py#L5174-L5180
googlevr/seurat
7b20ac69265ca7390a6c7f52a4f25b0fe87d0b53
seurat/generation/maya/seurat_rig.py
python
CubeFaceProjectionMatrix
(near, far)
return [a, 0.0, c, 0.0, 0.0, b, d, 0.0, 0.0, 0.0, e, f, 0.0, 0.0, -1.0, 0.0]
Creates a cube-face 90 degree FOV projection matrix. The created matrix is an OpenGL-style projection matrix. Args: near: Eye-space Z position of the near clipping plane. far: Eye-space Z position of the far clipping plane. Returns: The clip-from-eye matrix as a list in row-major order. Raises: ValueError: Invalid clip planes. near <= 0.0 or far <= near.
Creates a cube-face 90 degree FOV projection matrix.
[ "Creates", "a", "cube", "-", "face", "90", "degree", "FOV", "projection", "matrix", "." ]
def CubeFaceProjectionMatrix(near, far): """Creates a cube-face 90 degree FOV projection matrix. The created matrix is an OpenGL-style projection matrix. Args: near: Eye-space Z position of the near clipping plane. far: Eye-space Z position of the far clipping plane. Returns: The clip-from-eye matrix as a list in row-major order. Raises: ValueError: Invalid clip planes. near <= 0.0 or far <= near. """ if near <= 0.0: raise ValueError('near must be positive.') if far <= near: raise ValueError('far must be greater than near.') left = -near right = near bottom = -near top = near a = (2.0 * near) / (right - left) b = (2.0 * near) / (top - bottom) c = (right + left) / (right - left) d = (top + bottom) / (top - bottom) e = (near + far) / (near - far) f = (2.0 * near * far) / (near - far) # pylint: disable=bad-whitespace return [a, 0.0, c, 0.0, 0.0, b, d, 0.0, 0.0, 0.0, e, f, 0.0, 0.0, -1.0, 0.0]
[ "def", "CubeFaceProjectionMatrix", "(", "near", ",", "far", ")", ":", "if", "near", "<=", "0.0", ":", "raise", "ValueError", "(", "'near must be positive.'", ")", "if", "far", "<=", "near", ":", "raise", "ValueError", "(", "'far must be greater than near.'", ")", "left", "=", "-", "near", "right", "=", "near", "bottom", "=", "-", "near", "top", "=", "near", "a", "=", "(", "2.0", "*", "near", ")", "/", "(", "right", "-", "left", ")", "b", "=", "(", "2.0", "*", "near", ")", "/", "(", "top", "-", "bottom", ")", "c", "=", "(", "right", "+", "left", ")", "/", "(", "right", "-", "left", ")", "d", "=", "(", "top", "+", "bottom", ")", "/", "(", "top", "-", "bottom", ")", "e", "=", "(", "near", "+", "far", ")", "/", "(", "near", "-", "far", ")", "f", "=", "(", "2.0", "*", "near", "*", "far", ")", "/", "(", "near", "-", "far", ")", "# pylint: disable=bad-whitespace", "return", "[", "a", ",", "0.0", ",", "c", ",", "0.0", ",", "0.0", ",", "b", ",", "d", ",", "0.0", ",", "0.0", ",", "0.0", ",", "e", ",", "f", ",", "0.0", ",", "0.0", ",", "-", "1.0", ",", "0.0", "]" ]
https://github.com/googlevr/seurat/blob/7b20ac69265ca7390a6c7f52a4f25b0fe87d0b53/seurat/generation/maya/seurat_rig.py#L104-L140
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/foldpanelbar.py
python
CaptionBar.DrawSingleColour
(self, dc, rect)
Single colour fill for :class:`CaptionBar`. :param `dc`: an instance of :class:`DC`; :param `rect`: the :class:`CaptionBar` client rectangle.
Single colour fill for :class:`CaptionBar`.
[ "Single", "colour", "fill", "for", ":", "class", ":", "CaptionBar", "." ]
def DrawSingleColour(self, dc, rect): """ Single colour fill for :class:`CaptionBar`. :param `dc`: an instance of :class:`DC`; :param `rect`: the :class:`CaptionBar` client rectangle. """ if rect.height < 1 or rect.width < 1: return dc.SetPen(wx.TRANSPARENT_PEN) # draw simple rectangle dc.SetBrush(wx.Brush(self._style.GetFirstColour(), wx.SOLID)) dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height)
[ "def", "DrawSingleColour", "(", "self", ",", "dc", ",", "rect", ")", ":", "if", "rect", ".", "height", "<", "1", "or", "rect", ".", "width", "<", "1", ":", "return", "dc", ".", "SetPen", "(", "wx", ".", "TRANSPARENT_PEN", ")", "# draw simple rectangle", "dc", ".", "SetBrush", "(", "wx", ".", "Brush", "(", "self", ".", "_style", ".", "GetFirstColour", "(", ")", ",", "wx", ".", "SOLID", ")", ")", "dc", ".", "DrawRectangle", "(", "rect", ".", "x", ",", "rect", ".", "y", ",", "rect", ".", "width", ",", "rect", ".", "height", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/foldpanelbar.py#L1063-L1078
gnuradio/gnuradio
09c3c4fa4bfb1a02caac74cb5334dfe065391e3b
gr-blocks/python/blocks/qa_block_behavior.py
python
test_block_behavior.test_001
(self)
Tests the max noutput size when being explicitly set.
Tests the max noutput size when being explicitly set.
[ "Tests", "the", "max", "noutput", "size", "when", "being", "explicitly", "set", "." ]
def test_001(self): ''' Tests the max noutput size when being explicitly set. ''' src = blocks.null_source(gr.sizeof_float) op = blocks.head(gr.sizeof_float, 100) snk = blocks.null_sink(gr.sizeof_float) op.set_max_noutput_items(1024) maxn_pre = op.max_noutput_items() self.tb.connect(src, op, snk) self.tb.run() maxn_post = op.max_noutput_items() self.assertEqual(maxn_pre, 1024) self.assertEqual(maxn_post, 1024)
[ "def", "test_001", "(", "self", ")", ":", "src", "=", "blocks", ".", "null_source", "(", "gr", ".", "sizeof_float", ")", "op", "=", "blocks", ".", "head", "(", "gr", ".", "sizeof_float", ",", "100", ")", "snk", "=", "blocks", ".", "null_sink", "(", "gr", ".", "sizeof_float", ")", "op", ".", "set_max_noutput_items", "(", "1024", ")", "maxn_pre", "=", "op", ".", "max_noutput_items", "(", ")", "self", ".", "tb", ".", "connect", "(", "src", ",", "op", ",", "snk", ")", "self", ".", "tb", ".", "run", "(", ")", "maxn_post", "=", "op", ".", "max_noutput_items", "(", ")", "self", ".", "assertEqual", "(", "maxn_pre", ",", "1024", ")", "self", ".", "assertEqual", "(", "maxn_post", ",", "1024", ")" ]
https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/gr-blocks/python/blocks/qa_block_behavior.py#L47-L66
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/util.py
python
is_local
(path)
return normalize_path(path).startswith(normalize_path(sys.prefix))
Return True if path is within sys.prefix, if we're running in a virtualenv. If we're not in a virtualenv, all paths are considered "local."
Return True if path is within sys.prefix, if we're running in a virtualenv.
[ "Return", "True", "if", "path", "is", "within", "sys", ".", "prefix", "if", "we", "re", "running", "in", "a", "virtualenv", "." ]
def is_local(path): """ Return True if path is within sys.prefix, if we're running in a virtualenv. If we're not in a virtualenv, all paths are considered "local." """ if not running_under_virtualenv(): return True return normalize_path(path).startswith(normalize_path(sys.prefix))
[ "def", "is_local", "(", "path", ")", ":", "if", "not", "running_under_virtualenv", "(", ")", ":", "return", "True", "return", "normalize_path", "(", "path", ")", ".", "startswith", "(", "normalize_path", "(", "sys", ".", "prefix", ")", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/util.py#L304-L313
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/ros/rosunit/src/rosunit/xmlrunner.py
python
_XMLTestResult.print_report
(self, stream, time_taken, out, err)
Prints the XML report to the supplied stream. The time the tests took to perform as well as the captured standard output and standard error streams must be passed in.a
Prints the XML report to the supplied stream. The time the tests took to perform as well as the captured standard output and standard error streams must be passed in.a
[ "Prints", "the", "XML", "report", "to", "the", "supplied", "stream", ".", "The", "time", "the", "tests", "took", "to", "perform", "as", "well", "as", "the", "captured", "standard", "output", "and", "standard", "error", "streams", "must", "be", "passed", "in", ".", "a" ]
def print_report(self, stream, time_taken, out, err): """Prints the XML report to the supplied stream. The time the tests took to perform as well as the captured standard output and standard error streams must be passed in.a """ stream.write('<testsuite errors="%(e)d" failures="%(f)d" ' % \ { "e": len(self.errors), "f": len(self.failures) }) stream.write('name="%(n)s" tests="%(t)d" time="%(time).3f">\n' % \ { "n": self._test_name, "t": self.testsRun, "time": time_taken, }) for info in self._tests: info.print_report(stream) stream.write(' <system-out><![CDATA[%s]]></system-out>\n' % out) stream.write(' <system-err><![CDATA[%s]]></system-err>\n' % err) stream.write('</testsuite>\n')
[ "def", "print_report", "(", "self", ",", "stream", ",", "time_taken", ",", "out", ",", "err", ")", ":", "stream", ".", "write", "(", "'<testsuite errors=\"%(e)d\" failures=\"%(f)d\" '", "%", "{", "\"e\"", ":", "len", "(", "self", ".", "errors", ")", ",", "\"f\"", ":", "len", "(", "self", ".", "failures", ")", "}", ")", "stream", ".", "write", "(", "'name=\"%(n)s\" tests=\"%(t)d\" time=\"%(time).3f\">\\n'", "%", "{", "\"n\"", ":", "self", ".", "_test_name", ",", "\"t\"", ":", "self", ".", "testsRun", ",", "\"time\"", ":", "time_taken", ",", "}", ")", "for", "info", "in", "self", ".", "_tests", ":", "info", ".", "print_report", "(", "stream", ")", "stream", ".", "write", "(", "' <system-out><![CDATA[%s]]></system-out>\\n'", "%", "out", ")", "stream", ".", "write", "(", "' <system-err><![CDATA[%s]]></system-err>\\n'", "%", "err", ")", "stream", ".", "write", "(", "'</testsuite>\\n'", ")" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros/rosunit/src/rosunit/xmlrunner.py#L155-L174
GeometryCollective/boundary-first-flattening
8250e5a0e85980ec50b5e8aa8f49dd6519f915cd
deps/nanogui/ext/eigen/debug/gdb/printers.py
python
EigenMatrixPrinter.__init__
(self, variety, val)
Extract all the necessary information
Extract all the necessary information
[ "Extract", "all", "the", "necessary", "information" ]
def __init__(self, variety, val): "Extract all the necessary information" # Save the variety (presumably "Matrix" or "Array") for later usage self.variety = variety # The gdb extension does not support value template arguments - need to extract them by hand type = val.type if type.code == gdb.TYPE_CODE_REF: type = type.target() self.type = type.unqualified().strip_typedefs() tag = self.type.tag regex = re.compile('\<.*\>') m = regex.findall(tag)[0][1:-1] template_params = m.split(',') template_params = map(lambda x:x.replace(" ", ""), template_params) if template_params[1] == '-0x00000000000000001' or template_params[1] == '-0x000000001' or template_params[1] == '-1': self.rows = val['m_storage']['m_rows'] else: self.rows = int(template_params[1]) if template_params[2] == '-0x00000000000000001' or template_params[2] == '-0x000000001' or template_params[2] == '-1': self.cols = val['m_storage']['m_cols'] else: self.cols = int(template_params[2]) self.options = 0 # default value if len(template_params) > 3: self.options = template_params[3]; self.rowMajor = (int(self.options) & 0x1) self.innerType = self.type.template_argument(0) self.val = val # Fixed size matrices have a struct as their storage, so we need to walk through this self.data = self.val['m_storage']['m_data'] if self.data.type.code == gdb.TYPE_CODE_STRUCT: self.data = self.data['array'] self.data = self.data.cast(self.innerType.pointer())
[ "def", "__init__", "(", "self", ",", "variety", ",", "val", ")", ":", "# Save the variety (presumably \"Matrix\" or \"Array\") for later usage", "self", ".", "variety", "=", "variety", "# The gdb extension does not support value template arguments - need to extract them by hand", "type", "=", "val", ".", "type", "if", "type", ".", "code", "==", "gdb", ".", "TYPE_CODE_REF", ":", "type", "=", "type", ".", "target", "(", ")", "self", ".", "type", "=", "type", ".", "unqualified", "(", ")", ".", "strip_typedefs", "(", ")", "tag", "=", "self", ".", "type", ".", "tag", "regex", "=", "re", ".", "compile", "(", "'\\<.*\\>'", ")", "m", "=", "regex", ".", "findall", "(", "tag", ")", "[", "0", "]", "[", "1", ":", "-", "1", "]", "template_params", "=", "m", ".", "split", "(", "','", ")", "template_params", "=", "map", "(", "lambda", "x", ":", "x", ".", "replace", "(", "\" \"", ",", "\"\"", ")", ",", "template_params", ")", "if", "template_params", "[", "1", "]", "==", "'-0x00000000000000001'", "or", "template_params", "[", "1", "]", "==", "'-0x000000001'", "or", "template_params", "[", "1", "]", "==", "'-1'", ":", "self", ".", "rows", "=", "val", "[", "'m_storage'", "]", "[", "'m_rows'", "]", "else", ":", "self", ".", "rows", "=", "int", "(", "template_params", "[", "1", "]", ")", "if", "template_params", "[", "2", "]", "==", "'-0x00000000000000001'", "or", "template_params", "[", "2", "]", "==", "'-0x000000001'", "or", "template_params", "[", "2", "]", "==", "'-1'", ":", "self", ".", "cols", "=", "val", "[", "'m_storage'", "]", "[", "'m_cols'", "]", "else", ":", "self", ".", "cols", "=", "int", "(", "template_params", "[", "2", "]", ")", "self", ".", "options", "=", "0", "# default value", "if", "len", "(", "template_params", ")", ">", "3", ":", "self", ".", "options", "=", "template_params", "[", "3", "]", "self", ".", "rowMajor", "=", "(", "int", "(", "self", ".", "options", ")", "&", "0x1", ")", "self", ".", "innerType", "=", "self", ".", "type", ".", "template_argument", "(", "0", ")", "self", ".", "val", "=", "val", "# Fixed size matrices have a struct as their storage, so we need to walk through this", "self", ".", "data", "=", "self", ".", "val", "[", "'m_storage'", "]", "[", "'m_data'", "]", "if", "self", ".", "data", ".", "type", ".", "code", "==", "gdb", ".", "TYPE_CODE_STRUCT", ":", "self", ".", "data", "=", "self", ".", "data", "[", "'array'", "]", "self", ".", "data", "=", "self", ".", "data", ".", "cast", "(", "self", ".", "innerType", ".", "pointer", "(", ")", ")" ]
https://github.com/GeometryCollective/boundary-first-flattening/blob/8250e5a0e85980ec50b5e8aa8f49dd6519f915cd/deps/nanogui/ext/eigen/debug/gdb/printers.py#L37-L78
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/propgrid.py
python
PGChoices.AddAsSorted
(*args, **kwargs)
return _propgrid.PGChoices_AddAsSorted(*args, **kwargs)
AddAsSorted(self, String label, int value=INT_MAX)
AddAsSorted(self, String label, int value=INT_MAX)
[ "AddAsSorted", "(", "self", "String", "label", "int", "value", "=", "INT_MAX", ")" ]
def AddAsSorted(*args, **kwargs): """AddAsSorted(self, String label, int value=INT_MAX)""" return _propgrid.PGChoices_AddAsSorted(*args, **kwargs)
[ "def", "AddAsSorted", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PGChoices_AddAsSorted", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/propgrid.py#L243-L245
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/ssl.py
python
create_default_context
(purpose=Purpose.SERVER_AUTH, *, cafile=None, capath=None, cadata=None)
return context
Create a SSLContext object with default settings. NOTE: The protocol and settings may change anytime without prior deprecation. The values represent a fair balance between maximum compatibility and security.
Create a SSLContext object with default settings.
[ "Create", "a", "SSLContext", "object", "with", "default", "settings", "." ]
def create_default_context(purpose=Purpose.SERVER_AUTH, *, cafile=None, capath=None, cadata=None): """Create a SSLContext object with default settings. NOTE: The protocol and settings may change anytime without prior deprecation. The values represent a fair balance between maximum compatibility and security. """ if not isinstance(purpose, _ASN1Object): raise TypeError(purpose) # SSLContext sets OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION, # OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE and OP_SINGLE_ECDH_USE # by default. context = SSLContext(PROTOCOL_TLS) if purpose == Purpose.SERVER_AUTH: # verify certs and host name in client mode context.verify_mode = CERT_REQUIRED context.check_hostname = True if cafile or capath or cadata: context.load_verify_locations(cafile, capath, cadata) elif context.verify_mode != CERT_NONE: # no explicit cafile, capath or cadata but the verify mode is # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system # root CA certificates for the given purpose. This may fail silently. context.load_default_certs(purpose) return context
[ "def", "create_default_context", "(", "purpose", "=", "Purpose", ".", "SERVER_AUTH", ",", "*", ",", "cafile", "=", "None", ",", "capath", "=", "None", ",", "cadata", "=", "None", ")", ":", "if", "not", "isinstance", "(", "purpose", ",", "_ASN1Object", ")", ":", "raise", "TypeError", "(", "purpose", ")", "# SSLContext sets OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION,", "# OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE and OP_SINGLE_ECDH_USE", "# by default.", "context", "=", "SSLContext", "(", "PROTOCOL_TLS", ")", "if", "purpose", "==", "Purpose", ".", "SERVER_AUTH", ":", "# verify certs and host name in client mode", "context", ".", "verify_mode", "=", "CERT_REQUIRED", "context", ".", "check_hostname", "=", "True", "if", "cafile", "or", "capath", "or", "cadata", ":", "context", ".", "load_verify_locations", "(", "cafile", ",", "capath", ",", "cadata", ")", "elif", "context", ".", "verify_mode", "!=", "CERT_NONE", ":", "# no explicit cafile, capath or cadata but the verify mode is", "# CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system", "# root CA certificates for the given purpose. This may fail silently.", "context", ".", "load_default_certs", "(", "purpose", ")", "return", "context" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/ssl.py#L562-L590
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
Configuration/Applications/python/ConfigBuilder.py
python
ConfigBuilder.profileOptions
(self)
return (profilerStart,profilerInterval,profilerFormat,profilerJobFormat)
addIgProfService Function to add the igprof profile service so that you can dump in the middle of the run.
addIgProfService Function to add the igprof profile service so that you can dump in the middle of the run.
[ "addIgProfService", "Function", "to", "add", "the", "igprof", "profile", "service", "so", "that", "you", "can", "dump", "in", "the", "middle", "of", "the", "run", "." ]
def profileOptions(self): """ addIgProfService Function to add the igprof profile service so that you can dump in the middle of the run. """ profileOpts = self._options.profile.split(':') profilerStart = 1 profilerInterval = 100 profilerFormat = None profilerJobFormat = None if len(profileOpts): #type, given as first argument is unused here profileOpts.pop(0) if len(profileOpts): startEvent = profileOpts.pop(0) if not startEvent.isdigit(): raise Exception("%s is not a number" % startEvent) profilerStart = int(startEvent) if len(profileOpts): eventInterval = profileOpts.pop(0) if not eventInterval.isdigit(): raise Exception("%s is not a number" % eventInterval) profilerInterval = int(eventInterval) if len(profileOpts): profilerFormat = profileOpts.pop(0) if not profilerFormat: profilerFormat = "%s___%s___%%I.gz" % ( self._options.evt_type.replace("_cfi", ""), hashlib.md5( (str(self._options.step) + str(self._options.pileup) + str(self._options.conditions) + str(self._options.datatier) + str(self._options.profileTypeLabel)).encode('utf-8') ).hexdigest() ) if not profilerJobFormat and profilerFormat.endswith(".gz"): profilerJobFormat = profilerFormat.replace(".gz", "_EndOfJob.gz") elif not profilerJobFormat: profilerJobFormat = profilerFormat + "_EndOfJob.gz" return (profilerStart,profilerInterval,profilerFormat,profilerJobFormat)
[ "def", "profileOptions", "(", "self", ")", ":", "profileOpts", "=", "self", ".", "_options", ".", "profile", ".", "split", "(", "':'", ")", "profilerStart", "=", "1", "profilerInterval", "=", "100", "profilerFormat", "=", "None", "profilerJobFormat", "=", "None", "if", "len", "(", "profileOpts", ")", ":", "#type, given as first argument is unused here", "profileOpts", ".", "pop", "(", "0", ")", "if", "len", "(", "profileOpts", ")", ":", "startEvent", "=", "profileOpts", ".", "pop", "(", "0", ")", "if", "not", "startEvent", ".", "isdigit", "(", ")", ":", "raise", "Exception", "(", "\"%s is not a number\"", "%", "startEvent", ")", "profilerStart", "=", "int", "(", "startEvent", ")", "if", "len", "(", "profileOpts", ")", ":", "eventInterval", "=", "profileOpts", ".", "pop", "(", "0", ")", "if", "not", "eventInterval", ".", "isdigit", "(", ")", ":", "raise", "Exception", "(", "\"%s is not a number\"", "%", "eventInterval", ")", "profilerInterval", "=", "int", "(", "eventInterval", ")", "if", "len", "(", "profileOpts", ")", ":", "profilerFormat", "=", "profileOpts", ".", "pop", "(", "0", ")", "if", "not", "profilerFormat", ":", "profilerFormat", "=", "\"%s___%s___%%I.gz\"", "%", "(", "self", ".", "_options", ".", "evt_type", ".", "replace", "(", "\"_cfi\"", ",", "\"\"", ")", ",", "hashlib", ".", "md5", "(", "(", "str", "(", "self", ".", "_options", ".", "step", ")", "+", "str", "(", "self", ".", "_options", ".", "pileup", ")", "+", "str", "(", "self", ".", "_options", ".", "conditions", ")", "+", "str", "(", "self", ".", "_options", ".", "datatier", ")", "+", "str", "(", "self", ".", "_options", ".", "profileTypeLabel", ")", ")", ".", "encode", "(", "'utf-8'", ")", ")", ".", "hexdigest", "(", ")", ")", "if", "not", "profilerJobFormat", "and", "profilerFormat", ".", "endswith", "(", "\".gz\"", ")", ":", "profilerJobFormat", "=", "profilerFormat", ".", "replace", "(", "\".gz\"", ",", "\"_EndOfJob.gz\"", ")", "elif", "not", "profilerJobFormat", ":", "profilerJobFormat", "=", "profilerFormat", "+", "\"_EndOfJob.gz\"", "return", "(", "profilerStart", ",", "profilerInterval", ",", "profilerFormat", ",", "profilerJobFormat", ")" ]
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Configuration/Applications/python/ConfigBuilder.py#L275-L317
LLNL/Caliper
60e06980fc65057e1da01296e6eebbbed30f59c8
src/mpi/services/mpiwrap/wrap.py
python
Param.countParam
(self)
return self.decl.args[mpi_array_calls[self.decl.name][self.pos]]
If this Param is a handle array, returns the Param that represents the count of its elements
If this Param is a handle array, returns the Param that represents the count of its elements
[ "If", "this", "Param", "is", "a", "handle", "array", "returns", "the", "Param", "that", "represents", "the", "count", "of", "its", "elements" ]
def countParam(self): """If this Param is a handle array, returns the Param that represents the count of its elements""" return self.decl.args[mpi_array_calls[self.decl.name][self.pos]]
[ "def", "countParam", "(", "self", ")", ":", "return", "self", ".", "decl", ".", "args", "[", "mpi_array_calls", "[", "self", ".", "decl", ".", "name", "]", "[", "self", ".", "pos", "]", "]" ]
https://github.com/LLNL/Caliper/blob/60e06980fc65057e1da01296e6eebbbed30f59c8/src/mpi/services/mpiwrap/wrap.py#L394-L396
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/zipfile.py
python
ZipFile._extract_member
(self, member, targetpath, pwd)
return targetpath
Extract the ZipInfo object 'member' to a physical file on the path targetpath.
Extract the ZipInfo object 'member' to a physical file on the path targetpath.
[ "Extract", "the", "ZipInfo", "object", "member", "to", "a", "physical", "file", "on", "the", "path", "targetpath", "." ]
def _extract_member(self, member, targetpath, pwd): """Extract the ZipInfo object 'member' to a physical file on the path targetpath. """ if not isinstance(member, ZipInfo): member = self.getinfo(member) # build the destination pathname, replacing # forward slashes to platform specific separators. arcname = member.filename.replace('/', os.path.sep) if os.path.altsep: arcname = arcname.replace(os.path.altsep, os.path.sep) # interpret absolute pathname as relative, remove drive letter or # UNC path, redundant separators, "." and ".." components. arcname = os.path.splitdrive(arcname)[1] invalid_path_parts = ('', os.path.curdir, os.path.pardir) arcname = os.path.sep.join(x for x in arcname.split(os.path.sep) if x not in invalid_path_parts) if os.path.sep == '\\': # filter illegal characters on Windows arcname = self._sanitize_windows_name(arcname, os.path.sep) targetpath = os.path.join(targetpath, arcname) targetpath = os.path.normpath(targetpath) # Create all upper directories if necessary. upperdirs = os.path.dirname(targetpath) if upperdirs and not os.path.exists(upperdirs): os.makedirs(upperdirs) if member.is_dir(): if not os.path.isdir(targetpath): os.mkdir(targetpath) return targetpath with self.open(member, pwd=pwd) as source, \ open(targetpath, "wb") as target: shutil.copyfileobj(source, target) return targetpath
[ "def", "_extract_member", "(", "self", ",", "member", ",", "targetpath", ",", "pwd", ")", ":", "if", "not", "isinstance", "(", "member", ",", "ZipInfo", ")", ":", "member", "=", "self", ".", "getinfo", "(", "member", ")", "# build the destination pathname, replacing", "# forward slashes to platform specific separators.", "arcname", "=", "member", ".", "filename", ".", "replace", "(", "'/'", ",", "os", ".", "path", ".", "sep", ")", "if", "os", ".", "path", ".", "altsep", ":", "arcname", "=", "arcname", ".", "replace", "(", "os", ".", "path", ".", "altsep", ",", "os", ".", "path", ".", "sep", ")", "# interpret absolute pathname as relative, remove drive letter or", "# UNC path, redundant separators, \".\" and \"..\" components.", "arcname", "=", "os", ".", "path", ".", "splitdrive", "(", "arcname", ")", "[", "1", "]", "invalid_path_parts", "=", "(", "''", ",", "os", ".", "path", ".", "curdir", ",", "os", ".", "path", ".", "pardir", ")", "arcname", "=", "os", ".", "path", ".", "sep", ".", "join", "(", "x", "for", "x", "in", "arcname", ".", "split", "(", "os", ".", "path", ".", "sep", ")", "if", "x", "not", "in", "invalid_path_parts", ")", "if", "os", ".", "path", ".", "sep", "==", "'\\\\'", ":", "# filter illegal characters on Windows", "arcname", "=", "self", ".", "_sanitize_windows_name", "(", "arcname", ",", "os", ".", "path", ".", "sep", ")", "targetpath", "=", "os", ".", "path", ".", "join", "(", "targetpath", ",", "arcname", ")", "targetpath", "=", "os", ".", "path", ".", "normpath", "(", "targetpath", ")", "# Create all upper directories if necessary.", "upperdirs", "=", "os", ".", "path", ".", "dirname", "(", "targetpath", ")", "if", "upperdirs", "and", "not", "os", ".", "path", ".", "exists", "(", "upperdirs", ")", ":", "os", ".", "makedirs", "(", "upperdirs", ")", "if", "member", ".", "is_dir", "(", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "targetpath", ")", ":", "os", ".", "mkdir", "(", "targetpath", ")", "return", "targetpath", "with", "self", ".", "open", "(", "member", ",", "pwd", "=", "pwd", ")", "as", "source", ",", "open", "(", "targetpath", ",", "\"wb\"", ")", "as", "target", ":", "shutil", ".", "copyfileobj", "(", "source", ",", "target", ")", "return", "targetpath" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/zipfile.py#L1653-L1693
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Code/Tools/waf-1.7.13/crywaflib/default_settings.py
python
_is_user_option_true
(value)
return None
Convert multiple user inputs to True, False or None
Convert multiple user inputs to True, False or None
[ "Convert", "multiple", "user", "inputs", "to", "True", "False", "or", "None" ]
def _is_user_option_true(value): """ Convert multiple user inputs to True, False or None """ value = str(value) if value.lower() == 'true' or value.lower() == 't' or value.lower() == 'yes' or value.lower() == 'y' or value.lower() == '1': return True if value.lower() == 'false' or value.lower() == 'f' or value.lower() == 'no' or value.lower() == 'n' or value.lower() == '0': return False return None
[ "def", "_is_user_option_true", "(", "value", ")", ":", "value", "=", "str", "(", "value", ")", "if", "value", ".", "lower", "(", ")", "==", "'true'", "or", "value", ".", "lower", "(", ")", "==", "'t'", "or", "value", ".", "lower", "(", ")", "==", "'yes'", "or", "value", ".", "lower", "(", ")", "==", "'y'", "or", "value", ".", "lower", "(", ")", "==", "'1'", ":", "return", "True", "if", "value", ".", "lower", "(", ")", "==", "'false'", "or", "value", ".", "lower", "(", ")", "==", "'f'", "or", "value", ".", "lower", "(", ")", "==", "'no'", "or", "value", ".", "lower", "(", ")", "==", "'n'", "or", "value", ".", "lower", "(", ")", "==", "'0'", ":", "return", "False", "return", "None" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/crywaflib/default_settings.py#L56-L64
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/protobuf/python/google/protobuf/internal/cpp_message.py
python
ExtensionDict._FindExtensionByName
(self, name)
return self._message._extensions_by_name.get(name, None)
Tries to find a known extension with the specified name. Args: name: Extension full name. Returns: Extension field descriptor.
Tries to find a known extension with the specified name.
[ "Tries", "to", "find", "a", "known", "extension", "with", "the", "specified", "name", "." ]
def _FindExtensionByName(self, name): """Tries to find a known extension with the specified name. Args: name: Extension full name. Returns: Extension field descriptor. """ return self._message._extensions_by_name.get(name, None)
[ "def", "_FindExtensionByName", "(", "self", ",", "name", ")", ":", "return", "self", ".", "_message", ".", "_extensions_by_name", ".", "get", "(", "name", ",", "None", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/protobuf/python/google/protobuf/internal/cpp_message.py#L345-L354
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/logging/handlers.py
python
SMTPHandler.getSubject
(self, record)
return self.subject
Determine the subject for the email. If you want to specify a subject line which is record-dependent, override this method.
Determine the subject for the email.
[ "Determine", "the", "subject", "for", "the", "email", "." ]
def getSubject(self, record): """ Determine the subject for the email. If you want to specify a subject line which is record-dependent, override this method. """ return self.subject
[ "def", "getSubject", "(", "self", ",", "record", ")", ":", "return", "self", ".", "subject" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/logging/handlers.py#L924-L931
apiaryio/drafter
4634ebd07f6c6f257cc656598ccd535492fdfb55
tools/gyp/pylib/gyp/easy_xml.py
python
WriteXmlIfChanged
(content, path, encoding='utf-8', pretty=False, win32=False)
Writes the XML content to disk, touching the file only if it has changed. Args: content: The structured content to be written. path: Location of the file. encoding: The encoding to report on the first line of the XML file. pretty: True if we want pretty printing with indents and new lines.
Writes the XML content to disk, touching the file only if it has changed.
[ "Writes", "the", "XML", "content", "to", "disk", "touching", "the", "file", "only", "if", "it", "has", "changed", "." ]
def WriteXmlIfChanged(content, path, encoding='utf-8', pretty=False, win32=False): """ Writes the XML content to disk, touching the file only if it has changed. Args: content: The structured content to be written. path: Location of the file. encoding: The encoding to report on the first line of the XML file. pretty: True if we want pretty printing with indents and new lines. """ xml_string = XmlToString(content, encoding, pretty) if win32 and os.linesep != '\r\n': xml_string = xml_string.replace('\n', '\r\n') # Get the old content try: f = open(path, 'r') existing = f.read() f.close() except: existing = None # It has changed, write it if existing != xml_string: f = open(path, 'w') f.write(xml_string) f.close()
[ "def", "WriteXmlIfChanged", "(", "content", ",", "path", ",", "encoding", "=", "'utf-8'", ",", "pretty", "=", "False", ",", "win32", "=", "False", ")", ":", "xml_string", "=", "XmlToString", "(", "content", ",", "encoding", ",", "pretty", ")", "if", "win32", "and", "os", ".", "linesep", "!=", "'\\r\\n'", ":", "xml_string", "=", "xml_string", ".", "replace", "(", "'\\n'", ",", "'\\r\\n'", ")", "# Get the old content", "try", ":", "f", "=", "open", "(", "path", ",", "'r'", ")", "existing", "=", "f", ".", "read", "(", ")", "f", ".", "close", "(", ")", "except", ":", "existing", "=", "None", "# It has changed, write it", "if", "existing", "!=", "xml_string", ":", "f", "=", "open", "(", "path", ",", "'w'", ")", "f", ".", "write", "(", "xml_string", ")", "f", ".", "close", "(", ")" ]
https://github.com/apiaryio/drafter/blob/4634ebd07f6c6f257cc656598ccd535492fdfb55/tools/gyp/pylib/gyp/easy_xml.py#L105-L131
floooh/oryol
eb08cffe1b1cb6b05ed14ec692bca9372cef064e
fips-files/generators/util/png.py
python
Test.testEmpty
(self)
Test empty file.
Test empty file.
[ "Test", "empty", "file", "." ]
def testEmpty(self): """Test empty file.""" r = Reader(bytes='') self.assertRaises(FormatError, r.asDirect)
[ "def", "testEmpty", "(", "self", ")", ":", "r", "=", "Reader", "(", "bytes", "=", "''", ")", "self", ".", "assertRaises", "(", "FormatError", ",", "r", ".", "asDirect", ")" ]
https://github.com/floooh/oryol/blob/eb08cffe1b1cb6b05ed14ec692bca9372cef064e/fips-files/generators/util/png.py#L2646-L2650
CanalTP/navitia
cb84ce9859070187e708818b058e6a7e0b7f891b
source/jormungandr/jormungandr/external_services/vehicle_occupancy.py
python
VehicleOccupancyProvider.get_response
(self, arguments)
return first_occupancy["occupancy"] if "occupancy" in first_occupancy else None
Get vehicle_occupancy information from Forseti webservice
Get vehicle_occupancy information from Forseti webservice
[ "Get", "vehicle_occupancy", "information", "from", "Forseti", "webservice" ]
def get_response(self, arguments): """ Get vehicle_occupancy information from Forseti webservice """ raw_response = self._call_webservice(arguments) # We don't need any further action if raw_response is None if raw_response is None: return None resp = self.response_marshaller(raw_response) if resp is None: return None vehicle_occupancies = resp.get('vehicle_occupancies', []) if not vehicle_occupancies: return None first_occupancy = vehicle_occupancies[0] return first_occupancy["occupancy"] if "occupancy" in first_occupancy else None
[ "def", "get_response", "(", "self", ",", "arguments", ")", ":", "raw_response", "=", "self", ".", "_call_webservice", "(", "arguments", ")", "# We don't need any further action if raw_response is None", "if", "raw_response", "is", "None", ":", "return", "None", "resp", "=", "self", ".", "response_marshaller", "(", "raw_response", ")", "if", "resp", "is", "None", ":", "return", "None", "vehicle_occupancies", "=", "resp", ".", "get", "(", "'vehicle_occupancies'", ",", "[", "]", ")", "if", "not", "vehicle_occupancies", ":", "return", "None", "first_occupancy", "=", "vehicle_occupancies", "[", "0", "]", "return", "first_occupancy", "[", "\"occupancy\"", "]", "if", "\"occupancy\"", "in", "first_occupancy", "else", "None" ]
https://github.com/CanalTP/navitia/blob/cb84ce9859070187e708818b058e6a7e0b7f891b/source/jormungandr/jormungandr/external_services/vehicle_occupancy.py#L54-L70
tensorflow/io
92b44e180674a8af0e12e405530f7343e3e693e4
tensorflow_io/python/ops/io_tensor.py
python
IOTensor.from_json
(cls, filename, **kwargs)
Creates an `IOTensor` from an json file. Args: filename: A string, the filename of an json file. name: A name prefix for the IOTensor (optional). Returns: A `IOTensor`.
Creates an `IOTensor` from an json file.
[ "Creates", "an", "IOTensor", "from", "an", "json", "file", "." ]
def from_json(cls, filename, **kwargs): """Creates an `IOTensor` from an json file. Args: filename: A string, the filename of an json file. name: A name prefix for the IOTensor (optional). Returns: A `IOTensor`. """ with tf.name_scope(kwargs.get("name", "IOFromJSON")): return json_io_tensor_ops.JSONIOTensor( filename, mode=kwargs.get("mode", None), internal=True )
[ "def", "from_json", "(", "cls", ",", "filename", ",", "*", "*", "kwargs", ")", ":", "with", "tf", ".", "name_scope", "(", "kwargs", ".", "get", "(", "\"name\"", ",", "\"IOFromJSON\"", ")", ")", ":", "return", "json_io_tensor_ops", ".", "JSONIOTensor", "(", "filename", ",", "mode", "=", "kwargs", ".", "get", "(", "\"mode\"", ",", "None", ")", ",", "internal", "=", "True", ")" ]
https://github.com/tensorflow/io/blob/92b44e180674a8af0e12e405530f7343e3e693e4/tensorflow_io/python/ops/io_tensor.py#L261-L275
google/or-tools
2cb85b4eead4c38e1c54b48044f92087cf165bce
ortools/sat/python/cp_model.py
python
CpModel.AddAutomaton
(self, transition_variables, starting_state, final_states, transition_triples)
return ct
Adds an automaton constraint. An automaton constraint takes a list of variables (of size *n*), an initial state, a set of final states, and a set of transitions. A transition is a triplet (*tail*, *transition*, *head*), where *tail* and *head* are states, and *transition* is the label of an arc from *head* to *tail*, corresponding to the value of one variable in the list of variables. This automaton will be unrolled into a flow with *n* + 1 phases. Each phase contains the possible states of the automaton. The first state contains the initial state. The last phase contains the final states. Between two consecutive phases *i* and *i* + 1, the automaton creates a set of arcs. For each transition (*tail*, *transition*, *head*), it will add an arc from the state *tail* of phase *i* and the state *head* of phase *i* + 1. This arc is labeled by the value *transition* of the variables `variables[i]`. That is, this arc can only be selected if `variables[i]` is assigned the value *transition*. A feasible solution of this constraint is an assignment of variables such that, starting from the initial state in phase 0, there is a path labeled by the values of the variables that ends in one of the final states in the final phase. Args: transition_variables: A non-empty list of variables whose values correspond to the labels of the arcs traversed by the automaton. starting_state: The initial state of the automaton. final_states: A non-empty list of admissible final states. transition_triples: A list of transitions for the automaton, in the following format (current_state, variable_value, next_state). Returns: An instance of the `Constraint` class. Raises: ValueError: if `transition_variables`, `final_states`, or `transition_triples` are empty.
Adds an automaton constraint.
[ "Adds", "an", "automaton", "constraint", "." ]
def AddAutomaton(self, transition_variables, starting_state, final_states, transition_triples): """Adds an automaton constraint. An automaton constraint takes a list of variables (of size *n*), an initial state, a set of final states, and a set of transitions. A transition is a triplet (*tail*, *transition*, *head*), where *tail* and *head* are states, and *transition* is the label of an arc from *head* to *tail*, corresponding to the value of one variable in the list of variables. This automaton will be unrolled into a flow with *n* + 1 phases. Each phase contains the possible states of the automaton. The first state contains the initial state. The last phase contains the final states. Between two consecutive phases *i* and *i* + 1, the automaton creates a set of arcs. For each transition (*tail*, *transition*, *head*), it will add an arc from the state *tail* of phase *i* and the state *head* of phase *i* + 1. This arc is labeled by the value *transition* of the variables `variables[i]`. That is, this arc can only be selected if `variables[i]` is assigned the value *transition*. A feasible solution of this constraint is an assignment of variables such that, starting from the initial state in phase 0, there is a path labeled by the values of the variables that ends in one of the final states in the final phase. Args: transition_variables: A non-empty list of variables whose values correspond to the labels of the arcs traversed by the automaton. starting_state: The initial state of the automaton. final_states: A non-empty list of admissible final states. transition_triples: A list of transitions for the automaton, in the following format (current_state, variable_value, next_state). Returns: An instance of the `Constraint` class. Raises: ValueError: if `transition_variables`, `final_states`, or `transition_triples` are empty. """ if not transition_variables: raise ValueError( 'AddAutomaton expects a non-empty transition_variables ' 'array') if not final_states: raise ValueError('AddAutomaton expects some final states') if not transition_triples: raise ValueError('AddAutomaton expects some transition triples') ct = Constraint(self.__model.constraints) model_ct = self.__model.constraints[ct.Index()] model_ct.automaton.vars.extend( [self.GetOrMakeIndex(x) for x in transition_variables]) starting_state = cmh.assert_is_int64(starting_state) model_ct.automaton.starting_state = starting_state for v in final_states: v = cmh.assert_is_int64(v) model_ct.automaton.final_states.append(v) for t in transition_triples: if len(t) != 3: raise TypeError('Tuple ' + str(t) + ' has the wrong arity (!= 3)') tail = cmh.assert_is_int64(t[0]) label = cmh.assert_is_int64(t[1]) head = cmh.assert_is_int64(t[2]) model_ct.automaton.transition_tail.append(tail) model_ct.automaton.transition_label.append(label) model_ct.automaton.transition_head.append(head) return ct
[ "def", "AddAutomaton", "(", "self", ",", "transition_variables", ",", "starting_state", ",", "final_states", ",", "transition_triples", ")", ":", "if", "not", "transition_variables", ":", "raise", "ValueError", "(", "'AddAutomaton expects a non-empty transition_variables '", "'array'", ")", "if", "not", "final_states", ":", "raise", "ValueError", "(", "'AddAutomaton expects some final states'", ")", "if", "not", "transition_triples", ":", "raise", "ValueError", "(", "'AddAutomaton expects some transition triples'", ")", "ct", "=", "Constraint", "(", "self", ".", "__model", ".", "constraints", ")", "model_ct", "=", "self", ".", "__model", ".", "constraints", "[", "ct", ".", "Index", "(", ")", "]", "model_ct", ".", "automaton", ".", "vars", ".", "extend", "(", "[", "self", ".", "GetOrMakeIndex", "(", "x", ")", "for", "x", "in", "transition_variables", "]", ")", "starting_state", "=", "cmh", ".", "assert_is_int64", "(", "starting_state", ")", "model_ct", ".", "automaton", ".", "starting_state", "=", "starting_state", "for", "v", "in", "final_states", ":", "v", "=", "cmh", ".", "assert_is_int64", "(", "v", ")", "model_ct", ".", "automaton", ".", "final_states", ".", "append", "(", "v", ")", "for", "t", "in", "transition_triples", ":", "if", "len", "(", "t", ")", "!=", "3", ":", "raise", "TypeError", "(", "'Tuple '", "+", "str", "(", "t", ")", "+", "' has the wrong arity (!= 3)'", ")", "tail", "=", "cmh", ".", "assert_is_int64", "(", "t", "[", "0", "]", ")", "label", "=", "cmh", ".", "assert_is_int64", "(", "t", "[", "1", "]", ")", "head", "=", "cmh", ".", "assert_is_int64", "(", "t", "[", "2", "]", ")", "model_ct", ".", "automaton", ".", "transition_tail", ".", "append", "(", "tail", ")", "model_ct", ".", "automaton", ".", "transition_label", ".", "append", "(", "label", ")", "model_ct", ".", "automaton", ".", "transition_head", ".", "append", "(", "head", ")", "return", "ct" ]
https://github.com/google/or-tools/blob/2cb85b4eead4c38e1c54b48044f92087cf165bce/ortools/sat/python/cp_model.py#L1203-L1274
sdhash/sdhash
b9eff63e4e5867e910f41fd69032bbb1c94a2a5e
sdhash-ui/cherrypy/_cpchecker.py
python
Checker.check_config_namespaces
(self)
Process config and warn on each unknown config namespace.
Process config and warn on each unknown config namespace.
[ "Process", "config", "and", "warn", "on", "each", "unknown", "config", "namespace", "." ]
def check_config_namespaces(self): """Process config and warn on each unknown config namespace.""" for sn, app in cherrypy.tree.apps.items(): if not isinstance(app, cherrypy.Application): continue self._known_ns(app)
[ "def", "check_config_namespaces", "(", "self", ")", ":", "for", "sn", ",", "app", "in", "cherrypy", ".", "tree", ".", "apps", ".", "items", "(", ")", ":", "if", "not", "isinstance", "(", "app", ",", "cherrypy", ".", "Application", ")", ":", "continue", "self", ".", "_known_ns", "(", "app", ")" ]
https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-ui/cherrypy/_cpchecker.py#L254-L259
ucbrise/clipper
9f25e3fc7f8edc891615e81c5b80d3d8aed72608
clipper_admin/clipper_admin/docker/logging/fluentd.py
python
FluentdConfig.set_forward_address
(self, address, port)
Set the port number and address of external fluentd instance (internal is the clipper fluentd) in which centralized logs will be forwarded :param port: port number to forward logs
Set the port number and address of external fluentd instance (internal is the clipper fluentd) in which centralized logs will be forwarded
[ "Set", "the", "port", "number", "and", "address", "of", "external", "fluentd", "instance", "(", "internal", "is", "the", "clipper", "fluentd", ")", "in", "which", "centralized", "logs", "will", "be", "forwarded" ]
def set_forward_address(self, address, port): """ Set the port number and address of external fluentd instance (internal is the clipper fluentd) in which centralized logs will be forwarded :param port: port number to forward logs """ raise NotImplementedError("set_forward_address is not implemented yet. It will be coming soon.")
[ "def", "set_forward_address", "(", "self", ",", "address", ",", "port", ")", ":", "raise", "NotImplementedError", "(", "\"set_forward_address is not implemented yet. It will be coming soon.\"", ")" ]
https://github.com/ucbrise/clipper/blob/9f25e3fc7f8edc891615e81c5b80d3d8aed72608/clipper_admin/clipper_admin/docker/logging/fluentd.py#L109-L116
citizenfx/fivem
88276d40cc7baf8285d02754cc5ae42ec7a8563f
vendor/chromium/mojo/public/tools/bindings/pylib/mojom/parse/lexer.py
python
Lexer.t_COMMENT
(self, t)
r'(/\*(.|\n)*?\*/)|(//.*(\n[ \t]*//.*)*)
r'(/\*(.|\n)*?\*/)|(//.*(\n[ \t]*//.*)*)
[ "r", "(", "/", "\\", "*", "(", ".", "|", "\\", "n", ")", "*", "?", "\\", "*", "/", ")", "|", "(", "//", ".", "*", "(", "\\", "n", "[", "\\", "t", "]", "*", "//", ".", "*", ")", "*", ")" ]
def t_COMMENT(self, t): r'(/\*(.|\n)*?\*/)|(//.*(\n[ \t]*//.*)*)' t.lexer.lineno += t.value.count("\n")
[ "def", "t_COMMENT", "(", "self", ",", "t", ")", ":", "t", ".", "lexer", ".", "lineno", "+=", "t", ".", "value", ".", "count", "(", "\"\\n\"", ")" ]
https://github.com/citizenfx/fivem/blob/88276d40cc7baf8285d02754cc5ae42ec7a8563f/vendor/chromium/mojo/public/tools/bindings/pylib/mojom/parse/lexer.py#L252-L254
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/ops/nn_grad.py
python
_LogSoftmaxGrad
(op, grad)
return grad - math_ops.reduce_sum(grad, 1, keep_dims=True) * softmax
The gradient for log_softmax. log_softmax = input - log(sum(exp(input)) dlog_softmax/dinput = diag - softmax(input) Args: op: The log softmax op. grad: The tensor representing the gradient w.r.t. the output. Returns: The gradients w.r.t. the input.
The gradient for log_softmax.
[ "The", "gradient", "for", "log_softmax", "." ]
def _LogSoftmaxGrad(op, grad): """The gradient for log_softmax. log_softmax = input - log(sum(exp(input)) dlog_softmax/dinput = diag - softmax(input) Args: op: The log softmax op. grad: The tensor representing the gradient w.r.t. the output. Returns: The gradients w.r.t. the input. """ softmax = math_ops.exp(op.outputs[0]) return grad - math_ops.reduce_sum(grad, 1, keep_dims=True) * softmax
[ "def", "_LogSoftmaxGrad", "(", "op", ",", "grad", ")", ":", "softmax", "=", "math_ops", ".", "exp", "(", "op", ".", "outputs", "[", "0", "]", ")", "return", "grad", "-", "math_ops", ".", "reduce_sum", "(", "grad", ",", "1", ",", "keep_dims", "=", "True", ")", "*", "softmax" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/nn_grad.py#L218-L232
openvinotoolkit/openvino
dedcbeafa8b84cccdc55ca64b8da516682b381c7
src/bindings/python/src/openvino/runtime/opset1/ops.py
python
reduce_logical_or
( node: NodeInput, reduction_axes: NodeInput, keep_dims: bool = False, name: Optional[str] = None )
return _get_node_factory_opset1().create( "ReduceLogicalOr", as_nodes(node, reduction_axes), {"keep_dims": keep_dims} )
Logical OR reduction operation on input tensor, eliminating the specified reduction axes. @param node: The tensor we want to reduce. @param reduction_axes: The axes to eliminate through OR operation. @param keep_dims: If set to True it holds axes that are used for reduction @param name: Optional name for output node. @return The new node performing reduction operation.
Logical OR reduction operation on input tensor, eliminating the specified reduction axes.
[ "Logical", "OR", "reduction", "operation", "on", "input", "tensor", "eliminating", "the", "specified", "reduction", "axes", "." ]
def reduce_logical_or( node: NodeInput, reduction_axes: NodeInput, keep_dims: bool = False, name: Optional[str] = None ) -> Node: """Logical OR reduction operation on input tensor, eliminating the specified reduction axes. @param node: The tensor we want to reduce. @param reduction_axes: The axes to eliminate through OR operation. @param keep_dims: If set to True it holds axes that are used for reduction @param name: Optional name for output node. @return The new node performing reduction operation. """ return _get_node_factory_opset1().create( "ReduceLogicalOr", as_nodes(node, reduction_axes), {"keep_dims": keep_dims} )
[ "def", "reduce_logical_or", "(", "node", ":", "NodeInput", ",", "reduction_axes", ":", "NodeInput", ",", "keep_dims", ":", "bool", "=", "False", ",", "name", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "Node", ":", "return", "_get_node_factory_opset1", "(", ")", ".", "create", "(", "\"ReduceLogicalOr\"", ",", "as_nodes", "(", "node", ",", "reduction_axes", ")", ",", "{", "\"keep_dims\"", ":", "keep_dims", "}", ")" ]
https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/src/bindings/python/src/openvino/runtime/opset1/ops.py#L2258-L2271
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/third_party/modulegraph/modulegraph/modulegraph.py
python
_namespace_package_path
(fqname, pathnames, path=None)
return path
Return the __path__ for the python package in *fqname*. This function uses setuptools metadata to extract information about namespace packages from installed eggs.
Return the __path__ for the python package in *fqname*.
[ "Return", "the", "__path__", "for", "the", "python", "package", "in", "*", "fqname", "*", "." ]
def _namespace_package_path(fqname, pathnames, path=None): """ Return the __path__ for the python package in *fqname*. This function uses setuptools metadata to extract information about namespace packages from installed eggs. """ working_set = pkg_resources.WorkingSet(path) path = list(pathnames) for dist in working_set: if dist.has_metadata('namespace_packages.txt'): namespaces = dist.get_metadata( 'namespace_packages.txt').splitlines() if fqname in namespaces: nspath = os.path.join(dist.location, *fqname.split('.')) if nspath not in path: path.append(nspath) return path
[ "def", "_namespace_package_path", "(", "fqname", ",", "pathnames", ",", "path", "=", "None", ")", ":", "working_set", "=", "pkg_resources", ".", "WorkingSet", "(", "path", ")", "path", "=", "list", "(", "pathnames", ")", "for", "dist", "in", "working_set", ":", "if", "dist", ".", "has_metadata", "(", "'namespace_packages.txt'", ")", ":", "namespaces", "=", "dist", ".", "get_metadata", "(", "'namespace_packages.txt'", ")", ".", "splitlines", "(", ")", "if", "fqname", "in", "namespaces", ":", "nspath", "=", "os", ".", "path", ".", "join", "(", "dist", ".", "location", ",", "*", "fqname", ".", "split", "(", "'.'", ")", ")", "if", "nspath", "not", "in", "path", ":", "path", ".", "append", "(", "nspath", ")", "return", "path" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/modulegraph/modulegraph/modulegraph.py#L77-L97
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distro.py
python
LinuxDistribution.uname_info
(self)
return self._uname_info
Return a dictionary containing key-value pairs for the information items from the uname command data source of the OS distribution. For details, see :func:`distro.uname_info`.
[]
def uname_info(self): """ Return a dictionary containing key-value pairs for the information items from the uname command data source of the OS distribution. For details, see :func:`distro.uname_info`. """ return self._uname_info
[ "def", "uname_info", "(", "self", ")", ":", "return", "self", ".", "_uname_info" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distro.py#L1755-L1769
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
third_party/protobuf/python/google/protobuf/internal/wire_format.py
python
IsTypePackable
(field_type)
return field_type not in NON_PACKABLE_TYPES
Return true iff packable = true is valid for fields of this type. Args: field_type: a FieldDescriptor::Type value. Returns: True iff fields of this type are packable.
Return true iff packable = true is valid for fields of this type.
[ "Return", "true", "iff", "packable", "=", "true", "is", "valid", "for", "fields", "of", "this", "type", "." ]
def IsTypePackable(field_type): """Return true iff packable = true is valid for fields of this type. Args: field_type: a FieldDescriptor::Type value. Returns: True iff fields of this type are packable. """ return field_type not in NON_PACKABLE_TYPES
[ "def", "IsTypePackable", "(", "field_type", ")", ":", "return", "field_type", "not", "in", "NON_PACKABLE_TYPES" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/protobuf/python/google/protobuf/internal/wire_format.py#L259-L268
funnyzhou/Adaptive_Feeding
9c78182331d8c0ea28de47226e805776c638d46f
lib/pycocotools/cocoeval.py
python
COCOeval.accumulate
(self, p = None)
Accumulate per image evaluation results and store the result in self.eval :param p: input params for evaluation :return: None
Accumulate per image evaluation results and store the result in self.eval :param p: input params for evaluation :return: None
[ "Accumulate", "per", "image", "evaluation", "results", "and", "store", "the", "result", "in", "self", ".", "eval", ":", "param", "p", ":", "input", "params", "for", "evaluation", ":", "return", ":", "None" ]
def accumulate(self, p = None): ''' Accumulate per image evaluation results and store the result in self.eval :param p: input params for evaluation :return: None ''' print 'Accumulating evaluation results... ' tic = time.time() if not self.evalImgs: print 'Please run evaluate() first' # allows input customized parameters if p is None: p = self.params p.catIds = p.catIds if p.useCats == 1 else [-1] T = len(p.iouThrs) R = len(p.recThrs) K = len(p.catIds) if p.useCats else 1 A = len(p.areaRng) M = len(p.maxDets) precision = -np.ones((T,R,K,A,M)) # -1 for the precision of absent categories recall = -np.ones((T,K,A,M)) # create dictionary for future indexing _pe = self._paramsEval catIds = _pe.catIds if _pe.useCats else [-1] setK = set(catIds) setA = set(map(tuple, _pe.areaRng)) setM = set(_pe.maxDets) setI = set(_pe.imgIds) # get inds to evaluate k_list = [n for n, k in enumerate(p.catIds) if k in setK] m_list = [m for n, m in enumerate(p.maxDets) if m in setM] a_list = [n for n, a in enumerate(map(lambda x: tuple(x), p.areaRng)) if a in setA] i_list = [n for n, i in enumerate(p.imgIds) if i in setI] # K0 = len(_pe.catIds) I0 = len(_pe.imgIds) A0 = len(_pe.areaRng) # retrieve E at each category, area range, and max number of detections for k, k0 in enumerate(k_list): Nk = k0*A0*I0 for a, a0 in enumerate(a_list): Na = a0*I0 for m, maxDet in enumerate(m_list): E = [self.evalImgs[Nk+Na+i] for i in i_list] E = filter(None, E) if len(E) == 0: continue dtScores = np.concatenate([e['dtScores'][0:maxDet] for e in E]) # different sorting method generates slightly different results. # mergesort is used to be consistent as Matlab implementation. inds = np.argsort(-dtScores, kind='mergesort') dtm = np.concatenate([e['dtMatches'][:,0:maxDet] for e in E], axis=1)[:,inds] dtIg = np.concatenate([e['dtIgnore'][:,0:maxDet] for e in E], axis=1)[:,inds] gtIg = np.concatenate([e['gtIgnore'] for e in E]) npig = len([ig for ig in gtIg if ig == 0]) if npig == 0: continue tps = np.logical_and( dtm, np.logical_not(dtIg) ) fps = np.logical_and(np.logical_not(dtm), np.logical_not(dtIg) ) tp_sum = np.cumsum(tps, axis=1).astype(dtype=np.float) fp_sum = np.cumsum(fps, axis=1).astype(dtype=np.float) for t, (tp, fp) in enumerate(zip(tp_sum, fp_sum)): tp = np.array(tp) fp = np.array(fp) nd = len(tp) rc = tp / npig pr = tp / (fp+tp+np.spacing(1)) q = np.zeros((R,)) if nd: recall[t,k,a,m] = rc[-1] else: recall[t,k,a,m] = 0 # numpy is slow without cython optimization for accessing elements # use python array gets significant speed improvement pr = pr.tolist(); q = q.tolist() for i in range(nd-1, 0, -1): if pr[i] > pr[i-1]: pr[i-1] = pr[i] inds = np.searchsorted(rc, p.recThrs) try: for ri, pi in enumerate(inds): q[ri] = pr[pi] except: pass precision[t,:,k,a,m] = np.array(q) self.eval = { 'params': p, 'counts': [T, R, K, A, M], 'date': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), 'precision': precision, 'recall': recall, } toc = time.time() print 'DONE (t=%0.2fs).'%( toc-tic )
[ "def", "accumulate", "(", "self", ",", "p", "=", "None", ")", ":", "print", "'Accumulating evaluation results... '", "tic", "=", "time", ".", "time", "(", ")", "if", "not", "self", ".", "evalImgs", ":", "print", "'Please run evaluate() first'", "# allows input customized parameters", "if", "p", "is", "None", ":", "p", "=", "self", ".", "params", "p", ".", "catIds", "=", "p", ".", "catIds", "if", "p", ".", "useCats", "==", "1", "else", "[", "-", "1", "]", "T", "=", "len", "(", "p", ".", "iouThrs", ")", "R", "=", "len", "(", "p", ".", "recThrs", ")", "K", "=", "len", "(", "p", ".", "catIds", ")", "if", "p", ".", "useCats", "else", "1", "A", "=", "len", "(", "p", ".", "areaRng", ")", "M", "=", "len", "(", "p", ".", "maxDets", ")", "precision", "=", "-", "np", ".", "ones", "(", "(", "T", ",", "R", ",", "K", ",", "A", ",", "M", ")", ")", "# -1 for the precision of absent categories", "recall", "=", "-", "np", ".", "ones", "(", "(", "T", ",", "K", ",", "A", ",", "M", ")", ")", "# create dictionary for future indexing", "_pe", "=", "self", ".", "_paramsEval", "catIds", "=", "_pe", ".", "catIds", "if", "_pe", ".", "useCats", "else", "[", "-", "1", "]", "setK", "=", "set", "(", "catIds", ")", "setA", "=", "set", "(", "map", "(", "tuple", ",", "_pe", ".", "areaRng", ")", ")", "setM", "=", "set", "(", "_pe", ".", "maxDets", ")", "setI", "=", "set", "(", "_pe", ".", "imgIds", ")", "# get inds to evaluate", "k_list", "=", "[", "n", "for", "n", ",", "k", "in", "enumerate", "(", "p", ".", "catIds", ")", "if", "k", "in", "setK", "]", "m_list", "=", "[", "m", "for", "n", ",", "m", "in", "enumerate", "(", "p", ".", "maxDets", ")", "if", "m", "in", "setM", "]", "a_list", "=", "[", "n", "for", "n", ",", "a", "in", "enumerate", "(", "map", "(", "lambda", "x", ":", "tuple", "(", "x", ")", ",", "p", ".", "areaRng", ")", ")", "if", "a", "in", "setA", "]", "i_list", "=", "[", "n", "for", "n", ",", "i", "in", "enumerate", "(", "p", ".", "imgIds", ")", "if", "i", "in", "setI", "]", "# K0 = len(_pe.catIds)", "I0", "=", "len", "(", "_pe", ".", "imgIds", ")", "A0", "=", "len", "(", "_pe", ".", "areaRng", ")", "# retrieve E at each category, area range, and max number of detections", "for", "k", ",", "k0", "in", "enumerate", "(", "k_list", ")", ":", "Nk", "=", "k0", "*", "A0", "*", "I0", "for", "a", ",", "a0", "in", "enumerate", "(", "a_list", ")", ":", "Na", "=", "a0", "*", "I0", "for", "m", ",", "maxDet", "in", "enumerate", "(", "m_list", ")", ":", "E", "=", "[", "self", ".", "evalImgs", "[", "Nk", "+", "Na", "+", "i", "]", "for", "i", "in", "i_list", "]", "E", "=", "filter", "(", "None", ",", "E", ")", "if", "len", "(", "E", ")", "==", "0", ":", "continue", "dtScores", "=", "np", ".", "concatenate", "(", "[", "e", "[", "'dtScores'", "]", "[", "0", ":", "maxDet", "]", "for", "e", "in", "E", "]", ")", "# different sorting method generates slightly different results.", "# mergesort is used to be consistent as Matlab implementation.", "inds", "=", "np", ".", "argsort", "(", "-", "dtScores", ",", "kind", "=", "'mergesort'", ")", "dtm", "=", "np", ".", "concatenate", "(", "[", "e", "[", "'dtMatches'", "]", "[", ":", ",", "0", ":", "maxDet", "]", "for", "e", "in", "E", "]", ",", "axis", "=", "1", ")", "[", ":", ",", "inds", "]", "dtIg", "=", "np", ".", "concatenate", "(", "[", "e", "[", "'dtIgnore'", "]", "[", ":", ",", "0", ":", "maxDet", "]", "for", "e", "in", "E", "]", ",", "axis", "=", "1", ")", "[", ":", ",", "inds", "]", "gtIg", "=", "np", ".", "concatenate", "(", "[", "e", "[", "'gtIgnore'", "]", "for", "e", "in", "E", "]", ")", "npig", "=", "len", "(", "[", "ig", "for", "ig", "in", "gtIg", "if", "ig", "==", "0", "]", ")", "if", "npig", "==", "0", ":", "continue", "tps", "=", "np", ".", "logical_and", "(", "dtm", ",", "np", ".", "logical_not", "(", "dtIg", ")", ")", "fps", "=", "np", ".", "logical_and", "(", "np", ".", "logical_not", "(", "dtm", ")", ",", "np", ".", "logical_not", "(", "dtIg", ")", ")", "tp_sum", "=", "np", ".", "cumsum", "(", "tps", ",", "axis", "=", "1", ")", ".", "astype", "(", "dtype", "=", "np", ".", "float", ")", "fp_sum", "=", "np", ".", "cumsum", "(", "fps", ",", "axis", "=", "1", ")", ".", "astype", "(", "dtype", "=", "np", ".", "float", ")", "for", "t", ",", "(", "tp", ",", "fp", ")", "in", "enumerate", "(", "zip", "(", "tp_sum", ",", "fp_sum", ")", ")", ":", "tp", "=", "np", ".", "array", "(", "tp", ")", "fp", "=", "np", ".", "array", "(", "fp", ")", "nd", "=", "len", "(", "tp", ")", "rc", "=", "tp", "/", "npig", "pr", "=", "tp", "/", "(", "fp", "+", "tp", "+", "np", ".", "spacing", "(", "1", ")", ")", "q", "=", "np", ".", "zeros", "(", "(", "R", ",", ")", ")", "if", "nd", ":", "recall", "[", "t", ",", "k", ",", "a", ",", "m", "]", "=", "rc", "[", "-", "1", "]", "else", ":", "recall", "[", "t", ",", "k", ",", "a", ",", "m", "]", "=", "0", "# numpy is slow without cython optimization for accessing elements", "# use python array gets significant speed improvement", "pr", "=", "pr", ".", "tolist", "(", ")", "q", "=", "q", ".", "tolist", "(", ")", "for", "i", "in", "range", "(", "nd", "-", "1", ",", "0", ",", "-", "1", ")", ":", "if", "pr", "[", "i", "]", ">", "pr", "[", "i", "-", "1", "]", ":", "pr", "[", "i", "-", "1", "]", "=", "pr", "[", "i", "]", "inds", "=", "np", ".", "searchsorted", "(", "rc", ",", "p", ".", "recThrs", ")", "try", ":", "for", "ri", ",", "pi", "in", "enumerate", "(", "inds", ")", ":", "q", "[", "ri", "]", "=", "pr", "[", "pi", "]", "except", ":", "pass", "precision", "[", "t", ",", ":", ",", "k", ",", "a", ",", "m", "]", "=", "np", ".", "array", "(", "q", ")", "self", ".", "eval", "=", "{", "'params'", ":", "p", ",", "'counts'", ":", "[", "T", ",", "R", ",", "K", ",", "A", ",", "M", "]", ",", "'date'", ":", "datetime", ".", "datetime", ".", "now", "(", ")", ".", "strftime", "(", "\"%Y-%m-%d %H:%M:%S\"", ")", ",", "'precision'", ":", "precision", ",", "'recall'", ":", "recall", ",", "}", "toc", "=", "time", ".", "time", "(", ")", "print", "'DONE (t=%0.2fs).'", "%", "(", "toc", "-", "tic", ")" ]
https://github.com/funnyzhou/Adaptive_Feeding/blob/9c78182331d8c0ea28de47226e805776c638d46f/lib/pycocotools/cocoeval.py#L274-L374
etternagame/etterna
8775f74ac9c353320128609d4b4150672e9a6d04
extern/crashpad/crashpad/third_party/mini_chromium/mini_chromium/build/ios/codesign.py
python
ProvisioningProfile.Install
(self, installation_path)
Copies mobile provisioning profile info to |installation_path|.
Copies mobile provisioning profile info to |installation_path|.
[ "Copies", "mobile", "provisioning", "profile", "info", "to", "|installation_path|", "." ]
def Install(self, installation_path): """Copies mobile provisioning profile info to |installation_path|.""" shutil.copy2(self.path, installation_path)
[ "def", "Install", "(", "self", ",", "installation_path", ")", ":", "shutil", ".", "copy2", "(", "self", ".", "path", ",", "installation_path", ")" ]
https://github.com/etternagame/etterna/blob/8775f74ac9c353320128609d4b4150672e9a6d04/extern/crashpad/crashpad/third_party/mini_chromium/mini_chromium/build/ios/codesign.py#L130-L132
OSGeo/gdal
3748fc4ba4fba727492774b2b908a2130c864a83
swig/python/osgeo/ogr.py
python
Feature.__setitem__
(self, key, value)
Returns the value of a field by field name / index
Returns the value of a field by field name / index
[ "Returns", "the", "value", "of", "a", "field", "by", "field", "name", "/", "index" ]
def __setitem__(self, key, value): """Returns the value of a field by field name / index""" if isinstance(key, str): fld_index = self._getfieldindex(key) else: fld_index = key if key == self.GetFieldCount(): raise IndexError if fld_index < 0: if isinstance(key, str): fld_index = self.GetGeomFieldIndex(key) if fld_index < 0: raise KeyError("Illegal field requested in SetField()") else: return self.SetGeomField(fld_index, value) else: return self.SetField2(fld_index, value)
[ "def", "__setitem__", "(", "self", ",", "key", ",", "value", ")", ":", "if", "isinstance", "(", "key", ",", "str", ")", ":", "fld_index", "=", "self", ".", "_getfieldindex", "(", "key", ")", "else", ":", "fld_index", "=", "key", "if", "key", "==", "self", ".", "GetFieldCount", "(", ")", ":", "raise", "IndexError", "if", "fld_index", "<", "0", ":", "if", "isinstance", "(", "key", ",", "str", ")", ":", "fld_index", "=", "self", ".", "GetGeomFieldIndex", "(", "key", ")", "if", "fld_index", "<", "0", ":", "raise", "KeyError", "(", "\"Illegal field requested in SetField()\"", ")", "else", ":", "return", "self", ".", "SetGeomField", "(", "fld_index", ",", "value", ")", "else", ":", "return", "self", ".", "SetField2", "(", "fld_index", ",", "value", ")" ]
https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/ogr.py#L4300-L4316
epam/Indigo
30e40b4b1eb9bae0207435a26cfcb81ddcc42be1
api/python/indigo/__init__.py
python
Indigo.loadStructureFromBuffer
(self, structureData, parameter=None)
return self.IndigoObject( self, self._checkResult( Indigo._lib.indigoLoadStructureFromBuffer( values, len(buf), parameter.encode(ENCODE_ENCODING) ) ), )
Loads structure object from buffer Args: structureData (list): array of bytes parameter (str): parameters for loading. Optional, defaults to None. Returns: IndigoObject: loaded object
Loads structure object from buffer
[ "Loads", "structure", "object", "from", "buffer" ]
def loadStructureFromBuffer(self, structureData, parameter=None): """Loads structure object from buffer Args: structureData (list): array of bytes parameter (str): parameters for loading. Optional, defaults to None. Returns: IndigoObject: loaded object """ if sys.version_info[0] < 3: buf = map(ord, structureData) else: buf = structureData values = (c_byte * len(buf))() for i in range(len(buf)): values[i] = buf[i] self._setSessionId() parameter = "" if parameter is None else parameter return self.IndigoObject( self, self._checkResult( Indigo._lib.indigoLoadStructureFromBuffer( values, len(buf), parameter.encode(ENCODE_ENCODING) ) ), )
[ "def", "loadStructureFromBuffer", "(", "self", ",", "structureData", ",", "parameter", "=", "None", ")", ":", "if", "sys", ".", "version_info", "[", "0", "]", "<", "3", ":", "buf", "=", "map", "(", "ord", ",", "structureData", ")", "else", ":", "buf", "=", "structureData", "values", "=", "(", "c_byte", "*", "len", "(", "buf", ")", ")", "(", ")", "for", "i", "in", "range", "(", "len", "(", "buf", ")", ")", ":", "values", "[", "i", "]", "=", "buf", "[", "i", "]", "self", ".", "_setSessionId", "(", ")", "parameter", "=", "\"\"", "if", "parameter", "is", "None", "else", "parameter", "return", "self", ".", "IndigoObject", "(", "self", ",", "self", ".", "_checkResult", "(", "Indigo", ".", "_lib", ".", "indigoLoadStructureFromBuffer", "(", "values", ",", "len", "(", "buf", ")", ",", "parameter", ".", "encode", "(", "ENCODE_ENCODING", ")", ")", ")", ",", ")" ]
https://github.com/epam/Indigo/blob/30e40b4b1eb9bae0207435a26cfcb81ddcc42be1/api/python/indigo/__init__.py#L5807-L5833
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/win_tool.py
python
WinTool.Dispatch
(self, args)
return getattr(self, method)(*args[1:])
Dispatches a string command to a method.
Dispatches a string command to a method.
[ "Dispatches", "a", "string", "command", "to", "a", "method", "." ]
def Dispatch(self, args): """Dispatches a string command to a method.""" if len(args) < 1: raise Exception("Not enough arguments") method = "Exec%s" % self._CommandifyName(args[0]) return getattr(self, method)(*args[1:])
[ "def", "Dispatch", "(", "self", ",", "args", ")", ":", "if", "len", "(", "args", ")", "<", "1", ":", "raise", "Exception", "(", "\"Not enough arguments\"", ")", "method", "=", "\"Exec%s\"", "%", "self", ".", "_CommandifyName", "(", "args", "[", "0", "]", ")", "return", "getattr", "(", "self", ",", "method", ")", "(", "*", "args", "[", "1", ":", "]", ")" ]
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/win_tool.py#L64-L70
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/dataset/engine/validators.py
python
check_gnn_random_walk
(method)
return new_method
A wrapper that wraps a parameter checker around the GNN `random_walk` function.
A wrapper that wraps a parameter checker around the GNN `random_walk` function.
[ "A", "wrapper", "that", "wraps", "a", "parameter", "checker", "around", "the", "GNN", "random_walk", "function", "." ]
def check_gnn_random_walk(method): """A wrapper that wraps a parameter checker around the GNN `random_walk` function.""" @wraps(method) def new_method(self, *args, **kwargs): [target_nodes, meta_path, step_home_param, step_away_param, default_node], _ = parse_user_args(method, *args, **kwargs) check_gnn_list_or_ndarray(target_nodes, 'target_nodes') check_gnn_list_or_ndarray(meta_path, 'meta_path') type_check(step_home_param, (float,), "step_home_param") type_check(step_away_param, (float,), "step_away_param") type_check(default_node, (int,), "default_node") check_value(default_node, (-1, INT32_MAX), "default_node") return method(self, *args, **kwargs) return new_method
[ "def", "check_gnn_random_walk", "(", "method", ")", ":", "@", "wraps", "(", "method", ")", "def", "new_method", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "[", "target_nodes", ",", "meta_path", ",", "step_home_param", ",", "step_away_param", ",", "default_node", "]", ",", "_", "=", "parse_user_args", "(", "method", ",", "*", "args", ",", "*", "*", "kwargs", ")", "check_gnn_list_or_ndarray", "(", "target_nodes", ",", "'target_nodes'", ")", "check_gnn_list_or_ndarray", "(", "meta_path", ",", "'meta_path'", ")", "type_check", "(", "step_home_param", ",", "(", "float", ",", ")", ",", "\"step_home_param\"", ")", "type_check", "(", "step_away_param", ",", "(", "float", ",", ")", ",", "\"step_away_param\"", ")", "type_check", "(", "default_node", ",", "(", "int", ",", ")", ",", "\"default_node\"", ")", "check_value", "(", "default_node", ",", "(", "-", "1", ",", "INT32_MAX", ")", ",", "\"default_node\"", ")", "return", "method", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "new_method" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/dataset/engine/validators.py#L1700-L1716
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py2/numpy/core/_string_helpers.py
python
english_capitalize
(s)
Apply English case rules to convert the first character of an ASCII string to upper case. This is an internal utility function to replace calls to str.capitalize() such that we can avoid changing behavior with changing locales. Parameters ---------- s : str Returns ------- capitalized : str Examples -------- >>> from numpy.core.numerictypes import english_capitalize >>> english_capitalize('int8') 'Int8' >>> english_capitalize('Int8') 'Int8' >>> english_capitalize('') ''
Apply English case rules to convert the first character of an ASCII string to upper case.
[ "Apply", "English", "case", "rules", "to", "convert", "the", "first", "character", "of", "an", "ASCII", "string", "to", "upper", "case", "." ]
def english_capitalize(s): """ Apply English case rules to convert the first character of an ASCII string to upper case. This is an internal utility function to replace calls to str.capitalize() such that we can avoid changing behavior with changing locales. Parameters ---------- s : str Returns ------- capitalized : str Examples -------- >>> from numpy.core.numerictypes import english_capitalize >>> english_capitalize('int8') 'Int8' >>> english_capitalize('Int8') 'Int8' >>> english_capitalize('') '' """ if s: return english_upper(s[0]) + s[1:] else: return s
[ "def", "english_capitalize", "(", "s", ")", ":", "if", "s", ":", "return", "english_upper", "(", "s", "[", "0", "]", ")", "+", "s", "[", "1", ":", "]", "else", ":", "return", "s" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/core/_string_helpers.py#L72-L100
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/email/message.py
python
Message.is_multipart
(self)
return isinstance(self._payload, list)
Return True if the message consists of multiple parts.
Return True if the message consists of multiple parts.
[ "Return", "True", "if", "the", "message", "consists", "of", "multiple", "parts", "." ]
def is_multipart(self): """Return True if the message consists of multiple parts.""" return isinstance(self._payload, list)
[ "def", "is_multipart", "(", "self", ")", ":", "return", "isinstance", "(", "self", ".", "_payload", ",", "list", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/email/message.py#L140-L142
trilinos/Trilinos
6168be6dd51e35e1cd681e9c4b24433e709df140
packages/seacas/scripts/exodus2.in.py
python
exodus.put_side_set_property_value
(self, id, name, value)
return self.__ex_put_prop(ssType, id, name, value)
status = exo.put_side_set_property_value(side_set_id, \\ ssprop_name, \\ ssprop_val) -> store a side set property name and its integer value for a side set input value(s): <int> side_set_id side set *ID* (not *INDEX*) <string> ssprop_name <int> ssprop_val return value(s): <bool> status True = successful execution
status = exo.put_side_set_property_value(side_set_id, \\ ssprop_name, \\ ssprop_val)
[ "status", "=", "exo", ".", "put_side_set_property_value", "(", "side_set_id", "\\\\", "ssprop_name", "\\\\", "ssprop_val", ")" ]
def put_side_set_property_value(self, id, name, value): """ status = exo.put_side_set_property_value(side_set_id, \\ ssprop_name, \\ ssprop_val) -> store a side set property name and its integer value for a side set input value(s): <int> side_set_id side set *ID* (not *INDEX*) <string> ssprop_name <int> ssprop_val return value(s): <bool> status True = successful execution """ ssType = ex_entity_type("EX_SIDE_SET") return self.__ex_put_prop(ssType, id, name, value)
[ "def", "put_side_set_property_value", "(", "self", ",", "id", ",", "name", ",", "value", ")", ":", "ssType", "=", "ex_entity_type", "(", "\"EX_SIDE_SET\"", ")", "return", "self", ".", "__ex_put_prop", "(", "ssType", ",", "id", ",", "name", ",", "value", ")" ]
https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exodus2.in.py#L3065-L3083
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/requests/sessions.py
python
merge_hooks
(request_hooks, session_hooks, dict_class=OrderedDict)
return merge_setting(request_hooks, session_hooks, dict_class)
Properly merges both requests and session hooks. This is necessary because when request_hooks == {'response': []}, the merge breaks Session hooks entirely.
Properly merges both requests and session hooks.
[ "Properly", "merges", "both", "requests", "and", "session", "hooks", "." ]
def merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict): """Properly merges both requests and session hooks. This is necessary because when request_hooks == {'response': []}, the merge breaks Session hooks entirely. """ if session_hooks is None or session_hooks.get('response') == []: return request_hooks if request_hooks is None or request_hooks.get('response') == []: return session_hooks return merge_setting(request_hooks, session_hooks, dict_class)
[ "def", "merge_hooks", "(", "request_hooks", ",", "session_hooks", ",", "dict_class", "=", "OrderedDict", ")", ":", "if", "session_hooks", "is", "None", "or", "session_hooks", ".", "get", "(", "'response'", ")", "==", "[", "]", ":", "return", "request_hooks", "if", "request_hooks", "is", "None", "or", "request_hooks", ".", "get", "(", "'response'", ")", "==", "[", "]", ":", "return", "session_hooks", "return", "merge_setting", "(", "request_hooks", ",", "session_hooks", ",", "dict_class", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/requests/sessions.py#L81-L93
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/vendor/distlib/locators.py
python
SimpleScrapingLocator.get_distribution_names
(self)
return result
Return all the distribution names known to this locator.
Return all the distribution names known to this locator.
[ "Return", "all", "the", "distribution", "names", "known", "to", "this", "locator", "." ]
def get_distribution_names(self): """ Return all the distribution names known to this locator. """ result = set() page = self.get_page(self.base_url) if not page: raise DistlibException('Unable to get %s' % self.base_url) for match in self._distname_re.finditer(page.data): result.add(match.group(1)) return result
[ "def", "get_distribution_names", "(", "self", ")", ":", "result", "=", "set", "(", ")", "page", "=", "self", ".", "get_page", "(", "self", ".", "base_url", ")", "if", "not", "page", ":", "raise", "DistlibException", "(", "'Unable to get %s'", "%", "self", ".", "base_url", ")", "for", "match", "in", "self", ".", "_distname_re", ".", "finditer", "(", "page", ".", "data", ")", ":", "result", ".", "add", "(", "match", ".", "group", "(", "1", ")", ")", "return", "result" ]
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/locators.py#L697-L707
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py
python
Canvas.select_to
(self, tagOrId, index)
Set the variable end of a selection in item TAGORID to INDEX.
Set the variable end of a selection in item TAGORID to INDEX.
[ "Set", "the", "variable", "end", "of", "a", "selection", "in", "item", "TAGORID", "to", "INDEX", "." ]
def select_to(self, tagOrId, index): """Set the variable end of a selection in item TAGORID to INDEX.""" self.tk.call(self._w, 'select', 'to', tagOrId, index)
[ "def", "select_to", "(", "self", ",", "tagOrId", ",", "index", ")", ":", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "'select'", ",", "'to'", ",", "tagOrId", ",", "index", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py#L2398-L2400
grpc/grpc
27bc6fe7797e43298dc931b96dc57322d0852a9f
src/python/grpcio/grpc/_channel.py
python
_MultiThreadedRendezvous.initial_metadata
(self)
See grpc.Call.initial_metadata
See grpc.Call.initial_metadata
[ "See", "grpc", ".", "Call", ".", "initial_metadata" ]
def initial_metadata(self): """See grpc.Call.initial_metadata""" with self._state.condition: def _done(): return self._state.initial_metadata is not None _common.wait(self._state.condition.wait, _done) return self._state.initial_metadata
[ "def", "initial_metadata", "(", "self", ")", ":", "with", "self", ".", "_state", ".", "condition", ":", "def", "_done", "(", ")", ":", "return", "self", ".", "_state", ".", "initial_metadata", "is", "not", "None", "_common", ".", "wait", "(", "self", ".", "_state", ".", "condition", ".", "wait", ",", "_done", ")", "return", "self", ".", "_state", ".", "initial_metadata" ]
https://github.com/grpc/grpc/blob/27bc6fe7797e43298dc931b96dc57322d0852a9f/src/python/grpcio/grpc/_channel.py#L663-L671
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/metrics/python/ops/metric_ops.py
python
streaming_recall_at_thresholds
(predictions, labels, thresholds, weights=None, metrics_collections=None, updates_collections=None, name=None)
return metrics.recall_at_thresholds( thresholds=thresholds, predictions=predictions, labels=labels, weights=weights, metrics_collections=metrics_collections, updates_collections=updates_collections, name=name)
Computes various recall values for different `thresholds` on `predictions`. The `streaming_recall_at_thresholds` function creates four local variables, `true_positives`, `true_negatives`, `false_positives` and `false_negatives` for various values of thresholds. `recall[i]` is defined as the total weight of values in `predictions` above `thresholds[i]` whose corresponding entry in `labels` is `True`, divided by the total weight of `True` values in `labels` (`true_positives[i] / (true_positives[i] + false_negatives[i])`). For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `recall`. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Args: predictions: A floating point `Tensor` of arbitrary shape and whose values are in the range `[0, 1]`. labels: A `bool` `Tensor` whose shape matches `predictions`. thresholds: A python list or tuple of float thresholds in `[0, 1]`. weights: `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). metrics_collections: An optional list of collections that `recall` should be added to. updates_collections: An optional list of collections that `update_op` should be added to. name: An optional variable_scope name. Returns: recall: A float `Tensor` of shape `[len(thresholds)]`. update_op: An operation that increments the `true_positives`, `true_negatives`, `false_positives` and `false_negatives` variables that are used in the computation of `recall`. Raises: ValueError: If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple.
Computes various recall values for different `thresholds` on `predictions`.
[ "Computes", "various", "recall", "values", "for", "different", "thresholds", "on", "predictions", "." ]
def streaming_recall_at_thresholds(predictions, labels, thresholds, weights=None, metrics_collections=None, updates_collections=None, name=None): """Computes various recall values for different `thresholds` on `predictions`. The `streaming_recall_at_thresholds` function creates four local variables, `true_positives`, `true_negatives`, `false_positives` and `false_negatives` for various values of thresholds. `recall[i]` is defined as the total weight of values in `predictions` above `thresholds[i]` whose corresponding entry in `labels` is `True`, divided by the total weight of `True` values in `labels` (`true_positives[i] / (true_positives[i] + false_negatives[i])`). For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `recall`. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Args: predictions: A floating point `Tensor` of arbitrary shape and whose values are in the range `[0, 1]`. labels: A `bool` `Tensor` whose shape matches `predictions`. thresholds: A python list or tuple of float thresholds in `[0, 1]`. weights: `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). metrics_collections: An optional list of collections that `recall` should be added to. updates_collections: An optional list of collections that `update_op` should be added to. name: An optional variable_scope name. Returns: recall: A float `Tensor` of shape `[len(thresholds)]`. update_op: An operation that increments the `true_positives`, `true_negatives`, `false_positives` and `false_negatives` variables that are used in the computation of `recall`. Raises: ValueError: If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ return metrics.recall_at_thresholds( thresholds=thresholds, predictions=predictions, labels=labels, weights=weights, metrics_collections=metrics_collections, updates_collections=updates_collections, name=name)
[ "def", "streaming_recall_at_thresholds", "(", "predictions", ",", "labels", ",", "thresholds", ",", "weights", "=", "None", ",", "metrics_collections", "=", "None", ",", "updates_collections", "=", "None", ",", "name", "=", "None", ")", ":", "return", "metrics", ".", "recall_at_thresholds", "(", "thresholds", "=", "thresholds", ",", "predictions", "=", "predictions", ",", "labels", "=", "labels", ",", "weights", "=", "weights", ",", "metrics_collections", "=", "metrics_collections", ",", "updates_collections", "=", "updates_collections", ",", "name", "=", "name", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/metrics/python/ops/metric_ops.py#L1569-L1623
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/py_vulcanize/third_party/rcssmin/_setup/py2/commands.py
python
InstallData.initialize_options
(self)
Prepare for new options
Prepare for new options
[ "Prepare", "for", "new", "options" ]
def initialize_options(self): """ Prepare for new options """ _install_data.install_data.initialize_options(self) if _option_defaults.has_key('install_data'): for opt_name, default in _option_defaults['install_data']: setattr(self, opt_name, default)
[ "def", "initialize_options", "(", "self", ")", ":", "_install_data", ".", "install_data", ".", "initialize_options", "(", "self", ")", "if", "_option_defaults", ".", "has_key", "(", "'install_data'", ")", ":", "for", "opt_name", ",", "default", "in", "_option_defaults", "[", "'install_data'", "]", ":", "setattr", "(", "self", ",", "opt_name", ",", "default", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/py_vulcanize/third_party/rcssmin/_setup/py2/commands.py#L131-L136
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/unsafe/ndarray.py
python
to_fixed_tuple
(typingctx, array, length)
return sig, codegen
Convert *array* into a tuple of *length* Returns ``UniTuple(array.dtype, length)`` ** Warning ** - No boundchecking. If *length* is longer than *array.size*, the behavior is undefined.
Convert *array* into a tuple of *length*
[ "Convert", "*", "array", "*", "into", "a", "tuple", "of", "*", "length", "*" ]
def to_fixed_tuple(typingctx, array, length): """Convert *array* into a tuple of *length* Returns ``UniTuple(array.dtype, length)`` ** Warning ** - No boundchecking. If *length* is longer than *array.size*, the behavior is undefined. """ if not isinstance(length, types.IntegerLiteral): raise RequireLiteralValue('*length* argument must be a constant') if array.ndim != 1: raise TypingError("Not supported on array.ndim={}".format(array.ndim)) # Determine types tuple_size = int(length.literal_value) tuple_type = types.UniTuple(dtype=array.dtype, count=tuple_size) sig = tuple_type(array, length) def codegen(context, builder, signature, args): def impl(array, length, empty_tuple): out = empty_tuple for i in range(length): out = tuple_setitem(out, i, array[i]) return out inner_argtypes = [signature.args[0], types.intp, tuple_type] inner_sig = typing.signature(tuple_type, *inner_argtypes) ll_idx_type = context.get_value_type(types.intp) # Allocate an empty tuple empty_tuple = context.get_constant_undef(tuple_type) inner_args = [args[0], ll_idx_type(tuple_size), empty_tuple] res = context.compile_internal(builder, impl, inner_sig, inner_args) return res return sig, codegen
[ "def", "to_fixed_tuple", "(", "typingctx", ",", "array", ",", "length", ")", ":", "if", "not", "isinstance", "(", "length", ",", "types", ".", "IntegerLiteral", ")", ":", "raise", "RequireLiteralValue", "(", "'*length* argument must be a constant'", ")", "if", "array", ".", "ndim", "!=", "1", ":", "raise", "TypingError", "(", "\"Not supported on array.ndim={}\"", ".", "format", "(", "array", ".", "ndim", ")", ")", "# Determine types", "tuple_size", "=", "int", "(", "length", ".", "literal_value", ")", "tuple_type", "=", "types", ".", "UniTuple", "(", "dtype", "=", "array", ".", "dtype", ",", "count", "=", "tuple_size", ")", "sig", "=", "tuple_type", "(", "array", ",", "length", ")", "def", "codegen", "(", "context", ",", "builder", ",", "signature", ",", "args", ")", ":", "def", "impl", "(", "array", ",", "length", ",", "empty_tuple", ")", ":", "out", "=", "empty_tuple", "for", "i", "in", "range", "(", "length", ")", ":", "out", "=", "tuple_setitem", "(", "out", ",", "i", ",", "array", "[", "i", "]", ")", "return", "out", "inner_argtypes", "=", "[", "signature", ".", "args", "[", "0", "]", ",", "types", ".", "intp", ",", "tuple_type", "]", "inner_sig", "=", "typing", ".", "signature", "(", "tuple_type", ",", "*", "inner_argtypes", ")", "ll_idx_type", "=", "context", ".", "get_value_type", "(", "types", ".", "intp", ")", "# Allocate an empty tuple", "empty_tuple", "=", "context", ".", "get_constant_undef", "(", "tuple_type", ")", "inner_args", "=", "[", "args", "[", "0", "]", ",", "ll_idx_type", "(", "tuple_size", ")", ",", "empty_tuple", "]", "res", "=", "context", ".", "compile_internal", "(", "builder", ",", "impl", ",", "inner_sig", ",", "inner_args", ")", "return", "res", "return", "sig", ",", "codegen" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/unsafe/ndarray.py#L43-L80
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/macresource.py
python
open_pathname
(pathname, verbose=0)
Open a resource file given by pathname, possibly decoding an AppleSingle file
Open a resource file given by pathname, possibly decoding an AppleSingle file
[ "Open", "a", "resource", "file", "given", "by", "pathname", "possibly", "decoding", "an", "AppleSingle", "file" ]
def open_pathname(pathname, verbose=0): """Open a resource file given by pathname, possibly decoding an AppleSingle file""" # No resource fork. We may be on OSX, and this may be either # a data-fork based resource file or a AppleSingle file # from the CVS repository. try: refno = Res.FSOpenResourceFile(pathname, u'', 1) except Res.Error, arg: if arg[0] != -199: # -199 is "bad resource map" raise else: return refno # Finally try decoding an AppleSingle file pathname = _decode(pathname, verbose=verbose) refno = Res.FSOpenResourceFile(pathname, u'', 1)
[ "def", "open_pathname", "(", "pathname", ",", "verbose", "=", "0", ")", ":", "# No resource fork. We may be on OSX, and this may be either", "# a data-fork based resource file or a AppleSingle file", "# from the CVS repository.", "try", ":", "refno", "=", "Res", ".", "FSOpenResourceFile", "(", "pathname", ",", "u''", ",", "1", ")", "except", "Res", ".", "Error", ",", "arg", ":", "if", "arg", "[", "0", "]", "!=", "-", "199", ":", "# -199 is \"bad resource map\"", "raise", "else", ":", "return", "refno", "# Finally try decoding an AppleSingle file", "pathname", "=", "_decode", "(", "pathname", ",", "verbose", "=", "verbose", ")", "refno", "=", "Res", ".", "FSOpenResourceFile", "(", "pathname", ",", "u''", ",", "1", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/macresource.py#L77-L93
trailofbits/llvm-sanitizer-tutorial
d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99
llvm/projects/compiler-rt/lib/sanitizer_common/scripts/litlint.py
python
LintLine
(s)
return (None, None)
Validate a line Args: s: str, the line to validate Returns: Returns an error message and a 1-based column number if an error was detected, otherwise (None, None).
Validate a line
[ "Validate", "a", "line" ]
def LintLine(s): """ Validate a line Args: s: str, the line to validate Returns: Returns an error message and a 1-based column number if an error was detected, otherwise (None, None). """ # Check that RUN command can be executed with an emulator m = runRegex.search(s) if m: start, end = m.span() return ('missing %run before %t', start + 2) # No errors return (None, None)
[ "def", "LintLine", "(", "s", ")", ":", "# Check that RUN command can be executed with an emulator", "m", "=", "runRegex", ".", "search", "(", "s", ")", "if", "m", ":", "start", ",", "end", "=", "m", ".", "span", "(", ")", "return", "(", "'missing %run before %t'", ",", "start", "+", "2", ")", "# No errors", "return", "(", "None", ",", "None", ")" ]
https://github.com/trailofbits/llvm-sanitizer-tutorial/blob/d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99/llvm/projects/compiler-rt/lib/sanitizer_common/scripts/litlint.py#L17-L35
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/training/coordinator.py
python
Coordinator.wait_for_stop
(self, timeout=None)
return self._stop_event.wait(timeout)
Wait till the Coordinator is told to stop. Args: timeout: Float. Sleep for up to that many seconds waiting for should_stop() to become True. Returns: True if the Coordinator is told stop, False if the timeout expired.
Wait till the Coordinator is told to stop.
[ "Wait", "till", "the", "Coordinator", "is", "told", "to", "stop", "." ]
def wait_for_stop(self, timeout=None): """Wait till the Coordinator is told to stop. Args: timeout: Float. Sleep for up to that many seconds waiting for should_stop() to become True. Returns: True if the Coordinator is told stop, False if the timeout expired. """ return self._stop_event.wait(timeout)
[ "def", "wait_for_stop", "(", "self", ",", "timeout", "=", "None", ")", ":", "return", "self", ".", "_stop_event", ".", "wait", "(", "timeout", ")" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/training/coordinator.py#L301-L311
nsnam/ns-3-dev-git
efdb2e21f45c0a87a60b47c547b68fa140a7b686
waf-tools/versioning.py
python
ns3_version_info._find_closest_tag
(self, ctx)
Override in derived classes
Override in derived classes
[ "Override", "in", "derived", "classes" ]
def _find_closest_tag(self, ctx): """Override in derived classes""" pass
[ "def", "_find_closest_tag", "(", "self", ",", "ctx", ")", ":", "pass" ]
https://github.com/nsnam/ns-3-dev-git/blob/efdb2e21f45c0a87a60b47c547b68fa140a7b686/waf-tools/versioning.py#L30-L32
vnpy/vnpy
f50f2535ed39dd33272e0985ed40c7078e4c19f6
vnpy/trader/utility.py
python
ArrayManager.rocr_100
(self, n: int, array: bool = False)
return result[-1]
ROCR100.
ROCR100.
[ "ROCR100", "." ]
def rocr_100(self, n: int, array: bool = False) -> Union[float, np.ndarray]: """ ROCR100. """ result = talib.ROCR100(self.close, n) if array: return result return result[-1]
[ "def", "rocr_100", "(", "self", ",", "n", ":", "int", ",", "array", ":", "bool", "=", "False", ")", "->", "Union", "[", "float", ",", "np", ".", "ndarray", "]", ":", "result", "=", "talib", ".", "ROCR100", "(", "self", ".", "close", ",", "n", ")", "if", "array", ":", "return", "result", "return", "result", "[", "-", "1", "]" ]
https://github.com/vnpy/vnpy/blob/f50f2535ed39dd33272e0985ed40c7078e4c19f6/vnpy/trader/utility.py#L640-L647
idaholab/moose
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
python/mooseutils/levenshtein.py
python
levenshtein
(s1, s2)
return previous_row[-1]
Python implementation of Levenshtein algorithm https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Python
Python implementation of Levenshtein algorithm https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Python
[ "Python", "implementation", "of", "Levenshtein", "algorithm", "https", ":", "//", "en", ".", "wikibooks", ".", "org", "/", "wiki", "/", "Algorithm_Implementation", "/", "Strings", "/", "Levenshtein_distance#Python" ]
def levenshtein(s1, s2): """ Python implementation of Levenshtein algorithm https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Python """ if len(s1) < len(s2): return levenshtein(s2, s1) # len(s1) >= len(s2) if len(s2) == 0: return len(s1) previous_row = range(len(s2) + 1) for i, c1 in enumerate(s1): current_row = [i + 1] for j, c2 in enumerate(s2): insertions = previous_row[j + 1] + 1 # j+1 instead of j since previous_row and current_row are one character longer deletions = current_row[j] + 1 # than s2 substitutions = previous_row[j] + (c1 != c2) current_row.append(min(insertions, deletions, substitutions)) previous_row = current_row return previous_row[-1]
[ "def", "levenshtein", "(", "s1", ",", "s2", ")", ":", "if", "len", "(", "s1", ")", "<", "len", "(", "s2", ")", ":", "return", "levenshtein", "(", "s2", ",", "s1", ")", "# len(s1) >= len(s2)", "if", "len", "(", "s2", ")", "==", "0", ":", "return", "len", "(", "s1", ")", "previous_row", "=", "range", "(", "len", "(", "s2", ")", "+", "1", ")", "for", "i", ",", "c1", "in", "enumerate", "(", "s1", ")", ":", "current_row", "=", "[", "i", "+", "1", "]", "for", "j", ",", "c2", "in", "enumerate", "(", "s2", ")", ":", "insertions", "=", "previous_row", "[", "j", "+", "1", "]", "+", "1", "# j+1 instead of j since previous_row and current_row are one character longer", "deletions", "=", "current_row", "[", "j", "]", "+", "1", "# than s2", "substitutions", "=", "previous_row", "[", "j", "]", "+", "(", "c1", "!=", "c2", ")", "current_row", ".", "append", "(", "min", "(", "insertions", ",", "deletions", ",", "substitutions", ")", ")", "previous_row", "=", "current_row", "return", "previous_row", "[", "-", "1", "]" ]
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/mooseutils/levenshtein.py#L30-L53
runtimejs/runtime
0a6e84c30823d35a4548d6634166784260ae7b74
deps/v8/gypfiles/landmine_utils.py
python
builder
()
Returns a string representing the build engine (not compiler) to use. Possible values: 'make', 'ninja', 'xcode', 'msvs', 'scons'
Returns a string representing the build engine (not compiler) to use. Possible values: 'make', 'ninja', 'xcode', 'msvs', 'scons'
[ "Returns", "a", "string", "representing", "the", "build", "engine", "(", "not", "compiler", ")", "to", "use", ".", "Possible", "values", ":", "make", "ninja", "xcode", "msvs", "scons" ]
def builder(): """ Returns a string representing the build engine (not compiler) to use. Possible values: 'make', 'ninja', 'xcode', 'msvs', 'scons' """ if 'GYP_GENERATORS' in os.environ: # for simplicity, only support the first explicit generator generator = os.environ['GYP_GENERATORS'].split(',')[0] if generator.endswith('-android'): return generator.split('-')[0] elif generator.endswith('-ninja'): return 'ninja' else: return generator else: if platform() == 'android': # Good enough for now? Do any android bots use make? return 'make' elif platform() == 'ios': return 'xcode' elif IsWindows(): return 'msvs' elif IsLinux(): return 'make' elif IsMac(): return 'xcode' else: assert False, 'Don\'t know what builder we\'re using!'
[ "def", "builder", "(", ")", ":", "if", "'GYP_GENERATORS'", "in", "os", ".", "environ", ":", "# for simplicity, only support the first explicit generator", "generator", "=", "os", ".", "environ", "[", "'GYP_GENERATORS'", "]", ".", "split", "(", "','", ")", "[", "0", "]", "if", "generator", ".", "endswith", "(", "'-android'", ")", ":", "return", "generator", ".", "split", "(", "'-'", ")", "[", "0", "]", "elif", "generator", ".", "endswith", "(", "'-ninja'", ")", ":", "return", "'ninja'", "else", ":", "return", "generator", "else", ":", "if", "platform", "(", ")", "==", "'android'", ":", "# Good enough for now? Do any android bots use make?", "return", "'make'", "elif", "platform", "(", ")", "==", "'ios'", ":", "return", "'xcode'", "elif", "IsWindows", "(", ")", ":", "return", "'msvs'", "elif", "IsLinux", "(", ")", ":", "return", "'make'", "elif", "IsMac", "(", ")", ":", "return", "'xcode'", "else", ":", "assert", "False", ",", "'Don\\'t know what builder we\\'re using!'" ]
https://github.com/runtimejs/runtime/blob/0a6e84c30823d35a4548d6634166784260ae7b74/deps/v8/gypfiles/landmine_utils.py#L96-L123
raymondlu/super-animation-samples
04234269112ff0dc32447f27a761dbbb00b8ba17
samples/cocos2d-x-3.1/CocosLuaGame2/frameworks/cocos2d-x/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py
python
Type.is_restrict_qualified
(self)
return conf.lib.clang_isRestrictQualifiedType(self)
Determine whether a Type has the "restrict" qualifier set. This does not look through typedefs that may have added "restrict" at a different level.
Determine whether a Type has the "restrict" qualifier set.
[ "Determine", "whether", "a", "Type", "has", "the", "restrict", "qualifier", "set", "." ]
def is_restrict_qualified(self): """Determine whether a Type has the "restrict" qualifier set. This does not look through typedefs that may have added "restrict" at a different level. """ return conf.lib.clang_isRestrictQualifiedType(self)
[ "def", "is_restrict_qualified", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_isRestrictQualifiedType", "(", "self", ")" ]
https://github.com/raymondlu/super-animation-samples/blob/04234269112ff0dc32447f27a761dbbb00b8ba17/samples/cocos2d-x-3.1/CocosLuaGame2/frameworks/cocos2d-x/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py#L1580-L1586
tinyobjloader/tinyobjloader
8322e00ae685ea623ab6ac5a6cebcfa2d22fbf93
deps/cpplint.py
python
GetTemplateArgs
(clean_lines, linenum)
return typenames
Find list of template arguments associated with this function declaration. Args: clean_lines: A CleansedLines instance containing the file. linenum: Line number containing the start of the function declaration, usually one line after the end of the template-argument-list. Returns: Set of type names, or empty set if this does not appear to have any template parameters.
Find list of template arguments associated with this function declaration.
[ "Find", "list", "of", "template", "arguments", "associated", "with", "this", "function", "declaration", "." ]
def GetTemplateArgs(clean_lines, linenum): """Find list of template arguments associated with this function declaration. Args: clean_lines: A CleansedLines instance containing the file. linenum: Line number containing the start of the function declaration, usually one line after the end of the template-argument-list. Returns: Set of type names, or empty set if this does not appear to have any template parameters. """ # Find start of function func_line = linenum while func_line > 0: line = clean_lines.elided[func_line] if Match(r'^\s*$', line): return set() if line.find('(') >= 0: break func_line -= 1 if func_line == 0: return set() # Collapse template-argument-list into a single string argument_list = '' match = Match(r'^(\s*template\s*)<', clean_lines.elided[func_line]) if match: # template-argument-list on the same line as function name start_col = len(match.group(1)) _, end_line, end_col = CloseExpression(clean_lines, func_line, start_col) if end_col > -1 and end_line == func_line: start_col += 1 # Skip the opening bracket argument_list = clean_lines.elided[func_line][start_col:end_col] elif func_line > 1: # template-argument-list one line before function name match = Match(r'^(.*)>\s*$', clean_lines.elided[func_line - 1]) if match: end_col = len(match.group(1)) _, start_line, start_col = ReverseCloseExpression( clean_lines, func_line - 1, end_col) if start_col > -1: start_col += 1 # Skip the opening bracket while start_line < func_line - 1: argument_list += clean_lines.elided[start_line][start_col:] start_col = 0 start_line += 1 argument_list += clean_lines.elided[func_line - 1][start_col:end_col] if not argument_list: return set() # Extract type names typenames = set() while True: match = Match(r'^[,\s]*(?:typename|class)(?:\.\.\.)?\s+(\w+)(.*)$', argument_list) if not match: break typenames.add(match.group(1)) argument_list = match.group(2) return typenames
[ "def", "GetTemplateArgs", "(", "clean_lines", ",", "linenum", ")", ":", "# Find start of function", "func_line", "=", "linenum", "while", "func_line", ">", "0", ":", "line", "=", "clean_lines", ".", "elided", "[", "func_line", "]", "if", "Match", "(", "r'^\\s*$'", ",", "line", ")", ":", "return", "set", "(", ")", "if", "line", ".", "find", "(", "'('", ")", ">=", "0", ":", "break", "func_line", "-=", "1", "if", "func_line", "==", "0", ":", "return", "set", "(", ")", "# Collapse template-argument-list into a single string", "argument_list", "=", "''", "match", "=", "Match", "(", "r'^(\\s*template\\s*)<'", ",", "clean_lines", ".", "elided", "[", "func_line", "]", ")", "if", "match", ":", "# template-argument-list on the same line as function name", "start_col", "=", "len", "(", "match", ".", "group", "(", "1", ")", ")", "_", ",", "end_line", ",", "end_col", "=", "CloseExpression", "(", "clean_lines", ",", "func_line", ",", "start_col", ")", "if", "end_col", ">", "-", "1", "and", "end_line", "==", "func_line", ":", "start_col", "+=", "1", "# Skip the opening bracket", "argument_list", "=", "clean_lines", ".", "elided", "[", "func_line", "]", "[", "start_col", ":", "end_col", "]", "elif", "func_line", ">", "1", ":", "# template-argument-list one line before function name", "match", "=", "Match", "(", "r'^(.*)>\\s*$'", ",", "clean_lines", ".", "elided", "[", "func_line", "-", "1", "]", ")", "if", "match", ":", "end_col", "=", "len", "(", "match", ".", "group", "(", "1", ")", ")", "_", ",", "start_line", ",", "start_col", "=", "ReverseCloseExpression", "(", "clean_lines", ",", "func_line", "-", "1", ",", "end_col", ")", "if", "start_col", ">", "-", "1", ":", "start_col", "+=", "1", "# Skip the opening bracket", "while", "start_line", "<", "func_line", "-", "1", ":", "argument_list", "+=", "clean_lines", ".", "elided", "[", "start_line", "]", "[", "start_col", ":", "]", "start_col", "=", "0", "start_line", "+=", "1", "argument_list", "+=", "clean_lines", ".", "elided", "[", "func_line", "-", "1", "]", "[", "start_col", ":", "end_col", "]", "if", "not", "argument_list", ":", "return", "set", "(", ")", "# Extract type names", "typenames", "=", "set", "(", ")", "while", "True", ":", "match", "=", "Match", "(", "r'^[,\\s]*(?:typename|class)(?:\\.\\.\\.)?\\s+(\\w+)(.*)$'", ",", "argument_list", ")", "if", "not", "match", ":", "break", "typenames", ".", "add", "(", "match", ".", "group", "(", "1", ")", ")", "argument_list", "=", "match", ".", "group", "(", "2", ")", "return", "typenames" ]
https://github.com/tinyobjloader/tinyobjloader/blob/8322e00ae685ea623ab6ac5a6cebcfa2d22fbf93/deps/cpplint.py#L3712-L3773
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/pydoc.py
python
HTMLDoc.markup
(self, text, escape=None, funcs={}, classes={}, methods={})
return join(results, '')
Mark up some plain text, given a context of symbols to look for. Each context dictionary maps object names to anchor names.
Mark up some plain text, given a context of symbols to look for. Each context dictionary maps object names to anchor names.
[ "Mark", "up", "some", "plain", "text", "given", "a", "context", "of", "symbols", "to", "look", "for", ".", "Each", "context", "dictionary", "maps", "object", "names", "to", "anchor", "names", "." ]
def markup(self, text, escape=None, funcs={}, classes={}, methods={}): """Mark up some plain text, given a context of symbols to look for. Each context dictionary maps object names to anchor names.""" escape = escape or self.escape results = [] here = 0 pattern = re.compile(r'\b((http|ftp)://\S+[\w/]|' r'RFC[- ]?(\d+)|' r'PEP[- ]?(\d+)|' r'(self\.)?(\w+))') while True: match = pattern.search(text, here) if not match: break start, end = match.span() results.append(escape(text[here:start])) all, scheme, rfc, pep, selfdot, name = match.groups() if scheme: url = escape(all).replace('"', '&quot;') results.append('<a href="%s">%s</a>' % (url, url)) elif rfc: url = 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc) results.append('<a href="%s">%s</a>' % (url, escape(all))) elif pep: url = 'http://www.python.org/dev/peps/pep-%04d/' % int(pep) results.append('<a href="%s">%s</a>' % (url, escape(all))) elif text[end:end+1] == '(': results.append(self.namelink(name, methods, funcs, classes)) elif selfdot: results.append('self.<strong>%s</strong>' % name) else: results.append(self.namelink(name, classes)) here = end results.append(escape(text[here:])) return join(results, '')
[ "def", "markup", "(", "self", ",", "text", ",", "escape", "=", "None", ",", "funcs", "=", "{", "}", ",", "classes", "=", "{", "}", ",", "methods", "=", "{", "}", ")", ":", "escape", "=", "escape", "or", "self", ".", "escape", "results", "=", "[", "]", "here", "=", "0", "pattern", "=", "re", ".", "compile", "(", "r'\\b((http|ftp)://\\S+[\\w/]|'", "r'RFC[- ]?(\\d+)|'", "r'PEP[- ]?(\\d+)|'", "r'(self\\.)?(\\w+))'", ")", "while", "True", ":", "match", "=", "pattern", ".", "search", "(", "text", ",", "here", ")", "if", "not", "match", ":", "break", "start", ",", "end", "=", "match", ".", "span", "(", ")", "results", ".", "append", "(", "escape", "(", "text", "[", "here", ":", "start", "]", ")", ")", "all", ",", "scheme", ",", "rfc", ",", "pep", ",", "selfdot", ",", "name", "=", "match", ".", "groups", "(", ")", "if", "scheme", ":", "url", "=", "escape", "(", "all", ")", ".", "replace", "(", "'\"'", ",", "'&quot;'", ")", "results", ".", "append", "(", "'<a href=\"%s\">%s</a>'", "%", "(", "url", ",", "url", ")", ")", "elif", "rfc", ":", "url", "=", "'http://www.rfc-editor.org/rfc/rfc%d.txt'", "%", "int", "(", "rfc", ")", "results", ".", "append", "(", "'<a href=\"%s\">%s</a>'", "%", "(", "url", ",", "escape", "(", "all", ")", ")", ")", "elif", "pep", ":", "url", "=", "'http://www.python.org/dev/peps/pep-%04d/'", "%", "int", "(", "pep", ")", "results", ".", "append", "(", "'<a href=\"%s\">%s</a>'", "%", "(", "url", ",", "escape", "(", "all", ")", ")", ")", "elif", "text", "[", "end", ":", "end", "+", "1", "]", "==", "'('", ":", "results", ".", "append", "(", "self", ".", "namelink", "(", "name", ",", "methods", ",", "funcs", ",", "classes", ")", ")", "elif", "selfdot", ":", "results", ".", "append", "(", "'self.<strong>%s</strong>'", "%", "name", ")", "else", ":", "results", ".", "append", "(", "self", ".", "namelink", "(", "name", ",", "classes", ")", ")", "here", "=", "end", "results", ".", "append", "(", "escape", "(", "text", "[", "here", ":", "]", ")", ")", "return", "join", "(", "results", ",", "''", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/pydoc.py#L526-L560
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib2to3/pgen2/conv.py
python
Converter.finish_off
(self)
Create additional useful structures. (Internal).
Create additional useful structures. (Internal).
[ "Create", "additional", "useful", "structures", ".", "(", "Internal", ")", "." ]
def finish_off(self): """Create additional useful structures. (Internal).""" self.keywords = {} # map from keyword strings to arc labels self.tokens = {} # map from numeric token values to arc labels for ilabel, (type, value) in enumerate(self.labels): if type == token.NAME and value is not None: self.keywords[value] = ilabel elif value is None: self.tokens[type] = ilabel
[ "def", "finish_off", "(", "self", ")", ":", "self", ".", "keywords", "=", "{", "}", "# map from keyword strings to arc labels", "self", ".", "tokens", "=", "{", "}", "# map from numeric token values to arc labels", "for", "ilabel", ",", "(", "type", ",", "value", ")", "in", "enumerate", "(", "self", ".", "labels", ")", ":", "if", "type", "==", "token", ".", "NAME", "and", "value", "is", "not", "None", ":", "self", ".", "keywords", "[", "value", "]", "=", "ilabel", "elif", "value", "is", "None", ":", "self", ".", "tokens", "[", "type", "]", "=", "ilabel" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib2to3/pgen2/conv.py#L249-L257
SFTtech/openage
d6a08c53c48dc1e157807471df92197f6ca9e04d
openage/convert/entity_object/conversion/combined_sprite.py
python
CombinedSprite.add_metadata
(self, metadata)
Add a metadata file to the sprite.
Add a metadata file to the sprite.
[ "Add", "a", "metadata", "file", "to", "the", "sprite", "." ]
def add_metadata(self, metadata): """ Add a metadata file to the sprite. """ self.metadata = metadata
[ "def", "add_metadata", "(", "self", ",", "metadata", ")", ":", "self", ".", "metadata", "=", "metadata" ]
https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/convert/entity_object/conversion/combined_sprite.py#L49-L53
psi4/psi4
be533f7f426b6ccc263904e55122899b16663395
psi4/driver/qcdb/libmintsmolecule.py
python
LibmintsMolecule.print_dihedrals
(self)
return text
Print the geometrical parameters (dihedrals) of the molecule. >>> print(H2OH2O.print_dihedrals()) Dihedral Angles (Degrees) Dihedral 1-2-3-4: 180.000 Dihedral 1-2-3-5: 133.511 Dihedral 1-2-3-6: 133.511 ...
Print the geometrical parameters (dihedrals) of the molecule.
[ "Print", "the", "geometrical", "parameters", "(", "dihedrals", ")", "of", "the", "molecule", "." ]
def print_dihedrals(self): """Print the geometrical parameters (dihedrals) of the molecule. >>> print(H2OH2O.print_dihedrals()) Dihedral Angles (Degrees) Dihedral 1-2-3-4: 180.000 Dihedral 1-2-3-5: 133.511 Dihedral 1-2-3-6: 133.511 ... """ text = " Dihedral Angles (Degrees)\n\n" for i in range(self.natom()): for j in range(self.natom()): if i == j: continue for k in range(self.natom()): if i == k or j == k: continue for l in range(self.natom()): if i == l or j == l or k == l: continue eij = sub(self.xyz(j), self.xyz(i)) eij = normalize(eij) ejk = sub(self.xyz(k), self.xyz(j)) ejk = normalize(ejk) ekl = sub(self.xyz(l), self.xyz(k)) ekl = normalize(ekl) # Compute angle ijk angleijk = math.acos(dot(scale(eij, -1.0), ejk)) # Compute angle jkl anglejkl = math.acos(dot(scale(ejk, -1.0), ekl)) # compute term1 (eij x ejk) term1 = cross(eij, ejk) # compute term2 (ejk x ekl) term2 = cross(ejk, ekl) numerator = dot(term1, term2) denominator = math.sin(angleijk) * math.sin(anglejkl) try: costau = numerator / denominator except ZeroDivisionError: costau = 0.0 if costau > 1.00 and costau < 1.000001: costau = 1.00 if costau < -1.00 and costau > -1.000001: costau = -1.00 tau = 180.0 * math.acos(costau) / math.pi text += " Dihedral %d-%d-%d-%d: %8.3lf\n" % (i + 1, j + 1, k + 1, l + 1, tau) text += "\n\n" return text
[ "def", "print_dihedrals", "(", "self", ")", ":", "text", "=", "\" Dihedral Angles (Degrees)\\n\\n\"", "for", "i", "in", "range", "(", "self", ".", "natom", "(", ")", ")", ":", "for", "j", "in", "range", "(", "self", ".", "natom", "(", ")", ")", ":", "if", "i", "==", "j", ":", "continue", "for", "k", "in", "range", "(", "self", ".", "natom", "(", ")", ")", ":", "if", "i", "==", "k", "or", "j", "==", "k", ":", "continue", "for", "l", "in", "range", "(", "self", ".", "natom", "(", ")", ")", ":", "if", "i", "==", "l", "or", "j", "==", "l", "or", "k", "==", "l", ":", "continue", "eij", "=", "sub", "(", "self", ".", "xyz", "(", "j", ")", ",", "self", ".", "xyz", "(", "i", ")", ")", "eij", "=", "normalize", "(", "eij", ")", "ejk", "=", "sub", "(", "self", ".", "xyz", "(", "k", ")", ",", "self", ".", "xyz", "(", "j", ")", ")", "ejk", "=", "normalize", "(", "ejk", ")", "ekl", "=", "sub", "(", "self", ".", "xyz", "(", "l", ")", ",", "self", ".", "xyz", "(", "k", ")", ")", "ekl", "=", "normalize", "(", "ekl", ")", "# Compute angle ijk", "angleijk", "=", "math", ".", "acos", "(", "dot", "(", "scale", "(", "eij", ",", "-", "1.0", ")", ",", "ejk", ")", ")", "# Compute angle jkl", "anglejkl", "=", "math", ".", "acos", "(", "dot", "(", "scale", "(", "ejk", ",", "-", "1.0", ")", ",", "ekl", ")", ")", "# compute term1 (eij x ejk)", "term1", "=", "cross", "(", "eij", ",", "ejk", ")", "# compute term2 (ejk x ekl)", "term2", "=", "cross", "(", "ejk", ",", "ekl", ")", "numerator", "=", "dot", "(", "term1", ",", "term2", ")", "denominator", "=", "math", ".", "sin", "(", "angleijk", ")", "*", "math", ".", "sin", "(", "anglejkl", ")", "try", ":", "costau", "=", "numerator", "/", "denominator", "except", "ZeroDivisionError", ":", "costau", "=", "0.0", "if", "costau", ">", "1.00", "and", "costau", "<", "1.000001", ":", "costau", "=", "1.00", "if", "costau", "<", "-", "1.00", "and", "costau", ">", "-", "1.000001", ":", "costau", "=", "-", "1.00", "tau", "=", "180.0", "*", "math", ".", "acos", "(", "costau", ")", "/", "math", ".", "pi", "text", "+=", "\" Dihedral %d-%d-%d-%d: %8.3lf\\n\"", "%", "(", "i", "+", "1", ",", "j", "+", "1", ",", "k", "+", "1", ",", "l", "+", "1", ",", "tau", ")", "text", "+=", "\"\\n\\n\"", "return", "text" ]
https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/qcdb/libmintsmolecule.py#L1374-L1423
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/html.py
python
HtmlWinParser.GetFontBold
(*args, **kwargs)
return _html.HtmlWinParser_GetFontBold(*args, **kwargs)
GetFontBold(self) -> int
GetFontBold(self) -> int
[ "GetFontBold", "(", "self", ")", "-", ">", "int" ]
def GetFontBold(*args, **kwargs): """GetFontBold(self) -> int""" return _html.HtmlWinParser_GetFontBold(*args, **kwargs)
[ "def", "GetFontBold", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_html", ".", "HtmlWinParser_GetFontBold", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/html.py#L300-L302
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/fractions.py
python
Fraction._richcmp
(self, other, op)
Helper for comparison operators, for internal use only. Implement comparison between a Rational instance `self`, and either another Rational instance or a float `other`. If `other` is not a Rational instance or a float, return NotImplemented. `op` should be one of the six standard comparison operators.
Helper for comparison operators, for internal use only.
[ "Helper", "for", "comparison", "operators", "for", "internal", "use", "only", "." ]
def _richcmp(self, other, op): """Helper for comparison operators, for internal use only. Implement comparison between a Rational instance `self`, and either another Rational instance or a float `other`. If `other` is not a Rational instance or a float, return NotImplemented. `op` should be one of the six standard comparison operators. """ # convert other to a Rational instance where reasonable. if isinstance(other, numbers.Rational): return op(self._numerator * other.denominator, self._denominator * other.numerator) if isinstance(other, float): if math.isnan(other) or math.isinf(other): return op(0.0, other) else: return op(self, self.from_float(other)) else: return NotImplemented
[ "def", "_richcmp", "(", "self", ",", "other", ",", "op", ")", ":", "# convert other to a Rational instance where reasonable.", "if", "isinstance", "(", "other", ",", "numbers", ".", "Rational", ")", ":", "return", "op", "(", "self", ".", "_numerator", "*", "other", ".", "denominator", ",", "self", ".", "_denominator", "*", "other", ".", "numerator", ")", "if", "isinstance", "(", "other", ",", "float", ")", ":", "if", "math", ".", "isnan", "(", "other", ")", "or", "math", ".", "isinf", "(", "other", ")", ":", "return", "op", "(", "0.0", ",", "other", ")", "else", ":", "return", "op", "(", "self", ",", "self", ".", "from_float", "(", "other", ")", ")", "else", ":", "return", "NotImplemented" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/fractions.py#L588-L608
baidu/AnyQ
d94d450d2aaa5f7ed73424b10aa4539835b97527
tools/simnet/train/paddle/layers/paddle_layers.py
python
CosSimLayer.ops
(self, x, y)
return sim
operation
operation
[ "operation" ]
def ops(self, x, y): """ operation """ sim = fluid.layers.cos_sim(x, y) return sim
[ "def", "ops", "(", "self", ",", "x", ",", "y", ")", ":", "sim", "=", "fluid", ".", "layers", ".", "cos_sim", "(", "x", ",", "y", ")", "return", "sim" ]
https://github.com/baidu/AnyQ/blob/d94d450d2aaa5f7ed73424b10aa4539835b97527/tools/simnet/train/paddle/layers/paddle_layers.py#L275-L280
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/pkgutil.py
python
find_loader
(fullname)
return None
Find a PEP 302 "loader" object for fullname If fullname contains dots, path must be the containing package's __path__. Returns None if the module cannot be found or imported. This function uses iter_importers(), and is thus subject to the same limitations regarding platform-specific special import locations such as the Windows registry.
Find a PEP 302 "loader" object for fullname
[ "Find", "a", "PEP", "302", "loader", "object", "for", "fullname" ]
def find_loader(fullname): """Find a PEP 302 "loader" object for fullname If fullname contains dots, path must be the containing package's __path__. Returns None if the module cannot be found or imported. This function uses iter_importers(), and is thus subject to the same limitations regarding platform-specific special import locations such as the Windows registry. """ for importer in iter_importers(fullname): loader = importer.find_module(fullname) if loader is not None: return loader return None
[ "def", "find_loader", "(", "fullname", ")", ":", "for", "importer", "in", "iter_importers", "(", "fullname", ")", ":", "loader", "=", "importer", ".", "find_module", "(", "fullname", ")", "if", "loader", "is", "not", "None", ":", "return", "loader", "return", "None" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/pkgutil.py#L458-L471
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/imaplib.py
python
IMAP4.authenticate
(self, mechanism, authobject)
return typ, dat
Authenticate command - requires response processing. 'mechanism' specifies which authentication mechanism is to be used - it must appear in <instance>.capabilities in the form AUTH=<mechanism>. 'authobject' must be a callable object: data = authobject(response) It will be called to process server continuation responses; the response argument it is passed will be a bytes. It should return bytes data that will be base64 encoded and sent to the server. It should return None if the client abort response '*' should be sent instead.
Authenticate command - requires response processing.
[ "Authenticate", "command", "-", "requires", "response", "processing", "." ]
def authenticate(self, mechanism, authobject): """Authenticate command - requires response processing. 'mechanism' specifies which authentication mechanism is to be used - it must appear in <instance>.capabilities in the form AUTH=<mechanism>. 'authobject' must be a callable object: data = authobject(response) It will be called to process server continuation responses; the response argument it is passed will be a bytes. It should return bytes data that will be base64 encoded and sent to the server. It should return None if the client abort response '*' should be sent instead. """ mech = mechanism.upper() # XXX: shouldn't this code be removed, not commented out? #cap = 'AUTH=%s' % mech #if not cap in self.capabilities: # Let the server decide! # raise self.error("Server doesn't allow %s authentication." % mech) self.literal = _Authenticator(authobject).process typ, dat = self._simple_command('AUTHENTICATE', mech) if typ != 'OK': raise self.error(dat[-1].decode('utf-8', 'replace')) self.state = 'AUTH' return typ, dat
[ "def", "authenticate", "(", "self", ",", "mechanism", ",", "authobject", ")", ":", "mech", "=", "mechanism", ".", "upper", "(", ")", "# XXX: shouldn't this code be removed, not commented out?", "#cap = 'AUTH=%s' % mech", "#if not cap in self.capabilities: # Let the server decide!", "# raise self.error(\"Server doesn't allow %s authentication.\" % mech)", "self", ".", "literal", "=", "_Authenticator", "(", "authobject", ")", ".", "process", "typ", ",", "dat", "=", "self", ".", "_simple_command", "(", "'AUTHENTICATE'", ",", "mech", ")", "if", "typ", "!=", "'OK'", ":", "raise", "self", ".", "error", "(", "dat", "[", "-", "1", "]", ".", "decode", "(", "'utf-8'", ",", "'replace'", ")", ")", "self", ".", "state", "=", "'AUTH'", "return", "typ", ",", "dat" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/imaplib.py#L420-L446
nasa/fprime
595cf3682d8365943d86c1a6fe7c78f0a116acf0
Autocoders/Python/bin/tlm_packet_gen.py
python
main
()
Main program.
Main program.
[ "Main", "program", "." ]
def main(): """ Main program. """ global VERBOSE # prevent local creation of variable global BUILD_ROOT # environmental variable if set Parser = pinit() (opt, args) = Parser.parse_args() # opt.verbose_flag = True # # Parse the input Topology XML filename # if len(args) == 0: print("Usage: %s [options] xml_filename" % sys.argv[0]) return elif len(args) == 1: xml_filename = args[0] else: print("ERROR: Too many filenames, should only have one") return print("Processing packet file %s" % xml_filename) set_build_roots(os.environ.get("BUILD_ROOT")) packet_parser = TlmPacketParser(opt.verbose_flag, opt.dependency_file) try: packet_parser.gen_packet_file(xml_filename) except TlmPacketParseValueError as e: print("Packet XML parsing error: %s" % e) sys.exit(-1) except TlmPacketParseIOError as e: print("Packet XML file error: %s" % e) sys.exit(-1) sys.exit(0)
[ "def", "main", "(", ")", ":", "global", "VERBOSE", "# prevent local creation of variable", "global", "BUILD_ROOT", "# environmental variable if set", "Parser", "=", "pinit", "(", ")", "(", "opt", ",", "args", ")", "=", "Parser", ".", "parse_args", "(", ")", "# opt.verbose_flag = True", "#", "# Parse the input Topology XML filename", "#", "if", "len", "(", "args", ")", "==", "0", ":", "print", "(", "\"Usage: %s [options] xml_filename\"", "%", "sys", ".", "argv", "[", "0", "]", ")", "return", "elif", "len", "(", "args", ")", "==", "1", ":", "xml_filename", "=", "args", "[", "0", "]", "else", ":", "print", "(", "\"ERROR: Too many filenames, should only have one\"", ")", "return", "print", "(", "\"Processing packet file %s\"", "%", "xml_filename", ")", "set_build_roots", "(", "os", ".", "environ", ".", "get", "(", "\"BUILD_ROOT\"", ")", ")", "packet_parser", "=", "TlmPacketParser", "(", "opt", ".", "verbose_flag", ",", "opt", ".", "dependency_file", ")", "try", ":", "packet_parser", ".", "gen_packet_file", "(", "xml_filename", ")", "except", "TlmPacketParseValueError", "as", "e", ":", "print", "(", "\"Packet XML parsing error: %s\"", "%", "e", ")", "sys", ".", "exit", "(", "-", "1", ")", "except", "TlmPacketParseIOError", "as", "e", ":", "print", "(", "\"Packet XML file error: %s\"", "%", "e", ")", "sys", ".", "exit", "(", "-", "1", ")", "sys", ".", "exit", "(", "0", ")" ]
https://github.com/nasa/fprime/blob/595cf3682d8365943d86c1a6fe7c78f0a116acf0/Autocoders/Python/bin/tlm_packet_gen.py#L600-L636
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/idl/idl/errors.py
python
ParserErrorCollection.__str__
(self)
return ', '.join(self.to_list())
Return a list of errors.
Return a list of errors.
[ "Return", "a", "list", "of", "errors", "." ]
def __str__(self): # type: () -> str """Return a list of errors.""" return ', '.join(self.to_list())
[ "def", "__str__", "(", "self", ")", ":", "# type: () -> str", "return", "', '", ".", "join", "(", "self", ".", "to_list", "(", ")", ")" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/idl/idl/errors.py#L214-L217
SoarGroup/Soar
a1c5e249499137a27da60533c72969eef3b8ab6b
scons/scons-local-4.1.0/SCons/Environment.py
python
SubstitutionEnvironment.has_key
(self, key)
return key in self._dict
Emulates the has_key() method of dictionaries.
Emulates the has_key() method of dictionaries.
[ "Emulates", "the", "has_key", "()", "method", "of", "dictionaries", "." ]
def has_key(self, key): """Emulates the has_key() method of dictionaries.""" return key in self._dict
[ "def", "has_key", "(", "self", ",", "key", ")", ":", "return", "key", "in", "self", ".", "_dict" ]
https://github.com/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-local-4.1.0/SCons/Environment.py#L418-L420
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_controls.py
python
ListCtrl.SetItemText
(*args, **kwargs)
return _controls_.ListCtrl_SetItemText(*args, **kwargs)
SetItemText(self, long item, String str)
SetItemText(self, long item, String str)
[ "SetItemText", "(", "self", "long", "item", "String", "str", ")" ]
def SetItemText(*args, **kwargs): """SetItemText(self, long item, String str)""" return _controls_.ListCtrl_SetItemText(*args, **kwargs)
[ "def", "SetItemText", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "ListCtrl_SetItemText", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L4543-L4545
lightvector/KataGo
20d34784703c5b4000643d3ccc43bb37d418f3b5
python/sgfmill/sgf.py
python
Tree_node.find
(self, identifier)
return None
Find the nearest ancestor-or-self containing the specified property. Returns a Tree_node, or None if there is no such node.
Find the nearest ancestor-or-self containing the specified property.
[ "Find", "the", "nearest", "ancestor", "-", "or", "-", "self", "containing", "the", "specified", "property", "." ]
def find(self, identifier): """Find the nearest ancestor-or-self containing the specified property. Returns a Tree_node, or None if there is no such node. """ node = self while node is not None: if node.has_property(identifier): return node node = node.parent return None
[ "def", "find", "(", "self", ",", "identifier", ")", ":", "node", "=", "self", "while", "node", "is", "not", "None", ":", "if", "node", ".", "has_property", "(", "identifier", ")", ":", "return", "node", "node", "=", "node", ".", "parent", "return", "None" ]
https://github.com/lightvector/KataGo/blob/20d34784703c5b4000643d3ccc43bb37d418f3b5/python/sgfmill/sgf.py#L417-L428
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/core/_asarray.py
python
require
(a, dtype=None, requirements=None)
return arr
Return an ndarray of the provided type that satisfies requirements. This function is useful to be sure that an array with the correct flags is returned for passing to compiled code (perhaps through ctypes). Parameters ---------- a : array_like The object to be converted to a type-and-requirement-satisfying array. dtype : data-type The required data-type. If None preserve the current dtype. If your application requires the data to be in native byteorder, include a byteorder specification as a part of the dtype specification. requirements : str or list of str The requirements list can be any of the following * 'F_CONTIGUOUS' ('F') - ensure a Fortran-contiguous array * 'C_CONTIGUOUS' ('C') - ensure a C-contiguous array * 'ALIGNED' ('A') - ensure a data-type aligned array * 'WRITEABLE' ('W') - ensure a writable array * 'OWNDATA' ('O') - ensure an array that owns its own data * 'ENSUREARRAY', ('E') - ensure a base array, instead of a subclass Returns ------- out : ndarray Array with specified requirements and type if given. See Also -------- asarray : Convert input to an ndarray. asanyarray : Convert to an ndarray, but pass through ndarray subclasses. ascontiguousarray : Convert input to a contiguous array. asfortranarray : Convert input to an ndarray with column-major memory order. ndarray.flags : Information about the memory layout of the array. Notes ----- The returned array will be guaranteed to have the listed requirements by making a copy if needed. Examples -------- >>> x = np.arange(6).reshape(2,3) >>> x.flags C_CONTIGUOUS : True F_CONTIGUOUS : False OWNDATA : False WRITEABLE : True ALIGNED : True WRITEBACKIFCOPY : False UPDATEIFCOPY : False >>> y = np.require(x, dtype=np.float32, requirements=['A', 'O', 'W', 'F']) >>> y.flags C_CONTIGUOUS : False F_CONTIGUOUS : True OWNDATA : True WRITEABLE : True ALIGNED : True WRITEBACKIFCOPY : False UPDATEIFCOPY : False
Return an ndarray of the provided type that satisfies requirements.
[ "Return", "an", "ndarray", "of", "the", "provided", "type", "that", "satisfies", "requirements", "." ]
def require(a, dtype=None, requirements=None): """ Return an ndarray of the provided type that satisfies requirements. This function is useful to be sure that an array with the correct flags is returned for passing to compiled code (perhaps through ctypes). Parameters ---------- a : array_like The object to be converted to a type-and-requirement-satisfying array. dtype : data-type The required data-type. If None preserve the current dtype. If your application requires the data to be in native byteorder, include a byteorder specification as a part of the dtype specification. requirements : str or list of str The requirements list can be any of the following * 'F_CONTIGUOUS' ('F') - ensure a Fortran-contiguous array * 'C_CONTIGUOUS' ('C') - ensure a C-contiguous array * 'ALIGNED' ('A') - ensure a data-type aligned array * 'WRITEABLE' ('W') - ensure a writable array * 'OWNDATA' ('O') - ensure an array that owns its own data * 'ENSUREARRAY', ('E') - ensure a base array, instead of a subclass Returns ------- out : ndarray Array with specified requirements and type if given. See Also -------- asarray : Convert input to an ndarray. asanyarray : Convert to an ndarray, but pass through ndarray subclasses. ascontiguousarray : Convert input to a contiguous array. asfortranarray : Convert input to an ndarray with column-major memory order. ndarray.flags : Information about the memory layout of the array. Notes ----- The returned array will be guaranteed to have the listed requirements by making a copy if needed. Examples -------- >>> x = np.arange(6).reshape(2,3) >>> x.flags C_CONTIGUOUS : True F_CONTIGUOUS : False OWNDATA : False WRITEABLE : True ALIGNED : True WRITEBACKIFCOPY : False UPDATEIFCOPY : False >>> y = np.require(x, dtype=np.float32, requirements=['A', 'O', 'W', 'F']) >>> y.flags C_CONTIGUOUS : False F_CONTIGUOUS : True OWNDATA : True WRITEABLE : True ALIGNED : True WRITEBACKIFCOPY : False UPDATEIFCOPY : False """ possible_flags = {'C': 'C', 'C_CONTIGUOUS': 'C', 'CONTIGUOUS': 'C', 'F': 'F', 'F_CONTIGUOUS': 'F', 'FORTRAN': 'F', 'A': 'A', 'ALIGNED': 'A', 'W': 'W', 'WRITEABLE': 'W', 'O': 'O', 'OWNDATA': 'O', 'E': 'E', 'ENSUREARRAY': 'E'} if not requirements: return asanyarray(a, dtype=dtype) else: requirements = {possible_flags[x.upper()] for x in requirements} if 'E' in requirements: requirements.remove('E') subok = False else: subok = True order = 'A' if requirements >= {'C', 'F'}: raise ValueError('Cannot specify both "C" and "F" order') elif 'F' in requirements: order = 'F' requirements.remove('F') elif 'C' in requirements: order = 'C' requirements.remove('C') arr = array(a, dtype=dtype, order=order, copy=False, subok=subok) for prop in requirements: if not arr.flags[prop]: arr = arr.copy(order) break return arr
[ "def", "require", "(", "a", ",", "dtype", "=", "None", ",", "requirements", "=", "None", ")", ":", "possible_flags", "=", "{", "'C'", ":", "'C'", ",", "'C_CONTIGUOUS'", ":", "'C'", ",", "'CONTIGUOUS'", ":", "'C'", ",", "'F'", ":", "'F'", ",", "'F_CONTIGUOUS'", ":", "'F'", ",", "'FORTRAN'", ":", "'F'", ",", "'A'", ":", "'A'", ",", "'ALIGNED'", ":", "'A'", ",", "'W'", ":", "'W'", ",", "'WRITEABLE'", ":", "'W'", ",", "'O'", ":", "'O'", ",", "'OWNDATA'", ":", "'O'", ",", "'E'", ":", "'E'", ",", "'ENSUREARRAY'", ":", "'E'", "}", "if", "not", "requirements", ":", "return", "asanyarray", "(", "a", ",", "dtype", "=", "dtype", ")", "else", ":", "requirements", "=", "{", "possible_flags", "[", "x", ".", "upper", "(", ")", "]", "for", "x", "in", "requirements", "}", "if", "'E'", "in", "requirements", ":", "requirements", ".", "remove", "(", "'E'", ")", "subok", "=", "False", "else", ":", "subok", "=", "True", "order", "=", "'A'", "if", "requirements", ">=", "{", "'C'", ",", "'F'", "}", ":", "raise", "ValueError", "(", "'Cannot specify both \"C\" and \"F\" order'", ")", "elif", "'F'", "in", "requirements", ":", "order", "=", "'F'", "requirements", ".", "remove", "(", "'F'", ")", "elif", "'C'", "in", "requirements", ":", "order", "=", "'C'", "requirements", ".", "remove", "(", "'C'", ")", "arr", "=", "array", "(", "a", ",", "dtype", "=", "dtype", ",", "order", "=", "order", ",", "copy", "=", "False", ",", "subok", "=", "subok", ")", "for", "prop", "in", "requirements", ":", "if", "not", "arr", ".", "flags", "[", "prop", "]", ":", "arr", "=", "arr", ".", "copy", "(", "order", ")", "break", "return", "arr" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/core/_asarray.py#L224-L324
beefytech/Beef
d6a447f9159c3b387e0e4d95cfd59ad3bf5bf017
BeefySysLib/third_party/freetype/src/tools/docmaker/sources.py
python
SourceProcessor.dump
( self )
Print all blocks in a processor.
Print all blocks in a processor.
[ "Print", "all", "blocks", "in", "a", "processor", "." ]
def dump( self ): """Print all blocks in a processor.""" for b in self.blocks: b.dump()
[ "def", "dump", "(", "self", ")", ":", "for", "b", "in", "self", ".", "blocks", ":", "b", ".", "dump", "(", ")" ]
https://github.com/beefytech/Beef/blob/d6a447f9159c3b387e0e4d95cfd59ad3bf5bf017/BeefySysLib/third_party/freetype/src/tools/docmaker/sources.py#L405-L408
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReflectometryISISLoadAndProcess.py
python
ReflectometryISISLoadAndProcess._prefixedName
(self, name, isTrans)
Add a prefix for TOF workspaces onto the given name
Add a prefix for TOF workspaces onto the given name
[ "Add", "a", "prefix", "for", "TOF", "workspaces", "onto", "the", "given", "name" ]
def _prefixedName(self, name, isTrans): """Add a prefix for TOF workspaces onto the given name""" if isTrans: return self._transPrefix + name else: return self._tofPrefix + name
[ "def", "_prefixedName", "(", "self", ",", "name", ",", "isTrans", ")", ":", "if", "isTrans", ":", "return", "self", ".", "_transPrefix", "+", "name", "else", ":", "return", "self", ".", "_tofPrefix", "+", "name" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReflectometryISISLoadAndProcess.py#L220-L225
apache/singa
93fd9da72694e68bfe3fb29d0183a65263d238a1
python/singa/autograd.py
python
nonzero
(x)
return NonZero()(x)[0]
Init a NonZero, Constructs a tensor by tiling a given tensor. This is the same as function tile in Numpy: https://docs.scipy.org/doc/numpy/reference/generated/numpy.tile.html Args: x (Tensor): input tensor. Returns: the output Tensor.
Init a NonZero, Constructs a tensor by tiling a given tensor. This is the same as function tile in Numpy: https://docs.scipy.org/doc/numpy/reference/generated/numpy.tile.html Args: x (Tensor): input tensor. Returns: the output Tensor.
[ "Init", "a", "NonZero", "Constructs", "a", "tensor", "by", "tiling", "a", "given", "tensor", ".", "This", "is", "the", "same", "as", "function", "tile", "in", "Numpy", ":", "https", ":", "//", "docs", ".", "scipy", ".", "org", "/", "doc", "/", "numpy", "/", "reference", "/", "generated", "/", "numpy", ".", "tile", ".", "html", "Args", ":", "x", "(", "Tensor", ")", ":", "input", "tensor", ".", "Returns", ":", "the", "output", "Tensor", "." ]
def nonzero(x): """ Init a NonZero, Constructs a tensor by tiling a given tensor. This is the same as function tile in Numpy: https://docs.scipy.org/doc/numpy/reference/generated/numpy.tile.html Args: x (Tensor): input tensor. Returns: the output Tensor. """ return NonZero()(x)[0]
[ "def", "nonzero", "(", "x", ")", ":", "return", "NonZero", "(", ")", "(", "x", ")", "[", "0", "]" ]
https://github.com/apache/singa/blob/93fd9da72694e68bfe3fb29d0183a65263d238a1/python/singa/autograd.py#L4663-L4672
gimli-org/gimli
17aa2160de9b15ababd9ef99e89b1bc3277bbb23
pygimli/viewer/mpl/utils.py
python
plotLines
(ax, line_filename, linewidth=1.0, step=1)
Read lines from file and plot over model.
Read lines from file and plot over model.
[ "Read", "lines", "from", "file", "and", "plot", "over", "model", "." ]
def plotLines(ax, line_filename, linewidth=1.0, step=1): """Read lines from file and plot over model.""" xz = np.loadtxt(line_filename) n_points = xz.shape[0] if step == 2: for i in range(0, n_points, step): x = xz[i:i + step, 0] z = xz[i:i + step, 1] ax.plot(x, z, 'k-', linewidth=linewidth) if step == 1: ax.plot(xz[:, 0], xz[:, 1], 'k-', linewidth=linewidth)
[ "def", "plotLines", "(", "ax", ",", "line_filename", ",", "linewidth", "=", "1.0", ",", "step", "=", "1", ")", ":", "xz", "=", "np", ".", "loadtxt", "(", "line_filename", ")", "n_points", "=", "xz", ".", "shape", "[", "0", "]", "if", "step", "==", "2", ":", "for", "i", "in", "range", "(", "0", ",", "n_points", ",", "step", ")", ":", "x", "=", "xz", "[", "i", ":", "i", "+", "step", ",", "0", "]", "z", "=", "xz", "[", "i", ":", "i", "+", "step", ",", "1", "]", "ax", ".", "plot", "(", "x", ",", "z", ",", "'k-'", ",", "linewidth", "=", "linewidth", ")", "if", "step", "==", "1", ":", "ax", ".", "plot", "(", "xz", "[", ":", ",", "0", "]", ",", "xz", "[", ":", ",", "1", "]", ",", "'k-'", ",", "linewidth", "=", "linewidth", ")" ]
https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/viewer/mpl/utils.py#L283-L293
apache/singa
93fd9da72694e68bfe3fb29d0183a65263d238a1
python/singa/model.py
python
Model.graph
(self, mode=True, sequential=False)
Turn on the computational graph. Specify execution mode. Args: mode(bool): when mode is True, model will use computational graph sequential(bool): when sequential is True, model will execute ops in the graph follow the order of joining the graph
Turn on the computational graph. Specify execution mode.
[ "Turn", "on", "the", "computational", "graph", ".", "Specify", "execution", "mode", "." ]
def graph(self, mode=True, sequential=False): """ Turn on the computational graph. Specify execution mode. Args: mode(bool): when mode is True, model will use computational graph sequential(bool): when sequential is True, model will execute ops in the graph follow the order of joining the graph """ self.graph_mode = mode self.sequential = sequential
[ "def", "graph", "(", "self", ",", "mode", "=", "True", ",", "sequential", "=", "False", ")", ":", "self", ".", "graph_mode", "=", "mode", "self", ".", "sequential", "=", "sequential" ]
https://github.com/apache/singa/blob/93fd9da72694e68bfe3fb29d0183a65263d238a1/python/singa/model.py#L224-L233
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
python/mxnet/executor.py
python
Executor.debug_str
(self)
return py_str(debug_str.value)
Get a debug string about internal execution plan. Returns ------- debug_str : string Debug string of the executor. Examples -------- >>> a = mx.sym.Variable('a') >>> b = mx.sym.sin(a) >>> c = 2 * a + b >>> texec = c.bind(mx.cpu(), {'a': mx.nd.array([1,2]), 'b':mx.nd.array([2,3])}) >>> print(texec.debug_str()) Symbol Outputs: output[0]=_plus0(0) Variable:a -------------------- Op:_mul_scalar, Name=_mulscalar0 Inputs: arg[0]=a(0) version=0 Attrs: scalar=2 -------------------- Op:sin, Name=sin0 Inputs: arg[0]=a(0) version=0 -------------------- Op:elemwise_add, Name=_plus0 Inputs: arg[0]=_mulscalar0(0) arg[1]=sin0(0) Total 0 MB allocated Total 11 TempSpace resource requested
Get a debug string about internal execution plan.
[ "Get", "a", "debug", "string", "about", "internal", "execution", "plan", "." ]
def debug_str(self): """Get a debug string about internal execution plan. Returns ------- debug_str : string Debug string of the executor. Examples -------- >>> a = mx.sym.Variable('a') >>> b = mx.sym.sin(a) >>> c = 2 * a + b >>> texec = c.bind(mx.cpu(), {'a': mx.nd.array([1,2]), 'b':mx.nd.array([2,3])}) >>> print(texec.debug_str()) Symbol Outputs: output[0]=_plus0(0) Variable:a -------------------- Op:_mul_scalar, Name=_mulscalar0 Inputs: arg[0]=a(0) version=0 Attrs: scalar=2 -------------------- Op:sin, Name=sin0 Inputs: arg[0]=a(0) version=0 -------------------- Op:elemwise_add, Name=_plus0 Inputs: arg[0]=_mulscalar0(0) arg[1]=sin0(0) Total 0 MB allocated Total 11 TempSpace resource requested """ debug_str = ctypes.c_char_p() check_call(_LIB.MXExecutorPrint( self.handle, ctypes.byref(debug_str))) return py_str(debug_str.value)
[ "def", "debug_str", "(", "self", ")", ":", "debug_str", "=", "ctypes", ".", "c_char_p", "(", ")", "check_call", "(", "_LIB", ".", "MXExecutorPrint", "(", "self", ".", "handle", ",", "ctypes", ".", "byref", "(", "debug_str", ")", ")", ")", "return", "py_str", "(", "debug_str", ".", "value", ")" ]
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/executor.py#L474-L513
google/mysql-protobuf
467cda676afaa49e762c5c9164a43f6ad31a1fbf
storage/ndb/mcc/util.py
python
html_rep
(obj)
return s.strip().replace('<','&lt;').replace('>', '&gt;')
Format an object in an html-friendly way. That is; convert any < and > characters found in the str() representation to the corresponding html-escape sequence.
Format an object in an html-friendly way. That is; convert any < and > characters found in the str() representation to the corresponding html-escape sequence.
[ "Format", "an", "object", "in", "an", "html", "-", "friendly", "way", ".", "That", "is", ";", "convert", "any", "<", "and", ">", "characters", "found", "in", "the", "str", "()", "representation", "to", "the", "corresponding", "html", "-", "escape", "sequence", "." ]
def html_rep(obj): """Format an object in an html-friendly way. That is; convert any < and > characters found in the str() representation to the corresponding html-escape sequence.""" s = str(obj) if s == '': s = repr(obj) return s.strip().replace('<','&lt;').replace('>', '&gt;')
[ "def", "html_rep", "(", "obj", ")", ":", "s", "=", "str", "(", "obj", ")", "if", "s", "==", "''", ":", "s", "=", "repr", "(", "obj", ")", "return", "s", ".", "strip", "(", ")", ".", "replace", "(", "'<'", ",", "'&lt;'", ")", ".", "replace", "(", "'>'", ",", "'&gt;'", ")" ]
https://github.com/google/mysql-protobuf/blob/467cda676afaa49e762c5c9164a43f6ad31a1fbf/storage/ndb/mcc/util.py#L109-L116
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
Position.GetCol
(*args, **kwargs)
return _core_.Position_GetCol(*args, **kwargs)
GetCol(self) -> int
GetCol(self) -> int
[ "GetCol", "(", "self", ")", "-", ">", "int" ]
def GetCol(*args, **kwargs): """GetCol(self) -> int""" return _core_.Position_GetCol(*args, **kwargs)
[ "def", "GetCol", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Position_GetCol", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L2094-L2096
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/distributed/pipeline/sync/pipe.py
python
Pipe.__iter__
(self)
Iterates over children of the underlying sequential module.
Iterates over children of the underlying sequential module.
[ "Iterates", "over", "children", "of", "the", "underlying", "sequential", "module", "." ]
def __iter__(self) -> Iterable[nn.Module]: """Iterates over children of the underlying sequential module.""" for partition in self.partitions: yield from partition
[ "def", "__iter__", "(", "self", ")", "->", "Iterable", "[", "nn", ".", "Module", "]", ":", "for", "partition", "in", "self", ".", "partitions", ":", "yield", "from", "partition" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/distributed/pipeline/sync/pipe.py#L377-L380
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/pyfakefs/pyfakefs/fake_filesystem_shutil.py
python
FakeShutilModule.copystat
(self, src, dst)
Copy all stat info (mode bits, atime, and mtime) from src to dst. Args: src: (str) source file dst: (str) destination file
Copy all stat info (mode bits, atime, and mtime) from src to dst.
[ "Copy", "all", "stat", "info", "(", "mode", "bits", "atime", "and", "mtime", ")", "from", "src", "to", "dst", "." ]
def copystat(self, src, dst): """Copy all stat info (mode bits, atime, and mtime) from src to dst. Args: src: (str) source file dst: (str) destination file """ src_object = self.filesystem.GetObject(src) dst_object = self.filesystem.GetObject(dst) dst_object.st_mode = ((dst_object.st_mode & ~_PERM_ALL) | (src_object.st_mode & _PERM_ALL)) dst_object.st_uid = src_object.st_uid dst_object.st_gid = src_object.st_gid dst_object.st_atime = src_object.st_atime dst_object.st_mtime = src_object.st_mtime
[ "def", "copystat", "(", "self", ",", "src", ",", "dst", ")", ":", "src_object", "=", "self", ".", "filesystem", ".", "GetObject", "(", "src", ")", "dst_object", "=", "self", ".", "filesystem", ".", "GetObject", "(", "dst", ")", "dst_object", ".", "st_mode", "=", "(", "(", "dst_object", ".", "st_mode", "&", "~", "_PERM_ALL", ")", "|", "(", "src_object", ".", "st_mode", "&", "_PERM_ALL", ")", ")", "dst_object", ".", "st_uid", "=", "src_object", ".", "st_uid", "dst_object", ".", "st_gid", "=", "src_object", ".", "st_gid", "dst_object", ".", "st_atime", "=", "src_object", ".", "st_atime", "dst_object", ".", "st_mtime", "=", "src_object", ".", "st_mtime" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/pyfakefs/pyfakefs/fake_filesystem_shutil.py#L136-L150
EricLYang/courseRepo
60679ec7ec130fe0cff9d26b704f1e286e5fde13
3_class/mono-slam/build/devel/_setup_util.py
python
find_env_hooks
(environ, cmake_prefix_path)
return lines
Generate shell code with found environment hooks for the all workspaces.
Generate shell code with found environment hooks for the all workspaces.
[ "Generate", "shell", "code", "with", "found", "environment", "hooks", "for", "the", "all", "workspaces", "." ]
def find_env_hooks(environ, cmake_prefix_path): ''' Generate shell code with found environment hooks for the all workspaces. ''' lines = [] lines.append(comment('found environment hooks in workspaces')) generic_env_hooks = [] generic_env_hooks_workspace = [] specific_env_hooks = [] specific_env_hooks_workspace = [] generic_env_hooks_by_filename = {} specific_env_hooks_by_filename = {} generic_env_hook_ext = 'bat' if IS_WINDOWS else 'sh' specific_env_hook_ext = environ['CATKIN_SHELL'] if not IS_WINDOWS and 'CATKIN_SHELL' in environ and environ['CATKIN_SHELL'] else None # remove non-workspace paths workspaces = [path for path in cmake_prefix_path.split(os.pathsep) if path and os.path.isfile(os.path.join(path, CATKIN_MARKER_FILE))] for workspace in reversed(workspaces): env_hook_dir = os.path.join(workspace, 'etc', 'catkin', 'profile.d') if os.path.isdir(env_hook_dir): for filename in sorted(os.listdir(env_hook_dir)): if filename.endswith('.%s' % generic_env_hook_ext): # remove previous env hook with same name if present if filename in generic_env_hooks_by_filename: i = generic_env_hooks.index(generic_env_hooks_by_filename[filename]) generic_env_hooks.pop(i) generic_env_hooks_workspace.pop(i) # append env hook generic_env_hooks.append(os.path.join(env_hook_dir, filename)) generic_env_hooks_workspace.append(workspace) generic_env_hooks_by_filename[filename] = generic_env_hooks[-1] elif specific_env_hook_ext is not None and filename.endswith('.%s' % specific_env_hook_ext): # remove previous env hook with same name if present if filename in specific_env_hooks_by_filename: i = specific_env_hooks.index(specific_env_hooks_by_filename[filename]) specific_env_hooks.pop(i) specific_env_hooks_workspace.pop(i) # append env hook specific_env_hooks.append(os.path.join(env_hook_dir, filename)) specific_env_hooks_workspace.append(workspace) specific_env_hooks_by_filename[filename] = specific_env_hooks[-1] env_hooks = generic_env_hooks + specific_env_hooks env_hooks_workspace = generic_env_hooks_workspace + specific_env_hooks_workspace count = len(env_hooks) lines.append(assignment('_CATKIN_ENVIRONMENT_HOOKS_COUNT', count)) for i in range(count): lines.append(assignment('_CATKIN_ENVIRONMENT_HOOKS_%d' % i, env_hooks[i])) lines.append(assignment('_CATKIN_ENVIRONMENT_HOOKS_%d_WORKSPACE' % i, env_hooks_workspace[i])) return lines
[ "def", "find_env_hooks", "(", "environ", ",", "cmake_prefix_path", ")", ":", "lines", "=", "[", "]", "lines", ".", "append", "(", "comment", "(", "'found environment hooks in workspaces'", ")", ")", "generic_env_hooks", "=", "[", "]", "generic_env_hooks_workspace", "=", "[", "]", "specific_env_hooks", "=", "[", "]", "specific_env_hooks_workspace", "=", "[", "]", "generic_env_hooks_by_filename", "=", "{", "}", "specific_env_hooks_by_filename", "=", "{", "}", "generic_env_hook_ext", "=", "'bat'", "if", "IS_WINDOWS", "else", "'sh'", "specific_env_hook_ext", "=", "environ", "[", "'CATKIN_SHELL'", "]", "if", "not", "IS_WINDOWS", "and", "'CATKIN_SHELL'", "in", "environ", "and", "environ", "[", "'CATKIN_SHELL'", "]", "else", "None", "# remove non-workspace paths", "workspaces", "=", "[", "path", "for", "path", "in", "cmake_prefix_path", ".", "split", "(", "os", ".", "pathsep", ")", "if", "path", "and", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "path", ",", "CATKIN_MARKER_FILE", ")", ")", "]", "for", "workspace", "in", "reversed", "(", "workspaces", ")", ":", "env_hook_dir", "=", "os", ".", "path", ".", "join", "(", "workspace", ",", "'etc'", ",", "'catkin'", ",", "'profile.d'", ")", "if", "os", ".", "path", ".", "isdir", "(", "env_hook_dir", ")", ":", "for", "filename", "in", "sorted", "(", "os", ".", "listdir", "(", "env_hook_dir", ")", ")", ":", "if", "filename", ".", "endswith", "(", "'.%s'", "%", "generic_env_hook_ext", ")", ":", "# remove previous env hook with same name if present", "if", "filename", "in", "generic_env_hooks_by_filename", ":", "i", "=", "generic_env_hooks", ".", "index", "(", "generic_env_hooks_by_filename", "[", "filename", "]", ")", "generic_env_hooks", ".", "pop", "(", "i", ")", "generic_env_hooks_workspace", ".", "pop", "(", "i", ")", "# append env hook", "generic_env_hooks", ".", "append", "(", "os", ".", "path", ".", "join", "(", "env_hook_dir", ",", "filename", ")", ")", "generic_env_hooks_workspace", ".", "append", "(", "workspace", ")", "generic_env_hooks_by_filename", "[", "filename", "]", "=", "generic_env_hooks", "[", "-", "1", "]", "elif", "specific_env_hook_ext", "is", "not", "None", "and", "filename", ".", "endswith", "(", "'.%s'", "%", "specific_env_hook_ext", ")", ":", "# remove previous env hook with same name if present", "if", "filename", "in", "specific_env_hooks_by_filename", ":", "i", "=", "specific_env_hooks", ".", "index", "(", "specific_env_hooks_by_filename", "[", "filename", "]", ")", "specific_env_hooks", ".", "pop", "(", "i", ")", "specific_env_hooks_workspace", ".", "pop", "(", "i", ")", "# append env hook", "specific_env_hooks", ".", "append", "(", "os", ".", "path", ".", "join", "(", "env_hook_dir", ",", "filename", ")", ")", "specific_env_hooks_workspace", ".", "append", "(", "workspace", ")", "specific_env_hooks_by_filename", "[", "filename", "]", "=", "specific_env_hooks", "[", "-", "1", "]", "env_hooks", "=", "generic_env_hooks", "+", "specific_env_hooks", "env_hooks_workspace", "=", "generic_env_hooks_workspace", "+", "specific_env_hooks_workspace", "count", "=", "len", "(", "env_hooks", ")", "lines", ".", "append", "(", "assignment", "(", "'_CATKIN_ENVIRONMENT_HOOKS_COUNT'", ",", "count", ")", ")", "for", "i", "in", "range", "(", "count", ")", ":", "lines", ".", "append", "(", "assignment", "(", "'_CATKIN_ENVIRONMENT_HOOKS_%d'", "%", "i", ",", "env_hooks", "[", "i", "]", ")", ")", "lines", ".", "append", "(", "assignment", "(", "'_CATKIN_ENVIRONMENT_HOOKS_%d_WORKSPACE'", "%", "i", ",", "env_hooks_workspace", "[", "i", "]", ")", ")", "return", "lines" ]
https://github.com/EricLYang/courseRepo/blob/60679ec7ec130fe0cff9d26b704f1e286e5fde13/3_class/mono-slam/build/devel/_setup_util.py#L199-L248
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/requests/models.py
python
Response.next
(self)
return self._next
Returns a PreparedRequest for the next request in a redirect chain, if there is one.
Returns a PreparedRequest for the next request in a redirect chain, if there is one.
[ "Returns", "a", "PreparedRequest", "for", "the", "next", "request", "in", "a", "redirect", "chain", "if", "there", "is", "one", "." ]
def next(self): """Returns a PreparedRequest for the next request in a redirect chain, if there is one.""" return self._next
[ "def", "next", "(", "self", ")", ":", "return", "self", ".", "_next" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/requests/models.py#L723-L725