nwo
stringlengths
5
86
sha
stringlengths
40
40
path
stringlengths
4
189
language
stringclasses
1 value
identifier
stringlengths
1
94
parameters
stringlengths
2
4.03k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
11.5k
docstring
stringlengths
1
33.2k
docstring_summary
stringlengths
0
5.15k
docstring_tokens
list
function
stringlengths
34
151k
function_tokens
list
url
stringlengths
90
278
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/unicode.py
python
_codepoint_is_ascii
(ch)
return ch < 128
Returns true if a codepoint is in the ASCII range
Returns true if a codepoint is in the ASCII range
[ "Returns", "true", "if", "a", "codepoint", "is", "in", "the", "ASCII", "range" ]
def _codepoint_is_ascii(ch): """ Returns true if a codepoint is in the ASCII range """ return ch < 128
[ "def", "_codepoint_is_ascii", "(", "ch", ")", ":", "return", "ch", "<", "128" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/unicode.py#L409-L413
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/learn/python/learn/estimators/model_fn.py
python
ModelFnOps.estimator_spec
(self, default_serving_output_alternative_key=None)
return core_model_fn_lib.EstimatorSpec( mode=core_mode, predictions=self.predictions, loss=self.loss, train_op=self.train_op, eval_metric_ops=_get_eval_metric_ops(), export_outputs=export_outputs_dict, training_chief_hooks=self.training_chief_hooks, training_hooks=self.training_hooks, scaffold=self.scaffold)
Creates an equivalent `EstimatorSpec`. Args: default_serving_output_alternative_key: Required for multiple heads. If you have multiple entries in `output_alternatives` dict (comparable to multiple heads), `EstimatorSpec` requires a default head that will be used if a Servo request does not explicitly mention which head to infer on. Pass the key of the output alternative here that you want to designate as default. A separate ExportOutpout for this default head wil be added to the export_outputs dict with the special key signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, unless there is already an enry in output_alternatives with this special key. Returns: Instance of `EstimatorSpec` that is equivalent to this `ModelFnOps` Raises: ValueError: If problem type is unknown.
Creates an equivalent `EstimatorSpec`.
[ "Creates", "an", "equivalent", "EstimatorSpec", "." ]
def estimator_spec(self, default_serving_output_alternative_key=None): """Creates an equivalent `EstimatorSpec`. Args: default_serving_output_alternative_key: Required for multiple heads. If you have multiple entries in `output_alternatives` dict (comparable to multiple heads), `EstimatorSpec` requires a default head that will be used if a Servo request does not explicitly mention which head to infer on. Pass the key of the output alternative here that you want to designate as default. A separate ExportOutpout for this default head wil be added to the export_outputs dict with the special key signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, unless there is already an enry in output_alternatives with this special key. Returns: Instance of `EstimatorSpec` that is equivalent to this `ModelFnOps` Raises: ValueError: If problem type is unknown. """ def _scores(output_tensors): scores = output_tensors.get(prediction_key.PredictionKey.SCORES) if scores is None: scores = output_tensors.get(prediction_key.PredictionKey.PROBABILITIES) return scores def _classes(output_tensors): # pylint: disable=missing-docstring classes = output_tensors.get(prediction_key.PredictionKey.CLASSES) if classes is None: logging.warning( 'classes is None, Servo inference will not have class ids.') return None elif classes.dtype != dtypes.string: # Servo classification can only serve string classes logging.warning( 'classes is not string, Servo inference will not have class ids.') return None return classes def _export_output(problem_type, predictions): # pylint: disable=missing-docstring if problem_type == constants.ProblemType.LINEAR_REGRESSION: return core_export_lib.RegressionOutput(_scores(predictions)) if (problem_type == constants.ProblemType.CLASSIFICATION or problem_type == constants.ProblemType.LOGISTIC_REGRESSION): return core_export_lib.ClassificationOutput( scores=_scores(predictions), classes=_classes(predictions)) if problem_type == constants.ProblemType.UNSPECIFIED: return core_export_lib.PredictOutput(predictions) raise ValueError('Unknown problem_type=%s' % problem_type) # Converts output_alternatives export_outputs_dict = None if self.output_alternatives: output_alternatives = self.output_alternatives # Adds default output_alternative if needed. if (len(output_alternatives) > 1 and signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY not in output_alternatives): output_alternatives = output_alternatives.copy() output_alternatives[ signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY] = ( output_alternatives[default_serving_output_alternative_key]) export_outputs_dict = {key: _export_output(*val) for key, val in output_alternatives.items()} def _get_eval_metric_ops(): """Returns self.eval_metric_ops without loss metric.""" result = {} for key, value in six.iteritems(self.eval_metric_ops): if key != metric_key.MetricKey.LOSS: result[key] = value return result # Convert the contrib mode enum to the core mode enum. # Note: mode already validated in __new__(). if self.mode == ModeKeys.TRAIN: core_mode = core_model_fn_lib.ModeKeys.TRAIN elif self.mode == ModeKeys.EVAL: core_mode = core_model_fn_lib.ModeKeys.EVAL elif self.mode == ModeKeys.INFER: core_mode = core_model_fn_lib.ModeKeys.PREDICT return core_model_fn_lib.EstimatorSpec( mode=core_mode, predictions=self.predictions, loss=self.loss, train_op=self.train_op, eval_metric_ops=_get_eval_metric_ops(), export_outputs=export_outputs_dict, training_chief_hooks=self.training_chief_hooks, training_hooks=self.training_hooks, scaffold=self.scaffold)
[ "def", "estimator_spec", "(", "self", ",", "default_serving_output_alternative_key", "=", "None", ")", ":", "def", "_scores", "(", "output_tensors", ")", ":", "scores", "=", "output_tensors", ".", "get", "(", "prediction_key", ".", "PredictionKey", ".", "SCORES", ")", "if", "scores", "is", "None", ":", "scores", "=", "output_tensors", ".", "get", "(", "prediction_key", ".", "PredictionKey", ".", "PROBABILITIES", ")", "return", "scores", "def", "_classes", "(", "output_tensors", ")", ":", "# pylint: disable=missing-docstring", "classes", "=", "output_tensors", ".", "get", "(", "prediction_key", ".", "PredictionKey", ".", "CLASSES", ")", "if", "classes", "is", "None", ":", "logging", ".", "warning", "(", "'classes is None, Servo inference will not have class ids.'", ")", "return", "None", "elif", "classes", ".", "dtype", "!=", "dtypes", ".", "string", ":", "# Servo classification can only serve string classes", "logging", ".", "warning", "(", "'classes is not string, Servo inference will not have class ids.'", ")", "return", "None", "return", "classes", "def", "_export_output", "(", "problem_type", ",", "predictions", ")", ":", "# pylint: disable=missing-docstring", "if", "problem_type", "==", "constants", ".", "ProblemType", ".", "LINEAR_REGRESSION", ":", "return", "core_export_lib", ".", "RegressionOutput", "(", "_scores", "(", "predictions", ")", ")", "if", "(", "problem_type", "==", "constants", ".", "ProblemType", ".", "CLASSIFICATION", "or", "problem_type", "==", "constants", ".", "ProblemType", ".", "LOGISTIC_REGRESSION", ")", ":", "return", "core_export_lib", ".", "ClassificationOutput", "(", "scores", "=", "_scores", "(", "predictions", ")", ",", "classes", "=", "_classes", "(", "predictions", ")", ")", "if", "problem_type", "==", "constants", ".", "ProblemType", ".", "UNSPECIFIED", ":", "return", "core_export_lib", ".", "PredictOutput", "(", "predictions", ")", "raise", "ValueError", "(", "'Unknown problem_type=%s'", "%", "problem_type", ")", "# Converts output_alternatives", "export_outputs_dict", "=", "None", "if", "self", ".", "output_alternatives", ":", "output_alternatives", "=", "self", ".", "output_alternatives", "# Adds default output_alternative if needed.", "if", "(", "len", "(", "output_alternatives", ")", ">", "1", "and", "signature_constants", ".", "DEFAULT_SERVING_SIGNATURE_DEF_KEY", "not", "in", "output_alternatives", ")", ":", "output_alternatives", "=", "output_alternatives", ".", "copy", "(", ")", "output_alternatives", "[", "signature_constants", ".", "DEFAULT_SERVING_SIGNATURE_DEF_KEY", "]", "=", "(", "output_alternatives", "[", "default_serving_output_alternative_key", "]", ")", "export_outputs_dict", "=", "{", "key", ":", "_export_output", "(", "*", "val", ")", "for", "key", ",", "val", "in", "output_alternatives", ".", "items", "(", ")", "}", "def", "_get_eval_metric_ops", "(", ")", ":", "\"\"\"Returns self.eval_metric_ops without loss metric.\"\"\"", "result", "=", "{", "}", "for", "key", ",", "value", "in", "six", ".", "iteritems", "(", "self", ".", "eval_metric_ops", ")", ":", "if", "key", "!=", "metric_key", ".", "MetricKey", ".", "LOSS", ":", "result", "[", "key", "]", "=", "value", "return", "result", "# Convert the contrib mode enum to the core mode enum.", "# Note: mode already validated in __new__().", "if", "self", ".", "mode", "==", "ModeKeys", ".", "TRAIN", ":", "core_mode", "=", "core_model_fn_lib", ".", "ModeKeys", ".", "TRAIN", "elif", "self", ".", "mode", "==", "ModeKeys", ".", "EVAL", ":", "core_mode", "=", "core_model_fn_lib", ".", "ModeKeys", ".", "EVAL", "elif", "self", ".", "mode", "==", "ModeKeys", ".", "INFER", ":", "core_mode", "=", "core_model_fn_lib", ".", "ModeKeys", ".", "PREDICT", "return", "core_model_fn_lib", ".", "EstimatorSpec", "(", "mode", "=", "core_mode", ",", "predictions", "=", "self", ".", "predictions", ",", "loss", "=", "self", ".", "loss", ",", "train_op", "=", "self", ".", "train_op", ",", "eval_metric_ops", "=", "_get_eval_metric_ops", "(", ")", ",", "export_outputs", "=", "export_outputs_dict", ",", "training_chief_hooks", "=", "self", ".", "training_chief_hooks", ",", "training_hooks", "=", "self", ".", "training_hooks", ",", "scaffold", "=", "self", ".", "scaffold", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/learn/python/learn/estimators/model_fn.py#L196-L291
vesoft-inc/nebula
25a06217ebaf169e1f0e5ff6a797ba6f0c41fc35
.linters/cpp/cpplint.py
python
GetHeaderGuardCPPVariable
(filename)
return re.sub(r'[^a-zA-Z0-9]', '_', file_path_from_root).upper() + '_'
Returns the CPP variable that should be used as a header guard. Args: filename: The name of a C++ header file. Returns: The CPP variable that should be used as a header guard in the named file.
Returns the CPP variable that should be used as a header guard.
[ "Returns", "the", "CPP", "variable", "that", "should", "be", "used", "as", "a", "header", "guard", "." ]
def GetHeaderGuardCPPVariable(filename): """Returns the CPP variable that should be used as a header guard. Args: filename: The name of a C++ header file. Returns: The CPP variable that should be used as a header guard in the named file. """ # Restores original filename in case that cpplint is invoked from Emacs's # flymake. filename = re.sub(r'_flymake\.h$', '.h', filename) filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename) # Replace 'c++' with 'cpp'. filename = filename.replace('C++', 'cpp').replace('c++', 'cpp') fileinfo = FileInfo(filename) file_path_from_root = fileinfo.RepositoryName() def FixupPathFromRoot(): if _root_debug: sys.stderr.write("\n_root fixup, _root = '%s', repository name = '%s'\n" % (_root, fileinfo.RepositoryName())) # Process the file path with the --root flag if it was set. if not _root: if _root_debug: sys.stderr.write("_root unspecified\n") return file_path_from_root def StripListPrefix(lst, prefix): # f(['x', 'y'], ['w, z']) -> None (not a valid prefix) if lst[:len(prefix)] != prefix: return None # f(['a, 'b', 'c', 'd'], ['a', 'b']) -> ['c', 'd'] return lst[(len(prefix)):] # root behavior: # --root=subdir , lstrips subdir from the header guard maybe_path = StripListPrefix(PathSplitToList(file_path_from_root), PathSplitToList(_root)) if _root_debug: sys.stderr.write(("_root lstrip (maybe_path=%s, file_path_from_root=%s," + " _root=%s)\n") % (maybe_path, file_path_from_root, _root)) if maybe_path: return os.path.join(*maybe_path) # --root=.. , will prepend the outer directory to the header guard full_path = fileinfo.FullName() root_abspath = os.path.abspath(_root) maybe_path = StripListPrefix(PathSplitToList(full_path), PathSplitToList(root_abspath)) if _root_debug: sys.stderr.write(("_root prepend (maybe_path=%s, full_path=%s, " + "root_abspath=%s)\n") % (maybe_path, full_path, root_abspath)) if maybe_path: return os.path.join(*maybe_path) if _root_debug: sys.stderr.write("_root ignore, returning %s\n" % (file_path_from_root)) # --root=FAKE_DIR is ignored return file_path_from_root file_path_from_root = FixupPathFromRoot() return re.sub(r'[^a-zA-Z0-9]', '_', file_path_from_root).upper() + '_'
[ "def", "GetHeaderGuardCPPVariable", "(", "filename", ")", ":", "# Restores original filename in case that cpplint is invoked from Emacs's", "# flymake.", "filename", "=", "re", ".", "sub", "(", "r'_flymake\\.h$'", ",", "'.h'", ",", "filename", ")", "filename", "=", "re", ".", "sub", "(", "r'/\\.flymake/([^/]*)$'", ",", "r'/\\1'", ",", "filename", ")", "# Replace 'c++' with 'cpp'.", "filename", "=", "filename", ".", "replace", "(", "'C++'", ",", "'cpp'", ")", ".", "replace", "(", "'c++'", ",", "'cpp'", ")", "fileinfo", "=", "FileInfo", "(", "filename", ")", "file_path_from_root", "=", "fileinfo", ".", "RepositoryName", "(", ")", "def", "FixupPathFromRoot", "(", ")", ":", "if", "_root_debug", ":", "sys", ".", "stderr", ".", "write", "(", "\"\\n_root fixup, _root = '%s', repository name = '%s'\\n\"", "%", "(", "_root", ",", "fileinfo", ".", "RepositoryName", "(", ")", ")", ")", "# Process the file path with the --root flag if it was set.", "if", "not", "_root", ":", "if", "_root_debug", ":", "sys", ".", "stderr", ".", "write", "(", "\"_root unspecified\\n\"", ")", "return", "file_path_from_root", "def", "StripListPrefix", "(", "lst", ",", "prefix", ")", ":", "# f(['x', 'y'], ['w, z']) -> None (not a valid prefix)", "if", "lst", "[", ":", "len", "(", "prefix", ")", "]", "!=", "prefix", ":", "return", "None", "# f(['a, 'b', 'c', 'd'], ['a', 'b']) -> ['c', 'd']", "return", "lst", "[", "(", "len", "(", "prefix", ")", ")", ":", "]", "# root behavior:", "# --root=subdir , lstrips subdir from the header guard", "maybe_path", "=", "StripListPrefix", "(", "PathSplitToList", "(", "file_path_from_root", ")", ",", "PathSplitToList", "(", "_root", ")", ")", "if", "_root_debug", ":", "sys", ".", "stderr", ".", "write", "(", "(", "\"_root lstrip (maybe_path=%s, file_path_from_root=%s,\"", "+", "\" _root=%s)\\n\"", ")", "%", "(", "maybe_path", ",", "file_path_from_root", ",", "_root", ")", ")", "if", "maybe_path", ":", "return", "os", ".", "path", ".", "join", "(", "*", "maybe_path", ")", "# --root=.. , will prepend the outer directory to the header guard", "full_path", "=", "fileinfo", ".", "FullName", "(", ")", "root_abspath", "=", "os", ".", "path", ".", "abspath", "(", "_root", ")", "maybe_path", "=", "StripListPrefix", "(", "PathSplitToList", "(", "full_path", ")", ",", "PathSplitToList", "(", "root_abspath", ")", ")", "if", "_root_debug", ":", "sys", ".", "stderr", ".", "write", "(", "(", "\"_root prepend (maybe_path=%s, full_path=%s, \"", "+", "\"root_abspath=%s)\\n\"", ")", "%", "(", "maybe_path", ",", "full_path", ",", "root_abspath", ")", ")", "if", "maybe_path", ":", "return", "os", ".", "path", ".", "join", "(", "*", "maybe_path", ")", "if", "_root_debug", ":", "sys", ".", "stderr", ".", "write", "(", "\"_root ignore, returning %s\\n\"", "%", "(", "file_path_from_root", ")", ")", "# --root=FAKE_DIR is ignored", "return", "file_path_from_root", "file_path_from_root", "=", "FixupPathFromRoot", "(", ")", "return", "re", ".", "sub", "(", "r'[^a-zA-Z0-9]'", ",", "'_'", ",", "file_path_from_root", ")", ".", "upper", "(", ")", "+", "'_'" ]
https://github.com/vesoft-inc/nebula/blob/25a06217ebaf169e1f0e5ff6a797ba6f0c41fc35/.linters/cpp/cpplint.py#L2034-L2107
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
deps/src/libxml2-2.9.1/python/libxml2class.py
python
xmlDoc.newDocNodeEatName
(self, ns, name, content)
return __tmp
Creation of a new node element within a document. @ns and @content are optional (None). NOTE: @content is supposed to be a piece of XML CDATA, so it allow entities references, but XML special chars need to be escaped first by using xmlEncodeEntitiesReentrant(). Use xmlNewDocRawNode() if you don't need entities support.
Creation of a new node element within a document.
[ "Creation", "of", "a", "new", "node", "element", "within", "a", "document", "." ]
def newDocNodeEatName(self, ns, name, content): """Creation of a new node element within a document. @ns and @content are optional (None). NOTE: @content is supposed to be a piece of XML CDATA, so it allow entities references, but XML special chars need to be escaped first by using xmlEncodeEntitiesReentrant(). Use xmlNewDocRawNode() if you don't need entities support. """ if ns is None: ns__o = None else: ns__o = ns._o ret = libxml2mod.xmlNewDocNodeEatName(self._o, ns__o, name, content) if ret is None:raise treeError('xmlNewDocNodeEatName() failed') __tmp = xmlNode(_obj=ret) return __tmp
[ "def", "newDocNodeEatName", "(", "self", ",", "ns", ",", "name", ",", "content", ")", ":", "if", "ns", "is", "None", ":", "ns__o", "=", "None", "else", ":", "ns__o", "=", "ns", ".", "_o", "ret", "=", "libxml2mod", ".", "xmlNewDocNodeEatName", "(", "self", ".", "_o", ",", "ns__o", ",", "name", ",", "content", ")", "if", "ret", "is", "None", ":", "raise", "treeError", "(", "'xmlNewDocNodeEatName() failed'", ")", "__tmp", "=", "xmlNode", "(", "_obj", "=", "ret", ")", "return", "__tmp" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2class.py#L3556-L3568
crosslife/OpenBird
9e0198a1a2295f03fa1e8676e216e22c9c7d380b
cocos2d/tools/bindings-generator/clang/cindex.py
python
AccessSpecifierKind.get_all_kinds
()
return filter(None, AccessSpecifierKind._kinds)
Return all AccessSpecifierKind enumeration instances.
Return all AccessSpecifierKind enumeration instances.
[ "Return", "all", "AccessSpecifierKind", "enumeration", "instances", "." ]
def get_all_kinds(): """Return all AccessSpecifierKind enumeration instances.""" return filter(None, AccessSpecifierKind._kinds)
[ "def", "get_all_kinds", "(", ")", ":", "return", "filter", "(", "None", ",", "AccessSpecifierKind", ".", "_kinds", ")" ]
https://github.com/crosslife/OpenBird/blob/9e0198a1a2295f03fa1e8676e216e22c9c7d380b/cocos2d/tools/bindings-generator/clang/cindex.py#L424-L426
KratosMultiphysics/Kratos
0000833054ed0503424eb28205d6508d9ca6cbbc
applications/StructuralMechanicsApplication/python_scripts/structural_mechanics_analysis.py
python
StructuralMechanicsAnalysis.OutputSolutionStep
(self)
This function printed / writes output files after the solution of a step
This function printed / writes output files after the solution of a step
[ "This", "function", "printed", "/", "writes", "output", "files", "after", "the", "solution", "of", "a", "step" ]
def OutputSolutionStep(self): """This function printed / writes output files after the solution of a step """ # In case of contact problem if self.contact_problem: # First we check if one of the output processes will print output in this step this is done to save computation in case none of them will print is_output_step = False for output_process in self._GetListOfOutputProcesses(): if output_process.IsOutputStep(): is_output_step = True break if is_output_step: # Informing the output will be created KratosMultiphysics.Logger.PrintWarning("StructuralMechanicsAnalysis", "STEP: ", self._GetSolver().GetComputingModelPart().ProcessInfo[KratosMultiphysics.STEP]) KratosMultiphysics.Logger.PrintWarning("StructuralMechanicsAnalysis", "TIME: ", self.time) # Creating output super().OutputSolutionStep()
[ "def", "OutputSolutionStep", "(", "self", ")", ":", "# In case of contact problem", "if", "self", ".", "contact_problem", ":", "# First we check if one of the output processes will print output in this step this is done to save computation in case none of them will print", "is_output_step", "=", "False", "for", "output_process", "in", "self", ".", "_GetListOfOutputProcesses", "(", ")", ":", "if", "output_process", ".", "IsOutputStep", "(", ")", ":", "is_output_step", "=", "True", "break", "if", "is_output_step", ":", "# Informing the output will be created", "KratosMultiphysics", ".", "Logger", ".", "PrintWarning", "(", "\"StructuralMechanicsAnalysis\"", ",", "\"STEP: \"", ",", "self", ".", "_GetSolver", "(", ")", ".", "GetComputingModelPart", "(", ")", ".", "ProcessInfo", "[", "KratosMultiphysics", ".", "STEP", "]", ")", "KratosMultiphysics", ".", "Logger", ".", "PrintWarning", "(", "\"StructuralMechanicsAnalysis\"", ",", "\"TIME: \"", ",", "self", ".", "time", ")", "# Creating output", "super", "(", ")", ".", "OutputSolutionStep", "(", ")" ]
https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/StructuralMechanicsApplication/python_scripts/structural_mechanics_analysis.py#L51-L70
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/decomposition/_pca.py
python
PCA._fit_full
(self, X, n_components)
return U, S, V
Fit the model by computing full SVD on X
Fit the model by computing full SVD on X
[ "Fit", "the", "model", "by", "computing", "full", "SVD", "on", "X" ]
def _fit_full(self, X, n_components): """Fit the model by computing full SVD on X""" n_samples, n_features = X.shape if n_components == 'mle': if n_samples < n_features: raise ValueError("n_components='mle' is only supported " "if n_samples >= n_features") elif not 0 <= n_components <= min(n_samples, n_features): raise ValueError("n_components=%r must be between 0 and " "min(n_samples, n_features)=%r with " "svd_solver='full'" % (n_components, min(n_samples, n_features))) elif n_components >= 1: if not isinstance(n_components, numbers.Integral): raise ValueError("n_components=%r must be of type int " "when greater than or equal to 1, " "was of type=%r" % (n_components, type(n_components))) # Center data self.mean_ = np.mean(X, axis=0) X -= self.mean_ U, S, V = linalg.svd(X, full_matrices=False) # flip eigenvectors' sign to enforce deterministic output U, V = svd_flip(U, V) components_ = V # Get variance explained by singular values explained_variance_ = (S ** 2) / (n_samples - 1) total_var = explained_variance_.sum() explained_variance_ratio_ = explained_variance_ / total_var singular_values_ = S.copy() # Store the singular values. # Postprocess the number of components required if n_components == 'mle': n_components = \ _infer_dimension_(explained_variance_, n_samples, n_features) elif 0 < n_components < 1.0: # number of components for which the cumulated explained # variance percentage is superior to the desired threshold ratio_cumsum = stable_cumsum(explained_variance_ratio_) n_components = np.searchsorted(ratio_cumsum, n_components) + 1 # Compute noise covariance using Probabilistic PCA model # The sigma2 maximum likelihood (cf. eq. 12.46) if n_components < min(n_features, n_samples): self.noise_variance_ = explained_variance_[n_components:].mean() else: self.noise_variance_ = 0. self.n_samples_, self.n_features_ = n_samples, n_features self.components_ = components_[:n_components] self.n_components_ = n_components self.explained_variance_ = explained_variance_[:n_components] self.explained_variance_ratio_ = \ explained_variance_ratio_[:n_components] self.singular_values_ = singular_values_[:n_components] return U, S, V
[ "def", "_fit_full", "(", "self", ",", "X", ",", "n_components", ")", ":", "n_samples", ",", "n_features", "=", "X", ".", "shape", "if", "n_components", "==", "'mle'", ":", "if", "n_samples", "<", "n_features", ":", "raise", "ValueError", "(", "\"n_components='mle' is only supported \"", "\"if n_samples >= n_features\"", ")", "elif", "not", "0", "<=", "n_components", "<=", "min", "(", "n_samples", ",", "n_features", ")", ":", "raise", "ValueError", "(", "\"n_components=%r must be between 0 and \"", "\"min(n_samples, n_features)=%r with \"", "\"svd_solver='full'\"", "%", "(", "n_components", ",", "min", "(", "n_samples", ",", "n_features", ")", ")", ")", "elif", "n_components", ">=", "1", ":", "if", "not", "isinstance", "(", "n_components", ",", "numbers", ".", "Integral", ")", ":", "raise", "ValueError", "(", "\"n_components=%r must be of type int \"", "\"when greater than or equal to 1, \"", "\"was of type=%r\"", "%", "(", "n_components", ",", "type", "(", "n_components", ")", ")", ")", "# Center data", "self", ".", "mean_", "=", "np", ".", "mean", "(", "X", ",", "axis", "=", "0", ")", "X", "-=", "self", ".", "mean_", "U", ",", "S", ",", "V", "=", "linalg", ".", "svd", "(", "X", ",", "full_matrices", "=", "False", ")", "# flip eigenvectors' sign to enforce deterministic output", "U", ",", "V", "=", "svd_flip", "(", "U", ",", "V", ")", "components_", "=", "V", "# Get variance explained by singular values", "explained_variance_", "=", "(", "S", "**", "2", ")", "/", "(", "n_samples", "-", "1", ")", "total_var", "=", "explained_variance_", ".", "sum", "(", ")", "explained_variance_ratio_", "=", "explained_variance_", "/", "total_var", "singular_values_", "=", "S", ".", "copy", "(", ")", "# Store the singular values.", "# Postprocess the number of components required", "if", "n_components", "==", "'mle'", ":", "n_components", "=", "_infer_dimension_", "(", "explained_variance_", ",", "n_samples", ",", "n_features", ")", "elif", "0", "<", "n_components", "<", "1.0", ":", "# number of components for which the cumulated explained", "# variance percentage is superior to the desired threshold", "ratio_cumsum", "=", "stable_cumsum", "(", "explained_variance_ratio_", ")", "n_components", "=", "np", ".", "searchsorted", "(", "ratio_cumsum", ",", "n_components", ")", "+", "1", "# Compute noise covariance using Probabilistic PCA model", "# The sigma2 maximum likelihood (cf. eq. 12.46)", "if", "n_components", "<", "min", "(", "n_features", ",", "n_samples", ")", ":", "self", ".", "noise_variance_", "=", "explained_variance_", "[", "n_components", ":", "]", ".", "mean", "(", ")", "else", ":", "self", ".", "noise_variance_", "=", "0.", "self", ".", "n_samples_", ",", "self", ".", "n_features_", "=", "n_samples", ",", "n_features", "self", ".", "components_", "=", "components_", "[", ":", "n_components", "]", "self", ".", "n_components_", "=", "n_components", "self", ".", "explained_variance_", "=", "explained_variance_", "[", ":", "n_components", "]", "self", ".", "explained_variance_ratio_", "=", "explained_variance_ratio_", "[", ":", "n_components", "]", "self", ".", "singular_values_", "=", "singular_values_", "[", ":", "n_components", "]", "return", "U", ",", "S", ",", "V" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/decomposition/_pca.py#L423-L484
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/series.py
python
Series.keys
(self)
return self.index
Return alias for index. Returns ------- Index Index of the Series.
Return alias for index.
[ "Return", "alias", "for", "index", "." ]
def keys(self): """ Return alias for index. Returns ------- Index Index of the Series. """ return self.index
[ "def", "keys", "(", "self", ")", ":", "return", "self", ".", "index" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/series.py#L1514-L1523
epam/Indigo
30e40b4b1eb9bae0207435a26cfcb81ddcc42be1
api/python/indigo/ml/mpp/datasets.py
python
MolDataset.process
(self)
Process graph data and set attributes to dataset
Process graph data and set attributes to dataset
[ "Process", "graph", "data", "and", "set", "attributes", "to", "dataset" ]
def process(self): "Process graph data and set attributes to dataset" df = pd.read_csv(config.file_name) df = df.loc[df[config.target].notnull()] data = dict(zip(df[config.smiles], df[config.target])) self.graphs = [] self.labels = [] for smiles, label in data.items(): self.graphs.append(mol_to_graph(smiles)) self.labels.append(label) self.gclasses = len(self.labels) self.dim_nfeats = len(self.graphs[0].ndata["atomic"][0]) self.dim_efeats = len(self.graphs[0].edata["ord"][0]) self.labels = FloatTensor(self.labels)
[ "def", "process", "(", "self", ")", ":", "df", "=", "pd", ".", "read_csv", "(", "config", ".", "file_name", ")", "df", "=", "df", ".", "loc", "[", "df", "[", "config", ".", "target", "]", ".", "notnull", "(", ")", "]", "data", "=", "dict", "(", "zip", "(", "df", "[", "config", ".", "smiles", "]", ",", "df", "[", "config", ".", "target", "]", ")", ")", "self", ".", "graphs", "=", "[", "]", "self", ".", "labels", "=", "[", "]", "for", "smiles", ",", "label", "in", "data", ".", "items", "(", ")", ":", "self", ".", "graphs", ".", "append", "(", "mol_to_graph", "(", "smiles", ")", ")", "self", ".", "labels", ".", "append", "(", "label", ")", "self", ".", "gclasses", "=", "len", "(", "self", ".", "labels", ")", "self", ".", "dim_nfeats", "=", "len", "(", "self", ".", "graphs", "[", "0", "]", ".", "ndata", "[", "\"atomic\"", "]", "[", "0", "]", ")", "self", ".", "dim_efeats", "=", "len", "(", "self", ".", "graphs", "[", "0", "]", ".", "edata", "[", "\"ord\"", "]", "[", "0", "]", ")", "self", ".", "labels", "=", "FloatTensor", "(", "self", ".", "labels", ")" ]
https://github.com/epam/Indigo/blob/30e40b4b1eb9bae0207435a26cfcb81ddcc42be1/api/python/indigo/ml/mpp/datasets.py#L16-L30
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/strict_enum_value_checker/strict_enum_value_checker.py
python
StrictEnumValueChecker.CheckForFileDeletion
(self, affected_file)
return True
Emits a warning notification if file has been deleted
Emits a warning notification if file has been deleted
[ "Emits", "a", "warning", "notification", "if", "file", "has", "been", "deleted" ]
def CheckForFileDeletion(self, affected_file): """Emits a warning notification if file has been deleted """ if not affected_file.NewContents(): self.EmitWarning("The file seems to be deleted in the changelist. If " "your intent is to really delete the file, the code in " "PRESUBMIT.py should be updated to remove the " "|StrictEnumValueChecker| class."); return False return True
[ "def", "CheckForFileDeletion", "(", "self", ",", "affected_file", ")", ":", "if", "not", "affected_file", ".", "NewContents", "(", ")", ":", "self", ".", "EmitWarning", "(", "\"The file seems to be deleted in the changelist. If \"", "\"your intent is to really delete the file, the code in \"", "\"PRESUBMIT.py should be updated to remove the \"", "\"|StrictEnumValueChecker| class.\"", ")", "return", "False", "return", "True" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/strict_enum_value_checker/strict_enum_value_checker.py#L162-L170
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/protobuf/python/google/protobuf/internal/containers.py
python
RepeatedScalarFieldContainer.__delslice__
(self, start, stop)
Deletes the subset of items from between the specified indices.
Deletes the subset of items from between the specified indices.
[ "Deletes", "the", "subset", "of", "items", "from", "between", "the", "specified", "indices", "." ]
def __delslice__(self, start, stop): """Deletes the subset of items from between the specified indices.""" del self._values[start:stop] self._message_listener.Modified()
[ "def", "__delslice__", "(", "self", ",", "start", ",", "stop", ")", ":", "del", "self", ".", "_values", "[", "start", ":", "stop", "]", "self", ".", "_message_listener", ".", "Modified", "(", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/protobuf/python/google/protobuf/internal/containers.py#L325-L328
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/contrib/distributions/python/ops/dirichlet_multinomial.py
python
DirichletMultinomial.validate_args
(self)
return self._validate_args
Boolean describing behavior on invalid input.
Boolean describing behavior on invalid input.
[ "Boolean", "describing", "behavior", "on", "invalid", "input", "." ]
def validate_args(self): """Boolean describing behavior on invalid input.""" return self._validate_args
[ "def", "validate_args", "(", "self", ")", ":", "return", "self", ".", "_validate_args" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/dirichlet_multinomial.py#L186-L188
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/math_ops.py
python
cast
(x, dtype, name=None)
Casts a tensor to a new type. The operation casts `x` (in case of `Tensor`) or `x.values` (in case of `SparseTensor` or `IndexedSlices`) to `dtype`. For example: ```python x = tf.constant([1.8, 2.2], dtype=tf.float32) tf.dtypes.cast(x, tf.int32) # [1, 2], dtype=tf.int32 ``` The operation supports data types (for `x` and `dtype`) of `uint8`, `uint16`, `uint32`, `uint64`, `int8`, `int16`, `int32`, `int64`, `float16`, `float32`, `float64`, `complex64`, `complex128`, `bfloat16`. In case of casting from complex types (`complex64`, `complex128`) to real types, only the real part of `x` is returned. In case of casting from real types to complex types (`complex64`, `complex128`), the imaginary part of the returned value is set to `0`. The handling of complex types here matches the behavior of numpy. Args: x: A `Tensor` or `SparseTensor` or `IndexedSlices` of numeric type. It could be `uint8`, `uint16`, `uint32`, `uint64`, `int8`, `int16`, `int32`, `int64`, `float16`, `float32`, `float64`, `complex64`, `complex128`, `bfloat16`. dtype: The destination type. The list of supported dtypes is the same as `x`. name: A name for the operation (optional). Returns: A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` and same type as `dtype`. Raises: TypeError: If `x` cannot be cast to the `dtype`.
Casts a tensor to a new type.
[ "Casts", "a", "tensor", "to", "a", "new", "type", "." ]
def cast(x, dtype, name=None): """Casts a tensor to a new type. The operation casts `x` (in case of `Tensor`) or `x.values` (in case of `SparseTensor` or `IndexedSlices`) to `dtype`. For example: ```python x = tf.constant([1.8, 2.2], dtype=tf.float32) tf.dtypes.cast(x, tf.int32) # [1, 2], dtype=tf.int32 ``` The operation supports data types (for `x` and `dtype`) of `uint8`, `uint16`, `uint32`, `uint64`, `int8`, `int16`, `int32`, `int64`, `float16`, `float32`, `float64`, `complex64`, `complex128`, `bfloat16`. In case of casting from complex types (`complex64`, `complex128`) to real types, only the real part of `x` is returned. In case of casting from real types to complex types (`complex64`, `complex128`), the imaginary part of the returned value is set to `0`. The handling of complex types here matches the behavior of numpy. Args: x: A `Tensor` or `SparseTensor` or `IndexedSlices` of numeric type. It could be `uint8`, `uint16`, `uint32`, `uint64`, `int8`, `int16`, `int32`, `int64`, `float16`, `float32`, `float64`, `complex64`, `complex128`, `bfloat16`. dtype: The destination type. The list of supported dtypes is the same as `x`. name: A name for the operation (optional). Returns: A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` and same type as `dtype`. Raises: TypeError: If `x` cannot be cast to the `dtype`. """ base_type = dtypes.as_dtype(dtype).base_dtype if isinstance(x, (ops.Tensor, _resource_variable_type)) and base_type == x.dtype: return x with ops.name_scope(name, "Cast", [x]) as name: if isinstance(x, sparse_tensor.SparseTensor): values_cast = cast(x.values, base_type, name=name) x = sparse_tensor.SparseTensor(x.indices, values_cast, x.dense_shape) elif isinstance(x, ops.IndexedSlices): values_cast = cast(x.values, base_type, name=name) x = ops.IndexedSlices(values_cast, x.indices, x.dense_shape) else: # TODO(josh11b): If x is not already a Tensor, we could return # ops.convert_to_tensor(x, dtype=dtype, ...) here, but that # allows some conversions that cast() can't do, e.g. casting numbers to # strings. x = ops.convert_to_tensor(x, name="x") if x.dtype.base_dtype != base_type: x = gen_math_ops.cast(x, base_type, name=name) if x.dtype.is_complex and base_type.is_floating: logging.warn("Casting complex to real discards imaginary part.") return x
[ "def", "cast", "(", "x", ",", "dtype", ",", "name", "=", "None", ")", ":", "base_type", "=", "dtypes", ".", "as_dtype", "(", "dtype", ")", ".", "base_dtype", "if", "isinstance", "(", "x", ",", "(", "ops", ".", "Tensor", ",", "_resource_variable_type", ")", ")", "and", "base_type", "==", "x", ".", "dtype", ":", "return", "x", "with", "ops", ".", "name_scope", "(", "name", ",", "\"Cast\"", ",", "[", "x", "]", ")", "as", "name", ":", "if", "isinstance", "(", "x", ",", "sparse_tensor", ".", "SparseTensor", ")", ":", "values_cast", "=", "cast", "(", "x", ".", "values", ",", "base_type", ",", "name", "=", "name", ")", "x", "=", "sparse_tensor", ".", "SparseTensor", "(", "x", ".", "indices", ",", "values_cast", ",", "x", ".", "dense_shape", ")", "elif", "isinstance", "(", "x", ",", "ops", ".", "IndexedSlices", ")", ":", "values_cast", "=", "cast", "(", "x", ".", "values", ",", "base_type", ",", "name", "=", "name", ")", "x", "=", "ops", ".", "IndexedSlices", "(", "values_cast", ",", "x", ".", "indices", ",", "x", ".", "dense_shape", ")", "else", ":", "# TODO(josh11b): If x is not already a Tensor, we could return", "# ops.convert_to_tensor(x, dtype=dtype, ...) here, but that", "# allows some conversions that cast() can't do, e.g. casting numbers to", "# strings.", "x", "=", "ops", ".", "convert_to_tensor", "(", "x", ",", "name", "=", "\"x\"", ")", "if", "x", ".", "dtype", ".", "base_dtype", "!=", "base_type", ":", "x", "=", "gen_math_ops", ".", "cast", "(", "x", ",", "base_type", ",", "name", "=", "name", ")", "if", "x", ".", "dtype", ".", "is_complex", "and", "base_type", ".", "is_floating", ":", "logging", ".", "warn", "(", "\"Casting complex to real discards imaginary part.\"", ")", "return", "x" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/math_ops.py#L648-L707
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/training/optimizer.py
python
Optimizer._assert_valid_dtypes
(self, tensors)
Asserts tensors are all valid types (see `_valid_dtypes`). Args: tensors: Tensors to check. Raises: ValueError: If any tensor is not a valid type.
Asserts tensors are all valid types (see `_valid_dtypes`).
[ "Asserts", "tensors", "are", "all", "valid", "types", "(", "see", "_valid_dtypes", ")", "." ]
def _assert_valid_dtypes(self, tensors): """Asserts tensors are all valid types (see `_valid_dtypes`). Args: tensors: Tensors to check. Raises: ValueError: If any tensor is not a valid type. """ valid_dtypes = self._valid_dtypes() for t in tensors: dtype = t.dtype.base_dtype if dtype not in valid_dtypes: raise ValueError( "Invalid type %r for %s, expected: %s." % ( dtype, t.name, [v for v in valid_dtypes]))
[ "def", "_assert_valid_dtypes", "(", "self", ",", "tensors", ")", ":", "valid_dtypes", "=", "self", ".", "_valid_dtypes", "(", ")", "for", "t", "in", "tensors", ":", "dtype", "=", "t", ".", "dtype", ".", "base_dtype", "if", "dtype", "not", "in", "valid_dtypes", ":", "raise", "ValueError", "(", "\"Invalid type %r for %s, expected: %s.\"", "%", "(", "dtype", ",", "t", ".", "name", ",", "[", "v", "for", "v", "in", "valid_dtypes", "]", ")", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/training/optimizer.py#L502-L517
eerolanguage/clang
91360bee004a1cbdb95fe5eb605ef243152da41b
bindings/python/clang/cindex.py
python
Config.set_compatibility_check
(check_status)
Perform compatibility check when loading libclang The python bindings are only tested and evaluated with the version of libclang they are provided with. To ensure correct behavior a (limited) compatibility check is performed when loading the bindings. This check will throw an exception, as soon as it fails. In case these bindings are used with an older version of libclang, parts that have been stable between releases may still work. Users of the python bindings can disable the compatibility check. This will cause the python bindings to load, even though they are written for a newer version of libclang. Failures now arise if unsupported or incompatible features are accessed. The user is required to test himself if the features he is using are available and compatible between different libclang versions.
Perform compatibility check when loading libclang
[ "Perform", "compatibility", "check", "when", "loading", "libclang" ]
def set_compatibility_check(check_status): """ Perform compatibility check when loading libclang The python bindings are only tested and evaluated with the version of libclang they are provided with. To ensure correct behavior a (limited) compatibility check is performed when loading the bindings. This check will throw an exception, as soon as it fails. In case these bindings are used with an older version of libclang, parts that have been stable between releases may still work. Users of the python bindings can disable the compatibility check. This will cause the python bindings to load, even though they are written for a newer version of libclang. Failures now arise if unsupported or incompatible features are accessed. The user is required to test himself if the features he is using are available and compatible between different libclang versions. """ if Config.loaded: raise Exception("compatibility_check must be set before before " \ "using any other functionalities in libclang.") Config.compatibility_check = check_status
[ "def", "set_compatibility_check", "(", "check_status", ")", ":", "if", "Config", ".", "loaded", ":", "raise", "Exception", "(", "\"compatibility_check must be set before before \"", "\"using any other functionalities in libclang.\"", ")", "Config", ".", "compatibility_check", "=", "check_status" ]
https://github.com/eerolanguage/clang/blob/91360bee004a1cbdb95fe5eb605ef243152da41b/bindings/python/clang/cindex.py#L3319-L3340
naver/sling
5671cd445a2caae0b4dd0332299e4cfede05062c
webkit/Tools/Scripts/webkitpy/common/system/executive.py
python
Executive.kill_process
(self, pid)
Attempts to kill the given pid. Will fail silently if pid does not exist or insufficient permisssions.
Attempts to kill the given pid. Will fail silently if pid does not exist or insufficient permisssions.
[ "Attempts", "to", "kill", "the", "given", "pid", ".", "Will", "fail", "silently", "if", "pid", "does", "not", "exist", "or", "insufficient", "permisssions", "." ]
def kill_process(self, pid): """Attempts to kill the given pid. Will fail silently if pid does not exist or insufficient permisssions.""" if sys.platform.startswith('win32'): # We only use taskkill.exe on windows (not cygwin) because subprocess.pid # is a CYGWIN pid and taskkill.exe expects a windows pid. # Thankfully os.kill on CYGWIN handles either pid type. task_kill_executable = os.path.join('C:', os.sep, 'WINDOWS', 'system32', 'taskkill.exe') command = [task_kill_executable, "/f", "/t", "/pid", pid] # taskkill will exit 128 if the process is not found. We should log. self.run_command(command, error_handler=self.ignore_error) return # According to http://docs.python.org/library/os.html # os.kill isn't available on Windows. python 2.5.5 os.kill appears # to work in cygwin, however it occasionally raises EAGAIN. retries_left = 10 if sys.platform == "cygwin" else 1 while retries_left > 0: try: retries_left -= 1 # Give processes one change to clean up quickly before exiting. # Following up with a kill should have no effect if the process # already exited, and forcefully kill it if SIGTERM wasn't enough. os.kill(pid, signal.SIGTERM) os.kill(pid, signal.SIGKILL) except OSError, e: if e.errno == errno.EAGAIN: if retries_left <= 0: _log.warn("Failed to kill pid %s. Too many EAGAIN errors." % pid) continue if e.errno == errno.ESRCH: # The process does not exist. return if e.errno == errno.EPIPE: # The process has exited already on cygwin return if e.errno == errno.ECHILD: # Can't wait on a non-child process, but the kill worked. return if e.errno == errno.EACCES and sys.platform == 'cygwin': # Cygwin python sometimes can't kill native processes. return raise
[ "def", "kill_process", "(", "self", ",", "pid", ")", ":", "if", "sys", ".", "platform", ".", "startswith", "(", "'win32'", ")", ":", "# We only use taskkill.exe on windows (not cygwin) because subprocess.pid", "# is a CYGWIN pid and taskkill.exe expects a windows pid.", "# Thankfully os.kill on CYGWIN handles either pid type.", "task_kill_executable", "=", "os", ".", "path", ".", "join", "(", "'C:'", ",", "os", ".", "sep", ",", "'WINDOWS'", ",", "'system32'", ",", "'taskkill.exe'", ")", "command", "=", "[", "task_kill_executable", ",", "\"/f\"", ",", "\"/t\"", ",", "\"/pid\"", ",", "pid", "]", "# taskkill will exit 128 if the process is not found. We should log.", "self", ".", "run_command", "(", "command", ",", "error_handler", "=", "self", ".", "ignore_error", ")", "return", "# According to http://docs.python.org/library/os.html", "# os.kill isn't available on Windows. python 2.5.5 os.kill appears", "# to work in cygwin, however it occasionally raises EAGAIN.", "retries_left", "=", "10", "if", "sys", ".", "platform", "==", "\"cygwin\"", "else", "1", "while", "retries_left", ">", "0", ":", "try", ":", "retries_left", "-=", "1", "# Give processes one change to clean up quickly before exiting.", "# Following up with a kill should have no effect if the process", "# already exited, and forcefully kill it if SIGTERM wasn't enough.", "os", ".", "kill", "(", "pid", ",", "signal", ".", "SIGTERM", ")", "os", ".", "kill", "(", "pid", ",", "signal", ".", "SIGKILL", ")", "except", "OSError", ",", "e", ":", "if", "e", ".", "errno", "==", "errno", ".", "EAGAIN", ":", "if", "retries_left", "<=", "0", ":", "_log", ".", "warn", "(", "\"Failed to kill pid %s. Too many EAGAIN errors.\"", "%", "pid", ")", "continue", "if", "e", ".", "errno", "==", "errno", ".", "ESRCH", ":", "# The process does not exist.", "return", "if", "e", ".", "errno", "==", "errno", ".", "EPIPE", ":", "# The process has exited already on cygwin", "return", "if", "e", ".", "errno", "==", "errno", ".", "ECHILD", ":", "# Can't wait on a non-child process, but the kill worked.", "return", "if", "e", ".", "errno", "==", "errno", ".", "EACCES", "and", "sys", ".", "platform", "==", "'cygwin'", ":", "# Cygwin python sometimes can't kill native processes.", "return", "raise" ]
https://github.com/naver/sling/blob/5671cd445a2caae0b4dd0332299e4cfede05062c/webkit/Tools/Scripts/webkitpy/common/system/executive.py#L183-L223
albertz/openlierox
d316c14a8eb57848ef56e9bfa7b23a56f694a51b
tools/DedicatedServerVideo/gdata/Crypto/PublicKey/ElGamal.py
python
ElGamalobj.size
(self)
return number.size(self.p) - 1
Return the maximum number of bits that can be handled by this key.
Return the maximum number of bits that can be handled by this key.
[ "Return", "the", "maximum", "number", "of", "bits", "that", "can", "be", "handled", "by", "this", "key", "." ]
def size(self): "Return the maximum number of bits that can be handled by this key." return number.size(self.p) - 1
[ "def", "size", "(", "self", ")", ":", "return", "number", ".", "size", "(", "self", ".", "p", ")", "-", "1" ]
https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/Crypto/PublicKey/ElGamal.py#L115-L117
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/io/parsers.py
python
_read
(filepath_or_buffer, kwds)
return data
Generic reader of line files.
Generic reader of line files.
[ "Generic", "reader", "of", "line", "files", "." ]
def _read(filepath_or_buffer, kwds): """Generic reader of line files.""" encoding = kwds.get('encoding', None) if encoding is not None: encoding = re.sub('_', '-', encoding).lower() kwds['encoding'] = encoding compression = kwds.get('compression', 'infer') compression = _infer_compression(filepath_or_buffer, compression) filepath_or_buffer, _, compression, should_close = get_filepath_or_buffer( filepath_or_buffer, encoding, compression) kwds['compression'] = compression if kwds.get('date_parser', None) is not None: if isinstance(kwds['parse_dates'], bool): kwds['parse_dates'] = True # Extract some of the arguments (pass chunksize on). iterator = kwds.get('iterator', False) chunksize = _validate_integer('chunksize', kwds.get('chunksize', None), 1) nrows = kwds.get('nrows', None) # Check for duplicates in names. _validate_names(kwds.get("names", None)) # Create the parser. parser = TextFileReader(filepath_or_buffer, **kwds) if chunksize or iterator: return parser try: data = parser.read(nrows) finally: parser.close() if should_close: try: filepath_or_buffer.close() except ValueError: pass return data
[ "def", "_read", "(", "filepath_or_buffer", ",", "kwds", ")", ":", "encoding", "=", "kwds", ".", "get", "(", "'encoding'", ",", "None", ")", "if", "encoding", "is", "not", "None", ":", "encoding", "=", "re", ".", "sub", "(", "'_'", ",", "'-'", ",", "encoding", ")", ".", "lower", "(", ")", "kwds", "[", "'encoding'", "]", "=", "encoding", "compression", "=", "kwds", ".", "get", "(", "'compression'", ",", "'infer'", ")", "compression", "=", "_infer_compression", "(", "filepath_or_buffer", ",", "compression", ")", "filepath_or_buffer", ",", "_", ",", "compression", ",", "should_close", "=", "get_filepath_or_buffer", "(", "filepath_or_buffer", ",", "encoding", ",", "compression", ")", "kwds", "[", "'compression'", "]", "=", "compression", "if", "kwds", ".", "get", "(", "'date_parser'", ",", "None", ")", "is", "not", "None", ":", "if", "isinstance", "(", "kwds", "[", "'parse_dates'", "]", ",", "bool", ")", ":", "kwds", "[", "'parse_dates'", "]", "=", "True", "# Extract some of the arguments (pass chunksize on).", "iterator", "=", "kwds", ".", "get", "(", "'iterator'", ",", "False", ")", "chunksize", "=", "_validate_integer", "(", "'chunksize'", ",", "kwds", ".", "get", "(", "'chunksize'", ",", "None", ")", ",", "1", ")", "nrows", "=", "kwds", ".", "get", "(", "'nrows'", ",", "None", ")", "# Check for duplicates in names.", "_validate_names", "(", "kwds", ".", "get", "(", "\"names\"", ",", "None", ")", ")", "# Create the parser.", "parser", "=", "TextFileReader", "(", "filepath_or_buffer", ",", "*", "*", "kwds", ")", "if", "chunksize", "or", "iterator", ":", "return", "parser", "try", ":", "data", "=", "parser", ".", "read", "(", "nrows", ")", "finally", ":", "parser", ".", "close", "(", ")", "if", "should_close", ":", "try", ":", "filepath_or_buffer", ".", "close", "(", ")", "except", "ValueError", ":", "pass", "return", "data" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/io/parsers.py#L403-L445
rsummers11/CADLab
976ed959a0b5208bb4173127a7ef732ac73a9b6f
panreas_hnn/hed-globalweight/python/caffe/io.py
python
load_image
(filename, color=True)
return img
Load an image converting from grayscale or alpha as needed. Parameters ---------- filename : string color : boolean flag for color format. True (default) loads as RGB while False loads as intensity (if image is already grayscale). Returns ------- image : an image with type np.float32 in range [0, 1] of size (H x W x 3) in RGB or of size (H x W x 1) in grayscale.
Load an image converting from grayscale or alpha as needed.
[ "Load", "an", "image", "converting", "from", "grayscale", "or", "alpha", "as", "needed", "." ]
def load_image(filename, color=True): """ Load an image converting from grayscale or alpha as needed. Parameters ---------- filename : string color : boolean flag for color format. True (default) loads as RGB while False loads as intensity (if image is already grayscale). Returns ------- image : an image with type np.float32 in range [0, 1] of size (H x W x 3) in RGB or of size (H x W x 1) in grayscale. """ img = skimage.img_as_float(skimage.io.imread(filename)).astype(np.float32) if img.ndim == 2: img = img[:, :, np.newaxis] if color: img = np.tile(img, (1, 1, 3)) elif img.shape[2] == 4: img = img[:, :, :3] return img
[ "def", "load_image", "(", "filename", ",", "color", "=", "True", ")", ":", "img", "=", "skimage", ".", "img_as_float", "(", "skimage", ".", "io", ".", "imread", "(", "filename", ")", ")", ".", "astype", "(", "np", ".", "float32", ")", "if", "img", ".", "ndim", "==", "2", ":", "img", "=", "img", "[", ":", ",", ":", ",", "np", ".", "newaxis", "]", "if", "color", ":", "img", "=", "np", ".", "tile", "(", "img", ",", "(", "1", ",", "1", ",", "3", ")", ")", "elif", "img", ".", "shape", "[", "2", "]", "==", "4", ":", "img", "=", "img", "[", ":", ",", ":", ",", ":", "3", "]", "return", "img" ]
https://github.com/rsummers11/CADLab/blob/976ed959a0b5208bb4173127a7ef732ac73a9b6f/panreas_hnn/hed-globalweight/python/caffe/io.py#L275-L299
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/docutils/transforms/references.py
python
Footnotes.number_footnotes
(self, startnum)
return startnum
Assign numbers to autonumbered footnotes. For labeled autonumbered footnotes, copy the number over to corresponding footnote references.
Assign numbers to autonumbered footnotes.
[ "Assign", "numbers", "to", "autonumbered", "footnotes", "." ]
def number_footnotes(self, startnum): """ Assign numbers to autonumbered footnotes. For labeled autonumbered footnotes, copy the number over to corresponding footnote references. """ for footnote in self.document.autofootnotes: while True: label = str(startnum) startnum += 1 if label not in self.document.nameids: break footnote.insert(0, nodes.label('', label)) for name in footnote['names']: for ref in self.document.footnote_refs.get(name, []): ref += nodes.Text(label) ref.delattr('refname') assert len(footnote['ids']) == len(ref['ids']) == 1 ref['refid'] = footnote['ids'][0] footnote.add_backref(ref['ids'][0]) self.document.note_refid(ref) ref.resolved = 1 if not footnote['names'] and not footnote['dupnames']: footnote['names'].append(label) self.document.note_explicit_target(footnote, footnote) self.autofootnote_labels.append(label) return startnum
[ "def", "number_footnotes", "(", "self", ",", "startnum", ")", ":", "for", "footnote", "in", "self", ".", "document", ".", "autofootnotes", ":", "while", "True", ":", "label", "=", "str", "(", "startnum", ")", "startnum", "+=", "1", "if", "label", "not", "in", "self", ".", "document", ".", "nameids", ":", "break", "footnote", ".", "insert", "(", "0", ",", "nodes", ".", "label", "(", "''", ",", "label", ")", ")", "for", "name", "in", "footnote", "[", "'names'", "]", ":", "for", "ref", "in", "self", ".", "document", ".", "footnote_refs", ".", "get", "(", "name", ",", "[", "]", ")", ":", "ref", "+=", "nodes", ".", "Text", "(", "label", ")", "ref", ".", "delattr", "(", "'refname'", ")", "assert", "len", "(", "footnote", "[", "'ids'", "]", ")", "==", "len", "(", "ref", "[", "'ids'", "]", ")", "==", "1", "ref", "[", "'refid'", "]", "=", "footnote", "[", "'ids'", "]", "[", "0", "]", "footnote", ".", "add_backref", "(", "ref", "[", "'ids'", "]", "[", "0", "]", ")", "self", ".", "document", ".", "note_refid", "(", "ref", ")", "ref", ".", "resolved", "=", "1", "if", "not", "footnote", "[", "'names'", "]", "and", "not", "footnote", "[", "'dupnames'", "]", ":", "footnote", "[", "'names'", "]", ".", "append", "(", "label", ")", "self", ".", "document", ".", "note_explicit_target", "(", "footnote", ",", "footnote", ")", "self", ".", "autofootnote_labels", ".", "append", "(", "label", ")", "return", "startnum" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/transforms/references.py#L499-L526
xiaolonw/caffe-video_triplet
c39ea1ad6e937ccf7deba4510b7e555165abf05f
python/caffe/io.py
python
Transformer.set_input_scale
(self, in_, scale)
Set the scale of preprocessed inputs s.t. the blob = blob * scale. N.B. input_scale is done AFTER mean subtraction and other preprocessing while raw_scale is done BEFORE. Parameters ---------- in_ : which input to assign this scale factor scale : scale coefficient
Set the scale of preprocessed inputs s.t. the blob = blob * scale. N.B. input_scale is done AFTER mean subtraction and other preprocessing while raw_scale is done BEFORE.
[ "Set", "the", "scale", "of", "preprocessed", "inputs", "s", ".", "t", ".", "the", "blob", "=", "blob", "*", "scale", ".", "N", ".", "B", ".", "input_scale", "is", "done", "AFTER", "mean", "subtraction", "and", "other", "preprocessing", "while", "raw_scale", "is", "done", "BEFORE", "." ]
def set_input_scale(self, in_, scale): """ Set the scale of preprocessed inputs s.t. the blob = blob * scale. N.B. input_scale is done AFTER mean subtraction and other preprocessing while raw_scale is done BEFORE. Parameters ---------- in_ : which input to assign this scale factor scale : scale coefficient """ self.__check_input(in_) self.input_scale[in_] = scale
[ "def", "set_input_scale", "(", "self", ",", "in_", ",", "scale", ")", ":", "self", ".", "__check_input", "(", "in_", ")", "self", ".", "input_scale", "[", "in_", "]", "=", "scale" ]
https://github.com/xiaolonw/caffe-video_triplet/blob/c39ea1ad6e937ccf7deba4510b7e555165abf05f/python/caffe/io.py#L258-L270
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/masked/timectrl.py
python
TimeCtrl.GetMxDateTime
(self, value=None)
return t
Returns the value of the control as an mx.DateTime, with the date portion set to January 1, 1970.
Returns the value of the control as an mx.DateTime, with the date portion set to January 1, 1970.
[ "Returns", "the", "value", "of", "the", "control", "as", "an", "mx", ".", "DateTime", "with", "the", "date", "portion", "set", "to", "January", "1", "1970", "." ]
def GetMxDateTime(self, value=None): """ Returns the value of the control as an mx.DateTime, with the date portion set to January 1, 1970. """ if value is None: t = self.GetValue(as_mxDateTime=True) else: # Convert string 1st to wxDateTime, then use components, since # mx' DateTime.Parser.TimeFromString() doesn't handle AM/PM: wxdt = self.GetWxDateTime(value) hour, minute, second = wxdt.GetHour(), wxdt.GetMinute(), wxdt.GetSecond() t = DateTime.DateTime(1970,1,1) + DateTimeDelta(0, hour, minute, second) return t
[ "def", "GetMxDateTime", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "None", ":", "t", "=", "self", ".", "GetValue", "(", "as_mxDateTime", "=", "True", ")", "else", ":", "# Convert string 1st to wxDateTime, then use components, since", "# mx' DateTime.Parser.TimeFromString() doesn't handle AM/PM:", "wxdt", "=", "self", ".", "GetWxDateTime", "(", "value", ")", "hour", ",", "minute", ",", "second", "=", "wxdt", ".", "GetHour", "(", ")", ",", "wxdt", ".", "GetMinute", "(", ")", ",", "wxdt", ".", "GetSecond", "(", ")", "t", "=", "DateTime", ".", "DateTime", "(", "1970", ",", "1", ",", "1", ")", "+", "DateTimeDelta", "(", "0", ",", "hour", ",", "minute", ",", "second", ")", "return", "t" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/masked/timectrl.py#L783-L796
ycm-core/ycmd
fc0fb7e5e15176cc5a2a30c80956335988c6b59a
ycmd/completers/cs/cs_completer.py
python
CsharpSolutionCompleter.ServerIsHealthy
( self )
Check if our OmniSharp server is healthy (up and serving).
Check if our OmniSharp server is healthy (up and serving).
[ "Check", "if", "our", "OmniSharp", "server", "is", "healthy", "(", "up", "and", "serving", ")", "." ]
def ServerIsHealthy( self ): """ Check if our OmniSharp server is healthy (up and serving).""" if not self._ServerIsRunning(): return False try: return self._GetResponse( '/checkalivestatus', timeout = 3 ) except Exception: return False
[ "def", "ServerIsHealthy", "(", "self", ")", ":", "if", "not", "self", ".", "_ServerIsRunning", "(", ")", ":", "return", "False", "try", ":", "return", "self", ".", "_GetResponse", "(", "'/checkalivestatus'", ",", "timeout", "=", "3", ")", "except", "Exception", ":", "return", "False" ]
https://github.com/ycm-core/ycmd/blob/fc0fb7e5e15176cc5a2a30c80956335988c6b59a/ycmd/completers/cs/cs_completer.py#L835-L843
rdiankov/openrave
d1a23023fd4b58f077d2ca949ceaf1b91f3f13d7
python/databases/inversereachability.py
python
InverseReachabilityModel.classnormalizationconst
(classstd)
return quatconst+gaussconst
normalization const for the equation exp(dot(-0.5/bandwidth**2,r_[arccos(x[0])**2,x[1:]**2]))
normalization const for the equation exp(dot(-0.5/bandwidth**2,r_[arccos(x[0])**2,x[1:]**2]))
[ "normalization", "const", "for", "the", "equation", "exp", "(", "dot", "(", "-", "0", ".", "5", "/", "bandwidth", "**", "2", "r_", "[", "arccos", "(", "x", "[", "0", "]", ")", "**", "2", "x", "[", "1", ":", "]", "**", "2", "]", "))" ]
def classnormalizationconst(classstd): """normalization const for the equation exp(dot(-0.5/bandwidth**2,r_[arccos(x[0])**2,x[1:]**2]))""" gaussconst = -0.5*(len(classstd)-1)*numpy.log(pi)-0.5*numpy.log(prod(classstd[1:])) # normalization for the weights so that integrated volume is 1. this is necessary when comparing across different distributions? quatconst = numpy.log(1.0/classstd[0]**2+0.3334) return quatconst+gaussconst
[ "def", "classnormalizationconst", "(", "classstd", ")", ":", "gaussconst", "=", "-", "0.5", "*", "(", "len", "(", "classstd", ")", "-", "1", ")", "*", "numpy", ".", "log", "(", "pi", ")", "-", "0.5", "*", "numpy", ".", "log", "(", "prod", "(", "classstd", "[", "1", ":", "]", ")", ")", "# normalization for the weights so that integrated volume is 1. this is necessary when comparing across different distributions?", "quatconst", "=", "numpy", ".", "log", "(", "1.0", "/", "classstd", "[", "0", "]", "**", "2", "+", "0.3334", ")", "return", "quatconst", "+", "gaussconst" ]
https://github.com/rdiankov/openrave/blob/d1a23023fd4b58f077d2ca949ceaf1b91f3f13d7/python/databases/inversereachability.py#L108-L113
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/control_flow_state.py
python
_ZerosLikeV2
(op, index)
Branch of ZerosLike for TF2.
Branch of ZerosLike for TF2.
[ "Branch", "of", "ZerosLike", "for", "TF2", "." ]
def _ZerosLikeV2(op, index): """Branch of ZerosLike for TF2.""" val = op.outputs[index] if val.dtype == dtypes.resource: return array_ops.zeros( gen_resource_variable_ops.variable_shape(val), dtype=default_gradient.get_zeros_dtype(val)) if (isinstance(val.op.graph, control_flow_v2_func_graphs.WhileBodyFuncGraph) and val.dtype != dtypes.variant): # In while_v2 we do not want to add a `ZerosLike` op because that will # trigger accumulation of `val`. Normally `ZerosLike` is preferred because # it helps avoid creating extra nodes(possibly Consts) for the shape. # For variants, we must use ZerosLike. if val.shape.is_fully_defined(): return constant_op.constant(0, shape=val.shape.dims, dtype=val.dtype) else: # Note: Even though we add `Shape` in the default graph, while_v2 is smart # enough to place it in the forward graph i.e. `val.graph`. zeros_shape = array_ops.shape_internal(val, optimize=False) return array_ops.zeros(zeros_shape, val.dtype) else: return array_ops.zeros_like(val, optimize=False)
[ "def", "_ZerosLikeV2", "(", "op", ",", "index", ")", ":", "val", "=", "op", ".", "outputs", "[", "index", "]", "if", "val", ".", "dtype", "==", "dtypes", ".", "resource", ":", "return", "array_ops", ".", "zeros", "(", "gen_resource_variable_ops", ".", "variable_shape", "(", "val", ")", ",", "dtype", "=", "default_gradient", ".", "get_zeros_dtype", "(", "val", ")", ")", "if", "(", "isinstance", "(", "val", ".", "op", ".", "graph", ",", "control_flow_v2_func_graphs", ".", "WhileBodyFuncGraph", ")", "and", "val", ".", "dtype", "!=", "dtypes", ".", "variant", ")", ":", "# In while_v2 we do not want to add a `ZerosLike` op because that will", "# trigger accumulation of `val`. Normally `ZerosLike` is preferred because", "# it helps avoid creating extra nodes(possibly Consts) for the shape.", "# For variants, we must use ZerosLike.", "if", "val", ".", "shape", ".", "is_fully_defined", "(", ")", ":", "return", "constant_op", ".", "constant", "(", "0", ",", "shape", "=", "val", ".", "shape", ".", "dims", ",", "dtype", "=", "val", ".", "dtype", ")", "else", ":", "# Note: Even though we add `Shape` in the default graph, while_v2 is smart", "# enough to place it in the forward graph i.e. `val.graph`.", "zeros_shape", "=", "array_ops", ".", "shape_internal", "(", "val", ",", "optimize", "=", "False", ")", "return", "array_ops", ".", "zeros", "(", "zeros_shape", ",", "val", ".", "dtype", ")", "else", ":", "return", "array_ops", ".", "zeros_like", "(", "val", ",", "optimize", "=", "False", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/control_flow_state.py#L806-L827
zhaoweicai/cascade-rcnn
2252f46158ea6555868ca6fa5c221ea71d9b5e6c
scripts/cpp_lint.py
python
ResetNolintSuppressions
()
Resets the set of NOLINT suppressions to empty.
Resets the set of NOLINT suppressions to empty.
[ "Resets", "the", "set", "of", "NOLINT", "suppressions", "to", "empty", "." ]
def ResetNolintSuppressions(): "Resets the set of NOLINT suppressions to empty." _error_suppressions.clear()
[ "def", "ResetNolintSuppressions", "(", ")", ":", "_error_suppressions", ".", "clear", "(", ")" ]
https://github.com/zhaoweicai/cascade-rcnn/blob/2252f46158ea6555868ca6fa5c221ea71d9b5e6c/scripts/cpp_lint.py#L499-L501
nest/nest-simulator
f2623eb78518cdbd55e77e0ed486bf1111bcb62f
pynest/examples/hpc_benchmark.py
python
lambertwm1
(x)
return sp.lambertw(x, k=-1 if x < 0 else 0).real
Wrapper for LambertWm1 function
Wrapper for LambertWm1 function
[ "Wrapper", "for", "LambertWm1", "function" ]
def lambertwm1(x): """Wrapper for LambertWm1 function""" # Using scipy to mimic the gsl_sf_lambert_Wm1 function. return sp.lambertw(x, k=-1 if x < 0 else 0).real
[ "def", "lambertwm1", "(", "x", ")", ":", "# Using scipy to mimic the gsl_sf_lambert_Wm1 function.", "return", "sp", ".", "lambertw", "(", "x", ",", "k", "=", "-", "1", "if", "x", "<", "0", "else", "0", ")", ".", "real" ]
https://github.com/nest/nest-simulator/blob/f2623eb78518cdbd55e77e0ed486bf1111bcb62f/pynest/examples/hpc_benchmark.py#L426-L429
rdkit/rdkit
ede860ae316d12d8568daf5ee800921c3389c84e
rdkit/ML/ScreenComposite.py
python
ScreenIt
(composite, indices, data, partialVote=0, voteTol=0.0, verbose=1, screenResults=None, goodVotes=None, badVotes=None, noVotes=None)
return nGood, misCount, nSkipped, avgGood, avgBad, avgSkip, None
screens a set of data using a composite model and prints out statistics about the screen. #DOC The work of doing the screening and processing the results is handled by _DetailedScreen()_ **Arguments** - composite: the composite model to be used - data: the examples to be screened (a sequence of sequences) it's assumed that the last element in each example is its "value" - partialVote: (optional) toggles use of the threshold value in the screnning. - voteTol: (optional) the threshold to be used to decide whether or not a given prediction should be kept - verbose: (optional) sets degree of verbosity of the screening - screenResults: (optional) the results of screening the results (a sequence of 3-tuples in the format returned by _CollectResults()_). If this is provided, the examples will not be screened again. - goodVotes,badVotes,noVotes: (optional) if provided these should be lists (or anything supporting an _append()_ method) which will be used to pass the screening results back. **Returns** a 7-tuple: 1) the number of good (correct) predictions 2) the number of bad (incorrect) predictions 3) the number of predictions skipped due to the _threshold_ 4) the average confidence in the good predictions 5) the average confidence in the bad predictions 6) the average confidence in the skipped predictions 7) None
screens a set of data using a composite model and prints out statistics about the screen. #DOC The work of doing the screening and processing the results is handled by _DetailedScreen()_
[ "screens", "a", "set", "of", "data", "using", "a", "composite", "model", "and", "prints", "out", "statistics", "about", "the", "screen", ".", "#DOC", "The", "work", "of", "doing", "the", "screening", "and", "processing", "the", "results", "is", "handled", "by", "_DetailedScreen", "()", "_" ]
def ScreenIt(composite, indices, data, partialVote=0, voteTol=0.0, verbose=1, screenResults=None, goodVotes=None, badVotes=None, noVotes=None): """ screens a set of data using a composite model and prints out statistics about the screen. #DOC The work of doing the screening and processing the results is handled by _DetailedScreen()_ **Arguments** - composite: the composite model to be used - data: the examples to be screened (a sequence of sequences) it's assumed that the last element in each example is its "value" - partialVote: (optional) toggles use of the threshold value in the screnning. - voteTol: (optional) the threshold to be used to decide whether or not a given prediction should be kept - verbose: (optional) sets degree of verbosity of the screening - screenResults: (optional) the results of screening the results (a sequence of 3-tuples in the format returned by _CollectResults()_). If this is provided, the examples will not be screened again. - goodVotes,badVotes,noVotes: (optional) if provided these should be lists (or anything supporting an _append()_ method) which will be used to pass the screening results back. **Returns** a 7-tuple: 1) the number of good (correct) predictions 2) the number of bad (incorrect) predictions 3) the number of predictions skipped due to the _threshold_ 4) the average confidence in the good predictions 5) the average confidence in the bad predictions 6) the average confidence in the skipped predictions 7) None """ if goodVotes is None: goodVotes = [] if badVotes is None: badVotes = [] if noVotes is None: noVotes = [] if not partialVote: voteTol = 0.0 DetailedScreen(indices, data, composite, voteTol, screenResults=screenResults, goodVotes=goodVotes, badVotes=badVotes, noVotes=noVotes) nGood = len(goodVotes) goodAccum = 0. for res, pred, conf, idx in goodVotes: goodAccum += conf misCount = len(badVotes) badAccum = 0. for res, pred, conf, idx in badVotes: badAccum += conf nSkipped = len(noVotes) goodSkipped = 0 badSkipped = 0 skipAccum = 0. for ans, pred, conf, idx in noVotes: skipAccum += conf if ans != pred: badSkipped += 1 else: goodSkipped += 1 nData = nGood + misCount + nSkipped if verbose: print('Total N Points:', nData) if partialVote: nCounted = nData - nSkipped if verbose: print('Misclassifications: %d (%%%4.2f)' % (misCount, 100. * float(misCount) / nCounted)) print('N Skipped: %d (%%%4.2f)' % (nSkipped, 100. * float(nSkipped) / nData)) print('\tGood Votes Skipped: %d (%%%4.2f)' % (goodSkipped, 100. * float(goodSkipped) / nSkipped)) print('\tBad Votes Skipped: %d (%%%4.2f)' % (badSkipped, 100. * float(badSkipped) / nSkipped)) else: if verbose: print('Misclassifications: %d (%%%4.2f)' % (misCount, 100. * float(misCount) / nData)) print('Average Correct Vote Confidence: % 6.4f' % (goodAccum / (nData - misCount))) print('Average InCorrect Vote Confidence: % 6.4f' % (badAccum / misCount)) avgGood = 0 avgBad = 0 avgSkip = 0 if nGood: avgGood = goodAccum / nGood if misCount: avgBad = badAccum / misCount if nSkipped: avgSkip = skipAccum / nSkipped return nGood, misCount, nSkipped, avgGood, avgBad, avgSkip, None
[ "def", "ScreenIt", "(", "composite", ",", "indices", ",", "data", ",", "partialVote", "=", "0", ",", "voteTol", "=", "0.0", ",", "verbose", "=", "1", ",", "screenResults", "=", "None", ",", "goodVotes", "=", "None", ",", "badVotes", "=", "None", ",", "noVotes", "=", "None", ")", ":", "if", "goodVotes", "is", "None", ":", "goodVotes", "=", "[", "]", "if", "badVotes", "is", "None", ":", "badVotes", "=", "[", "]", "if", "noVotes", "is", "None", ":", "noVotes", "=", "[", "]", "if", "not", "partialVote", ":", "voteTol", "=", "0.0", "DetailedScreen", "(", "indices", ",", "data", ",", "composite", ",", "voteTol", ",", "screenResults", "=", "screenResults", ",", "goodVotes", "=", "goodVotes", ",", "badVotes", "=", "badVotes", ",", "noVotes", "=", "noVotes", ")", "nGood", "=", "len", "(", "goodVotes", ")", "goodAccum", "=", "0.", "for", "res", ",", "pred", ",", "conf", ",", "idx", "in", "goodVotes", ":", "goodAccum", "+=", "conf", "misCount", "=", "len", "(", "badVotes", ")", "badAccum", "=", "0.", "for", "res", ",", "pred", ",", "conf", ",", "idx", "in", "badVotes", ":", "badAccum", "+=", "conf", "nSkipped", "=", "len", "(", "noVotes", ")", "goodSkipped", "=", "0", "badSkipped", "=", "0", "skipAccum", "=", "0.", "for", "ans", ",", "pred", ",", "conf", ",", "idx", "in", "noVotes", ":", "skipAccum", "+=", "conf", "if", "ans", "!=", "pred", ":", "badSkipped", "+=", "1", "else", ":", "goodSkipped", "+=", "1", "nData", "=", "nGood", "+", "misCount", "+", "nSkipped", "if", "verbose", ":", "print", "(", "'Total N Points:'", ",", "nData", ")", "if", "partialVote", ":", "nCounted", "=", "nData", "-", "nSkipped", "if", "verbose", ":", "print", "(", "'Misclassifications: %d (%%%4.2f)'", "%", "(", "misCount", ",", "100.", "*", "float", "(", "misCount", ")", "/", "nCounted", ")", ")", "print", "(", "'N Skipped: %d (%%%4.2f)'", "%", "(", "nSkipped", ",", "100.", "*", "float", "(", "nSkipped", ")", "/", "nData", ")", ")", "print", "(", "'\\tGood Votes Skipped: %d (%%%4.2f)'", "%", "(", "goodSkipped", ",", "100.", "*", "float", "(", "goodSkipped", ")", "/", "nSkipped", ")", ")", "print", "(", "'\\tBad Votes Skipped: %d (%%%4.2f)'", "%", "(", "badSkipped", ",", "100.", "*", "float", "(", "badSkipped", ")", "/", "nSkipped", ")", ")", "else", ":", "if", "verbose", ":", "print", "(", "'Misclassifications: %d (%%%4.2f)'", "%", "(", "misCount", ",", "100.", "*", "float", "(", "misCount", ")", "/", "nData", ")", ")", "print", "(", "'Average Correct Vote Confidence: % 6.4f'", "%", "(", "goodAccum", "/", "(", "nData", "-", "misCount", ")", ")", ")", "print", "(", "'Average InCorrect Vote Confidence: % 6.4f'", "%", "(", "badAccum", "/", "misCount", ")", ")", "avgGood", "=", "0", "avgBad", "=", "0", "avgSkip", "=", "0", "if", "nGood", ":", "avgGood", "=", "goodAccum", "/", "nGood", "if", "misCount", ":", "avgBad", "=", "badAccum", "/", "misCount", "if", "nSkipped", ":", "avgSkip", "=", "skipAccum", "/", "nSkipped", "return", "nGood", ",", "misCount", ",", "nSkipped", ",", "avgGood", ",", "avgBad", ",", "avgSkip", ",", "None" ]
https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/ML/ScreenComposite.py#L465-L577
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/psutil/_common.py
python
wrap_numbers
(input_dict, name)
Given an `input_dict` and a function `name`, adjust the numbers which "wrap" (restart from zero) across different calls by adding "old value" to "new value" and return an updated dict.
Given an `input_dict` and a function `name`, adjust the numbers which "wrap" (restart from zero) across different calls by adding "old value" to "new value" and return an updated dict.
[ "Given", "an", "input_dict", "and", "a", "function", "name", "adjust", "the", "numbers", "which", "wrap", "(", "restart", "from", "zero", ")", "across", "different", "calls", "by", "adding", "old", "value", "to", "new", "value", "and", "return", "an", "updated", "dict", "." ]
def wrap_numbers(input_dict, name): """Given an `input_dict` and a function `name`, adjust the numbers which "wrap" (restart from zero) across different calls by adding "old value" to "new value" and return an updated dict. """ with _wn.lock: return _wn.run(input_dict, name)
[ "def", "wrap_numbers", "(", "input_dict", ",", "name", ")", ":", "with", "_wn", ".", "lock", ":", "return", "_wn", ".", "run", "(", "input_dict", ",", "name", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/psutil/_common.py#L698-L704
Cocos-BCX/cocos-mainnet
68451c4d882c0efe871806394be473f5689bd982
programs/build_helpers/check_reflect.py
python
process_node
(path, node)
return
if node.tag == "TestCase": if node.attrib.get("result", "UNKNOWN") != "passed": failset.add(node) return if node.tag in ["TestResult", "TestSuite"]: for child in node: cpath = path+"/"+child.attrib["name"] process_node(cpath, child) return
if node.tag == "TestCase": if node.attrib.get("result", "UNKNOWN") != "passed": failset.add(node) return if node.tag in ["TestResult", "TestSuite"]: for child in node: cpath = path+"/"+child.attrib["name"] process_node(cpath, child) return
[ "if", "node", ".", "tag", "==", "TestCase", ":", "if", "node", ".", "attrib", ".", "get", "(", "result", "UNKNOWN", ")", "!", "=", "passed", ":", "failset", ".", "add", "(", "node", ")", "return", "if", "node", ".", "tag", "in", "[", "TestResult", "TestSuite", "]", ":", "for", "child", "in", "node", ":", "cpath", "=", "path", "+", "/", "+", "child", ".", "attrib", "[", "name", "]", "process_node", "(", "cpath", "child", ")", "return" ]
def process_node(path, node): """ if node.tag == "TestCase": if node.attrib.get("result", "UNKNOWN") != "passed": failset.add(node) return if node.tag in ["TestResult", "TestSuite"]: for child in node: cpath = path+"/"+child.attrib["name"] process_node(cpath, child) return """ #print("unknown node", node.tag) print(node.tag) return
[ "def", "process_node", "(", "path", ",", "node", ")", ":", "#print(\"unknown node\", node.tag)", "print", "(", "node", ".", "tag", ")", "return" ]
https://github.com/Cocos-BCX/cocos-mainnet/blob/68451c4d882c0efe871806394be473f5689bd982/programs/build_helpers/check_reflect.py#L8-L22
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/pipeline/pipeline/pipeline.py
python
Pipeline.finalized
(self)
Finalizes this Pipeline after execution if it's a generator. Default action as the root pipeline is to email the admins with the status. Implementors be sure to call 'was_aborted' to find out if the finalization that you're handling is for a success or error case.
Finalizes this Pipeline after execution if it's a generator.
[ "Finalizes", "this", "Pipeline", "after", "execution", "if", "it", "s", "a", "generator", "." ]
def finalized(self): """Finalizes this Pipeline after execution if it's a generator. Default action as the root pipeline is to email the admins with the status. Implementors be sure to call 'was_aborted' to find out if the finalization that you're handling is for a success or error case. """ if self.pipeline_id == self.root_pipeline_id: self.send_result_email()
[ "def", "finalized", "(", "self", ")", ":", "if", "self", ".", "pipeline_id", "==", "self", ".", "root_pipeline_id", ":", "self", ".", "send_result_email", "(", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/pipeline/pipeline/pipeline.py#L999-L1007
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/tools/optimize_for_inference_lib.py
python
ensure_graph_is_valid
(graph_def)
Makes sure that the graph is internally consistent. Checks basic properties of the graph def and raises an exception if there are input references to missing nodes, duplicated names, or other logic errors. Args: graph_def: Definition of a graph to be checked. Raises: ValueError: If the graph is incorrectly constructed.
Makes sure that the graph is internally consistent.
[ "Makes", "sure", "that", "the", "graph", "is", "internally", "consistent", "." ]
def ensure_graph_is_valid(graph_def): """Makes sure that the graph is internally consistent. Checks basic properties of the graph def and raises an exception if there are input references to missing nodes, duplicated names, or other logic errors. Args: graph_def: Definition of a graph to be checked. Raises: ValueError: If the graph is incorrectly constructed. """ node_map = {} for node in graph_def.node: if node.name not in node_map.keys(): node_map[node.name] = node else: raise ValueError("Duplicate node names detected for ", node.name) for node in graph_def.node: for input_name in node.input: input_node_name = node_name_from_input(input_name) if input_node_name not in node_map.keys(): raise ValueError("Input for ", node.name, " not found: ", input_name)
[ "def", "ensure_graph_is_valid", "(", "graph_def", ")", ":", "node_map", "=", "{", "}", "for", "node", "in", "graph_def", ".", "node", ":", "if", "node", ".", "name", "not", "in", "node_map", ".", "keys", "(", ")", ":", "node_map", "[", "node", ".", "name", "]", "=", "node", "else", ":", "raise", "ValueError", "(", "\"Duplicate node names detected for \"", ",", "node", ".", "name", ")", "for", "node", "in", "graph_def", ".", "node", ":", "for", "input_name", "in", "node", ".", "input", ":", "input_node_name", "=", "node_name_from_input", "(", "input_name", ")", "if", "input_node_name", "not", "in", "node_map", ".", "keys", "(", ")", ":", "raise", "ValueError", "(", "\"Input for \"", ",", "node", ".", "name", ",", "\" not found: \"", ",", "input_name", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/tools/optimize_for_inference_lib.py#L119-L141
panda3d/panda3d
833ad89ebad58395d0af0b7ec08538e5e4308265
direct/src/showbase/Audio3DManager.py
python
Audio3DManager.getDropOffFactor
(self)
return self.audio_manager.audio3dGetDropOffFactor()
Exaggerate or diminish the effect of distance on sound. Default is 1.0 Valid range is 0 to 10 Faster drop off, use >1.0 Slower drop off, use <1.0
Exaggerate or diminish the effect of distance on sound. Default is 1.0 Valid range is 0 to 10 Faster drop off, use >1.0 Slower drop off, use <1.0
[ "Exaggerate", "or", "diminish", "the", "effect", "of", "distance", "on", "sound", ".", "Default", "is", "1", ".", "0", "Valid", "range", "is", "0", "to", "10", "Faster", "drop", "off", "use", ">", "1", ".", "0", "Slower", "drop", "off", "use", "<1", ".", "0" ]
def getDropOffFactor(self): """ Exaggerate or diminish the effect of distance on sound. Default is 1.0 Valid range is 0 to 10 Faster drop off, use >1.0 Slower drop off, use <1.0 """ return self.audio_manager.audio3dGetDropOffFactor()
[ "def", "getDropOffFactor", "(", "self", ")", ":", "return", "self", ".", "audio_manager", ".", "audio3dGetDropOffFactor", "(", ")" ]
https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/showbase/Audio3DManager.py#L76-L83
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/lib-tk/Tkinter.py
python
Canvas.tag_bind
(self, tagOrId, sequence=None, func=None, add=None)
return self._bind((self._w, 'bind', tagOrId), sequence, func, add)
Bind to all items with TAGORID at event SEQUENCE a call to function FUNC. An additional boolean parameter ADD specifies whether FUNC will be called additionally to the other bound function or whether it will replace the previous function. See bind for the return value.
Bind to all items with TAGORID at event SEQUENCE a call to function FUNC.
[ "Bind", "to", "all", "items", "with", "TAGORID", "at", "event", "SEQUENCE", "a", "call", "to", "function", "FUNC", "." ]
def tag_bind(self, tagOrId, sequence=None, func=None, add=None): """Bind to all items with TAGORID at event SEQUENCE a call to function FUNC. An additional boolean parameter ADD specifies whether FUNC will be called additionally to the other bound function or whether it will replace the previous function. See bind for the return value.""" return self._bind((self._w, 'bind', tagOrId), sequence, func, add)
[ "def", "tag_bind", "(", "self", ",", "tagOrId", ",", "sequence", "=", "None", ",", "func", "=", "None", ",", "add", "=", "None", ")", ":", "return", "self", ".", "_bind", "(", "(", "self", ".", "_w", ",", "'bind'", ",", "tagOrId", ")", ",", "sequence", ",", "func", ",", "add", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/Tkinter.py#L2282-L2289
francinexue/xuefu
b6ff79747a42e020588c0c0a921048e08fe4680c
ctpx/ctp2/ctptd.py
python
CtpTd.onRtnInstrumentStatus
(self, InstrumentStatusField)
合约交易状态通知
合约交易状态通知
[ "合约交易状态通知" ]
def onRtnInstrumentStatus(self, InstrumentStatusField): """合约交易状态通知""" pass
[ "def", "onRtnInstrumentStatus", "(", "self", ",", "InstrumentStatusField", ")", ":", "pass" ]
https://github.com/francinexue/xuefu/blob/b6ff79747a42e020588c0c0a921048e08fe4680c/ctpx/ctp2/ctptd.py#L367-L369
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/framework/python/ops/variables.py
python
variable
(name, shape=None, dtype=None, initializer=None, regularizer=None, trainable=True, collections=None, caching_device=None, device=None, partitioner=None, custom_getter=None, use_resource=None)
Gets an existing variable with these parameters or creates a new one. Args: name: the name of the new or existing variable. shape: shape of the new or existing variable. dtype: type of the new or existing variable (defaults to `DT_FLOAT`). initializer: initializer for the variable if one is created. regularizer: a (Tensor -> Tensor or None) function; the result of applying it on a newly created variable will be added to the collection GraphKeys.REGULARIZATION_LOSSES and can be used for regularization. trainable: If `True` also add the variable to the graph collection `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`). collections: A list of collection names to which the Variable will be added. If None it would default to `tf.GraphKeys.GLOBAL_VARIABLES`. caching_device: Optional device string or function describing where the Variable should be cached for reading. Defaults to the Variable's device. device: Optional device to place the variable. It can be an string or a function that is called to get the device for the variable. partitioner: Optional callable that accepts a fully defined `TensorShape` and dtype of the `Variable` to be created, and returns a list of partitions for each axis (currently only one axis can be partitioned). custom_getter: Callable that allows overwriting the internal get_variable method and has to have the same signature. use_resource: If `True` use a ResourceVariable instead of a Variable. Returns: The created or existing variable.
Gets an existing variable with these parameters or creates a new one.
[ "Gets", "an", "existing", "variable", "with", "these", "parameters", "or", "creates", "a", "new", "one", "." ]
def variable(name, shape=None, dtype=None, initializer=None, regularizer=None, trainable=True, collections=None, caching_device=None, device=None, partitioner=None, custom_getter=None, use_resource=None): """Gets an existing variable with these parameters or creates a new one. Args: name: the name of the new or existing variable. shape: shape of the new or existing variable. dtype: type of the new or existing variable (defaults to `DT_FLOAT`). initializer: initializer for the variable if one is created. regularizer: a (Tensor -> Tensor or None) function; the result of applying it on a newly created variable will be added to the collection GraphKeys.REGULARIZATION_LOSSES and can be used for regularization. trainable: If `True` also add the variable to the graph collection `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`). collections: A list of collection names to which the Variable will be added. If None it would default to `tf.GraphKeys.GLOBAL_VARIABLES`. caching_device: Optional device string or function describing where the Variable should be cached for reading. Defaults to the Variable's device. device: Optional device to place the variable. It can be an string or a function that is called to get the device for the variable. partitioner: Optional callable that accepts a fully defined `TensorShape` and dtype of the `Variable` to be created, and returns a list of partitions for each axis (currently only one axis can be partitioned). custom_getter: Callable that allows overwriting the internal get_variable method and has to have the same signature. use_resource: If `True` use a ResourceVariable instead of a Variable. Returns: The created or existing variable. """ collections = list(collections if collections is not None else [ops.GraphKeys.GLOBAL_VARIABLES]) # Remove duplicates collections = set(collections) getter = variable_scope.get_variable if custom_getter is not None: getter = functools.partial(custom_getter, reuse=variable_scope.get_variable_scope().reuse) with ops.device(device or ''): return getter(name, shape=shape, dtype=dtype, initializer=initializer, regularizer=regularizer, trainable=trainable, collections=collections, caching_device=caching_device, partitioner=partitioner, use_resource=use_resource)
[ "def", "variable", "(", "name", ",", "shape", "=", "None", ",", "dtype", "=", "None", ",", "initializer", "=", "None", ",", "regularizer", "=", "None", ",", "trainable", "=", "True", ",", "collections", "=", "None", ",", "caching_device", "=", "None", ",", "device", "=", "None", ",", "partitioner", "=", "None", ",", "custom_getter", "=", "None", ",", "use_resource", "=", "None", ")", ":", "collections", "=", "list", "(", "collections", "if", "collections", "is", "not", "None", "else", "[", "ops", ".", "GraphKeys", ".", "GLOBAL_VARIABLES", "]", ")", "# Remove duplicates", "collections", "=", "set", "(", "collections", ")", "getter", "=", "variable_scope", ".", "get_variable", "if", "custom_getter", "is", "not", "None", ":", "getter", "=", "functools", ".", "partial", "(", "custom_getter", ",", "reuse", "=", "variable_scope", ".", "get_variable_scope", "(", ")", ".", "reuse", ")", "with", "ops", ".", "device", "(", "device", "or", "''", ")", ":", "return", "getter", "(", "name", ",", "shape", "=", "shape", ",", "dtype", "=", "dtype", ",", "initializer", "=", "initializer", ",", "regularizer", "=", "regularizer", ",", "trainable", "=", "trainable", ",", "collections", "=", "collections", ",", "caching_device", "=", "caching_device", ",", "partitioner", "=", "partitioner", ",", "use_resource", "=", "use_resource", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/framework/python/ops/variables.py#L167-L217
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_gdi.py
python
EnhMetaFile.IsOk
(*args, **kwargs)
return _gdi_.EnhMetaFile_IsOk(*args, **kwargs)
IsOk(self) -> bool
IsOk(self) -> bool
[ "IsOk", "(", "self", ")", "-", ">", "bool" ]
def IsOk(*args, **kwargs): """IsOk(self) -> bool""" return _gdi_.EnhMetaFile_IsOk(*args, **kwargs)
[ "def", "IsOk", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "EnhMetaFile_IsOk", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L5540-L5542
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/dateutil/dateutil/parser/isoparser.py
python
isoparser.__init__
(self, sep=None)
:param sep: A single character that separates date and time portions. If ``None``, the parser will accept any single character. For strict ISO-8601 adherence, pass ``'T'``.
:param sep: A single character that separates date and time portions. If ``None``, the parser will accept any single character. For strict ISO-8601 adherence, pass ``'T'``.
[ ":", "param", "sep", ":", "A", "single", "character", "that", "separates", "date", "and", "time", "portions", ".", "If", "None", "the", "parser", "will", "accept", "any", "single", "character", ".", "For", "strict", "ISO", "-", "8601", "adherence", "pass", "T", "." ]
def __init__(self, sep=None): """ :param sep: A single character that separates date and time portions. If ``None``, the parser will accept any single character. For strict ISO-8601 adherence, pass ``'T'``. """ if sep is not None: if (len(sep) != 1 or ord(sep) >= 128 or sep in '0123456789'): raise ValueError('Separator must be a single, non-numeric ' + 'ASCII character') sep = sep.encode('ascii') self._sep = sep
[ "def", "__init__", "(", "self", ",", "sep", "=", "None", ")", ":", "if", "sep", "is", "not", "None", ":", "if", "(", "len", "(", "sep", ")", "!=", "1", "or", "ord", "(", "sep", ")", ">=", "128", "or", "sep", "in", "'0123456789'", ")", ":", "raise", "ValueError", "(", "'Separator must be a single, non-numeric '", "+", "'ASCII character'", ")", "sep", "=", "sep", ".", "encode", "(", "'ascii'", ")", "self", ".", "_sep", "=", "sep" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/dateutil/dateutil/parser/isoparser.py#L43-L57
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/xml/sax/xmlreader.py
python
AttributesImpl.__init__
(self, attrs)
Non-NS-aware implementation. attrs should be of the form {name : value}.
Non-NS-aware implementation.
[ "Non", "-", "NS", "-", "aware", "implementation", "." ]
def __init__(self, attrs): """Non-NS-aware implementation. attrs should be of the form {name : value}.""" self._attrs = attrs
[ "def", "__init__", "(", "self", ",", "attrs", ")", ":", "self", ".", "_attrs", "=", "attrs" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/xml/sax/xmlreader.py#L278-L282
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
config/check_spidermonkey_style.py
python
Include.section
(self, enclosing_inclname)
return 3
Identify which section inclname belongs to. The section numbers are as follows. 0. Module header (e.g. jsfoo.h or jsfooinlines.h within jsfoo.cpp) 1. mozilla/Foo.h 2. <foo.h> or <foo> 3. jsfoo.h, prmjtime.h, etc 4. foo/Bar.h 5. jsfooinlines.h 6. foo/Bar-inl.h 7. non-.h, e.g. *.tbl, *.msg
Identify which section inclname belongs to.
[ "Identify", "which", "section", "inclname", "belongs", "to", "." ]
def section(self, enclosing_inclname): '''Identify which section inclname belongs to. The section numbers are as follows. 0. Module header (e.g. jsfoo.h or jsfooinlines.h within jsfoo.cpp) 1. mozilla/Foo.h 2. <foo.h> or <foo> 3. jsfoo.h, prmjtime.h, etc 4. foo/Bar.h 5. jsfooinlines.h 6. foo/Bar-inl.h 7. non-.h, e.g. *.tbl, *.msg ''' if self.is_system: return 2 if not self.inclname.endswith('.h'): return 7 # A couple of modules have the .h file in js/ and the .cpp file elsewhere and so need # special handling. if is_module_header(enclosing_inclname, self.inclname): return 0 if '/' in self.inclname: if self.inclname.startswith('mozilla/'): return 1 if self.inclname.endswith('-inl.h'): return 6 return 4 if self.inclname.endswith('inlines.h'): return 5 return 3
[ "def", "section", "(", "self", ",", "enclosing_inclname", ")", ":", "if", "self", ".", "is_system", ":", "return", "2", "if", "not", "self", ".", "inclname", ".", "endswith", "(", "'.h'", ")", ":", "return", "7", "# A couple of modules have the .h file in js/ and the .cpp file elsewhere and so need", "# special handling.", "if", "is_module_header", "(", "enclosing_inclname", ",", "self", ".", "inclname", ")", ":", "return", "0", "if", "'/'", "in", "self", ".", "inclname", ":", "if", "self", ".", "inclname", ".", "startswith", "(", "'mozilla/'", ")", ":", "return", "1", "if", "self", ".", "inclname", ".", "endswith", "(", "'-inl.h'", ")", ":", "return", "6", "return", "4", "if", "self", ".", "inclname", ".", "endswith", "(", "'inlines.h'", ")", ":", "return", "5", "return", "3" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/config/check_spidermonkey_style.py#L335-L372
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/plotting/_matplotlib/converter.py
python
TimeSeries_TimedeltaFormatter.format_timedelta_ticks
(x, pos, n_decimals)
return s
Convert seconds to 'D days HH:MM:SS.F'
Convert seconds to 'D days HH:MM:SS.F'
[ "Convert", "seconds", "to", "D", "days", "HH", ":", "MM", ":", "SS", ".", "F" ]
def format_timedelta_ticks(x, pos, n_decimals): """ Convert seconds to 'D days HH:MM:SS.F' """ s, ns = divmod(x, 1e9) m, s = divmod(s, 60) h, m = divmod(m, 60) d, h = divmod(h, 24) decimals = int(ns * 10 ** (n_decimals - 9)) s = f"{int(h):02d}:{int(m):02d}:{int(s):02d}" if n_decimals > 0: s += f".{decimals:0{n_decimals}d}" if d != 0: s = f"{int(d):d} days {s}" return s
[ "def", "format_timedelta_ticks", "(", "x", ",", "pos", ",", "n_decimals", ")", ":", "s", ",", "ns", "=", "divmod", "(", "x", ",", "1e9", ")", "m", ",", "s", "=", "divmod", "(", "s", ",", "60", ")", "h", ",", "m", "=", "divmod", "(", "m", ",", "60", ")", "d", ",", "h", "=", "divmod", "(", "h", ",", "24", ")", "decimals", "=", "int", "(", "ns", "*", "10", "**", "(", "n_decimals", "-", "9", ")", ")", "s", "=", "f\"{int(h):02d}:{int(m):02d}:{int(s):02d}\"", "if", "n_decimals", ">", "0", ":", "s", "+=", "f\".{decimals:0{n_decimals}d}\"", "if", "d", "!=", "0", ":", "s", "=", "f\"{int(d):d} days {s}\"", "return", "s" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/plotting/_matplotlib/converter.py#L1111-L1125
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/operations/sponge_update_ops.py
python
PMEReciprocalForceUpdate.__init__
(self, atom_numbers, beta, fftx, ffty, fftz, box_length_0, box_length_1, box_length_2, need_update=0)
Initialize PMEReciprocalForce
Initialize PMEReciprocalForce
[ "Initialize", "PMEReciprocalForce" ]
def __init__(self, atom_numbers, beta, fftx, ffty, fftz, box_length_0, box_length_1, box_length_2, need_update=0): """Initialize PMEReciprocalForce""" validator.check_value_type('atom_numbers', atom_numbers, int, self.name) validator.check_value_type('beta', beta, float, self.name) validator.check_value_type('fftx', fftx, int, self.name) validator.check_value_type('ffty', ffty, int, self.name) validator.check_value_type('fftz', fftz, int, self.name) validator.check_value_type('box_length_0', box_length_0, float, self.name) validator.check_value_type('box_length_1', box_length_1, float, self.name) validator.check_value_type('box_length_2', box_length_2, float, self.name) validator.check_value_type('need_update', need_update, int, self.name) self.atom_numbers = atom_numbers self.beta = beta self.fftx = fftx self.ffty = ffty self.fftz = fftz self.box_length_0 = box_length_0 self.box_length_1 = box_length_1 self.box_length_2 = box_length_2 self.need_update = need_update self.init_prim_io_names(inputs=['uint_crd', 'charge', 'beta'], outputs=['force']) self.add_prim_attr('atom_numbers', self.atom_numbers) self.add_prim_attr('beta', self.beta) self.add_prim_attr('fftx', self.fftx) self.add_prim_attr('ffty', self.ffty) self.add_prim_attr('fftz', self.fftz) self.add_prim_attr('box_length_0', self.box_length_0) self.add_prim_attr('box_length_1', self.box_length_1) self.add_prim_attr('box_length_2', self.box_length_2) self.add_prim_attr('need_update', self.need_update)
[ "def", "__init__", "(", "self", ",", "atom_numbers", ",", "beta", ",", "fftx", ",", "ffty", ",", "fftz", ",", "box_length_0", ",", "box_length_1", ",", "box_length_2", ",", "need_update", "=", "0", ")", ":", "validator", ".", "check_value_type", "(", "'atom_numbers'", ",", "atom_numbers", ",", "int", ",", "self", ".", "name", ")", "validator", ".", "check_value_type", "(", "'beta'", ",", "beta", ",", "float", ",", "self", ".", "name", ")", "validator", ".", "check_value_type", "(", "'fftx'", ",", "fftx", ",", "int", ",", "self", ".", "name", ")", "validator", ".", "check_value_type", "(", "'ffty'", ",", "ffty", ",", "int", ",", "self", ".", "name", ")", "validator", ".", "check_value_type", "(", "'fftz'", ",", "fftz", ",", "int", ",", "self", ".", "name", ")", "validator", ".", "check_value_type", "(", "'box_length_0'", ",", "box_length_0", ",", "float", ",", "self", ".", "name", ")", "validator", ".", "check_value_type", "(", "'box_length_1'", ",", "box_length_1", ",", "float", ",", "self", ".", "name", ")", "validator", ".", "check_value_type", "(", "'box_length_2'", ",", "box_length_2", ",", "float", ",", "self", ".", "name", ")", "validator", ".", "check_value_type", "(", "'need_update'", ",", "need_update", ",", "int", ",", "self", ".", "name", ")", "self", ".", "atom_numbers", "=", "atom_numbers", "self", ".", "beta", "=", "beta", "self", ".", "fftx", "=", "fftx", "self", ".", "ffty", "=", "ffty", "self", ".", "fftz", "=", "fftz", "self", ".", "box_length_0", "=", "box_length_0", "self", ".", "box_length_1", "=", "box_length_1", "self", ".", "box_length_2", "=", "box_length_2", "self", ".", "need_update", "=", "need_update", "self", ".", "init_prim_io_names", "(", "inputs", "=", "[", "'uint_crd'", ",", "'charge'", ",", "'beta'", "]", ",", "outputs", "=", "[", "'force'", "]", ")", "self", ".", "add_prim_attr", "(", "'atom_numbers'", ",", "self", ".", "atom_numbers", ")", "self", ".", "add_prim_attr", "(", "'beta'", ",", "self", ".", "beta", ")", "self", ".", "add_prim_attr", "(", "'fftx'", ",", "self", ".", "fftx", ")", "self", ".", "add_prim_attr", "(", "'ffty'", ",", "self", ".", "ffty", ")", "self", ".", "add_prim_attr", "(", "'fftz'", ",", "self", ".", "fftz", ")", "self", ".", "add_prim_attr", "(", "'box_length_0'", ",", "self", ".", "box_length_0", ")", "self", ".", "add_prim_attr", "(", "'box_length_1'", ",", "self", ".", "box_length_1", ")", "self", ".", "add_prim_attr", "(", "'box_length_2'", ",", "self", ".", "box_length_2", ")", "self", ".", "add_prim_attr", "(", "'need_update'", ",", "self", ".", "need_update", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/operations/sponge_update_ops.py#L1601-L1633
DLR-SC/tigl
d1c5901e948e33d10b1f9659ff3e22c4717b455f
thirdparty/nsiqcppstyle/nsiqcppstyle_checker.py
python
CppLexerNavigator.GetCurToken
(self)
return self.tokenlist[self.tokenindex]
Get Current Token
Get Current Token
[ "Get", "Current", "Token" ]
def GetCurToken(self): """ Get Current Token """ return self.tokenlist[self.tokenindex]
[ "def", "GetCurToken", "(", "self", ")", ":", "return", "self", ".", "tokenlist", "[", "self", ".", "tokenindex", "]" ]
https://github.com/DLR-SC/tigl/blob/d1c5901e948e33d10b1f9659ff3e22c4717b455f/thirdparty/nsiqcppstyle/nsiqcppstyle_checker.py#L417-L421
rrwick/Unicycler
96ffea71e3a78d63ade19d6124946773e65cf129
unicycler/misc.py
python
flip_number_order
(num_1, num_2)
Given two segment numbers, this function possibly flips them around. It returns the new numbers (either unchanged or flipped) and whether or not a flip took place. The decision is somewhat arbitrary, but it needs to be consistent so when we collect bridging read sequences they are always in the same direction.
Given two segment numbers, this function possibly flips them around. It returns the new numbers (either unchanged or flipped) and whether or not a flip took place. The decision is somewhat arbitrary, but it needs to be consistent so when we collect bridging read sequences they are always in the same direction.
[ "Given", "two", "segment", "numbers", "this", "function", "possibly", "flips", "them", "around", ".", "It", "returns", "the", "new", "numbers", "(", "either", "unchanged", "or", "flipped", ")", "and", "whether", "or", "not", "a", "flip", "took", "place", ".", "The", "decision", "is", "somewhat", "arbitrary", "but", "it", "needs", "to", "be", "consistent", "so", "when", "we", "collect", "bridging", "read", "sequences", "they", "are", "always", "in", "the", "same", "direction", "." ]
def flip_number_order(num_1, num_2): """ Given two segment numbers, this function possibly flips them around. It returns the new numbers (either unchanged or flipped) and whether or not a flip took place. The decision is somewhat arbitrary, but it needs to be consistent so when we collect bridging read sequences they are always in the same direction. """ if num_1 > 0 and num_2 > 0: flip = False elif num_1 < 0 and num_2 < 0: flip = True elif num_1 < 0: # only num_1 is negative flip = abs(num_1) > abs(num_2) else: # only num_2 is negative flip = abs(num_2) > abs(num_1) if flip: return (-num_2, -num_1), True else: return (num_1, num_2), False
[ "def", "flip_number_order", "(", "num_1", ",", "num_2", ")", ":", "if", "num_1", ">", "0", "and", "num_2", ">", "0", ":", "flip", "=", "False", "elif", "num_1", "<", "0", "and", "num_2", "<", "0", ":", "flip", "=", "True", "elif", "num_1", "<", "0", ":", "# only num_1 is negative", "flip", "=", "abs", "(", "num_1", ")", ">", "abs", "(", "num_2", ")", "else", ":", "# only num_2 is negative", "flip", "=", "abs", "(", "num_2", ")", ">", "abs", "(", "num_1", ")", "if", "flip", ":", "return", "(", "-", "num_2", ",", "-", "num_1", ")", ",", "True", "else", ":", "return", "(", "num_1", ",", "num_2", ")", ",", "False" ]
https://github.com/rrwick/Unicycler/blob/96ffea71e3a78d63ade19d6124946773e65cf129/unicycler/misc.py#L299-L317
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Source/ThirdParty/CEF3/pristine/cef_source/tools/make_distrib.py
python
normalize_headers
(file, new_path = '')
Normalize headers post-processing. Remove the path component from any project include directives.
Normalize headers post-processing. Remove the path component from any project include directives.
[ "Normalize", "headers", "post", "-", "processing", ".", "Remove", "the", "path", "component", "from", "any", "project", "include", "directives", "." ]
def normalize_headers(file, new_path = ''): """ Normalize headers post-processing. Remove the path component from any project include directives. """ data = read_file(file) data = re.sub(r'''#include \"(?!include\/)[a-zA-Z0-9_\/]+\/+([a-zA-Z0-9_\.]+)\"''', \ "// Include path modified for CEF Binary Distribution.\n#include \""+new_path+"\\1\"", data) write_file(file, data)
[ "def", "normalize_headers", "(", "file", ",", "new_path", "=", "''", ")", ":", "data", "=", "read_file", "(", "file", ")", "data", "=", "re", ".", "sub", "(", "r'''#include \\\"(?!include\\/)[a-zA-Z0-9_\\/]+\\/+([a-zA-Z0-9_\\.]+)\\\"'''", ",", "\"// Include path modified for CEF Binary Distribution.\\n#include \\\"\"", "+", "new_path", "+", "\"\\\\1\\\"\"", ",", "data", ")", "write_file", "(", "file", ",", "data", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Source/ThirdParty/CEF3/pristine/cef_source/tools/make_distrib.py#L195-L201
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py
python
ContainerSize.setparameter
(self, container, name)
Read a size parameter off a container, and set it if present.
Read a size parameter off a container, and set it if present.
[ "Read", "a", "size", "parameter", "off", "a", "container", "and", "set", "it", "if", "present", "." ]
def setparameter(self, container, name): "Read a size parameter off a container, and set it if present." value = container.getparameter(name) self.setvalue(name, value)
[ "def", "setparameter", "(", "self", ",", "container", ",", "name", ")", ":", "value", "=", "container", ".", "getparameter", "(", "name", ")", "self", ".", "setvalue", "(", "name", ",", "value", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py#L3443-L3446
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/src/robotsim.py
python
IKSolver.add
(self, objective)
return _robotsim.IKSolver_add(self, objective)
add(IKSolver self, IKObjective objective) Adds a new simultaneous objective.
add(IKSolver self, IKObjective objective)
[ "add", "(", "IKSolver", "self", "IKObjective", "objective", ")" ]
def add(self, objective): """ add(IKSolver self, IKObjective objective) Adds a new simultaneous objective. """ return _robotsim.IKSolver_add(self, objective)
[ "def", "add", "(", "self", ",", "objective", ")", ":", "return", "_robotsim", ".", "IKSolver_add", "(", "self", ",", "objective", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/src/robotsim.py#L6595-L6604
zerotier/libzt
41eb9aebc80a5f1c816fa26a06cefde9de906676
src/bindings/python/sockets.py
python
socket.getpeername
(self)
libzt does not support this (yet)
libzt does not support this (yet)
[ "libzt", "does", "not", "support", "this", "(", "yet", ")" ]
def getpeername(self): """libzt does not support this (yet)""" raise NotImplementedError("libzt does not support this (yet?)")
[ "def", "getpeername", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "\"libzt does not support this (yet?)\"", ")" ]
https://github.com/zerotier/libzt/blob/41eb9aebc80a5f1c816fa26a06cefde9de906676/src/bindings/python/sockets.py#L291-L293
rdkit/rdkit
ede860ae316d12d8568daf5ee800921c3389c84e
rdkit/ML/DecTree/PruneTree.py
python
_Pruner
(node, level=0)
return bestTree
Recursively finds and removes the nodes whose removals improve classification **Arguments** - node: the tree to be pruned. The pruning data should already be contained within node (i.e. node.GetExamples() should return the pruning data) - level: (optional) the level of recursion, used only in _verbose printing **Returns** the pruned version of node **Notes** - This uses a greedy algorithm which basically does a DFS traversal of the tree, removing nodes whenever possible. - If removing a node does not affect the accuracy, it *will be* removed. We favor smaller trees.
Recursively finds and removes the nodes whose removals improve classification
[ "Recursively", "finds", "and", "removes", "the", "nodes", "whose", "removals", "improve", "classification" ]
def _Pruner(node, level=0): """Recursively finds and removes the nodes whose removals improve classification **Arguments** - node: the tree to be pruned. The pruning data should already be contained within node (i.e. node.GetExamples() should return the pruning data) - level: (optional) the level of recursion, used only in _verbose printing **Returns** the pruned version of node **Notes** - This uses a greedy algorithm which basically does a DFS traversal of the tree, removing nodes whenever possible. - If removing a node does not affect the accuracy, it *will be* removed. We favor smaller trees. """ if _verbose: print(' ' * level, '<%d> ' % level, '>>> Pruner') children = node.GetChildren()[:] bestTree = copy.deepcopy(node) bestErr = 1e6 # # Loop over the children of this node, removing them when doing so # either improves the local error or leaves it unchanged (we're # introducing a bias for simpler trees). # for i in range(len(children)): child = children[i] examples = child.GetExamples() if _verbose: print(' ' * level, '<%d> ' % level, ' Child:', i, child.GetLabel()) bestTree.Print() print() if len(examples): if _verbose: print(' ' * level, '<%d> ' % level, ' Examples', len(examples)) if child.GetTerminal(): if _verbose: print(' ' * level, '<%d> ' % level, ' Terminal') continue if _verbose: print(' ' * level, '<%d> ' % level, ' Nonterminal') workTree = copy.deepcopy(bestTree) # # First recurse on the child (try removing things below it) # newNode = _Pruner(child, level=level + 1) workTree.ReplaceChildIndex(i, newNode) tempErr = _GetLocalError(workTree) if tempErr <= bestErr: bestErr = tempErr bestTree = copy.deepcopy(workTree) if _verbose: print(' ' * level, '<%d> ' % level, '>->->->->->') print(' ' * level, '<%d> ' % level, 'replacing:', i, child.GetLabel()) child.Print() print(' ' * level, '<%d> ' % level, 'with:') newNode.Print() print(' ' * level, '<%d> ' % level, '<-<-<-<-<-<') else: workTree.ReplaceChildIndex(i, child) # # Now try replacing the child entirely # bestGuess = MaxCount(child.GetExamples()) newNode = DecTree.DecTreeNode(workTree, 'L:%d' % ( bestGuess), label=bestGuess, isTerminal=1) newNode.SetExamples(child.GetExamples()) workTree.ReplaceChildIndex(i, newNode) if _verbose: print(' ' * level, '<%d> ' % level, 'ATTEMPT:') workTree.Print() newErr = _GetLocalError(workTree) if _verbose: print(' ' * level, '<%d> ' % level, '---> ', newErr, bestErr) if newErr <= bestErr: bestErr = newErr bestTree = copy.deepcopy(workTree) if _verbose: print(' ' * level, '<%d> ' % level, 'PRUNING:') workTree.Print() else: if _verbose: print(' ' * level, '<%d> ' % level, 'FAIL') # whoops... put the child back in: workTree.ReplaceChildIndex(i, child) else: if _verbose: print(' ' * level, '<%d> ' % level, ' No Examples', len(examples)) # # FIX: we need to figure out what to do here (nodes that contain # no examples in the testing set). I can concoct arguments for # leaving them in and for removing them. At the moment they are # left intact. # pass if _verbose: print(' ' * level, '<%d> ' % level, '<<< out') return bestTree
[ "def", "_Pruner", "(", "node", ",", "level", "=", "0", ")", ":", "if", "_verbose", ":", "print", "(", "' '", "*", "level", ",", "'<%d> '", "%", "level", ",", "'>>> Pruner'", ")", "children", "=", "node", ".", "GetChildren", "(", ")", "[", ":", "]", "bestTree", "=", "copy", ".", "deepcopy", "(", "node", ")", "bestErr", "=", "1e6", "#", "# Loop over the children of this node, removing them when doing so", "# either improves the local error or leaves it unchanged (we're", "# introducing a bias for simpler trees).", "#", "for", "i", "in", "range", "(", "len", "(", "children", ")", ")", ":", "child", "=", "children", "[", "i", "]", "examples", "=", "child", ".", "GetExamples", "(", ")", "if", "_verbose", ":", "print", "(", "' '", "*", "level", ",", "'<%d> '", "%", "level", ",", "' Child:'", ",", "i", ",", "child", ".", "GetLabel", "(", ")", ")", "bestTree", ".", "Print", "(", ")", "print", "(", ")", "if", "len", "(", "examples", ")", ":", "if", "_verbose", ":", "print", "(", "' '", "*", "level", ",", "'<%d> '", "%", "level", ",", "' Examples'", ",", "len", "(", "examples", ")", ")", "if", "child", ".", "GetTerminal", "(", ")", ":", "if", "_verbose", ":", "print", "(", "' '", "*", "level", ",", "'<%d> '", "%", "level", ",", "' Terminal'", ")", "continue", "if", "_verbose", ":", "print", "(", "' '", "*", "level", ",", "'<%d> '", "%", "level", ",", "' Nonterminal'", ")", "workTree", "=", "copy", ".", "deepcopy", "(", "bestTree", ")", "#", "# First recurse on the child (try removing things below it)", "#", "newNode", "=", "_Pruner", "(", "child", ",", "level", "=", "level", "+", "1", ")", "workTree", ".", "ReplaceChildIndex", "(", "i", ",", "newNode", ")", "tempErr", "=", "_GetLocalError", "(", "workTree", ")", "if", "tempErr", "<=", "bestErr", ":", "bestErr", "=", "tempErr", "bestTree", "=", "copy", ".", "deepcopy", "(", "workTree", ")", "if", "_verbose", ":", "print", "(", "' '", "*", "level", ",", "'<%d> '", "%", "level", ",", "'>->->->->->'", ")", "print", "(", "' '", "*", "level", ",", "'<%d> '", "%", "level", ",", "'replacing:'", ",", "i", ",", "child", ".", "GetLabel", "(", ")", ")", "child", ".", "Print", "(", ")", "print", "(", "' '", "*", "level", ",", "'<%d> '", "%", "level", ",", "'with:'", ")", "newNode", ".", "Print", "(", ")", "print", "(", "' '", "*", "level", ",", "'<%d> '", "%", "level", ",", "'<-<-<-<-<-<'", ")", "else", ":", "workTree", ".", "ReplaceChildIndex", "(", "i", ",", "child", ")", "#", "# Now try replacing the child entirely", "#", "bestGuess", "=", "MaxCount", "(", "child", ".", "GetExamples", "(", ")", ")", "newNode", "=", "DecTree", ".", "DecTreeNode", "(", "workTree", ",", "'L:%d'", "%", "(", "bestGuess", ")", ",", "label", "=", "bestGuess", ",", "isTerminal", "=", "1", ")", "newNode", ".", "SetExamples", "(", "child", ".", "GetExamples", "(", ")", ")", "workTree", ".", "ReplaceChildIndex", "(", "i", ",", "newNode", ")", "if", "_verbose", ":", "print", "(", "' '", "*", "level", ",", "'<%d> '", "%", "level", ",", "'ATTEMPT:'", ")", "workTree", ".", "Print", "(", ")", "newErr", "=", "_GetLocalError", "(", "workTree", ")", "if", "_verbose", ":", "print", "(", "' '", "*", "level", ",", "'<%d> '", "%", "level", ",", "'---> '", ",", "newErr", ",", "bestErr", ")", "if", "newErr", "<=", "bestErr", ":", "bestErr", "=", "newErr", "bestTree", "=", "copy", ".", "deepcopy", "(", "workTree", ")", "if", "_verbose", ":", "print", "(", "' '", "*", "level", ",", "'<%d> '", "%", "level", ",", "'PRUNING:'", ")", "workTree", ".", "Print", "(", ")", "else", ":", "if", "_verbose", ":", "print", "(", "' '", "*", "level", ",", "'<%d> '", "%", "level", ",", "'FAIL'", ")", "# whoops... put the child back in:", "workTree", ".", "ReplaceChildIndex", "(", "i", ",", "child", ")", "else", ":", "if", "_verbose", ":", "print", "(", "' '", "*", "level", ",", "'<%d> '", "%", "level", ",", "' No Examples'", ",", "len", "(", "examples", ")", ")", "#", "# FIX: we need to figure out what to do here (nodes that contain", "# no examples in the testing set). I can concoct arguments for", "# leaving them in and for removing them. At the moment they are", "# left intact.", "#", "pass", "if", "_verbose", ":", "print", "(", "' '", "*", "level", ",", "'<%d> '", "%", "level", ",", "'<<< out'", ")", "return", "bestTree" ]
https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/ML/DecTree/PruneTree.py#L49-L160
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/turtle.py
python
_Screen.exitonclick
(self)
Go into mainloop until the mouse is clicked. No arguments. Bind bye() method to mouseclick on TurtleScreen. If "using_IDLE" - value in configuration dictionary is False (default value), enter mainloop. If IDLE with -n switch (no subprocess) is used, this value should be set to True in turtle.cfg. In this case IDLE's mainloop is active also for the client script. This is a method of the Screen-class and not available for TurtleScreen instances. Example (for a Screen instance named screen): >>> screen.exitonclick()
Go into mainloop until the mouse is clicked.
[ "Go", "into", "mainloop", "until", "the", "mouse", "is", "clicked", "." ]
def exitonclick(self): """Go into mainloop until the mouse is clicked. No arguments. Bind bye() method to mouseclick on TurtleScreen. If "using_IDLE" - value in configuration dictionary is False (default value), enter mainloop. If IDLE with -n switch (no subprocess) is used, this value should be set to True in turtle.cfg. In this case IDLE's mainloop is active also for the client script. This is a method of the Screen-class and not available for TurtleScreen instances. Example (for a Screen instance named screen): >>> screen.exitonclick() """ def exitGracefully(x, y): """Screen.bye() with two dummy-parameters""" self.bye() self.onclick(exitGracefully) if _CFG["using_IDLE"]: return try: mainloop() except AttributeError: exit(0)
[ "def", "exitonclick", "(", "self", ")", ":", "def", "exitGracefully", "(", "x", ",", "y", ")", ":", "\"\"\"Screen.bye() with two dummy-parameters\"\"\"", "self", ".", "bye", "(", ")", "self", ".", "onclick", "(", "exitGracefully", ")", "if", "_CFG", "[", "\"using_IDLE\"", "]", ":", "return", "try", ":", "mainloop", "(", ")", "except", "AttributeError", ":", "exit", "(", "0", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/turtle.py#L3768-L3796
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/idl_parser/idl_lexer.py
python
IDLLexer.t_ELLIPSIS
(self, t)
return t
r'\.\.\.
r'\.\.\.
[ "r", "\\", ".", "\\", ".", "\\", "." ]
def t_ELLIPSIS(self, t): r'\.\.\.' return t
[ "def", "t_ELLIPSIS", "(", "self", ",", "t", ")", ":", "return", "t" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/idl_parser/idl_lexer.py#L128-L130
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/unicode.py
python
_rfinder
(data, substr, start, end)
return -1
Right finder.
Right finder.
[ "Right", "finder", "." ]
def _rfinder(data, substr, start, end): """Right finder.""" if len(substr) == 0: return end for i in range(min(len(data), end) - len(substr), start - 1, -1): if _cmp_region(data, i, substr, 0, len(substr)) == 0: return i return -1
[ "def", "_rfinder", "(", "data", ",", "substr", ",", "start", ",", "end", ")", ":", "if", "len", "(", "substr", ")", "==", "0", ":", "return", "end", "for", "i", "in", "range", "(", "min", "(", "len", "(", "data", ")", ",", "end", ")", "-", "len", "(", "substr", ")", ",", "start", "-", "1", ",", "-", "1", ")", ":", "if", "_cmp_region", "(", "data", ",", "i", ",", "substr", ",", "0", ",", "len", "(", "substr", ")", ")", "==", "0", ":", "return", "i", "return", "-", "1" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/unicode.py#L590-L597
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/examples/tutorials/mnist/mnist.py
python
inference
(images, hidden1_units, hidden2_units)
return logits
Build the MNIST model up to where it may be used for inference. Args: images: Images placeholder, from inputs(). hidden1_units: Size of the first hidden layer. hidden2_units: Size of the second hidden layer. Returns: softmax_linear: Output tensor with the computed logits.
Build the MNIST model up to where it may be used for inference.
[ "Build", "the", "MNIST", "model", "up", "to", "where", "it", "may", "be", "used", "for", "inference", "." ]
def inference(images, hidden1_units, hidden2_units): """Build the MNIST model up to where it may be used for inference. Args: images: Images placeholder, from inputs(). hidden1_units: Size of the first hidden layer. hidden2_units: Size of the second hidden layer. Returns: softmax_linear: Output tensor with the computed logits. """ # Hidden 1 with tf.name_scope('hidden1'): weights = tf.Variable( tf.truncated_normal([IMAGE_PIXELS, hidden1_units], stddev=1.0 / math.sqrt(float(IMAGE_PIXELS))), name='weights') biases = tf.Variable(tf.zeros([hidden1_units]), name='biases') hidden1 = tf.nn.relu(tf.matmul(images, weights) + biases) # Hidden 2 with tf.name_scope('hidden2'): weights = tf.Variable( tf.truncated_normal([hidden1_units, hidden2_units], stddev=1.0 / math.sqrt(float(hidden1_units))), name='weights') biases = tf.Variable(tf.zeros([hidden2_units]), name='biases') hidden2 = tf.nn.relu(tf.matmul(hidden1, weights) + biases) # Linear with tf.name_scope('softmax_linear'): weights = tf.Variable( tf.truncated_normal([hidden2_units, NUM_CLASSES], stddev=1.0 / math.sqrt(float(hidden2_units))), name='weights') biases = tf.Variable(tf.zeros([NUM_CLASSES]), name='biases') logits = tf.matmul(hidden2, weights) + biases return logits
[ "def", "inference", "(", "images", ",", "hidden1_units", ",", "hidden2_units", ")", ":", "# Hidden 1", "with", "tf", ".", "name_scope", "(", "'hidden1'", ")", ":", "weights", "=", "tf", ".", "Variable", "(", "tf", ".", "truncated_normal", "(", "[", "IMAGE_PIXELS", ",", "hidden1_units", "]", ",", "stddev", "=", "1.0", "/", "math", ".", "sqrt", "(", "float", "(", "IMAGE_PIXELS", ")", ")", ")", ",", "name", "=", "'weights'", ")", "biases", "=", "tf", ".", "Variable", "(", "tf", ".", "zeros", "(", "[", "hidden1_units", "]", ")", ",", "name", "=", "'biases'", ")", "hidden1", "=", "tf", ".", "nn", ".", "relu", "(", "tf", ".", "matmul", "(", "images", ",", "weights", ")", "+", "biases", ")", "# Hidden 2", "with", "tf", ".", "name_scope", "(", "'hidden2'", ")", ":", "weights", "=", "tf", ".", "Variable", "(", "tf", ".", "truncated_normal", "(", "[", "hidden1_units", ",", "hidden2_units", "]", ",", "stddev", "=", "1.0", "/", "math", ".", "sqrt", "(", "float", "(", "hidden1_units", ")", ")", ")", ",", "name", "=", "'weights'", ")", "biases", "=", "tf", ".", "Variable", "(", "tf", ".", "zeros", "(", "[", "hidden2_units", "]", ")", ",", "name", "=", "'biases'", ")", "hidden2", "=", "tf", ".", "nn", ".", "relu", "(", "tf", ".", "matmul", "(", "hidden1", ",", "weights", ")", "+", "biases", ")", "# Linear", "with", "tf", ".", "name_scope", "(", "'softmax_linear'", ")", ":", "weights", "=", "tf", ".", "Variable", "(", "tf", ".", "truncated_normal", "(", "[", "hidden2_units", ",", "NUM_CLASSES", "]", ",", "stddev", "=", "1.0", "/", "math", ".", "sqrt", "(", "float", "(", "hidden2_units", ")", ")", ")", ",", "name", "=", "'weights'", ")", "biases", "=", "tf", ".", "Variable", "(", "tf", ".", "zeros", "(", "[", "NUM_CLASSES", "]", ")", ",", "name", "=", "'biases'", ")", "logits", "=", "tf", ".", "matmul", "(", "hidden2", ",", "weights", ")", "+", "biases", "return", "logits" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/examples/tutorials/mnist/mnist.py#L45-L83
savoirfairelinux/jami-daemon
7634487e9f568ae727f2d4cffbb735d23fa0324c
tools/jamictrl/controller.py
python
DRingCtrl.onCallInactive
(self, callid, state)
Update state for this call to current
Update state for this call to current
[ "Update", "state", "for", "this", "call", "to", "current" ]
def onCallInactive(self, callid, state): """ Update state for this call to current """ self.activeCalls[callid]['State'] = state self.onCallInactive_cb()
[ "def", "onCallInactive", "(", "self", ",", "callid", ",", "state", ")", ":", "self", ".", "activeCalls", "[", "callid", "]", "[", "'State'", "]", "=", "state", "self", ".", "onCallInactive_cb", "(", ")" ]
https://github.com/savoirfairelinux/jami-daemon/blob/7634487e9f568ae727f2d4cffbb735d23fa0324c/tools/jamictrl/controller.py#L231-L235
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBProcess.GetSelectedThread
(self)
return _lldb.SBProcess_GetSelectedThread(self)
Returns the currently selected thread.
[]
def GetSelectedThread(self): """ Returns the currently selected thread. """ return _lldb.SBProcess_GetSelectedThread(self)
[ "def", "GetSelectedThread", "(", "self", ")", ":", "return", "_lldb", ".", "SBProcess_GetSelectedThread", "(", "self", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L8425-L8430
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/distutils/system_info.py
python
_c_string_literal
(s)
return '"{}"'.format(s)
Convert a python string into a literal suitable for inclusion into C code
Convert a python string into a literal suitable for inclusion into C code
[ "Convert", "a", "python", "string", "into", "a", "literal", "suitable", "for", "inclusion", "into", "C", "code" ]
def _c_string_literal(s): """ Convert a python string into a literal suitable for inclusion into C code """ # only these three characters are forbidden in C strings s = s.replace('\\', r'\\') s = s.replace('"', r'\"') s = s.replace('\n', r'\n') return '"{}"'.format(s)
[ "def", "_c_string_literal", "(", "s", ")", ":", "# only these three characters are forbidden in C strings", "s", "=", "s", ".", "replace", "(", "'\\\\'", ",", "r'\\\\'", ")", "s", "=", "s", ".", "replace", "(", "'\"'", ",", "r'\\\"'", ")", "s", "=", "s", ".", "replace", "(", "'\\n'", ",", "r'\\n'", ")", "return", "'\"{}\"'", ".", "format", "(", "s", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/distutils/system_info.py#L189-L197
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/speedmeter.py
python
SpeedMeter.GetIntervalColours
(self)
Returns the colours for the intervals.
Returns the colours for the intervals.
[ "Returns", "the", "colours", "for", "the", "intervals", "." ]
def GetIntervalColours(self): """ Returns the colours for the intervals.""" if hasattr(self, "_intervalcolours"): return self._intervalcolours else: raise Exception("\nERROR: No Interval Colours Have Been Defined")
[ "def", "GetIntervalColours", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "\"_intervalcolours\"", ")", ":", "return", "self", ".", "_intervalcolours", "else", ":", "raise", "Exception", "(", "\"\\nERROR: No Interval Colours Have Been Defined\"", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/speedmeter.py#L1232-L1238
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/operator.py
python
PythonOp.forward
(self, in_data, out_data)
Forward interface. Override to create new operators. Parameters ---------- in_data, out_data: list input and output for forward. See document for corresponding arguments of Operator::Forward
Forward interface. Override to create new operators.
[ "Forward", "interface", ".", "Override", "to", "create", "new", "operators", "." ]
def forward(self, in_data, out_data): """Forward interface. Override to create new operators. Parameters ---------- in_data, out_data: list input and output for forward. See document for corresponding arguments of Operator::Forward """ out_data[0][:] = in_data[0]
[ "def", "forward", "(", "self", ",", "in_data", ",", "out_data", ")", ":", "out_data", "[", "0", "]", "[", ":", "]", "=", "in_data", "[", "0", "]" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/operator.py#L80-L89
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/generic.py
python
NDFrame._set_axis_name
(self, name, axis=0, inplace=False)
Set the name(s) of the axis. Parameters ---------- name : str or list of str Name(s) to set. axis : {0 or 'index', 1 or 'columns'}, default 0 The axis to set the label. The value 0 or 'index' specifies index, and the value 1 or 'columns' specifies columns. inplace : bool, default False If `True`, do operation inplace and return None. .. versionadded:: 0.21.0 Returns ------- Series, DataFrame, or None The same type as the caller or `None` if `inplace` is `True`. See Also -------- DataFrame.rename : Alter the axis labels of :class:`DataFrame`. Series.rename : Alter the index labels or set the index name of :class:`Series`. Index.rename : Set the name of :class:`Index` or :class:`MultiIndex`. Examples -------- >>> df = pd.DataFrame({"num_legs": [4, 4, 2]}, ... ["dog", "cat", "monkey"]) >>> df num_legs dog 4 cat 4 monkey 2 >>> df._set_axis_name("animal") num_legs animal dog 4 cat 4 monkey 2 >>> df.index = pd.MultiIndex.from_product( ... [["mammal"], ['dog', 'cat', 'monkey']]) >>> df._set_axis_name(["type", "name"]) legs type name mammal dog 4 cat 4 monkey 2
Set the name(s) of the axis.
[ "Set", "the", "name", "(", "s", ")", "of", "the", "axis", "." ]
def _set_axis_name(self, name, axis=0, inplace=False): """ Set the name(s) of the axis. Parameters ---------- name : str or list of str Name(s) to set. axis : {0 or 'index', 1 or 'columns'}, default 0 The axis to set the label. The value 0 or 'index' specifies index, and the value 1 or 'columns' specifies columns. inplace : bool, default False If `True`, do operation inplace and return None. .. versionadded:: 0.21.0 Returns ------- Series, DataFrame, or None The same type as the caller or `None` if `inplace` is `True`. See Also -------- DataFrame.rename : Alter the axis labels of :class:`DataFrame`. Series.rename : Alter the index labels or set the index name of :class:`Series`. Index.rename : Set the name of :class:`Index` or :class:`MultiIndex`. Examples -------- >>> df = pd.DataFrame({"num_legs": [4, 4, 2]}, ... ["dog", "cat", "monkey"]) >>> df num_legs dog 4 cat 4 monkey 2 >>> df._set_axis_name("animal") num_legs animal dog 4 cat 4 monkey 2 >>> df.index = pd.MultiIndex.from_product( ... [["mammal"], ['dog', 'cat', 'monkey']]) >>> df._set_axis_name(["type", "name"]) legs type name mammal dog 4 cat 4 monkey 2 """ axis = self._get_axis_number(axis) idx = self._get_axis(axis).set_names(name) inplace = validate_bool_kwarg(inplace, 'inplace') renamed = self if inplace else self.copy() renamed.set_axis(idx, axis=axis, inplace=True) if not inplace: return renamed
[ "def", "_set_axis_name", "(", "self", ",", "name", ",", "axis", "=", "0", ",", "inplace", "=", "False", ")", ":", "axis", "=", "self", ".", "_get_axis_number", "(", "axis", ")", "idx", "=", "self", ".", "_get_axis", "(", "axis", ")", ".", "set_names", "(", "name", ")", "inplace", "=", "validate_bool_kwarg", "(", "inplace", ",", "'inplace'", ")", "renamed", "=", "self", "if", "inplace", "else", "self", ".", "copy", "(", ")", "renamed", ".", "set_axis", "(", "idx", ",", "axis", "=", "axis", ",", "inplace", "=", "True", ")", "if", "not", "inplace", ":", "return", "renamed" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/generic.py#L1282-L1341
gimli-org/gimli
17aa2160de9b15ababd9ef99e89b1bc3277bbb23
pygimli/physics/em/fdem.py
python
FDEM.deactivate
(self, fr)
Deactivate a single frequency.
Deactivate a single frequency.
[ "Deactivate", "a", "single", "frequency", "." ]
def deactivate(self, fr): """Deactivate a single frequency.""" fi = np.nonzero(np.absolute(self.frequencies / fr - 1.) < 0.1) self.isActiveFreq[fi] = False self.activeFreq = np.nonzero(self.isActiveFreq)[0]
[ "def", "deactivate", "(", "self", ",", "fr", ")", ":", "fi", "=", "np", ".", "nonzero", "(", "np", ".", "absolute", "(", "self", ".", "frequencies", "/", "fr", "-", "1.", ")", "<", "0.1", ")", "self", ".", "isActiveFreq", "[", "fi", "]", "=", "False", "self", ".", "activeFreq", "=", "np", ".", "nonzero", "(", "self", ".", "isActiveFreq", ")", "[", "0", "]" ]
https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/physics/em/fdem.py#L351-L355
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/contrib/layers/python/layers/target_column.py
python
_TargetColumn.get_eval_ops
(self, features, logits, targets, metrics=None)
Returns eval op.
Returns eval op.
[ "Returns", "eval", "op", "." ]
def get_eval_ops(self, features, logits, targets, metrics=None): """Returns eval op.""" raise NotImplementedError
[ "def", "get_eval_ops", "(", "self", ",", "features", ",", "logits", ",", "targets", ",", "metrics", "=", "None", ")", ":", "raise", "NotImplementedError" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/layers/python/layers/target_column.py#L142-L144
physercoe/starquant
c00cad64d1de2da05081b3dc320ef264c6295e08
source/gui/ui_strategy_window.py
python
CtaManager.load_strategy_class_from_folder
(self, path: Path, module_name: str = "", reload: bool = False)
Load strategy class from certain folder.
Load strategy class from certain folder.
[ "Load", "strategy", "class", "from", "certain", "folder", "." ]
def load_strategy_class_from_folder(self, path: Path, module_name: str = "", reload: bool = False): """ Load strategy class from certain folder. """ for dirpath, dirnames, filenames in os.walk(path): for filename in filenames: if filename.endswith(".py"): strategy_module_name = "mystrategy.".join( [module_name, filename.replace(".py", "")]) self.load_strategy_class_from_module( strategy_module_name, reload)
[ "def", "load_strategy_class_from_folder", "(", "self", ",", "path", ":", "Path", ",", "module_name", ":", "str", "=", "\"\"", ",", "reload", ":", "bool", "=", "False", ")", ":", "for", "dirpath", ",", "dirnames", ",", "filenames", "in", "os", ".", "walk", "(", "path", ")", ":", "for", "filename", "in", "filenames", ":", "if", "filename", ".", "endswith", "(", "\".py\"", ")", ":", "strategy_module_name", "=", "\"mystrategy.\"", ".", "join", "(", "[", "module_name", ",", "filename", ".", "replace", "(", "\".py\"", ",", "\"\"", ")", "]", ")", "self", ".", "load_strategy_class_from_module", "(", "strategy_module_name", ",", "reload", ")" ]
https://github.com/physercoe/starquant/blob/c00cad64d1de2da05081b3dc320ef264c6295e08/source/gui/ui_strategy_window.py#L59-L69
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pathlib2/pathlib2/__init__.py
python
Path.is_block_device
(self)
Whether this path is a block device.
Whether this path is a block device.
[ "Whether", "this", "path", "is", "a", "block", "device", "." ]
def is_block_device(self): """ Whether this path is a block device. """ try: return S_ISBLK(self.stat().st_mode) except OSError as e: if not _ignore_error(e): raise # Path doesn't exist or is a broken symlink # (see https://bitbucket.org/pitrou/pathlib/issue/12/) return False except ValueError: # Non-encodable path return False
[ "def", "is_block_device", "(", "self", ")", ":", "try", ":", "return", "S_ISBLK", "(", "self", ".", "stat", "(", ")", ".", "st_mode", ")", "except", "OSError", "as", "e", ":", "if", "not", "_ignore_error", "(", "e", ")", ":", "raise", "# Path doesn't exist or is a broken symlink", "# (see https://bitbucket.org/pitrou/pathlib/issue/12/)", "return", "False", "except", "ValueError", ":", "# Non-encodable path", "return", "False" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pathlib2/pathlib2/__init__.py#L1721-L1735
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/extern/aui/auibar.py
python
AuiToolBar.SetToolTextOrientation
(self, orientation)
Sets the label orientation for the toolbar items. :param integer `orientation`: the :class:`AuiToolBarItem` label orientation.
Sets the label orientation for the toolbar items.
[ "Sets", "the", "label", "orientation", "for", "the", "toolbar", "items", "." ]
def SetToolTextOrientation(self, orientation): """ Sets the label orientation for the toolbar items. :param integer `orientation`: the :class:`AuiToolBarItem` label orientation. """ self._tool_text_orientation = orientation if self._art: self._art.SetTextOrientation(orientation)
[ "def", "SetToolTextOrientation", "(", "self", ",", "orientation", ")", ":", "self", ".", "_tool_text_orientation", "=", "orientation", "if", "self", ".", "_art", ":", "self", ".", "_art", ".", "SetTextOrientation", "(", "orientation", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/auibar.py#L2367-L2377
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/propgrid.py
python
PropertyGridPopulator.SetState
(*args, **kwargs)
return _propgrid.PropertyGridPopulator_SetState(*args, **kwargs)
SetState(self, state)
SetState(self, state)
[ "SetState", "(", "self", "state", ")" ]
def SetState(*args, **kwargs): """SetState(self, state)""" return _propgrid.PropertyGridPopulator_SetState(*args, **kwargs)
[ "def", "SetState", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PropertyGridPopulator_SetState", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L2577-L2579
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/contrib/learn/python/learn/learn_io/data_feeder.py
python
setup_processor_data_feeder
(x)
return x
Sets up processor iterable. Args: x: numpy, pandas or iterable. Returns: Iterable of data to process.
Sets up processor iterable.
[ "Sets", "up", "processor", "iterable", "." ]
def setup_processor_data_feeder(x): """Sets up processor iterable. Args: x: numpy, pandas or iterable. Returns: Iterable of data to process. """ if HAS_PANDAS: x = extract_pandas_matrix(x) return x
[ "def", "setup_processor_data_feeder", "(", "x", ")", ":", "if", "HAS_PANDAS", ":", "x", "=", "extract_pandas_matrix", "(", "x", ")", "return", "x" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/learn/python/learn/learn_io/data_feeder.py#L162-L173
arangodb/arangodb
0d658689c7d1b721b314fa3ca27d38303e1570c8
3rdParty/V8/gyp/generator/cmake.py
python
RemovePrefix
(a, prefix)
return a[len(prefix):] if a.startswith(prefix) else a
Returns 'a' without 'prefix' if it starts with 'prefix'.
Returns 'a' without 'prefix' if it starts with 'prefix'.
[ "Returns", "a", "without", "prefix", "if", "it", "starts", "with", "prefix", "." ]
def RemovePrefix(a, prefix): """Returns 'a' without 'prefix' if it starts with 'prefix'.""" return a[len(prefix):] if a.startswith(prefix) else a
[ "def", "RemovePrefix", "(", "a", ",", "prefix", ")", ":", "return", "a", "[", "len", "(", "prefix", ")", ":", "]", "if", "a", ".", "startswith", "(", "prefix", ")", "else", "a" ]
https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/gyp/generator/cmake.py#L80-L82
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/pydoc.py
python
TextDoc.docmodule
(self, object, name=None, mod=None)
return result
Produce text documentation for a given module object.
Produce text documentation for a given module object.
[ "Produce", "text", "documentation", "for", "a", "given", "module", "object", "." ]
def docmodule(self, object, name=None, mod=None): """Produce text documentation for a given module object.""" name = object.__name__ # ignore the passed-in name synop, desc = splitdoc(getdoc(object)) result = self.section('NAME', name + (synop and ' - ' + synop)) all = getattr(object, '__all__', None) docloc = self.getdocloc(object) if docloc is not None: result = result + self.section('MODULE REFERENCE', docloc + """ The following documentation is automatically generated from the Python source files. It may be incomplete, incorrect or include features that are considered implementation detail and may vary between Python implementations. When in doubt, consult the module reference at the location listed above. """) if desc: result = result + self.section('DESCRIPTION', desc) classes = [] for key, value in inspect.getmembers(object, inspect.isclass): # if __all__ exists, believe it. Otherwise use old heuristic. if (all is not None or (inspect.getmodule(value) or object) is object): if visiblename(key, all, object): classes.append((key, value)) funcs = [] for key, value in inspect.getmembers(object, inspect.isroutine): # if __all__ exists, believe it. Otherwise use old heuristic. if (all is not None or inspect.isbuiltin(value) or inspect.getmodule(value) is object): if visiblename(key, all, object): funcs.append((key, value)) data = [] for key, value in inspect.getmembers(object, isdata): if visiblename(key, all, object): data.append((key, value)) modpkgs = [] modpkgs_names = set() if hasattr(object, '__path__'): for importer, modname, ispkg in pkgutil.iter_modules(object.__path__): modpkgs_names.add(modname) if ispkg: modpkgs.append(modname + ' (package)') else: modpkgs.append(modname) modpkgs.sort() result = result + self.section( 'PACKAGE CONTENTS', '\n'.join(modpkgs)) # Detect submodules as sometimes created by C extensions submodules = [] for key, value in inspect.getmembers(object, inspect.ismodule): if value.__name__.startswith(name + '.') and key not in modpkgs_names: submodules.append(key) if submodules: submodules.sort() result = result + self.section( 'SUBMODULES', '\n'.join(submodules)) if classes: classlist = [value for key, value in classes] contents = [self.formattree( inspect.getclasstree(classlist, 1), name)] for key, value in classes: contents.append(self.document(value, key, name)) result = result + self.section('CLASSES', '\n'.join(contents)) if funcs: contents = [] for key, value in funcs: contents.append(self.document(value, key, name)) result = result + self.section('FUNCTIONS', '\n'.join(contents)) if data: contents = [] for key, value in data: contents.append(self.docother(value, key, name, maxlen=70)) result = result + self.section('DATA', '\n'.join(contents)) if hasattr(object, '__version__'): version = str(object.__version__) if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': version = version[11:-1].strip() result = result + self.section('VERSION', version) if hasattr(object, '__date__'): result = result + self.section('DATE', str(object.__date__)) if hasattr(object, '__author__'): result = result + self.section('AUTHOR', str(object.__author__)) if hasattr(object, '__credits__'): result = result + self.section('CREDITS', str(object.__credits__)) try: file = inspect.getabsfile(object) except TypeError: file = '(built-in)' result = result + self.section('FILE', file) return result
[ "def", "docmodule", "(", "self", ",", "object", ",", "name", "=", "None", ",", "mod", "=", "None", ")", ":", "name", "=", "object", ".", "__name__", "# ignore the passed-in name", "synop", ",", "desc", "=", "splitdoc", "(", "getdoc", "(", "object", ")", ")", "result", "=", "self", ".", "section", "(", "'NAME'", ",", "name", "+", "(", "synop", "and", "' - '", "+", "synop", ")", ")", "all", "=", "getattr", "(", "object", ",", "'__all__'", ",", "None", ")", "docloc", "=", "self", ".", "getdocloc", "(", "object", ")", "if", "docloc", "is", "not", "None", ":", "result", "=", "result", "+", "self", ".", "section", "(", "'MODULE REFERENCE'", ",", "docloc", "+", "\"\"\"\n\nThe following documentation is automatically generated from the Python\nsource files. It may be incomplete, incorrect or include features that\nare considered implementation detail and may vary between Python\nimplementations. When in doubt, consult the module reference at the\nlocation listed above.\n\"\"\"", ")", "if", "desc", ":", "result", "=", "result", "+", "self", ".", "section", "(", "'DESCRIPTION'", ",", "desc", ")", "classes", "=", "[", "]", "for", "key", ",", "value", "in", "inspect", ".", "getmembers", "(", "object", ",", "inspect", ".", "isclass", ")", ":", "# if __all__ exists, believe it. Otherwise use old heuristic.", "if", "(", "all", "is", "not", "None", "or", "(", "inspect", ".", "getmodule", "(", "value", ")", "or", "object", ")", "is", "object", ")", ":", "if", "visiblename", "(", "key", ",", "all", ",", "object", ")", ":", "classes", ".", "append", "(", "(", "key", ",", "value", ")", ")", "funcs", "=", "[", "]", "for", "key", ",", "value", "in", "inspect", ".", "getmembers", "(", "object", ",", "inspect", ".", "isroutine", ")", ":", "# if __all__ exists, believe it. Otherwise use old heuristic.", "if", "(", "all", "is", "not", "None", "or", "inspect", ".", "isbuiltin", "(", "value", ")", "or", "inspect", ".", "getmodule", "(", "value", ")", "is", "object", ")", ":", "if", "visiblename", "(", "key", ",", "all", ",", "object", ")", ":", "funcs", ".", "append", "(", "(", "key", ",", "value", ")", ")", "data", "=", "[", "]", "for", "key", ",", "value", "in", "inspect", ".", "getmembers", "(", "object", ",", "isdata", ")", ":", "if", "visiblename", "(", "key", ",", "all", ",", "object", ")", ":", "data", ".", "append", "(", "(", "key", ",", "value", ")", ")", "modpkgs", "=", "[", "]", "modpkgs_names", "=", "set", "(", ")", "if", "hasattr", "(", "object", ",", "'__path__'", ")", ":", "for", "importer", ",", "modname", ",", "ispkg", "in", "pkgutil", ".", "iter_modules", "(", "object", ".", "__path__", ")", ":", "modpkgs_names", ".", "add", "(", "modname", ")", "if", "ispkg", ":", "modpkgs", ".", "append", "(", "modname", "+", "' (package)'", ")", "else", ":", "modpkgs", ".", "append", "(", "modname", ")", "modpkgs", ".", "sort", "(", ")", "result", "=", "result", "+", "self", ".", "section", "(", "'PACKAGE CONTENTS'", ",", "'\\n'", ".", "join", "(", "modpkgs", ")", ")", "# Detect submodules as sometimes created by C extensions", "submodules", "=", "[", "]", "for", "key", ",", "value", "in", "inspect", ".", "getmembers", "(", "object", ",", "inspect", ".", "ismodule", ")", ":", "if", "value", ".", "__name__", ".", "startswith", "(", "name", "+", "'.'", ")", "and", "key", "not", "in", "modpkgs_names", ":", "submodules", ".", "append", "(", "key", ")", "if", "submodules", ":", "submodules", ".", "sort", "(", ")", "result", "=", "result", "+", "self", ".", "section", "(", "'SUBMODULES'", ",", "'\\n'", ".", "join", "(", "submodules", ")", ")", "if", "classes", ":", "classlist", "=", "[", "value", "for", "key", ",", "value", "in", "classes", "]", "contents", "=", "[", "self", ".", "formattree", "(", "inspect", ".", "getclasstree", "(", "classlist", ",", "1", ")", ",", "name", ")", "]", "for", "key", ",", "value", "in", "classes", ":", "contents", ".", "append", "(", "self", ".", "document", "(", "value", ",", "key", ",", "name", ")", ")", "result", "=", "result", "+", "self", ".", "section", "(", "'CLASSES'", ",", "'\\n'", ".", "join", "(", "contents", ")", ")", "if", "funcs", ":", "contents", "=", "[", "]", "for", "key", ",", "value", "in", "funcs", ":", "contents", ".", "append", "(", "self", ".", "document", "(", "value", ",", "key", ",", "name", ")", ")", "result", "=", "result", "+", "self", ".", "section", "(", "'FUNCTIONS'", ",", "'\\n'", ".", "join", "(", "contents", ")", ")", "if", "data", ":", "contents", "=", "[", "]", "for", "key", ",", "value", "in", "data", ":", "contents", ".", "append", "(", "self", ".", "docother", "(", "value", ",", "key", ",", "name", ",", "maxlen", "=", "70", ")", ")", "result", "=", "result", "+", "self", ".", "section", "(", "'DATA'", ",", "'\\n'", ".", "join", "(", "contents", ")", ")", "if", "hasattr", "(", "object", ",", "'__version__'", ")", ":", "version", "=", "str", "(", "object", ".", "__version__", ")", "if", "version", "[", ":", "11", "]", "==", "'$'", "+", "'Revision: '", "and", "version", "[", "-", "1", ":", "]", "==", "'$'", ":", "version", "=", "version", "[", "11", ":", "-", "1", "]", ".", "strip", "(", ")", "result", "=", "result", "+", "self", ".", "section", "(", "'VERSION'", ",", "version", ")", "if", "hasattr", "(", "object", ",", "'__date__'", ")", ":", "result", "=", "result", "+", "self", ".", "section", "(", "'DATE'", ",", "str", "(", "object", ".", "__date__", ")", ")", "if", "hasattr", "(", "object", ",", "'__author__'", ")", ":", "result", "=", "result", "+", "self", ".", "section", "(", "'AUTHOR'", ",", "str", "(", "object", ".", "__author__", ")", ")", "if", "hasattr", "(", "object", ",", "'__credits__'", ")", ":", "result", "=", "result", "+", "self", ".", "section", "(", "'CREDITS'", ",", "str", "(", "object", ".", "__credits__", ")", ")", "try", ":", "file", "=", "inspect", ".", "getabsfile", "(", "object", ")", "except", "TypeError", ":", "file", "=", "'(built-in)'", "result", "=", "result", "+", "self", ".", "section", "(", "'FILE'", ",", "file", ")", "return", "result" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/pydoc.py#L1199-L1298
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_misc.py
python
TimeSpan.Second
(*args, **kwargs)
return _misc_.TimeSpan_Second(*args, **kwargs)
Second() -> TimeSpan
Second() -> TimeSpan
[ "Second", "()", "-", ">", "TimeSpan" ]
def Second(*args, **kwargs): """Second() -> TimeSpan""" return _misc_.TimeSpan_Second(*args, **kwargs)
[ "def", "Second", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "TimeSpan_Second", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L4364-L4366
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/python/turicreate/data_structures/sarray.py
python
SArray.head
(self, n=10)
return SArray(_proxy=self.__proxy__.head(n))
Returns an SArray which contains the first n rows of this SArray. Parameters ---------- n : int The number of rows to fetch. Returns ------- out : SArray A new SArray which contains the first n rows of the current SArray. Examples -------- >>> tc.SArray(range(10)).head(5) dtype: int Rows: 5 [0, 1, 2, 3, 4]
Returns an SArray which contains the first n rows of this SArray.
[ "Returns", "an", "SArray", "which", "contains", "the", "first", "n", "rows", "of", "this", "SArray", "." ]
def head(self, n=10): """ Returns an SArray which contains the first n rows of this SArray. Parameters ---------- n : int The number of rows to fetch. Returns ------- out : SArray A new SArray which contains the first n rows of the current SArray. Examples -------- >>> tc.SArray(range(10)).head(5) dtype: int Rows: 5 [0, 1, 2, 3, 4] """ return SArray(_proxy=self.__proxy__.head(n))
[ "def", "head", "(", "self", ",", "n", "=", "10", ")", ":", "return", "SArray", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "head", "(", "n", ")", ")" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/data_structures/sarray.py#L1471-L1492
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/combo.py
python
ComboPopup.OnComboCharEvent
(*args, **kwargs)
return _combo.ComboPopup_OnComboCharEvent(*args, **kwargs)
OnComboCharEvent(self, KeyEvent event)
OnComboCharEvent(self, KeyEvent event)
[ "OnComboCharEvent", "(", "self", "KeyEvent", "event", ")" ]
def OnComboCharEvent(*args, **kwargs): """OnComboCharEvent(self, KeyEvent event)""" return _combo.ComboPopup_OnComboCharEvent(*args, **kwargs)
[ "def", "OnComboCharEvent", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_combo", ".", "ComboPopup_OnComboCharEvent", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/combo.py#L708-L710
google/syzygy
8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5
third_party/numpy/files/numpy/polynomial/polynomial.py
python
polyval
(x, cs)
return c0
Evaluate a polynomial. If `cs` is of length `n`, this function returns : ``p(x) = cs[0] + cs[1]*x + ... + cs[n-1]*x**(n-1)`` If x is a sequence or array then p(x) will have the same shape as x. If r is a ring_like object that supports multiplication and addition by the values in `cs`, then an object of the same type is returned. Parameters ---------- x : array_like, ring_like If x is a list or tuple, it is converted to an ndarray. Otherwise it must support addition and multiplication with itself and the elements of `cs`. cs : array_like 1-d array of Chebyshev coefficients ordered from low to high. Returns ------- values : ndarray The return array has the same shape as `x`. See Also -------- polyfit Notes ----- The evaluation uses Horner's method.
Evaluate a polynomial.
[ "Evaluate", "a", "polynomial", "." ]
def polyval(x, cs): """ Evaluate a polynomial. If `cs` is of length `n`, this function returns : ``p(x) = cs[0] + cs[1]*x + ... + cs[n-1]*x**(n-1)`` If x is a sequence or array then p(x) will have the same shape as x. If r is a ring_like object that supports multiplication and addition by the values in `cs`, then an object of the same type is returned. Parameters ---------- x : array_like, ring_like If x is a list or tuple, it is converted to an ndarray. Otherwise it must support addition and multiplication with itself and the elements of `cs`. cs : array_like 1-d array of Chebyshev coefficients ordered from low to high. Returns ------- values : ndarray The return array has the same shape as `x`. See Also -------- polyfit Notes ----- The evaluation uses Horner's method. """ # cs is a trimmed copy [cs] = pu.as_series([cs]) if isinstance(x, tuple) or isinstance(x, list) : x = np.asarray(x) c0 = cs[-1] + x*0 for i in range(2, len(cs) + 1) : c0 = cs[-i] + c0*x return c0
[ "def", "polyval", "(", "x", ",", "cs", ")", ":", "# cs is a trimmed copy", "[", "cs", "]", "=", "pu", ".", "as_series", "(", "[", "cs", "]", ")", "if", "isinstance", "(", "x", ",", "tuple", ")", "or", "isinstance", "(", "x", ",", "list", ")", ":", "x", "=", "np", ".", "asarray", "(", "x", ")", "c0", "=", "cs", "[", "-", "1", "]", "+", "x", "*", "0", "for", "i", "in", "range", "(", "2", ",", "len", "(", "cs", ")", "+", "1", ")", ":", "c0", "=", "cs", "[", "-", "i", "]", "+", "c0", "*", "x", "return", "c0" ]
https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/polynomial/polynomial.py#L612-L655
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/ops/data_flow_ops.py
python
SparseConditionalAccumulator.take_grad
(self, num_required, name=None)
return gen_data_flow_ops.sparse_accumulator_take_gradient( self._accumulator_ref, num_required, dtype=self._dtype, name=name)
Attempts to extract the average gradient from the accumulator. The operation blocks until sufficient number of gradients have been successfully applied to the accumulator. Once successful, the following actions are also triggered: - Counter of accumulated gradients is reset to 0. - Aggregated gradient is reset to 0 tensor. - Accumulator's internal time step is incremented by 1. Args: num_required: Number of gradients that needs to have been aggregated name: Optional name for the operation Returns: A tuple of indices, values, and shape representing the average gradient. Raises: InvalidArgumentError: If num_required < 1
Attempts to extract the average gradient from the accumulator.
[ "Attempts", "to", "extract", "the", "average", "gradient", "from", "the", "accumulator", "." ]
def take_grad(self, num_required, name=None): """Attempts to extract the average gradient from the accumulator. The operation blocks until sufficient number of gradients have been successfully applied to the accumulator. Once successful, the following actions are also triggered: - Counter of accumulated gradients is reset to 0. - Aggregated gradient is reset to 0 tensor. - Accumulator's internal time step is incremented by 1. Args: num_required: Number of gradients that needs to have been aggregated name: Optional name for the operation Returns: A tuple of indices, values, and shape representing the average gradient. Raises: InvalidArgumentError: If num_required < 1 """ return gen_data_flow_ops.sparse_accumulator_take_gradient( self._accumulator_ref, num_required, dtype=self._dtype, name=name)
[ "def", "take_grad", "(", "self", ",", "num_required", ",", "name", "=", "None", ")", ":", "return", "gen_data_flow_ops", ".", "sparse_accumulator_take_gradient", "(", "self", ".", "_accumulator_ref", ",", "num_required", ",", "dtype", "=", "self", ".", "_dtype", ",", "name", "=", "name", ")" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/ops/data_flow_ops.py#L1402-L1424
cksystemsgroup/scal
fa2208a97a77d65f4e90f85fef3404c27c1f2ac2
tools/cpplint.py
python
Search
(pattern, s)
return _regexp_compile_cache[pattern].search(s)
Searches the string for the pattern, caching the compiled regexp.
Searches the string for the pattern, caching the compiled regexp.
[ "Searches", "the", "string", "for", "the", "pattern", "caching", "the", "compiled", "regexp", "." ]
def Search(pattern, s): """Searches the string for the pattern, caching the compiled regexp.""" if pattern not in _regexp_compile_cache: _regexp_compile_cache[pattern] = sre_compile.compile(pattern) return _regexp_compile_cache[pattern].search(s)
[ "def", "Search", "(", "pattern", ",", "s", ")", ":", "if", "pattern", "not", "in", "_regexp_compile_cache", ":", "_regexp_compile_cache", "[", "pattern", "]", "=", "sre_compile", ".", "compile", "(", "pattern", ")", "return", "_regexp_compile_cache", "[", "pattern", "]", ".", "search", "(", "s", ")" ]
https://github.com/cksystemsgroup/scal/blob/fa2208a97a77d65f4e90f85fef3404c27c1f2ac2/tools/cpplint.py#L585-L589
openweave/openweave-core
11ceb6b7efd39fe05de7f79229247a5774d56766
src/device-manager/python/openweave/WeaveCoreBluetoothMgr.py
python
CoreBluetoothManager.peripheral_didDiscoverServices_
(self, peripheral, services)
Called by CoreBluetooth via runloop when peripheral services are discovered.
Called by CoreBluetooth via runloop when peripheral services are discovered.
[ "Called", "by", "CoreBluetooth", "via", "runloop", "when", "peripheral", "services", "are", "discovered", "." ]
def peripheral_didDiscoverServices_(self, peripheral, services): """Called by CoreBluetooth via runloop when peripheral services are discovered.""" if len(self.peripheral.services()) == 0: self.logger.error("Weave service not found") self.connect_state = False else: # in debugging, we found connect being called twice. This # would trigger discovering the services twice, and # consequently, discovering characteristics twice. We use the # self.service as a flag to indicate whether the # characteristics need to be invalidated immediately. if (self.service == self.peripheral.services()[0]): self.logger.debug("didDiscoverServices already happened") else: self.service = self.peripheral.services()[0] self.characteristics[self.service.UUID()] = [] # NOTE: currently limiting discovery to only the pair of Weave characteristics. self.peripheral.discoverCharacteristics_forService_([weave_rx, weave_tx], self.service)
[ "def", "peripheral_didDiscoverServices_", "(", "self", ",", "peripheral", ",", "services", ")", ":", "if", "len", "(", "self", ".", "peripheral", ".", "services", "(", ")", ")", "==", "0", ":", "self", ".", "logger", ".", "error", "(", "\"Weave service not found\"", ")", "self", ".", "connect_state", "=", "False", "else", ":", "# in debugging, we found connect being called twice. This", "# would trigger discovering the services twice, and", "# consequently, discovering characteristics twice. We use the", "# self.service as a flag to indicate whether the", "# characteristics need to be invalidated immediately.", "if", "(", "self", ".", "service", "==", "self", ".", "peripheral", ".", "services", "(", ")", "[", "0", "]", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"didDiscoverServices already happened\"", ")", "else", ":", "self", ".", "service", "=", "self", ".", "peripheral", ".", "services", "(", ")", "[", "0", "]", "self", ".", "characteristics", "[", "self", ".", "service", ".", "UUID", "(", ")", "]", "=", "[", "]", "# NOTE: currently limiting discovery to only the pair of Weave characteristics.", "self", ".", "peripheral", ".", "discoverCharacteristics_forService_", "(", "[", "weave_rx", ",", "weave_tx", "]", ",", "self", ".", "service", ")" ]
https://github.com/openweave/openweave-core/blob/11ceb6b7efd39fe05de7f79229247a5774d56766/src/device-manager/python/openweave/WeaveCoreBluetoothMgr.py#L271-L288
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/distributed/fleet/meta_optimizers/dygraph_optimizer/sharding_optimizer_stage2.py
python
ShardingOptimizerStage2.step
(self)
A wrapper for Optimizer's step function to finish the update operation of the optimizer.
A wrapper for Optimizer's step function to finish the update operation of the optimizer.
[ "A", "wrapper", "for", "Optimizer", "s", "step", "function", "to", "finish", "the", "update", "operation", "of", "the", "optimizer", "." ]
def step(self): """ A wrapper for Optimizer's step function to finish the update operation of the optimizer. """ if self.offload: params_list = [self.offload_params.buffer] #TODO(Baibaifan): Offload will support param_groups later if not isinstance(self._optim._param_groups[0], dict): self._optim._parameter_list = params_list self._optim._param_groups = params_list # Run the optimizer of the current rank step if self.offload: with device_guard(device=self.offload_device): self._optim.step() dev_id = int(paddle.get_device().split(":")[1]) for param in self._local_params: if param.name in self._master_params.keys(): param.set_value(self._master_params[param.name].cuda(dev_id) .cast(dtype=param.dtype)) else: self._optim.step() # Synchronize all the updated shards in between the ranks self._broadcast_params()
[ "def", "step", "(", "self", ")", ":", "if", "self", ".", "offload", ":", "params_list", "=", "[", "self", ".", "offload_params", ".", "buffer", "]", "#TODO(Baibaifan): Offload will support param_groups later", "if", "not", "isinstance", "(", "self", ".", "_optim", ".", "_param_groups", "[", "0", "]", ",", "dict", ")", ":", "self", ".", "_optim", ".", "_parameter_list", "=", "params_list", "self", ".", "_optim", ".", "_param_groups", "=", "params_list", "# Run the optimizer of the current rank step", "if", "self", ".", "offload", ":", "with", "device_guard", "(", "device", "=", "self", ".", "offload_device", ")", ":", "self", ".", "_optim", ".", "step", "(", ")", "dev_id", "=", "int", "(", "paddle", ".", "get_device", "(", ")", ".", "split", "(", "\":\"", ")", "[", "1", "]", ")", "for", "param", "in", "self", ".", "_local_params", ":", "if", "param", ".", "name", "in", "self", ".", "_master_params", ".", "keys", "(", ")", ":", "param", ".", "set_value", "(", "self", ".", "_master_params", "[", "param", ".", "name", "]", ".", "cuda", "(", "dev_id", ")", ".", "cast", "(", "dtype", "=", "param", ".", "dtype", ")", ")", "else", ":", "self", ".", "_optim", ".", "step", "(", ")", "# Synchronize all the updated shards in between the ranks", "self", ".", "_broadcast_params", "(", ")" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/distributed/fleet/meta_optimizers/dygraph_optimizer/sharding_optimizer_stage2.py#L337-L364
ycm-core/ycmd
fc0fb7e5e15176cc5a2a30c80956335988c6b59a
ycmd/completers/language_server/language_server_protocol.py
python
ServerFileState.GetDirtyFileAction
( self, contents )
return self._SendNewVersion( new_checksum, action, contents )
Progress the state for a file to be updated due to being supplied in the dirty buffers list. Returns any one of the Actions to perform.
Progress the state for a file to be updated due to being supplied in the dirty buffers list. Returns any one of the Actions to perform.
[ "Progress", "the", "state", "for", "a", "file", "to", "be", "updated", "due", "to", "being", "supplied", "in", "the", "dirty", "buffers", "list", ".", "Returns", "any", "one", "of", "the", "Actions", "to", "perform", "." ]
def GetDirtyFileAction( self, contents ): """Progress the state for a file to be updated due to being supplied in the dirty buffers list. Returns any one of the Actions to perform.""" new_checksum = self._CalculateCheckSum( contents ) if ( self.state == ServerFileState.OPEN and self.checksum.digest() == new_checksum.digest() ): return ServerFileState.NO_ACTION elif self.state == ServerFileState.CLOSED: self.version = 0 action = ServerFileState.OPEN_FILE else: action = ServerFileState.CHANGE_FILE return self._SendNewVersion( new_checksum, action, contents )
[ "def", "GetDirtyFileAction", "(", "self", ",", "contents", ")", ":", "new_checksum", "=", "self", ".", "_CalculateCheckSum", "(", "contents", ")", "if", "(", "self", ".", "state", "==", "ServerFileState", ".", "OPEN", "and", "self", ".", "checksum", ".", "digest", "(", ")", "==", "new_checksum", ".", "digest", "(", ")", ")", ":", "return", "ServerFileState", ".", "NO_ACTION", "elif", "self", ".", "state", "==", "ServerFileState", ".", "CLOSED", ":", "self", ".", "version", "=", "0", "action", "=", "ServerFileState", ".", "OPEN_FILE", "else", ":", "action", "=", "ServerFileState", ".", "CHANGE_FILE", "return", "self", ".", "_SendNewVersion", "(", "new_checksum", ",", "action", ",", "contents", ")" ]
https://github.com/ycm-core/ycmd/blob/fc0fb7e5e15176cc5a2a30c80956335988c6b59a/ycmd/completers/language_server/language_server_protocol.py#L178-L192
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/tools/gyp/pylib/gyp/xcode_emulation.py
python
XcodeSettings.GetWrapperExtension
(self)
Returns the bundle extension (.app, .framework, .plugin, etc). Only valid for bundles.
Returns the bundle extension (.app, .framework, .plugin, etc). Only valid for bundles.
[ "Returns", "the", "bundle", "extension", "(", ".", "app", ".", "framework", ".", "plugin", "etc", ")", ".", "Only", "valid", "for", "bundles", "." ]
def GetWrapperExtension(self): """Returns the bundle extension (.app, .framework, .plugin, etc). Only valid for bundles.""" assert self._IsBundle() if self.spec['type'] in ('loadable_module', 'shared_library'): default_wrapper_extension = { 'loadable_module': 'bundle', 'shared_library': 'framework', }[self.spec['type']] wrapper_extension = self.GetPerTargetSetting( 'WRAPPER_EXTENSION', default=default_wrapper_extension) return '.' + self.spec.get('product_extension', wrapper_extension) elif self.spec['type'] == 'executable': if self._IsIosAppExtension() or self._IsIosWatchKitExtension(): return '.' + self.spec.get('product_extension', 'appex') else: return '.' + self.spec.get('product_extension', 'app') else: assert False, "Don't know extension for '%s', target '%s'" % ( self.spec['type'], self.spec['target_name'])
[ "def", "GetWrapperExtension", "(", "self", ")", ":", "assert", "self", ".", "_IsBundle", "(", ")", "if", "self", ".", "spec", "[", "'type'", "]", "in", "(", "'loadable_module'", ",", "'shared_library'", ")", ":", "default_wrapper_extension", "=", "{", "'loadable_module'", ":", "'bundle'", ",", "'shared_library'", ":", "'framework'", ",", "}", "[", "self", ".", "spec", "[", "'type'", "]", "]", "wrapper_extension", "=", "self", ".", "GetPerTargetSetting", "(", "'WRAPPER_EXTENSION'", ",", "default", "=", "default_wrapper_extension", ")", "return", "'.'", "+", "self", ".", "spec", ".", "get", "(", "'product_extension'", ",", "wrapper_extension", ")", "elif", "self", ".", "spec", "[", "'type'", "]", "==", "'executable'", ":", "if", "self", ".", "_IsIosAppExtension", "(", ")", "or", "self", ".", "_IsIosWatchKitExtension", "(", ")", ":", "return", "'.'", "+", "self", ".", "spec", ".", "get", "(", "'product_extension'", ",", "'appex'", ")", "else", ":", "return", "'.'", "+", "self", ".", "spec", ".", "get", "(", "'product_extension'", ",", "'app'", ")", "else", ":", "assert", "False", ",", "\"Don't know extension for '%s', target '%s'\"", "%", "(", "self", ".", "spec", "[", "'type'", "]", ",", "self", ".", "spec", "[", "'target_name'", "]", ")" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/gyp/pylib/gyp/xcode_emulation.py#L260-L279
crosslife/OpenBird
9e0198a1a2295f03fa1e8676e216e22c9c7d380b
cocos2d/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py
python
Type.get_size
(self)
return conf.lib.clang_Type_getSizeOf(self)
Retrieve the size of the record.
Retrieve the size of the record.
[ "Retrieve", "the", "size", "of", "the", "record", "." ]
def get_size(self): """ Retrieve the size of the record. """ return conf.lib.clang_Type_getSizeOf(self)
[ "def", "get_size", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_Type_getSizeOf", "(", "self", ")" ]
https://github.com/crosslife/OpenBird/blob/9e0198a1a2295f03fa1e8676e216e22c9c7d380b/cocos2d/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py#L1634-L1638
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
PyApp.ProcessPendingEvents
(*args, **kwargs)
return _core_.PyApp_ProcessPendingEvents(*args, **kwargs)
ProcessPendingEvents(self) Process all events in the Pending Events list -- it is necessary to call this function to process posted events. This normally happens during each event loop iteration.
ProcessPendingEvents(self)
[ "ProcessPendingEvents", "(", "self", ")" ]
def ProcessPendingEvents(*args, **kwargs): """ ProcessPendingEvents(self) Process all events in the Pending Events list -- it is necessary to call this function to process posted events. This normally happens during each event loop iteration. """ return _core_.PyApp_ProcessPendingEvents(*args, **kwargs)
[ "def", "ProcessPendingEvents", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "PyApp_ProcessPendingEvents", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L7858-L7866
avast/retdec
b9879088a5f0278508185ec645494e6c5c57a455
scripts/type_extractor/type_extractor/io.py
python
print_types_info_lti
(f_out, functions, types, structs, unions, enums, indent=0)
Lti output for types and functions.
Lti output for types and functions.
[ "Lti", "output", "for", "types", "and", "functions", "." ]
def print_types_info_lti(f_out, functions, types, structs, unions, enums, indent=0): """Lti output for types and functions.""" for sname, sinfo in sorted(structs.items()): lti = '%struct.' + sname + ' = type { ' lti = lti + ', '.join([str_types_sub(members.type_text, members.name_text) for members in sinfo.members_list]) lti = lti + ' }\n' f_out.write(lti) for fname, f_info in sorted(functions.items()): lti_1 = f_info.name_text+' '+str_types_sub(f_info.ret_type_text, '') lti_2 = ' ' + str(len(f_info.params_list)) + ' ' lti_3 = ', '.join([str_types_sub(param.type_text, param.name_text) for param in f_info.params_list]) lti_4 = ' # ' + f_info.decl lti = lti_1 + lti_2 + lti_3 + lti_4 f_out.write(lti + '\n')
[ "def", "print_types_info_lti", "(", "f_out", ",", "functions", ",", "types", ",", "structs", ",", "unions", ",", "enums", ",", "indent", "=", "0", ")", ":", "for", "sname", ",", "sinfo", "in", "sorted", "(", "structs", ".", "items", "(", ")", ")", ":", "lti", "=", "'%struct.'", "+", "sname", "+", "' = type { '", "lti", "=", "lti", "+", "', '", ".", "join", "(", "[", "str_types_sub", "(", "members", ".", "type_text", ",", "members", ".", "name_text", ")", "for", "members", "in", "sinfo", ".", "members_list", "]", ")", "lti", "=", "lti", "+", "' }\\n'", "f_out", ".", "write", "(", "lti", ")", "for", "fname", ",", "f_info", "in", "sorted", "(", "functions", ".", "items", "(", ")", ")", ":", "lti_1", "=", "f_info", ".", "name_text", "+", "' '", "+", "str_types_sub", "(", "f_info", ".", "ret_type_text", ",", "''", ")", "lti_2", "=", "' '", "+", "str", "(", "len", "(", "f_info", ".", "params_list", ")", ")", "+", "' '", "lti_3", "=", "', '", ".", "join", "(", "[", "str_types_sub", "(", "param", ".", "type_text", ",", "param", ".", "name_text", ")", "for", "param", "in", "f_info", ".", "params_list", "]", ")", "lti_4", "=", "' # '", "+", "f_info", ".", "decl", "lti", "=", "lti_1", "+", "lti_2", "+", "lti_3", "+", "lti_4", "f_out", ".", "write", "(", "lti", "+", "'\\n'", ")" ]
https://github.com/avast/retdec/blob/b9879088a5f0278508185ec645494e6c5c57a455/scripts/type_extractor/type_extractor/io.py#L95-L111
plumonito/dtslam
5994bb9cf7a11981b830370db206bceb654c085d
3rdparty/opencv-git/3rdparty/jinja2/parser.py
python
Parser.fail_unknown_tag
(self, name, lineno=None)
return self._fail_ut_eof(name, self._end_token_stack, lineno)
Called if the parser encounters an unknown tag. Tries to fail with a human readable error message that could help to identify the problem.
Called if the parser encounters an unknown tag. Tries to fail with a human readable error message that could help to identify the problem.
[ "Called", "if", "the", "parser", "encounters", "an", "unknown", "tag", ".", "Tries", "to", "fail", "with", "a", "human", "readable", "error", "message", "that", "could", "help", "to", "identify", "the", "problem", "." ]
def fail_unknown_tag(self, name, lineno=None): """Called if the parser encounters an unknown tag. Tries to fail with a human readable error message that could help to identify the problem. """ return self._fail_ut_eof(name, self._end_token_stack, lineno)
[ "def", "fail_unknown_tag", "(", "self", ",", "name", ",", "lineno", "=", "None", ")", ":", "return", "self", ".", "_fail_ut_eof", "(", "name", ",", "self", ".", "_end_token_stack", ",", "lineno", ")" ]
https://github.com/plumonito/dtslam/blob/5994bb9cf7a11981b830370db206bceb654c085d/3rdparty/opencv-git/3rdparty/jinja2/parser.py#L84-L89
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/urllib3/util/wait.py
python
_wait_for_io_events
(socks, events, timeout=None)
Waits for IO events to be available from a list of sockets or optionally a single socket if passed in. Returns a list of sockets that can be interacted with immediately.
Waits for IO events to be available from a list of sockets or optionally a single socket if passed in. Returns a list of sockets that can be interacted with immediately.
[ "Waits", "for", "IO", "events", "to", "be", "available", "from", "a", "list", "of", "sockets", "or", "optionally", "a", "single", "socket", "if", "passed", "in", ".", "Returns", "a", "list", "of", "sockets", "that", "can", "be", "interacted", "with", "immediately", "." ]
def _wait_for_io_events(socks, events, timeout=None): """ Waits for IO events to be available from a list of sockets or optionally a single socket if passed in. Returns a list of sockets that can be interacted with immediately. """ if not HAS_SELECT: raise ValueError('Platform does not have a selector') if not isinstance(socks, list): # Probably just a single socket. if hasattr(socks, "fileno"): socks = [socks] # Otherwise it might be a non-list iterable. else: socks = list(socks) with DefaultSelector() as selector: for sock in socks: selector.register(sock, events) return [key[0].fileobj for key in selector.select(timeout) if key[1] & events]
[ "def", "_wait_for_io_events", "(", "socks", ",", "events", ",", "timeout", "=", "None", ")", ":", "if", "not", "HAS_SELECT", ":", "raise", "ValueError", "(", "'Platform does not have a selector'", ")", "if", "not", "isinstance", "(", "socks", ",", "list", ")", ":", "# Probably just a single socket.", "if", "hasattr", "(", "socks", ",", "\"fileno\"", ")", ":", "socks", "=", "[", "socks", "]", "# Otherwise it might be a non-list iterable.", "else", ":", "socks", "=", "list", "(", "socks", ")", "with", "DefaultSelector", "(", ")", "as", "selector", ":", "for", "sock", "in", "socks", ":", "selector", ".", "register", "(", "sock", ",", "events", ")", "return", "[", "key", "[", "0", "]", ".", "fileobj", "for", "key", "in", "selector", ".", "select", "(", "timeout", ")", "if", "key", "[", "1", "]", "&", "events", "]" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/urllib3/util/wait.py#L9-L26
Samsung/veles
95ed733c2e49bc011ad98ccf2416ecec23fbf352
veles/result_provider.py
python
IResultProvider.get_metric_values
()
:return The measurable results of model's execution, e.g., accuracy, number of errors, RMSE, etc. Technically, they are a dictionary of metric names (as returned by get_metric_names()) and achieved values.
:return The measurable results of model's execution, e.g., accuracy, number of errors, RMSE, etc. Technically, they are a dictionary of metric names (as returned by get_metric_names()) and achieved values.
[ ":", "return", "The", "measurable", "results", "of", "model", "s", "execution", "e", ".", "g", ".", "accuracy", "number", "of", "errors", "RMSE", "etc", ".", "Technically", "they", "are", "a", "dictionary", "of", "metric", "names", "(", "as", "returned", "by", "get_metric_names", "()", ")", "and", "achieved", "values", "." ]
def get_metric_values(): """ :return The measurable results of model's execution, e.g., accuracy, number of errors, RMSE, etc. Technically, they are a dictionary of metric names (as returned by get_metric_names()) and achieved values. """
[ "def", "get_metric_values", "(", ")", ":" ]
https://github.com/Samsung/veles/blob/95ed733c2e49bc011ad98ccf2416ecec23fbf352/veles/result_provider.py#L48-L53
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/func_graph.py
python
FuncGraph.reset_captures
(self, capture_list)
Set the captures with the provided list of captures & placeholder.
Set the captures with the provided list of captures & placeholder.
[ "Set", "the", "captures", "with", "the", "provided", "list", "of", "captures", "&", "placeholder", "." ]
def reset_captures(self, capture_list): """Set the captures with the provided list of captures & placeholder.""" self._captures = py_collections.OrderedDict() for tensor, placeholder in capture_list: self._captures[ops.tensor_id(tensor)] = (tensor, placeholder)
[ "def", "reset_captures", "(", "self", ",", "capture_list", ")", ":", "self", ".", "_captures", "=", "py_collections", ".", "OrderedDict", "(", ")", "for", "tensor", ",", "placeholder", "in", "capture_list", ":", "self", ".", "_captures", "[", "ops", ".", "tensor_id", "(", "tensor", ")", "]", "=", "(", "tensor", ",", "placeholder", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/func_graph.py#L635-L639
openweave/openweave-core
11ceb6b7efd39fe05de7f79229247a5774d56766
src/device-manager/python/openweave/WeaveBleBase.py
python
WeaveBleBase.GetBleEvent
(self)
return
Called by WeaveDeviceMgr.py on behalf of Weave to retrieve a queued message.
Called by WeaveDeviceMgr.py on behalf of Weave to retrieve a queued message.
[ "Called", "by", "WeaveDeviceMgr", ".", "py", "on", "behalf", "of", "Weave", "to", "retrieve", "a", "queued", "message", "." ]
def GetBleEvent(self): """ Called by WeaveDeviceMgr.py on behalf of Weave to retrieve a queued message.""" return
[ "def", "GetBleEvent", "(", "self", ")", ":", "return" ]
https://github.com/openweave/openweave-core/blob/11ceb6b7efd39fe05de7f79229247a5774d56766/src/device-manager/python/openweave/WeaveBleBase.py#L67-L69
msitt/blpapi-python
bebcf43668c9e5f5467b1f685f9baebbfc45bc87
src/blpapi/name.py
python
Name.__str__
(self)
return internals.blpapi_Name_string(self.__handle)
x.__str__() <==> str(x) Return a string that this Name represents.
x.__str__() <==> str(x)
[ "x", ".", "__str__", "()", "<", "==", ">", "str", "(", "x", ")" ]
def __str__(self): """x.__str__() <==> str(x) Return a string that this Name represents. """ return internals.blpapi_Name_string(self.__handle)
[ "def", "__str__", "(", "self", ")", ":", "return", "internals", ".", "blpapi_Name_string", "(", "self", ".", "__handle", ")" ]
https://github.com/msitt/blpapi-python/blob/bebcf43668c9e5f5467b1f685f9baebbfc45bc87/src/blpapi/name.py#L94-L101
google/llvm-propeller
45c226984fe8377ebfb2ad7713c680d652ba678d
openmp/runtime/tools/summarizeStats.py
python
setRadarFigure
(titles)
return {'ax':ax, 'theta':theta}
Set the attributes for the radar plots
Set the attributes for the radar plots
[ "Set", "the", "attributes", "for", "the", "radar", "plots" ]
def setRadarFigure(titles): """Set the attributes for the radar plots""" fig = plt.figure(figsize=(9,9)) rect = [0.1, 0.1, 0.8, 0.8] labels = [0.2, 0.4, 0.6, 0.8, 1, 2, 3, 4, 5, 10] matplotlib.rcParams.update({'font.size':13}) theta = radar_factory(len(titles)) ax = fig.add_axes(rect, projection='radar') ax.set_rgrids(labels) ax.set_varlabels(titles) ax.text(theta[2], 1, "Linear->Log", horizontalalignment='center', color='green', fontsize=18) return {'ax':ax, 'theta':theta}
[ "def", "setRadarFigure", "(", "titles", ")", ":", "fig", "=", "plt", ".", "figure", "(", "figsize", "=", "(", "9", ",", "9", ")", ")", "rect", "=", "[", "0.1", ",", "0.1", ",", "0.8", ",", "0.8", "]", "labels", "=", "[", "0.2", ",", "0.4", ",", "0.6", ",", "0.8", ",", "1", ",", "2", ",", "3", ",", "4", ",", "5", ",", "10", "]", "matplotlib", ".", "rcParams", ".", "update", "(", "{", "'font.size'", ":", "13", "}", ")", "theta", "=", "radar_factory", "(", "len", "(", "titles", ")", ")", "ax", "=", "fig", ".", "add_axes", "(", "rect", ",", "projection", "=", "'radar'", ")", "ax", ".", "set_rgrids", "(", "labels", ")", "ax", ".", "set_varlabels", "(", "titles", ")", "ax", ".", "text", "(", "theta", "[", "2", "]", ",", "1", ",", "\"Linear->Log\"", ",", "horizontalalignment", "=", "'center'", ",", "color", "=", "'green'", ",", "fontsize", "=", "18", ")", "return", "{", "'ax'", ":", "ax", ",", "'theta'", ":", "theta", "}" ]
https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/openmp/runtime/tools/summarizeStats.py#L177-L188
arkenthera/electron-vibrancy
383153ef9ccb23a6c7517150d6bb0794dff3115e
scripts/cpplint.py
python
_BlockInfo.CheckBegin
(self, filename, clean_lines, linenum, error)
Run checks that applies to text up to the opening brace. This is mostly for checking the text after the class identifier and the "{", usually where the base class is specified. For other blocks, there isn't much to check, so we always pass. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Run checks that applies to text up to the opening brace.
[ "Run", "checks", "that", "applies", "to", "text", "up", "to", "the", "opening", "brace", "." ]
def CheckBegin(self, filename, clean_lines, linenum, error): """Run checks that applies to text up to the opening brace. This is mostly for checking the text after the class identifier and the "{", usually where the base class is specified. For other blocks, there isn't much to check, so we always pass. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ pass
[ "def", "CheckBegin", "(", "self", ",", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "pass" ]
https://github.com/arkenthera/electron-vibrancy/blob/383153ef9ccb23a6c7517150d6bb0794dff3115e/scripts/cpplint.py#L1778-L1791
google/syzygy
8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5
third_party/numpy/files/numpy/oldnumeric/ma.py
python
MaskedArray.__add__
(self, other)
return add(self, other)
Return add(self, other)
Return add(self, other)
[ "Return", "add", "(", "self", "other", ")" ]
def __add__(self, other): "Return add(self, other)" return add(self, other)
[ "def", "__add__", "(", "self", ",", "other", ")", ":", "return", "add", "(", "self", ",", "other", ")" ]
https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/oldnumeric/ma.py#L899-L901
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Draft/draftguitools/gui_polygons.py
python
Polygon.action
(self, arg)
Handle the 3D scene events. This is installed as an EventCallback in the Inventor view. Parameters ---------- arg: dict Dictionary with strings that indicates the type of event received from the 3D view.
Handle the 3D scene events.
[ "Handle", "the", "3D", "scene", "events", "." ]
def action(self, arg): """Handle the 3D scene events. This is installed as an EventCallback in the Inventor view. Parameters ---------- arg: dict Dictionary with strings that indicates the type of event received from the 3D view. """ import DraftGeomUtils if arg["Type"] == "SoKeyboardEvent": if arg["Key"] == "ESCAPE": self.finish() elif arg["Type"] == "SoLocation2Event": # mouse movement detection self.point, ctrlPoint, info = gui_tool_utils.getPoint(self, arg) # this is to make sure radius is what you see on screen if self.center and DraftVecUtils.dist(self.point, self.center) > 0: viewdelta = DraftVecUtils.project(self.point.sub(self.center), App.DraftWorkingPlane.axis) if not DraftVecUtils.isNull(viewdelta): self.point = self.point.add(viewdelta.negative()) if self.step == 0: # choose center if gui_tool_utils.hasMod(arg, gui_tool_utils.MODALT): if not self.altdown: self.altdown = True self.ui.switchUi(True) else: if self.altdown: self.altdown = False self.ui.switchUi(False) else: # choose radius if len(self.tangents) == 2: cir = DraftGeomUtils.circleFrom2tan1pt(self.tangents[0], self.tangents[1], self.point) _c = DraftGeomUtils.findClosestCircle(self.point, cir) self.center = _c.Center self.arctrack.setCenter(self.center) elif self.tangents and self.tanpoints: cir = DraftGeomUtils.circleFrom1tan2pt(self.tangents[0], self.tanpoints[0], self.point) _c = DraftGeomUtils.findClosestCircle(self.point, cir) self.center = _c.Center self.arctrack.setCenter(self.center) if gui_tool_utils.hasMod(arg, gui_tool_utils.MODALT): if not self.altdown: self.altdown = True snapped = self.view.getObjectInfo((arg["Position"][0], arg["Position"][1])) if snapped: ob = self.doc.getObject(snapped['Object']) num = int(snapped['Component'].lstrip('Edge')) - 1 ed = ob.Shape.Edges[num] if len(self.tangents) == 2: cir = DraftGeomUtils.circleFrom3tan(self.tangents[0], self.tangents[1], ed) cl = DraftGeomUtils.findClosestCircle(self.point, cir) self.center = cl.Center self.rad = cl.Radius self.arctrack.setCenter(self.center) else: self.rad = self.center.add(DraftGeomUtils.findDistance(self.center,ed).sub(self.center)).Length else: self.rad = DraftVecUtils.dist(self.point, self.center) else: if self.altdown: self.altdown = False self.rad = DraftVecUtils.dist(self.point, self.center) self.ui.setRadiusValue(self.rad, 'Length') self.arctrack.setRadius(self.rad) gui_tool_utils.redraw3DView() elif (arg["Type"] == "SoMouseButtonEvent" and arg["State"] == "DOWN" and arg["Button"] == "BUTTON1"): # mouse click if self.point: if self.step == 0: # choose center if (not self.node) and (not self.support): gui_tool_utils.getSupport(arg) (self.point, ctrlPoint, info) = gui_tool_utils.getPoint(self, arg) if gui_tool_utils.hasMod(arg, gui_tool_utils.MODALT): snapped = self.view.getObjectInfo((arg["Position"][0], arg["Position"][1])) if snapped: ob = self.doc.getObject(snapped['Object']) num = int(snapped['Component'].lstrip('Edge')) - 1 ed = ob.Shape.Edges[num] self.tangents.append(ed) if len(self.tangents) == 2: self.arctrack.on() self.ui.radiusUi() self.step = 1 _msg(translate("draft", "Pick radius")) else: if len(self.tangents) == 1: self.tanpoints.append(self.point) else: self.center = self.point self.node = [self.point] self.arctrack.setCenter(self.center) self.arctrack.on() self.ui.radiusUi() self.step = 1 _msg(translate("draft", "Pick radius")) if self.planetrack: self.planetrack.set(self.point) elif self.step == 1: # choose radius self.drawPolygon()
[ "def", "action", "(", "self", ",", "arg", ")", ":", "import", "DraftGeomUtils", "if", "arg", "[", "\"Type\"", "]", "==", "\"SoKeyboardEvent\"", ":", "if", "arg", "[", "\"Key\"", "]", "==", "\"ESCAPE\"", ":", "self", ".", "finish", "(", ")", "elif", "arg", "[", "\"Type\"", "]", "==", "\"SoLocation2Event\"", ":", "# mouse movement detection", "self", ".", "point", ",", "ctrlPoint", ",", "info", "=", "gui_tool_utils", ".", "getPoint", "(", "self", ",", "arg", ")", "# this is to make sure radius is what you see on screen", "if", "self", ".", "center", "and", "DraftVecUtils", ".", "dist", "(", "self", ".", "point", ",", "self", ".", "center", ")", ">", "0", ":", "viewdelta", "=", "DraftVecUtils", ".", "project", "(", "self", ".", "point", ".", "sub", "(", "self", ".", "center", ")", ",", "App", ".", "DraftWorkingPlane", ".", "axis", ")", "if", "not", "DraftVecUtils", ".", "isNull", "(", "viewdelta", ")", ":", "self", ".", "point", "=", "self", ".", "point", ".", "add", "(", "viewdelta", ".", "negative", "(", ")", ")", "if", "self", ".", "step", "==", "0", ":", "# choose center", "if", "gui_tool_utils", ".", "hasMod", "(", "arg", ",", "gui_tool_utils", ".", "MODALT", ")", ":", "if", "not", "self", ".", "altdown", ":", "self", ".", "altdown", "=", "True", "self", ".", "ui", ".", "switchUi", "(", "True", ")", "else", ":", "if", "self", ".", "altdown", ":", "self", ".", "altdown", "=", "False", "self", ".", "ui", ".", "switchUi", "(", "False", ")", "else", ":", "# choose radius", "if", "len", "(", "self", ".", "tangents", ")", "==", "2", ":", "cir", "=", "DraftGeomUtils", ".", "circleFrom2tan1pt", "(", "self", ".", "tangents", "[", "0", "]", ",", "self", ".", "tangents", "[", "1", "]", ",", "self", ".", "point", ")", "_c", "=", "DraftGeomUtils", ".", "findClosestCircle", "(", "self", ".", "point", ",", "cir", ")", "self", ".", "center", "=", "_c", ".", "Center", "self", ".", "arctrack", ".", "setCenter", "(", "self", ".", "center", ")", "elif", "self", ".", "tangents", "and", "self", ".", "tanpoints", ":", "cir", "=", "DraftGeomUtils", ".", "circleFrom1tan2pt", "(", "self", ".", "tangents", "[", "0", "]", ",", "self", ".", "tanpoints", "[", "0", "]", ",", "self", ".", "point", ")", "_c", "=", "DraftGeomUtils", ".", "findClosestCircle", "(", "self", ".", "point", ",", "cir", ")", "self", ".", "center", "=", "_c", ".", "Center", "self", ".", "arctrack", ".", "setCenter", "(", "self", ".", "center", ")", "if", "gui_tool_utils", ".", "hasMod", "(", "arg", ",", "gui_tool_utils", ".", "MODALT", ")", ":", "if", "not", "self", ".", "altdown", ":", "self", ".", "altdown", "=", "True", "snapped", "=", "self", ".", "view", ".", "getObjectInfo", "(", "(", "arg", "[", "\"Position\"", "]", "[", "0", "]", ",", "arg", "[", "\"Position\"", "]", "[", "1", "]", ")", ")", "if", "snapped", ":", "ob", "=", "self", ".", "doc", ".", "getObject", "(", "snapped", "[", "'Object'", "]", ")", "num", "=", "int", "(", "snapped", "[", "'Component'", "]", ".", "lstrip", "(", "'Edge'", ")", ")", "-", "1", "ed", "=", "ob", ".", "Shape", ".", "Edges", "[", "num", "]", "if", "len", "(", "self", ".", "tangents", ")", "==", "2", ":", "cir", "=", "DraftGeomUtils", ".", "circleFrom3tan", "(", "self", ".", "tangents", "[", "0", "]", ",", "self", ".", "tangents", "[", "1", "]", ",", "ed", ")", "cl", "=", "DraftGeomUtils", ".", "findClosestCircle", "(", "self", ".", "point", ",", "cir", ")", "self", ".", "center", "=", "cl", ".", "Center", "self", ".", "rad", "=", "cl", ".", "Radius", "self", ".", "arctrack", ".", "setCenter", "(", "self", ".", "center", ")", "else", ":", "self", ".", "rad", "=", "self", ".", "center", ".", "add", "(", "DraftGeomUtils", ".", "findDistance", "(", "self", ".", "center", ",", "ed", ")", ".", "sub", "(", "self", ".", "center", ")", ")", ".", "Length", "else", ":", "self", ".", "rad", "=", "DraftVecUtils", ".", "dist", "(", "self", ".", "point", ",", "self", ".", "center", ")", "else", ":", "if", "self", ".", "altdown", ":", "self", ".", "altdown", "=", "False", "self", ".", "rad", "=", "DraftVecUtils", ".", "dist", "(", "self", ".", "point", ",", "self", ".", "center", ")", "self", ".", "ui", ".", "setRadiusValue", "(", "self", ".", "rad", ",", "'Length'", ")", "self", ".", "arctrack", ".", "setRadius", "(", "self", ".", "rad", ")", "gui_tool_utils", ".", "redraw3DView", "(", ")", "elif", "(", "arg", "[", "\"Type\"", "]", "==", "\"SoMouseButtonEvent\"", "and", "arg", "[", "\"State\"", "]", "==", "\"DOWN\"", "and", "arg", "[", "\"Button\"", "]", "==", "\"BUTTON1\"", ")", ":", "# mouse click", "if", "self", ".", "point", ":", "if", "self", ".", "step", "==", "0", ":", "# choose center", "if", "(", "not", "self", ".", "node", ")", "and", "(", "not", "self", ".", "support", ")", ":", "gui_tool_utils", ".", "getSupport", "(", "arg", ")", "(", "self", ".", "point", ",", "ctrlPoint", ",", "info", ")", "=", "gui_tool_utils", ".", "getPoint", "(", "self", ",", "arg", ")", "if", "gui_tool_utils", ".", "hasMod", "(", "arg", ",", "gui_tool_utils", ".", "MODALT", ")", ":", "snapped", "=", "self", ".", "view", ".", "getObjectInfo", "(", "(", "arg", "[", "\"Position\"", "]", "[", "0", "]", ",", "arg", "[", "\"Position\"", "]", "[", "1", "]", ")", ")", "if", "snapped", ":", "ob", "=", "self", ".", "doc", ".", "getObject", "(", "snapped", "[", "'Object'", "]", ")", "num", "=", "int", "(", "snapped", "[", "'Component'", "]", ".", "lstrip", "(", "'Edge'", ")", ")", "-", "1", "ed", "=", "ob", ".", "Shape", ".", "Edges", "[", "num", "]", "self", ".", "tangents", ".", "append", "(", "ed", ")", "if", "len", "(", "self", ".", "tangents", ")", "==", "2", ":", "self", ".", "arctrack", ".", "on", "(", ")", "self", ".", "ui", ".", "radiusUi", "(", ")", "self", ".", "step", "=", "1", "_msg", "(", "translate", "(", "\"draft\"", ",", "\"Pick radius\"", ")", ")", "else", ":", "if", "len", "(", "self", ".", "tangents", ")", "==", "1", ":", "self", ".", "tanpoints", ".", "append", "(", "self", ".", "point", ")", "else", ":", "self", ".", "center", "=", "self", ".", "point", "self", ".", "node", "=", "[", "self", ".", "point", "]", "self", ".", "arctrack", ".", "setCenter", "(", "self", ".", "center", ")", "self", ".", "arctrack", ".", "on", "(", ")", "self", ".", "ui", ".", "radiusUi", "(", ")", "self", ".", "step", "=", "1", "_msg", "(", "translate", "(", "\"draft\"", ",", "\"Pick radius\"", ")", ")", "if", "self", ".", "planetrack", ":", "self", ".", "planetrack", ".", "set", "(", "self", ".", "point", ")", "elif", "self", ".", "step", "==", "1", ":", "# choose radius", "self", ".", "drawPolygon", "(", ")" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_polygons.py#L89-L204
google/nucleus
68d3947fafba1337f294c0668a6e1c7f3f1273e3
nucleus/io/genomics_reader.py
python
TFRecordReader.c_reader
(self)
return self.reader
Returns the underlying C++ reader.
Returns the underlying C++ reader.
[ "Returns", "the", "underlying", "C", "++", "reader", "." ]
def c_reader(self): """Returns the underlying C++ reader.""" return self.reader
[ "def", "c_reader", "(", "self", ")", ":", "return", "self", ".", "reader" ]
https://github.com/google/nucleus/blob/68d3947fafba1337f294c0668a6e1c7f3f1273e3/nucleus/io/genomics_reader.py#L179-L181
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/functools.py
python
_compose_mro
(cls, types)
return _c3_mro(cls, abcs=mro)
Calculates the method resolution order for a given class *cls*. Includes relevant abstract base classes (with their respective bases) from the *types* iterable. Uses a modified C3 linearization algorithm.
Calculates the method resolution order for a given class *cls*.
[ "Calculates", "the", "method", "resolution", "order", "for", "a", "given", "class", "*", "cls", "*", "." ]
def _compose_mro(cls, types): """Calculates the method resolution order for a given class *cls*. Includes relevant abstract base classes (with their respective bases) from the *types* iterable. Uses a modified C3 linearization algorithm. """ bases = set(cls.__mro__) # Remove entries which are already present in the __mro__ or unrelated. def is_related(typ): return (typ not in bases and hasattr(typ, '__mro__') and issubclass(cls, typ)) types = [n for n in types if is_related(n)] # Remove entries which are strict bases of other entries (they will end up # in the MRO anyway. def is_strict_base(typ): for other in types: if typ != other and typ in other.__mro__: return True return False types = [n for n in types if not is_strict_base(n)] # Subclasses of the ABCs in *types* which are also implemented by # *cls* can be used to stabilize ABC ordering. type_set = set(types) mro = [] for typ in types: found = [] for sub in typ.__subclasses__(): if sub not in bases and issubclass(cls, sub): found.append([s for s in sub.__mro__ if s in type_set]) if not found: mro.append(typ) continue # Favor subclasses with the biggest number of useful bases found.sort(key=len, reverse=True) for sub in found: for subcls in sub: if subcls not in mro: mro.append(subcls) return _c3_mro(cls, abcs=mro)
[ "def", "_compose_mro", "(", "cls", ",", "types", ")", ":", "bases", "=", "set", "(", "cls", ".", "__mro__", ")", "# Remove entries which are already present in the __mro__ or unrelated.", "def", "is_related", "(", "typ", ")", ":", "return", "(", "typ", "not", "in", "bases", "and", "hasattr", "(", "typ", ",", "'__mro__'", ")", "and", "issubclass", "(", "cls", ",", "typ", ")", ")", "types", "=", "[", "n", "for", "n", "in", "types", "if", "is_related", "(", "n", ")", "]", "# Remove entries which are strict bases of other entries (they will end up", "# in the MRO anyway.", "def", "is_strict_base", "(", "typ", ")", ":", "for", "other", "in", "types", ":", "if", "typ", "!=", "other", "and", "typ", "in", "other", ".", "__mro__", ":", "return", "True", "return", "False", "types", "=", "[", "n", "for", "n", "in", "types", "if", "not", "is_strict_base", "(", "n", ")", "]", "# Subclasses of the ABCs in *types* which are also implemented by", "# *cls* can be used to stabilize ABC ordering.", "type_set", "=", "set", "(", "types", ")", "mro", "=", "[", "]", "for", "typ", "in", "types", ":", "found", "=", "[", "]", "for", "sub", "in", "typ", ".", "__subclasses__", "(", ")", ":", "if", "sub", "not", "in", "bases", "and", "issubclass", "(", "cls", ",", "sub", ")", ":", "found", ".", "append", "(", "[", "s", "for", "s", "in", "sub", ".", "__mro__", "if", "s", "in", "type_set", "]", ")", "if", "not", "found", ":", "mro", ".", "append", "(", "typ", ")", "continue", "# Favor subclasses with the biggest number of useful bases", "found", ".", "sort", "(", "key", "=", "len", ",", "reverse", "=", "True", ")", "for", "sub", "in", "found", ":", "for", "subcls", "in", "sub", ":", "if", "subcls", "not", "in", "mro", ":", "mro", ".", "append", "(", "subcls", ")", "return", "_c3_mro", "(", "cls", ",", "abcs", "=", "mro", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/functools.py#L696-L735
evpo/EncryptPad
156904860aaba8e7e8729b44e269b2992f9fe9f4
deps/botan/configure.py
python
process_command_line
(args)
return options
Handle command line options Do not use logging in this method as command line options need to be available before logging is setup.
Handle command line options Do not use logging in this method as command line options need to be available before logging is setup.
[ "Handle", "command", "line", "options", "Do", "not", "use", "logging", "in", "this", "method", "as", "command", "line", "options", "need", "to", "be", "available", "before", "logging", "is", "setup", "." ]
def process_command_line(args): # pylint: disable=too-many-locals,too-many-statements """ Handle command line options Do not use logging in this method as command line options need to be available before logging is setup. """ parser = optparse.OptionParser( formatter=optparse.IndentedHelpFormatter(max_help_position=50), version=Version.as_string()) parser.add_option('--verbose', action='store_true', default=False, help='Show debug messages') parser.add_option('--quiet', action='store_true', default=False, help='Show only warnings and errors') target_group = optparse.OptionGroup(parser, 'Target options') target_group.add_option('--cpu', help='set the target CPU architecture') target_group.add_option('--os', help='set the target operating system') target_group.add_option('--cc', dest='compiler', help='set the desired build compiler') target_group.add_option('--cc-min-version', dest='cc_min_version', default=None, metavar='MAJOR.MINOR', help='Set the minimal version of the target compiler. ' \ 'Use --cc-min-version=0.0 to support all compiler versions. ' \ 'Default is auto detection.') target_group.add_option('--cc-bin', dest='compiler_binary', metavar='BINARY', help='set path to compiler binary') target_group.add_option('--cc-abi-flags', metavar='FLAGS', default='', help='set compiler ABI flags') target_group.add_option('--cxxflags', metavar='FLAGS', default=None, help='override all compiler flags') target_group.add_option('--extra-cxxflags', metavar='FLAGS', default=[], action='append', help='set extra compiler flags') target_group.add_option('--ldflags', metavar='FLAGS', help='set linker flags', default=None) target_group.add_option('--extra-libs', metavar='LIBS', help='specify extra libraries to link against', default='') target_group.add_option('--ar-command', dest='ar_command', metavar='AR', default=None, help='set path to static archive creator') target_group.add_option('--ar-options', dest='ar_options', metavar='AR_OPTIONS', default=None, help='set options for ar') target_group.add_option('--msvc-runtime', metavar='RT', default=None, help='specify MSVC runtime (MT, MD, MTd, MDd)') target_group.add_option('--compiler-cache', help='specify a compiler cache to use') target_group.add_option('--with-endian', metavar='ORDER', default=None, help='override byte order guess') target_group.add_option('--with-os-features', action='append', metavar='FEAT', help='specify OS features to use') target_group.add_option('--without-os-features', action='append', metavar='FEAT', help='specify OS features to disable') isa_extensions = [ 'SSE2', 'SSSE3', 'SSE4.1', 'SSE4.2', 'AVX2', 'BMI2', 'RDRAND', 'RDSEED', 'AES-NI', 'SHA-NI', 'AltiVec', 'NEON', 'ARMv8 Crypto', 'POWER Crypto'] for isa_extn_name in isa_extensions: isa_extn = isa_extn_name.lower().replace(' ', '') target_group.add_option('--disable-%s' % (isa_extn), help='disable %s intrinsics' % (isa_extn_name), action='append_const', const=isa_extn.replace('-', '').replace('.', '').replace(' ', ''), dest='disable_intrinsics') build_group = optparse.OptionGroup(parser, 'Build options') build_group.add_option('--system-cert-bundle', metavar='PATH', default=None, help='set path to trusted CA bundle') build_group.add_option('--with-debug-info', action='store_true', default=False, dest='with_debug_info', help='include debug symbols') build_group.add_option('--with-sanitizers', action='store_true', default=False, dest='with_sanitizers', help='enable ASan/UBSan checks') build_group.add_option('--enable-sanitizers', metavar='SAN', default='', help='enable specific sanitizers') build_group.add_option('--with-stack-protector', dest='with_stack_protector', action='store_false', default=None, help=optparse.SUPPRESS_HELP) build_group.add_option('--without-stack-protector', dest='with_stack_protector', action='store_false', help='disable stack smashing protections') build_group.add_option('--with-coverage', action='store_true', default=False, dest='with_coverage', help='add coverage info and disable opts') build_group.add_option('--with-coverage-info', action='store_true', default=False, dest='with_coverage_info', help='add coverage info') build_group.add_option('--enable-shared-library', dest='build_shared_lib', action='store_true', default=None, help=optparse.SUPPRESS_HELP) build_group.add_option('--disable-shared-library', dest='build_shared_lib', action='store_false', help='disable building shared library') build_group.add_option('--enable-static-library', dest='build_static_lib', action='store_true', default=None, help=optparse.SUPPRESS_HELP) build_group.add_option('--disable-static-library', dest='build_static_lib', action='store_false', help='disable building static library') build_group.add_option('--optimize-for-size', dest='optimize_for_size', action='store_true', default=False, help='optimize for code size') build_group.add_option('--no-optimizations', dest='no_optimizations', action='store_true', default=False, help='disable all optimizations (for debugging)') build_group.add_option('--debug-mode', action='store_true', default=False, dest='debug_mode', help='enable debug info, disable optimizations') build_group.add_option('--amalgamation', dest='amalgamation', default=False, action='store_true', help='use amalgamation to build') build_group.add_option('--name-amalgamation', metavar='NAME', default='botan_all', help='specify alternate name for amalgamation files') build_group.add_option('--with-build-dir', metavar='DIR', default='', help='setup the build in DIR') build_group.add_option('--with-external-includedir', metavar='DIR', default=[], help='use DIR for external includes', action='append') build_group.add_option('--with-external-libdir', metavar='DIR', default=[], help='use DIR for external libs', action='append') build_group.add_option('--define-build-macro', metavar='DEFINE', default=[], help='set compile-time pre-processor definition like KEY[=VALUE]', action='append') build_group.add_option('--with-sysroot-dir', metavar='DIR', default='', help='use DIR for system root while cross-compiling') build_group.add_option('--with-openmp', default=False, action='store_true', help='enable use of OpenMP') link_methods = ['symlink', 'hardlink', 'copy'] build_group.add_option('--link-method', default=None, metavar='METHOD', choices=link_methods, help='choose how links to include headers are created (%s)' % ', '.join(link_methods)) build_group.add_option('--with-local-config', dest='local_config', metavar='FILE', help='include the contents of FILE into build.h') build_group.add_option('--distribution-info', metavar='STRING', help='distribution specific version', default='unspecified') build_group.add_option('--maintainer-mode', dest='maintainer_mode', action='store_true', default=False, help=optparse.SUPPRESS_HELP) build_group.add_option('--werror-mode', dest='werror_mode', action='store_true', default=False, help="Prohibit compiler warnings") build_group.add_option('--no-store-vc-rev', action='store_true', default=False, help=optparse.SUPPRESS_HELP) build_group.add_option('--no-install-python-module', action='store_true', default=False, help='skip installing Python module') build_group.add_option('--with-python-versions', dest='python_version', metavar='N.M', default='%d.%d' % (sys.version_info[0], sys.version_info[1]), help='where to install botan2.py (def %default)') build_group.add_option('--disable-cc-tests', dest='enable_cc_tests', default=True, action='store_false', help=optparse.SUPPRESS_HELP) build_group.add_option('--with-valgrind', help='use valgrind API', dest='with_valgrind', action='store_true', default=False) # Cmake and bakefile options are hidden as they should not be used by end users build_group.add_option('--with-cmake', action='store_true', default=False, help=optparse.SUPPRESS_HELP) build_group.add_option('--with-bakefile', action='store_true', default=False, help=optparse.SUPPRESS_HELP) build_group.add_option('--unsafe-fuzzer-mode', action='store_true', default=False, help='Disable essential checks for testing') build_group.add_option('--build-fuzzers', dest='build_fuzzers', metavar='TYPE', default=None, help='Build fuzzers (afl, libfuzzer, klee, test)') build_group.add_option('--with-fuzzer-lib', metavar='LIB', default=None, dest='fuzzer_lib', help='additionally link in LIB') build_group.add_option('--test-mode', action='store_true', default=False, help=optparse.SUPPRESS_HELP) build_group.add_option('--with-debug-asserts', action='store_true', default=False, help=optparse.SUPPRESS_HELP) build_group.add_option('--build-targets', default=None, dest="build_targets", action='append', help="build specific targets and tools (%s)" % ', '.join(ACCEPTABLE_BUILD_TARGETS)) build_group.add_option('--with-pkg-config', action='store_true', default=None, help=optparse.SUPPRESS_HELP) build_group.add_option('--without-pkg-config', dest='with_pkg_config', action='store_false', help=optparse.SUPPRESS_HELP) build_group.add_option('--boost-library-name', dest='boost_libnames', default=[], help="file name of some boost library to link", action='append') docs_group = optparse.OptionGroup(parser, 'Documentation Options') docs_group.add_option('--with-documentation', action='store_true', help=optparse.SUPPRESS_HELP) docs_group.add_option('--without-documentation', action='store_false', default=True, dest='with_documentation', help='Skip building/installing documentation') docs_group.add_option('--with-sphinx', action='store_true', default=None, help='Use Sphinx') docs_group.add_option('--without-sphinx', action='store_false', dest='with_sphinx', help=optparse.SUPPRESS_HELP) docs_group.add_option('--with-pdf', action='store_true', default=False, help='Use Sphinx to generate PDF doc') docs_group.add_option('--without-pdf', action='store_false', dest='with_pdf', help=optparse.SUPPRESS_HELP) docs_group.add_option('--with-rst2man', action='store_true', default=None, help='Use rst2man to generate man page') docs_group.add_option('--without-rst2man', action='store_false', dest='with_rst2man', help=optparse.SUPPRESS_HELP) docs_group.add_option('--with-doxygen', action='store_true', default=False, help='Use Doxygen') docs_group.add_option('--without-doxygen', action='store_false', dest='with_doxygen', help=optparse.SUPPRESS_HELP) mods_group = optparse.OptionGroup(parser, 'Module selection') mods_group.add_option('--module-policy', dest='module_policy', help="module policy file (see src/build-data/policy)", metavar='POL', default=None) mods_group.add_option('--enable-modules', dest='enabled_modules', metavar='MODS', action='append', help='enable specific modules') mods_group.add_option('--disable-modules', dest='disabled_modules', metavar='MODS', action='append', help='disable specific modules') mods_group.add_option('--no-autoload', action='store_true', default=False, help=optparse.SUPPRESS_HELP) mods_group.add_option('--minimized-build', action='store_true', dest='no_autoload', help='minimize build') # Should be derived from info.txt but this runs too early third_party = ['boost', 'bzip2', 'lzma', 'openssl', 'commoncrypto', 'sqlite3', 'zlib', 'tpm'] for mod in third_party: mods_group.add_option('--with-%s' % (mod), help=('use %s' % (mod)) if mod in third_party else optparse.SUPPRESS_HELP, action='append_const', const=mod, dest='enabled_modules') mods_group.add_option('--without-%s' % (mod), help=optparse.SUPPRESS_HELP, action='append_const', const=mod, dest='disabled_modules') mods_group.add_option('--with-everything', help=optparse.SUPPRESS_HELP, action='store_true', default=False) install_group = optparse.OptionGroup(parser, 'Installation options') install_group.add_option('--program-suffix', metavar='SUFFIX', help='append string to program names') install_group.add_option('--library-suffix', metavar='SUFFIX', default='', help='append string to library names') install_group.add_option('--prefix', metavar='DIR', help='set the install prefix') install_group.add_option('--docdir', metavar='DIR', help='set the doc install dir') install_group.add_option('--bindir', metavar='DIR', help='set the binary install dir') install_group.add_option('--libdir', metavar='DIR', help='set the library install dir') install_group.add_option('--mandir', metavar='DIR', help='set the install dir for man pages') install_group.add_option('--includedir', metavar='DIR', help='set the include file install dir') info_group = optparse.OptionGroup(parser, 'Informational') info_group.add_option('--list-modules', dest='list_modules', action='store_true', help='list available modules and exit') info_group.add_option('--list-os-features', dest='list_os_features', action='store_true', help='list available OS features and exit') parser.add_option_group(target_group) parser.add_option_group(build_group) parser.add_option_group(docs_group) parser.add_option_group(mods_group) parser.add_option_group(install_group) parser.add_option_group(info_group) # These exist only for autoconf compatibility (requested by zw for mtn) compat_with_autoconf_options = [ 'datadir', 'datarootdir', 'dvidir', 'exec-prefix', 'htmldir', 'infodir', 'libexecdir', 'localedir', 'localstatedir', 'oldincludedir', 'pdfdir', 'psdir', 'sbindir', 'sharedstatedir', 'sysconfdir' ] for opt in compat_with_autoconf_options: parser.add_option('--' + opt, help=optparse.SUPPRESS_HELP) (options, args) = parser.parse_args(args) if args != []: raise UserError('Unhandled option(s): ' + ' '.join(args)) if options.with_endian not in [None, 'little', 'big']: raise UserError('Bad value to --with-endian "%s"' % (options.with_endian)) if options.debug_mode: options.no_optimizations = True options.with_debug_info = True if options.with_coverage: options.with_coverage_info = True options.no_optimizations = True def parse_multiple_enable(modules): if modules is None: return [] return sorted({m for m in flatten([s.split(',') for s in modules]) if m != ''}) options.enabled_modules = parse_multiple_enable(options.enabled_modules) options.disabled_modules = parse_multiple_enable(options.disabled_modules) options.with_os_features = parse_multiple_enable(options.with_os_features) options.without_os_features = parse_multiple_enable(options.without_os_features) options.disable_intrinsics = parse_multiple_enable(options.disable_intrinsics) return options
[ "def", "process_command_line", "(", "args", ")", ":", "# pylint: disable=too-many-locals,too-many-statements", "parser", "=", "optparse", ".", "OptionParser", "(", "formatter", "=", "optparse", ".", "IndentedHelpFormatter", "(", "max_help_position", "=", "50", ")", ",", "version", "=", "Version", ".", "as_string", "(", ")", ")", "parser", ".", "add_option", "(", "'--verbose'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "'Show debug messages'", ")", "parser", ".", "add_option", "(", "'--quiet'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "'Show only warnings and errors'", ")", "target_group", "=", "optparse", ".", "OptionGroup", "(", "parser", ",", "'Target options'", ")", "target_group", ".", "add_option", "(", "'--cpu'", ",", "help", "=", "'set the target CPU architecture'", ")", "target_group", ".", "add_option", "(", "'--os'", ",", "help", "=", "'set the target operating system'", ")", "target_group", ".", "add_option", "(", "'--cc'", ",", "dest", "=", "'compiler'", ",", "help", "=", "'set the desired build compiler'", ")", "target_group", ".", "add_option", "(", "'--cc-min-version'", ",", "dest", "=", "'cc_min_version'", ",", "default", "=", "None", ",", "metavar", "=", "'MAJOR.MINOR'", ",", "help", "=", "'Set the minimal version of the target compiler. '", "'Use --cc-min-version=0.0 to support all compiler versions. '", "'Default is auto detection.'", ")", "target_group", ".", "add_option", "(", "'--cc-bin'", ",", "dest", "=", "'compiler_binary'", ",", "metavar", "=", "'BINARY'", ",", "help", "=", "'set path to compiler binary'", ")", "target_group", ".", "add_option", "(", "'--cc-abi-flags'", ",", "metavar", "=", "'FLAGS'", ",", "default", "=", "''", ",", "help", "=", "'set compiler ABI flags'", ")", "target_group", ".", "add_option", "(", "'--cxxflags'", ",", "metavar", "=", "'FLAGS'", ",", "default", "=", "None", ",", "help", "=", "'override all compiler flags'", ")", "target_group", ".", "add_option", "(", "'--extra-cxxflags'", ",", "metavar", "=", "'FLAGS'", ",", "default", "=", "[", "]", ",", "action", "=", "'append'", ",", "help", "=", "'set extra compiler flags'", ")", "target_group", ".", "add_option", "(", "'--ldflags'", ",", "metavar", "=", "'FLAGS'", ",", "help", "=", "'set linker flags'", ",", "default", "=", "None", ")", "target_group", ".", "add_option", "(", "'--extra-libs'", ",", "metavar", "=", "'LIBS'", ",", "help", "=", "'specify extra libraries to link against'", ",", "default", "=", "''", ")", "target_group", ".", "add_option", "(", "'--ar-command'", ",", "dest", "=", "'ar_command'", ",", "metavar", "=", "'AR'", ",", "default", "=", "None", ",", "help", "=", "'set path to static archive creator'", ")", "target_group", ".", "add_option", "(", "'--ar-options'", ",", "dest", "=", "'ar_options'", ",", "metavar", "=", "'AR_OPTIONS'", ",", "default", "=", "None", ",", "help", "=", "'set options for ar'", ")", "target_group", ".", "add_option", "(", "'--msvc-runtime'", ",", "metavar", "=", "'RT'", ",", "default", "=", "None", ",", "help", "=", "'specify MSVC runtime (MT, MD, MTd, MDd)'", ")", "target_group", ".", "add_option", "(", "'--compiler-cache'", ",", "help", "=", "'specify a compiler cache to use'", ")", "target_group", ".", "add_option", "(", "'--with-endian'", ",", "metavar", "=", "'ORDER'", ",", "default", "=", "None", ",", "help", "=", "'override byte order guess'", ")", "target_group", ".", "add_option", "(", "'--with-os-features'", ",", "action", "=", "'append'", ",", "metavar", "=", "'FEAT'", ",", "help", "=", "'specify OS features to use'", ")", "target_group", ".", "add_option", "(", "'--without-os-features'", ",", "action", "=", "'append'", ",", "metavar", "=", "'FEAT'", ",", "help", "=", "'specify OS features to disable'", ")", "isa_extensions", "=", "[", "'SSE2'", ",", "'SSSE3'", ",", "'SSE4.1'", ",", "'SSE4.2'", ",", "'AVX2'", ",", "'BMI2'", ",", "'RDRAND'", ",", "'RDSEED'", ",", "'AES-NI'", ",", "'SHA-NI'", ",", "'AltiVec'", ",", "'NEON'", ",", "'ARMv8 Crypto'", ",", "'POWER Crypto'", "]", "for", "isa_extn_name", "in", "isa_extensions", ":", "isa_extn", "=", "isa_extn_name", ".", "lower", "(", ")", ".", "replace", "(", "' '", ",", "''", ")", "target_group", ".", "add_option", "(", "'--disable-%s'", "%", "(", "isa_extn", ")", ",", "help", "=", "'disable %s intrinsics'", "%", "(", "isa_extn_name", ")", ",", "action", "=", "'append_const'", ",", "const", "=", "isa_extn", ".", "replace", "(", "'-'", ",", "''", ")", ".", "replace", "(", "'.'", ",", "''", ")", ".", "replace", "(", "' '", ",", "''", ")", ",", "dest", "=", "'disable_intrinsics'", ")", "build_group", "=", "optparse", ".", "OptionGroup", "(", "parser", ",", "'Build options'", ")", "build_group", ".", "add_option", "(", "'--system-cert-bundle'", ",", "metavar", "=", "'PATH'", ",", "default", "=", "None", ",", "help", "=", "'set path to trusted CA bundle'", ")", "build_group", ".", "add_option", "(", "'--with-debug-info'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "dest", "=", "'with_debug_info'", ",", "help", "=", "'include debug symbols'", ")", "build_group", ".", "add_option", "(", "'--with-sanitizers'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "dest", "=", "'with_sanitizers'", ",", "help", "=", "'enable ASan/UBSan checks'", ")", "build_group", ".", "add_option", "(", "'--enable-sanitizers'", ",", "metavar", "=", "'SAN'", ",", "default", "=", "''", ",", "help", "=", "'enable specific sanitizers'", ")", "build_group", ".", "add_option", "(", "'--with-stack-protector'", ",", "dest", "=", "'with_stack_protector'", ",", "action", "=", "'store_false'", ",", "default", "=", "None", ",", "help", "=", "optparse", ".", "SUPPRESS_HELP", ")", "build_group", ".", "add_option", "(", "'--without-stack-protector'", ",", "dest", "=", "'with_stack_protector'", ",", "action", "=", "'store_false'", ",", "help", "=", "'disable stack smashing protections'", ")", "build_group", ".", "add_option", "(", "'--with-coverage'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "dest", "=", "'with_coverage'", ",", "help", "=", "'add coverage info and disable opts'", ")", "build_group", ".", "add_option", "(", "'--with-coverage-info'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "dest", "=", "'with_coverage_info'", ",", "help", "=", "'add coverage info'", ")", "build_group", ".", "add_option", "(", "'--enable-shared-library'", ",", "dest", "=", "'build_shared_lib'", ",", "action", "=", "'store_true'", ",", "default", "=", "None", ",", "help", "=", "optparse", ".", "SUPPRESS_HELP", ")", "build_group", ".", "add_option", "(", "'--disable-shared-library'", ",", "dest", "=", "'build_shared_lib'", ",", "action", "=", "'store_false'", ",", "help", "=", "'disable building shared library'", ")", "build_group", ".", "add_option", "(", "'--enable-static-library'", ",", "dest", "=", "'build_static_lib'", ",", "action", "=", "'store_true'", ",", "default", "=", "None", ",", "help", "=", "optparse", ".", "SUPPRESS_HELP", ")", "build_group", ".", "add_option", "(", "'--disable-static-library'", ",", "dest", "=", "'build_static_lib'", ",", "action", "=", "'store_false'", ",", "help", "=", "'disable building static library'", ")", "build_group", ".", "add_option", "(", "'--optimize-for-size'", ",", "dest", "=", "'optimize_for_size'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "'optimize for code size'", ")", "build_group", ".", "add_option", "(", "'--no-optimizations'", ",", "dest", "=", "'no_optimizations'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "'disable all optimizations (for debugging)'", ")", "build_group", ".", "add_option", "(", "'--debug-mode'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "dest", "=", "'debug_mode'", ",", "help", "=", "'enable debug info, disable optimizations'", ")", "build_group", ".", "add_option", "(", "'--amalgamation'", ",", "dest", "=", "'amalgamation'", ",", "default", "=", "False", ",", "action", "=", "'store_true'", ",", "help", "=", "'use amalgamation to build'", ")", "build_group", ".", "add_option", "(", "'--name-amalgamation'", ",", "metavar", "=", "'NAME'", ",", "default", "=", "'botan_all'", ",", "help", "=", "'specify alternate name for amalgamation files'", ")", "build_group", ".", "add_option", "(", "'--with-build-dir'", ",", "metavar", "=", "'DIR'", ",", "default", "=", "''", ",", "help", "=", "'setup the build in DIR'", ")", "build_group", ".", "add_option", "(", "'--with-external-includedir'", ",", "metavar", "=", "'DIR'", ",", "default", "=", "[", "]", ",", "help", "=", "'use DIR for external includes'", ",", "action", "=", "'append'", ")", "build_group", ".", "add_option", "(", "'--with-external-libdir'", ",", "metavar", "=", "'DIR'", ",", "default", "=", "[", "]", ",", "help", "=", "'use DIR for external libs'", ",", "action", "=", "'append'", ")", "build_group", ".", "add_option", "(", "'--define-build-macro'", ",", "metavar", "=", "'DEFINE'", ",", "default", "=", "[", "]", ",", "help", "=", "'set compile-time pre-processor definition like KEY[=VALUE]'", ",", "action", "=", "'append'", ")", "build_group", ".", "add_option", "(", "'--with-sysroot-dir'", ",", "metavar", "=", "'DIR'", ",", "default", "=", "''", ",", "help", "=", "'use DIR for system root while cross-compiling'", ")", "build_group", ".", "add_option", "(", "'--with-openmp'", ",", "default", "=", "False", ",", "action", "=", "'store_true'", ",", "help", "=", "'enable use of OpenMP'", ")", "link_methods", "=", "[", "'symlink'", ",", "'hardlink'", ",", "'copy'", "]", "build_group", ".", "add_option", "(", "'--link-method'", ",", "default", "=", "None", ",", "metavar", "=", "'METHOD'", ",", "choices", "=", "link_methods", ",", "help", "=", "'choose how links to include headers are created (%s)'", "%", "', '", ".", "join", "(", "link_methods", ")", ")", "build_group", ".", "add_option", "(", "'--with-local-config'", ",", "dest", "=", "'local_config'", ",", "metavar", "=", "'FILE'", ",", "help", "=", "'include the contents of FILE into build.h'", ")", "build_group", ".", "add_option", "(", "'--distribution-info'", ",", "metavar", "=", "'STRING'", ",", "help", "=", "'distribution specific version'", ",", "default", "=", "'unspecified'", ")", "build_group", ".", "add_option", "(", "'--maintainer-mode'", ",", "dest", "=", "'maintainer_mode'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "optparse", ".", "SUPPRESS_HELP", ")", "build_group", ".", "add_option", "(", "'--werror-mode'", ",", "dest", "=", "'werror_mode'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "\"Prohibit compiler warnings\"", ")", "build_group", ".", "add_option", "(", "'--no-store-vc-rev'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "optparse", ".", "SUPPRESS_HELP", ")", "build_group", ".", "add_option", "(", "'--no-install-python-module'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "'skip installing Python module'", ")", "build_group", ".", "add_option", "(", "'--with-python-versions'", ",", "dest", "=", "'python_version'", ",", "metavar", "=", "'N.M'", ",", "default", "=", "'%d.%d'", "%", "(", "sys", ".", "version_info", "[", "0", "]", ",", "sys", ".", "version_info", "[", "1", "]", ")", ",", "help", "=", "'where to install botan2.py (def %default)'", ")", "build_group", ".", "add_option", "(", "'--disable-cc-tests'", ",", "dest", "=", "'enable_cc_tests'", ",", "default", "=", "True", ",", "action", "=", "'store_false'", ",", "help", "=", "optparse", ".", "SUPPRESS_HELP", ")", "build_group", ".", "add_option", "(", "'--with-valgrind'", ",", "help", "=", "'use valgrind API'", ",", "dest", "=", "'with_valgrind'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ")", "# Cmake and bakefile options are hidden as they should not be used by end users", "build_group", ".", "add_option", "(", "'--with-cmake'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "optparse", ".", "SUPPRESS_HELP", ")", "build_group", ".", "add_option", "(", "'--with-bakefile'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "optparse", ".", "SUPPRESS_HELP", ")", "build_group", ".", "add_option", "(", "'--unsafe-fuzzer-mode'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "'Disable essential checks for testing'", ")", "build_group", ".", "add_option", "(", "'--build-fuzzers'", ",", "dest", "=", "'build_fuzzers'", ",", "metavar", "=", "'TYPE'", ",", "default", "=", "None", ",", "help", "=", "'Build fuzzers (afl, libfuzzer, klee, test)'", ")", "build_group", ".", "add_option", "(", "'--with-fuzzer-lib'", ",", "metavar", "=", "'LIB'", ",", "default", "=", "None", ",", "dest", "=", "'fuzzer_lib'", ",", "help", "=", "'additionally link in LIB'", ")", "build_group", ".", "add_option", "(", "'--test-mode'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "optparse", ".", "SUPPRESS_HELP", ")", "build_group", ".", "add_option", "(", "'--with-debug-asserts'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "optparse", ".", "SUPPRESS_HELP", ")", "build_group", ".", "add_option", "(", "'--build-targets'", ",", "default", "=", "None", ",", "dest", "=", "\"build_targets\"", ",", "action", "=", "'append'", ",", "help", "=", "\"build specific targets and tools (%s)\"", "%", "', '", ".", "join", "(", "ACCEPTABLE_BUILD_TARGETS", ")", ")", "build_group", ".", "add_option", "(", "'--with-pkg-config'", ",", "action", "=", "'store_true'", ",", "default", "=", "None", ",", "help", "=", "optparse", ".", "SUPPRESS_HELP", ")", "build_group", ".", "add_option", "(", "'--without-pkg-config'", ",", "dest", "=", "'with_pkg_config'", ",", "action", "=", "'store_false'", ",", "help", "=", "optparse", ".", "SUPPRESS_HELP", ")", "build_group", ".", "add_option", "(", "'--boost-library-name'", ",", "dest", "=", "'boost_libnames'", ",", "default", "=", "[", "]", ",", "help", "=", "\"file name of some boost library to link\"", ",", "action", "=", "'append'", ")", "docs_group", "=", "optparse", ".", "OptionGroup", "(", "parser", ",", "'Documentation Options'", ")", "docs_group", ".", "add_option", "(", "'--with-documentation'", ",", "action", "=", "'store_true'", ",", "help", "=", "optparse", ".", "SUPPRESS_HELP", ")", "docs_group", ".", "add_option", "(", "'--without-documentation'", ",", "action", "=", "'store_false'", ",", "default", "=", "True", ",", "dest", "=", "'with_documentation'", ",", "help", "=", "'Skip building/installing documentation'", ")", "docs_group", ".", "add_option", "(", "'--with-sphinx'", ",", "action", "=", "'store_true'", ",", "default", "=", "None", ",", "help", "=", "'Use Sphinx'", ")", "docs_group", ".", "add_option", "(", "'--without-sphinx'", ",", "action", "=", "'store_false'", ",", "dest", "=", "'with_sphinx'", ",", "help", "=", "optparse", ".", "SUPPRESS_HELP", ")", "docs_group", ".", "add_option", "(", "'--with-pdf'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "'Use Sphinx to generate PDF doc'", ")", "docs_group", ".", "add_option", "(", "'--without-pdf'", ",", "action", "=", "'store_false'", ",", "dest", "=", "'with_pdf'", ",", "help", "=", "optparse", ".", "SUPPRESS_HELP", ")", "docs_group", ".", "add_option", "(", "'--with-rst2man'", ",", "action", "=", "'store_true'", ",", "default", "=", "None", ",", "help", "=", "'Use rst2man to generate man page'", ")", "docs_group", ".", "add_option", "(", "'--without-rst2man'", ",", "action", "=", "'store_false'", ",", "dest", "=", "'with_rst2man'", ",", "help", "=", "optparse", ".", "SUPPRESS_HELP", ")", "docs_group", ".", "add_option", "(", "'--with-doxygen'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "'Use Doxygen'", ")", "docs_group", ".", "add_option", "(", "'--without-doxygen'", ",", "action", "=", "'store_false'", ",", "dest", "=", "'with_doxygen'", ",", "help", "=", "optparse", ".", "SUPPRESS_HELP", ")", "mods_group", "=", "optparse", ".", "OptionGroup", "(", "parser", ",", "'Module selection'", ")", "mods_group", ".", "add_option", "(", "'--module-policy'", ",", "dest", "=", "'module_policy'", ",", "help", "=", "\"module policy file (see src/build-data/policy)\"", ",", "metavar", "=", "'POL'", ",", "default", "=", "None", ")", "mods_group", ".", "add_option", "(", "'--enable-modules'", ",", "dest", "=", "'enabled_modules'", ",", "metavar", "=", "'MODS'", ",", "action", "=", "'append'", ",", "help", "=", "'enable specific modules'", ")", "mods_group", ".", "add_option", "(", "'--disable-modules'", ",", "dest", "=", "'disabled_modules'", ",", "metavar", "=", "'MODS'", ",", "action", "=", "'append'", ",", "help", "=", "'disable specific modules'", ")", "mods_group", ".", "add_option", "(", "'--no-autoload'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "optparse", ".", "SUPPRESS_HELP", ")", "mods_group", ".", "add_option", "(", "'--minimized-build'", ",", "action", "=", "'store_true'", ",", "dest", "=", "'no_autoload'", ",", "help", "=", "'minimize build'", ")", "# Should be derived from info.txt but this runs too early", "third_party", "=", "[", "'boost'", ",", "'bzip2'", ",", "'lzma'", ",", "'openssl'", ",", "'commoncrypto'", ",", "'sqlite3'", ",", "'zlib'", ",", "'tpm'", "]", "for", "mod", "in", "third_party", ":", "mods_group", ".", "add_option", "(", "'--with-%s'", "%", "(", "mod", ")", ",", "help", "=", "(", "'use %s'", "%", "(", "mod", ")", ")", "if", "mod", "in", "third_party", "else", "optparse", ".", "SUPPRESS_HELP", ",", "action", "=", "'append_const'", ",", "const", "=", "mod", ",", "dest", "=", "'enabled_modules'", ")", "mods_group", ".", "add_option", "(", "'--without-%s'", "%", "(", "mod", ")", ",", "help", "=", "optparse", ".", "SUPPRESS_HELP", ",", "action", "=", "'append_const'", ",", "const", "=", "mod", ",", "dest", "=", "'disabled_modules'", ")", "mods_group", ".", "add_option", "(", "'--with-everything'", ",", "help", "=", "optparse", ".", "SUPPRESS_HELP", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ")", "install_group", "=", "optparse", ".", "OptionGroup", "(", "parser", ",", "'Installation options'", ")", "install_group", ".", "add_option", "(", "'--program-suffix'", ",", "metavar", "=", "'SUFFIX'", ",", "help", "=", "'append string to program names'", ")", "install_group", ".", "add_option", "(", "'--library-suffix'", ",", "metavar", "=", "'SUFFIX'", ",", "default", "=", "''", ",", "help", "=", "'append string to library names'", ")", "install_group", ".", "add_option", "(", "'--prefix'", ",", "metavar", "=", "'DIR'", ",", "help", "=", "'set the install prefix'", ")", "install_group", ".", "add_option", "(", "'--docdir'", ",", "metavar", "=", "'DIR'", ",", "help", "=", "'set the doc install dir'", ")", "install_group", ".", "add_option", "(", "'--bindir'", ",", "metavar", "=", "'DIR'", ",", "help", "=", "'set the binary install dir'", ")", "install_group", ".", "add_option", "(", "'--libdir'", ",", "metavar", "=", "'DIR'", ",", "help", "=", "'set the library install dir'", ")", "install_group", ".", "add_option", "(", "'--mandir'", ",", "metavar", "=", "'DIR'", ",", "help", "=", "'set the install dir for man pages'", ")", "install_group", ".", "add_option", "(", "'--includedir'", ",", "metavar", "=", "'DIR'", ",", "help", "=", "'set the include file install dir'", ")", "info_group", "=", "optparse", ".", "OptionGroup", "(", "parser", ",", "'Informational'", ")", "info_group", ".", "add_option", "(", "'--list-modules'", ",", "dest", "=", "'list_modules'", ",", "action", "=", "'store_true'", ",", "help", "=", "'list available modules and exit'", ")", "info_group", ".", "add_option", "(", "'--list-os-features'", ",", "dest", "=", "'list_os_features'", ",", "action", "=", "'store_true'", ",", "help", "=", "'list available OS features and exit'", ")", "parser", ".", "add_option_group", "(", "target_group", ")", "parser", ".", "add_option_group", "(", "build_group", ")", "parser", ".", "add_option_group", "(", "docs_group", ")", "parser", ".", "add_option_group", "(", "mods_group", ")", "parser", ".", "add_option_group", "(", "install_group", ")", "parser", ".", "add_option_group", "(", "info_group", ")", "# These exist only for autoconf compatibility (requested by zw for mtn)", "compat_with_autoconf_options", "=", "[", "'datadir'", ",", "'datarootdir'", ",", "'dvidir'", ",", "'exec-prefix'", ",", "'htmldir'", ",", "'infodir'", ",", "'libexecdir'", ",", "'localedir'", ",", "'localstatedir'", ",", "'oldincludedir'", ",", "'pdfdir'", ",", "'psdir'", ",", "'sbindir'", ",", "'sharedstatedir'", ",", "'sysconfdir'", "]", "for", "opt", "in", "compat_with_autoconf_options", ":", "parser", ".", "add_option", "(", "'--'", "+", "opt", ",", "help", "=", "optparse", ".", "SUPPRESS_HELP", ")", "(", "options", ",", "args", ")", "=", "parser", ".", "parse_args", "(", "args", ")", "if", "args", "!=", "[", "]", ":", "raise", "UserError", "(", "'Unhandled option(s): '", "+", "' '", ".", "join", "(", "args", ")", ")", "if", "options", ".", "with_endian", "not", "in", "[", "None", ",", "'little'", ",", "'big'", "]", ":", "raise", "UserError", "(", "'Bad value to --with-endian \"%s\"'", "%", "(", "options", ".", "with_endian", ")", ")", "if", "options", ".", "debug_mode", ":", "options", ".", "no_optimizations", "=", "True", "options", ".", "with_debug_info", "=", "True", "if", "options", ".", "with_coverage", ":", "options", ".", "with_coverage_info", "=", "True", "options", ".", "no_optimizations", "=", "True", "def", "parse_multiple_enable", "(", "modules", ")", ":", "if", "modules", "is", "None", ":", "return", "[", "]", "return", "sorted", "(", "{", "m", "for", "m", "in", "flatten", "(", "[", "s", ".", "split", "(", "','", ")", "for", "s", "in", "modules", "]", ")", "if", "m", "!=", "''", "}", ")", "options", ".", "enabled_modules", "=", "parse_multiple_enable", "(", "options", ".", "enabled_modules", ")", "options", ".", "disabled_modules", "=", "parse_multiple_enable", "(", "options", ".", "disabled_modules", ")", "options", ".", "with_os_features", "=", "parse_multiple_enable", "(", "options", ".", "with_os_features", ")", "options", ".", "without_os_features", "=", "parse_multiple_enable", "(", "options", ".", "without_os_features", ")", "options", ".", "disable_intrinsics", "=", "parse_multiple_enable", "(", "options", ".", "disable_intrinsics", ")", "return", "options" ]
https://github.com/evpo/EncryptPad/blob/156904860aaba8e7e8729b44e269b2992f9fe9f4/deps/botan/configure.py#L291-L679
llvm/llvm-project
ffa6262cb4e2a335d26416fad39a581b4f98c5f4
mlir/utils/jupyter/mlir_opt_kernel/kernel.py
python
MlirOptKernel.process_output
(self, output)
Reports regular command output.
Reports regular command output.
[ "Reports", "regular", "command", "output", "." ]
def process_output(self, output): """Reports regular command output.""" if not self.silent: # Send standard output stream_content = {'name': 'stdout', 'text': output} self.send_response(self.iopub_socket, 'stream', stream_content)
[ "def", "process_output", "(", "self", ",", "output", ")", ":", "if", "not", "self", ".", "silent", ":", "# Send standard output", "stream_content", "=", "{", "'name'", ":", "'stdout'", ",", "'text'", ":", "output", "}", "self", ".", "send_response", "(", "self", ".", "iopub_socket", ",", "'stream'", ",", "stream_content", ")" ]
https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/mlir/utils/jupyter/mlir_opt_kernel/kernel.py#L87-L92
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/distutils/dir_util.py
python
remove_tree
(directory, verbose=1, dry_run=0)
Recursively remove an entire directory tree. Any errors are ignored (apart from being reported to stdout if 'verbose' is true).
Recursively remove an entire directory tree.
[ "Recursively", "remove", "an", "entire", "directory", "tree", "." ]
def remove_tree(directory, verbose=1, dry_run=0): """Recursively remove an entire directory tree. Any errors are ignored (apart from being reported to stdout if 'verbose' is true). """ global _path_created if verbose >= 1: log.info("removing '%s' (and everything under it)", directory) if dry_run: return cmdtuples = [] _build_cmdtuple(directory, cmdtuples) for cmd in cmdtuples: try: cmd[0](cmd[1]) # remove dir from cache if it's already there abspath = os.path.abspath(cmd[1]) if abspath in _path_created: del _path_created[abspath] except OSError as exc: log.warn("error removing %s: %s", directory, exc)
[ "def", "remove_tree", "(", "directory", ",", "verbose", "=", "1", ",", "dry_run", "=", "0", ")", ":", "global", "_path_created", "if", "verbose", ">=", "1", ":", "log", ".", "info", "(", "\"removing '%s' (and everything under it)\"", ",", "directory", ")", "if", "dry_run", ":", "return", "cmdtuples", "=", "[", "]", "_build_cmdtuple", "(", "directory", ",", "cmdtuples", ")", "for", "cmd", "in", "cmdtuples", ":", "try", ":", "cmd", "[", "0", "]", "(", "cmd", "[", "1", "]", ")", "# remove dir from cache if it's already there", "abspath", "=", "os", ".", "path", ".", "abspath", "(", "cmd", "[", "1", "]", ")", "if", "abspath", "in", "_path_created", ":", "del", "_path_created", "[", "abspath", "]", "except", "OSError", "as", "exc", ":", "log", ".", "warn", "(", "\"error removing %s: %s\"", ",", "directory", ",", "exc", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/distutils/dir_util.py#L178-L200
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/timeit.py
python
reindent
(src, indent)
return src.replace("\n", "\n" + " "*indent)
Helper to reindent a multi-line statement.
Helper to reindent a multi-line statement.
[ "Helper", "to", "reindent", "a", "multi", "-", "line", "statement", "." ]
def reindent(src, indent): """Helper to reindent a multi-line statement.""" return src.replace("\n", "\n" + " "*indent)
[ "def", "reindent", "(", "src", ",", "indent", ")", ":", "return", "src", ".", "replace", "(", "\"\\n\"", ",", "\"\\n\"", "+", "\" \"", "*", "indent", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/timeit.py#L79-L81
MegEngine/MegEngine
ce9ad07a27ec909fb8db4dd67943d24ba98fb93a
imperative/python/megengine/module/quantized/module.py
python
QuantizedModule.from_qat_module
(cls, qat_module: QATModule)
r""" Return a :class:`~.QATModule` instance converted from a float :class:`~.Module` instance.
r""" Return a :class:`~.QATModule` instance converted from a float :class:`~.Module` instance.
[ "r", "Return", "a", ":", "class", ":", "~", ".", "QATModule", "instance", "converted", "from", "a", "float", ":", "class", ":", "~", ".", "Module", "instance", "." ]
def from_qat_module(cls, qat_module: QATModule): r""" Return a :class:`~.QATModule` instance converted from a float :class:`~.Module` instance. """
[ "def", "from_qat_module", "(", "cls", ",", "qat_module", ":", "QATModule", ")", ":" ]
https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/module/quantized/module.py#L29-L33
Illumina/strelka
d7377443b62319f7c7bd70c241c4b2df3459e29a
src/python/deNovoQualityScore/denovo.py
python
is_in_regions
(variant, regions=None, chrom=None)
return False
Check if the variant is located within the annotated regions
Check if the variant is located within the annotated regions
[ "Check", "if", "the", "variant", "is", "located", "within", "the", "annotated", "regions" ]
def is_in_regions(variant, regions=None, chrom=None): """Check if the variant is located within the annotated regions""" if chrom is None: chrom = variant.CHROM.lstrip('chr') if regions and chrom in regions: for coords in regions[chrom]: if variant.POS >= coords[0] and variant.POS <= coords[1]: return True return False
[ "def", "is_in_regions", "(", "variant", ",", "regions", "=", "None", ",", "chrom", "=", "None", ")", ":", "if", "chrom", "is", "None", ":", "chrom", "=", "variant", ".", "CHROM", ".", "lstrip", "(", "'chr'", ")", "if", "regions", "and", "chrom", "in", "regions", ":", "for", "coords", "in", "regions", "[", "chrom", "]", ":", "if", "variant", ".", "POS", ">=", "coords", "[", "0", "]", "and", "variant", ".", "POS", "<=", "coords", "[", "1", "]", ":", "return", "True", "return", "False" ]
https://github.com/Illumina/strelka/blob/d7377443b62319f7c7bd70c241c4b2df3459e29a/src/python/deNovoQualityScore/denovo.py#L1021-L1032
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/parso/py3/parso/python/diff.py
python
DiffParser._parse
(self, until_line)
Parses at least until the given line, but might just parse more until a valid state is reached.
Parses at least until the given line, but might just parse more until a valid state is reached.
[ "Parses", "at", "least", "until", "the", "given", "line", "but", "might", "just", "parse", "more", "until", "a", "valid", "state", "is", "reached", "." ]
def _parse(self, until_line): """ Parses at least until the given line, but might just parse more until a valid state is reached. """ last_until_line = 0 while until_line > self._nodes_tree.parsed_until_line: node = self._try_parse_part(until_line) nodes = node.children self._nodes_tree.add_parsed_nodes(nodes, self._keyword_token_indents) if self._replace_tos_indent is not None: self._nodes_tree.indents[-1] = self._replace_tos_indent LOG.debug( 'parse_part from %s to %s (to %s in part parser)', nodes[0].get_start_pos_of_prefix()[0], self._nodes_tree.parsed_until_line, node.end_pos[0] - 1 ) # Since the tokenizer sometimes has bugs, we cannot be sure that # this loop terminates. Therefore assert that there's always a # change. assert last_until_line != self._nodes_tree.parsed_until_line, last_until_line last_until_line = self._nodes_tree.parsed_until_line
[ "def", "_parse", "(", "self", ",", "until_line", ")", ":", "last_until_line", "=", "0", "while", "until_line", ">", "self", ".", "_nodes_tree", ".", "parsed_until_line", ":", "node", "=", "self", ".", "_try_parse_part", "(", "until_line", ")", "nodes", "=", "node", ".", "children", "self", ".", "_nodes_tree", ".", "add_parsed_nodes", "(", "nodes", ",", "self", ".", "_keyword_token_indents", ")", "if", "self", ".", "_replace_tos_indent", "is", "not", "None", ":", "self", ".", "_nodes_tree", ".", "indents", "[", "-", "1", "]", "=", "self", ".", "_replace_tos_indent", "LOG", ".", "debug", "(", "'parse_part from %s to %s (to %s in part parser)'", ",", "nodes", "[", "0", "]", ".", "get_start_pos_of_prefix", "(", ")", "[", "0", "]", ",", "self", ".", "_nodes_tree", ".", "parsed_until_line", ",", "node", ".", "end_pos", "[", "0", "]", "-", "1", ")", "# Since the tokenizer sometimes has bugs, we cannot be sure that", "# this loop terminates. Therefore assert that there's always a", "# change.", "assert", "last_until_line", "!=", "self", ".", "_nodes_tree", ".", "parsed_until_line", ",", "last_until_line", "last_until_line", "=", "self", ".", "_nodes_tree", ".", "parsed_until_line" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/parso/py3/parso/python/diff.py#L407-L431