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
sequence
function
stringlengths
34
151k
function_tokens
sequence
url
stringlengths
90
278
psi4/psi4
be533f7f426b6ccc263904e55122899b16663395
psi4/driver/qcdb/vecutil.py
python
mult
(matrix1, matrix2)
Matrix multiplication
Matrix multiplication
[ "Matrix", "multiplication" ]
def mult(matrix1, matrix2): """ Matrix multiplication""" if len(matrix1[0]) != len(matrix2): # Check matrix dimensions raise ValidationError('Matrices must be m*n and n*p to multiply!') else: # Multiply if correct dimensions try: new_matrix = zero(len(matrix1), len(matrix2[0])) for i in range(len(matrix1)): for j in range(len(matrix2[0])): for k in range(len(matrix2)): new_matrix[i][j] += matrix1[i][k] * matrix2[k][j] except TypeError: new_matrix = zero(len(matrix1), 1) for i in range(len(matrix1)): for k in range(len(matrix2)): new_matrix[i][0] += matrix1[i][k] * matrix2[k] return new_matrix
[ "def", "mult", "(", "matrix1", ",", "matrix2", ")", ":", "if", "len", "(", "matrix1", "[", "0", "]", ")", "!=", "len", "(", "matrix2", ")", ":", "# Check matrix dimensions", "raise", "ValidationError", "(", "'Matrices must be m*n and n*p to multiply!'", ")", "else", ":", "# Multiply if correct dimensions", "try", ":", "new_matrix", "=", "zero", "(", "len", "(", "matrix1", ")", ",", "len", "(", "matrix2", "[", "0", "]", ")", ")", "for", "i", "in", "range", "(", "len", "(", "matrix1", ")", ")", ":", "for", "j", "in", "range", "(", "len", "(", "matrix2", "[", "0", "]", ")", ")", ":", "for", "k", "in", "range", "(", "len", "(", "matrix2", ")", ")", ":", "new_matrix", "[", "i", "]", "[", "j", "]", "+=", "matrix1", "[", "i", "]", "[", "k", "]", "*", "matrix2", "[", "k", "]", "[", "j", "]", "except", "TypeError", ":", "new_matrix", "=", "zero", "(", "len", "(", "matrix1", ")", ",", "1", ")", "for", "i", "in", "range", "(", "len", "(", "matrix1", ")", ")", ":", "for", "k", "in", "range", "(", "len", "(", "matrix2", ")", ")", ":", "new_matrix", "[", "i", "]", "[", "0", "]", "+=", "matrix1", "[", "i", "]", "[", "k", "]", "*", "matrix2", "[", "k", "]", "return", "new_matrix" ]
https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/qcdb/vecutil.py#L307-L326
eric612/MobileNet-YOLO
69b4441cb3ec8d553fbdef788ad033e246f901bd
scripts/cpp_lint.py
python
CleansedLines.NumLines
(self)
return self.num_lines
Returns the number of lines represented.
Returns the number of lines represented.
[ "Returns", "the", "number", "of", "lines", "represented", "." ]
def NumLines(self): """Returns the number of lines represented.""" return self.num_lines
[ "def", "NumLines", "(", "self", ")", ":", "return", "self", ".", "num_lines" ]
https://github.com/eric612/MobileNet-YOLO/blob/69b4441cb3ec8d553fbdef788ad033e246f901bd/scripts/cpp_lint.py#L1208-L1210
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/Pygments/py3/pygments/lexers/matlab.py
python
OctaveLexer.analyse_text
(text)
return 0
Octave is quite hard to spot, and it looks like Matlab as well.
Octave is quite hard to spot, and it looks like Matlab as well.
[ "Octave", "is", "quite", "hard", "to", "spot", "and", "it", "looks", "like", "Matlab", "as", "well", "." ]
def analyse_text(text): """Octave is quite hard to spot, and it looks like Matlab as well.""" return 0
[ "def", "analyse_text", "(", "text", ")", ":", "return", "0" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Pygments/py3/pygments/lexers/matlab.py#L3223-L3225
NVIDIA/TensorRT
42805f078052daad1a98bc5965974fcffaad0960
tools/onnx-graphsurgeon/onnx_graphsurgeon/logger/logger.py
python
Logger.indent
(self, level=1)
return LoggerIndent(self, level + self.logging_indent)
Returns a context manager that indents all strings logged by the specified amount.
Returns a context manager that indents all strings logged by the specified amount.
[ "Returns", "a", "context", "manager", "that", "indents", "all", "strings", "logged", "by", "the", "specified", "amount", "." ]
def indent(self, level=1): """ Returns a context manager that indents all strings logged by the specified amount. """ return LoggerIndent(self, level + self.logging_indent)
[ "def", "indent", "(", "self", ",", "level", "=", "1", ")", ":", "return", "LoggerIndent", "(", "self", ",", "level", "+", "self", ".", "logging_indent", ")" ]
https://github.com/NVIDIA/TensorRT/blob/42805f078052daad1a98bc5965974fcffaad0960/tools/onnx-graphsurgeon/onnx_graphsurgeon/logger/logger.py#L131-L135
facebookresearch/faiss
eb8781557f556505ca93f6f21fff932e17f0d9e0
faiss/python/__init__.py
python
index_cpu_to_gpus_list
(index, co=None, gpus=None, ngpu=-1)
return index_gpu
Here we can pass list of GPU ids as a parameter or ngpu to use first n GPU's. gpus mut be a list or None
Here we can pass list of GPU ids as a parameter or ngpu to use first n GPU's. gpus mut be a list or None
[ "Here", "we", "can", "pass", "list", "of", "GPU", "ids", "as", "a", "parameter", "or", "ngpu", "to", "use", "first", "n", "GPU", "s", ".", "gpus", "mut", "be", "a", "list", "or", "None" ]
def index_cpu_to_gpus_list(index, co=None, gpus=None, ngpu=-1): """ Here we can pass list of GPU ids as a parameter or ngpu to use first n GPU's. gpus mut be a list or None""" if (gpus is None) and (ngpu == -1): # All blank gpus = range(get_num_gpus()) elif (gpus is None) and (ngpu != -1): # Get number of GPU's only gpus = range(ngpu) res = [StandardGpuResources() for _ in gpus] index_gpu = index_cpu_to_gpu_multiple_py(res, index, co, gpus) return index_gpu
[ "def", "index_cpu_to_gpus_list", "(", "index", ",", "co", "=", "None", ",", "gpus", "=", "None", ",", "ngpu", "=", "-", "1", ")", ":", "if", "(", "gpus", "is", "None", ")", "and", "(", "ngpu", "==", "-", "1", ")", ":", "# All blank", "gpus", "=", "range", "(", "get_num_gpus", "(", ")", ")", "elif", "(", "gpus", "is", "None", ")", "and", "(", "ngpu", "!=", "-", "1", ")", ":", "# Get number of GPU's only", "gpus", "=", "range", "(", "ngpu", ")", "res", "=", "[", "StandardGpuResources", "(", ")", "for", "_", "in", "gpus", "]", "index_gpu", "=", "index_cpu_to_gpu_multiple_py", "(", "res", ",", "index", ",", "co", ",", "gpus", ")", "return", "index_gpu" ]
https://github.com/facebookresearch/faiss/blob/eb8781557f556505ca93f6f21fff932e17f0d9e0/faiss/python/__init__.py#L891-L900
google/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
earth_enterprise/src/fusion/portableglobe/cutter/cgi-bin/common/form_wrap.py
python
FormWrap.getvalue_path
(self, key, default_val=None)
return val
Gets path value (filesystem path). Args: key: requested argument. default_val: a default value to return if requested argument is not present. Returns: value for requested argument.
Gets path value (filesystem path).
[ "Gets", "path", "value", "(", "filesystem", "path", ")", "." ]
def getvalue_path(self, key, default_val=None): """Gets path value (filesystem path). Args: key: requested argument. default_val: a default value to return if requested argument is not present. Returns: value for requested argument. """ logging.debug("getvalue_path() - key: %s", key) val = self._getvalue_raw(key, default_val) if not val: return val if self._do_sanitize: val = self._sanitize_path(val) logging.debug("getvalue_path() - key: %s, val: %s", key, val) return val
[ "def", "getvalue_path", "(", "self", ",", "key", ",", "default_val", "=", "None", ")", ":", "logging", ".", "debug", "(", "\"getvalue_path() - key: %s\"", ",", "key", ")", "val", "=", "self", ".", "_getvalue_raw", "(", "key", ",", "default_val", ")", "if", "not", "val", ":", "return", "val", "if", "self", ".", "_do_sanitize", ":", "val", "=", "self", ".", "_sanitize_path", "(", "val", ")", "logging", ".", "debug", "(", "\"getvalue_path() - key: %s, val: %s\"", ",", "key", ",", "val", ")", "return", "val" ]
https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/fusion/portableglobe/cutter/cgi-bin/common/form_wrap.py#L241-L261
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/DirectILLReduction.py
python
DirectILLReduction._correctByDetectorEfficiency
(self, mainWS)
return correctedWS
Apply detector efficiency corrections.
Apply detector efficiency corrections.
[ "Apply", "detector", "efficiency", "corrections", "." ]
def _correctByDetectorEfficiency(self, mainWS): """Apply detector efficiency corrections.""" correctedWSName = self._names.withSuffix('detector_efficiency_corrected') correctedWS = \ DetectorEfficiencyCorUser(InputWorkspace=mainWS, OutputWorkspace=correctedWSName, EnableLogging=self._subalgLogging) self._cleanup.cleanup(mainWS) return correctedWS
[ "def", "_correctByDetectorEfficiency", "(", "self", ",", "mainWS", ")", ":", "correctedWSName", "=", "self", ".", "_names", ".", "withSuffix", "(", "'detector_efficiency_corrected'", ")", "correctedWS", "=", "DetectorEfficiencyCorUser", "(", "InputWorkspace", "=", "mainWS", ",", "OutputWorkspace", "=", "correctedWSName", ",", "EnableLogging", "=", "self", ".", "_subalgLogging", ")", "self", ".", "_cleanup", ".", "cleanup", "(", "mainWS", ")", "return", "correctedWS" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/DirectILLReduction.py#L426-L434
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/eclib/panelbox.py
python
PanelBoxItem.SetLabel
(self, lbl)
Set the label text @param lbl: string
Set the label text @param lbl: string
[ "Set", "the", "label", "text", "@param", "lbl", ":", "string" ]
def SetLabel(self, lbl): """Set the label text @param lbl: string """ self._lbl.SetLabel(lbl) self._lbl.Refresh() self.Layout()
[ "def", "SetLabel", "(", "self", ",", "lbl", ")", ":", "self", ".", "_lbl", ".", "SetLabel", "(", "lbl", ")", "self", ".", "_lbl", ".", "Refresh", "(", ")", "self", ".", "Layout", "(", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/eclib/panelbox.py#L431-L438
apache/thrift
0b29261a4f3c6882ef3b09aae47914f0012b0472
lib/py/src/server/TNonblockingServer.py
python
TNonblockingServer.stop
(self)
Stop the server. This method causes the serve() method to return. stop() may be invoked from within your handler, or from another thread. After stop() is called, serve() will return but the server will still be listening on the socket. serve() may then be called again to resume processing requests. Alternatively, close() may be called after serve() returns to close the server socket and shutdown all worker threads.
Stop the server.
[ "Stop", "the", "server", "." ]
def stop(self): """Stop the server. This method causes the serve() method to return. stop() may be invoked from within your handler, or from another thread. After stop() is called, serve() will return but the server will still be listening on the socket. serve() may then be called again to resume processing requests. Alternatively, close() may be called after serve() returns to close the server socket and shutdown all worker threads. """ self._stop = True self.wake_up()
[ "def", "stop", "(", "self", ")", ":", "self", ".", "_stop", "=", "True", "self", ".", "wake_up", "(", ")" ]
https://github.com/apache/thrift/blob/0b29261a4f3c6882ef3b09aae47914f0012b0472/lib/py/src/server/TNonblockingServer.py#L283-L296
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/utils/generic_utils.py
python
object_list_uid
(object_list)
return ', '.join([str(abs(id(x))) for x in object_list])
Creates a single string from object ids.
Creates a single string from object ids.
[ "Creates", "a", "single", "string", "from", "object", "ids", "." ]
def object_list_uid(object_list): """Creates a single string from object ids.""" object_list = nest.flatten(object_list) return ', '.join([str(abs(id(x))) for x in object_list])
[ "def", "object_list_uid", "(", "object_list", ")", ":", "object_list", "=", "nest", ".", "flatten", "(", "object_list", ")", "return", "', '", ".", "join", "(", "[", "str", "(", "abs", "(", "id", "(", "x", ")", ")", ")", "for", "x", "in", "object_list", "]", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/utils/generic_utils.py#L561-L564
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/drill/view/DrillHeaderView.py
python
DrillHeaderView.mousePressEvent
(self, event)
Deal with mouse press event. Override of QTableView::mousePressEvent. This function change the state of a eventual push button below the mouse pointer. Args: event (QMouseEvent): mouse press envent
Deal with mouse press event. Override of QTableView::mousePressEvent. This function change the state of a eventual push button below the mouse pointer.
[ "Deal", "with", "mouse", "press", "event", ".", "Override", "of", "QTableView", "::", "mousePressEvent", ".", "This", "function", "change", "the", "state", "of", "a", "eventual", "push", "button", "below", "the", "mouse", "pointer", "." ]
def mousePressEvent(self, event): """ Deal with mouse press event. Override of QTableView::mousePressEvent. This function change the state of a eventual push button below the mouse pointer. Args: event (QMouseEvent): mouse press envent """ li = self.logicalIndexAt(event.pos()) if self.mouseOnButton(event.pos(), li): self.buttonPressed = li self.updateSection(li) else: super(DrillHeaderView, self).mousePressEvent(event)
[ "def", "mousePressEvent", "(", "self", ",", "event", ")", ":", "li", "=", "self", ".", "logicalIndexAt", "(", "event", ".", "pos", "(", ")", ")", "if", "self", ".", "mouseOnButton", "(", "event", ".", "pos", "(", ")", ",", "li", ")", ":", "self", ".", "buttonPressed", "=", "li", "self", ".", "updateSection", "(", "li", ")", "else", ":", "super", "(", "DrillHeaderView", ",", "self", ")", ".", "mousePressEvent", "(", "event", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/drill/view/DrillHeaderView.py#L175-L189
deepmind/open_spiel
4ca53bea32bb2875c7385d215424048ae92f78c8
open_spiel/python/algorithms/psro_v2/optimization_oracle.py
python
AbstractOracle.__call__
(self, game, policy, total_policies, current_player, probabilities_of_playing_policies, **oracle_specific_execution_kwargs)
Call method for oracle, returns best response against a set of policies. Args: game: The game on which the optimization process takes place. policy: The current policy, in policy.Policy, from which we wish to start optimizing. total_policies: A list of all policy.Policy strategies used for training, including the one for the current player. current_player: Integer representing the current player. probabilities_of_playing_policies: A list of arrays representing, per player, the probabilities of playing each policy in total_policies for the same player. **oracle_specific_execution_kwargs: Other set of arguments, for compatibility purposes. Can for example represent whether to Rectify Training or not.
Call method for oracle, returns best response against a set of policies.
[ "Call", "method", "for", "oracle", "returns", "best", "response", "against", "a", "set", "of", "policies", "." ]
def __call__(self, game, policy, total_policies, current_player, probabilities_of_playing_policies, **oracle_specific_execution_kwargs): """Call method for oracle, returns best response against a set of policies. Args: game: The game on which the optimization process takes place. policy: The current policy, in policy.Policy, from which we wish to start optimizing. total_policies: A list of all policy.Policy strategies used for training, including the one for the current player. current_player: Integer representing the current player. probabilities_of_playing_policies: A list of arrays representing, per player, the probabilities of playing each policy in total_policies for the same player. **oracle_specific_execution_kwargs: Other set of arguments, for compatibility purposes. Can for example represent whether to Rectify Training or not. """ raise NotImplementedError("Calling Abstract class method.")
[ "def", "__call__", "(", "self", ",", "game", ",", "policy", ",", "total_policies", ",", "current_player", ",", "probabilities_of_playing_policies", ",", "*", "*", "oracle_specific_execution_kwargs", ")", ":", "raise", "NotImplementedError", "(", "\"Calling Abstract class method.\"", ")" ]
https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/algorithms/psro_v2/optimization_oracle.py#L76-L95
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/bayesflow/python/ops/variational_inference_impl.py
python
register_prior
(variational, prior)
Associate a variational `StochasticTensor` with a `Distribution` prior. This is a helper function used in conjunction with `elbo` that allows users to specify the mapping between variational distributions and their priors without having to pass in `variational_with_prior` explicitly. Args: variational: `StochasticTensor` q(Z). Approximating distribution. prior: `Distribution` p(Z). Prior distribution. Returns: None Raises: ValueError: if variational is not a `StochasticTensor` or `prior` is not a `Distribution`.
Associate a variational `StochasticTensor` with a `Distribution` prior.
[ "Associate", "a", "variational", "StochasticTensor", "with", "a", "Distribution", "prior", "." ]
def register_prior(variational, prior): """Associate a variational `StochasticTensor` with a `Distribution` prior. This is a helper function used in conjunction with `elbo` that allows users to specify the mapping between variational distributions and their priors without having to pass in `variational_with_prior` explicitly. Args: variational: `StochasticTensor` q(Z). Approximating distribution. prior: `Distribution` p(Z). Prior distribution. Returns: None Raises: ValueError: if variational is not a `StochasticTensor` or `prior` is not a `Distribution`. """ if not isinstance(variational, st.StochasticTensor): raise TypeError("variational must be a StochasticTensor") if not isinstance(prior, distribution.Distribution): raise TypeError("prior must be a Distribution") ops.add_to_collection(VI_PRIORS, (variational, prior))
[ "def", "register_prior", "(", "variational", ",", "prior", ")", ":", "if", "not", "isinstance", "(", "variational", ",", "st", ".", "StochasticTensor", ")", ":", "raise", "TypeError", "(", "\"variational must be a StochasticTensor\"", ")", "if", "not", "isinstance", "(", "prior", ",", "distribution", ".", "Distribution", ")", ":", "raise", "TypeError", "(", "\"prior must be a Distribution\"", ")", "ops", ".", "add_to_collection", "(", "VI_PRIORS", ",", "(", "variational", ",", "prior", ")", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/bayesflow/python/ops/variational_inference_impl.py#L40-L62
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py3/setuptools/_vendor/ordered_set.py
python
OrderedSet.symmetric_difference_update
(self, other)
Update this OrderedSet to remove items from another set, then add items from the other set that were not present in this set. Example: >>> this = OrderedSet([1, 4, 3, 5, 7]) >>> other = OrderedSet([9, 7, 1, 3, 2]) >>> this.symmetric_difference_update(other) >>> print(this) OrderedSet([4, 5, 9, 2])
Update this OrderedSet to remove items from another set, then add items from the other set that were not present in this set.
[ "Update", "this", "OrderedSet", "to", "remove", "items", "from", "another", "set", "then", "add", "items", "from", "the", "other", "set", "that", "were", "not", "present", "in", "this", "set", "." ]
def symmetric_difference_update(self, other): """ Update this OrderedSet to remove items from another set, then add items from the other set that were not present in this set. Example: >>> this = OrderedSet([1, 4, 3, 5, 7]) >>> other = OrderedSet([9, 7, 1, 3, 2]) >>> this.symmetric_difference_update(other) >>> print(this) OrderedSet([4, 5, 9, 2]) """ items_to_add = [item for item in other if item not in self] items_to_remove = set(other) self._update_items( [item for item in self.items if item not in items_to_remove] + items_to_add )
[ "def", "symmetric_difference_update", "(", "self", ",", "other", ")", ":", "items_to_add", "=", "[", "item", "for", "item", "in", "other", "if", "item", "not", "in", "self", "]", "items_to_remove", "=", "set", "(", "other", ")", "self", ".", "_update_items", "(", "[", "item", "for", "item", "in", "self", ".", "items", "if", "item", "not", "in", "items_to_remove", "]", "+", "items_to_add", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/_vendor/ordered_set.py#L472-L488
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/pdb.py
python
Pdb.do_args
(self, arg)
a(rgs) Print the argument list of the current function.
a(rgs) Print the argument list of the current function.
[ "a", "(", "rgs", ")", "Print", "the", "argument", "list", "of", "the", "current", "function", "." ]
def do_args(self, arg): """a(rgs) Print the argument list of the current function. """ co = self.curframe.f_code dict = self.curframe_locals n = co.co_argcount + co.co_kwonlyargcount if co.co_flags & inspect.CO_VARARGS: n = n+1 if co.co_flags & inspect.CO_VARKEYWORDS: n = n+1 for i in range(n): name = co.co_varnames[i] if name in dict: self.message('%s = %r' % (name, dict[name])) else: self.message('%s = *** undefined ***' % (name,))
[ "def", "do_args", "(", "self", ",", "arg", ")", ":", "co", "=", "self", ".", "curframe", ".", "f_code", "dict", "=", "self", ".", "curframe_locals", "n", "=", "co", ".", "co_argcount", "+", "co", ".", "co_kwonlyargcount", "if", "co", ".", "co_flags", "&", "inspect", ".", "CO_VARARGS", ":", "n", "=", "n", "+", "1", "if", "co", ".", "co_flags", "&", "inspect", ".", "CO_VARKEYWORDS", ":", "n", "=", "n", "+", "1", "for", "i", "in", "range", "(", "n", ")", ":", "name", "=", "co", ".", "co_varnames", "[", "i", "]", "if", "name", "in", "dict", ":", "self", ".", "message", "(", "'%s = %r'", "%", "(", "name", ",", "dict", "[", "name", "]", ")", ")", "else", ":", "self", ".", "message", "(", "'%s = *** undefined ***'", "%", "(", "name", ",", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/pdb.py#L1128-L1142
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/linalg/_interpolative_backend.py
python
id_srandi
(t)
Initialize seed values for :func:`id_srand` (any appropriately random numbers will do). :param t: Array of 55 seed values. :type t: :class:`numpy.ndarray`
Initialize seed values for :func:`id_srand` (any appropriately random numbers will do).
[ "Initialize", "seed", "values", "for", ":", "func", ":", "id_srand", "(", "any", "appropriately", "random", "numbers", "will", "do", ")", "." ]
def id_srandi(t): """ Initialize seed values for :func:`id_srand` (any appropriately random numbers will do). :param t: Array of 55 seed values. :type t: :class:`numpy.ndarray` """ t = np.asfortranarray(t) _id.id_srandi(t)
[ "def", "id_srandi", "(", "t", ")", ":", "t", "=", "np", ".", "asfortranarray", "(", "t", ")", "_id", ".", "id_srandi", "(", "t", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/linalg/_interpolative_backend.py#L60-L70
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/labelbook.py
python
ImageContainerBase.GetImageSize
(self)
return self._nImgSize
Returns the image size inside the :class:`ImageContainerBase` image list.
Returns the image size inside the :class:`ImageContainerBase` image list.
[ "Returns", "the", "image", "size", "inside", "the", ":", "class", ":", "ImageContainerBase", "image", "list", "." ]
def GetImageSize(self): """ Returns the image size inside the :class:`ImageContainerBase` image list. """ return self._nImgSize
[ "def", "GetImageSize", "(", "self", ")", ":", "return", "self", ".", "_nImgSize" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/labelbook.py#L589-L592
Genius-x/genius-x
9fc9f194e6d1fb92dd0e33d43db19ddb67cda7b0
cocos2d/tools/bindings-generator/clang/cindex.py
python
Cursor.result_type
(self)
return self._result_type
Retrieve the Type of the result for this Cursor.
Retrieve the Type of the result for this Cursor.
[ "Retrieve", "the", "Type", "of", "the", "result", "for", "this", "Cursor", "." ]
def result_type(self): """Retrieve the Type of the result for this Cursor.""" if not hasattr(self, '_result_type'): self._result_type = conf.lib.clang_getResultType(self.type) return self._result_type
[ "def", "result_type", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_result_type'", ")", ":", "self", ".", "_result_type", "=", "conf", ".", "lib", ".", "clang_getResultType", "(", "self", ".", "type", ")", "return", "self", ".", "_result_type" ]
https://github.com/Genius-x/genius-x/blob/9fc9f194e6d1fb92dd0e33d43db19ddb67cda7b0/cocos2d/tools/bindings-generator/clang/cindex.py#L1323-L1328
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/ops/losses/losses_impl.py
python
_safe_mean
(losses, num_present)
return _safe_div(total_loss, num_present)
Computes a safe mean of the losses. Args: losses: `Tensor` whose elements contain individual loss measurements. num_present: The number of measurable elements in `losses`. Returns: A scalar representing the mean of `losses`. If `num_present` is zero, then zero is returned.
Computes a safe mean of the losses.
[ "Computes", "a", "safe", "mean", "of", "the", "losses", "." ]
def _safe_mean(losses, num_present): """Computes a safe mean of the losses. Args: losses: `Tensor` whose elements contain individual loss measurements. num_present: The number of measurable elements in `losses`. Returns: A scalar representing the mean of `losses`. If `num_present` is zero, then zero is returned. """ total_loss = math_ops.reduce_sum(losses) return _safe_div(total_loss, num_present)
[ "def", "_safe_mean", "(", "losses", ",", "num_present", ")", ":", "total_loss", "=", "math_ops", ".", "reduce_sum", "(", "losses", ")", "return", "_safe_div", "(", "total_loss", ",", "num_present", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/losses/losses_impl.py#L87-L99
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/Pygments/py3/pygments/lexers/textedit.py
python
VimLexer.is_in
(self, w, mapping)
return False
r""" It's kind of difficult to decide if something might be a keyword in VimL because it allows you to abbreviate them. In fact, 'ab[breviate]' is a good example. :ab, :abbre, or :abbreviate are valid ways to call it so rather than making really awful regexps like:: \bab(?:b(?:r(?:e(?:v(?:i(?:a(?:t(?:e)?)?)?)?)?)?)?)?\b we match `\b\w+\b` and then call is_in() on those tokens. See `scripts/get_vimkw.py` for how the lists are extracted.
r""" It's kind of difficult to decide if something might be a keyword in VimL because it allows you to abbreviate them. In fact, 'ab[breviate]' is a good example. :ab, :abbre, or :abbreviate are valid ways to call it so rather than making really awful regexps like::
[ "r", "It", "s", "kind", "of", "difficult", "to", "decide", "if", "something", "might", "be", "a", "keyword", "in", "VimL", "because", "it", "allows", "you", "to", "abbreviate", "them", ".", "In", "fact", "ab", "[", "breviate", "]", "is", "a", "good", "example", ".", ":", "ab", ":", "abbre", "or", ":", "abbreviate", "are", "valid", "ways", "to", "call", "it", "so", "rather", "than", "making", "really", "awful", "regexps", "like", "::" ]
def is_in(self, w, mapping): r""" It's kind of difficult to decide if something might be a keyword in VimL because it allows you to abbreviate them. In fact, 'ab[breviate]' is a good example. :ab, :abbre, or :abbreviate are valid ways to call it so rather than making really awful regexps like:: \bab(?:b(?:r(?:e(?:v(?:i(?:a(?:t(?:e)?)?)?)?)?)?)?)?\b we match `\b\w+\b` and then call is_in() on those tokens. See `scripts/get_vimkw.py` for how the lists are extracted. """ p = bisect(mapping, (w,)) if p > 0: if mapping[p-1][0] == w[:len(mapping[p-1][0])] and \ mapping[p-1][1][:len(w)] == w: return True if p < len(mapping): return mapping[p][0] == w[:len(mapping[p][0])] and \ mapping[p][1][:len(w)] == w return False
[ "def", "is_in", "(", "self", ",", "w", ",", "mapping", ")", ":", "p", "=", "bisect", "(", "mapping", ",", "(", "w", ",", ")", ")", "if", "p", ">", "0", ":", "if", "mapping", "[", "p", "-", "1", "]", "[", "0", "]", "==", "w", "[", ":", "len", "(", "mapping", "[", "p", "-", "1", "]", "[", "0", "]", ")", "]", "and", "mapping", "[", "p", "-", "1", "]", "[", "1", "]", "[", ":", "len", "(", "w", ")", "]", "==", "w", ":", "return", "True", "if", "p", "<", "len", "(", "mapping", ")", ":", "return", "mapping", "[", "p", "]", "[", "0", "]", "==", "w", "[", ":", "len", "(", "mapping", "[", "p", "]", "[", "0", "]", ")", "]", "and", "mapping", "[", "p", "]", "[", "1", "]", "[", ":", "len", "(", "w", ")", "]", "==", "w", "return", "False" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Pygments/py3/pygments/lexers/textedit.py#L164-L185
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/lib2to3/btm_utils.py
python
MinNode.get_linear_subpattern
(self)
Drives the leaf_to_root method. The reason that leaf_to_root must be run multiple times is because we need to reject 'group' matches; for example the alternative form (a | b c) creates a group [b c] that needs to be matched. Since matching multiple linear patterns overcomes the automaton's capabilities, leaf_to_root merges each group into a single choice based on 'characteristic'ity, i.e. (a|b c) -> (a|b) if b more characteristic than c Returns: The most 'characteristic'(as defined by get_characteristic_subpattern) path for the compiled pattern tree.
Drives the leaf_to_root method. The reason that leaf_to_root must be run multiple times is because we need to reject 'group' matches; for example the alternative form (a | b c) creates a group [b c] that needs to be matched. Since matching multiple linear patterns overcomes the automaton's capabilities, leaf_to_root merges each group into a single choice based on 'characteristic'ity,
[ "Drives", "the", "leaf_to_root", "method", ".", "The", "reason", "that", "leaf_to_root", "must", "be", "run", "multiple", "times", "is", "because", "we", "need", "to", "reject", "group", "matches", ";", "for", "example", "the", "alternative", "form", "(", "a", "|", "b", "c", ")", "creates", "a", "group", "[", "b", "c", "]", "that", "needs", "to", "be", "matched", ".", "Since", "matching", "multiple", "linear", "patterns", "overcomes", "the", "automaton", "s", "capabilities", "leaf_to_root", "merges", "each", "group", "into", "a", "single", "choice", "based", "on", "characteristic", "ity" ]
def get_linear_subpattern(self): """Drives the leaf_to_root method. The reason that leaf_to_root must be run multiple times is because we need to reject 'group' matches; for example the alternative form (a | b c) creates a group [b c] that needs to be matched. Since matching multiple linear patterns overcomes the automaton's capabilities, leaf_to_root merges each group into a single choice based on 'characteristic'ity, i.e. (a|b c) -> (a|b) if b more characteristic than c Returns: The most 'characteristic'(as defined by get_characteristic_subpattern) path for the compiled pattern tree. """ for l in self.leaves(): subp = l.leaf_to_root() if subp: return subp
[ "def", "get_linear_subpattern", "(", "self", ")", ":", "for", "l", "in", "self", ".", "leaves", "(", ")", ":", "subp", "=", "l", ".", "leaf_to_root", "(", ")", "if", "subp", ":", "return", "subp" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/lib2to3/btm_utils.py#L75-L94
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_controls.py
python
DragImage.Show
(*args, **kwargs)
return _controls_.DragImage_Show(*args, **kwargs)
Show(self) -> bool
Show(self) -> bool
[ "Show", "(", "self", ")", "-", ">", "bool" ]
def Show(*args, **kwargs): """Show(self) -> bool""" return _controls_.DragImage_Show(*args, **kwargs)
[ "def", "Show", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "DragImage_Show", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L6372-L6374
keyboardio/Kaleidoscope
d59604e98b2439d108647f15be52984a6837d360
bin/cpplint.py
python
_SetVerboseLevel
(level)
return _cpplint_state.SetVerboseLevel(level)
Sets the module's verbosity, and returns the previous setting.
Sets the module's verbosity, and returns the previous setting.
[ "Sets", "the", "module", "s", "verbosity", "and", "returns", "the", "previous", "setting", "." ]
def _SetVerboseLevel(level): """Sets the module's verbosity, and returns the previous setting.""" return _cpplint_state.SetVerboseLevel(level)
[ "def", "_SetVerboseLevel", "(", "level", ")", ":", "return", "_cpplint_state", ".", "SetVerboseLevel", "(", "level", ")" ]
https://github.com/keyboardio/Kaleidoscope/blob/d59604e98b2439d108647f15be52984a6837d360/bin/cpplint.py#L1185-L1187
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/idl/idl/generator.py
python
_CppHeaderFileWriter._gen_config_function_declaration
(self, spec)
Generate function declarations for config initializers.
Generate function declarations for config initializers.
[ "Generate", "function", "declarations", "for", "config", "initializers", "." ]
def _gen_config_function_declaration(self, spec): # type: (ast.IDLAST) -> None """Generate function declarations for config initializers.""" initializer = spec.globals.configs and spec.globals.configs.initializer if not initializer: return if initializer.register: self._writer.write_line( 'Status %s(optionenvironment::OptionSection*);' % (initializer.register)) if initializer.store: self._writer.write_line( 'Status %s(const optionenvironment::Environment&);' % (initializer.store)) if initializer.register or initializer.store: self.write_empty_line()
[ "def", "_gen_config_function_declaration", "(", "self", ",", "spec", ")", ":", "# type: (ast.IDLAST) -> None", "initializer", "=", "spec", ".", "globals", ".", "configs", "and", "spec", ".", "globals", ".", "configs", ".", "initializer", "if", "not", "initializer", ":", "return", "if", "initializer", ".", "register", ":", "self", ".", "_writer", ".", "write_line", "(", "'Status %s(optionenvironment::OptionSection*);'", "%", "(", "initializer", ".", "register", ")", ")", "if", "initializer", ".", "store", ":", "self", ".", "_writer", ".", "write_line", "(", "'Status %s(const optionenvironment::Environment&);'", "%", "(", "initializer", ".", "store", ")", ")", "if", "initializer", ".", "register", "or", "initializer", ".", "store", ":", "self", ".", "write_empty_line", "(", ")" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/idl/idl/generator.py#L799-L815
facebook/ThreatExchange
31914a51820c73c8a0daffe62ccca29a6e3d359e
python-threatexchange/threatexchange/api.py
python
ThreatExchangeAPI.react_to_threat_descriptor
( self, descriptor_id, reaction, *, showURLs=False, dryRun=False )
return self._postThreatDescriptor( "/".join( ( self._base_url, str(descriptor_id), f"?access_token={self.api_token}", ) ), {"reactions": reaction}, showURLs=showURLs, dryRun=dryRun, )
Does a POST to the reactions API. See: https://developers.facebook.com/docs/threat-exchange/reference/reacting
Does a POST to the reactions API.
[ "Does", "a", "POST", "to", "the", "reactions", "API", "." ]
def react_to_threat_descriptor( self, descriptor_id, reaction, *, showURLs=False, dryRun=False ): """ Does a POST to the reactions API. See: https://developers.facebook.com/docs/threat-exchange/reference/reacting """ return self._postThreatDescriptor( "/".join( ( self._base_url, str(descriptor_id), f"?access_token={self.api_token}", ) ), {"reactions": reaction}, showURLs=showURLs, dryRun=dryRun, )
[ "def", "react_to_threat_descriptor", "(", "self", ",", "descriptor_id", ",", "reaction", ",", "*", ",", "showURLs", "=", "False", ",", "dryRun", "=", "False", ")", ":", "return", "self", ".", "_postThreatDescriptor", "(", "\"/\"", ".", "join", "(", "(", "self", ".", "_base_url", ",", "str", "(", "descriptor_id", ")", ",", "f\"?access_token={self.api_token}\"", ",", ")", ")", ",", "{", "\"reactions\"", ":", "reaction", "}", ",", "showURLs", "=", "showURLs", ",", "dryRun", "=", "dryRun", ",", ")" ]
https://github.com/facebook/ThreatExchange/blob/31914a51820c73c8a0daffe62ccca29a6e3d359e/python-threatexchange/threatexchange/api.py#L428-L447
apache/arrow
af33dd1157eb8d7d9bfac25ebf61445b793b7943
dev/archery/archery/cli.py
python
release_curate
(obj, version)
Release curation.
Release curation.
[ "Release", "curation", "." ]
def release_curate(obj, version): """Release curation.""" from .release import Release release = Release.from_jira(version, jira=obj['jira'], repo=obj['repo']) curation = release.curate() click.echo(curation.render('console'))
[ "def", "release_curate", "(", "obj", ",", "version", ")", ":", "from", ".", "release", "import", "Release", "release", "=", "Release", ".", "from_jira", "(", "version", ",", "jira", "=", "obj", "[", "'jira'", "]", ",", "repo", "=", "obj", "[", "'repo'", "]", ")", "curation", "=", "release", ".", "curate", "(", ")", "click", ".", "echo", "(", "curation", ".", "render", "(", "'console'", ")", ")" ]
https://github.com/apache/arrow/blob/af33dd1157eb8d7d9bfac25ebf61445b793b7943/dev/archery/archery/cli.py#L802-L809
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/framework/tensor_shape.py
python
TensorShape.concatenate
(self, other)
Returns the concatenation of the dimension in `self` and `other`. *N.B.* If either `self` or `other` is completely unknown, concatenation will discard information about the other shape. In future, we might support concatenation that preserves this information for use with slicing. Args: other: Another `TensorShape`. Returns: A `TensorShape` whose dimensions are the concatenation of the dimensions in `self` and `other`.
Returns the concatenation of the dimension in `self` and `other`.
[ "Returns", "the", "concatenation", "of", "the", "dimension", "in", "self", "and", "other", "." ]
def concatenate(self, other): """Returns the concatenation of the dimension in `self` and `other`. *N.B.* If either `self` or `other` is completely unknown, concatenation will discard information about the other shape. In future, we might support concatenation that preserves this information for use with slicing. Args: other: Another `TensorShape`. Returns: A `TensorShape` whose dimensions are the concatenation of the dimensions in `self` and `other`. """ # TODO(mrry): Handle the case where we concatenate a known shape with a # completely unknown shape, so that we can use the partial information. other = as_shape(other) if self._dims is None or other.dims is None: return unknown_shape() else: return TensorShape(self._dims + other.dims)
[ "def", "concatenate", "(", "self", ",", "other", ")", ":", "# TODO(mrry): Handle the case where we concatenate a known shape with a", "# completely unknown shape, so that we can use the partial information.", "other", "=", "as_shape", "(", "other", ")", "if", "self", ".", "_dims", "is", "None", "or", "other", ".", "dims", "is", "None", ":", "return", "unknown_shape", "(", ")", "else", ":", "return", "TensorShape", "(", "self", ".", "_dims", "+", "other", ".", "dims", ")" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/framework/tensor_shape.py#L572-L593
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
PyApp.__init__
(self, *args, **kwargs)
__init__(self) -> PyApp Create a new application object, starting the bootstrap process.
__init__(self) -> PyApp
[ "__init__", "(", "self", ")", "-", ">", "PyApp" ]
def __init__(self, *args, **kwargs): """ __init__(self) -> PyApp Create a new application object, starting the bootstrap process. """ _core_.PyApp_swiginit(self,_core_.new_PyApp(*args, **kwargs)) self._setOORInfo(self, False);PyApp._setCallbackInfo(self, self, PyApp);self.this.own(True)
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_core_", ".", "PyApp_swiginit", "(", "self", ",", "_core_", ".", "new_PyApp", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", "self", ".", "_setOORInfo", "(", "self", ",", "False", ")", "PyApp", ".", "_setCallbackInfo", "(", "self", ",", "self", ",", "PyApp", ")", "self", ".", "this", ".", "own", "(", "True", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L7700-L7707
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/training/checkpoint_utils.py
python
list_variables
(ckpt_dir_or_file)
return result
Lists the checkpoint keys and shapes of variables in a checkpoint. Checkpoint keys are paths in a checkpoint graph. Example usage: ```python import tensorflow as tf import os ckpt_directory = "/tmp/training_checkpoints/ckpt" ckpt = tf.train.Checkpoint(optimizer=optimizer, model=model) manager = tf.train.CheckpointManager(ckpt, ckpt_directory, max_to_keep=3) train_and_checkpoint(model, manager) tf.train.list_variables(manager.latest_checkpoint) ``` Args: ckpt_dir_or_file: Directory with checkpoints file or path to checkpoint. Returns: List of tuples `(key, shape)`.
Lists the checkpoint keys and shapes of variables in a checkpoint.
[ "Lists", "the", "checkpoint", "keys", "and", "shapes", "of", "variables", "in", "a", "checkpoint", "." ]
def list_variables(ckpt_dir_or_file): """Lists the checkpoint keys and shapes of variables in a checkpoint. Checkpoint keys are paths in a checkpoint graph. Example usage: ```python import tensorflow as tf import os ckpt_directory = "/tmp/training_checkpoints/ckpt" ckpt = tf.train.Checkpoint(optimizer=optimizer, model=model) manager = tf.train.CheckpointManager(ckpt, ckpt_directory, max_to_keep=3) train_and_checkpoint(model, manager) tf.train.list_variables(manager.latest_checkpoint) ``` Args: ckpt_dir_or_file: Directory with checkpoints file or path to checkpoint. Returns: List of tuples `(key, shape)`. """ reader = load_checkpoint(ckpt_dir_or_file) variable_map = reader.get_variable_to_shape_map() names = sorted(variable_map.keys()) result = [] for name in names: result.append((name, variable_map[name])) return result
[ "def", "list_variables", "(", "ckpt_dir_or_file", ")", ":", "reader", "=", "load_checkpoint", "(", "ckpt_dir_or_file", ")", "variable_map", "=", "reader", ".", "get_variable_to_shape_map", "(", ")", "names", "=", "sorted", "(", "variable_map", ".", "keys", "(", ")", ")", "result", "=", "[", "]", "for", "name", "in", "names", ":", "result", ".", "append", "(", "(", "name", ",", "variable_map", "[", "name", "]", ")", ")", "return", "result" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/training/checkpoint_utils.py#L86-L115
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/mapreduce/mapreduce/operation/db.py
python
Delete.__call__
(self, context)
Perform operation. Args: context: mapreduce context as context.Context.
Perform operation.
[ "Perform", "operation", "." ]
def __call__(self, context): """Perform operation. Args: context: mapreduce context as context.Context. """ context._mutation_pool.delete(self.entity)
[ "def", "__call__", "(", "self", ",", "context", ")", ":", "context", ".", "_mutation_pool", ".", "delete", "(", "self", ".", "entity", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/mapreduce/mapreduce/operation/db.py#L66-L72
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
python/mxnet/rnn/rnn_cell.py
python
BaseRNNCell.unroll
(self, length, inputs, begin_state=None, layout='NTC', merge_outputs=None)
return outputs, states
Unroll an RNN cell across time steps. Parameters ---------- length : int Number of steps to unroll. inputs : Symbol, list of Symbol, or None If `inputs` is a single Symbol (usually the output of Embedding symbol), it should have shape (batch_size, length, ...) if layout == 'NTC', or (length, batch_size, ...) if layout == 'TNC'. If `inputs` is a list of symbols (usually output of previous unroll), they should all have shape (batch_size, ...). begin_state : nested list of Symbol, default None Input states created by `begin_state()` or output state of another cell. Created from `begin_state()` if None. layout : str, optional `layout` of input symbol. Only used if inputs is a single Symbol. merge_outputs : bool, optional If False, return outputs as a list of Symbols. If True, concatenate output across time steps and return a single symbol with shape (batch_size, length, ...) if layout == 'NTC', or (length, batch_size, ...) if layout == 'TNC'. If None, output whatever is faster. Returns ------- outputs : list of Symbol or Symbol Symbol (if `merge_outputs` is True) or list of Symbols (if `merge_outputs` is False) corresponding to the output from the RNN from this unrolling. states : nested list of Symbol The new state of this RNN after this unrolling. The type of this symbol is same as the output of begin_state().
Unroll an RNN cell across time steps.
[ "Unroll", "an", "RNN", "cell", "across", "time", "steps", "." ]
def unroll(self, length, inputs, begin_state=None, layout='NTC', merge_outputs=None): """Unroll an RNN cell across time steps. Parameters ---------- length : int Number of steps to unroll. inputs : Symbol, list of Symbol, or None If `inputs` is a single Symbol (usually the output of Embedding symbol), it should have shape (batch_size, length, ...) if layout == 'NTC', or (length, batch_size, ...) if layout == 'TNC'. If `inputs` is a list of symbols (usually output of previous unroll), they should all have shape (batch_size, ...). begin_state : nested list of Symbol, default None Input states created by `begin_state()` or output state of another cell. Created from `begin_state()` if None. layout : str, optional `layout` of input symbol. Only used if inputs is a single Symbol. merge_outputs : bool, optional If False, return outputs as a list of Symbols. If True, concatenate output across time steps and return a single symbol with shape (batch_size, length, ...) if layout == 'NTC', or (length, batch_size, ...) if layout == 'TNC'. If None, output whatever is faster. Returns ------- outputs : list of Symbol or Symbol Symbol (if `merge_outputs` is True) or list of Symbols (if `merge_outputs` is False) corresponding to the output from the RNN from this unrolling. states : nested list of Symbol The new state of this RNN after this unrolling. The type of this symbol is same as the output of begin_state(). """ self.reset() inputs, _ = _normalize_sequence(length, inputs, layout, False) if begin_state is None: begin_state = self.begin_state() states = begin_state outputs = [] for i in range(length): output, states = self(inputs[i], states) outputs.append(output) outputs, _ = _normalize_sequence(length, outputs, layout, merge_outputs) return outputs, states
[ "def", "unroll", "(", "self", ",", "length", ",", "inputs", ",", "begin_state", "=", "None", ",", "layout", "=", "'NTC'", ",", "merge_outputs", "=", "None", ")", ":", "self", ".", "reset", "(", ")", "inputs", ",", "_", "=", "_normalize_sequence", "(", "length", ",", "inputs", ",", "layout", ",", "False", ")", "if", "begin_state", "is", "None", ":", "begin_state", "=", "self", ".", "begin_state", "(", ")", "states", "=", "begin_state", "outputs", "=", "[", "]", "for", "i", "in", "range", "(", "length", ")", ":", "output", ",", "states", "=", "self", "(", "inputs", "[", "i", "]", ",", "states", ")", "outputs", ".", "append", "(", "output", ")", "outputs", ",", "_", "=", "_normalize_sequence", "(", "length", ",", "outputs", ",", "layout", ",", "merge_outputs", ")", "return", "outputs", ",", "states" ]
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/rnn/rnn_cell.py#L295-L351
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/json_schema_compiler/cpp_util.py
python
Classname
(s)
return '_'.join([x[0].upper() + x[1:] for x in re.split('\W', s)])
Translates a namespace name or function name into something more suited to C++. eg experimental.downloads -> Experimental_Downloads updateAll -> UpdateAll.
Translates a namespace name or function name into something more suited to C++.
[ "Translates", "a", "namespace", "name", "or", "function", "name", "into", "something", "more", "suited", "to", "C", "++", "." ]
def Classname(s): """Translates a namespace name or function name into something more suited to C++. eg experimental.downloads -> Experimental_Downloads updateAll -> UpdateAll. """ return '_'.join([x[0].upper() + x[1:] for x in re.split('\W', s)])
[ "def", "Classname", "(", "s", ")", ":", "return", "'_'", ".", "join", "(", "[", "x", "[", "0", "]", ".", "upper", "(", ")", "+", "x", "[", "1", ":", "]", "for", "x", "in", "re", ".", "split", "(", "'\\W'", ",", "s", ")", "]", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/json_schema_compiler/cpp_util.py#L32-L39
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/mailbox.py
python
_singlefileMailbox._append_message
(self, message)
return offsets
Append message to mailbox and return (start, stop) offsets.
Append message to mailbox and return (start, stop) offsets.
[ "Append", "message", "to", "mailbox", "and", "return", "(", "start", "stop", ")", "offsets", "." ]
def _append_message(self, message): """Append message to mailbox and return (start, stop) offsets.""" self._file.seek(0, 2) before = self._file.tell() if len(self._toc) == 0 and not self._pending: # This is the first message, and the _pre_mailbox_hook # hasn't yet been called. If self._pending is True, # messages have been removed, so _pre_mailbox_hook must # have been called already. self._pre_mailbox_hook(self._file) try: self._pre_message_hook(self._file) offsets = self._install_message(message) self._post_message_hook(self._file) except BaseException: self._file.truncate(before) raise self._file.flush() self._file_length = self._file.tell() # Record current length of mailbox return offsets
[ "def", "_append_message", "(", "self", ",", "message", ")", ":", "self", ".", "_file", ".", "seek", "(", "0", ",", "2", ")", "before", "=", "self", ".", "_file", ".", "tell", "(", ")", "if", "len", "(", "self", ".", "_toc", ")", "==", "0", "and", "not", "self", ".", "_pending", ":", "# This is the first message, and the _pre_mailbox_hook", "# hasn't yet been called. If self._pending is True,", "# messages have been removed, so _pre_mailbox_hook must", "# have been called already.", "self", ".", "_pre_mailbox_hook", "(", "self", ".", "_file", ")", "try", ":", "self", ".", "_pre_message_hook", "(", "self", ".", "_file", ")", "offsets", "=", "self", ".", "_install_message", "(", "message", ")", "self", ".", "_post_message_hook", "(", "self", ".", "_file", ")", "except", "BaseException", ":", "self", ".", "_file", ".", "truncate", "(", "before", ")", "raise", "self", ".", "_file", ".", "flush", "(", ")", "self", ".", "_file_length", "=", "self", ".", "_file", ".", "tell", "(", ")", "# Record current length of mailbox", "return", "offsets" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/mailbox.py#L746-L765
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/richtext.py
python
RichTextCtrl.ClearListStyle
(*args, **kwargs)
return _richtext.RichTextCtrl_ClearListStyle(*args, **kwargs)
ClearListStyle(self, RichTextRange range, int flags=RICHTEXT_SETSTYLE_WITH_UNDO) -> bool
ClearListStyle(self, RichTextRange range, int flags=RICHTEXT_SETSTYLE_WITH_UNDO) -> bool
[ "ClearListStyle", "(", "self", "RichTextRange", "range", "int", "flags", "=", "RICHTEXT_SETSTYLE_WITH_UNDO", ")", "-", ">", "bool" ]
def ClearListStyle(*args, **kwargs): """ClearListStyle(self, RichTextRange range, int flags=RICHTEXT_SETSTYLE_WITH_UNDO) -> bool""" return _richtext.RichTextCtrl_ClearListStyle(*args, **kwargs)
[ "def", "ClearListStyle", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextCtrl_ClearListStyle", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L3188-L3190
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py3/numpy/polynomial/_polybase.py
python
ABCPolyBase.has_samewindow
(self, other)
return np.all(self.window == other.window)
Check if windows match. .. versionadded:: 1.6.0 Parameters ---------- other : class instance The other class must have the ``window`` attribute. Returns ------- bool : boolean True if the windows are the same, False otherwise.
Check if windows match.
[ "Check", "if", "windows", "match", "." ]
def has_samewindow(self, other): """Check if windows match. .. versionadded:: 1.6.0 Parameters ---------- other : class instance The other class must have the ``window`` attribute. Returns ------- bool : boolean True if the windows are the same, False otherwise. """ return np.all(self.window == other.window)
[ "def", "has_samewindow", "(", "self", ",", "other", ")", ":", "return", "np", ".", "all", "(", "self", ".", "window", "==", "other", ".", "window", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/polynomial/_polybase.py#L218-L234
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/spatial/distance.py
python
directed_hausdorff
(u, v, seed=0)
return result
Compute the directed Hausdorff distance between two N-D arrays. Distances between pairs are calculated using a Euclidean metric. Parameters ---------- u : (M,N) ndarray Input array. v : (O,N) ndarray Input array. seed : int or None Local `np.random.RandomState` seed. Default is 0, a random shuffling of u and v that guarantees reproducibility. Returns ------- d : double The directed Hausdorff distance between arrays `u` and `v`, index_1 : int index of point contributing to Hausdorff pair in `u` index_2 : int index of point contributing to Hausdorff pair in `v` Notes ----- Uses the early break technique and the random sampling approach described by [1]_. Although worst-case performance is ``O(m * o)`` (as with the brute force algorithm), this is unlikely in practice as the input data would have to require the algorithm to explore every single point interaction, and after the algorithm shuffles the input points at that. The best case performance is O(m), which is satisfied by selecting an inner loop distance that is less than cmax and leads to an early break as often as possible. The authors have formally shown that the average runtime is closer to O(m). .. versionadded:: 0.19.0 References ---------- .. [1] A. A. Taha and A. Hanbury, "An efficient algorithm for calculating the exact Hausdorff distance." IEEE Transactions On Pattern Analysis And Machine Intelligence, vol. 37 pp. 2153-63, 2015. See Also -------- scipy.spatial.procrustes : Another similarity test for two data sets Examples -------- Find the directed Hausdorff distance between two 2-D arrays of coordinates: >>> from scipy.spatial.distance import directed_hausdorff >>> u = np.array([(1.0, 0.0), ... (0.0, 1.0), ... (-1.0, 0.0), ... (0.0, -1.0)]) >>> v = np.array([(2.0, 0.0), ... (0.0, 2.0), ... (-2.0, 0.0), ... (0.0, -4.0)]) >>> directed_hausdorff(u, v)[0] 2.23606797749979 >>> directed_hausdorff(v, u)[0] 3.0 Find the general (symmetric) Hausdorff distance between two 2-D arrays of coordinates: >>> max(directed_hausdorff(u, v)[0], directed_hausdorff(v, u)[0]) 3.0 Find the indices of the points that generate the Hausdorff distance (the Hausdorff pair): >>> directed_hausdorff(v, u)[1:] (3, 3)
Compute the directed Hausdorff distance between two N-D arrays.
[ "Compute", "the", "directed", "Hausdorff", "distance", "between", "two", "N", "-", "D", "arrays", "." ]
def directed_hausdorff(u, v, seed=0): """ Compute the directed Hausdorff distance between two N-D arrays. Distances between pairs are calculated using a Euclidean metric. Parameters ---------- u : (M,N) ndarray Input array. v : (O,N) ndarray Input array. seed : int or None Local `np.random.RandomState` seed. Default is 0, a random shuffling of u and v that guarantees reproducibility. Returns ------- d : double The directed Hausdorff distance between arrays `u` and `v`, index_1 : int index of point contributing to Hausdorff pair in `u` index_2 : int index of point contributing to Hausdorff pair in `v` Notes ----- Uses the early break technique and the random sampling approach described by [1]_. Although worst-case performance is ``O(m * o)`` (as with the brute force algorithm), this is unlikely in practice as the input data would have to require the algorithm to explore every single point interaction, and after the algorithm shuffles the input points at that. The best case performance is O(m), which is satisfied by selecting an inner loop distance that is less than cmax and leads to an early break as often as possible. The authors have formally shown that the average runtime is closer to O(m). .. versionadded:: 0.19.0 References ---------- .. [1] A. A. Taha and A. Hanbury, "An efficient algorithm for calculating the exact Hausdorff distance." IEEE Transactions On Pattern Analysis And Machine Intelligence, vol. 37 pp. 2153-63, 2015. See Also -------- scipy.spatial.procrustes : Another similarity test for two data sets Examples -------- Find the directed Hausdorff distance between two 2-D arrays of coordinates: >>> from scipy.spatial.distance import directed_hausdorff >>> u = np.array([(1.0, 0.0), ... (0.0, 1.0), ... (-1.0, 0.0), ... (0.0, -1.0)]) >>> v = np.array([(2.0, 0.0), ... (0.0, 2.0), ... (-2.0, 0.0), ... (0.0, -4.0)]) >>> directed_hausdorff(u, v)[0] 2.23606797749979 >>> directed_hausdorff(v, u)[0] 3.0 Find the general (symmetric) Hausdorff distance between two 2-D arrays of coordinates: >>> max(directed_hausdorff(u, v)[0], directed_hausdorff(v, u)[0]) 3.0 Find the indices of the points that generate the Hausdorff distance (the Hausdorff pair): >>> directed_hausdorff(v, u)[1:] (3, 3) """ u = np.asarray(u, dtype=np.float64, order='c') v = np.asarray(v, dtype=np.float64, order='c') result = _hausdorff.directed_hausdorff(u, v, seed) return result
[ "def", "directed_hausdorff", "(", "u", ",", "v", ",", "seed", "=", "0", ")", ":", "u", "=", "np", ".", "asarray", "(", "u", ",", "dtype", "=", "np", ".", "float64", ",", "order", "=", "'c'", ")", "v", "=", "np", ".", "asarray", "(", "v", ",", "dtype", "=", "np", ".", "float64", ",", "order", "=", "'c'", ")", "result", "=", "_hausdorff", ".", "directed_hausdorff", "(", "u", ",", "v", ",", "seed", ")", "return", "result" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/spatial/distance.py#L351-L439
rapidsai/cudf
d5b2448fc69f17509304d594f029d0df56984962
python/cudf/cudf/core/df_protocol.py
python
_CuDFColumn.num_chunks
(self)
return 1
Return the number of chunks the column consists of.
Return the number of chunks the column consists of.
[ "Return", "the", "number", "of", "chunks", "the", "column", "consists", "of", "." ]
def num_chunks(self) -> int: """ Return the number of chunks the column consists of. """ return 1
[ "def", "num_chunks", "(", "self", ")", "->", "int", ":", "return", "1" ]
https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/core/df_protocol.py#L342-L346
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py3/numpy/f2py/f2py2e.py
python
run_compile
()
Do it all in one call!
Do it all in one call!
[ "Do", "it", "all", "in", "one", "call!" ]
def run_compile(): """ Do it all in one call! """ import tempfile i = sys.argv.index('-c') del sys.argv[i] remove_build_dir = 0 try: i = sys.argv.index('--build-dir') except ValueError: i = None if i is not None: build_dir = sys.argv[i + 1] del sys.argv[i + 1] del sys.argv[i] else: remove_build_dir = 1 build_dir = tempfile.mkdtemp() _reg1 = re.compile(r'--link-') sysinfo_flags = [_m for _m in sys.argv[1:] if _reg1.match(_m)] sys.argv = [_m for _m in sys.argv if _m not in sysinfo_flags] if sysinfo_flags: sysinfo_flags = [f[7:] for f in sysinfo_flags] _reg2 = re.compile( r'--((no-|)(wrap-functions|lower)|debug-capi|quiet)|-include') f2py_flags = [_m for _m in sys.argv[1:] if _reg2.match(_m)] sys.argv = [_m for _m in sys.argv if _m not in f2py_flags] f2py_flags2 = [] fl = 0 for a in sys.argv[1:]: if a in ['only:', 'skip:']: fl = 1 elif a == ':': fl = 0 if fl or a == ':': f2py_flags2.append(a) if f2py_flags2 and f2py_flags2[-1] != ':': f2py_flags2.append(':') f2py_flags.extend(f2py_flags2) sys.argv = [_m for _m in sys.argv if _m not in f2py_flags2] _reg3 = re.compile( r'--((f(90)?compiler(-exec|)|compiler)=|help-compiler)') flib_flags = [_m for _m in sys.argv[1:] if _reg3.match(_m)] sys.argv = [_m for _m in sys.argv if _m not in flib_flags] _reg4 = re.compile( r'--((f(77|90)(flags|exec)|opt|arch)=|(debug|noopt|noarch|help-fcompiler))') fc_flags = [_m for _m in sys.argv[1:] if _reg4.match(_m)] sys.argv = [_m for _m in sys.argv if _m not in fc_flags] if 1: del_list = [] for s in flib_flags: v = '--fcompiler=' if s[:len(v)] == v: from numpy.distutils import fcompiler fcompiler.load_all_fcompiler_classes() allowed_keys = list(fcompiler.fcompiler_class.keys()) nv = ov = s[len(v):].lower() if ov not in allowed_keys: vmap = {} # XXX try: nv = vmap[ov] except KeyError: if ov not in vmap.values(): print('Unknown vendor: "%s"' % (s[len(v):])) nv = ov i = flib_flags.index(s) flib_flags[i] = '--fcompiler=' + nv continue for s in del_list: i = flib_flags.index(s) del flib_flags[i] assert len(flib_flags) <= 2, repr(flib_flags) _reg5 = re.compile(r'--(verbose)') setup_flags = [_m for _m in sys.argv[1:] if _reg5.match(_m)] sys.argv = [_m for _m in sys.argv if _m not in setup_flags] if '--quiet' in f2py_flags: setup_flags.append('--quiet') modulename = 'untitled' sources = sys.argv[1:] for optname in ['--include_paths', '--include-paths', '--f2cmap']: if optname in sys.argv: i = sys.argv.index(optname) f2py_flags.extend(sys.argv[i:i + 2]) del sys.argv[i + 1], sys.argv[i] sources = sys.argv[1:] if '-m' in sys.argv: i = sys.argv.index('-m') modulename = sys.argv[i + 1] del sys.argv[i + 1], sys.argv[i] sources = sys.argv[1:] else: from numpy.distutils.command.build_src import get_f2py_modulename pyf_files, sources = filter_files('', '[.]pyf([.]src|)', sources) sources = pyf_files + sources for f in pyf_files: modulename = get_f2py_modulename(f) if modulename: break extra_objects, sources = filter_files('', '[.](o|a|so|dylib)', sources) include_dirs, sources = filter_files('-I', '', sources, remove_prefix=1) library_dirs, sources = filter_files('-L', '', sources, remove_prefix=1) libraries, sources = filter_files('-l', '', sources, remove_prefix=1) undef_macros, sources = filter_files('-U', '', sources, remove_prefix=1) define_macros, sources = filter_files('-D', '', sources, remove_prefix=1) for i in range(len(define_macros)): name_value = define_macros[i].split('=', 1) if len(name_value) == 1: name_value.append(None) if len(name_value) == 2: define_macros[i] = tuple(name_value) else: print('Invalid use of -D:', name_value) from numpy.distutils.system_info import get_info num_info = {} if num_info: include_dirs.extend(num_info.get('include_dirs', [])) from numpy.distutils.core import setup, Extension ext_args = {'name': modulename, 'sources': sources, 'include_dirs': include_dirs, 'library_dirs': library_dirs, 'libraries': libraries, 'define_macros': define_macros, 'undef_macros': undef_macros, 'extra_objects': extra_objects, 'f2py_options': f2py_flags, } if sysinfo_flags: from numpy.distutils.misc_util import dict_append for n in sysinfo_flags: i = get_info(n) if not i: outmess('No %s resources found in system' ' (try `f2py --help-link`)\n' % (repr(n))) dict_append(ext_args, **i) ext = Extension(**ext_args) sys.argv = [sys.argv[0]] + setup_flags sys.argv.extend(['build', '--build-temp', build_dir, '--build-base', build_dir, '--build-platlib', '.', # disable CCompilerOpt '--disable-optimization']) if fc_flags: sys.argv.extend(['config_fc'] + fc_flags) if flib_flags: sys.argv.extend(['build_ext'] + flib_flags) setup(ext_modules=[ext]) if remove_build_dir and os.path.exists(build_dir): import shutil outmess('Removing build directory %s\n' % (build_dir)) shutil.rmtree(build_dir)
[ "def", "run_compile", "(", ")", ":", "import", "tempfile", "i", "=", "sys", ".", "argv", ".", "index", "(", "'-c'", ")", "del", "sys", ".", "argv", "[", "i", "]", "remove_build_dir", "=", "0", "try", ":", "i", "=", "sys", ".", "argv", ".", "index", "(", "'--build-dir'", ")", "except", "ValueError", ":", "i", "=", "None", "if", "i", "is", "not", "None", ":", "build_dir", "=", "sys", ".", "argv", "[", "i", "+", "1", "]", "del", "sys", ".", "argv", "[", "i", "+", "1", "]", "del", "sys", ".", "argv", "[", "i", "]", "else", ":", "remove_build_dir", "=", "1", "build_dir", "=", "tempfile", ".", "mkdtemp", "(", ")", "_reg1", "=", "re", ".", "compile", "(", "r'--link-'", ")", "sysinfo_flags", "=", "[", "_m", "for", "_m", "in", "sys", ".", "argv", "[", "1", ":", "]", "if", "_reg1", ".", "match", "(", "_m", ")", "]", "sys", ".", "argv", "=", "[", "_m", "for", "_m", "in", "sys", ".", "argv", "if", "_m", "not", "in", "sysinfo_flags", "]", "if", "sysinfo_flags", ":", "sysinfo_flags", "=", "[", "f", "[", "7", ":", "]", "for", "f", "in", "sysinfo_flags", "]", "_reg2", "=", "re", ".", "compile", "(", "r'--((no-|)(wrap-functions|lower)|debug-capi|quiet)|-include'", ")", "f2py_flags", "=", "[", "_m", "for", "_m", "in", "sys", ".", "argv", "[", "1", ":", "]", "if", "_reg2", ".", "match", "(", "_m", ")", "]", "sys", ".", "argv", "=", "[", "_m", "for", "_m", "in", "sys", ".", "argv", "if", "_m", "not", "in", "f2py_flags", "]", "f2py_flags2", "=", "[", "]", "fl", "=", "0", "for", "a", "in", "sys", ".", "argv", "[", "1", ":", "]", ":", "if", "a", "in", "[", "'only:'", ",", "'skip:'", "]", ":", "fl", "=", "1", "elif", "a", "==", "':'", ":", "fl", "=", "0", "if", "fl", "or", "a", "==", "':'", ":", "f2py_flags2", ".", "append", "(", "a", ")", "if", "f2py_flags2", "and", "f2py_flags2", "[", "-", "1", "]", "!=", "':'", ":", "f2py_flags2", ".", "append", "(", "':'", ")", "f2py_flags", ".", "extend", "(", "f2py_flags2", ")", "sys", ".", "argv", "=", "[", "_m", "for", "_m", "in", "sys", ".", "argv", "if", "_m", "not", "in", "f2py_flags2", "]", "_reg3", "=", "re", ".", "compile", "(", "r'--((f(90)?compiler(-exec|)|compiler)=|help-compiler)'", ")", "flib_flags", "=", "[", "_m", "for", "_m", "in", "sys", ".", "argv", "[", "1", ":", "]", "if", "_reg3", ".", "match", "(", "_m", ")", "]", "sys", ".", "argv", "=", "[", "_m", "for", "_m", "in", "sys", ".", "argv", "if", "_m", "not", "in", "flib_flags", "]", "_reg4", "=", "re", ".", "compile", "(", "r'--((f(77|90)(flags|exec)|opt|arch)=|(debug|noopt|noarch|help-fcompiler))'", ")", "fc_flags", "=", "[", "_m", "for", "_m", "in", "sys", ".", "argv", "[", "1", ":", "]", "if", "_reg4", ".", "match", "(", "_m", ")", "]", "sys", ".", "argv", "=", "[", "_m", "for", "_m", "in", "sys", ".", "argv", "if", "_m", "not", "in", "fc_flags", "]", "if", "1", ":", "del_list", "=", "[", "]", "for", "s", "in", "flib_flags", ":", "v", "=", "'--fcompiler='", "if", "s", "[", ":", "len", "(", "v", ")", "]", "==", "v", ":", "from", "numpy", ".", "distutils", "import", "fcompiler", "fcompiler", ".", "load_all_fcompiler_classes", "(", ")", "allowed_keys", "=", "list", "(", "fcompiler", ".", "fcompiler_class", ".", "keys", "(", ")", ")", "nv", "=", "ov", "=", "s", "[", "len", "(", "v", ")", ":", "]", ".", "lower", "(", ")", "if", "ov", "not", "in", "allowed_keys", ":", "vmap", "=", "{", "}", "# XXX", "try", ":", "nv", "=", "vmap", "[", "ov", "]", "except", "KeyError", ":", "if", "ov", "not", "in", "vmap", ".", "values", "(", ")", ":", "print", "(", "'Unknown vendor: \"%s\"'", "%", "(", "s", "[", "len", "(", "v", ")", ":", "]", ")", ")", "nv", "=", "ov", "i", "=", "flib_flags", ".", "index", "(", "s", ")", "flib_flags", "[", "i", "]", "=", "'--fcompiler='", "+", "nv", "continue", "for", "s", "in", "del_list", ":", "i", "=", "flib_flags", ".", "index", "(", "s", ")", "del", "flib_flags", "[", "i", "]", "assert", "len", "(", "flib_flags", ")", "<=", "2", ",", "repr", "(", "flib_flags", ")", "_reg5", "=", "re", ".", "compile", "(", "r'--(verbose)'", ")", "setup_flags", "=", "[", "_m", "for", "_m", "in", "sys", ".", "argv", "[", "1", ":", "]", "if", "_reg5", ".", "match", "(", "_m", ")", "]", "sys", ".", "argv", "=", "[", "_m", "for", "_m", "in", "sys", ".", "argv", "if", "_m", "not", "in", "setup_flags", "]", "if", "'--quiet'", "in", "f2py_flags", ":", "setup_flags", ".", "append", "(", "'--quiet'", ")", "modulename", "=", "'untitled'", "sources", "=", "sys", ".", "argv", "[", "1", ":", "]", "for", "optname", "in", "[", "'--include_paths'", ",", "'--include-paths'", ",", "'--f2cmap'", "]", ":", "if", "optname", "in", "sys", ".", "argv", ":", "i", "=", "sys", ".", "argv", ".", "index", "(", "optname", ")", "f2py_flags", ".", "extend", "(", "sys", ".", "argv", "[", "i", ":", "i", "+", "2", "]", ")", "del", "sys", ".", "argv", "[", "i", "+", "1", "]", ",", "sys", ".", "argv", "[", "i", "]", "sources", "=", "sys", ".", "argv", "[", "1", ":", "]", "if", "'-m'", "in", "sys", ".", "argv", ":", "i", "=", "sys", ".", "argv", ".", "index", "(", "'-m'", ")", "modulename", "=", "sys", ".", "argv", "[", "i", "+", "1", "]", "del", "sys", ".", "argv", "[", "i", "+", "1", "]", ",", "sys", ".", "argv", "[", "i", "]", "sources", "=", "sys", ".", "argv", "[", "1", ":", "]", "else", ":", "from", "numpy", ".", "distutils", ".", "command", ".", "build_src", "import", "get_f2py_modulename", "pyf_files", ",", "sources", "=", "filter_files", "(", "''", ",", "'[.]pyf([.]src|)'", ",", "sources", ")", "sources", "=", "pyf_files", "+", "sources", "for", "f", "in", "pyf_files", ":", "modulename", "=", "get_f2py_modulename", "(", "f", ")", "if", "modulename", ":", "break", "extra_objects", ",", "sources", "=", "filter_files", "(", "''", ",", "'[.](o|a|so|dylib)'", ",", "sources", ")", "include_dirs", ",", "sources", "=", "filter_files", "(", "'-I'", ",", "''", ",", "sources", ",", "remove_prefix", "=", "1", ")", "library_dirs", ",", "sources", "=", "filter_files", "(", "'-L'", ",", "''", ",", "sources", ",", "remove_prefix", "=", "1", ")", "libraries", ",", "sources", "=", "filter_files", "(", "'-l'", ",", "''", ",", "sources", ",", "remove_prefix", "=", "1", ")", "undef_macros", ",", "sources", "=", "filter_files", "(", "'-U'", ",", "''", ",", "sources", ",", "remove_prefix", "=", "1", ")", "define_macros", ",", "sources", "=", "filter_files", "(", "'-D'", ",", "''", ",", "sources", ",", "remove_prefix", "=", "1", ")", "for", "i", "in", "range", "(", "len", "(", "define_macros", ")", ")", ":", "name_value", "=", "define_macros", "[", "i", "]", ".", "split", "(", "'='", ",", "1", ")", "if", "len", "(", "name_value", ")", "==", "1", ":", "name_value", ".", "append", "(", "None", ")", "if", "len", "(", "name_value", ")", "==", "2", ":", "define_macros", "[", "i", "]", "=", "tuple", "(", "name_value", ")", "else", ":", "print", "(", "'Invalid use of -D:'", ",", "name_value", ")", "from", "numpy", ".", "distutils", ".", "system_info", "import", "get_info", "num_info", "=", "{", "}", "if", "num_info", ":", "include_dirs", ".", "extend", "(", "num_info", ".", "get", "(", "'include_dirs'", ",", "[", "]", ")", ")", "from", "numpy", ".", "distutils", ".", "core", "import", "setup", ",", "Extension", "ext_args", "=", "{", "'name'", ":", "modulename", ",", "'sources'", ":", "sources", ",", "'include_dirs'", ":", "include_dirs", ",", "'library_dirs'", ":", "library_dirs", ",", "'libraries'", ":", "libraries", ",", "'define_macros'", ":", "define_macros", ",", "'undef_macros'", ":", "undef_macros", ",", "'extra_objects'", ":", "extra_objects", ",", "'f2py_options'", ":", "f2py_flags", ",", "}", "if", "sysinfo_flags", ":", "from", "numpy", ".", "distutils", ".", "misc_util", "import", "dict_append", "for", "n", "in", "sysinfo_flags", ":", "i", "=", "get_info", "(", "n", ")", "if", "not", "i", ":", "outmess", "(", "'No %s resources found in system'", "' (try `f2py --help-link`)\\n'", "%", "(", "repr", "(", "n", ")", ")", ")", "dict_append", "(", "ext_args", ",", "*", "*", "i", ")", "ext", "=", "Extension", "(", "*", "*", "ext_args", ")", "sys", ".", "argv", "=", "[", "sys", ".", "argv", "[", "0", "]", "]", "+", "setup_flags", "sys", ".", "argv", ".", "extend", "(", "[", "'build'", ",", "'--build-temp'", ",", "build_dir", ",", "'--build-base'", ",", "build_dir", ",", "'--build-platlib'", ",", "'.'", ",", "# disable CCompilerOpt", "'--disable-optimization'", "]", ")", "if", "fc_flags", ":", "sys", ".", "argv", ".", "extend", "(", "[", "'config_fc'", "]", "+", "fc_flags", ")", "if", "flib_flags", ":", "sys", ".", "argv", ".", "extend", "(", "[", "'build_ext'", "]", "+", "flib_flags", ")", "setup", "(", "ext_modules", "=", "[", "ext", "]", ")", "if", "remove_build_dir", "and", "os", ".", "path", ".", "exists", "(", "build_dir", ")", ":", "import", "shutil", "outmess", "(", "'Removing build directory %s\\n'", "%", "(", "build_dir", ")", ")", "shutil", ".", "rmtree", "(", "build_dir", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/f2py/f2py2e.py#L492-L662
microsoft/ivy
9f3c7ecc0b2383129fdd0953e10890d98d09a82d
ivy/ivy_parser.py
python
p_optreturns_tsyms
(p)
optreturns : RETURNS LPAREN lparams RPAREN
optreturns : RETURNS LPAREN lparams RPAREN
[ "optreturns", ":", "RETURNS", "LPAREN", "lparams", "RPAREN" ]
def p_optreturns_tsyms(p): 'optreturns : RETURNS LPAREN lparams RPAREN' p[0] = p[3]
[ "def", "p_optreturns_tsyms", "(", "p", ")", ":", "p", "[", "0", "]", "=", "p", "[", "3", "]" ]
https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/ivy_parser.py#L1392-L1394
gv22ga/dlib-face-recognition-android
42d6305cbd85833f2b85bb79b70ab9ab004153c9
tools/lint/cpplint.py
python
NestingState.CheckCompletedBlocks
(self, filename, error)
Checks that all classes and namespaces have been completely parsed. Call this when all lines in a file have been processed. Args: filename: The name of the current file. error: The function to call with any errors found.
Checks that all classes and namespaces have been completely parsed. Call this when all lines in a file have been processed. Args: filename: The name of the current file. error: The function to call with any errors found.
[ "Checks", "that", "all", "classes", "and", "namespaces", "have", "been", "completely", "parsed", ".", "Call", "this", "when", "all", "lines", "in", "a", "file", "have", "been", "processed", ".", "Args", ":", "filename", ":", "The", "name", "of", "the", "current", "file", ".", "error", ":", "The", "function", "to", "call", "with", "any", "errors", "found", "." ]
def CheckCompletedBlocks(self, filename, error): """Checks that all classes and namespaces have been completely parsed. Call this when all lines in a file have been processed. Args: filename: The name of the current file. error: The function to call with any errors found. """ # Note: This test can result in false positives if #ifdef constructs # get in the way of brace matching. See the testBuildClass test in # cpplint_unittest.py for an example of this. for obj in self.stack: if isinstance(obj, _ClassInfo): error(filename, obj.starting_linenum, 'build/class', 5, 'Failed to find complete declaration of class %s' % obj.name) elif isinstance(obj, _NamespaceInfo): error(filename, obj.starting_linenum, 'build/namespaces', 5, 'Failed to find complete declaration of namespace %s' % obj.name)
[ "def", "CheckCompletedBlocks", "(", "self", ",", "filename", ",", "error", ")", ":", "# Note: This test can result in false positives if #ifdef constructs", "# get in the way of brace matching. See the testBuildClass test in", "# cpplint_unittest.py for an example of this.", "for", "obj", "in", "self", ".", "stack", ":", "if", "isinstance", "(", "obj", ",", "_ClassInfo", ")", ":", "error", "(", "filename", ",", "obj", ".", "starting_linenum", ",", "'build/class'", ",", "5", ",", "'Failed to find complete declaration of class %s'", "%", "obj", ".", "name", ")", "elif", "isinstance", "(", "obj", ",", "_NamespaceInfo", ")", ":", "error", "(", "filename", ",", "obj", ".", "starting_linenum", ",", "'build/namespaces'", ",", "5", ",", "'Failed to find complete declaration of namespace %s'", "%", "obj", ".", "name", ")" ]
https://github.com/gv22ga/dlib-face-recognition-android/blob/42d6305cbd85833f2b85bb79b70ab9ab004153c9/tools/lint/cpplint.py#L2528-L2546
Komnomnomnom/swigibpy
cfd307fdbfaffabc69a2dc037538d7e34a8b8daf
swigibpy.py
python
EClientSocketBase.cancelHistoricalData
(self, tickerId)
return _swigibpy.EClientSocketBase_cancelHistoricalData(self, tickerId)
cancelHistoricalData(EClientSocketBase self, TickerId tickerId)
cancelHistoricalData(EClientSocketBase self, TickerId tickerId)
[ "cancelHistoricalData", "(", "EClientSocketBase", "self", "TickerId", "tickerId", ")" ]
def cancelHistoricalData(self, tickerId): """cancelHistoricalData(EClientSocketBase self, TickerId tickerId)""" return _swigibpy.EClientSocketBase_cancelHistoricalData(self, tickerId)
[ "def", "cancelHistoricalData", "(", "self", ",", "tickerId", ")", ":", "return", "_swigibpy", ".", "EClientSocketBase_cancelHistoricalData", "(", "self", ",", "tickerId", ")" ]
https://github.com/Komnomnomnom/swigibpy/blob/cfd307fdbfaffabc69a2dc037538d7e34a8b8daf/swigibpy.py#L1562-L1564
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/generate_stubs/generate_stubs.py
python
PosixStubWriter.__init__
(self, module_name, signatures)
Initializes PosixStubWriter for this set of signatures and module_name. Args: module_name: The name of the module we are writing a stub for. signatures: The list of signature hashes, as produced by ParseSignatures, to create stubs for.
Initializes PosixStubWriter for this set of signatures and module_name.
[ "Initializes", "PosixStubWriter", "for", "this", "set", "of", "signatures", "and", "module_name", "." ]
def __init__(self, module_name, signatures): """Initializes PosixStubWriter for this set of signatures and module_name. Args: module_name: The name of the module we are writing a stub for. signatures: The list of signature hashes, as produced by ParseSignatures, to create stubs for. """ self.signatures = signatures self.module_name = module_name
[ "def", "__init__", "(", "self", ",", "module_name", ",", "signatures", ")", ":", "self", ".", "signatures", "=", "signatures", "self", ".", "module_name", "=", "module_name" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/generate_stubs/generate_stubs.py#L520-L529
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_controls.py
python
HelpEvent.SetTarget
(*args, **kwargs)
return _controls_.HelpEvent_SetTarget(*args, **kwargs)
SetTarget(self, String target) Set an optional target to display help in. E.g. a window specification
SetTarget(self, String target)
[ "SetTarget", "(", "self", "String", "target", ")" ]
def SetTarget(*args, **kwargs): """ SetTarget(self, String target) Set an optional target to display help in. E.g. a window specification """ return _controls_.HelpEvent_SetTarget(*args, **kwargs)
[ "def", "SetTarget", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "HelpEvent_SetTarget", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L6094-L6100
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/ultimatelistctrl.py
python
UltimateListCtrl.SetAGWWindowStyleFlag
(self, style)
Sets the :class:`UltimateListCtrl` AGW-specific style flag. :param `style`: the AGW-specific window style; can be almost any combination of the following bits: =============================== =========== ==================================================================================================== Window Styles Hex Value Description =============================== =========== ==================================================================================================== ``ULC_VRULES`` 0x1 Draws light vertical rules between rows in report mode. ``ULC_HRULES`` 0x2 Draws light horizontal rules between rows in report mode. ``ULC_ICON`` 0x4 Large icon view, with optional labels. ``ULC_SMALL_ICON`` 0x8 Small icon view, with optional labels. ``ULC_LIST`` 0x10 Multicolumn list view, with optional small icons. Columns are computed automatically, i.e. you don't set columns as in ``ULC_REPORT``. In other words, the list wraps, unlike a :class:`ListBox`. ``ULC_REPORT`` 0x20 Single or multicolumn report view, with optional header. ``ULC_ALIGN_TOP`` 0x40 Icons align to the top. Win32 default, Win32 only. ``ULC_ALIGN_LEFT`` 0x80 Icons align to the left. ``ULC_AUTOARRANGE`` 0x100 Icons arrange themselves. Win32 only. ``ULC_VIRTUAL`` 0x200 The application provides items text on demand. May only be used with ``ULC_REPORT``. ``ULC_EDIT_LABELS`` 0x400 Labels are editable: the application will be notified when editing starts. ``ULC_NO_HEADER`` 0x800 No header in report mode. ``ULC_NO_SORT_HEADER`` 0x1000 No Docs. ``ULC_SINGLE_SEL`` 0x2000 Single selection (default is multiple). ``ULC_SORT_ASCENDING`` 0x4000 Sort in ascending order. (You must still supply a comparison callback in :meth:`ListCtrl.SortItems`.) ``ULC_SORT_DESCENDING`` 0x8000 Sort in descending order. (You must still supply a comparison callback in :meth:`ListCtrl.SortItems`.) ``ULC_TILE`` 0x10000 Each item appears as a full-sized icon with a label of one or more lines beside it (partially implemented). ``ULC_NO_HIGHLIGHT`` 0x20000 No highlight when an item is selected. ``ULC_STICKY_HIGHLIGHT`` 0x40000 Items are selected by simply hovering on them, with no need to click on them. ``ULC_STICKY_NOSELEVENT`` 0x80000 Don't send a selection event when using ``ULC_STICKY_HIGHLIGHT`` style. ``ULC_SEND_LEFTCLICK`` 0x100000 Send a left click event when an item is selected. ``ULC_HAS_VARIABLE_ROW_HEIGHT`` 0x200000 The list has variable row heights. ``ULC_AUTO_CHECK_CHILD`` 0x400000 When a column header has a checkbox associated, auto-check all the subitems in that column. ``ULC_AUTO_TOGGLE_CHILD`` 0x800000 When a column header has a checkbox associated, toggle all the subitems in that column. ``ULC_AUTO_CHECK_PARENT`` 0x1000000 Only meaningful foe checkbox-type items: when an item is checked/unchecked its column header item is checked/unchecked as well. ``ULC_SHOW_TOOLTIPS`` 0x2000000 Show tooltips for ellipsized items/subitems (text too long to be shown in the available space) containing the full item/subitem text. ``ULC_HOT_TRACKING`` 0x4000000 Enable hot tracking of items on mouse motion. ``ULC_BORDER_SELECT`` 0x8000000 Changes border colour whan an item is selected, instead of highlighting the item. ``ULC_TRACK_SELECT`` 0x10000000 Enables hot-track selection in a list control. Hot track selection means that an item is automatically selected when the cursor remains over the item for a certain period of time. The delay is retrieved on Windows using the `win32api` call `win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME)`, and is defaulted to 400ms on other platforms. This style applies to all views of `UltimateListCtrl`. ``ULC_HEADER_IN_ALL_VIEWS`` 0x20000000 Show column headers in all view modes. ``ULC_NO_FULL_ROW_SELECT`` 0x40000000 When an item is selected, the only the item in the first column is highlighted. ``ULC_FOOTER`` 0x80000000 Show a footer too (only when header is present). ``ULC_USER_ROW_HEIGHT`` 0x100000000 Allows to set a custom row height (one value for all the items, only in report mode). =============================== =========== ====================================================================================================
Sets the :class:`UltimateListCtrl` AGW-specific style flag.
[ "Sets", "the", ":", "class", ":", "UltimateListCtrl", "AGW", "-", "specific", "style", "flag", "." ]
def SetAGWWindowStyleFlag(self, style): """ Sets the :class:`UltimateListCtrl` AGW-specific style flag. :param `style`: the AGW-specific window style; can be almost any combination of the following bits: =============================== =========== ==================================================================================================== Window Styles Hex Value Description =============================== =========== ==================================================================================================== ``ULC_VRULES`` 0x1 Draws light vertical rules between rows in report mode. ``ULC_HRULES`` 0x2 Draws light horizontal rules between rows in report mode. ``ULC_ICON`` 0x4 Large icon view, with optional labels. ``ULC_SMALL_ICON`` 0x8 Small icon view, with optional labels. ``ULC_LIST`` 0x10 Multicolumn list view, with optional small icons. Columns are computed automatically, i.e. you don't set columns as in ``ULC_REPORT``. In other words, the list wraps, unlike a :class:`ListBox`. ``ULC_REPORT`` 0x20 Single or multicolumn report view, with optional header. ``ULC_ALIGN_TOP`` 0x40 Icons align to the top. Win32 default, Win32 only. ``ULC_ALIGN_LEFT`` 0x80 Icons align to the left. ``ULC_AUTOARRANGE`` 0x100 Icons arrange themselves. Win32 only. ``ULC_VIRTUAL`` 0x200 The application provides items text on demand. May only be used with ``ULC_REPORT``. ``ULC_EDIT_LABELS`` 0x400 Labels are editable: the application will be notified when editing starts. ``ULC_NO_HEADER`` 0x800 No header in report mode. ``ULC_NO_SORT_HEADER`` 0x1000 No Docs. ``ULC_SINGLE_SEL`` 0x2000 Single selection (default is multiple). ``ULC_SORT_ASCENDING`` 0x4000 Sort in ascending order. (You must still supply a comparison callback in :meth:`ListCtrl.SortItems`.) ``ULC_SORT_DESCENDING`` 0x8000 Sort in descending order. (You must still supply a comparison callback in :meth:`ListCtrl.SortItems`.) ``ULC_TILE`` 0x10000 Each item appears as a full-sized icon with a label of one or more lines beside it (partially implemented). ``ULC_NO_HIGHLIGHT`` 0x20000 No highlight when an item is selected. ``ULC_STICKY_HIGHLIGHT`` 0x40000 Items are selected by simply hovering on them, with no need to click on them. ``ULC_STICKY_NOSELEVENT`` 0x80000 Don't send a selection event when using ``ULC_STICKY_HIGHLIGHT`` style. ``ULC_SEND_LEFTCLICK`` 0x100000 Send a left click event when an item is selected. ``ULC_HAS_VARIABLE_ROW_HEIGHT`` 0x200000 The list has variable row heights. ``ULC_AUTO_CHECK_CHILD`` 0x400000 When a column header has a checkbox associated, auto-check all the subitems in that column. ``ULC_AUTO_TOGGLE_CHILD`` 0x800000 When a column header has a checkbox associated, toggle all the subitems in that column. ``ULC_AUTO_CHECK_PARENT`` 0x1000000 Only meaningful foe checkbox-type items: when an item is checked/unchecked its column header item is checked/unchecked as well. ``ULC_SHOW_TOOLTIPS`` 0x2000000 Show tooltips for ellipsized items/subitems (text too long to be shown in the available space) containing the full item/subitem text. ``ULC_HOT_TRACKING`` 0x4000000 Enable hot tracking of items on mouse motion. ``ULC_BORDER_SELECT`` 0x8000000 Changes border colour whan an item is selected, instead of highlighting the item. ``ULC_TRACK_SELECT`` 0x10000000 Enables hot-track selection in a list control. Hot track selection means that an item is automatically selected when the cursor remains over the item for a certain period of time. The delay is retrieved on Windows using the `win32api` call `win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME)`, and is defaulted to 400ms on other platforms. This style applies to all views of `UltimateListCtrl`. ``ULC_HEADER_IN_ALL_VIEWS`` 0x20000000 Show column headers in all view modes. ``ULC_NO_FULL_ROW_SELECT`` 0x40000000 When an item is selected, the only the item in the first column is highlighted. ``ULC_FOOTER`` 0x80000000 Show a footer too (only when header is present). ``ULC_USER_ROW_HEIGHT`` 0x100000000 Allows to set a custom row height (one value for all the items, only in report mode). =============================== =========== ==================================================================================================== """ if style & ULC_HAS_VARIABLE_ROW_HEIGHT and not self.HasAGWFlag(ULC_REPORT): raise Exception("ULC_HAS_VARIABLE_ROW_HEIGHT style can be used only in report mode") wasInReportView = self.HasAGWFlag(ULC_REPORT) self._agwStyle = style if self._mainWin: inReportView = (style & ULC_REPORT) != 0 if inReportView != wasInReportView: # we need to notify the main window about this change as it must # update its data structures self._mainWin.SetReportView(inReportView) self.CreateOrDestroyHeaderWindowAsNeeded() self.CreateOrDestroyFooterWindowAsNeeded() self.GetSizer().Layout() if style & ULC_HAS_VARIABLE_ROW_HEIGHT: self._mainWin.ResetLineDimensions() self._mainWin.ResetVisibleLinesRange() self.Refresh()
[ "def", "SetAGWWindowStyleFlag", "(", "self", ",", "style", ")", ":", "if", "style", "&", "ULC_HAS_VARIABLE_ROW_HEIGHT", "and", "not", "self", ".", "HasAGWFlag", "(", "ULC_REPORT", ")", ":", "raise", "Exception", "(", "\"ULC_HAS_VARIABLE_ROW_HEIGHT style can be used only in report mode\"", ")", "wasInReportView", "=", "self", ".", "HasAGWFlag", "(", "ULC_REPORT", ")", "self", ".", "_agwStyle", "=", "style", "if", "self", ".", "_mainWin", ":", "inReportView", "=", "(", "style", "&", "ULC_REPORT", ")", "!=", "0", "if", "inReportView", "!=", "wasInReportView", ":", "# we need to notify the main window about this change as it must", "# update its data structures", "self", ".", "_mainWin", ".", "SetReportView", "(", "inReportView", ")", "self", ".", "CreateOrDestroyHeaderWindowAsNeeded", "(", ")", "self", ".", "CreateOrDestroyFooterWindowAsNeeded", "(", ")", "self", ".", "GetSizer", "(", ")", ".", "Layout", "(", ")", "if", "style", "&", "ULC_HAS_VARIABLE_ROW_HEIGHT", ":", "self", ".", "_mainWin", ".", "ResetLineDimensions", "(", ")", "self", ".", "_mainWin", ".", "ResetVisibleLinesRange", "(", ")", "self", ".", "Refresh", "(", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L11132-L11201
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/minimum-operations-to-make-a-uni-value-grid.py
python
Solution.minOperations
(self, grid, x)
return sum(abs(v-median)//x for v in nums)
:type grid: List[List[int]] :type x: int :rtype: int
:type grid: List[List[int]] :type x: int :rtype: int
[ ":", "type", "grid", ":", "List", "[", "List", "[", "int", "]]", ":", "type", "x", ":", "int", ":", "rtype", ":", "int" ]
def minOperations(self, grid, x): """ :type grid: List[List[int]] :type x: int :rtype: int """ def nth_element(nums, n, compare=lambda a, b: a < b): def tri_partition(nums, left, right, target, compare): mid = left while mid <= right: if nums[mid] == target: mid += 1 elif compare(nums[mid], target): nums[left], nums[mid] = nums[mid], nums[left] left += 1 mid += 1 else: nums[mid], nums[right] = nums[right], nums[mid] right -= 1 return left, right left, right = 0, len(nums)-1 while left <= right: pivot_idx = random.randint(left, right) pivot_left, pivot_right = tri_partition(nums, left, right, nums[pivot_idx], compare) if pivot_left <= n <= pivot_right: return elif pivot_left > n: right = pivot_left-1 else: # pivot_right < n. left = pivot_right+1 nums = [v for row in grid for v in row] if len(set(v%x for v in nums)) > 1: return -1 nth_element(nums, len(nums)//2) median = nums[len(nums)//2] return sum(abs(v-median)//x for v in nums)
[ "def", "minOperations", "(", "self", ",", "grid", ",", "x", ")", ":", "def", "nth_element", "(", "nums", ",", "n", ",", "compare", "=", "lambda", "a", ",", "b", ":", "a", "<", "b", ")", ":", "def", "tri_partition", "(", "nums", ",", "left", ",", "right", ",", "target", ",", "compare", ")", ":", "mid", "=", "left", "while", "mid", "<=", "right", ":", "if", "nums", "[", "mid", "]", "==", "target", ":", "mid", "+=", "1", "elif", "compare", "(", "nums", "[", "mid", "]", ",", "target", ")", ":", "nums", "[", "left", "]", ",", "nums", "[", "mid", "]", "=", "nums", "[", "mid", "]", ",", "nums", "[", "left", "]", "left", "+=", "1", "mid", "+=", "1", "else", ":", "nums", "[", "mid", "]", ",", "nums", "[", "right", "]", "=", "nums", "[", "right", "]", ",", "nums", "[", "mid", "]", "right", "-=", "1", "return", "left", ",", "right", "left", ",", "right", "=", "0", ",", "len", "(", "nums", ")", "-", "1", "while", "left", "<=", "right", ":", "pivot_idx", "=", "random", ".", "randint", "(", "left", ",", "right", ")", "pivot_left", ",", "pivot_right", "=", "tri_partition", "(", "nums", ",", "left", ",", "right", ",", "nums", "[", "pivot_idx", "]", ",", "compare", ")", "if", "pivot_left", "<=", "n", "<=", "pivot_right", ":", "return", "elif", "pivot_left", ">", "n", ":", "right", "=", "pivot_left", "-", "1", "else", ":", "# pivot_right < n.", "left", "=", "pivot_right", "+", "1", "nums", "=", "[", "v", "for", "row", "in", "grid", "for", "v", "in", "row", "]", "if", "len", "(", "set", "(", "v", "%", "x", "for", "v", "in", "nums", ")", ")", ">", "1", ":", "return", "-", "1", "nth_element", "(", "nums", ",", "len", "(", "nums", ")", "//", "2", ")", "median", "=", "nums", "[", "len", "(", "nums", ")", "//", "2", "]", "return", "sum", "(", "abs", "(", "v", "-", "median", ")", "//", "x", "for", "v", "in", "nums", ")" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/minimum-operations-to-make-a-uni-value-grid.py#L7-L44
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/nn/functional.py
python
gumbel_softmax
(logits: Tensor, tau: float = 1, hard: bool = False, eps: float = 1e-10, dim: int = -1)
return ret
r""" Samples from the Gumbel-Softmax distribution (`Link 1`_ `Link 2`_) and optionally discretizes. Args: logits: `[..., num_features]` unnormalized log probabilities tau: non-negative scalar temperature hard: if ``True``, the returned samples will be discretized as one-hot vectors, but will be differentiated as if it is the soft sample in autograd dim (int): A dimension along which softmax will be computed. Default: -1. Returns: Sampled tensor of same shape as `logits` from the Gumbel-Softmax distribution. If ``hard=True``, the returned samples will be one-hot, otherwise they will be probability distributions that sum to 1 across `dim`. .. note:: This function is here for legacy reasons, may be removed from nn.Functional in the future. .. note:: The main trick for `hard` is to do `y_hard - y_soft.detach() + y_soft` It achieves two things: - makes the output value exactly one-hot (since we add then subtract y_soft value) - makes the gradient equal to y_soft gradient (since we strip all other gradients) Examples:: >>> logits = torch.randn(20, 32) >>> # Sample soft categorical using reparametrization trick: >>> F.gumbel_softmax(logits, tau=1, hard=False) >>> # Sample hard categorical using "Straight-through" trick: >>> F.gumbel_softmax(logits, tau=1, hard=True) .. _Link 1: https://arxiv.org/abs/1611.00712 .. _Link 2: https://arxiv.org/abs/1611.01144
r""" Samples from the Gumbel-Softmax distribution (`Link 1`_ `Link 2`_) and optionally discretizes.
[ "r", "Samples", "from", "the", "Gumbel", "-", "Softmax", "distribution", "(", "Link", "1", "_", "Link", "2", "_", ")", "and", "optionally", "discretizes", "." ]
def gumbel_softmax(logits: Tensor, tau: float = 1, hard: bool = False, eps: float = 1e-10, dim: int = -1) -> Tensor: r""" Samples from the Gumbel-Softmax distribution (`Link 1`_ `Link 2`_) and optionally discretizes. Args: logits: `[..., num_features]` unnormalized log probabilities tau: non-negative scalar temperature hard: if ``True``, the returned samples will be discretized as one-hot vectors, but will be differentiated as if it is the soft sample in autograd dim (int): A dimension along which softmax will be computed. Default: -1. Returns: Sampled tensor of same shape as `logits` from the Gumbel-Softmax distribution. If ``hard=True``, the returned samples will be one-hot, otherwise they will be probability distributions that sum to 1 across `dim`. .. note:: This function is here for legacy reasons, may be removed from nn.Functional in the future. .. note:: The main trick for `hard` is to do `y_hard - y_soft.detach() + y_soft` It achieves two things: - makes the output value exactly one-hot (since we add then subtract y_soft value) - makes the gradient equal to y_soft gradient (since we strip all other gradients) Examples:: >>> logits = torch.randn(20, 32) >>> # Sample soft categorical using reparametrization trick: >>> F.gumbel_softmax(logits, tau=1, hard=False) >>> # Sample hard categorical using "Straight-through" trick: >>> F.gumbel_softmax(logits, tau=1, hard=True) .. _Link 1: https://arxiv.org/abs/1611.00712 .. _Link 2: https://arxiv.org/abs/1611.01144 """ if has_torch_function_unary(logits): return handle_torch_function(gumbel_softmax, (logits,), logits, tau=tau, hard=hard, eps=eps, dim=dim) if eps != 1e-10: warnings.warn("`eps` parameter is deprecated and has no effect.") gumbels = ( -torch.empty_like(logits, memory_format=torch.legacy_contiguous_format).exponential_().log() ) # ~Gumbel(0,1) gumbels = (logits + gumbels) / tau # ~Gumbel(logits,tau) y_soft = gumbels.softmax(dim) if hard: # Straight through. index = y_soft.max(dim, keepdim=True)[1] y_hard = torch.zeros_like(logits, memory_format=torch.legacy_contiguous_format).scatter_(dim, index, 1.0) ret = y_hard - y_soft.detach() + y_soft else: # Reparametrization trick. ret = y_soft return ret
[ "def", "gumbel_softmax", "(", "logits", ":", "Tensor", ",", "tau", ":", "float", "=", "1", ",", "hard", ":", "bool", "=", "False", ",", "eps", ":", "float", "=", "1e-10", ",", "dim", ":", "int", "=", "-", "1", ")", "->", "Tensor", ":", "if", "has_torch_function_unary", "(", "logits", ")", ":", "return", "handle_torch_function", "(", "gumbel_softmax", ",", "(", "logits", ",", ")", ",", "logits", ",", "tau", "=", "tau", ",", "hard", "=", "hard", ",", "eps", "=", "eps", ",", "dim", "=", "dim", ")", "if", "eps", "!=", "1e-10", ":", "warnings", ".", "warn", "(", "\"`eps` parameter is deprecated and has no effect.\"", ")", "gumbels", "=", "(", "-", "torch", ".", "empty_like", "(", "logits", ",", "memory_format", "=", "torch", ".", "legacy_contiguous_format", ")", ".", "exponential_", "(", ")", ".", "log", "(", ")", ")", "# ~Gumbel(0,1)", "gumbels", "=", "(", "logits", "+", "gumbels", ")", "/", "tau", "# ~Gumbel(logits,tau)", "y_soft", "=", "gumbels", ".", "softmax", "(", "dim", ")", "if", "hard", ":", "# Straight through.", "index", "=", "y_soft", ".", "max", "(", "dim", ",", "keepdim", "=", "True", ")", "[", "1", "]", "y_hard", "=", "torch", ".", "zeros_like", "(", "logits", ",", "memory_format", "=", "torch", ".", "legacy_contiguous_format", ")", ".", "scatter_", "(", "dim", ",", "index", ",", "1.0", ")", "ret", "=", "y_hard", "-", "y_soft", ".", "detach", "(", ")", "+", "y_soft", "else", ":", "# Reparametrization trick.", "ret", "=", "y_soft", "return", "ret" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/nn/functional.py#L1824-L1883
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/batch_norm_benchmark.py
python
batch_norm_py
(tensor, mean, variance, beta, gamma, scale)
return nn_impl.batch_normalization(tensor, mean, variance, beta, gamma if scale else None, 0.001)
Python implementation of batch normalization.
Python implementation of batch normalization.
[ "Python", "implementation", "of", "batch", "normalization", "." ]
def batch_norm_py(tensor, mean, variance, beta, gamma, scale): """Python implementation of batch normalization.""" return nn_impl.batch_normalization(tensor, mean, variance, beta, gamma if scale else None, 0.001)
[ "def", "batch_norm_py", "(", "tensor", ",", "mean", ",", "variance", ",", "beta", ",", "gamma", ",", "scale", ")", ":", "return", "nn_impl", ".", "batch_normalization", "(", "tensor", ",", "mean", ",", "variance", ",", "beta", ",", "gamma", "if", "scale", "else", "None", ",", "0.001", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/batch_norm_benchmark.py#L51-L54
tiny-dnn/tiny-dnn
c0f576f5cb7b35893f62127cb7aec18f77a3bcc5
third_party/gemmlowp/meta/generators/zip_Nx8_neon.py
python
GenerateLeftoverLoadAggregateStore
(emitter, leftovers, lanes, output_address)
Handle leftovers when count is not a multiply of 8.
Handle leftovers when count is not a multiply of 8.
[ "Handle", "leftovers", "when", "count", "is", "not", "a", "multiply", "of", "8", "." ]
def GenerateLeftoverLoadAggregateStore(emitter, leftovers, lanes, output_address): """Handle leftovers when count is not a multiply of 8.""" emitter.EmitNewline() emitter.EmitComment('Leftover Load Aggregate Store.') # Clear load registers. for lane in lanes: emitter.EmitVMov('i8', lane.load, emitter.ImmediateConstant(0)) for lane in lanes: emitter.EmitVLoadE(8, leftovers, lane.load, lane.input_address, None) # Aggregate. for lane in lanes: emitter.EmitVAddw('u8', lane.aggregator, lane.aggregator, lane.load) # Store. emitter.EmitVStoreA(1, 8, [lane.load for lane in lanes], emitter.DereferenceIncrement(output_address, 64))
[ "def", "GenerateLeftoverLoadAggregateStore", "(", "emitter", ",", "leftovers", ",", "lanes", ",", "output_address", ")", ":", "emitter", ".", "EmitNewline", "(", ")", "emitter", ".", "EmitComment", "(", "'Leftover Load Aggregate Store.'", ")", "# Clear load registers.", "for", "lane", "in", "lanes", ":", "emitter", ".", "EmitVMov", "(", "'i8'", ",", "lane", ".", "load", ",", "emitter", ".", "ImmediateConstant", "(", "0", ")", ")", "for", "lane", "in", "lanes", ":", "emitter", ".", "EmitVLoadE", "(", "8", ",", "leftovers", ",", "lane", ".", "load", ",", "lane", ".", "input_address", ",", "None", ")", "# Aggregate.", "for", "lane", "in", "lanes", ":", "emitter", ".", "EmitVAddw", "(", "'u8'", ",", "lane", ".", "aggregator", ",", "lane", ".", "aggregator", ",", "lane", ".", "load", ")", "# Store.", "emitter", ".", "EmitVStoreA", "(", "1", ",", "8", ",", "[", "lane", ".", "load", "for", "lane", "in", "lanes", "]", ",", "emitter", ".", "DereferenceIncrement", "(", "output_address", ",", "64", ")", ")" ]
https://github.com/tiny-dnn/tiny-dnn/blob/c0f576f5cb7b35893f62127cb7aec18f77a3bcc5/third_party/gemmlowp/meta/generators/zip_Nx8_neon.py#L84-L103
AngoraFuzzer/Angora
80e81c8590077bc0ac069dbd367da8ce405ff618
llvm_mode/dfsan_rt/sanitizer_common/scripts/cpplint.py
python
_SetVerboseLevel
(level)
return _cpplint_state.SetVerboseLevel(level)
Sets the module's verbosity, and returns the previous setting.
Sets the module's verbosity, and returns the previous setting.
[ "Sets", "the", "module", "s", "verbosity", "and", "returns", "the", "previous", "setting", "." ]
def _SetVerboseLevel(level): """Sets the module's verbosity, and returns the previous setting.""" return _cpplint_state.SetVerboseLevel(level)
[ "def", "_SetVerboseLevel", "(", "level", ")", ":", "return", "_cpplint_state", ".", "SetVerboseLevel", "(", "level", ")" ]
https://github.com/AngoraFuzzer/Angora/blob/80e81c8590077bc0ac069dbd367da8ce405ff618/llvm_mode/dfsan_rt/sanitizer_common/scripts/cpplint.py#L646-L648
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py
python
outputBuffer.htmlNodeDumpFormatOutput
(self, doc, cur, encoding, format)
Dump an HTML node, recursive behaviour,children are printed too.
Dump an HTML node, recursive behaviour,children are printed too.
[ "Dump", "an", "HTML", "node", "recursive", "behaviour", "children", "are", "printed", "too", "." ]
def htmlNodeDumpFormatOutput(self, doc, cur, encoding, format): """Dump an HTML node, recursive behaviour,children are printed too. """ if doc is None: doc__o = None else: doc__o = doc._o if cur is None: cur__o = None else: cur__o = cur._o libxml2mod.htmlNodeDumpFormatOutput(self._o, doc__o, cur__o, encoding, format)
[ "def", "htmlNodeDumpFormatOutput", "(", "self", ",", "doc", ",", "cur", ",", "encoding", ",", "format", ")", ":", "if", "doc", "is", "None", ":", "doc__o", "=", "None", "else", ":", "doc__o", "=", "doc", ".", "_o", "if", "cur", "is", "None", ":", "cur__o", "=", "None", "else", ":", "cur__o", "=", "cur", ".", "_o", "libxml2mod", ".", "htmlNodeDumpFormatOutput", "(", "self", ".", "_o", ",", "doc__o", ",", "cur__o", ",", "encoding", ",", "format", ")" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L5263-L5270
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/constant_op.py
python
_constant_impl
( value, dtype, shape, name, verify_shape, allow_broadcast)
return const_tensor
Implementation of constant.
Implementation of constant.
[ "Implementation", "of", "constant", "." ]
def _constant_impl( value, dtype, shape, name, verify_shape, allow_broadcast): """Implementation of constant.""" ctx = context.context() if ctx.executing_eagerly(): t = convert_to_eager_tensor(value, ctx, dtype) if shape is None: return t shape = tensor_shape.as_shape(shape) if shape == t.shape: return t if verify_shape: raise TypeError("Expected Tensor's shape: %s, got %s." % (tuple(shape), tuple(t.shape))) num_t = t.shape.num_elements() # TODO(josh11b): Implement shape -> eager tensor conversion. if num_t == shape.num_elements(): return _eager_reshape(t, shape.as_list(), ctx) if num_t == 1: if t.dtype == dtypes.bool: # We don't have a Fill kernel for bool dtype on GPU. So we first run # Fill on CPU and then copy to GPU if needed. with ops.device("/device:CPU:0"): x = _eager_fill(shape.as_list(), t.cpu(), ctx) return _eager_identity(x, ctx) else: return _eager_fill(shape.as_list(), t, ctx) raise TypeError("Eager execution of tf.constant with unsupported shape " "(value has %d elements, shape is %s with %d elements)." % (num_t, shape, shape.num_elements())) g = ops.get_default_graph() tensor_value = attr_value_pb2.AttrValue() tensor_value.tensor.CopyFrom( tensor_util.make_tensor_proto( value, dtype=dtype, shape=shape, verify_shape=verify_shape, allow_broadcast=allow_broadcast)) dtype_value = attr_value_pb2.AttrValue(type=tensor_value.tensor.dtype) const_tensor = g.create_op( "Const", [], [dtype_value.type], attrs={"value": tensor_value, "dtype": dtype_value}, name=name).outputs[0] return const_tensor
[ "def", "_constant_impl", "(", "value", ",", "dtype", ",", "shape", ",", "name", ",", "verify_shape", ",", "allow_broadcast", ")", ":", "ctx", "=", "context", ".", "context", "(", ")", "if", "ctx", ".", "executing_eagerly", "(", ")", ":", "t", "=", "convert_to_eager_tensor", "(", "value", ",", "ctx", ",", "dtype", ")", "if", "shape", "is", "None", ":", "return", "t", "shape", "=", "tensor_shape", ".", "as_shape", "(", "shape", ")", "if", "shape", "==", "t", ".", "shape", ":", "return", "t", "if", "verify_shape", ":", "raise", "TypeError", "(", "\"Expected Tensor's shape: %s, got %s.\"", "%", "(", "tuple", "(", "shape", ")", ",", "tuple", "(", "t", ".", "shape", ")", ")", ")", "num_t", "=", "t", ".", "shape", ".", "num_elements", "(", ")", "# TODO(josh11b): Implement shape -> eager tensor conversion.", "if", "num_t", "==", "shape", ".", "num_elements", "(", ")", ":", "return", "_eager_reshape", "(", "t", ",", "shape", ".", "as_list", "(", ")", ",", "ctx", ")", "if", "num_t", "==", "1", ":", "if", "t", ".", "dtype", "==", "dtypes", ".", "bool", ":", "# We don't have a Fill kernel for bool dtype on GPU. So we first run", "# Fill on CPU and then copy to GPU if needed.", "with", "ops", ".", "device", "(", "\"/device:CPU:0\"", ")", ":", "x", "=", "_eager_fill", "(", "shape", ".", "as_list", "(", ")", ",", "t", ".", "cpu", "(", ")", ",", "ctx", ")", "return", "_eager_identity", "(", "x", ",", "ctx", ")", "else", ":", "return", "_eager_fill", "(", "shape", ".", "as_list", "(", ")", ",", "t", ",", "ctx", ")", "raise", "TypeError", "(", "\"Eager execution of tf.constant with unsupported shape \"", "\"(value has %d elements, shape is %s with %d elements).\"", "%", "(", "num_t", ",", "shape", ",", "shape", ".", "num_elements", "(", ")", ")", ")", "g", "=", "ops", ".", "get_default_graph", "(", ")", "tensor_value", "=", "attr_value_pb2", ".", "AttrValue", "(", ")", "tensor_value", ".", "tensor", ".", "CopyFrom", "(", "tensor_util", ".", "make_tensor_proto", "(", "value", ",", "dtype", "=", "dtype", ",", "shape", "=", "shape", ",", "verify_shape", "=", "verify_shape", ",", "allow_broadcast", "=", "allow_broadcast", ")", ")", "dtype_value", "=", "attr_value_pb2", ".", "AttrValue", "(", "type", "=", "tensor_value", ".", "tensor", ".", "dtype", ")", "const_tensor", "=", "g", ".", "create_op", "(", "\"Const\"", ",", "[", "]", ",", "[", "dtype_value", ".", "type", "]", ",", "attrs", "=", "{", "\"value\"", ":", "tensor_value", ",", "\"dtype\"", ":", "dtype_value", "}", ",", "name", "=", "name", ")", ".", "outputs", "[", "0", "]", "return", "const_tensor" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/constant_op.py#L230-L272
lammps/lammps
b75c3065430a75b1b5543a10e10f46d9b4c91913
tools/i-pi/ipi/inputs/forces.py
python
InputForceBeads.store
(self, forceb)
Takes a ForceBeads instance and stores a minimal representation of it. Args: forceb: A ForceBeads object.
Takes a ForceBeads instance and stores a minimal representation of it.
[ "Takes", "a", "ForceBeads", "instance", "and", "stores", "a", "minimal", "representation", "of", "it", "." ]
def store(self, forceb): """Takes a ForceBeads instance and stores a minimal representation of it. Args: forceb: A ForceBeads object. """ Input.store(self,forceb) self.nbeads.store(forceb.nbeads) self.weight.store(forceb.weight)
[ "def", "store", "(", "self", ",", "forceb", ")", ":", "Input", ".", "store", "(", "self", ",", "forceb", ")", "self", ".", "nbeads", ".", "store", "(", "forceb", ".", "nbeads", ")", "self", ".", "weight", ".", "store", "(", "forceb", ".", "weight", ")" ]
https://github.com/lammps/lammps/blob/b75c3065430a75b1b5543a10e10f46d9b4c91913/tools/i-pi/ipi/inputs/forces.py#L55-L64
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/saved_model/function_deserialization.py
python
fix_node_def
(node_def, functions, shared_name_suffix, debug_name)
Replace functions calls and shared names in `node_def`.
Replace functions calls and shared names in `node_def`.
[ "Replace", "functions", "calls", "and", "shared", "names", "in", "node_def", "." ]
def fix_node_def(node_def, functions, shared_name_suffix, debug_name): """Replace functions calls and shared names in `node_def`.""" if "_gradient_op_type" in node_def.attr: if node_def.op in ["StatefulPartitionedCall", "PartitionedCall"]: # TODO(andresp): This code assumes that the gradient registered for this # function call is the default gradient for the function and not a # custom one. fname = node_def.attr["f"].func.name gradient_name = functions[fname]._register_delayed_rewrite_gradient() # pylint: disable=protected-access node_def.attr["_gradient_op_type"].s = compat.as_bytes(gradient_name) else: logging.warning("Importing a function (%s) with ops with custom " "gradients. Will likely fail if a gradient is " "requested.", debug_name) if node_def.op in functions: node_def.op = functions[node_def.op].name for _, attr_value in node_def.attr.items(): if attr_value.func.name: attr_value.func.name = functions[attr_value.func.name].name # Fix old table creation bug. if node_def.op == "HashTableV2": if ("use_node_name_sharing" not in node_def.attr or not node_def.attr["use_node_name_sharing"].b): node_def.attr["use_node_name_sharing"].b = True # We are turning on node mame sharing, so have to make sure we don't # accidentally share a table resource. shared_name_suffix += "_{}".format(ops.uid()) # TODO(b/124205571): Avoid accidental sharing and destruction of restored # resources. For now uniquify "shared_name" when loading functions to avoid # sharing. if "shared_name" in node_def.attr: if node_def.attr["shared_name"].s: node_def.attr["shared_name"].s += compat.as_bytes(shared_name_suffix) else: # Blank shared_name attributes would use the node name, so we'll start # with that when uniquifying. node_def.attr["shared_name"].s = ( compat.as_bytes(node_def.name) + compat.as_bytes(shared_name_suffix))
[ "def", "fix_node_def", "(", "node_def", ",", "functions", ",", "shared_name_suffix", ",", "debug_name", ")", ":", "if", "\"_gradient_op_type\"", "in", "node_def", ".", "attr", ":", "if", "node_def", ".", "op", "in", "[", "\"StatefulPartitionedCall\"", ",", "\"PartitionedCall\"", "]", ":", "# TODO(andresp): This code assumes that the gradient registered for this", "# function call is the default gradient for the function and not a", "# custom one.", "fname", "=", "node_def", ".", "attr", "[", "\"f\"", "]", ".", "func", ".", "name", "gradient_name", "=", "functions", "[", "fname", "]", ".", "_register_delayed_rewrite_gradient", "(", ")", "# pylint: disable=protected-access", "node_def", ".", "attr", "[", "\"_gradient_op_type\"", "]", ".", "s", "=", "compat", ".", "as_bytes", "(", "gradient_name", ")", "else", ":", "logging", ".", "warning", "(", "\"Importing a function (%s) with ops with custom \"", "\"gradients. Will likely fail if a gradient is \"", "\"requested.\"", ",", "debug_name", ")", "if", "node_def", ".", "op", "in", "functions", ":", "node_def", ".", "op", "=", "functions", "[", "node_def", ".", "op", "]", ".", "name", "for", "_", ",", "attr_value", "in", "node_def", ".", "attr", ".", "items", "(", ")", ":", "if", "attr_value", ".", "func", ".", "name", ":", "attr_value", ".", "func", ".", "name", "=", "functions", "[", "attr_value", ".", "func", ".", "name", "]", ".", "name", "# Fix old table creation bug.", "if", "node_def", ".", "op", "==", "\"HashTableV2\"", ":", "if", "(", "\"use_node_name_sharing\"", "not", "in", "node_def", ".", "attr", "or", "not", "node_def", ".", "attr", "[", "\"use_node_name_sharing\"", "]", ".", "b", ")", ":", "node_def", ".", "attr", "[", "\"use_node_name_sharing\"", "]", ".", "b", "=", "True", "# We are turning on node mame sharing, so have to make sure we don't", "# accidentally share a table resource.", "shared_name_suffix", "+=", "\"_{}\"", ".", "format", "(", "ops", ".", "uid", "(", ")", ")", "# TODO(b/124205571): Avoid accidental sharing and destruction of restored", "# resources. For now uniquify \"shared_name\" when loading functions to avoid", "# sharing.", "if", "\"shared_name\"", "in", "node_def", ".", "attr", ":", "if", "node_def", ".", "attr", "[", "\"shared_name\"", "]", ".", "s", ":", "node_def", ".", "attr", "[", "\"shared_name\"", "]", ".", "s", "+=", "compat", ".", "as_bytes", "(", "shared_name_suffix", ")", "else", ":", "# Blank shared_name attributes would use the node name, so we'll start", "# with that when uniquifying.", "node_def", ".", "attr", "[", "\"shared_name\"", "]", ".", "s", "=", "(", "compat", ".", "as_bytes", "(", "node_def", ".", "name", ")", "+", "compat", ".", "as_bytes", "(", "shared_name_suffix", ")", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/saved_model/function_deserialization.py#L363-L402
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/indexes/frozen.py
python
FrozenNDArray.__unicode__
(self)
return "%s(%s, dtype='%s')" % (type(self).__name__, prepr, self.dtype)
Return a string representation for this object. Invoked by unicode(df) in py2 only. Yields a Unicode String in both py2/py3.
Return a string representation for this object.
[ "Return", "a", "string", "representation", "for", "this", "object", "." ]
def __unicode__(self): """ Return a string representation for this object. Invoked by unicode(df) in py2 only. Yields a Unicode String in both py2/py3. """ prepr = pprint_thing(self, escape_chars=('\t', '\r', '\n'), quote_strings=True) return "%s(%s, dtype='%s')" % (type(self).__name__, prepr, self.dtype)
[ "def", "__unicode__", "(", "self", ")", ":", "prepr", "=", "pprint_thing", "(", "self", ",", "escape_chars", "=", "(", "'\\t'", ",", "'\\r'", ",", "'\\n'", ")", ",", "quote_strings", "=", "True", ")", "return", "\"%s(%s, dtype='%s')\"", "%", "(", "type", "(", "self", ")", ".", "__name__", ",", "prepr", ",", "self", ".", "dtype", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/indexes/frozen.py#L152-L161
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/contrib/factorization/python/ops/gmm_ops.py
python
GmmAlgorithm._define_partial_maximization_operation
(self, shard_id, shard)
Computes the partial statistics of the means and covariances. Args: shard_id: current shard id. shard: current data shard, 1 X num_examples X dimensions.
Computes the partial statistics of the means and covariances.
[ "Computes", "the", "partial", "statistics", "of", "the", "means", "and", "covariances", "." ]
def _define_partial_maximization_operation(self, shard_id, shard): """Computes the partial statistics of the means and covariances. Args: shard_id: current shard id. shard: current data shard, 1 X num_examples X dimensions. """ # Soft assignment of each data point to each of the two clusters. self._points_in_k[shard_id] = tf.reduce_sum(self._w[shard_id], 0, keep_dims=True) # Partial means. w_mul_x = tf.expand_dims( tf.matmul(self._w[shard_id], tf.squeeze(shard, [0]), transpose_a=True), 1) self._w_mul_x.append(w_mul_x) # Partial covariances. x = tf.concat(0, [shard for _ in range(self._num_classes)]) x_trans = tf.transpose(x, perm=[0, 2, 1]) x_mul_w = tf.concat(0, [ tf.expand_dims(x_trans[k, :, :] * self._w[shard_id][:, k], 0) for k in range(self._num_classes)]) self._w_mul_x2.append(tf.batch_matmul(x_mul_w, x))
[ "def", "_define_partial_maximization_operation", "(", "self", ",", "shard_id", ",", "shard", ")", ":", "# Soft assignment of each data point to each of the two clusters.", "self", ".", "_points_in_k", "[", "shard_id", "]", "=", "tf", ".", "reduce_sum", "(", "self", ".", "_w", "[", "shard_id", "]", ",", "0", ",", "keep_dims", "=", "True", ")", "# Partial means.", "w_mul_x", "=", "tf", ".", "expand_dims", "(", "tf", ".", "matmul", "(", "self", ".", "_w", "[", "shard_id", "]", ",", "tf", ".", "squeeze", "(", "shard", ",", "[", "0", "]", ")", ",", "transpose_a", "=", "True", ")", ",", "1", ")", "self", ".", "_w_mul_x", ".", "append", "(", "w_mul_x", ")", "# Partial covariances.", "x", "=", "tf", ".", "concat", "(", "0", ",", "[", "shard", "for", "_", "in", "range", "(", "self", ".", "_num_classes", ")", "]", ")", "x_trans", "=", "tf", ".", "transpose", "(", "x", ",", "perm", "=", "[", "0", ",", "2", ",", "1", "]", ")", "x_mul_w", "=", "tf", ".", "concat", "(", "0", ",", "[", "tf", ".", "expand_dims", "(", "x_trans", "[", "k", ",", ":", ",", ":", "]", "*", "self", ".", "_w", "[", "shard_id", "]", "[", ":", ",", "k", "]", ",", "0", ")", "for", "k", "in", "range", "(", "self", ".", "_num_classes", ")", "]", ")", "self", ".", "_w_mul_x2", ".", "append", "(", "tf", ".", "batch_matmul", "(", "x_mul_w", ",", "x", ")", ")" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/factorization/python/ops/gmm_ops.py#L307-L328
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py3/numpy/distutils/fcompiler/gnu.py
python
Gnu95FCompiler.wrap_unlinkable_objects
(self, objects, output_dir, extra_dll_dir)
Convert a set of object files that are not compatible with the default linker, to a file that is compatible.
Convert a set of object files that are not compatible with the default linker, to a file that is compatible.
[ "Convert", "a", "set", "of", "object", "files", "that", "are", "not", "compatible", "with", "the", "default", "linker", "to", "a", "file", "that", "is", "compatible", "." ]
def wrap_unlinkable_objects(self, objects, output_dir, extra_dll_dir): """ Convert a set of object files that are not compatible with the default linker, to a file that is compatible. """ if self.c_compiler.compiler_type == "msvc": # Compile a DLL and return the lib for the DLL as # the object. Also keep track of previous DLLs that # we have compiled so that we can link against them. # If there are .a archives, assume they are self-contained # static libraries, and build separate DLLs for each archives = [] plain_objects = [] for obj in objects: if obj.lower().endswith('.a'): archives.append(obj) else: plain_objects.append(obj) chained_libs = [] chained_dlls = [] for archive in archives[::-1]: lib, dll = self._link_wrapper_lib( [archive], output_dir, extra_dll_dir, chained_dlls=chained_dlls, is_archive=True) chained_libs.insert(0, lib) chained_dlls.insert(0, dll) if not plain_objects: return chained_libs lib, dll = self._link_wrapper_lib( plain_objects, output_dir, extra_dll_dir, chained_dlls=chained_dlls, is_archive=False) return [lib] + chained_libs else: raise ValueError("Unsupported C compiler")
[ "def", "wrap_unlinkable_objects", "(", "self", ",", "objects", ",", "output_dir", ",", "extra_dll_dir", ")", ":", "if", "self", ".", "c_compiler", ".", "compiler_type", "==", "\"msvc\"", ":", "# Compile a DLL and return the lib for the DLL as", "# the object. Also keep track of previous DLLs that", "# we have compiled so that we can link against them.", "# If there are .a archives, assume they are self-contained", "# static libraries, and build separate DLLs for each", "archives", "=", "[", "]", "plain_objects", "=", "[", "]", "for", "obj", "in", "objects", ":", "if", "obj", ".", "lower", "(", ")", ".", "endswith", "(", "'.a'", ")", ":", "archives", ".", "append", "(", "obj", ")", "else", ":", "plain_objects", ".", "append", "(", "obj", ")", "chained_libs", "=", "[", "]", "chained_dlls", "=", "[", "]", "for", "archive", "in", "archives", "[", ":", ":", "-", "1", "]", ":", "lib", ",", "dll", "=", "self", ".", "_link_wrapper_lib", "(", "[", "archive", "]", ",", "output_dir", ",", "extra_dll_dir", ",", "chained_dlls", "=", "chained_dlls", ",", "is_archive", "=", "True", ")", "chained_libs", ".", "insert", "(", "0", ",", "lib", ")", "chained_dlls", ".", "insert", "(", "0", ",", "dll", ")", "if", "not", "plain_objects", ":", "return", "chained_libs", "lib", ",", "dll", "=", "self", ".", "_link_wrapper_lib", "(", "plain_objects", ",", "output_dir", ",", "extra_dll_dir", ",", "chained_dlls", "=", "chained_dlls", ",", "is_archive", "=", "False", ")", "return", "[", "lib", "]", "+", "chained_libs", "else", ":", "raise", "ValueError", "(", "\"Unsupported C compiler\"", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/distutils/fcompiler/gnu.py#L474-L517
kristjankorjus/Replicating-DeepMind
68539394e792b34a4d6b430a2eb73b8b8f91d8db
Hybrid/src/ai/layers.py
python
shared_single
(dim=2)
return theano.shared(np.zeros(shp, dtype='float32'))
Shortcut to create an undefined single precision Theano shared variable.
Shortcut to create an undefined single precision Theano shared variable.
[ "Shortcut", "to", "create", "an", "undefined", "single", "precision", "Theano", "shared", "variable", "." ]
def shared_single(dim=2): """ Shortcut to create an undefined single precision Theano shared variable. """ shp = tuple([1] * dim) return theano.shared(np.zeros(shp, dtype='float32'))
[ "def", "shared_single", "(", "dim", "=", "2", ")", ":", "shp", "=", "tuple", "(", "[", "1", "]", "*", "dim", ")", "return", "theano", ".", "shared", "(", "np", ".", "zeros", "(", "shp", ",", "dtype", "=", "'float32'", ")", ")" ]
https://github.com/kristjankorjus/Replicating-DeepMind/blob/68539394e792b34a4d6b430a2eb73b8b8f91d8db/Hybrid/src/ai/layers.py#L296-L301
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/wsgiref/handlers.py
python
BaseHandler.setup_environ
(self)
Set up the environment for one request
Set up the environment for one request
[ "Set", "up", "the", "environment", "for", "one", "request" ]
def setup_environ(self): """Set up the environment for one request""" env = self.environ = self.os_environ.copy() self.add_cgi_vars() env['wsgi.input'] = self.get_stdin() env['wsgi.errors'] = self.get_stderr() env['wsgi.version'] = self.wsgi_version env['wsgi.run_once'] = self.wsgi_run_once env['wsgi.url_scheme'] = self.get_scheme() env['wsgi.multithread'] = self.wsgi_multithread env['wsgi.multiprocess'] = self.wsgi_multiprocess if self.wsgi_file_wrapper is not None: env['wsgi.file_wrapper'] = self.wsgi_file_wrapper if self.origin_server and self.server_software: env.setdefault('SERVER_SOFTWARE',self.server_software)
[ "def", "setup_environ", "(", "self", ")", ":", "env", "=", "self", ".", "environ", "=", "self", ".", "os_environ", ".", "copy", "(", ")", "self", ".", "add_cgi_vars", "(", ")", "env", "[", "'wsgi.input'", "]", "=", "self", ".", "get_stdin", "(", ")", "env", "[", "'wsgi.errors'", "]", "=", "self", ".", "get_stderr", "(", ")", "env", "[", "'wsgi.version'", "]", "=", "self", ".", "wsgi_version", "env", "[", "'wsgi.run_once'", "]", "=", "self", ".", "wsgi_run_once", "env", "[", "'wsgi.url_scheme'", "]", "=", "self", ".", "get_scheme", "(", ")", "env", "[", "'wsgi.multithread'", "]", "=", "self", ".", "wsgi_multithread", "env", "[", "'wsgi.multiprocess'", "]", "=", "self", ".", "wsgi_multiprocess", "if", "self", ".", "wsgi_file_wrapper", "is", "not", "None", ":", "env", "[", "'wsgi.file_wrapper'", "]", "=", "self", ".", "wsgi_file_wrapper", "if", "self", ".", "origin_server", "and", "self", ".", "server_software", ":", "env", ".", "setdefault", "(", "'SERVER_SOFTWARE'", ",", "self", ".", "server_software", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/wsgiref/handlers.py#L96-L114
hszhao/PSPNet
cf7e5a99ba37e46118026e96be5821a9bc63bde0
scripts/cpp_lint.py
python
FindNextMultiLineCommentStart
(lines, lineix)
return len(lines)
Find the beginning marker for a multiline comment.
Find the beginning marker for a multiline comment.
[ "Find", "the", "beginning", "marker", "for", "a", "multiline", "comment", "." ]
def FindNextMultiLineCommentStart(lines, lineix): """Find the beginning marker for a multiline comment.""" while lineix < len(lines): if lines[lineix].strip().startswith('/*'): # Only return this marker if the comment goes beyond this line if lines[lineix].strip().find('*/', 2) < 0: return lineix lineix += 1 return len(lines)
[ "def", "FindNextMultiLineCommentStart", "(", "lines", ",", "lineix", ")", ":", "while", "lineix", "<", "len", "(", "lines", ")", ":", "if", "lines", "[", "lineix", "]", ".", "strip", "(", ")", ".", "startswith", "(", "'/*'", ")", ":", "# Only return this marker if the comment goes beyond this line", "if", "lines", "[", "lineix", "]", ".", "strip", "(", ")", ".", "find", "(", "'*/'", ",", "2", ")", "<", "0", ":", "return", "lineix", "lineix", "+=", "1", "return", "len", "(", "lines", ")" ]
https://github.com/hszhao/PSPNet/blob/cf7e5a99ba37e46118026e96be5821a9bc63bde0/scripts/cpp_lint.py#L1123-L1131
google/syzygy
8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5
third_party/numpy/files/numpy/core/fromnumeric.py
python
round_
(a, decimals=0, out=None)
return round(decimals, out)
Round an array to the given number of decimals. Refer to `around` for full documentation. See Also -------- around : equivalent function
Round an array to the given number of decimals.
[ "Round", "an", "array", "to", "the", "given", "number", "of", "decimals", "." ]
def round_(a, decimals=0, out=None): """ Round an array to the given number of decimals. Refer to `around` for full documentation. See Also -------- around : equivalent function """ try: round = a.round except AttributeError: return _wrapit(a, 'round', decimals, out) return round(decimals, out)
[ "def", "round_", "(", "a", ",", "decimals", "=", "0", ",", "out", "=", "None", ")", ":", "try", ":", "round", "=", "a", ".", "round", "except", "AttributeError", ":", "return", "_wrapit", "(", "a", ",", "'round'", ",", "decimals", ",", "out", ")", "return", "round", "(", "decimals", ",", "out", ")" ]
https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/core/fromnumeric.py#L2281-L2296
facebookincubator/profilo
d3a275d0e7897cc4e3507d543459f3227e85c67f
python/profilo/workflow_demo.py
python
syscounters
(tracefile, args)
Parse system counter information from a trace file, sort by increasing timestamp order, and plot as a time series.
Parse system counter information from a trace file, sort by increasing timestamp order, and plot as a time series.
[ "Parse", "system", "counter", "information", "from", "a", "trace", "file", "sort", "by", "increasing", "timestamp", "order", "and", "plot", "as", "a", "time", "series", "." ]
def syscounters(tracefile, args): """ Parse system counter information from a trace file, sort by increasing timestamp order, and plot as a time series. """ plotdir = os.path.join(args.plotdir, "") # Validate output directory actually exists if not os.path.exists(args.plotdir): print("syscounters: {plt}: no such file or directory".format(plt=args.plotdir)) sys.exit(2) interpreter = TraceFileInterpreter(tracefile) trace = interpreter.interpret() counters = defaultdict(lambda: []) # counter_type -> [(timestamp, counter)] for unit in trace.executionUnits.values(): for block_id in unit.blocks: block = trace.blocks[block_id] for point in block.points: counter = point.properties.counterProps.get(tt.CounterUnit.ITEMS, None) if not counter: continue for counterType, count in counter.items(): counters[counterType].append((point.timestamp, count)) for counterType, series in counters.items(): counters[counterType] = rescale(counters[counterType]) counters[counterType].sort(key=lambda x: x[0]) # Now <counters> is a time series for each counter type. We can plot a few # of them. Plotting other time series is just a matter of adding here # any counter from the list in python/profilo/importer/constants.py import matplotlib.pyplot as plt test_counters = [ "NUM_PROCS", "PROC_CPU_TIME", "GLOBAL_ALLOC_SIZE", "ALLOC_FREE_BYTES", ] for tc in test_counters: data = counters[tc] x, y = list(zip(*data)) plt.xlabel("time") plt.ylabel(tc.lower()) plt.plot(x, y) plt.axis([min(x), max(x), min(y), max(y)]) plt.savefig(plotdir + tc.lower()) plt.clf()
[ "def", "syscounters", "(", "tracefile", ",", "args", ")", ":", "plotdir", "=", "os", ".", "path", ".", "join", "(", "args", ".", "plotdir", ",", "\"\"", ")", "# Validate output directory actually exists", "if", "not", "os", ".", "path", ".", "exists", "(", "args", ".", "plotdir", ")", ":", "print", "(", "\"syscounters: {plt}: no such file or directory\"", ".", "format", "(", "plt", "=", "args", ".", "plotdir", ")", ")", "sys", ".", "exit", "(", "2", ")", "interpreter", "=", "TraceFileInterpreter", "(", "tracefile", ")", "trace", "=", "interpreter", ".", "interpret", "(", ")", "counters", "=", "defaultdict", "(", "lambda", ":", "[", "]", ")", "# counter_type -> [(timestamp, counter)]", "for", "unit", "in", "trace", ".", "executionUnits", ".", "values", "(", ")", ":", "for", "block_id", "in", "unit", ".", "blocks", ":", "block", "=", "trace", ".", "blocks", "[", "block_id", "]", "for", "point", "in", "block", ".", "points", ":", "counter", "=", "point", ".", "properties", ".", "counterProps", ".", "get", "(", "tt", ".", "CounterUnit", ".", "ITEMS", ",", "None", ")", "if", "not", "counter", ":", "continue", "for", "counterType", ",", "count", "in", "counter", ".", "items", "(", ")", ":", "counters", "[", "counterType", "]", ".", "append", "(", "(", "point", ".", "timestamp", ",", "count", ")", ")", "for", "counterType", ",", "series", "in", "counters", ".", "items", "(", ")", ":", "counters", "[", "counterType", "]", "=", "rescale", "(", "counters", "[", "counterType", "]", ")", "counters", "[", "counterType", "]", ".", "sort", "(", "key", "=", "lambda", "x", ":", "x", "[", "0", "]", ")", "# Now <counters> is a time series for each counter type. We can plot a few", "# of them. Plotting other time series is just a matter of adding here", "# any counter from the list in python/profilo/importer/constants.py", "import", "matplotlib", ".", "pyplot", "as", "plt", "test_counters", "=", "[", "\"NUM_PROCS\"", ",", "\"PROC_CPU_TIME\"", ",", "\"GLOBAL_ALLOC_SIZE\"", ",", "\"ALLOC_FREE_BYTES\"", ",", "]", "for", "tc", "in", "test_counters", ":", "data", "=", "counters", "[", "tc", "]", "x", ",", "y", "=", "list", "(", "zip", "(", "*", "data", ")", ")", "plt", ".", "xlabel", "(", "\"time\"", ")", "plt", ".", "ylabel", "(", "tc", ".", "lower", "(", ")", ")", "plt", ".", "plot", "(", "x", ",", "y", ")", "plt", ".", "axis", "(", "[", "min", "(", "x", ")", ",", "max", "(", "x", ")", ",", "min", "(", "y", ")", ",", "max", "(", "y", ")", "]", ")", "plt", ".", "savefig", "(", "plotdir", "+", "tc", ".", "lower", "(", ")", ")", "plt", ".", "clf", "(", ")" ]
https://github.com/facebookincubator/profilo/blob/d3a275d0e7897cc4e3507d543459f3227e85c67f/python/profilo/workflow_demo.py#L125-L175
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/extern/aui/aui_utilities.py
python
DrawMACCloseButton
(colour, backColour=None)
return bmp
Draws the wxMAC tab close button using :class:`GraphicsContext`. :param Colour `colour`: the colour to use to draw the circle; :param Colour `backColour`: the optional background colour for the circle.
Draws the wxMAC tab close button using :class:`GraphicsContext`.
[ "Draws", "the", "wxMAC", "tab", "close", "button", "using", ":", "class", ":", "GraphicsContext", "." ]
def DrawMACCloseButton(colour, backColour=None): """ Draws the wxMAC tab close button using :class:`GraphicsContext`. :param Colour `colour`: the colour to use to draw the circle; :param Colour `backColour`: the optional background colour for the circle. """ bmp = wx.EmptyBitmapRGBA(16, 16) dc = wx.MemoryDC() dc.SelectObject(bmp) gc = wx.GraphicsContext.Create(dc) gc.SetBrush(wx.Brush(colour)) path = gc.CreatePath() path.AddCircle(6.5, 7, 6.5) path.CloseSubpath() gc.FillPath(path) path = gc.CreatePath() if backColour is not None: pen = wx.Pen(backColour, 2) else: pen = wx.Pen("white", 2) pen.SetCap(wx.CAP_BUTT) pen.SetJoin(wx.JOIN_BEVEL) gc.SetPen(pen) path.MoveToPoint(3.5, 4) path.AddLineToPoint(9.5, 10) path.MoveToPoint(3.5, 10) path.AddLineToPoint(9.5, 4) path.CloseSubpath() gc.DrawPath(path) dc.SelectObject(wx.NullBitmap) return bmp
[ "def", "DrawMACCloseButton", "(", "colour", ",", "backColour", "=", "None", ")", ":", "bmp", "=", "wx", ".", "EmptyBitmapRGBA", "(", "16", ",", "16", ")", "dc", "=", "wx", ".", "MemoryDC", "(", ")", "dc", ".", "SelectObject", "(", "bmp", ")", "gc", "=", "wx", ".", "GraphicsContext", ".", "Create", "(", "dc", ")", "gc", ".", "SetBrush", "(", "wx", ".", "Brush", "(", "colour", ")", ")", "path", "=", "gc", ".", "CreatePath", "(", ")", "path", ".", "AddCircle", "(", "6.5", ",", "7", ",", "6.5", ")", "path", ".", "CloseSubpath", "(", ")", "gc", ".", "FillPath", "(", "path", ")", "path", "=", "gc", ".", "CreatePath", "(", ")", "if", "backColour", "is", "not", "None", ":", "pen", "=", "wx", ".", "Pen", "(", "backColour", ",", "2", ")", "else", ":", "pen", "=", "wx", ".", "Pen", "(", "\"white\"", ",", "2", ")", "pen", ".", "SetCap", "(", "wx", ".", "CAP_BUTT", ")", "pen", ".", "SetJoin", "(", "wx", ".", "JOIN_BEVEL", ")", "gc", ".", "SetPen", "(", "pen", ")", "path", ".", "MoveToPoint", "(", "3.5", ",", "4", ")", "path", ".", "AddLineToPoint", "(", "9.5", ",", "10", ")", "path", ".", "MoveToPoint", "(", "3.5", ",", "10", ")", "path", ".", "AddLineToPoint", "(", "9.5", ",", "4", ")", "path", ".", "CloseSubpath", "(", ")", "gc", ".", "DrawPath", "(", "path", ")", "dc", ".", "SelectObject", "(", "wx", ".", "NullBitmap", ")", "return", "bmp" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/aui_utilities.py#L295-L331
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
src/pybind/mgr/rbd_support/module.py
python
Module.task_add_remove
(self, image_spec: str)
Remove an image asynchronously in the background
Remove an image asynchronously in the background
[ "Remove", "an", "image", "asynchronously", "in", "the", "background" ]
def task_add_remove(self, image_spec: str) -> Tuple[int, str, str]: """ Remove an image asynchronously in the background """ with self.task.lock: return self.task.queue_remove(image_spec)
[ "def", "task_add_remove", "(", "self", ",", "image_spec", ":", "str", ")", "->", "Tuple", "[", "int", ",", "str", ",", "str", "]", ":", "with", "self", ".", "task", ".", "lock", ":", "return", "self", ".", "task", ".", "queue_remove", "(", "image_spec", ")" ]
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/pybind/mgr/rbd_support/module.py#L163-L168
unicode-org/icu
2f8749a026f3ddc8cf54d4622480b7c543bb7fc0
tools/unicode/py/preparseucd.py
python
CopyAndStrip
(s, t)
return CopyAndStripWithOptionalMerge(s, t, False)
Copies a file and removes comments behind data lines but not in others.
Copies a file and removes comments behind data lines but not in others.
[ "Copies", "a", "file", "and", "removes", "comments", "behind", "data", "lines", "but", "not", "in", "others", "." ]
def CopyAndStrip(s, t): """Copies a file and removes comments behind data lines but not in others.""" return CopyAndStripWithOptionalMerge(s, t, False)
[ "def", "CopyAndStrip", "(", "s", ",", "t", ")", ":", "return", "CopyAndStripWithOptionalMerge", "(", "s", ",", "t", ",", "False", ")" ]
https://github.com/unicode-org/icu/blob/2f8749a026f3ddc8cf54d4622480b7c543bb7fc0/tools/unicode/py/preparseucd.py#L1582-L1584
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/meta_graph_transform/meta_graph_transform.py
python
_get_single_node_name_from_collection
(meta_graph_def, collection_key)
return collection.node_list.value[0]
Obtain a node name that is the single element of a collection.
Obtain a node name that is the single element of a collection.
[ "Obtain", "a", "node", "name", "that", "is", "the", "single", "element", "of", "a", "collection", "." ]
def _get_single_node_name_from_collection(meta_graph_def, collection_key): """Obtain a node name that is the single element of a collection.""" if collection_key not in meta_graph_def.collection_def: return None collection = meta_graph_def.collection_def[collection_key] if not collection.node_list.value: raise ValueError( 'Collection {} is present but type is not node_list.'.format( collection_key)) if len(collection.node_list.value) != 1: raise ValueError( 'Collection {} is has {} elements; expected exactly one.'.format( collection_key, collection.bytes_list)) return collection.node_list.value[0]
[ "def", "_get_single_node_name_from_collection", "(", "meta_graph_def", ",", "collection_key", ")", ":", "if", "collection_key", "not", "in", "meta_graph_def", ".", "collection_def", ":", "return", "None", "collection", "=", "meta_graph_def", ".", "collection_def", "[", "collection_key", "]", "if", "not", "collection", ".", "node_list", ".", "value", ":", "raise", "ValueError", "(", "'Collection {} is present but type is not node_list.'", ".", "format", "(", "collection_key", ")", ")", "if", "len", "(", "collection", ".", "node_list", ".", "value", ")", "!=", "1", ":", "raise", "ValueError", "(", "'Collection {} is has {} elements; expected exactly one.'", ".", "format", "(", "collection_key", ",", "collection", ".", "bytes_list", ")", ")", "return", "collection", ".", "node_list", ".", "value", "[", "0", "]" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/meta_graph_transform/meta_graph_transform.py#L572-L585
intel/llvm
e6d0547e9d99b5a56430c4749f6c7e328bf221ab
clang/tools/scan-build-py/lib/libscanbuild/intercept.py
python
write_exec_trace
(filename, entry)
Write execution report file. This method shall be sync with the execution report writer in interception library. The entry in the file is a JSON objects. :param filename: path to the output execution trace file, :param entry: the Execution object to append to that file.
Write execution report file.
[ "Write", "execution", "report", "file", "." ]
def write_exec_trace(filename, entry): """ Write execution report file. This method shall be sync with the execution report writer in interception library. The entry in the file is a JSON objects. :param filename: path to the output execution trace file, :param entry: the Execution object to append to that file. """ with open(filename, 'ab') as handler: pid = str(entry.pid) command = US.join(entry.cmd) + US content = RS.join([pid, pid, 'wrapper', entry.cwd, command]) + GS handler.write(content.encode('utf-8'))
[ "def", "write_exec_trace", "(", "filename", ",", "entry", ")", ":", "with", "open", "(", "filename", ",", "'ab'", ")", "as", "handler", ":", "pid", "=", "str", "(", "entry", ".", "pid", ")", "command", "=", "US", ".", "join", "(", "entry", ".", "cmd", ")", "+", "US", "content", "=", "RS", ".", "join", "(", "[", "pid", ",", "pid", ",", "'wrapper'", ",", "entry", ".", "cwd", ",", "command", "]", ")", "+", "GS", "handler", ".", "write", "(", "content", ".", "encode", "(", "'utf-8'", ")", ")" ]
https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/clang/tools/scan-build-py/lib/libscanbuild/intercept.py#L167-L180
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TIntIntVH.Load
(self, *args)
return _snap.TIntIntVH_Load(self, *args)
Load(TIntIntVH self, TSIn SIn) Parameters: SIn: TSIn &
Load(TIntIntVH self, TSIn SIn)
[ "Load", "(", "TIntIntVH", "self", "TSIn", "SIn", ")" ]
def Load(self, *args): """ Load(TIntIntVH self, TSIn SIn) Parameters: SIn: TSIn & """ return _snap.TIntIntVH_Load(self, *args)
[ "def", "Load", "(", "self", ",", "*", "args", ")", ":", "return", "_snap", ".", "TIntIntVH_Load", "(", "self", ",", "*", "args", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L17664-L17672
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/mailbox.py
python
Mailbox.discard
(self, key)
If the keyed message exists, remove it.
If the keyed message exists, remove it.
[ "If", "the", "keyed", "message", "exists", "remove", "it", "." ]
def discard(self, key): """If the keyed message exists, remove it.""" try: self.remove(key) except KeyError: pass
[ "def", "discard", "(", "self", ",", "key", ")", ":", "try", ":", "self", ".", "remove", "(", "key", ")", "except", "KeyError", ":", "pass" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/mailbox.py#L61-L66
neilogd/Engine
58fe0eed517b894e67dd646f0f5adfe328e129fb
3rdparty/jsoncpp/makerelease.py
python
check_no_pending_commit
()
return '\n'.join(msg)
Checks that there is no pending commit in the sandbox.
Checks that there is no pending commit in the sandbox.
[ "Checks", "that", "there", "is", "no", "pending", "commit", "in", "the", "sandbox", "." ]
def check_no_pending_commit(): """Checks that there is no pending commit in the sandbox.""" stdout = svn_command('status', '--xml') etree = ElementTree.fromstring(stdout) msg = [] for entry in etree.getiterator('entry'): path = entry.get('path') status = entry.find('wc-status').get('item') if status != 'unversioned' and path != 'version': msg.append('File "%s" has pending change (status="%s")' % (path, status)) if msg: msg.insert(0, 'Pending change to commit found in sandbox. Commit them first!') return '\n'.join(msg)
[ "def", "check_no_pending_commit", "(", ")", ":", "stdout", "=", "svn_command", "(", "'status'", ",", "'--xml'", ")", "etree", "=", "ElementTree", ".", "fromstring", "(", "stdout", ")", "msg", "=", "[", "]", "for", "entry", "in", "etree", ".", "getiterator", "(", "'entry'", ")", ":", "path", "=", "entry", ".", "get", "(", "'path'", ")", "status", "=", "entry", ".", "find", "(", "'wc-status'", ")", ".", "get", "(", "'item'", ")", "if", "status", "!=", "'unversioned'", "and", "path", "!=", "'version'", ":", "msg", ".", "append", "(", "'File \"%s\" has pending change (status=\"%s\")'", "%", "(", "path", ",", "status", ")", ")", "if", "msg", ":", "msg", ".", "insert", "(", "0", ",", "'Pending change to commit found in sandbox. Commit them first!'", ")", "return", "'\\n'", ".", "join", "(", "msg", ")" ]
https://github.com/neilogd/Engine/blob/58fe0eed517b894e67dd646f0f5adfe328e129fb/3rdparty/jsoncpp/makerelease.py#L67-L79
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/richtext.py
python
RichTextParagraphLayoutBox.UpdateRanges
(*args, **kwargs)
return _richtext.RichTextParagraphLayoutBox_UpdateRanges(*args, **kwargs)
UpdateRanges(self)
UpdateRanges(self)
[ "UpdateRanges", "(", "self", ")" ]
def UpdateRanges(*args, **kwargs): """UpdateRanges(self)""" return _richtext.RichTextParagraphLayoutBox_UpdateRanges(*args, **kwargs)
[ "def", "UpdateRanges", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextParagraphLayoutBox_UpdateRanges", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L1826-L1828
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/prompt-toolkit/py3/prompt_toolkit/application/application.py
python
Application.get_used_style_strings
(self)
return []
Return a list of used style strings. This is helpful for debugging, and for writing a new `Style`.
Return a list of used style strings. This is helpful for debugging, and for writing a new `Style`.
[ "Return", "a", "list", "of", "used", "style", "strings", ".", "This", "is", "helpful", "for", "debugging", "and", "for", "writing", "a", "new", "Style", "." ]
def get_used_style_strings(self) -> List[str]: """ Return a list of used style strings. This is helpful for debugging, and for writing a new `Style`. """ attrs_for_style = self.renderer._attrs_for_style if attrs_for_style: return sorted( [ re.sub(r"\s+", " ", style_str).strip() for style_str in attrs_for_style.keys() ] ) return []
[ "def", "get_used_style_strings", "(", "self", ")", "->", "List", "[", "str", "]", ":", "attrs_for_style", "=", "self", ".", "renderer", ".", "_attrs_for_style", "if", "attrs_for_style", ":", "return", "sorted", "(", "[", "re", ".", "sub", "(", "r\"\\s+\"", ",", "\" \"", ",", "style_str", ")", ".", "strip", "(", ")", "for", "style_str", "in", "attrs_for_style", ".", "keys", "(", ")", "]", ")", "return", "[", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py3/prompt_toolkit/application/application.py#L1250-L1265
PixarAnimationStudios/USD
faed18ce62c8736b02413635b584a2f637156bad
pxr/usdImaging/usdviewq/appController.py
python
AppController.selectBoundMaterialForPurpose
(self, materialPurpose)
Iterates through all selected prims, selecting their bound preview materials.
Iterates through all selected prims, selecting their bound preview materials.
[ "Iterates", "through", "all", "selected", "prims", "selecting", "their", "bound", "preview", "materials", "." ]
def selectBoundMaterialForPurpose(self, materialPurpose): """Iterates through all selected prims, selecting their bound preview materials. """ oldPrims = self._dataModel.selection.getPrims() with self._dataModel.selection.batchPrimChanges: self._dataModel.selection.clearPrims() for prim in oldPrims: (boundMaterial, bindingRel) = \ UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial( materialPurpose=materialPurpose) if boundMaterial: self._dataModel.selection.addPrim(boundMaterial.GetPrim())
[ "def", "selectBoundMaterialForPurpose", "(", "self", ",", "materialPurpose", ")", ":", "oldPrims", "=", "self", ".", "_dataModel", ".", "selection", ".", "getPrims", "(", ")", "with", "self", ".", "_dataModel", ".", "selection", ".", "batchPrimChanges", ":", "self", ".", "_dataModel", ".", "selection", ".", "clearPrims", "(", ")", "for", "prim", "in", "oldPrims", ":", "(", "boundMaterial", ",", "bindingRel", ")", "=", "UsdShade", ".", "MaterialBindingAPI", "(", "prim", ")", ".", "ComputeBoundMaterial", "(", "materialPurpose", "=", "materialPurpose", ")", "if", "boundMaterial", ":", "self", ".", "_dataModel", ".", "selection", ".", "addPrim", "(", "boundMaterial", ".", "GetPrim", "(", ")", ")" ]
https://github.com/PixarAnimationStudios/USD/blob/faed18ce62c8736b02413635b584a2f637156bad/pxr/usdImaging/usdviewq/appController.py#L3172-L3184
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Draft/draftguitools/gui_layers.py
python
Layer.GetResources
(self)
return {'Pixmap': 'Draft_Layer', 'MenuText': QT_TRANSLATE_NOOP("Draft_Layer", "Layer"), 'ToolTip': QT_TRANSLATE_NOOP("Draft_Layer", "Adds a layer to the document.\nObjects added to this layer can share the same visual properties such as line color, line width, and shape color.")}
Set icon, menu and tooltip.
Set icon, menu and tooltip.
[ "Set", "icon", "menu", "and", "tooltip", "." ]
def GetResources(self): """Set icon, menu and tooltip.""" return {'Pixmap': 'Draft_Layer', 'MenuText': QT_TRANSLATE_NOOP("Draft_Layer", "Layer"), 'ToolTip': QT_TRANSLATE_NOOP("Draft_Layer", "Adds a layer to the document.\nObjects added to this layer can share the same visual properties such as line color, line width, and shape color.")}
[ "def", "GetResources", "(", "self", ")", ":", "return", "{", "'Pixmap'", ":", "'Draft_Layer'", ",", "'MenuText'", ":", "QT_TRANSLATE_NOOP", "(", "\"Draft_Layer\"", ",", "\"Layer\"", ")", ",", "'ToolTip'", ":", "QT_TRANSLATE_NOOP", "(", "\"Draft_Layer\"", ",", "\"Adds a layer to the document.\\nObjects added to this layer can share the same visual properties such as line color, line width, and shape color.\"", ")", "}" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_layers.py#L49-L53
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/vi.py
python
load_extra_vi_page_navigation_bindings
()
return registry
Key bindings, for scrolling up and down through pages. This are separate bindings, because GNU readline doesn't have them.
Key bindings, for scrolling up and down through pages. This are separate bindings, because GNU readline doesn't have them.
[ "Key", "bindings", "for", "scrolling", "up", "and", "down", "through", "pages", ".", "This", "are", "separate", "bindings", "because", "GNU", "readline", "doesn", "t", "have", "them", "." ]
def load_extra_vi_page_navigation_bindings(): """ Key bindings, for scrolling up and down through pages. This are separate bindings, because GNU readline doesn't have them. """ registry = ConditionalRegistry(Registry(), ViMode()) handle = registry.add_binding handle(Keys.ControlF)(scroll_forward) handle(Keys.ControlB)(scroll_backward) handle(Keys.ControlD)(scroll_half_page_down) handle(Keys.ControlU)(scroll_half_page_up) handle(Keys.ControlE)(scroll_one_line_down) handle(Keys.ControlY)(scroll_one_line_up) handle(Keys.PageDown)(scroll_page_down) handle(Keys.PageUp)(scroll_page_up) return registry
[ "def", "load_extra_vi_page_navigation_bindings", "(", ")", ":", "registry", "=", "ConditionalRegistry", "(", "Registry", "(", ")", ",", "ViMode", "(", ")", ")", "handle", "=", "registry", ".", "add_binding", "handle", "(", "Keys", ".", "ControlF", ")", "(", "scroll_forward", ")", "handle", "(", "Keys", ".", "ControlB", ")", "(", "scroll_backward", ")", "handle", "(", "Keys", ".", "ControlD", ")", "(", "scroll_half_page_down", ")", "handle", "(", "Keys", ".", "ControlU", ")", "(", "scroll_half_page_up", ")", "handle", "(", "Keys", ".", "ControlE", ")", "(", "scroll_one_line_down", ")", "handle", "(", "Keys", ".", "ControlY", ")", "(", "scroll_one_line_up", ")", "handle", "(", "Keys", ".", "PageDown", ")", "(", "scroll_page_down", ")", "handle", "(", "Keys", ".", "PageUp", ")", "(", "scroll_page_up", ")", "return", "registry" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/vi.py#L1876-L1893
NVIDIA/TensorRT
42805f078052daad1a98bc5965974fcffaad0960
samples/python/efficientnet/build_engine.py
python
EngineBuilder.__init__
(self, verbose=False)
:param verbose: If enabled, a higher verbosity level will be set on the TensorRT logger.
:param verbose: If enabled, a higher verbosity level will be set on the TensorRT logger.
[ ":", "param", "verbose", ":", "If", "enabled", "a", "higher", "verbosity", "level", "will", "be", "set", "on", "the", "TensorRT", "logger", "." ]
def __init__(self, verbose=False): """ :param verbose: If enabled, a higher verbosity level will be set on the TensorRT logger. """ self.trt_logger = trt.Logger(trt.Logger.INFO) if verbose: self.trt_logger.min_severity = trt.Logger.Severity.VERBOSE trt.init_libnvinfer_plugins(self.trt_logger, namespace="") self.builder = trt.Builder(self.trt_logger) self.config = self.builder.create_builder_config() self.config.max_workspace_size = 8 * (2 ** 30) # 8 GB self.batch_size = None self.network = None self.parser = None
[ "def", "__init__", "(", "self", ",", "verbose", "=", "False", ")", ":", "self", ".", "trt_logger", "=", "trt", ".", "Logger", "(", "trt", ".", "Logger", ".", "INFO", ")", "if", "verbose", ":", "self", ".", "trt_logger", ".", "min_severity", "=", "trt", ".", "Logger", ".", "Severity", ".", "VERBOSE", "trt", ".", "init_libnvinfer_plugins", "(", "self", ".", "trt_logger", ",", "namespace", "=", "\"\"", ")", "self", ".", "builder", "=", "trt", ".", "Builder", "(", "self", ".", "trt_logger", ")", "self", ".", "config", "=", "self", ".", "builder", ".", "create_builder_config", "(", ")", "self", ".", "config", ".", "max_workspace_size", "=", "8", "*", "(", "2", "**", "30", ")", "# 8 GB", "self", ".", "batch_size", "=", "None", "self", ".", "network", "=", "None", "self", ".", "parser", "=", "None" ]
https://github.com/NVIDIA/TensorRT/blob/42805f078052daad1a98bc5965974fcffaad0960/samples/python/efficientnet/build_engine.py#L115-L131
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/urllib3/util/request.py
python
make_headers
( keep_alive=None, accept_encoding=None, user_agent=None, basic_auth=None, proxy_basic_auth=None, disable_cache=None, )
return headers
Shortcuts for generating request headers. :param keep_alive: If ``True``, adds 'connection: keep-alive' header. :param accept_encoding: Can be a boolean, list, or string. ``True`` translates to 'gzip,deflate'. List will get joined by comma. String will be used as provided. :param user_agent: String representing the user-agent you want, such as "python-urllib3/0.6" :param basic_auth: Colon-separated username:password string for 'authorization: basic ...' auth header. :param proxy_basic_auth: Colon-separated username:password string for 'proxy-authorization: basic ...' auth header. :param disable_cache: If ``True``, adds 'cache-control: no-cache' header. Example:: >>> make_headers(keep_alive=True, user_agent="Batman/1.0") {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'} >>> make_headers(accept_encoding=True) {'accept-encoding': 'gzip,deflate'}
[]
def make_headers( keep_alive=None, accept_encoding=None, user_agent=None, basic_auth=None, proxy_basic_auth=None, disable_cache=None, ): """ Shortcuts for generating request headers. :param keep_alive: If ``True``, adds 'connection: keep-alive' header. :param accept_encoding: Can be a boolean, list, or string. ``True`` translates to 'gzip,deflate'. List will get joined by comma. String will be used as provided. :param user_agent: String representing the user-agent you want, such as "python-urllib3/0.6" :param basic_auth: Colon-separated username:password string for 'authorization: basic ...' auth header. :param proxy_basic_auth: Colon-separated username:password string for 'proxy-authorization: basic ...' auth header. :param disable_cache: If ``True``, adds 'cache-control: no-cache' header. Example:: >>> make_headers(keep_alive=True, user_agent="Batman/1.0") {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'} >>> make_headers(accept_encoding=True) {'accept-encoding': 'gzip,deflate'} """ headers = {} if accept_encoding: if isinstance(accept_encoding, str): pass elif isinstance(accept_encoding, list): accept_encoding = ",".join(accept_encoding) else: accept_encoding = ACCEPT_ENCODING headers["accept-encoding"] = accept_encoding if user_agent: headers["user-agent"] = user_agent if keep_alive: headers["connection"] = "keep-alive" if basic_auth: headers["authorization"] = "Basic " + b64encode(b(basic_auth)).decode("utf-8") if proxy_basic_auth: headers["proxy-authorization"] = "Basic " + b64encode( b(proxy_basic_auth) ).decode("utf-8") if disable_cache: headers["cache-control"] = "no-cache" return headers
[ "def", "make_headers", "(", "keep_alive", "=", "None", ",", "accept_encoding", "=", "None", ",", "user_agent", "=", "None", ",", "basic_auth", "=", "None", ",", "proxy_basic_auth", "=", "None", ",", "disable_cache", "=", "None", ",", ")", ":", "headers", "=", "{", "}", "if", "accept_encoding", ":", "if", "isinstance", "(", "accept_encoding", ",", "str", ")", ":", "pass", "elif", "isinstance", "(", "accept_encoding", ",", "list", ")", ":", "accept_encoding", "=", "\",\"", ".", "join", "(", "accept_encoding", ")", "else", ":", "accept_encoding", "=", "ACCEPT_ENCODING", "headers", "[", "\"accept-encoding\"", "]", "=", "accept_encoding", "if", "user_agent", ":", "headers", "[", "\"user-agent\"", "]", "=", "user_agent", "if", "keep_alive", ":", "headers", "[", "\"connection\"", "]", "=", "\"keep-alive\"", "if", "basic_auth", ":", "headers", "[", "\"authorization\"", "]", "=", "\"Basic \"", "+", "b64encode", "(", "b", "(", "basic_auth", ")", ")", ".", "decode", "(", "\"utf-8\"", ")", "if", "proxy_basic_auth", ":", "headers", "[", "\"proxy-authorization\"", "]", "=", "\"Basic \"", "+", "b64encode", "(", "b", "(", "proxy_basic_auth", ")", ")", ".", "decode", "(", "\"utf-8\"", ")", "if", "disable_cache", ":", "headers", "[", "\"cache-control\"", "]", "=", "\"no-cache\"", "return", "headers" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/urllib3/util/request.py#L51-L189
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/contrib/learn/python/learn/utils/export.py
python
regression_signature_fn
(examples, unused_features, predictions)
return signatures['regression'], signatures
Creates regression signature from given examples and predictions. Args: examples: `Tensor`. unused_features: `dict` of `Tensor`s. predictions: `dict` of `Tensor`s. Returns: Tuple of default regression signature and named signature.
Creates regression signature from given examples and predictions.
[ "Creates", "regression", "signature", "from", "given", "examples", "and", "predictions", "." ]
def regression_signature_fn(examples, unused_features, predictions): """Creates regression signature from given examples and predictions. Args: examples: `Tensor`. unused_features: `dict` of `Tensor`s. predictions: `dict` of `Tensor`s. Returns: Tuple of default regression signature and named signature. """ signatures = {} signatures['regression'] = exporter.regression_signature( input_tensor=examples, output_tensor=predictions) return signatures['regression'], signatures
[ "def", "regression_signature_fn", "(", "examples", ",", "unused_features", ",", "predictions", ")", ":", "signatures", "=", "{", "}", "signatures", "[", "'regression'", "]", "=", "exporter", ".", "regression_signature", "(", "input_tensor", "=", "examples", ",", "output_tensor", "=", "predictions", ")", "return", "signatures", "[", "'regression'", "]", ",", "signatures" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/learn/python/learn/utils/export.py#L135-L149
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/traci/_edge.py
python
EdgeDomain.getFuelConsumption
(self, edgeID)
return self._getUniversal(tc.VAR_FUELCONSUMPTION, edgeID)
getFuelConsumption(string) -> double Returns the fuel consumption in ml for the last time step on the given edge.
getFuelConsumption(string) -> double
[ "getFuelConsumption", "(", "string", ")", "-", ">", "double" ]
def getFuelConsumption(self, edgeID): """getFuelConsumption(string) -> double Returns the fuel consumption in ml for the last time step on the given edge. """ return self._getUniversal(tc.VAR_FUELCONSUMPTION, edgeID)
[ "def", "getFuelConsumption", "(", "self", ",", "edgeID", ")", ":", "return", "self", ".", "_getUniversal", "(", "tc", ".", "VAR_FUELCONSUMPTION", ",", "edgeID", ")" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/traci/_edge.py#L91-L96
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_pydecimal.py
python
Context.min_mag
(self, a, b)
return a.min_mag(b, context=self)
Compares the values numerically with their sign ignored. >>> ExtendedContext.min_mag(Decimal('3'), Decimal('-2')) Decimal('-2') >>> ExtendedContext.min_mag(Decimal('-3'), Decimal('NaN')) Decimal('-3') >>> ExtendedContext.min_mag(1, -2) Decimal('1') >>> ExtendedContext.min_mag(Decimal(1), -2) Decimal('1') >>> ExtendedContext.min_mag(1, Decimal(-2)) Decimal('1')
Compares the values numerically with their sign ignored.
[ "Compares", "the", "values", "numerically", "with", "their", "sign", "ignored", "." ]
def min_mag(self, a, b): """Compares the values numerically with their sign ignored. >>> ExtendedContext.min_mag(Decimal('3'), Decimal('-2')) Decimal('-2') >>> ExtendedContext.min_mag(Decimal('-3'), Decimal('NaN')) Decimal('-3') >>> ExtendedContext.min_mag(1, -2) Decimal('1') >>> ExtendedContext.min_mag(Decimal(1), -2) Decimal('1') >>> ExtendedContext.min_mag(1, Decimal(-2)) Decimal('1') """ a = _convert_other(a, raiseit=True) return a.min_mag(b, context=self)
[ "def", "min_mag", "(", "self", ",", "a", ",", "b", ")", ":", "a", "=", "_convert_other", "(", "a", ",", "raiseit", "=", "True", ")", "return", "a", ".", "min_mag", "(", "b", ",", "context", "=", "self", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_pydecimal.py#L4909-L4924
su2code/SU2
72b2fa977b64b9683a388920f05298a40d39e5c5
SU2_PY/SU2/io/config.py
python
Config.dist
(self,konfig,keys_check='ALL')
return distance
calculates a distance to another config Inputs: konfig - a second config keys_check - optional, a list of keys to check Outputs: distance - a float Currently only works for DV_VALUE_NEW and DV_VALUE_OLD Returns a large value otherwise
calculates a distance to another config Inputs: konfig - a second config keys_check - optional, a list of keys to check Outputs: distance - a float Currently only works for DV_VALUE_NEW and DV_VALUE_OLD Returns a large value otherwise
[ "calculates", "a", "distance", "to", "another", "config", "Inputs", ":", "konfig", "-", "a", "second", "config", "keys_check", "-", "optional", "a", "list", "of", "keys", "to", "check", "Outputs", ":", "distance", "-", "a", "float", "Currently", "only", "works", "for", "DV_VALUE_NEW", "and", "DV_VALUE_OLD", "Returns", "a", "large", "value", "otherwise" ]
def dist(self,konfig,keys_check='ALL'): """ calculates a distance to another config Inputs: konfig - a second config keys_check - optional, a list of keys to check Outputs: distance - a float Currently only works for DV_VALUE_NEW and DV_VALUE_OLD Returns a large value otherwise """ konfig_diff = self.diff(konfig) if keys_check == 'ALL': keys_check = konfig_diff.keys() distance = 0.0 for key in keys_check: if key in konfig_diff: val1 = konfig_diff[key][0] val2 = konfig_diff[key][1] if key in ['DV_VALUE_NEW', 'DV_VALUE_OLD']: val1 = np.array( val1 ) val2 = np.array( val2 ) this_diff = np.sqrt( np.sum( (val1-val2)**2 ) ) else: print('Warning, unexpected config difference') this_diff = inf distance += this_diff #: if key different #: for each keys_check return distance
[ "def", "dist", "(", "self", ",", "konfig", ",", "keys_check", "=", "'ALL'", ")", ":", "konfig_diff", "=", "self", ".", "diff", "(", "konfig", ")", "if", "keys_check", "==", "'ALL'", ":", "keys_check", "=", "konfig_diff", ".", "keys", "(", ")", "distance", "=", "0.0", "for", "key", "in", "keys_check", ":", "if", "key", "in", "konfig_diff", ":", "val1", "=", "konfig_diff", "[", "key", "]", "[", "0", "]", "val2", "=", "konfig_diff", "[", "key", "]", "[", "1", "]", "if", "key", "in", "[", "'DV_VALUE_NEW'", ",", "'DV_VALUE_OLD'", "]", ":", "val1", "=", "np", ".", "array", "(", "val1", ")", "val2", "=", "np", ".", "array", "(", "val2", ")", "this_diff", "=", "np", ".", "sqrt", "(", "np", ".", "sum", "(", "(", "val1", "-", "val2", ")", "**", "2", ")", ")", "else", ":", "print", "(", "'Warning, unexpected config difference'", ")", "this_diff", "=", "inf", "distance", "+=", "this_diff", "#: if key different", "#: for each keys_check", "return", "distance" ]
https://github.com/su2code/SU2/blob/72b2fa977b64b9683a388920f05298a40d39e5c5/SU2_PY/SU2/io/config.py#L261-L304
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/ed_cmdbar.py
python
PopupList.SetStringSelection
(self, text)
Set the list selection by using a string value @param text: string to select in list
Set the list selection by using a string value @param text: string to select in list
[ "Set", "the", "list", "selection", "by", "using", "a", "string", "value", "@param", "text", ":", "string", "to", "select", "in", "list" ]
def SetStringSelection(self, text): """Set the list selection by using a string value @param text: string to select in list """ self._list.SetStringSelection(text)
[ "def", "SetStringSelection", "(", "self", ",", "text", ")", ":", "self", ".", "_list", ".", "SetStringSelection", "(", "text", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_cmdbar.py#L1224-L1229
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/distutils/exec_command.py
python
exec_command
( command, execute_in='', use_shell=None, use_tee = None, _with_python = 1, **env )
return st
Return (status,output) of executed command. command is a concatenated string of executable and arguments. The output contains both stdout and stderr messages. The following special keyword arguments can be used: use_shell - execute `sh -c command` use_tee - pipe the output of command through tee execute_in - before run command `cd execute_in` and after `cd -`. On NT, DOS systems the returned status is correct for external commands. Wild cards will not work for non-posix systems or when use_shell=0.
Return (status,output) of executed command.
[ "Return", "(", "status", "output", ")", "of", "executed", "command", "." ]
def exec_command( command, execute_in='', use_shell=None, use_tee = None, _with_python = 1, **env ): """ Return (status,output) of executed command. command is a concatenated string of executable and arguments. The output contains both stdout and stderr messages. The following special keyword arguments can be used: use_shell - execute `sh -c command` use_tee - pipe the output of command through tee execute_in - before run command `cd execute_in` and after `cd -`. On NT, DOS systems the returned status is correct for external commands. Wild cards will not work for non-posix systems or when use_shell=0. """ log.debug('exec_command(%r,%s)' % (command,\ ','.join(['%s=%r'%kv for kv in env.items()]))) if use_tee is None: use_tee = os.name=='posix' if use_shell is None: use_shell = os.name=='posix' execute_in = os.path.abspath(execute_in) oldcwd = os.path.abspath(os.getcwd()) if __name__[-12:] == 'exec_command': exec_dir = os.path.dirname(os.path.abspath(__file__)) elif os.path.isfile('exec_command.py'): exec_dir = os.path.abspath('.') else: exec_dir = os.path.abspath(sys.argv[0]) if os.path.isfile(exec_dir): exec_dir = os.path.dirname(exec_dir) if oldcwd!=execute_in: os.chdir(execute_in) log.debug('New cwd: %s' % execute_in) else: log.debug('Retaining cwd: %s' % oldcwd) oldenv = _preserve_environment( list(env.keys()) ) _update_environment( **env ) try: # _exec_command is robust but slow, it relies on # usable sys.std*.fileno() descriptors. If they # are bad (like in win32 Idle, PyCrust environments) # then _exec_command_python (even slower) # will be used as a last resort. # # _exec_command_posix uses os.system and is faster # but not on all platforms os.system will return # a correct status. if (_with_python and _supports_fileno(sys.stdout) and sys.stdout.fileno() == -1): st = _exec_command_python(command, exec_command_dir = exec_dir, **env) elif os.name=='posix': st = _exec_command_posix(command, use_shell=use_shell, use_tee=use_tee, **env) else: st = _exec_command(command, use_shell=use_shell, use_tee=use_tee,**env) finally: if oldcwd!=execute_in: os.chdir(oldcwd) log.debug('Restored cwd to %s' % oldcwd) _update_environment(**oldenv) return st
[ "def", "exec_command", "(", "command", ",", "execute_in", "=", "''", ",", "use_shell", "=", "None", ",", "use_tee", "=", "None", ",", "_with_python", "=", "1", ",", "*", "*", "env", ")", ":", "log", ".", "debug", "(", "'exec_command(%r,%s)'", "%", "(", "command", ",", "','", ".", "join", "(", "[", "'%s=%r'", "%", "kv", "for", "kv", "in", "env", ".", "items", "(", ")", "]", ")", ")", ")", "if", "use_tee", "is", "None", ":", "use_tee", "=", "os", ".", "name", "==", "'posix'", "if", "use_shell", "is", "None", ":", "use_shell", "=", "os", ".", "name", "==", "'posix'", "execute_in", "=", "os", ".", "path", ".", "abspath", "(", "execute_in", ")", "oldcwd", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "getcwd", "(", ")", ")", "if", "__name__", "[", "-", "12", ":", "]", "==", "'exec_command'", ":", "exec_dir", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "__file__", ")", ")", "elif", "os", ".", "path", ".", "isfile", "(", "'exec_command.py'", ")", ":", "exec_dir", "=", "os", ".", "path", ".", "abspath", "(", "'.'", ")", "else", ":", "exec_dir", "=", "os", ".", "path", ".", "abspath", "(", "sys", ".", "argv", "[", "0", "]", ")", "if", "os", ".", "path", ".", "isfile", "(", "exec_dir", ")", ":", "exec_dir", "=", "os", ".", "path", ".", "dirname", "(", "exec_dir", ")", "if", "oldcwd", "!=", "execute_in", ":", "os", ".", "chdir", "(", "execute_in", ")", "log", ".", "debug", "(", "'New cwd: %s'", "%", "execute_in", ")", "else", ":", "log", ".", "debug", "(", "'Retaining cwd: %s'", "%", "oldcwd", ")", "oldenv", "=", "_preserve_environment", "(", "list", "(", "env", ".", "keys", "(", ")", ")", ")", "_update_environment", "(", "*", "*", "env", ")", "try", ":", "# _exec_command is robust but slow, it relies on", "# usable sys.std*.fileno() descriptors. If they", "# are bad (like in win32 Idle, PyCrust environments)", "# then _exec_command_python (even slower)", "# will be used as a last resort.", "#", "# _exec_command_posix uses os.system and is faster", "# but not on all platforms os.system will return", "# a correct status.", "if", "(", "_with_python", "and", "_supports_fileno", "(", "sys", ".", "stdout", ")", "and", "sys", ".", "stdout", ".", "fileno", "(", ")", "==", "-", "1", ")", ":", "st", "=", "_exec_command_python", "(", "command", ",", "exec_command_dir", "=", "exec_dir", ",", "*", "*", "env", ")", "elif", "os", ".", "name", "==", "'posix'", ":", "st", "=", "_exec_command_posix", "(", "command", ",", "use_shell", "=", "use_shell", ",", "use_tee", "=", "use_tee", ",", "*", "*", "env", ")", "else", ":", "st", "=", "_exec_command", "(", "command", ",", "use_shell", "=", "use_shell", ",", "use_tee", "=", "use_tee", ",", "*", "*", "env", ")", "finally", ":", "if", "oldcwd", "!=", "execute_in", ":", "os", ".", "chdir", "(", "oldcwd", ")", "log", ".", "debug", "(", "'Restored cwd to %s'", "%", "oldcwd", ")", "_update_environment", "(", "*", "*", "oldenv", ")", "return", "st" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/distutils/exec_command.py#L157-L230
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
TPM2_ReadPublic_REQUEST.__init__
(self, objectHandle = TPM_HANDLE())
This command allows access to the public area of a loaded object. Attributes: objectHandle (TPM_HANDLE): TPM handle of an object Auth Index: None
This command allows access to the public area of a loaded object.
[ "This", "command", "allows", "access", "to", "the", "public", "area", "of", "a", "loaded", "object", "." ]
def __init__(self, objectHandle = TPM_HANDLE()): """ This command allows access to the public area of a loaded object. Attributes: objectHandle (TPM_HANDLE): TPM handle of an object Auth Index: None """ self.objectHandle = objectHandle
[ "def", "__init__", "(", "self", ",", "objectHandle", "=", "TPM_HANDLE", "(", ")", ")", ":", "self", ".", "objectHandle", "=", "objectHandle" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L9752-L9759
ApolloAuto/apollo
463fb82f9e979d02dcb25044e60931293ab2dba0
modules/tools/vehicle_calibration/data_collector.py
python
main
()
Main function
Main function
[ "Main", "function" ]
def main(): """ Main function """ node = cyber.Node("data_collector") data_collector = DataCollector(node) plotter = Plotter() node.create_reader('/apollo/localization/pose', localization_pb2.LocalizationEstimate, data_collector.callback_localization) node.create_reader('/apollo/canbus/chassis', chassis_pb2.Chassis, data_collector.callback_canbus) print('Enter q to quit.') print('Enter p to plot result from last run.') print('Enter x to remove result from last run.') print('Enter x y z, where x is acceleration command, ' + 'y is speed limit, z is decceleration command.') print('Positive number for throttle and negative number for brake.') while True: cmd = input("Enter commands: ").split() if len(cmd) == 0: print('Quiting.') break elif len(cmd) == 1: if cmd[0] == "q": break elif cmd[0] == "p": print('Plotting result.') if os.path.exists(data_collector.outfile): plotter.process_data(data_collector.outfile) plotter.plot_result() else: print('File does not exist: %s' % data_collector.outfile) elif cmd[0] == "x": print('Removing last result.') if os.path.exists(data_collector.outfile): os.remove(data_collector.outfile) else: print('File does not exist: %s' % date_collector.outfile) elif len(cmd) == 3: data_collector.run(cmd)
[ "def", "main", "(", ")", ":", "node", "=", "cyber", ".", "Node", "(", "\"data_collector\"", ")", "data_collector", "=", "DataCollector", "(", "node", ")", "plotter", "=", "Plotter", "(", ")", "node", ".", "create_reader", "(", "'/apollo/localization/pose'", ",", "localization_pb2", ".", "LocalizationEstimate", ",", "data_collector", ".", "callback_localization", ")", "node", ".", "create_reader", "(", "'/apollo/canbus/chassis'", ",", "chassis_pb2", ".", "Chassis", ",", "data_collector", ".", "callback_canbus", ")", "print", "(", "'Enter q to quit.'", ")", "print", "(", "'Enter p to plot result from last run.'", ")", "print", "(", "'Enter x to remove result from last run.'", ")", "print", "(", "'Enter x y z, where x is acceleration command, '", "+", "'y is speed limit, z is decceleration command.'", ")", "print", "(", "'Positive number for throttle and negative number for brake.'", ")", "while", "True", ":", "cmd", "=", "input", "(", "\"Enter commands: \"", ")", ".", "split", "(", ")", "if", "len", "(", "cmd", ")", "==", "0", ":", "print", "(", "'Quiting.'", ")", "break", "elif", "len", "(", "cmd", ")", "==", "1", ":", "if", "cmd", "[", "0", "]", "==", "\"q\"", ":", "break", "elif", "cmd", "[", "0", "]", "==", "\"p\"", ":", "print", "(", "'Plotting result.'", ")", "if", "os", ".", "path", ".", "exists", "(", "data_collector", ".", "outfile", ")", ":", "plotter", ".", "process_data", "(", "data_collector", ".", "outfile", ")", "plotter", ".", "plot_result", "(", ")", "else", ":", "print", "(", "'File does not exist: %s'", "%", "data_collector", ".", "outfile", ")", "elif", "cmd", "[", "0", "]", "==", "\"x\"", ":", "print", "(", "'Removing last result.'", ")", "if", "os", ".", "path", ".", "exists", "(", "data_collector", ".", "outfile", ")", ":", "os", ".", "remove", "(", "data_collector", ".", "outfile", ")", "else", ":", "print", "(", "'File does not exist: %s'", "%", "date_collector", ".", "outfile", ")", "elif", "len", "(", "cmd", ")", "==", "3", ":", "data_collector", ".", "run", "(", "cmd", ")" ]
https://github.com/ApolloAuto/apollo/blob/463fb82f9e979d02dcb25044e60931293ab2dba0/modules/tools/vehicle_calibration/data_collector.py#L188-L231
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/debug/cli/base_ui.py
python
BaseUI.register_command_handler
(self, prefix, handler, help_info, prefix_aliases=None)
A wrapper around CommandHandlerRegistry.register_command_handler(). In addition to calling the wrapped register_command_handler() method, this method also registers the top-level tab-completion context based on the command prefixes and their aliases. See the doc string of the wrapped method for more details on the args. Args: prefix: (str) command prefix. handler: (callable) command handler. help_info: (str) help information. prefix_aliases: (list of str) aliases of the command prefix.
A wrapper around CommandHandlerRegistry.register_command_handler().
[ "A", "wrapper", "around", "CommandHandlerRegistry", ".", "register_command_handler", "()", "." ]
def register_command_handler(self, prefix, handler, help_info, prefix_aliases=None): """A wrapper around CommandHandlerRegistry.register_command_handler(). In addition to calling the wrapped register_command_handler() method, this method also registers the top-level tab-completion context based on the command prefixes and their aliases. See the doc string of the wrapped method for more details on the args. Args: prefix: (str) command prefix. handler: (callable) command handler. help_info: (str) help information. prefix_aliases: (list of str) aliases of the command prefix. """ self._command_handler_registry.register_command_handler( prefix, handler, help_info, prefix_aliases=prefix_aliases) self._tab_completion_registry.extend_comp_items("", [prefix]) if prefix_aliases: self._tab_completion_registry.extend_comp_items("", prefix_aliases)
[ "def", "register_command_handler", "(", "self", ",", "prefix", ",", "handler", ",", "help_info", ",", "prefix_aliases", "=", "None", ")", ":", "self", ".", "_command_handler_registry", ".", "register_command_handler", "(", "prefix", ",", "handler", ",", "help_info", ",", "prefix_aliases", "=", "prefix_aliases", ")", "self", ".", "_tab_completion_registry", ".", "extend_comp_items", "(", "\"\"", ",", "[", "prefix", "]", ")", "if", "prefix_aliases", ":", "self", ".", "_tab_completion_registry", ".", "extend_comp_items", "(", "\"\"", ",", "prefix_aliases", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/debug/cli/base_ui.py#L78-L103
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
third_party/tlslite/tlslite/Checker.py
python
Checker.__call__
(self, connection)
Check a TLSConnection. When a Checker is passed to a handshake function, this will be called at the end of the function. @type connection: L{tlslite.TLSConnection.TLSConnection} @param connection: The TLSConnection to examine. @raise tlslite.errors.TLSAuthenticationError: If the other party's certificate chain is missing or bad.
Check a TLSConnection.
[ "Check", "a", "TLSConnection", "." ]
def __call__(self, connection): """Check a TLSConnection. When a Checker is passed to a handshake function, this will be called at the end of the function. @type connection: L{tlslite.TLSConnection.TLSConnection} @param connection: The TLSConnection to examine. @raise tlslite.errors.TLSAuthenticationError: If the other party's certificate chain is missing or bad. """ if not self.checkResumedSession and connection.resumed: return if self.cryptoID or self.x509Fingerprint or self.x509TrustList: if connection._client: chain = connection.session.serverCertChain else: chain = connection.session.clientCertChain if self.x509Fingerprint or self.x509TrustList: if isinstance(chain, X509CertChain): if self.x509Fingerprint: if chain.getFingerprint() != self.x509Fingerprint: raise TLSFingerprintError(\ "X.509 fingerprint mismatch: %s, %s" % \ (chain.getFingerprint(), self.x509Fingerprint)) else: #self.x509TrustList if not chain.validate(self.x509TrustList): raise TLSValidationError("X.509 validation failure") if self.x509CommonName and \ (chain.getCommonName() != self.x509CommonName): raise TLSAuthorizationError(\ "X.509 Common Name mismatch: %s, %s" % \ (chain.getCommonName(), self.x509CommonName)) elif chain: raise TLSAuthenticationTypeError() else: raise TLSNoAuthenticationError() elif self.cryptoID: import cryptoIDlib.CertChain if isinstance(chain, cryptoIDlib.CertChain.CertChain): if chain.cryptoID != self.cryptoID: raise TLSFingerprintError(\ "cryptoID mismatch: %s, %s" % \ (chain.cryptoID, self.cryptoID)) if self.protocol: if not chain.checkProtocol(self.protocol): raise TLSAuthorizationError(\ "cryptoID protocol mismatch") if not chain.validate(): raise TLSValidationError("cryptoID validation failure") elif chain: raise TLSAuthenticationTypeError() else: raise TLSNoAuthenticationError()
[ "def", "__call__", "(", "self", ",", "connection", ")", ":", "if", "not", "self", ".", "checkResumedSession", "and", "connection", ".", "resumed", ":", "return", "if", "self", ".", "cryptoID", "or", "self", ".", "x509Fingerprint", "or", "self", ".", "x509TrustList", ":", "if", "connection", ".", "_client", ":", "chain", "=", "connection", ".", "session", ".", "serverCertChain", "else", ":", "chain", "=", "connection", ".", "session", ".", "clientCertChain", "if", "self", ".", "x509Fingerprint", "or", "self", ".", "x509TrustList", ":", "if", "isinstance", "(", "chain", ",", "X509CertChain", ")", ":", "if", "self", ".", "x509Fingerprint", ":", "if", "chain", ".", "getFingerprint", "(", ")", "!=", "self", ".", "x509Fingerprint", ":", "raise", "TLSFingerprintError", "(", "\"X.509 fingerprint mismatch: %s, %s\"", "%", "(", "chain", ".", "getFingerprint", "(", ")", ",", "self", ".", "x509Fingerprint", ")", ")", "else", ":", "#self.x509TrustList", "if", "not", "chain", ".", "validate", "(", "self", ".", "x509TrustList", ")", ":", "raise", "TLSValidationError", "(", "\"X.509 validation failure\"", ")", "if", "self", ".", "x509CommonName", "and", "(", "chain", ".", "getCommonName", "(", ")", "!=", "self", ".", "x509CommonName", ")", ":", "raise", "TLSAuthorizationError", "(", "\"X.509 Common Name mismatch: %s, %s\"", "%", "(", "chain", ".", "getCommonName", "(", ")", ",", "self", ".", "x509CommonName", ")", ")", "elif", "chain", ":", "raise", "TLSAuthenticationTypeError", "(", ")", "else", ":", "raise", "TLSNoAuthenticationError", "(", ")", "elif", "self", ".", "cryptoID", ":", "import", "cryptoIDlib", ".", "CertChain", "if", "isinstance", "(", "chain", ",", "cryptoIDlib", ".", "CertChain", ".", "CertChain", ")", ":", "if", "chain", ".", "cryptoID", "!=", "self", ".", "cryptoID", ":", "raise", "TLSFingerprintError", "(", "\"cryptoID mismatch: %s, %s\"", "%", "(", "chain", ".", "cryptoID", ",", "self", ".", "cryptoID", ")", ")", "if", "self", ".", "protocol", ":", "if", "not", "chain", ".", "checkProtocol", "(", "self", ".", "protocol", ")", ":", "raise", "TLSAuthorizationError", "(", "\"cryptoID protocol mismatch\"", ")", "if", "not", "chain", ".", "validate", "(", ")", ":", "raise", "TLSValidationError", "(", "\"cryptoID validation failure\"", ")", "elif", "chain", ":", "raise", "TLSAuthenticationTypeError", "(", ")", "else", ":", "raise", "TLSNoAuthenticationError", "(", ")" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/tlslite/tlslite/Checker.py#L89-L145
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
current/deps/v8/tools/run_perf.py
python
TraceConfig.ConsumeOutput
(self, output, result_tracker)
return result
Extracts trace results from the output. Args: output: Output object from the test run. result_tracker: Result tracker to be updated. Returns: The raw extracted result value or None if an error occurred.
Extracts trace results from the output.
[ "Extracts", "trace", "results", "from", "the", "output", "." ]
def ConsumeOutput(self, output, result_tracker): """Extracts trace results from the output. Args: output: Output object from the test run. result_tracker: Result tracker to be updated. Returns: The raw extracted result value or None if an error occurred. """ result = None stddev = None try: result = float( re.search(self.results_regexp, output.stdout, re.M).group(1)) except ValueError: result_tracker.AddError( 'Regexp "%s" returned a non-numeric for test %s.' % (self.results_regexp, self.name)) except: result_tracker.AddError( 'Regexp "%s" did not match for test %s.' % (self.results_regexp, self.name)) try: if self.stddev_regexp: if result_tracker.TraceHasStdDev(self): result_tracker.AddError( 'Test %s should only run once since a stddev is provided by the ' 'test.' % self.name) stddev = re.search(self.stddev_regexp, output.stdout, re.M).group(1) except: result_tracker.AddError( 'Regexp "%s" did not match for test %s.' % (self.stddev_regexp, self.name)) if result: result_tracker.AddTraceResult(self, result, stddev) return result
[ "def", "ConsumeOutput", "(", "self", ",", "output", ",", "result_tracker", ")", ":", "result", "=", "None", "stddev", "=", "None", "try", ":", "result", "=", "float", "(", "re", ".", "search", "(", "self", ".", "results_regexp", ",", "output", ".", "stdout", ",", "re", ".", "M", ")", ".", "group", "(", "1", ")", ")", "except", "ValueError", ":", "result_tracker", ".", "AddError", "(", "'Regexp \"%s\" returned a non-numeric for test %s.'", "%", "(", "self", ".", "results_regexp", ",", "self", ".", "name", ")", ")", "except", ":", "result_tracker", ".", "AddError", "(", "'Regexp \"%s\" did not match for test %s.'", "%", "(", "self", ".", "results_regexp", ",", "self", ".", "name", ")", ")", "try", ":", "if", "self", ".", "stddev_regexp", ":", "if", "result_tracker", ".", "TraceHasStdDev", "(", "self", ")", ":", "result_tracker", ".", "AddError", "(", "'Test %s should only run once since a stddev is provided by the '", "'test.'", "%", "self", ".", "name", ")", "stddev", "=", "re", ".", "search", "(", "self", ".", "stddev_regexp", ",", "output", ".", "stdout", ",", "re", ".", "M", ")", ".", "group", "(", "1", ")", "except", ":", "result_tracker", ".", "AddError", "(", "'Regexp \"%s\" did not match for test %s.'", "%", "(", "self", ".", "stddev_regexp", ",", "self", ".", "name", ")", ")", "if", "result", ":", "result_tracker", ".", "AddTraceResult", "(", "self", ",", "result", ",", "stddev", ")", "return", "result" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/deps/v8/tools/run_perf.py#L400-L439
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/build/linux_setup_msr.py
python
_CheckMsrDevNodes
()
return True
Check whether the MSR /dev files have the right permissions.
Check whether the MSR /dev files have the right permissions.
[ "Check", "whether", "the", "MSR", "/", "dev", "files", "have", "the", "right", "permissions", "." ]
def _CheckMsrDevNodes(): """Check whether the MSR /dev files have the right permissions.""" if not os.path.exists(MSR_DEV_FILE_PATH): print 'Error: %s does not exist.' % MSR_DEV_FILE_PATH return False if not os.access(MSR_DEV_FILE_PATH, os.R_OK): print 'Error: Cannot read from %s' % MSR_DEV_FILE_PATH return False return True
[ "def", "_CheckMsrDevNodes", "(", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "MSR_DEV_FILE_PATH", ")", ":", "print", "'Error: %s does not exist.'", "%", "MSR_DEV_FILE_PATH", "return", "False", "if", "not", "os", ".", "access", "(", "MSR_DEV_FILE_PATH", ",", "os", ".", "R_OK", ")", ":", "print", "'Error: Cannot read from %s'", "%", "MSR_DEV_FILE_PATH", "return", "False", "return", "True" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/build/linux_setup_msr.py#L45-L55
LLNL/lbann
26083e6c86050302ce33148aea70f62e61cacb92
python/lbann/launcher/slurm.py
python
SlurmBatchScript.__init__
(self, script_file=None, work_dir=os.getcwd(), nodes=1, procs_per_node=1, time_limit=None, job_name=None, partition=None, account=None, launcher='srun', launcher_args=[], interpreter='/bin/bash')
Construct Slurm batch script manager. Args: script_file (str): Script file. work_dir (str, optional): Working directory (default: current working directory). nodes (int, optional): Number of compute nodes (default: 1). procs_per_node (int, optional): Parallel processes per compute node (default: 1). time_limit (int, optional): Job time limit, in minutes (default: none). job_name (str, optional): Job name (default: none). partition (str, optional): Scheduler partition (default: none). account (str, optional): Scheduler account (default: none). launcher (str, optional): Parallel command launcher (default: srun). launcher_args (`Iterable` of `str`, optional): Command-line arguments to srun. interpreter (str, optional): Script interpreter (default: /bin/bash).
Construct Slurm batch script manager.
[ "Construct", "Slurm", "batch", "script", "manager", "." ]
def __init__(self, script_file=None, work_dir=os.getcwd(), nodes=1, procs_per_node=1, time_limit=None, job_name=None, partition=None, account=None, launcher='srun', launcher_args=[], interpreter='/bin/bash'): """Construct Slurm batch script manager. Args: script_file (str): Script file. work_dir (str, optional): Working directory (default: current working directory). nodes (int, optional): Number of compute nodes (default: 1). procs_per_node (int, optional): Parallel processes per compute node (default: 1). time_limit (int, optional): Job time limit, in minutes (default: none). job_name (str, optional): Job name (default: none). partition (str, optional): Scheduler partition (default: none). account (str, optional): Scheduler account (default: none). launcher (str, optional): Parallel command launcher (default: srun). launcher_args (`Iterable` of `str`, optional): Command-line arguments to srun. interpreter (str, optional): Script interpreter (default: /bin/bash). """ super().__init__(script_file=script_file, work_dir=work_dir, interpreter=interpreter) self.nodes = nodes self.procs_per_node = procs_per_node self.time_limit = time_limit self.job_name = job_name self.partition = partition self.account = account self.launcher = launcher self.launcher_args = launcher_args # Configure header with Slurm job options self.add_header_line(f'#SBATCH --chdir={self.work_dir}') self.add_header_line(f'#SBATCH --output={self.out_log_file}') self.add_header_line(f'#SBATCH --error={self.err_log_file}') self.add_header_line(f'#SBATCH --nodes={self.nodes}') self.add_header_line(f'#SBATCH --ntasks={self.nodes * self.procs_per_node}') self.add_header_line(f'#SBATCH --ntasks-per-node={self.procs_per_node}') if self.time_limit is not None: self.add_header_line(f'#SBATCH --time={_time_string(self.time_limit)}') if self.job_name: self.add_header_line(f'#SBATCH --job-name={self.job_name}') if self.partition: self.add_header_line(f'#SBATCH --partition={self.partition}') if self.account: self.add_header_line(f'#SBATCH --account={self.account}') for arg in self.launcher_args: self.add_header_line(f'#SBATCH {arg}')
[ "def", "__init__", "(", "self", ",", "script_file", "=", "None", ",", "work_dir", "=", "os", ".", "getcwd", "(", ")", ",", "nodes", "=", "1", ",", "procs_per_node", "=", "1", ",", "time_limit", "=", "None", ",", "job_name", "=", "None", ",", "partition", "=", "None", ",", "account", "=", "None", ",", "launcher", "=", "'srun'", ",", "launcher_args", "=", "[", "]", ",", "interpreter", "=", "'/bin/bash'", ")", ":", "super", "(", ")", ".", "__init__", "(", "script_file", "=", "script_file", ",", "work_dir", "=", "work_dir", ",", "interpreter", "=", "interpreter", ")", "self", ".", "nodes", "=", "nodes", "self", ".", "procs_per_node", "=", "procs_per_node", "self", ".", "time_limit", "=", "time_limit", "self", ".", "job_name", "=", "job_name", "self", ".", "partition", "=", "partition", "self", ".", "account", "=", "account", "self", ".", "launcher", "=", "launcher", "self", ".", "launcher_args", "=", "launcher_args", "# Configure header with Slurm job options", "self", ".", "add_header_line", "(", "f'#SBATCH --chdir={self.work_dir}'", ")", "self", ".", "add_header_line", "(", "f'#SBATCH --output={self.out_log_file}'", ")", "self", ".", "add_header_line", "(", "f'#SBATCH --error={self.err_log_file}'", ")", "self", ".", "add_header_line", "(", "f'#SBATCH --nodes={self.nodes}'", ")", "self", ".", "add_header_line", "(", "f'#SBATCH --ntasks={self.nodes * self.procs_per_node}'", ")", "self", ".", "add_header_line", "(", "f'#SBATCH --ntasks-per-node={self.procs_per_node}'", ")", "if", "self", ".", "time_limit", "is", "not", "None", ":", "self", ".", "add_header_line", "(", "f'#SBATCH --time={_time_string(self.time_limit)}'", ")", "if", "self", ".", "job_name", ":", "self", ".", "add_header_line", "(", "f'#SBATCH --job-name={self.job_name}'", ")", "if", "self", ".", "partition", ":", "self", ".", "add_header_line", "(", "f'#SBATCH --partition={self.partition}'", ")", "if", "self", ".", "account", ":", "self", ".", "add_header_line", "(", "f'#SBATCH --account={self.account}'", ")", "for", "arg", "in", "self", ".", "launcher_args", ":", "self", ".", "add_header_line", "(", "f'#SBATCH {arg}'", ")" ]
https://github.com/LLNL/lbann/blob/26083e6c86050302ce33148aea70f62e61cacb92/python/lbann/launcher/slurm.py#L19-L85
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/stc.py
python
StyledTextCtrl.SetFoldMarginHiColour
(*args, **kwargs)
return _stc.StyledTextCtrl_SetFoldMarginHiColour(*args, **kwargs)
SetFoldMarginHiColour(self, bool useSetting, Colour fore)
SetFoldMarginHiColour(self, bool useSetting, Colour fore)
[ "SetFoldMarginHiColour", "(", "self", "bool", "useSetting", "Colour", "fore", ")" ]
def SetFoldMarginHiColour(*args, **kwargs): """SetFoldMarginHiColour(self, bool useSetting, Colour fore)""" return _stc.StyledTextCtrl_SetFoldMarginHiColour(*args, **kwargs)
[ "def", "SetFoldMarginHiColour", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_SetFoldMarginHiColour", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/stc.py#L4322-L4324
google/llvm-propeller
45c226984fe8377ebfb2ad7713c680d652ba678d
lldb/utils/lui/lldbutil.py
python
which
(program)
return None
Returns the full path to a program; None otherwise.
Returns the full path to a program; None otherwise.
[ "Returns", "the", "full", "path", "to", "a", "program", ";", "None", "otherwise", "." ]
def which(program): """Returns the full path to a program; None otherwise.""" fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: for path in os.environ["PATH"].split(os.pathsep): exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None
[ "def", "which", "(", "program", ")", ":", "fpath", ",", "fname", "=", "os", ".", "path", ".", "split", "(", "program", ")", "if", "fpath", ":", "if", "is_exe", "(", "program", ")", ":", "return", "program", "else", ":", "for", "path", "in", "os", ".", "environ", "[", "\"PATH\"", "]", ".", "split", "(", "os", ".", "pathsep", ")", ":", "exe_file", "=", "os", ".", "path", ".", "join", "(", "path", ",", "program", ")", "if", "is_exe", "(", "exe_file", ")", ":", "return", "exe_file", "return", "None" ]
https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/lldb/utils/lui/lldbutil.py#L32-L43
Genius-x/genius-x
9fc9f194e6d1fb92dd0e33d43db19ddb67cda7b0
cocos2d/tools/bindings-generator/clang/cindex.py
python
CompilationDatabase.getCompileCommands
(self, filename)
return conf.lib.clang_CompilationDatabase_getCompileCommands(self, filename)
Get an iterable object providing all the CompileCommands available to build filename. Returns None if filename is not found in the database.
Get an iterable object providing all the CompileCommands available to build filename. Returns None if filename is not found in the database.
[ "Get", "an", "iterable", "object", "providing", "all", "the", "CompileCommands", "available", "to", "build", "filename", ".", "Returns", "None", "if", "filename", "is", "not", "found", "in", "the", "database", "." ]
def getCompileCommands(self, filename): """ Get an iterable object providing all the CompileCommands available to build filename. Returns None if filename is not found in the database. """ return conf.lib.clang_CompilationDatabase_getCompileCommands(self, filename)
[ "def", "getCompileCommands", "(", "self", ",", "filename", ")", ":", "return", "conf", ".", "lib", ".", "clang_CompilationDatabase_getCompileCommands", "(", "self", ",", "filename", ")" ]
https://github.com/Genius-x/genius-x/blob/9fc9f194e6d1fb92dd0e33d43db19ddb67cda7b0/cocos2d/tools/bindings-generator/clang/cindex.py#L2641-L2647
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/stc.py
python
StyledTextCtrl.StyleSetBackground
(*args, **kwargs)
return _stc.StyledTextCtrl_StyleSetBackground(*args, **kwargs)
StyleSetBackground(self, int style, Colour back) Set the background colour of a style.
StyleSetBackground(self, int style, Colour back)
[ "StyleSetBackground", "(", "self", "int", "style", "Colour", "back", ")" ]
def StyleSetBackground(*args, **kwargs): """ StyleSetBackground(self, int style, Colour back) Set the background colour of a style. """ return _stc.StyledTextCtrl_StyleSetBackground(*args, **kwargs)
[ "def", "StyleSetBackground", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_StyleSetBackground", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/stc.py#L2522-L2528
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
dom/bindings/parser/WebIDL.py
python
Parser.p_Const
(self, p)
Const : CONST ConstType IDENTIFIER EQUALS ConstValue SEMICOLON
Const : CONST ConstType IDENTIFIER EQUALS ConstValue SEMICOLON
[ "Const", ":", "CONST", "ConstType", "IDENTIFIER", "EQUALS", "ConstValue", "SEMICOLON" ]
def p_Const(self, p): """ Const : CONST ConstType IDENTIFIER EQUALS ConstValue SEMICOLON """ location = self.getLocation(p, 1) type = p[2] identifier = IDLUnresolvedIdentifier(self.getLocation(p, 3), p[3]) value = p[5] p[0] = IDLConst(location, identifier, type, value)
[ "def", "p_Const", "(", "self", ",", "p", ")", ":", "location", "=", "self", ".", "getLocation", "(", "p", ",", "1", ")", "type", "=", "p", "[", "2", "]", "identifier", "=", "IDLUnresolvedIdentifier", "(", "self", ".", "getLocation", "(", "p", ",", "3", ")", ",", "p", "[", "3", "]", ")", "value", "=", "p", "[", "5", "]", "p", "[", "0", "]", "=", "IDLConst", "(", "location", ",", "identifier", ",", "type", ",", "value", ")" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/dom/bindings/parser/WebIDL.py#L4554-L4562
SequoiaDB/SequoiaDB
2894ed7e5bd6fe57330afc900cf76d0ff0df9f64
tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py
python
xmlNode.newTextChild
(self, ns, name, content)
return __tmp
Creation of a new child element, added at the end of @parent children list. @ns and @content parameters are optional (None). If @ns is None, the newly created element inherits the namespace of @parent. If @content is non None, a child TEXT node will be created containing the string @content. NOTE: Use xmlNewChild() if @content will contain entities that need to be preserved. Use this function, xmlNewTextChild(), if you need to ensure that reserved XML chars that might appear in @content, such as the ampersand, greater-than or less-than signs, are automatically replaced by their XML escaped entity representations.
Creation of a new child element, added at the end of
[ "Creation", "of", "a", "new", "child", "element", "added", "at", "the", "end", "of" ]
def newTextChild(self, ns, name, content): """Creation of a new child element, added at the end of @parent children list. @ns and @content parameters are optional (None). If @ns is None, the newly created element inherits the namespace of @parent. If @content is non None, a child TEXT node will be created containing the string @content. NOTE: Use xmlNewChild() if @content will contain entities that need to be preserved. Use this function, xmlNewTextChild(), if you need to ensure that reserved XML chars that might appear in @content, such as the ampersand, greater-than or less-than signs, are automatically replaced by their XML escaped entity representations. """ if ns is None: ns__o = None else: ns__o = ns._o ret = libxml2mod.xmlNewTextChild(self._o, ns__o, name, content) if ret is None:raise treeError('xmlNewTextChild() failed') __tmp = xmlNode(_obj=ret) return __tmp
[ "def", "newTextChild", "(", "self", ",", "ns", ",", "name", ",", "content", ")", ":", "if", "ns", "is", "None", ":", "ns__o", "=", "None", "else", ":", "ns__o", "=", "ns", ".", "_o", "ret", "=", "libxml2mod", ".", "xmlNewTextChild", "(", "self", ".", "_o", ",", "ns__o", ",", "name", ",", "content", ")", "if", "ret", "is", "None", ":", "raise", "treeError", "(", "'xmlNewTextChild() failed'", ")", "__tmp", "=", "xmlNode", "(", "_obj", "=", "ret", ")", "return", "__tmp" ]
https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L3353-L3370
chromiumembedded/cef
80caf947f3fe2210e5344713c5281d8af9bdc295
tools/yapf/yapf/yapflib/format_token.py
python
FormatToken.must_split
(self)
return pytree_utils.GetNodeAnnotation(self.node, pytree_utils.Annotation.MUST_SPLIT)
Return true if the token requires a split before it.
Return true if the token requires a split before it.
[ "Return", "true", "if", "the", "token", "requires", "a", "split", "before", "it", "." ]
def must_split(self): """Return true if the token requires a split before it.""" return pytree_utils.GetNodeAnnotation(self.node, pytree_utils.Annotation.MUST_SPLIT)
[ "def", "must_split", "(", "self", ")", ":", "return", "pytree_utils", ".", "GetNodeAnnotation", "(", "self", ".", "node", ",", "pytree_utils", ".", "Annotation", ".", "MUST_SPLIT", ")" ]
https://github.com/chromiumembedded/cef/blob/80caf947f3fe2210e5344713c5281d8af9bdc295/tools/yapf/yapf/yapflib/format_token.py#L202-L205
sfzhang15/RefineDet
52b6fe23dc1a160fe710b7734576dca509bf4fae
scripts/cpp_lint.py
python
_CppLintState.SetVerboseLevel
(self, level)
return last_verbose_level
Sets the module's verbosity, and returns the previous setting.
Sets the module's verbosity, and returns the previous setting.
[ "Sets", "the", "module", "s", "verbosity", "and", "returns", "the", "previous", "setting", "." ]
def SetVerboseLevel(self, level): """Sets the module's verbosity, and returns the previous setting.""" last_verbose_level = self.verbose_level self.verbose_level = level return last_verbose_level
[ "def", "SetVerboseLevel", "(", "self", ",", "level", ")", ":", "last_verbose_level", "=", "self", ".", "verbose_level", "self", ".", "verbose_level", "=", "level", "return", "last_verbose_level" ]
https://github.com/sfzhang15/RefineDet/blob/52b6fe23dc1a160fe710b7734576dca509bf4fae/scripts/cpp_lint.py#L707-L711
DLR-SC/tigl
d1c5901e948e33d10b1f9659ff3e22c4717b455f
thirdparty/nsiqcppstyle/nsiqcppstyle_checker.py
python
t_COMMENT
(t)
return t
r'/\*(.|\n)*?\*/
r'/\*(.|\n)*?\*/
[ "r", "/", "\\", "*", "(", ".", "|", "\\", "n", ")", "*", "?", "\\", "*", "/" ]
def t_COMMENT(t): r'/\*(.|\n)*?\*/' t.lexer.lineno += t.value.count('\n') if Search(r"/\*\*\s", t.value) : t.additional = 'DOXYGEN' return t
[ "def", "t_COMMENT", "(", "t", ")", ":", "t", ".", "lexer", ".", "lineno", "+=", "t", ".", "value", ".", "count", "(", "'\\n'", ")", "if", "Search", "(", "r\"/\\*\\*\\s\"", ",", "t", ".", "value", ")", ":", "t", ".", "additional", "=", "'DOXYGEN'", "return", "t" ]
https://github.com/DLR-SC/tigl/blob/d1c5901e948e33d10b1f9659ff3e22c4717b455f/thirdparty/nsiqcppstyle/nsiqcppstyle_checker.py#L291-L296
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/build/waf-1.7.13/waflib/Tools/gxx.py
python
configure
(conf)
Configuration for g++
Configuration for g++
[ "Configuration", "for", "g", "++" ]
def configure(conf): """ Configuration for g++ """ conf.find_gxx() conf.find_ar() conf.gxx_common_flags() conf.gxx_modifier_platform() conf.cxx_load_tools() conf.cxx_add_flags() conf.link_add_flags()
[ "def", "configure", "(", "conf", ")", ":", "conf", ".", "find_gxx", "(", ")", "conf", ".", "find_ar", "(", ")", "conf", ".", "gxx_common_flags", "(", ")", "conf", ".", "gxx_modifier_platform", "(", ")", "conf", ".", "cxx_load_tools", "(", ")", "conf", ".", "cxx_add_flags", "(", ")", "conf", ".", "link_add_flags", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/Tools/gxx.py#L143-L153
HANDS-FREE/handsfree
3766907a44d46828cc9de462c1126ceeb8e14061
handsfree_smach/script/RadianTurn.py
python
RadianTurn.turn_to_target
(self, radian_to_turn=0.0)
to make robot turn target_radian radians :param: target_radian: the target radian that robot needs to turn :type: float :return:
to make robot turn target_radian radians :param: target_radian: the target radian that robot needs to turn :type: float :return:
[ "to", "make", "robot", "turn", "target_radian", "radians", ":", "param", ":", "target_radian", ":", "the", "target", "radian", "that", "robot", "needs", "to", "turn", ":", "type", ":", "float", ":", "return", ":" ]
def turn_to_target(self, radian_to_turn=0.0): """ to make robot turn target_radian radians :param: target_radian: the target radian that robot needs to turn :type: float :return: """ # the range of yaw of odom is -pi ~ pi, we transform it to 0 ~ 2*pi robot_start_yaw = (self.__get_robot_pos() + math.pi*2) % (math.pi*2) # to avoid the radian_to_turn value is bigger than 2*pi or less than -2*pi target_yaw = math.copysign(math.fabs(radian_to_turn)%(math.pi*2), radian_to_turn)+robot_start_yaw # to transform the range target_yaw = (target_yaw + math.pi*2) % (math.pi*2) # to find the shortest direction to turn radian_to_move = target_yaw-robot_start_yaw if radian_to_move < -math.pi or math.pi < radian_to_move: direction = 1 if radian_to_move < -math.pi else -1 else: direction = 1 if radian_to_move > 0 else -1 self.brake() # to stop robot first rospy.logdebug("****************************************************************************") rospy.logdebug("the robot's Yaw = %f, try to turn to Yaw = %f, the direction = %d" %(robot_start_yaw, target_yaw, direction)) rospy.logdebug("****************************************************************************") while self.__is_robot_arrived(target_yaw) is not True: self.__turn_robot(turn_direction=direction) self.rate.sleep() self.brake() rospy.loginfo('arrived the target radian!')
[ "def", "turn_to_target", "(", "self", ",", "radian_to_turn", "=", "0.0", ")", ":", "# the range of yaw of odom is -pi ~ pi, we transform it to 0 ~ 2*pi", "robot_start_yaw", "=", "(", "self", ".", "__get_robot_pos", "(", ")", "+", "math", ".", "pi", "*", "2", ")", "%", "(", "math", ".", "pi", "*", "2", ")", "# to avoid the radian_to_turn value is bigger than 2*pi or less than -2*pi", "target_yaw", "=", "math", ".", "copysign", "(", "math", ".", "fabs", "(", "radian_to_turn", ")", "%", "(", "math", ".", "pi", "*", "2", ")", ",", "radian_to_turn", ")", "+", "robot_start_yaw", "# to transform the range", "target_yaw", "=", "(", "target_yaw", "+", "math", ".", "pi", "*", "2", ")", "%", "(", "math", ".", "pi", "*", "2", ")", "# to find the shortest direction to turn", "radian_to_move", "=", "target_yaw", "-", "robot_start_yaw", "if", "radian_to_move", "<", "-", "math", ".", "pi", "or", "math", ".", "pi", "<", "radian_to_move", ":", "direction", "=", "1", "if", "radian_to_move", "<", "-", "math", ".", "pi", "else", "-", "1", "else", ":", "direction", "=", "1", "if", "radian_to_move", ">", "0", "else", "-", "1", "self", ".", "brake", "(", ")", "# to stop robot first", "rospy", ".", "logdebug", "(", "\"****************************************************************************\"", ")", "rospy", ".", "logdebug", "(", "\"the robot's Yaw = %f, try to turn to Yaw = %f, the direction = %d\"", "%", "(", "robot_start_yaw", ",", "target_yaw", ",", "direction", ")", ")", "rospy", ".", "logdebug", "(", "\"****************************************************************************\"", ")", "while", "self", ".", "__is_robot_arrived", "(", "target_yaw", ")", "is", "not", "True", ":", "self", ".", "__turn_robot", "(", "turn_direction", "=", "direction", ")", "self", ".", "rate", ".", "sleep", "(", ")", "self", ".", "brake", "(", ")", "rospy", ".", "loginfo", "(", "'arrived the target radian!'", ")" ]
https://github.com/HANDS-FREE/handsfree/blob/3766907a44d46828cc9de462c1126ceeb8e14061/handsfree_smach/script/RadianTurn.py#L33-L64