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
apache/parquet-cpp
642da055adf009652689b20e68a198cffb857651
build-support/cpplint.py
python
_CppLintState.BackupFilters
(self)
Saves the current filter list to backup storage.
Saves the current filter list to backup storage.
[ "Saves", "the", "current", "filter", "list", "to", "backup", "storage", "." ]
def BackupFilters(self): """ Saves the current filter list to backup storage.""" self._filters_backup = self.filters[:]
[ "def", "BackupFilters", "(", "self", ")", ":", "self", ".", "_filters_backup", "=", "self", ".", "filters", "[", ":", "]" ]
https://github.com/apache/parquet-cpp/blob/642da055adf009652689b20e68a198cffb857651/build-support/cpplint.py#L818-L820
msftguy/ssh-rd
a5f3a79daeac5844edebf01916c9613563f1c390
_3rd/boost_1_48_0/tools/build/v2/build/generators.py
python
override
(overrider_id, overridee_id)
Make generator 'overrider-id' be preferred to 'overridee-id'. If, when searching for generators that could produce a target of certain type, both those generators are amoung viable generators, the overridden generator is immediately discarded. The overridden generators are discarded immediately after computing the list of viable generators, before running any of them.
Make generator 'overrider-id' be preferred to 'overridee-id'. If, when searching for generators that could produce a target of certain type, both those generators are amoung viable generators, the overridden generator is immediately discarded. The overridden generators are discarded immediately after computing the list of viable generators, before running any of them.
[ "Make", "generator", "overrider", "-", "id", "be", "preferred", "to", "overridee", "-", "id", ".", "If", "when", "searching", "for", "generators", "that", "could", "produce", "a", "target", "of", "certain", "type", "both", "those", "generators", "are", "amoung", "viable", "generators", "the", "overridden", "generator", "is", "immediately", "discarded", ".", "The", "overridden", "generators", "are", "discarded", "immediately", "after", "computing", "the", "list", "of", "viable", "generators", "before", "running", "any", "of", "them", "." ]
def override (overrider_id, overridee_id): """Make generator 'overrider-id' be preferred to 'overridee-id'. If, when searching for generators that could produce a target of certain type, both those generators are amoung viable generators, the overridden generator is immediately discarded. The overridden generators are discarded immediately after computing the list of viable generators, before running any of them.""" __overrides.get(overrider_id, []).append(overridee_id)
[ "def", "override", "(", "overrider_id", ",", "overridee_id", ")", ":", "__overrides", ".", "get", "(", "overrider_id", ",", "[", "]", ")", ".", "append", "(", "overridee_id", ")" ]
https://github.com/msftguy/ssh-rd/blob/a5f3a79daeac5844edebf01916c9613563f1c390/_3rd/boost_1_48_0/tools/build/v2/build/generators.py#L684-L695
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_controls.py
python
TreeCtrl.IsBold
(*args, **kwargs)
return _controls_.TreeCtrl_IsBold(*args, **kwargs)
IsBold(self, TreeItemId item) -> bool
IsBold(self, TreeItemId item) -> bool
[ "IsBold", "(", "self", "TreeItemId", "item", ")", "-", ">", "bool" ]
def IsBold(*args, **kwargs): """IsBold(self, TreeItemId item) -> bool""" return _controls_.TreeCtrl_IsBold(*args, **kwargs)
[ "def", "IsBold", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "TreeCtrl_IsBold", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L5347-L5349
glotzerlab/hoomd-blue
f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a
hoomd/data/syncedlist.py
python
identity
(obj)
return obj
Returns obj.
Returns obj.
[ "Returns", "obj", "." ]
def identity(obj): """Returns obj.""" return obj
[ "def", "identity", "(", "obj", ")", ":", "return", "obj" ]
https://github.com/glotzerlab/hoomd-blue/blob/f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a/hoomd/data/syncedlist.py#L39-L41
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/indexes/base.py
python
Index.set_names
(self, names, level=None, inplace=False)
Set Index or MultiIndex name. Able to set new names partially and by level. Parameters ---------- names : label or list of label Name(s) to set. level : int, label or list of int or label, optional If the index is a MultiIndex, level(s) to set (None for all levels). Otherwise level must be None. inplace : bool, default False Modifies the object directly, instead of creating a new Index or MultiIndex. Returns ------- Index The same type as the caller or None if inplace is True. See Also -------- Index.rename : Able to set new names without level. Examples -------- >>> idx = pd.Index([1, 2, 3, 4]) >>> idx Int64Index([1, 2, 3, 4], dtype='int64') >>> idx.set_names('quarter') Int64Index([1, 2, 3, 4], dtype='int64', name='quarter') >>> idx = pd.MultiIndex.from_product([['python', 'cobra'], ... [2018, 2019]]) >>> idx MultiIndex([('python', 2018), ('python', 2019), ( 'cobra', 2018), ( 'cobra', 2019)], ) >>> idx.set_names(['kind', 'year'], inplace=True) >>> idx MultiIndex([('python', 2018), ('python', 2019), ( 'cobra', 2018), ( 'cobra', 2019)], names=['kind', 'year']) >>> idx.set_names('species', level=0) MultiIndex([('python', 2018), ('python', 2019), ( 'cobra', 2018), ( 'cobra', 2019)], names=['species', 'year'])
Set Index or MultiIndex name.
[ "Set", "Index", "or", "MultiIndex", "name", "." ]
def set_names(self, names, level=None, inplace=False): """ Set Index or MultiIndex name. Able to set new names partially and by level. Parameters ---------- names : label or list of label Name(s) to set. level : int, label or list of int or label, optional If the index is a MultiIndex, level(s) to set (None for all levels). Otherwise level must be None. inplace : bool, default False Modifies the object directly, instead of creating a new Index or MultiIndex. Returns ------- Index The same type as the caller or None if inplace is True. See Also -------- Index.rename : Able to set new names without level. Examples -------- >>> idx = pd.Index([1, 2, 3, 4]) >>> idx Int64Index([1, 2, 3, 4], dtype='int64') >>> idx.set_names('quarter') Int64Index([1, 2, 3, 4], dtype='int64', name='quarter') >>> idx = pd.MultiIndex.from_product([['python', 'cobra'], ... [2018, 2019]]) >>> idx MultiIndex([('python', 2018), ('python', 2019), ( 'cobra', 2018), ( 'cobra', 2019)], ) >>> idx.set_names(['kind', 'year'], inplace=True) >>> idx MultiIndex([('python', 2018), ('python', 2019), ( 'cobra', 2018), ( 'cobra', 2019)], names=['kind', 'year']) >>> idx.set_names('species', level=0) MultiIndex([('python', 2018), ('python', 2019), ( 'cobra', 2018), ( 'cobra', 2019)], names=['species', 'year']) """ if level is not None and not isinstance(self, ABCMultiIndex): raise ValueError("Level must be None for non-MultiIndex") if level is not None and not is_list_like(level) and is_list_like(names): raise TypeError("Names must be a string when a single level is provided.") if not is_list_like(names) and level is None and self.nlevels > 1: raise TypeError("Must pass list-like as `names`.") if not is_list_like(names): names = [names] if level is not None and not is_list_like(level): level = [level] if inplace: idx = self else: idx = self._shallow_copy() idx._set_names(names, level=level) if not inplace: return idx
[ "def", "set_names", "(", "self", ",", "names", ",", "level", "=", "None", ",", "inplace", "=", "False", ")", ":", "if", "level", "is", "not", "None", "and", "not", "isinstance", "(", "self", ",", "ABCMultiIndex", ")", ":", "raise", "ValueError", "(", "\"Level must be None for non-MultiIndex\"", ")", "if", "level", "is", "not", "None", "and", "not", "is_list_like", "(", "level", ")", "and", "is_list_like", "(", "names", ")", ":", "raise", "TypeError", "(", "\"Names must be a string when a single level is provided.\"", ")", "if", "not", "is_list_like", "(", "names", ")", "and", "level", "is", "None", "and", "self", ".", "nlevels", ">", "1", ":", "raise", "TypeError", "(", "\"Must pass list-like as `names`.\"", ")", "if", "not", "is_list_like", "(", "names", ")", ":", "names", "=", "[", "names", "]", "if", "level", "is", "not", "None", "and", "not", "is_list_like", "(", "level", ")", ":", "level", "=", "[", "level", "]", "if", "inplace", ":", "idx", "=", "self", "else", ":", "idx", "=", "self", ".", "_shallow_copy", "(", ")", "idx", ".", "_set_names", "(", "names", ",", "level", "=", "level", ")", "if", "not", "inplace", ":", "return", "idx" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/indexes/base.py#L1250-L1327
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/functools.py
python
_c3_mro
(cls, abcs=None)
return _c3_merge( [[cls]] + explicit_c3_mros + abstract_c3_mros + other_c3_mros + [explicit_bases] + [abstract_bases] + [other_bases] )
Computes the method resolution order using extended C3 linearization. If no *abcs* are given, the algorithm works exactly like the built-in C3 linearization used for method resolution. If given, *abcs* is a list of abstract base classes that should be inserted into the resulting MRO. Unrelated ABCs are ignored and don't end up in the result. The algorithm inserts ABCs where their functionality is introduced, i.e. issubclass(cls, abc) returns True for the class itself but returns False for all its direct base classes. Implicit ABCs for a given class (either registered or inferred from the presence of a special method like __len__) are inserted directly after the last ABC explicitly listed in the MRO of said class. If two implicit ABCs end up next to each other in the resulting MRO, their ordering depends on the order of types in *abcs*.
Computes the method resolution order using extended C3 linearization.
[ "Computes", "the", "method", "resolution", "order", "using", "extended", "C3", "linearization", "." ]
def _c3_mro(cls, abcs=None): """Computes the method resolution order using extended C3 linearization. If no *abcs* are given, the algorithm works exactly like the built-in C3 linearization used for method resolution. If given, *abcs* is a list of abstract base classes that should be inserted into the resulting MRO. Unrelated ABCs are ignored and don't end up in the result. The algorithm inserts ABCs where their functionality is introduced, i.e. issubclass(cls, abc) returns True for the class itself but returns False for all its direct base classes. Implicit ABCs for a given class (either registered or inferred from the presence of a special method like __len__) are inserted directly after the last ABC explicitly listed in the MRO of said class. If two implicit ABCs end up next to each other in the resulting MRO, their ordering depends on the order of types in *abcs*. """ for i, base in enumerate(reversed(cls.__bases__)): if hasattr(base, '__abstractmethods__'): boundary = len(cls.__bases__) - i break # Bases up to the last explicit ABC are considered first. else: boundary = 0 abcs = list(abcs) if abcs else [] explicit_bases = list(cls.__bases__[:boundary]) abstract_bases = [] other_bases = list(cls.__bases__[boundary:]) for base in abcs: if issubclass(cls, base) and not any( issubclass(b, base) for b in cls.__bases__ ): # If *cls* is the class that introduces behaviour described by # an ABC *base*, insert said ABC to its MRO. abstract_bases.append(base) for base in abstract_bases: abcs.remove(base) explicit_c3_mros = [_c3_mro(base, abcs=abcs) for base in explicit_bases] abstract_c3_mros = [_c3_mro(base, abcs=abcs) for base in abstract_bases] other_c3_mros = [_c3_mro(base, abcs=abcs) for base in other_bases] return _c3_merge( [[cls]] + explicit_c3_mros + abstract_c3_mros + other_c3_mros + [explicit_bases] + [abstract_bases] + [other_bases] )
[ "def", "_c3_mro", "(", "cls", ",", "abcs", "=", "None", ")", ":", "for", "i", ",", "base", "in", "enumerate", "(", "reversed", "(", "cls", ".", "__bases__", ")", ")", ":", "if", "hasattr", "(", "base", ",", "'__abstractmethods__'", ")", ":", "boundary", "=", "len", "(", "cls", ".", "__bases__", ")", "-", "i", "break", "# Bases up to the last explicit ABC are considered first.", "else", ":", "boundary", "=", "0", "abcs", "=", "list", "(", "abcs", ")", "if", "abcs", "else", "[", "]", "explicit_bases", "=", "list", "(", "cls", ".", "__bases__", "[", ":", "boundary", "]", ")", "abstract_bases", "=", "[", "]", "other_bases", "=", "list", "(", "cls", ".", "__bases__", "[", "boundary", ":", "]", ")", "for", "base", "in", "abcs", ":", "if", "issubclass", "(", "cls", ",", "base", ")", "and", "not", "any", "(", "issubclass", "(", "b", ",", "base", ")", "for", "b", "in", "cls", ".", "__bases__", ")", ":", "# If *cls* is the class that introduces behaviour described by", "# an ABC *base*, insert said ABC to its MRO.", "abstract_bases", ".", "append", "(", "base", ")", "for", "base", "in", "abstract_bases", ":", "abcs", ".", "remove", "(", "base", ")", "explicit_c3_mros", "=", "[", "_c3_mro", "(", "base", ",", "abcs", "=", "abcs", ")", "for", "base", "in", "explicit_bases", "]", "abstract_c3_mros", "=", "[", "_c3_mro", "(", "base", ",", "abcs", "=", "abcs", ")", "for", "base", "in", "abstract_bases", "]", "other_c3_mros", "=", "[", "_c3_mro", "(", "base", ",", "abcs", "=", "abcs", ")", "for", "base", "in", "other_bases", "]", "return", "_c3_merge", "(", "[", "[", "cls", "]", "]", "+", "explicit_c3_mros", "+", "abstract_c3_mros", "+", "other_c3_mros", "+", "[", "explicit_bases", "]", "+", "[", "abstract_bases", "]", "+", "[", "other_bases", "]", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/functools.py#L651-L694
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/CGIHTTPServer.py
python
executable
(path)
return st.st_mode & 0111 != 0
Test for executable file.
Test for executable file.
[ "Test", "for", "executable", "file", "." ]
def executable(path): """Test for executable file.""" try: st = os.stat(path) except os.error: return False return st.st_mode & 0111 != 0
[ "def", "executable", "(", "path", ")", ":", "try", ":", "st", "=", "os", ".", "stat", "(", "path", ")", "except", "os", ".", "error", ":", "return", "False", "return", "st", ".", "st_mode", "&", "0111", "!=", "0" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/CGIHTTPServer.py#L363-L369
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/debug/local_cli.py
python
LocalCLIDebugWrapperSession._on_run_start_step_handler
(self, args, screen_info=None)
return debugger_cli_common.RichTextLines([], annotations=annotations)
Command handler for "invoke_stepper" command during on-run-start.
Command handler for "invoke_stepper" command during on-run-start.
[ "Command", "handler", "for", "invoke_stepper", "command", "during", "on", "-", "run", "-", "start", "." ]
def _on_run_start_step_handler(self, args, screen_info=None): """Command handler for "invoke_stepper" command during on-run-start.""" _ = screen_info # Currently unused. # No parsing is currently necessary for invoke_stepper. This may change # in the future when the command has arguments. action = framework.OnRunStartAction.INVOKE_STEPPER annotations = { debugger_cli_common.EXIT_TOKEN_KEY: framework.OnRunStartResponse(action, []) } return debugger_cli_common.RichTextLines([], annotations=annotations)
[ "def", "_on_run_start_step_handler", "(", "self", ",", "args", ",", "screen_info", "=", "None", ")", ":", "_", "=", "screen_info", "# Currently unused.", "# No parsing is currently necessary for invoke_stepper. This may change", "# in the future when the command has arguments.", "action", "=", "framework", ".", "OnRunStartAction", ".", "INVOKE_STEPPER", "annotations", "=", "{", "debugger_cli_common", ".", "EXIT_TOKEN_KEY", ":", "framework", ".", "OnRunStartResponse", "(", "action", ",", "[", "]", ")", "}", "return", "debugger_cli_common", ".", "RichTextLines", "(", "[", "]", ",", "annotations", "=", "annotations", ")" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/debug/local_cli.py#L374-L388
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/neural_network/_multilayer_perceptron.py
python
MLPClassifier.predict
(self, X)
return self._label_binarizer.inverse_transform(y_pred)
Predict using the multi-layer perceptron classifier Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input data. Returns ------- y : ndarray, shape (n_samples,) or (n_samples, n_classes) The predicted classes.
Predict using the multi-layer perceptron classifier
[ "Predict", "using", "the", "multi", "-", "layer", "perceptron", "classifier" ]
def predict(self, X): """Predict using the multi-layer perceptron classifier Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input data. Returns ------- y : ndarray, shape (n_samples,) or (n_samples, n_classes) The predicted classes. """ check_is_fitted(self) y_pred = self._predict(X) if self.n_outputs_ == 1: y_pred = y_pred.ravel() return self._label_binarizer.inverse_transform(y_pred)
[ "def", "predict", "(", "self", ",", "X", ")", ":", "check_is_fitted", "(", "self", ")", "y_pred", "=", "self", ".", "_predict", "(", "X", ")", "if", "self", ".", "n_outputs_", "==", "1", ":", "y_pred", "=", "y_pred", ".", "ravel", "(", ")", "return", "self", ".", "_label_binarizer", ".", "inverse_transform", "(", "y_pred", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/neural_network/_multilayer_perceptron.py#L957-L976
tensorflow/deepmath
b5b721f54de1d5d6a02d78f5da5995237f9995f9
deepmath/deephol/theorem_fingerprint.py
python
ToTacticArgument
(theorem)
return 'THM %d' % Fingerprint(theorem)
Return a representation of the theorem as a tactic argument label. Args: theorem: proof_assistant_pb2.Theorem object Returns: String that can be used as a tactic argument.
Return a representation of the theorem as a tactic argument label.
[ "Return", "a", "representation", "of", "the", "theorem", "as", "a", "tactic", "argument", "label", "." ]
def ToTacticArgument(theorem): """Return a representation of the theorem as a tactic argument label. Args: theorem: proof_assistant_pb2.Theorem object Returns: String that can be used as a tactic argument. """ return 'THM %d' % Fingerprint(theorem)
[ "def", "ToTacticArgument", "(", "theorem", ")", ":", "return", "'THM %d'", "%", "Fingerprint", "(", "theorem", ")" ]
https://github.com/tensorflow/deepmath/blob/b5b721f54de1d5d6a02d78f5da5995237f9995f9/deepmath/deephol/theorem_fingerprint.py#L61-L70
apiaryio/drafter
4634ebd07f6c6f257cc656598ccd535492fdfb55
tools/gyp/pylib/gyp/msvs_emulation.py
python
ExpandMacros
(string, expansions)
return string
Expand $(Variable) per expansions dict. See MsvsSettings.GetVSMacroEnv for the canonical way to retrieve a suitable dict.
Expand $(Variable) per expansions dict. See MsvsSettings.GetVSMacroEnv for the canonical way to retrieve a suitable dict.
[ "Expand", "$", "(", "Variable", ")", "per", "expansions", "dict", ".", "See", "MsvsSettings", ".", "GetVSMacroEnv", "for", "the", "canonical", "way", "to", "retrieve", "a", "suitable", "dict", "." ]
def ExpandMacros(string, expansions): """Expand $(Variable) per expansions dict. See MsvsSettings.GetVSMacroEnv for the canonical way to retrieve a suitable dict.""" if '$' in string: for old, new in expansions.iteritems(): assert '$(' not in new, new string = string.replace(old, new) return string
[ "def", "ExpandMacros", "(", "string", ",", "expansions", ")", ":", "if", "'$'", "in", "string", ":", "for", "old", ",", "new", "in", "expansions", ".", "iteritems", "(", ")", ":", "assert", "'$('", "not", "in", "new", ",", "new", "string", "=", "string", ".", "replace", "(", "old", ",", "new", ")", "return", "string" ]
https://github.com/apiaryio/drafter/blob/4634ebd07f6c6f257cc656598ccd535492fdfb55/tools/gyp/pylib/gyp/msvs_emulation.py#L940-L947
BitMEX/api-connectors
37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812
auto-generated/python/swagger_client/models/position.py
python
Position.opening_qty
(self)
return self._opening_qty
Gets the opening_qty of this Position. # noqa: E501 :return: The opening_qty of this Position. # noqa: E501 :rtype: float
Gets the opening_qty of this Position. # noqa: E501
[ "Gets", "the", "opening_qty", "of", "this", "Position", ".", "#", "noqa", ":", "E501" ]
def opening_qty(self): """Gets the opening_qty of this Position. # noqa: E501 :return: The opening_qty of this Position. # noqa: E501 :rtype: float """ return self._opening_qty
[ "def", "opening_qty", "(", "self", ")", ":", "return", "self", ".", "_opening_qty" ]
https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/position.py#L861-L868
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/package_index.py
python
parse_bdist_wininst
(name)
return base, py_ver, plat
Return (base,pyversion) or (None,None) for possible .exe name
Return (base,pyversion) or (None,None) for possible .exe name
[ "Return", "(", "base", "pyversion", ")", "or", "(", "None", "None", ")", "for", "possible", ".", "exe", "name" ]
def parse_bdist_wininst(name): """Return (base,pyversion) or (None,None) for possible .exe name""" lower = name.lower() base, py_ver, plat = None, None, None if lower.endswith('.exe'): if lower.endswith('.win32.exe'): base = name[:-10] plat = 'win32' elif lower.startswith('.win32-py', -16): py_ver = name[-7:-4] base = name[:-16] plat = 'win32' elif lower.endswith('.win-amd64.exe'): base = name[:-14] plat = 'win-amd64' elif lower.startswith('.win-amd64-py', -20): py_ver = name[-7:-4] base = name[:-20] plat = 'win-amd64' return base, py_ver, plat
[ "def", "parse_bdist_wininst", "(", "name", ")", ":", "lower", "=", "name", ".", "lower", "(", ")", "base", ",", "py_ver", ",", "plat", "=", "None", ",", "None", ",", "None", "if", "lower", ".", "endswith", "(", "'.exe'", ")", ":", "if", "lower", ".", "endswith", "(", "'.win32.exe'", ")", ":", "base", "=", "name", "[", ":", "-", "10", "]", "plat", "=", "'win32'", "elif", "lower", ".", "startswith", "(", "'.win32-py'", ",", "-", "16", ")", ":", "py_ver", "=", "name", "[", "-", "7", ":", "-", "4", "]", "base", "=", "name", "[", ":", "-", "16", "]", "plat", "=", "'win32'", "elif", "lower", ".", "endswith", "(", "'.win-amd64.exe'", ")", ":", "base", "=", "name", "[", ":", "-", "14", "]", "plat", "=", "'win-amd64'", "elif", "lower", ".", "startswith", "(", "'.win-amd64-py'", ",", "-", "20", ")", ":", "py_ver", "=", "name", "[", "-", "7", ":", "-", "4", "]", "base", "=", "name", "[", ":", "-", "20", "]", "plat", "=", "'win-amd64'", "return", "base", ",", "py_ver", ",", "plat" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/package_index.py#L62-L83
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py
python
URLopener.open_data
(self, url, data=None)
return addinfourl(f, headers, url)
Use "data" URL.
Use "data" URL.
[ "Use", "data", "URL", "." ]
def open_data(self, url, data=None): """Use "data" URL.""" if not isinstance(url, str): raise URLError('data error: proxy support for data protocol currently not implemented') # ignore POSTed data # # syntax of data URLs: # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data # mediatype := [ type "/" subtype ] *( ";" parameter ) # data := *urlchar # parameter := attribute "=" value try: [type, data] = url.split(',', 1) except ValueError: raise OSError('data error', 'bad data URL') if not type: type = 'text/plain;charset=US-ASCII' semi = type.rfind(';') if semi >= 0 and '=' not in type[semi:]: encoding = type[semi+1:] type = type[:semi] else: encoding = '' msg = [] msg.append('Date: %s'%time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(time.time()))) msg.append('Content-type: %s' % type) if encoding == 'base64': # XXX is this encoding/decoding ok? data = base64.decodebytes(data.encode('ascii')).decode('latin-1') else: data = unquote(data) msg.append('Content-Length: %d' % len(data)) msg.append('') msg.append(data) msg = '\n'.join(msg) headers = email.message_from_string(msg) f = io.StringIO(msg) #f.fileno = None # needed for addinfourl return addinfourl(f, headers, url)
[ "def", "open_data", "(", "self", ",", "url", ",", "data", "=", "None", ")", ":", "if", "not", "isinstance", "(", "url", ",", "str", ")", ":", "raise", "URLError", "(", "'data error: proxy support for data protocol currently not implemented'", ")", "# ignore POSTed data", "#", "# syntax of data URLs:", "# dataurl := \"data:\" [ mediatype ] [ \";base64\" ] \",\" data", "# mediatype := [ type \"/\" subtype ] *( \";\" parameter )", "# data := *urlchar", "# parameter := attribute \"=\" value", "try", ":", "[", "type", ",", "data", "]", "=", "url", ".", "split", "(", "','", ",", "1", ")", "except", "ValueError", ":", "raise", "OSError", "(", "'data error'", ",", "'bad data URL'", ")", "if", "not", "type", ":", "type", "=", "'text/plain;charset=US-ASCII'", "semi", "=", "type", ".", "rfind", "(", "';'", ")", "if", "semi", ">=", "0", "and", "'='", "not", "in", "type", "[", "semi", ":", "]", ":", "encoding", "=", "type", "[", "semi", "+", "1", ":", "]", "type", "=", "type", "[", ":", "semi", "]", "else", ":", "encoding", "=", "''", "msg", "=", "[", "]", "msg", ".", "append", "(", "'Date: %s'", "%", "time", ".", "strftime", "(", "'%a, %d %b %Y %H:%M:%S GMT'", ",", "time", ".", "gmtime", "(", "time", ".", "time", "(", ")", ")", ")", ")", "msg", ".", "append", "(", "'Content-type: %s'", "%", "type", ")", "if", "encoding", "==", "'base64'", ":", "# XXX is this encoding/decoding ok?", "data", "=", "base64", ".", "decodebytes", "(", "data", ".", "encode", "(", "'ascii'", ")", ")", ".", "decode", "(", "'latin-1'", ")", "else", ":", "data", "=", "unquote", "(", "data", ")", "msg", ".", "append", "(", "'Content-Length: %d'", "%", "len", "(", "data", ")", ")", "msg", ".", "append", "(", "''", ")", "msg", ".", "append", "(", "data", ")", "msg", "=", "'\\n'", ".", "join", "(", "msg", ")", "headers", "=", "email", ".", "message_from_string", "(", "msg", ")", "f", "=", "io", ".", "StringIO", "(", "msg", ")", "#f.fileno = None # needed for addinfourl", "return", "addinfourl", "(", "f", ",", "headers", ",", "url", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py#L2099-L2138
r45635/HVAC-IR-Control
4b6b7944b28ce78247f19744c272a36935bbb305
python/hvac_ircontrol/mitsubishi.py
python
Mitsubishi.power_off
(self)
power_off
power_off
[ "power_off" ]
def power_off(self): """ power_off """ self.__send_command( ClimateMode.Auto, 21, FanMode.Auto, VanneVerticalMode.Auto, VanneHorizontalMode.Swing, ISeeMode.ISeeOff, AreaMode.NotSet, None, None, PowerfulMode.PowerfulOff, PowerMode.PowerOff)
[ "def", "power_off", "(", "self", ")", ":", "self", ".", "__send_command", "(", "ClimateMode", ".", "Auto", ",", "21", ",", "FanMode", ".", "Auto", ",", "VanneVerticalMode", ".", "Auto", ",", "VanneHorizontalMode", ".", "Swing", ",", "ISeeMode", ".", "ISeeOff", ",", "AreaMode", ".", "NotSet", ",", "None", ",", "None", ",", "PowerfulMode", ".", "PowerfulOff", ",", "PowerMode", ".", "PowerOff", ")" ]
https://github.com/r45635/HVAC-IR-Control/blob/4b6b7944b28ce78247f19744c272a36935bbb305/python/hvac_ircontrol/mitsubishi.py#L168-L183
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/valgrind/gdb_helper.py
python
AddressTable.Add
(self, binary, address)
Register a lookup request.
Register a lookup request.
[ "Register", "a", "lookup", "request", "." ]
def Add(self, binary, address): ''' Register a lookup request. ''' if binary == '': logging.warn('adding address %s in empty binary?' % address) if binary in self._binaries: self._binaries[binary].append(address) else: self._binaries[binary] = [address] self._all_resolved = False
[ "def", "Add", "(", "self", ",", "binary", ",", "address", ")", ":", "if", "binary", "==", "''", ":", "logging", ".", "warn", "(", "'adding address %s in empty binary?'", "%", "address", ")", "if", "binary", "in", "self", ".", "_binaries", ":", "self", ".", "_binaries", "[", "binary", "]", ".", "append", "(", "address", ")", "else", ":", "self", ".", "_binaries", "[", "binary", "]", "=", "[", "address", "]", "self", ".", "_all_resolved", "=", "False" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/valgrind/gdb_helper.py#L58-L66
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/email/generator.py
python
DecodedGenerator.__init__
(self, outfp, mangle_from_=True, maxheaderlen=78, fmt=None)
Like Generator.__init__() except that an additional optional argument is allowed. Walks through all subparts of a message. If the subpart is of main type `text', then it prints the decoded payload of the subpart. Otherwise, fmt is a format string that is used instead of the message payload. fmt is expanded with the following keywords (in %(keyword)s format): type : Full MIME type of the non-text part maintype : Main MIME type of the non-text part subtype : Sub-MIME type of the non-text part filename : Filename of the non-text part description: Description associated with the non-text part encoding : Content transfer encoding of the non-text part The default value for fmt is None, meaning [Non-text (%(type)s) part of message omitted, filename %(filename)s]
Like Generator.__init__() except that an additional optional argument is allowed.
[ "Like", "Generator", ".", "__init__", "()", "except", "that", "an", "additional", "optional", "argument", "is", "allowed", "." ]
def __init__(self, outfp, mangle_from_=True, maxheaderlen=78, fmt=None): """Like Generator.__init__() except that an additional optional argument is allowed. Walks through all subparts of a message. If the subpart is of main type `text', then it prints the decoded payload of the subpart. Otherwise, fmt is a format string that is used instead of the message payload. fmt is expanded with the following keywords (in %(keyword)s format): type : Full MIME type of the non-text part maintype : Main MIME type of the non-text part subtype : Sub-MIME type of the non-text part filename : Filename of the non-text part description: Description associated with the non-text part encoding : Content transfer encoding of the non-text part The default value for fmt is None, meaning [Non-text (%(type)s) part of message omitted, filename %(filename)s] """ Generator.__init__(self, outfp, mangle_from_, maxheaderlen) if fmt is None: self._fmt = _FMT else: self._fmt = fmt
[ "def", "__init__", "(", "self", ",", "outfp", ",", "mangle_from_", "=", "True", ",", "maxheaderlen", "=", "78", ",", "fmt", "=", "None", ")", ":", "Generator", ".", "__init__", "(", "self", ",", "outfp", ",", "mangle_from_", ",", "maxheaderlen", ")", "if", "fmt", "is", "None", ":", "self", ".", "_fmt", "=", "_FMT", "else", ":", "self", ".", "_fmt", "=", "fmt" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/email/generator.py#L302-L328
htcondor/htcondor
4829724575176d1d6c936e4693dfd78a728569b0
bindings/python/htcondor/htchirp/htchirp.py
python
HTChirp.whoareyou
(self, remote_host)
return result
Get the server's identity with respect to the remote host. :param remote_host: Remote host :returns: The server's identity
Get the server's identity with respect to the remote host.
[ "Get", "the", "server", "s", "identity", "with", "respect", "to", "the", "remote", "host", "." ]
def whoareyou(self, remote_host): """Get the server's identity with respect to the remote host. :param remote_host: Remote host :returns: The server's identity """ length = int( self._simple_command( "whoareyou {0} {1}\n".format( quote(remote_host), self.__class__.CHIRP_LINE_MAX ) ) ) result = self._get_fixed_data(length).decode() return result
[ "def", "whoareyou", "(", "self", ",", "remote_host", ")", ":", "length", "=", "int", "(", "self", ".", "_simple_command", "(", "\"whoareyou {0} {1}\\n\"", ".", "format", "(", "quote", "(", "remote_host", ")", ",", "self", ".", "__class__", ".", "CHIRP_LINE_MAX", ")", ")", ")", "result", "=", "self", ".", "_get_fixed_data", "(", "length", ")", ".", "decode", "(", ")", "return", "result" ]
https://github.com/htcondor/htcondor/blob/4829724575176d1d6c936e4693dfd78a728569b0/bindings/python/htcondor/htchirp/htchirp.py#L1016-L1033
vgteam/vg
cf4d516a5e9ee5163c783e4437ddf16b18a4b561
scripts/giraffe-facts.py
python
Table.box
(self, part)
return skin[part]
Return the box-drawing character to draw the given part of a box. Parts are {(t)op, (m)iddle, (b)ottom} crossed with {(l)eft, (m)iddle, (r)ight} as two-character strings, plus (v)ertical and (h)orizontal as one-character strings.
Return the box-drawing character to draw the given part of a box. Parts are {(t)op, (m)iddle, (b)ottom} crossed with {(l)eft, (m)iddle, (r)ight} as two-character strings, plus (v)ertical and (h)orizontal as one-character strings.
[ "Return", "the", "box", "-", "drawing", "character", "to", "draw", "the", "given", "part", "of", "a", "box", ".", "Parts", "are", "{", "(", "t", ")", "op", "(", "m", ")", "iddle", "(", "b", ")", "ottom", "}", "crossed", "with", "{", "(", "l", ")", "eft", "(", "m", ")", "iddle", "(", "r", ")", "ight", "}", "as", "two", "-", "character", "strings", "plus", "(", "v", ")", "ertical", "and", "(", "h", ")", "orizontal", "as", "one", "-", "character", "strings", "." ]
def box(self, part): """ Return the box-drawing character to draw the given part of a box. Parts are {(t)op, (m)iddle, (b)ottom} crossed with {(l)eft, (m)iddle, (r)ight} as two-character strings, plus (v)ertical and (h)orizontal as one-character strings. """ skin = { 'tl': '┌', 'tm': '┬', 'tr': '┐', 'bl': '└', 'bm': '┴', 'br': '┘', 'ml': '├', 'mm': '┼', 'mr': '┤', 'v': '│', 'h': '─' } return skin[part]
[ "def", "box", "(", "self", ",", "part", ")", ":", "skin", "=", "{", "'tl'", ":", "'┌',", "", "'tm'", ":", "'┬',", "", "'tr'", ":", "'┐',", "", "'bl'", ":", "'└',", "", "'bm'", ":", "'┴',", "", "'br'", ":", "'┘',", "", "'ml'", ":", "'├',", "", "'mm'", ":", "'┼',", "", "'mr'", ":", "'┤',", "", "'v'", ":", "'│',", "", "'h'", ":", "'─'", "}", "return", "skin", "[", "part", "]" ]
https://github.com/vgteam/vg/blob/cf4d516a5e9ee5163c783e4437ddf16b18a4b561/scripts/giraffe-facts.py#L373-L394
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_windows.py
python
PrintPreview.GetCurrentPage
(*args, **kwargs)
return _windows_.PrintPreview_GetCurrentPage(*args, **kwargs)
GetCurrentPage(self) -> int
GetCurrentPage(self) -> int
[ "GetCurrentPage", "(", "self", ")", "-", ">", "int" ]
def GetCurrentPage(*args, **kwargs): """GetCurrentPage(self) -> int""" return _windows_.PrintPreview_GetCurrentPage(*args, **kwargs)
[ "def", "GetCurrentPage", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "PrintPreview_GetCurrentPage", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_windows.py#L5569-L5571
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/android/loading/user_satisfied_lens.py
python
_FirstEventLens.PostloadTimeMsec
(self)
return self._postload_msec
Override.
Override.
[ "Override", "." ]
def PostloadTimeMsec(self): """Override.""" return self._postload_msec
[ "def", "PostloadTimeMsec", "(", "self", ")", ":", "return", "self", ".", "_postload_msec" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/android/loading/user_satisfied_lens.py#L142-L144
FEniCS/dolfinx
3dfdf038cccdb70962865b58a63bf29c2e55ec6e
python/dolfinx/io.py
python
XDMFFile.write_mesh
(self, mesh: Mesh)
Write mesh to file for a given time (default 0.0)
Write mesh to file for a given time (default 0.0)
[ "Write", "mesh", "to", "file", "for", "a", "given", "time", "(", "default", "0", ".", "0", ")" ]
def write_mesh(self, mesh: Mesh) -> None: """Write mesh to file for a given time (default 0.0)""" super().write_mesh(mesh)
[ "def", "write_mesh", "(", "self", ",", "mesh", ":", "Mesh", ")", "->", "None", ":", "super", "(", ")", ".", "write_mesh", "(", "mesh", ")" ]
https://github.com/FEniCS/dolfinx/blob/3dfdf038cccdb70962865b58a63bf29c2e55ec6e/python/dolfinx/io.py#L46-L48
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/distlib/_backport/tarfile.py
python
is_tarfile
(name)
Return True if name points to a tar archive that we are able to handle, else return False.
Return True if name points to a tar archive that we are able to handle, else return False.
[ "Return", "True", "if", "name", "points", "to", "a", "tar", "archive", "that", "we", "are", "able", "to", "handle", "else", "return", "False", "." ]
def is_tarfile(name): """Return True if name points to a tar archive that we are able to handle, else return False. """ try: t = open(name) t.close() return True except TarError: return False
[ "def", "is_tarfile", "(", "name", ")", ":", "try", ":", "t", "=", "open", "(", "name", ")", "t", ".", "close", "(", ")", "return", "True", "except", "TarError", ":", "return", "False" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/distlib/_backport/tarfile.py#L2595-L2604
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
chrome/app/policy/syntax_check_policy_template_json.py
python
PolicyTemplateChecker._CheckPolicyIDs
(self, policy_ids)
Checks a set of policy_ids to make sure it contains a continuous range of entries (i.e. no holes). Holes would not be a technical problem, but we want to ensure that nobody accidentally omits IDs.
Checks a set of policy_ids to make sure it contains a continuous range of entries (i.e. no holes). Holes would not be a technical problem, but we want to ensure that nobody accidentally omits IDs.
[ "Checks", "a", "set", "of", "policy_ids", "to", "make", "sure", "it", "contains", "a", "continuous", "range", "of", "entries", "(", "i", ".", "e", ".", "no", "holes", ")", ".", "Holes", "would", "not", "be", "a", "technical", "problem", "but", "we", "want", "to", "ensure", "that", "nobody", "accidentally", "omits", "IDs", "." ]
def _CheckPolicyIDs(self, policy_ids): ''' Checks a set of policy_ids to make sure it contains a continuous range of entries (i.e. no holes). Holes would not be a technical problem, but we want to ensure that nobody accidentally omits IDs. ''' for i in range(len(policy_ids)): if (i + 1) not in policy_ids: self._Error('No policy with id: %s' % (i + 1))
[ "def", "_CheckPolicyIDs", "(", "self", ",", "policy_ids", ")", ":", "for", "i", "in", "range", "(", "len", "(", "policy_ids", ")", ")", ":", "if", "(", "i", "+", "1", ")", "not", "in", "policy_ids", ":", "self", ".", "_Error", "(", "'No policy with id: %s'", "%", "(", "i", "+", "1", ")", ")" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/chrome/app/policy/syntax_check_policy_template_json.py#L104-L113
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_aarch64/python2.7/dist-packages/catkin_pkg/changelog.py
python
BulletList.__init__
(self, bullets=None, bullet_type=None)
:param bullets: ``list(MixedText)`` list of text bullets :param bullet_type: ``str`` either 'bullet' or 'enumerated'
:param bullets: ``list(MixedText)`` list of text bullets :param bullet_type: ``str`` either 'bullet' or 'enumerated'
[ ":", "param", "bullets", ":", "list", "(", "MixedText", ")", "list", "of", "text", "bullets", ":", "param", "bullet_type", ":", "str", "either", "bullet", "or", "enumerated" ]
def __init__(self, bullets=None, bullet_type=None): ''' :param bullets: ``list(MixedText)`` list of text bullets :param bullet_type: ``str`` either 'bullet' or 'enumerated' ''' bullet_type = 'bullet' if bullet_type is None else bullet_type if bullet_type not in ['bullet', 'enumerated']: raise RuntimeError("Invalid bullet type: '{0}'".format(bullet_type)) self.bullets = bullets or [] self.bullet_type = bullet_type
[ "def", "__init__", "(", "self", ",", "bullets", "=", "None", ",", "bullet_type", "=", "None", ")", ":", "bullet_type", "=", "'bullet'", "if", "bullet_type", "is", "None", "else", "bullet_type", "if", "bullet_type", "not", "in", "[", "'bullet'", ",", "'enumerated'", "]", ":", "raise", "RuntimeError", "(", "\"Invalid bullet type: '{0}'\"", ".", "format", "(", "bullet_type", ")", ")", "self", ".", "bullets", "=", "bullets", "or", "[", "]", "self", ".", "bullet_type", "=", "bullet_type" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_aarch64/python2.7/dist-packages/catkin_pkg/changelog.py#L313-L322
kushview/Element
1cc16380caa2ab79461246ba758b9de1f46db2a5
waflib/extras/clang_cross_common.py
python
clang_modifier_msvc
(conf)
Really basic setup to use clang in msvc mode. We actually don't really want to do a lot, even though clang is msvc compatible in this mode, that doesn't mean we're actually using msvc. It's probably the best to leave it to the user, we can assume msvc mode if the user uses the clang-cl frontend, but this module only concerns itself with the gcc-like frontend.
Really basic setup to use clang in msvc mode. We actually don't really want to do a lot, even though clang is msvc compatible in this mode, that doesn't mean we're actually using msvc. It's probably the best to leave it to the user, we can assume msvc mode if the user uses the clang-cl frontend, but this module only concerns itself with the gcc-like frontend.
[ "Really", "basic", "setup", "to", "use", "clang", "in", "msvc", "mode", ".", "We", "actually", "don", "t", "really", "want", "to", "do", "a", "lot", "even", "though", "clang", "is", "msvc", "compatible", "in", "this", "mode", "that", "doesn", "t", "mean", "we", "re", "actually", "using", "msvc", ".", "It", "s", "probably", "the", "best", "to", "leave", "it", "to", "the", "user", "we", "can", "assume", "msvc", "mode", "if", "the", "user", "uses", "the", "clang", "-", "cl", "frontend", "but", "this", "module", "only", "concerns", "itself", "with", "the", "gcc", "-", "like", "frontend", "." ]
def clang_modifier_msvc(conf): import os """ Really basic setup to use clang in msvc mode. We actually don't really want to do a lot, even though clang is msvc compatible in this mode, that doesn't mean we're actually using msvc. It's probably the best to leave it to the user, we can assume msvc mode if the user uses the clang-cl frontend, but this module only concerns itself with the gcc-like frontend. """ v = conf.env v.cprogram_PATTERN = '%s.exe' v.cshlib_PATTERN = '%s.dll' v.implib_PATTERN = '%s.lib' v.IMPLIB_ST = '-Wl,-IMPLIB:%s' v.SHLIB_MARKER = [] v.CFLAGS_cshlib = [] v.LINKFLAGS_cshlib = ['-Wl,-DLL'] v.cstlib_PATTERN = '%s.lib' v.STLIB_MARKER = [] del(v.AR) conf.find_program(['llvm-lib', 'lib'], var='AR') v.ARFLAGS = ['-nologo'] v.AR_TGT_F = ['-out:'] # Default to the linker supplied with llvm instead of link.exe or ld v.LINK_CC = v.CC + ['-fuse-ld=lld', '-nostdlib'] v.CCLNK_TGT_F = ['-o'] v.def_PATTERN = '-Wl,-def:%s' v.LINKFLAGS = [] v.LIB_ST = '-l%s' v.LIBPATH_ST = '-Wl,-LIBPATH:%s' v.STLIB_ST = '-l%s' v.STLIBPATH_ST = '-Wl,-LIBPATH:%s' CFLAGS_CRT_COMMON = [ '-Xclang', '--dependent-lib=oldnames', '-Xclang', '-fno-rtti-data', '-D_MT' ] v.CFLAGS_CRT_MULTITHREADED = CFLAGS_CRT_COMMON + [ '-Xclang', '-flto-visibility-public-std', '-Xclang', '--dependent-lib=libcmt', ] v.CXXFLAGS_CRT_MULTITHREADED = v.CFLAGS_CRT_MULTITHREADED v.CFLAGS_CRT_MULTITHREADED_DBG = CFLAGS_CRT_COMMON + [ '-D_DEBUG', '-Xclang', '-flto-visibility-public-std', '-Xclang', '--dependent-lib=libcmtd', ] v.CXXFLAGS_CRT_MULTITHREADED_DBG = v.CFLAGS_CRT_MULTITHREADED_DBG v.CFLAGS_CRT_MULTITHREADED_DLL = CFLAGS_CRT_COMMON + [ '-D_DLL', '-Xclang', '--dependent-lib=msvcrt' ] v.CXXFLAGS_CRT_MULTITHREADED_DLL = v.CFLAGS_CRT_MULTITHREADED_DLL v.CFLAGS_CRT_MULTITHREADED_DLL_DBG = CFLAGS_CRT_COMMON + [ '-D_DLL', '-D_DEBUG', '-Xclang', '--dependent-lib=msvcrtd', ] v.CXXFLAGS_CRT_MULTITHREADED_DLL_DBG = v.CFLAGS_CRT_MULTITHREADED_DLL_DBG
[ "def", "clang_modifier_msvc", "(", "conf", ")", ":", "import", "os", "v", "=", "conf", ".", "env", "v", ".", "cprogram_PATTERN", "=", "'%s.exe'", "v", ".", "cshlib_PATTERN", "=", "'%s.dll'", "v", ".", "implib_PATTERN", "=", "'%s.lib'", "v", ".", "IMPLIB_ST", "=", "'-Wl,-IMPLIB:%s'", "v", ".", "SHLIB_MARKER", "=", "[", "]", "v", ".", "CFLAGS_cshlib", "=", "[", "]", "v", ".", "LINKFLAGS_cshlib", "=", "[", "'-Wl,-DLL'", "]", "v", ".", "cstlib_PATTERN", "=", "'%s.lib'", "v", ".", "STLIB_MARKER", "=", "[", "]", "del", "(", "v", ".", "AR", ")", "conf", ".", "find_program", "(", "[", "'llvm-lib'", ",", "'lib'", "]", ",", "var", "=", "'AR'", ")", "v", ".", "ARFLAGS", "=", "[", "'-nologo'", "]", "v", ".", "AR_TGT_F", "=", "[", "'-out:'", "]", "# Default to the linker supplied with llvm instead of link.exe or ld", "v", ".", "LINK_CC", "=", "v", ".", "CC", "+", "[", "'-fuse-ld=lld'", ",", "'-nostdlib'", "]", "v", ".", "CCLNK_TGT_F", "=", "[", "'-o'", "]", "v", ".", "def_PATTERN", "=", "'-Wl,-def:%s'", "v", ".", "LINKFLAGS", "=", "[", "]", "v", ".", "LIB_ST", "=", "'-l%s'", "v", ".", "LIBPATH_ST", "=", "'-Wl,-LIBPATH:%s'", "v", ".", "STLIB_ST", "=", "'-l%s'", "v", ".", "STLIBPATH_ST", "=", "'-Wl,-LIBPATH:%s'", "CFLAGS_CRT_COMMON", "=", "[", "'-Xclang'", ",", "'--dependent-lib=oldnames'", ",", "'-Xclang'", ",", "'-fno-rtti-data'", ",", "'-D_MT'", "]", "v", ".", "CFLAGS_CRT_MULTITHREADED", "=", "CFLAGS_CRT_COMMON", "+", "[", "'-Xclang'", ",", "'-flto-visibility-public-std'", ",", "'-Xclang'", ",", "'--dependent-lib=libcmt'", ",", "]", "v", ".", "CXXFLAGS_CRT_MULTITHREADED", "=", "v", ".", "CFLAGS_CRT_MULTITHREADED", "v", ".", "CFLAGS_CRT_MULTITHREADED_DBG", "=", "CFLAGS_CRT_COMMON", "+", "[", "'-D_DEBUG'", ",", "'-Xclang'", ",", "'-flto-visibility-public-std'", ",", "'-Xclang'", ",", "'--dependent-lib=libcmtd'", ",", "]", "v", ".", "CXXFLAGS_CRT_MULTITHREADED_DBG", "=", "v", ".", "CFLAGS_CRT_MULTITHREADED_DBG", "v", ".", "CFLAGS_CRT_MULTITHREADED_DLL", "=", "CFLAGS_CRT_COMMON", "+", "[", "'-D_DLL'", ",", "'-Xclang'", ",", "'--dependent-lib=msvcrt'", "]", "v", ".", "CXXFLAGS_CRT_MULTITHREADED_DLL", "=", "v", ".", "CFLAGS_CRT_MULTITHREADED_DLL", "v", ".", "CFLAGS_CRT_MULTITHREADED_DLL_DBG", "=", "CFLAGS_CRT_COMMON", "+", "[", "'-D_DLL'", ",", "'-D_DEBUG'", ",", "'-Xclang'", ",", "'--dependent-lib=msvcrtd'", ",", "]", "v", ".", "CXXFLAGS_CRT_MULTITHREADED_DLL_DBG", "=", "v", ".", "CFLAGS_CRT_MULTITHREADED_DLL_DBG" ]
https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/extras/clang_cross_common.py#L33-L103
tomahawk-player/tomahawk-resolvers
7f827bbe410ccfdb0446f7d6a91acc2199c9cc8d
archive/spotify/breakpad/third_party/protobuf/protobuf/python/mox.py
python
Reset
(*args)
Reset mocks. Args: # args is any number of mocks to be reset.
Reset mocks.
[ "Reset", "mocks", "." ]
def Reset(*args): """Reset mocks. Args: # args is any number of mocks to be reset. """ for mock in args: mock._Reset()
[ "def", "Reset", "(", "*", "args", ")", ":", "for", "mock", "in", "args", ":", "mock", ".", "_Reset", "(", ")" ]
https://github.com/tomahawk-player/tomahawk-resolvers/blob/7f827bbe410ccfdb0446f7d6a91acc2199c9cc8d/archive/spotify/breakpad/third_party/protobuf/protobuf/python/mox.py#L257-L265
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
media/webrtc/trunk/tools/gyp/pylib/gyp/common.py
python
AllTargets
(target_list, target_dicts, build_file)
return bftargets + deptargets
Returns all targets (direct and dependencies) for the specified build_file.
Returns all targets (direct and dependencies) for the specified build_file.
[ "Returns", "all", "targets", "(", "direct", "and", "dependencies", ")", "for", "the", "specified", "build_file", "." ]
def AllTargets(target_list, target_dicts, build_file): """Returns all targets (direct and dependencies) for the specified build_file. """ bftargets = BuildFileTargets(target_list, build_file) deptargets = DeepDependencyTargets(target_dicts, bftargets) return bftargets + deptargets
[ "def", "AllTargets", "(", "target_list", ",", "target_dicts", ",", "build_file", ")", ":", "bftargets", "=", "BuildFileTargets", "(", "target_list", ",", "build_file", ")", "deptargets", "=", "DeepDependencyTargets", "(", "target_dicts", ",", "bftargets", ")", "return", "bftargets", "+", "deptargets" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/media/webrtc/trunk/tools/gyp/pylib/gyp/common.py#L284-L289
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/lib2to3/pytree.py
python
BasePattern.generate_matches
(self, nodes)
Generator yielding all matches for this pattern. Default implementation for non-wildcard patterns.
Generator yielding all matches for this pattern.
[ "Generator", "yielding", "all", "matches", "for", "this", "pattern", "." ]
def generate_matches(self, nodes): """ Generator yielding all matches for this pattern. Default implementation for non-wildcard patterns. """ r = {} if nodes and self.match(nodes[0], r): yield 1, r
[ "def", "generate_matches", "(", "self", ",", "nodes", ")", ":", "r", "=", "{", "}", "if", "nodes", "and", "self", ".", "match", "(", "nodes", "[", "0", "]", ",", "r", ")", ":", "yield", "1", ",", "r" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/lib2to3/pytree.py#L489-L497
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/deps/v8/third_party/jinja2/nodes.py
python
Const.from_untrusted
(cls, value, lineno=None, environment=None)
return cls(value, lineno=lineno, environment=environment)
Return a const object if the value is representable as constant value in the generated code, otherwise it will raise an `Impossible` exception.
Return a const object if the value is representable as constant value in the generated code, otherwise it will raise an `Impossible` exception.
[ "Return", "a", "const", "object", "if", "the", "value", "is", "representable", "as", "constant", "value", "in", "the", "generated", "code", "otherwise", "it", "will", "raise", "an", "Impossible", "exception", "." ]
def from_untrusted(cls, value, lineno=None, environment=None): """Return a const object if the value is representable as constant value in the generated code, otherwise it will raise an `Impossible` exception. """ from .compiler import has_safe_repr if not has_safe_repr(value): raise Impossible() return cls(value, lineno=lineno, environment=environment)
[ "def", "from_untrusted", "(", "cls", ",", "value", ",", "lineno", "=", "None", ",", "environment", "=", "None", ")", ":", "from", ".", "compiler", "import", "has_safe_repr", "if", "not", "has_safe_repr", "(", "value", ")", ":", "raise", "Impossible", "(", ")", "return", "cls", "(", "value", ",", "lineno", "=", "lineno", ",", "environment", "=", "environment", ")" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/v8/third_party/jinja2/nodes.py#L504-L512
polyworld/polyworld
eb7e6bbc82fe77ba79e3bc48c3da2ad8c8238c26
scripts/plotNeuralRhythms.py
python
next_line
(the_file)
return line
Return next line from the brainFunction file, formatted.
Return next line from the brainFunction file, formatted.
[ "Return", "next", "line", "from", "the", "brainFunction", "file", "formatted", "." ]
def next_line(the_file): """Return next line from the brainFunction file, formatted.""" line = the_file.readline() line = line.replace("/", "\n") return line
[ "def", "next_line", "(", "the_file", ")", ":", "line", "=", "the_file", ".", "readline", "(", ")", "line", "=", "line", ".", "replace", "(", "\"/\"", ",", "\"\\n\"", ")", "return", "line" ]
https://github.com/polyworld/polyworld/blob/eb7e6bbc82fe77ba79e3bc48c3da2ad8c8238c26/scripts/plotNeuralRhythms.py#L39-L43
RapidsAtHKUST/CommunityDetectionCodes
23dbafd2e57ab0f5f0528b1322c4a409f21e5892
Algorithms/2012-DEMON/Demon.py
python
Demon.__overlapping_label_propagation
(self, ego_minus_ego, ego, max_iteration=100)
return community_to_nodes
:param max_iteration: number of desired iteration for the label propagation :param ego_minus_ego: ego network minus its center :param ego: ego network center
[]
def __overlapping_label_propagation(self, ego_minus_ego, ego, max_iteration=100): """ :param max_iteration: number of desired iteration for the label propagation :param ego_minus_ego: ego network minus its center :param ego: ego network center """ t = 0 old_node_to_coms = {} while t < max_iteration: t += 1 node_to_coms = {} nodes = list(nx.nodes(ego_minus_ego)) random.shuffle(nodes) count = -len(nodes) for n in nodes: label_freq = {} n_neighbors = list(nx.neighbors(ego_minus_ego, n)) if len(n_neighbors) < 1: continue if count == 0: t += 1 # compute the frequency of the labels for nn in n_neighbors: communities_nn = [nn] if nn in old_node_to_coms: communities_nn = old_node_to_coms[nn] for nn_c in communities_nn: if nn_c in label_freq: v = label_freq.get(nn_c) # case of weighted graph if self.weighted: label_freq[nn_c] = v + ego_minus_ego.edge[nn][n]['weight'] else: label_freq[nn_c] = v + 1 else: # case of weighted graph if self.weighted: label_freq[nn_c] = ego_minus_ego.edge[nn][n]['weight'] else: label_freq[nn_c] = 1 # first run, random choosing of the communities among the neighbors labels if t == 1: if not len(n_neighbors) == 0: r_label = random.sample(label_freq.keys(), 1) ego_minus_ego.node[n]['communities'] = r_label old_node_to_coms[n] = r_label count += 1 continue # choose the majority else: labels = [] max_freq = -1 for l, c in label_freq.items(): if c > max_freq: max_freq = c labels = [l] elif c == max_freq: labels.append(l) node_to_coms[n] = labels if not n in old_node_to_coms or not set(node_to_coms[n]) == set(old_node_to_coms[n]): old_node_to_coms[n] = node_to_coms[n] ego_minus_ego.node[n]['communities'] = labels t += 1 # build the communities reintroducing the ego community_to_nodes = {} for n in nx.nodes(ego_minus_ego): if len(list(nx.neighbors(ego_minus_ego, n))) == 0: ego_minus_ego.node[n]['communities'] = [n] c_n = ego_minus_ego.node[n]['communities'] for c in c_n: if c in community_to_nodes: com = community_to_nodes.get(c) com.append(n) else: nodes = [n, ego] community_to_nodes[c] = nodes return community_to_nodes
[ "def", "__overlapping_label_propagation", "(", "self", ",", "ego_minus_ego", ",", "ego", ",", "max_iteration", "=", "100", ")", ":", "t", "=", "0", "old_node_to_coms", "=", "{", "}", "while", "t", "<", "max_iteration", ":", "t", "+=", "1", "node_to_coms", "=", "{", "}", "nodes", "=", "list", "(", "nx", ".", "nodes", "(", "ego_minus_ego", ")", ")", "random", ".", "shuffle", "(", "nodes", ")", "count", "=", "-", "len", "(", "nodes", ")", "for", "n", "in", "nodes", ":", "label_freq", "=", "{", "}", "n_neighbors", "=", "list", "(", "nx", ".", "neighbors", "(", "ego_minus_ego", ",", "n", ")", ")", "if", "len", "(", "n_neighbors", ")", "<", "1", ":", "continue", "if", "count", "==", "0", ":", "t", "+=", "1", "# compute the frequency of the labels", "for", "nn", "in", "n_neighbors", ":", "communities_nn", "=", "[", "nn", "]", "if", "nn", "in", "old_node_to_coms", ":", "communities_nn", "=", "old_node_to_coms", "[", "nn", "]", "for", "nn_c", "in", "communities_nn", ":", "if", "nn_c", "in", "label_freq", ":", "v", "=", "label_freq", ".", "get", "(", "nn_c", ")", "# case of weighted graph", "if", "self", ".", "weighted", ":", "label_freq", "[", "nn_c", "]", "=", "v", "+", "ego_minus_ego", ".", "edge", "[", "nn", "]", "[", "n", "]", "[", "'weight'", "]", "else", ":", "label_freq", "[", "nn_c", "]", "=", "v", "+", "1", "else", ":", "# case of weighted graph", "if", "self", ".", "weighted", ":", "label_freq", "[", "nn_c", "]", "=", "ego_minus_ego", ".", "edge", "[", "nn", "]", "[", "n", "]", "[", "'weight'", "]", "else", ":", "label_freq", "[", "nn_c", "]", "=", "1", "# first run, random choosing of the communities among the neighbors labels", "if", "t", "==", "1", ":", "if", "not", "len", "(", "n_neighbors", ")", "==", "0", ":", "r_label", "=", "random", ".", "sample", "(", "label_freq", ".", "keys", "(", ")", ",", "1", ")", "ego_minus_ego", ".", "node", "[", "n", "]", "[", "'communities'", "]", "=", "r_label", "old_node_to_coms", "[", "n", "]", "=", "r_label", "count", "+=", "1", "continue", "# choose the majority", "else", ":", "labels", "=", "[", "]", "max_freq", "=", "-", "1", "for", "l", ",", "c", "in", "label_freq", ".", "items", "(", ")", ":", "if", "c", ">", "max_freq", ":", "max_freq", "=", "c", "labels", "=", "[", "l", "]", "elif", "c", "==", "max_freq", ":", "labels", ".", "append", "(", "l", ")", "node_to_coms", "[", "n", "]", "=", "labels", "if", "not", "n", "in", "old_node_to_coms", "or", "not", "set", "(", "node_to_coms", "[", "n", "]", ")", "==", "set", "(", "old_node_to_coms", "[", "n", "]", ")", ":", "old_node_to_coms", "[", "n", "]", "=", "node_to_coms", "[", "n", "]", "ego_minus_ego", ".", "node", "[", "n", "]", "[", "'communities'", "]", "=", "labels", "t", "+=", "1", "# build the communities reintroducing the ego", "community_to_nodes", "=", "{", "}", "for", "n", "in", "nx", ".", "nodes", "(", "ego_minus_ego", ")", ":", "if", "len", "(", "list", "(", "nx", ".", "neighbors", "(", "ego_minus_ego", ",", "n", ")", ")", ")", "==", "0", ":", "ego_minus_ego", ".", "node", "[", "n", "]", "[", "'communities'", "]", "=", "[", "n", "]", "c_n", "=", "ego_minus_ego", ".", "node", "[", "n", "]", "[", "'communities'", "]", "for", "c", "in", "c_n", ":", "if", "c", "in", "community_to_nodes", ":", "com", "=", "community_to_nodes", ".", "get", "(", "c", ")", "com", ".", "append", "(", "n", ")", "else", ":", "nodes", "=", "[", "n", ",", "ego", "]", "community_to_nodes", "[", "c", "]", "=", "nodes", "return", "community_to_nodes" ]
https://github.com/RapidsAtHKUST/CommunityDetectionCodes/blob/23dbafd2e57ab0f5f0528b1322c4a409f21e5892/Algorithms/2012-DEMON/Demon.py#L74-L175
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/distutils/ccompiler.py
python
CCompiler.set_runtime_library_dirs
(self, dirs)
Set the list of directories to search for shared libraries at runtime to 'dirs' (a list of strings). This does not affect any standard search path that the runtime linker may search by default.
Set the list of directories to search for shared libraries at runtime to 'dirs' (a list of strings). This does not affect any standard search path that the runtime linker may search by default.
[ "Set", "the", "list", "of", "directories", "to", "search", "for", "shared", "libraries", "at", "runtime", "to", "dirs", "(", "a", "list", "of", "strings", ")", ".", "This", "does", "not", "affect", "any", "standard", "search", "path", "that", "the", "runtime", "linker", "may", "search", "by", "default", "." ]
def set_runtime_library_dirs(self, dirs): """Set the list of directories to search for shared libraries at runtime to 'dirs' (a list of strings). This does not affect any standard search path that the runtime linker may search by default. """ self.runtime_library_dirs = dirs[:]
[ "def", "set_runtime_library_dirs", "(", "self", ",", "dirs", ")", ":", "self", ".", "runtime_library_dirs", "=", "dirs", "[", ":", "]" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/distutils/ccompiler.py#L293-L299
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/math/symbolic_io.py
python
exprToStr
(expr,parseCompatible=True,expandSubexprs='auto')
Converts an Expression to a printable or parseable string. Args: expr (Expression): the Expression to convert parseCompatible (bool, optional): if True, the result is readable via exprFromStr() expandSubexprs (str or bool, optional): whether to expand subexpressions. Can be: * 'auto': if parseCompatible, equivalent to False. if parseCompatible=False, equivalent to True. * True: expands all common subexpressions * False: does not expand common subexpressions. * 'show': Internally used. Returns: (str): a printable or parsable string representing expr.
Converts an Expression to a printable or parseable string.
[ "Converts", "an", "Expression", "to", "a", "printable", "or", "parseable", "string", "." ]
def exprToStr(expr,parseCompatible=True,expandSubexprs='auto'): """Converts an Expression to a printable or parseable string. Args: expr (Expression): the Expression to convert parseCompatible (bool, optional): if True, the result is readable via exprFromStr() expandSubexprs (str or bool, optional): whether to expand subexpressions. Can be: * 'auto': if parseCompatible, equivalent to False. if parseCompatible=False, equivalent to True. * True: expands all common subexpressions * False: does not expand common subexpressions. * 'show': Internally used. Returns: (str): a printable or parsable string representing expr. """ if isinstance(expr,ConstantExpression): if isinstance(expr.value,slice): start,stop,step = expr.value.start,expr.value.stop,expr.value.step return "%s:%s%s"%(str(start),"" if stop > 900000000000 else str(stop),"" if step is None else ":"+str(step)) try: jsonval = _to_jsonobj(expr.value) except: return str(expr.value) if parseCompatible: return json.dumps(jsonval) else: original_float_repr = encoder.FLOAT_REPR encoder.FLOAT_REPR = lambda o:format(o,'.14g') if _json_complex(jsonval): res = json.dumps(jsonval,sort_keys=True, indent=4, separators=(',', ': ')) else: res = json.dumps(jsonval,sort_keys=True) encoder.FLOAT_REPR = original_float_repr return res elif isinstance(expr,VariableExpression): if parseCompatible: return VAR_PREFIX+expr.var.name else: return str(expr.var) elif isinstance(expr,UserDataExpression): return USER_DATA_PREFIX+expr.name elif isinstance(expr,OperatorExpression): if expandSubexprs == 'auto': expandSubexprs = not parseCompatible if expandSubexprs: astr = [] for i,a in enumerate(expr.args): a._parent = (weakref.ref(expr),i) astr.append(exprToStr(a,parseCompatible,expandSubexprs)) if not isinstance(a,OperatorExpression) and expandSubexprs == 'show' and ('id' in a._cache or 'name' in a._cache): #tagged subexprs need parenthesies if astr[-1][-1] != ')': astr[-1] = '('+astr[-1]+')' astr[-1] = astr[-1] + NAMED_EXPRESSION_TAG + a._cache.get('id',a._cache.get('name')) a._parent = None res = _prettyPrintExpr(expr,astr,parseCompatible) if expandSubexprs == 'show' and ('id' in expr._cache or 'name' in expr._cache): #tagged subexprs need parenthesies if res[-1] != ')': res = '('+res+')' return res + NAMED_EXPRESSION_TAG + expr._cache.get('id',expr._cache.get('name')) oldparent = expr._parent iscomplex = expr.depth() >= 0 and (expr.functionInfo.name in _operator_precedence) expr._parent = oldparent if iscomplex and (expr._parent is not None and not isinstance(expr._parent,str)): if parseCompatible: return '(' + res + ')' else: parent = expr._parent[0]() if parent.functionInfo.name in _operator_precedence: expr_precedence = _operator_precedence[expr.functionInfo.name] parent_precedence = _operator_precedence[parent.functionInfo.name] #if - is the first in a summation, don't parenthesize it if expr._parent[1] == 0 and expr.functionInfo.name == 'neg' and parent.functionInfo.name in ['sum','add','sub']: return res if expr_precedence > parent_precedence: return '(' + res + ')' if expr_precedence == parent_precedence: if expr.functionInfo is parent.functionInfo and expr.functionInfo.properties.get('associative',False): return res else: return '(' + res + ')' return res else: if not parseCompatible: taggedexpr = _make_tagged(expr,"") else: taggedexpr = _make_tagged(expr) res = exprToStr(taggedexpr,parseCompatible,'show') if taggedexpr is not expr: expr._clearCache('id',deep=True) return res elif isinstance(expr,_TaggedExpression): return NAMED_EXPRESSION_PREFIX+expr.name elif is_const(expr): return str(expr) else: raise ValueError("Unknown type "+expr.__class__.__name__)
[ "def", "exprToStr", "(", "expr", ",", "parseCompatible", "=", "True", ",", "expandSubexprs", "=", "'auto'", ")", ":", "if", "isinstance", "(", "expr", ",", "ConstantExpression", ")", ":", "if", "isinstance", "(", "expr", ".", "value", ",", "slice", ")", ":", "start", ",", "stop", ",", "step", "=", "expr", ".", "value", ".", "start", ",", "expr", ".", "value", ".", "stop", ",", "expr", ".", "value", ".", "step", "return", "\"%s:%s%s\"", "%", "(", "str", "(", "start", ")", ",", "\"\"", "if", "stop", ">", "900000000000", "else", "str", "(", "stop", ")", ",", "\"\"", "if", "step", "is", "None", "else", "\":\"", "+", "str", "(", "step", ")", ")", "try", ":", "jsonval", "=", "_to_jsonobj", "(", "expr", ".", "value", ")", "except", ":", "return", "str", "(", "expr", ".", "value", ")", "if", "parseCompatible", ":", "return", "json", ".", "dumps", "(", "jsonval", ")", "else", ":", "original_float_repr", "=", "encoder", ".", "FLOAT_REPR", "encoder", ".", "FLOAT_REPR", "=", "lambda", "o", ":", "format", "(", "o", ",", "'.14g'", ")", "if", "_json_complex", "(", "jsonval", ")", ":", "res", "=", "json", ".", "dumps", "(", "jsonval", ",", "sort_keys", "=", "True", ",", "indent", "=", "4", ",", "separators", "=", "(", "','", ",", "': '", ")", ")", "else", ":", "res", "=", "json", ".", "dumps", "(", "jsonval", ",", "sort_keys", "=", "True", ")", "encoder", ".", "FLOAT_REPR", "=", "original_float_repr", "return", "res", "elif", "isinstance", "(", "expr", ",", "VariableExpression", ")", ":", "if", "parseCompatible", ":", "return", "VAR_PREFIX", "+", "expr", ".", "var", ".", "name", "else", ":", "return", "str", "(", "expr", ".", "var", ")", "elif", "isinstance", "(", "expr", ",", "UserDataExpression", ")", ":", "return", "USER_DATA_PREFIX", "+", "expr", ".", "name", "elif", "isinstance", "(", "expr", ",", "OperatorExpression", ")", ":", "if", "expandSubexprs", "==", "'auto'", ":", "expandSubexprs", "=", "not", "parseCompatible", "if", "expandSubexprs", ":", "astr", "=", "[", "]", "for", "i", ",", "a", "in", "enumerate", "(", "expr", ".", "args", ")", ":", "a", ".", "_parent", "=", "(", "weakref", ".", "ref", "(", "expr", ")", ",", "i", ")", "astr", ".", "append", "(", "exprToStr", "(", "a", ",", "parseCompatible", ",", "expandSubexprs", ")", ")", "if", "not", "isinstance", "(", "a", ",", "OperatorExpression", ")", "and", "expandSubexprs", "==", "'show'", "and", "(", "'id'", "in", "a", ".", "_cache", "or", "'name'", "in", "a", ".", "_cache", ")", ":", "#tagged subexprs need parenthesies", "if", "astr", "[", "-", "1", "]", "[", "-", "1", "]", "!=", "')'", ":", "astr", "[", "-", "1", "]", "=", "'('", "+", "astr", "[", "-", "1", "]", "+", "')'", "astr", "[", "-", "1", "]", "=", "astr", "[", "-", "1", "]", "+", "NAMED_EXPRESSION_TAG", "+", "a", ".", "_cache", ".", "get", "(", "'id'", ",", "a", ".", "_cache", ".", "get", "(", "'name'", ")", ")", "a", ".", "_parent", "=", "None", "res", "=", "_prettyPrintExpr", "(", "expr", ",", "astr", ",", "parseCompatible", ")", "if", "expandSubexprs", "==", "'show'", "and", "(", "'id'", "in", "expr", ".", "_cache", "or", "'name'", "in", "expr", ".", "_cache", ")", ":", "#tagged subexprs need parenthesies", "if", "res", "[", "-", "1", "]", "!=", "')'", ":", "res", "=", "'('", "+", "res", "+", "')'", "return", "res", "+", "NAMED_EXPRESSION_TAG", "+", "expr", ".", "_cache", ".", "get", "(", "'id'", ",", "expr", ".", "_cache", ".", "get", "(", "'name'", ")", ")", "oldparent", "=", "expr", ".", "_parent", "iscomplex", "=", "expr", ".", "depth", "(", ")", ">=", "0", "and", "(", "expr", ".", "functionInfo", ".", "name", "in", "_operator_precedence", ")", "expr", ".", "_parent", "=", "oldparent", "if", "iscomplex", "and", "(", "expr", ".", "_parent", "is", "not", "None", "and", "not", "isinstance", "(", "expr", ".", "_parent", ",", "str", ")", ")", ":", "if", "parseCompatible", ":", "return", "'('", "+", "res", "+", "')'", "else", ":", "parent", "=", "expr", ".", "_parent", "[", "0", "]", "(", ")", "if", "parent", ".", "functionInfo", ".", "name", "in", "_operator_precedence", ":", "expr_precedence", "=", "_operator_precedence", "[", "expr", ".", "functionInfo", ".", "name", "]", "parent_precedence", "=", "_operator_precedence", "[", "parent", ".", "functionInfo", ".", "name", "]", "#if - is the first in a summation, don't parenthesize it", "if", "expr", ".", "_parent", "[", "1", "]", "==", "0", "and", "expr", ".", "functionInfo", ".", "name", "==", "'neg'", "and", "parent", ".", "functionInfo", ".", "name", "in", "[", "'sum'", ",", "'add'", ",", "'sub'", "]", ":", "return", "res", "if", "expr_precedence", ">", "parent_precedence", ":", "return", "'('", "+", "res", "+", "')'", "if", "expr_precedence", "==", "parent_precedence", ":", "if", "expr", ".", "functionInfo", "is", "parent", ".", "functionInfo", "and", "expr", ".", "functionInfo", ".", "properties", ".", "get", "(", "'associative'", ",", "False", ")", ":", "return", "res", "else", ":", "return", "'('", "+", "res", "+", "')'", "return", "res", "else", ":", "if", "not", "parseCompatible", ":", "taggedexpr", "=", "_make_tagged", "(", "expr", ",", "\"\"", ")", "else", ":", "taggedexpr", "=", "_make_tagged", "(", "expr", ")", "res", "=", "exprToStr", "(", "taggedexpr", ",", "parseCompatible", ",", "'show'", ")", "if", "taggedexpr", "is", "not", "expr", ":", "expr", ".", "_clearCache", "(", "'id'", ",", "deep", "=", "True", ")", "return", "res", "elif", "isinstance", "(", "expr", ",", "_TaggedExpression", ")", ":", "return", "NAMED_EXPRESSION_PREFIX", "+", "expr", ".", "name", "elif", "is_const", "(", "expr", ")", ":", "return", "str", "(", "expr", ")", "else", ":", "raise", "ValueError", "(", "\"Unknown type \"", "+", "expr", ".", "__class__", ".", "__name__", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/math/symbolic_io.py#L195-L294
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/learn/python/learn/dataframe/tensorflow_dataframe.py
python
TensorFlowDataFrame.from_examples
(cls, filepatterns, features, reader_cls=io_ops.TFRecordReader, num_threads=1, enqueue_size=None, batch_size=32, queue_capacity=None, min_after_dequeue=None, shuffle=True, seed=None)
return dataframe
Create a `DataFrame` from `tensorflow.Example`s. Args: filepatterns: a list of file patterns containing `tensorflow.Example`s. features: a dict mapping feature names to `VarLenFeature` or `FixedLenFeature`. reader_cls: a subclass of `tensorflow.ReaderBase` that will be used to read the `Example`s. num_threads: the number of readers that will work in parallel. enqueue_size: block size for each read operation. batch_size: desired batch size. queue_capacity: capacity of the queue that will store parsed `Example`s min_after_dequeue: minimum number of elements that can be left by a dequeue operation. Only used if `shuffle` is true. shuffle: whether records should be shuffled. Defaults to true. seed: passed to random shuffle operations. Only used if `shuffle` is true. Returns: A `DataFrame` that has columns corresponding to `features` and is filled with `Example`s from `filepatterns`. Raises: ValueError: no files match `filepatterns`. ValueError: `features` contains the reserved name 'index'.
Create a `DataFrame` from `tensorflow.Example`s.
[ "Create", "a", "DataFrame", "from", "tensorflow", ".", "Example", "s", "." ]
def from_examples(cls, filepatterns, features, reader_cls=io_ops.TFRecordReader, num_threads=1, enqueue_size=None, batch_size=32, queue_capacity=None, min_after_dequeue=None, shuffle=True, seed=None): """Create a `DataFrame` from `tensorflow.Example`s. Args: filepatterns: a list of file patterns containing `tensorflow.Example`s. features: a dict mapping feature names to `VarLenFeature` or `FixedLenFeature`. reader_cls: a subclass of `tensorflow.ReaderBase` that will be used to read the `Example`s. num_threads: the number of readers that will work in parallel. enqueue_size: block size for each read operation. batch_size: desired batch size. queue_capacity: capacity of the queue that will store parsed `Example`s min_after_dequeue: minimum number of elements that can be left by a dequeue operation. Only used if `shuffle` is true. shuffle: whether records should be shuffled. Defaults to true. seed: passed to random shuffle operations. Only used if `shuffle` is true. Returns: A `DataFrame` that has columns corresponding to `features` and is filled with `Example`s from `filepatterns`. Raises: ValueError: no files match `filepatterns`. ValueError: `features` contains the reserved name 'index'. """ filenames = _expand_file_names(filepatterns) if not filenames: raise ValueError("No matching file names.") if "index" in features: raise ValueError( "'index' is reserved and can not be used for a feature name.") index, record = reader_source.ReaderSource( reader_cls, filenames, enqueue_size=enqueue_size, batch_size=batch_size, queue_capacity=queue_capacity, shuffle=shuffle, min_after_dequeue=min_after_dequeue, num_threads=num_threads, seed=seed)() parser = example_parser.ExampleParser(features) parsed = parser(record) column_dict = parsed._asdict() column_dict["index"] = index dataframe = cls() dataframe.assign(**column_dict) return dataframe
[ "def", "from_examples", "(", "cls", ",", "filepatterns", ",", "features", ",", "reader_cls", "=", "io_ops", ".", "TFRecordReader", ",", "num_threads", "=", "1", ",", "enqueue_size", "=", "None", ",", "batch_size", "=", "32", ",", "queue_capacity", "=", "None", ",", "min_after_dequeue", "=", "None", ",", "shuffle", "=", "True", ",", "seed", "=", "None", ")", ":", "filenames", "=", "_expand_file_names", "(", "filepatterns", ")", "if", "not", "filenames", ":", "raise", "ValueError", "(", "\"No matching file names.\"", ")", "if", "\"index\"", "in", "features", ":", "raise", "ValueError", "(", "\"'index' is reserved and can not be used for a feature name.\"", ")", "index", ",", "record", "=", "reader_source", ".", "ReaderSource", "(", "reader_cls", ",", "filenames", ",", "enqueue_size", "=", "enqueue_size", ",", "batch_size", "=", "batch_size", ",", "queue_capacity", "=", "queue_capacity", ",", "shuffle", "=", "shuffle", ",", "min_after_dequeue", "=", "min_after_dequeue", ",", "num_threads", "=", "num_threads", ",", "seed", "=", "seed", ")", "(", ")", "parser", "=", "example_parser", ".", "ExampleParser", "(", "features", ")", "parsed", "=", "parser", "(", "record", ")", "column_dict", "=", "parsed", ".", "_asdict", "(", ")", "column_dict", "[", "\"index\"", "]", "=", "index", "dataframe", "=", "cls", "(", ")", "dataframe", ".", "assign", "(", "*", "*", "column_dict", ")", "return", "dataframe" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/learn/python/learn/dataframe/tensorflow_dataframe.py#L528-L590
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Code/Tools/waf-1.7.13/waflib/Node.py
python
Node.find_or_declare
(self, lst)
return node
if 'self' is in build directory, try to return an existing node if no node is found, go to the source directory try to find an existing node in the source directory if no node is found, create it in the build directory :param lst: path :type lst: string or list of string
if 'self' is in build directory, try to return an existing node if no node is found, go to the source directory try to find an existing node in the source directory if no node is found, create it in the build directory
[ "if", "self", "is", "in", "build", "directory", "try", "to", "return", "an", "existing", "node", "if", "no", "node", "is", "found", "go", "to", "the", "source", "directory", "try", "to", "find", "an", "existing", "node", "in", "the", "source", "directory", "if", "no", "node", "is", "found", "create", "it", "in", "the", "build", "directory" ]
def find_or_declare(self, lst): """ if 'self' is in build directory, try to return an existing node if no node is found, go to the source directory try to find an existing node in the source directory if no node is found, create it in the build directory :param lst: path :type lst: string or list of string """ if isinstance(lst, str): lst = [x for x in split_path(lst) if x and x != '.'] node = self.get_bld().search_node(lst) if node: if not os.path.isfile(node.abspath()): node.sig = None node.parent.mkdir() return node self = self.get_src() node = self.find_node(lst) if node: if not os.path.isfile(node.abspath()): node.sig = None node.parent.mkdir() return node node = self.get_bld().make_node(lst) node.parent.mkdir() return node
[ "def", "find_or_declare", "(", "self", ",", "lst", ")", ":", "if", "isinstance", "(", "lst", ",", "str", ")", ":", "lst", "=", "[", "x", "for", "x", "in", "split_path", "(", "lst", ")", "if", "x", "and", "x", "!=", "'.'", "]", "node", "=", "self", ".", "get_bld", "(", ")", ".", "search_node", "(", "lst", ")", "if", "node", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "node", ".", "abspath", "(", ")", ")", ":", "node", ".", "sig", "=", "None", "node", ".", "parent", ".", "mkdir", "(", ")", "return", "node", "self", "=", "self", ".", "get_src", "(", ")", "node", "=", "self", ".", "find_node", "(", "lst", ")", "if", "node", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "node", ".", "abspath", "(", ")", ")", ":", "node", ".", "sig", "=", "None", "node", ".", "parent", ".", "mkdir", "(", ")", "return", "node", "node", "=", "self", ".", "get_bld", "(", ")", ".", "make_node", "(", "lst", ")", "node", ".", "parent", ".", "mkdir", "(", ")", "return", "node" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/Node.py#L692-L720
kevin-ssy/Optical-Flow-Guided-Feature
07d4501a29002ee7821c38c1820e4a64c1acf6e8
lib/caffe-action/tools/extra/parse_log.py
python
parse_log
(path_to_log)
return train_dict_list, test_dict_list
Parse log file Returns (train_dict_list, train_dict_names, test_dict_list, test_dict_names) train_dict_list and test_dict_list are lists of dicts that define the table rows train_dict_names and test_dict_names are ordered tuples of the column names for the two dict_lists
Parse log file Returns (train_dict_list, train_dict_names, test_dict_list, test_dict_names)
[ "Parse", "log", "file", "Returns", "(", "train_dict_list", "train_dict_names", "test_dict_list", "test_dict_names", ")" ]
def parse_log(path_to_log): """Parse log file Returns (train_dict_list, train_dict_names, test_dict_list, test_dict_names) train_dict_list and test_dict_list are lists of dicts that define the table rows train_dict_names and test_dict_names are ordered tuples of the column names for the two dict_lists """ regex_iteration = re.compile('Iteration (\d+)') regex_train_output = re.compile('Train net output #(\d+): (\S+) = ([\.\deE+-]+)') regex_test_output = re.compile('Test net output #(\d+): (\S+) = ([\.\deE+-]+)') regex_learning_rate = re.compile('lr = ([\.\d]+)') # Pick out lines of interest iteration = -1 learning_rate = float('NaN') train_dict_list = [] test_dict_list = [] train_row = None test_row = None logfile_year = extract_seconds.get_log_created_year(path_to_log) with open(path_to_log) as f: start_time = extract_seconds.get_start_time(f, logfile_year) for line in f: iteration_match = regex_iteration.search(line) if iteration_match: iteration = float(iteration_match.group(1)) if iteration == -1: # Only start parsing for other stuff if we've found the first # iteration continue time = extract_seconds.extract_datetime_from_line(line, logfile_year) seconds = (time - start_time).total_seconds() learning_rate_match = regex_learning_rate.search(line) if learning_rate_match: learning_rate = float(learning_rate_match.group(1)) train_dict_list, train_row = parse_line_for_net_output( regex_train_output, train_row, train_dict_list, line, iteration, seconds, learning_rate ) test_dict_list, test_row = parse_line_for_net_output( regex_test_output, test_row, test_dict_list, line, iteration, seconds, learning_rate ) fix_initial_nan_learning_rate(train_dict_list) fix_initial_nan_learning_rate(test_dict_list) return train_dict_list, test_dict_list
[ "def", "parse_log", "(", "path_to_log", ")", ":", "regex_iteration", "=", "re", ".", "compile", "(", "'Iteration (\\d+)'", ")", "regex_train_output", "=", "re", ".", "compile", "(", "'Train net output #(\\d+): (\\S+) = ([\\.\\deE+-]+)'", ")", "regex_test_output", "=", "re", ".", "compile", "(", "'Test net output #(\\d+): (\\S+) = ([\\.\\deE+-]+)'", ")", "regex_learning_rate", "=", "re", ".", "compile", "(", "'lr = ([\\.\\d]+)'", ")", "# Pick out lines of interest", "iteration", "=", "-", "1", "learning_rate", "=", "float", "(", "'NaN'", ")", "train_dict_list", "=", "[", "]", "test_dict_list", "=", "[", "]", "train_row", "=", "None", "test_row", "=", "None", "logfile_year", "=", "extract_seconds", ".", "get_log_created_year", "(", "path_to_log", ")", "with", "open", "(", "path_to_log", ")", "as", "f", ":", "start_time", "=", "extract_seconds", ".", "get_start_time", "(", "f", ",", "logfile_year", ")", "for", "line", "in", "f", ":", "iteration_match", "=", "regex_iteration", ".", "search", "(", "line", ")", "if", "iteration_match", ":", "iteration", "=", "float", "(", "iteration_match", ".", "group", "(", "1", ")", ")", "if", "iteration", "==", "-", "1", ":", "# Only start parsing for other stuff if we've found the first", "# iteration", "continue", "time", "=", "extract_seconds", ".", "extract_datetime_from_line", "(", "line", ",", "logfile_year", ")", "seconds", "=", "(", "time", "-", "start_time", ")", ".", "total_seconds", "(", ")", "learning_rate_match", "=", "regex_learning_rate", ".", "search", "(", "line", ")", "if", "learning_rate_match", ":", "learning_rate", "=", "float", "(", "learning_rate_match", ".", "group", "(", "1", ")", ")", "train_dict_list", ",", "train_row", "=", "parse_line_for_net_output", "(", "regex_train_output", ",", "train_row", ",", "train_dict_list", ",", "line", ",", "iteration", ",", "seconds", ",", "learning_rate", ")", "test_dict_list", ",", "test_row", "=", "parse_line_for_net_output", "(", "regex_test_output", ",", "test_row", ",", "test_dict_list", ",", "line", ",", "iteration", ",", "seconds", ",", "learning_rate", ")", "fix_initial_nan_learning_rate", "(", "train_dict_list", ")", "fix_initial_nan_learning_rate", "(", "test_dict_list", ")", "return", "train_dict_list", ",", "test_dict_list" ]
https://github.com/kevin-ssy/Optical-Flow-Guided-Feature/blob/07d4501a29002ee7821c38c1820e4a64c1acf6e8/lib/caffe-action/tools/extra/parse_log.py#L17-L74
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/distributions/python/ops/wishart.py
python
_WishartLinearOperator.log_normalization
(self, name="log_normalization")
Computes the log normalizing constant, log(Z).
Computes the log normalizing constant, log(Z).
[ "Computes", "the", "log", "normalizing", "constant", "log", "(", "Z", ")", "." ]
def log_normalization(self, name="log_normalization"): """Computes the log normalizing constant, log(Z).""" with self._name_scope(name): return (self.df * self.scale_operator.log_abs_determinant() + 0.5 * self.df * self.dimension * math.log(2.) + self._multi_lgamma(0.5 * self.df, self.dimension))
[ "def", "log_normalization", "(", "self", ",", "name", "=", "\"log_normalization\"", ")", ":", "with", "self", ".", "_name_scope", "(", "name", ")", ":", "return", "(", "self", ".", "df", "*", "self", ".", "scale_operator", ".", "log_abs_determinant", "(", ")", "+", "0.5", "*", "self", ".", "df", "*", "self", ".", "dimension", "*", "math", ".", "log", "(", "2.", ")", "+", "self", ".", "_multi_lgamma", "(", "0.5", "*", "self", ".", "df", ",", "self", ".", "dimension", ")", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/distributions/python/ops/wishart.py#L406-L411
sfzhang15/FaceBoxes
b52cc92f9362d3adc08d54666aeb9ebb62fdb7da
scripts/cpp_lint.py
python
_GetTextInside
(text, start_pattern)
return text[start_position:position - 1]
r"""Retrieves all the text between matching open and close parentheses. Given a string of lines and a regular expression string, retrieve all the text following the expression and between opening punctuation symbols like (, [, or {, and the matching close-punctuation symbol. This properly nested occurrences of the punctuations, so for the text like printf(a(), b(c())); a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'. start_pattern must match string having an open punctuation symbol at the end. Args: text: The lines to extract text. Its comments and strings must be elided. It can be single line and can span multiple lines. start_pattern: The regexp string indicating where to start extracting the text. Returns: The extracted text. None if either the opening string or ending punctuation could not be found.
r"""Retrieves all the text between matching open and close parentheses.
[ "r", "Retrieves", "all", "the", "text", "between", "matching", "open", "and", "close", "parentheses", "." ]
def _GetTextInside(text, start_pattern): r"""Retrieves all the text between matching open and close parentheses. Given a string of lines and a regular expression string, retrieve all the text following the expression and between opening punctuation symbols like (, [, or {, and the matching close-punctuation symbol. This properly nested occurrences of the punctuations, so for the text like printf(a(), b(c())); a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'. start_pattern must match string having an open punctuation symbol at the end. Args: text: The lines to extract text. Its comments and strings must be elided. It can be single line and can span multiple lines. start_pattern: The regexp string indicating where to start extracting the text. Returns: The extracted text. None if either the opening string or ending punctuation could not be found. """ # TODO(sugawarayu): Audit cpplint.py to see what places could be profitably # rewritten to use _GetTextInside (and use inferior regexp matching today). # Give opening punctuations to get the matching close-punctuations. matching_punctuation = {'(': ')', '{': '}', '[': ']'} closing_punctuation = set(matching_punctuation.itervalues()) # Find the position to start extracting text. match = re.search(start_pattern, text, re.M) if not match: # start_pattern not found in text. return None start_position = match.end(0) assert start_position > 0, ( 'start_pattern must ends with an opening punctuation.') assert text[start_position - 1] in matching_punctuation, ( 'start_pattern must ends with an opening punctuation.') # Stack of closing punctuations we expect to have in text after position. punctuation_stack = [matching_punctuation[text[start_position - 1]]] position = start_position while punctuation_stack and position < len(text): if text[position] == punctuation_stack[-1]: punctuation_stack.pop() elif text[position] in closing_punctuation: # A closing punctuation without matching opening punctuations. return None elif text[position] in matching_punctuation: punctuation_stack.append(matching_punctuation[text[position]]) position += 1 if punctuation_stack: # Opening punctuations left without matching close-punctuations. return None # punctuations match. return text[start_position:position - 1]
[ "def", "_GetTextInside", "(", "text", ",", "start_pattern", ")", ":", "# TODO(sugawarayu): Audit cpplint.py to see what places could be profitably", "# rewritten to use _GetTextInside (and use inferior regexp matching today).", "# Give opening punctuations to get the matching close-punctuations.", "matching_punctuation", "=", "{", "'('", ":", "')'", ",", "'{'", ":", "'}'", ",", "'['", ":", "']'", "}", "closing_punctuation", "=", "set", "(", "matching_punctuation", ".", "itervalues", "(", ")", ")", "# Find the position to start extracting text.", "match", "=", "re", ".", "search", "(", "start_pattern", ",", "text", ",", "re", ".", "M", ")", "if", "not", "match", ":", "# start_pattern not found in text.", "return", "None", "start_position", "=", "match", ".", "end", "(", "0", ")", "assert", "start_position", ">", "0", ",", "(", "'start_pattern must ends with an opening punctuation.'", ")", "assert", "text", "[", "start_position", "-", "1", "]", "in", "matching_punctuation", ",", "(", "'start_pattern must ends with an opening punctuation.'", ")", "# Stack of closing punctuations we expect to have in text after position.", "punctuation_stack", "=", "[", "matching_punctuation", "[", "text", "[", "start_position", "-", "1", "]", "]", "]", "position", "=", "start_position", "while", "punctuation_stack", "and", "position", "<", "len", "(", "text", ")", ":", "if", "text", "[", "position", "]", "==", "punctuation_stack", "[", "-", "1", "]", ":", "punctuation_stack", ".", "pop", "(", ")", "elif", "text", "[", "position", "]", "in", "closing_punctuation", ":", "# A closing punctuation without matching opening punctuations.", "return", "None", "elif", "text", "[", "position", "]", "in", "matching_punctuation", ":", "punctuation_stack", ".", "append", "(", "matching_punctuation", "[", "text", "[", "position", "]", "]", ")", "position", "+=", "1", "if", "punctuation_stack", ":", "# Opening punctuations left without matching close-punctuations.", "return", "None", "# punctuations match.", "return", "text", "[", "start_position", ":", "position", "-", "1", "]" ]
https://github.com/sfzhang15/FaceBoxes/blob/b52cc92f9362d3adc08d54666aeb9ebb62fdb7da/scripts/cpp_lint.py#L3756-L3809
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/network/lazy_wheel.py
python
dist_from_wheel_url
(name, url, session)
Return a pkg_resources.Distribution from the given wheel URL. This uses HTTP range requests to only fetch the potion of the wheel containing metadata, just enough for the object to be constructed. If such requests are not supported, HTTPRangeRequestUnsupported is raised.
Return a pkg_resources.Distribution from the given wheel URL.
[ "Return", "a", "pkg_resources", ".", "Distribution", "from", "the", "given", "wheel", "URL", "." ]
def dist_from_wheel_url(name, url, session): # type: (str, str, PipSession) -> Distribution """Return a pkg_resources.Distribution from the given wheel URL. This uses HTTP range requests to only fetch the potion of the wheel containing metadata, just enough for the object to be constructed. If such requests are not supported, HTTPRangeRequestUnsupported is raised. """ with LazyZipOverHTTP(url, session) as wheel: # For read-only ZIP files, ZipFile only needs methods read, # seek, seekable and tell, not the whole IO protocol. zip_file = ZipFile(wheel) # type: ignore # After context manager exit, wheel.name # is an invalid file by intention. return pkg_resources_distribution_for_wheel(zip_file, name, wheel.name)
[ "def", "dist_from_wheel_url", "(", "name", ",", "url", ",", "session", ")", ":", "# type: (str, str, PipSession) -> Distribution", "with", "LazyZipOverHTTP", "(", "url", ",", "session", ")", "as", "wheel", ":", "# For read-only ZIP files, ZipFile only needs methods read,", "# seek, seekable and tell, not the whole IO protocol.", "zip_file", "=", "ZipFile", "(", "wheel", ")", "# type: ignore", "# After context manager exit, wheel.name", "# is an invalid file by intention.", "return", "pkg_resources_distribution_for_wheel", "(", "zip_file", ",", "name", ",", "wheel", ".", "name", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/network/lazy_wheel.py#L29-L44
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/coverage/parser.py
python
ByteParser._find_statements
(self)
return stmts
Find the statements in `self.code`. Return a set of line numbers that start statements. Recurses into all code objects reachable from `self.code`.
Find the statements in `self.code`.
[ "Find", "the", "statements", "in", "self", ".", "code", "." ]
def _find_statements(self): """Find the statements in `self.code`. Return a set of line numbers that start statements. Recurses into all code objects reachable from `self.code`. """ stmts = set() for bp in self.child_parsers(): # Get all of the lineno information from this code. for _, l in bp._bytes_lines(): stmts.add(l) return stmts
[ "def", "_find_statements", "(", "self", ")", ":", "stmts", "=", "set", "(", ")", "for", "bp", "in", "self", ".", "child_parsers", "(", ")", ":", "# Get all of the lineno information from this code.", "for", "_", ",", "l", "in", "bp", ".", "_bytes_lines", "(", ")", ":", "stmts", ".", "add", "(", "l", ")", "return", "stmts" ]
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/coverage/parser.py#L394-L406
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
DQM/Integration/scripts/harvesting_tools/cmsHarvester.py
python
CMSHarvester.build_dataset_list
(self, input_method, input_name)
return dataset_names
Build a list of all datasets to be processed.
Build a list of all datasets to be processed.
[ "Build", "a", "list", "of", "all", "datasets", "to", "be", "processed", "." ]
def build_dataset_list(self, input_method, input_name): """Build a list of all datasets to be processed. """ dataset_names = [] # It may be, but only for the list of datasets to ignore, that # the input method and name are None because nothing was # specified. In that case just an empty list is returned. if input_method is None: pass elif input_method == "dataset": # Input comes from a dataset name directly on the command # line. But, this can also contain wildcards so we need # DBS to translate it conclusively into a list of explicit # dataset names. self.logger.info("Asking DBS for dataset names") dataset_names = self.dbs_resolve_dataset_name(input_name) elif input_method == "datasetfile": # In this case a file containing a list of dataset names # is specified. Still, each line may contain wildcards so # this step also needs help from DBS. # NOTE: Lines starting with a `#' are ignored. self.logger.info("Reading input from list file `%s'" % \ input_name) try: listfile = open("/afs/cern.ch/cms/CAF/CMSCOMM/COMM_DQM/harvesting/bin/%s" %input_name, "r") print("open listfile") for dataset in listfile: # Skip empty lines. dataset_stripped = dataset.strip() if len(dataset_stripped) < 1: continue # Skip lines starting with a `#'. if dataset_stripped[0] != "#": dataset_names.extend(self. \ dbs_resolve_dataset_name(dataset_stripped)) listfile.close() except IOError: msg = "ERROR: Could not open input list file `%s'" % \ input_name self.logger.fatal(msg) raise Error(msg) else: # DEBUG DEBUG DEBUG # We should never get here. assert False, "Unknown input method `%s'" % input_method # DEBUG DEBUG DEBUG end # Remove duplicates from the dataset list. # NOTE: There should not be any duplicates in any list coming # from DBS, but maybe the user provided a list file with less # care. # Store for later use. dataset_names = sorted(set(dataset_names)) # End of build_dataset_list. return dataset_names
[ "def", "build_dataset_list", "(", "self", ",", "input_method", ",", "input_name", ")", ":", "dataset_names", "=", "[", "]", "# It may be, but only for the list of datasets to ignore, that", "# the input method and name are None because nothing was", "# specified. In that case just an empty list is returned.", "if", "input_method", "is", "None", ":", "pass", "elif", "input_method", "==", "\"dataset\"", ":", "# Input comes from a dataset name directly on the command", "# line. But, this can also contain wildcards so we need", "# DBS to translate it conclusively into a list of explicit", "# dataset names.", "self", ".", "logger", ".", "info", "(", "\"Asking DBS for dataset names\"", ")", "dataset_names", "=", "self", ".", "dbs_resolve_dataset_name", "(", "input_name", ")", "elif", "input_method", "==", "\"datasetfile\"", ":", "# In this case a file containing a list of dataset names", "# is specified. Still, each line may contain wildcards so", "# this step also needs help from DBS.", "# NOTE: Lines starting with a `#' are ignored.", "self", ".", "logger", ".", "info", "(", "\"Reading input from list file `%s'\"", "%", "input_name", ")", "try", ":", "listfile", "=", "open", "(", "\"/afs/cern.ch/cms/CAF/CMSCOMM/COMM_DQM/harvesting/bin/%s\"", "%", "input_name", ",", "\"r\"", ")", "print", "(", "\"open listfile\"", ")", "for", "dataset", "in", "listfile", ":", "# Skip empty lines.", "dataset_stripped", "=", "dataset", ".", "strip", "(", ")", "if", "len", "(", "dataset_stripped", ")", "<", "1", ":", "continue", "# Skip lines starting with a `#'.", "if", "dataset_stripped", "[", "0", "]", "!=", "\"#\"", ":", "dataset_names", ".", "extend", "(", "self", ".", "dbs_resolve_dataset_name", "(", "dataset_stripped", ")", ")", "listfile", ".", "close", "(", ")", "except", "IOError", ":", "msg", "=", "\"ERROR: Could not open input list file `%s'\"", "%", "input_name", "self", ".", "logger", ".", "fatal", "(", "msg", ")", "raise", "Error", "(", "msg", ")", "else", ":", "# DEBUG DEBUG DEBUG", "# We should never get here.", "assert", "False", ",", "\"Unknown input method `%s'\"", "%", "input_method", "# DEBUG DEBUG DEBUG end", "# Remove duplicates from the dataset list.", "# NOTE: There should not be any duplicates in any list coming", "# from DBS, but maybe the user provided a list file with less", "# care.", "# Store for later use.", "dataset_names", "=", "sorted", "(", "set", "(", "dataset_names", ")", ")", "# End of build_dataset_list.", "return", "dataset_names" ]
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/DQM/Integration/scripts/harvesting_tools/cmsHarvester.py#L3357-L3416
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py
python
nanoFTPScanProxy
(URL)
(Re)Initialize the FTP Proxy context by parsing the URL and finding the protocol host port it indicates. Should be like ftp://myproxy/ or ftp://myproxy:3128/ A None URL cleans up proxy informations.
(Re)Initialize the FTP Proxy context by parsing the URL and finding the protocol host port it indicates. Should be like ftp://myproxy/ or ftp://myproxy:3128/ A None URL cleans up proxy informations.
[ "(", "Re", ")", "Initialize", "the", "FTP", "Proxy", "context", "by", "parsing", "the", "URL", "and", "finding", "the", "protocol", "host", "port", "it", "indicates", ".", "Should", "be", "like", "ftp", ":", "//", "myproxy", "/", "or", "ftp", ":", "//", "myproxy", ":", "3128", "/", "A", "None", "URL", "cleans", "up", "proxy", "informations", "." ]
def nanoFTPScanProxy(URL): """(Re)Initialize the FTP Proxy context by parsing the URL and finding the protocol host port it indicates. Should be like ftp://myproxy/ or ftp://myproxy:3128/ A None URL cleans up proxy informations. """ libxml2mod.xmlNanoFTPScanProxy(URL)
[ "def", "nanoFTPScanProxy", "(", "URL", ")", ":", "libxml2mod", ".", "xmlNanoFTPScanProxy", "(", "URL", ")" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L452-L457
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/simpla/_platoon.py
python
Platoon.getMode
(self)
return mode
getMode() -> PlatoonMode Returns the platoon leader's desired PlatoonMode (may return LEADER if current mode is FOLLOWER).
getMode() -> PlatoonMode
[ "getMode", "()", "-", ">", "PlatoonMode" ]
def getMode(self): '''getMode() -> PlatoonMode Returns the platoon leader's desired PlatoonMode (may return LEADER if current mode is FOLLOWER). ''' mode = self._vehicles[0].getCurrentPlatoonMode() if mode == PlatoonMode.FOLLOWER: # Leader was kept in FOLLOW mode due to safety constraints mode = PlatoonMode.LEADER elif mode == PlatoonMode.CATCHUP_FOLLOWER: # Leader was kept in CATCHUP_FOLLOW mode due to safety constraints mode = PlatoonMode.CATCHUP return mode
[ "def", "getMode", "(", "self", ")", ":", "mode", "=", "self", ".", "_vehicles", "[", "0", "]", ".", "getCurrentPlatoonMode", "(", ")", "if", "mode", "==", "PlatoonMode", ".", "FOLLOWER", ":", "# Leader was kept in FOLLOW mode due to safety constraints", "mode", "=", "PlatoonMode", ".", "LEADER", "elif", "mode", "==", "PlatoonMode", ".", "CATCHUP_FOLLOWER", ":", "# Leader was kept in CATCHUP_FOLLOW mode due to safety constraints", "mode", "=", "PlatoonMode", ".", "CATCHUP", "return", "mode" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/simpla/_platoon.py#L290-L302
lballabio/quantlib-old
136336947ed4fea9ecc1da6edad188700e821739
gensrc/gensrc/serialization/exceptions.py
python
SerializationDictException.__init__
(self, xmlDocumentName, dictElementName)
Initialize the SerializationDictException object.
Initialize the SerializationDictException object.
[ "Initialize", "the", "SerializationDictException", "object", "." ]
def __init__(self, xmlDocumentName, dictElementName): """Initialize the SerializationDictException object.""" self.value_ = SerializationDictException.EMPTY_DICT_ERROR % { 'xmlDocumentName' : xmlDocumentName, 'dictElementName' : dictElementName }
[ "def", "__init__", "(", "self", ",", "xmlDocumentName", ",", "dictElementName", ")", ":", "self", ".", "value_", "=", "SerializationDictException", ".", "EMPTY_DICT_ERROR", "%", "{", "'xmlDocumentName'", ":", "xmlDocumentName", ",", "'dictElementName'", ":", "dictElementName", "}" ]
https://github.com/lballabio/quantlib-old/blob/136336947ed4fea9ecc1da6edad188700e821739/gensrc/gensrc/serialization/exceptions.py#L60-L64
sfzhang15/RefineDet
52b6fe23dc1a160fe710b7734576dca509bf4fae
python/caffe/draw.py
python
get_pooling_types_dict
()
return d
Get dictionary mapping pooling type number to type name
Get dictionary mapping pooling type number to type name
[ "Get", "dictionary", "mapping", "pooling", "type", "number", "to", "type", "name" ]
def get_pooling_types_dict(): """Get dictionary mapping pooling type number to type name """ desc = caffe_pb2.PoolingParameter.PoolMethod.DESCRIPTOR d = {} for k, v in desc.values_by_name.items(): d[v.number] = k return d
[ "def", "get_pooling_types_dict", "(", ")", ":", "desc", "=", "caffe_pb2", ".", "PoolingParameter", ".", "PoolMethod", ".", "DESCRIPTOR", "d", "=", "{", "}", "for", "k", ",", "v", "in", "desc", ".", "values_by_name", ".", "items", "(", ")", ":", "d", "[", "v", ".", "number", "]", "=", "k", "return", "d" ]
https://github.com/sfzhang15/RefineDet/blob/52b6fe23dc1a160fe710b7734576dca509bf4fae/python/caffe/draw.py#L36-L43
gimli-org/gimli
17aa2160de9b15ababd9ef99e89b1bc3277bbb23
doc/tutorials/dev/solverFVM.py
python
findVelocity
(mesh, v, b, c, nc=None)
return vel
Find velocity for boundary b based on vector field v Parameters ---------- mesh : :gimliapi:`GIMLI::Mesh` v : Vector field [[x,y,z]] Cell based or Boundary based b : :gimliapi:`GIMLI::Boundary` Boundary c : :gimliapi:`GIMLI::Cell` Associated Cell in flow direction nc : :gimliapi:`GIMLI::Cell` Associated neighbor cell .. if one given from flow direction
Find velocity for boundary b based on vector field v
[ "Find", "velocity", "for", "boundary", "b", "based", "on", "vector", "field", "v" ]
def findVelocity(mesh, v, b, c, nc=None): """ Find velocity for boundary b based on vector field v Parameters ---------- mesh : :gimliapi:`GIMLI::Mesh` v : Vector field [[x,y,z]] Cell based or Boundary based b : :gimliapi:`GIMLI::Boundary` Boundary c : :gimliapi:`GIMLI::Cell` Associated Cell in flow direction nc : :gimliapi:`GIMLI::Cell` Associated neighbor cell .. if one given from flow direction """ vel = [0.0, 0.0, 0.0] if hasattr(v, '__len__'): if len(v) == mesh.cellCount(): if nc: # mean cell based vector-field v[x,y,z] for cell c and cell nc vel = (v[c.id()] + v[nc.id()])/2.0 else: # cell based vector-field v[x,y,z] for cell c vel = v[c.id()] elif len(v) == mesh.boundaryCount(): vel = v[b.id()] else: # interpolate node based vector-field v[x,y,z] at point b.center() vel = c.vec(b.center(), v) return vel
[ "def", "findVelocity", "(", "mesh", ",", "v", ",", "b", ",", "c", ",", "nc", "=", "None", ")", ":", "vel", "=", "[", "0.0", ",", "0.0", ",", "0.0", "]", "if", "hasattr", "(", "v", ",", "'__len__'", ")", ":", "if", "len", "(", "v", ")", "==", "mesh", ".", "cellCount", "(", ")", ":", "if", "nc", ":", "# mean cell based vector-field v[x,y,z] for cell c and cell nc", "vel", "=", "(", "v", "[", "c", ".", "id", "(", ")", "]", "+", "v", "[", "nc", ".", "id", "(", ")", "]", ")", "/", "2.0", "else", ":", "# cell based vector-field v[x,y,z] for cell c", "vel", "=", "v", "[", "c", ".", "id", "(", ")", "]", "elif", "len", "(", "v", ")", "==", "mesh", ".", "boundaryCount", "(", ")", ":", "vel", "=", "v", "[", "b", ".", "id", "(", ")", "]", "else", ":", "# interpolate node based vector-field v[x,y,z] at point b.center()", "vel", "=", "c", ".", "vec", "(", "b", ".", "center", "(", ")", ",", "v", ")", "return", "vel" ]
https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/doc/tutorials/dev/solverFVM.py#L253-L291
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/sparse/csc.py
python
isspmatrix_csc
(x)
return isinstance(x, csc_matrix)
Is x of csc_matrix type? Parameters ---------- x object to check for being a csc matrix Returns ------- bool True if x is a csc matrix, False otherwise Examples -------- >>> from scipy.sparse import csc_matrix, isspmatrix_csc >>> isspmatrix_csc(csc_matrix([[5]])) True >>> from scipy.sparse import csc_matrix, csr_matrix, isspmatrix_csc >>> isspmatrix_csc(csr_matrix([[5]])) False
Is x of csc_matrix type?
[ "Is", "x", "of", "csc_matrix", "type?" ]
def isspmatrix_csc(x): """Is x of csc_matrix type? Parameters ---------- x object to check for being a csc matrix Returns ------- bool True if x is a csc matrix, False otherwise Examples -------- >>> from scipy.sparse import csc_matrix, isspmatrix_csc >>> isspmatrix_csc(csc_matrix([[5]])) True >>> from scipy.sparse import csc_matrix, csr_matrix, isspmatrix_csc >>> isspmatrix_csc(csr_matrix([[5]])) False """ return isinstance(x, csc_matrix)
[ "def", "isspmatrix_csc", "(", "x", ")", ":", "return", "isinstance", "(", "x", ",", "csc_matrix", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/sparse/csc.py#L230-L253
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Tools/scripts/patchcheck.py
python
normalize_whitespace
(file_paths)
return fixed
Make sure that the whitespace for .py files have been normalized.
Make sure that the whitespace for .py files have been normalized.
[ "Make", "sure", "that", "the", "whitespace", "for", ".", "py", "files", "have", "been", "normalized", "." ]
def normalize_whitespace(file_paths): """Make sure that the whitespace for .py files have been normalized.""" reindent.makebackup = False # No need to create backups. fixed = [path for path in file_paths if path.endswith('.py') and reindent.check(os.path.join(SRCDIR, path))] return fixed
[ "def", "normalize_whitespace", "(", "file_paths", ")", ":", "reindent", ".", "makebackup", "=", "False", "# No need to create backups.", "fixed", "=", "[", "path", "for", "path", "in", "file_paths", "if", "path", ".", "endswith", "(", "'.py'", ")", "and", "reindent", ".", "check", "(", "os", ".", "path", ".", "join", "(", "SRCDIR", ",", "path", ")", ")", "]", "return", "fixed" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Tools/scripts/patchcheck.py#L146-L151
cvxpy/cvxpy
5165b4fb750dfd237de8659383ef24b4b2e33aaf
cvxpy/atoms/norm_inf.py
python
norm_inf.is_incr
(self, idx)
return self.args[0].is_nonneg()
Is the composition non-decreasing in argument idx?
Is the composition non-decreasing in argument idx?
[ "Is", "the", "composition", "non", "-", "decreasing", "in", "argument", "idx?" ]
def is_incr(self, idx) -> bool: """Is the composition non-decreasing in argument idx? """ return self.args[0].is_nonneg()
[ "def", "is_incr", "(", "self", ",", "idx", ")", "->", "bool", ":", "return", "self", ".", "args", "[", "0", "]", ".", "is_nonneg", "(", ")" ]
https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/atoms/norm_inf.py#L66-L69
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py3/IPython/core/completer.py
python
cursor_to_position
(text:str, line:int, column:int)
return sum(len(l) + 1 for l in lines[:line]) + column
Convert the (line,column) position of the cursor in text to an offset in a string. Parameters ---------- text : str The text in which to calculate the cursor offset line : int Line of the cursor; 0-indexed column : int Column of the cursor 0-indexed Return ------ Position of the cursor in ``text``, 0-indexed. See Also -------- position_to_cursor: reciprocal of this function
[]
def cursor_to_position(text:str, line:int, column:int)->int: """ Convert the (line,column) position of the cursor in text to an offset in a string. Parameters ---------- text : str The text in which to calculate the cursor offset line : int Line of the cursor; 0-indexed column : int Column of the cursor 0-indexed Return ------ Position of the cursor in ``text``, 0-indexed. See Also -------- position_to_cursor: reciprocal of this function """ lines = text.split('\n') assert line <= len(lines), '{} <= {}'.format(str(line), str(len(lines))) return sum(len(l) + 1 for l in lines[:line]) + column
[ "def", "cursor_to_position", "(", "text", ":", "str", ",", "line", ":", "int", ",", "column", ":", "int", ")", "->", "int", ":", "lines", "=", "text", ".", "split", "(", "'\\n'", ")", "assert", "line", "<=", "len", "(", "lines", ")", ",", "'{} <= {}'", ".", "format", "(", "str", "(", "line", ")", ",", "str", "(", "len", "(", "lines", ")", ")", ")", "return", "sum", "(", "len", "(", "l", ")", "+", "1", "for", "l", "in", "lines", "[", ":", "line", "]", ")", "+", "column" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/core/completer.py#L829-L857
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/propgrid.py
python
PropertyGrid.AutoGetTranslation
(*args, **kwargs)
return _propgrid.PropertyGrid_AutoGetTranslation(*args, **kwargs)
AutoGetTranslation(bool enable)
AutoGetTranslation(bool enable)
[ "AutoGetTranslation", "(", "bool", "enable", ")" ]
def AutoGetTranslation(*args, **kwargs): """AutoGetTranslation(bool enable)""" return _propgrid.PropertyGrid_AutoGetTranslation(*args, **kwargs)
[ "def", "AutoGetTranslation", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PropertyGrid_AutoGetTranslation", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/propgrid.py#L1991-L1993
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/protobuf/py3/google/protobuf/internal/python_message.py
python
_AddClearFieldMethod
(message_descriptor, cls)
Helper for _AddMessageMethods().
Helper for _AddMessageMethods().
[ "Helper", "for", "_AddMessageMethods", "()", "." ]
def _AddClearFieldMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def ClearField(self, field_name): try: field = message_descriptor.fields_by_name[field_name] except KeyError: try: field = message_descriptor.oneofs_by_name[field_name] if field in self._oneofs: field = self._oneofs[field] else: return except KeyError: raise ValueError('Protocol message %s has no "%s" field.' % (message_descriptor.name, field_name)) if field in self._fields: # To match the C++ implementation, we need to invalidate iterators # for map fields when ClearField() happens. if hasattr(self._fields[field], 'InvalidateIterators'): self._fields[field].InvalidateIterators() # Note: If the field is a sub-message, its listener will still point # at us. That's fine, because the worst than can happen is that it # will call _Modified() and invalidate our byte size. Big deal. del self._fields[field] if self._oneofs.get(field.containing_oneof, None) is field: del self._oneofs[field.containing_oneof] # Always call _Modified() -- even if nothing was changed, this is # a mutating method, and thus calling it should cause the field to become # present in the parent message. self._Modified() cls.ClearField = ClearField
[ "def", "_AddClearFieldMethod", "(", "message_descriptor", ",", "cls", ")", ":", "def", "ClearField", "(", "self", ",", "field_name", ")", ":", "try", ":", "field", "=", "message_descriptor", ".", "fields_by_name", "[", "field_name", "]", "except", "KeyError", ":", "try", ":", "field", "=", "message_descriptor", ".", "oneofs_by_name", "[", "field_name", "]", "if", "field", "in", "self", ".", "_oneofs", ":", "field", "=", "self", ".", "_oneofs", "[", "field", "]", "else", ":", "return", "except", "KeyError", ":", "raise", "ValueError", "(", "'Protocol message %s has no \"%s\" field.'", "%", "(", "message_descriptor", ".", "name", ",", "field_name", ")", ")", "if", "field", "in", "self", ".", "_fields", ":", "# To match the C++ implementation, we need to invalidate iterators", "# for map fields when ClearField() happens.", "if", "hasattr", "(", "self", ".", "_fields", "[", "field", "]", ",", "'InvalidateIterators'", ")", ":", "self", ".", "_fields", "[", "field", "]", ".", "InvalidateIterators", "(", ")", "# Note: If the field is a sub-message, its listener will still point", "# at us. That's fine, because the worst than can happen is that it", "# will call _Modified() and invalidate our byte size. Big deal.", "del", "self", ".", "_fields", "[", "field", "]", "if", "self", ".", "_oneofs", ".", "get", "(", "field", ".", "containing_oneof", ",", "None", ")", "is", "field", ":", "del", "self", ".", "_oneofs", "[", "field", ".", "containing_oneof", "]", "# Always call _Modified() -- even if nothing was changed, this is", "# a mutating method, and thus calling it should cause the field to become", "# present in the parent message.", "self", ".", "_Modified", "(", ")", "cls", ".", "ClearField", "=", "ClearField" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py3/google/protobuf/internal/python_message.py#L885-L920
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
InputStream.close
(*args, **kwargs)
return _core_.InputStream_close(*args, **kwargs)
close(self)
close(self)
[ "close", "(", "self", ")" ]
def close(*args, **kwargs): """close(self)""" return _core_.InputStream_close(*args, **kwargs)
[ "def", "close", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "InputStream_close", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L2158-L2160
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/input.py
python
Unify
(l)
return [seen.setdefault(e, e) for e in l if e not in seen]
Removes duplicate elements from l, keeping the first element.
Removes duplicate elements from l, keeping the first element.
[ "Removes", "duplicate", "elements", "from", "l", "keeping", "the", "first", "element", "." ]
def Unify(l): """Removes duplicate elements from l, keeping the first element.""" seen = {} return [seen.setdefault(e, e) for e in l if e not in seen]
[ "def", "Unify", "(", "l", ")", ":", "seen", "=", "{", "}", "return", "[", "seen", ".", "setdefault", "(", "e", ",", "e", ")", "for", "e", "in", "l", "if", "e", "not", "in", "seen", "]" ]
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/input.py#L1466-L1469
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/robotsim.py
python
RobotModel.getConfig
(self)
return _robotsim.RobotModel_getConfig(self)
getConfig(RobotModel self) Retrieves the current configuration of the robot model.
getConfig(RobotModel self)
[ "getConfig", "(", "RobotModel", "self", ")" ]
def getConfig(self): """ getConfig(RobotModel self) Retrieves the current configuration of the robot model. """ return _robotsim.RobotModel_getConfig(self)
[ "def", "getConfig", "(", "self", ")", ":", "return", "_robotsim", ".", "RobotModel_getConfig", "(", "self", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/robotsim.py#L4630-L4639
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
benchmark/opperf/utils/op_registry_utils.py
python
get_all_broadcast_binary_operators
()
return binary_broadcast_mx_operators
Gets all binary broadcast operators registered with MXNet. Returns ------- {"operator_name": {"has_backward", "nd_op_handle", "params"}}
Gets all binary broadcast operators registered with MXNet.
[ "Gets", "all", "binary", "broadcast", "operators", "registered", "with", "MXNet", "." ]
def get_all_broadcast_binary_operators(): """Gets all binary broadcast operators registered with MXNet. Returns ------- {"operator_name": {"has_backward", "nd_op_handle", "params"}} """ # Get all mxnet operators mx_operators = _get_all_mxnet_operators() # Filter for binary broadcast operators binary_broadcast_mx_operators = {} for op_name, op_params in mx_operators.items(): if op_name.startswith("broadcast_") and op_params["params"]["narg"] == 2 and \ "lhs" in op_params["params"]["arg_names"] and \ "rhs" in op_params["params"]["arg_names"]: binary_broadcast_mx_operators[op_name] = mx_operators[op_name] return binary_broadcast_mx_operators
[ "def", "get_all_broadcast_binary_operators", "(", ")", ":", "# Get all mxnet operators", "mx_operators", "=", "_get_all_mxnet_operators", "(", ")", "# Filter for binary broadcast operators", "binary_broadcast_mx_operators", "=", "{", "}", "for", "op_name", ",", "op_params", "in", "mx_operators", ".", "items", "(", ")", ":", "if", "op_name", ".", "startswith", "(", "\"broadcast_\"", ")", "and", "op_params", "[", "\"params\"", "]", "[", "\"narg\"", "]", "==", "2", "and", "\"lhs\"", "in", "op_params", "[", "\"params\"", "]", "[", "\"arg_names\"", "]", "and", "\"rhs\"", "in", "op_params", "[", "\"params\"", "]", "[", "\"arg_names\"", "]", ":", "binary_broadcast_mx_operators", "[", "op_name", "]", "=", "mx_operators", "[", "op_name", "]", "return", "binary_broadcast_mx_operators" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/benchmark/opperf/utils/op_registry_utils.py#L237-L254
GoSSIP-SJTU/TripleDoggy
03648d6b19c812504b14e8b98c8c7b3f443f4e54
utils/lit/lit/llvm/config.py
python
LLVMConfig.use_clang
(self, required=True)
Configure the test suite to be able to invoke clang. Sets up some environment variables important to clang, locates a just-built or installed clang, and add a set of standard substitutions useful to any test suite that makes use of clang.
Configure the test suite to be able to invoke clang.
[ "Configure", "the", "test", "suite", "to", "be", "able", "to", "invoke", "clang", "." ]
def use_clang(self, required=True): """Configure the test suite to be able to invoke clang. Sets up some environment variables important to clang, locates a just-built or installed clang, and add a set of standard substitutions useful to any test suite that makes use of clang. """ # Clear some environment variables that might affect Clang. # # This first set of vars are read by Clang, but shouldn't affect tests # that aren't specifically looking for these features, or are required # simply to run the tests at all. # # FIXME: Should we have a tool that enforces this? # safe_env_vars = ('TMPDIR', 'TEMP', 'TMP', 'USERPROFILE', 'PWD', # 'MACOSX_DEPLOYMENT_TARGET', 'IPHONEOS_DEPLOYMENT_TARGET', # 'VCINSTALLDIR', 'VC100COMNTOOLS', 'VC90COMNTOOLS', # 'VC80COMNTOOLS') possibly_dangerous_env_vars = ['COMPILER_PATH', 'RC_DEBUG_OPTIONS', 'CINDEXTEST_PREAMBLE_FILE', 'LIBRARY_PATH', 'CPATH', 'C_INCLUDE_PATH', 'CPLUS_INCLUDE_PATH', 'OBJC_INCLUDE_PATH', 'OBJCPLUS_INCLUDE_PATH', 'LIBCLANG_TIMING', 'LIBCLANG_OBJTRACKING', 'LIBCLANG_LOGGING', 'LIBCLANG_BGPRIO_INDEX', 'LIBCLANG_BGPRIO_EDIT', 'LIBCLANG_NOTHREADS', 'LIBCLANG_RESOURCE_USAGE', 'LIBCLANG_CODE_COMPLETION_LOGGING'] # Clang/Win32 may refer to %INCLUDE%. vsvarsall.bat sets it. if platform.system() != 'Windows': possibly_dangerous_env_vars.append('INCLUDE') self.clear_environment(possibly_dangerous_env_vars) # Tweak the PATH to include the tools dir and the scripts dir. # Put Clang first to avoid LLVM from overriding out-of-tree clang builds. possible_paths = ['clang_tools_dir', 'llvm_tools_dir'] paths = [getattr(self.config, pp) for pp in possible_paths if getattr(self.config, pp, None)] self.with_environment('PATH', paths, append_path=True) paths = [self.config.llvm_shlib_dir, self.config.llvm_libs_dir] self.with_environment('LD_LIBRARY_PATH', paths, append_path=True) # Discover the 'clang' and 'clangcc' to use. self.config.clang = self.use_llvm_tool( 'clang', search_env='CLANG', required=required) self.config.substitutions.append( ('%llvmshlibdir', self.config.llvm_shlib_dir)) self.config.substitutions.append( ('%pluginext', self.config.llvm_plugin_ext)) builtin_include_dir = self.get_clang_builtin_include_dir(self.config.clang) tool_substitutions = [ ToolSubst('%clang', command=self.config.clang), ToolSubst('%clang_analyze_cc1', command='%clang_cc1', extra_args=['-analyze']), ToolSubst('%clang_cc1', command=self.config.clang, extra_args=['-cc1', '-internal-isystem', builtin_include_dir, '-nostdsysteminc']), ToolSubst('%clang_cpp', command=self.config.clang, extra_args=['--driver-mode=cpp']), ToolSubst('%clang_cl', command=self.config.clang, extra_args=['--driver-mode=cl']), ToolSubst('%clangxx', command=self.config.clang, extra_args=['--driver-mode=g++']), ] self.add_tool_substitutions(tool_substitutions) self.config.substitutions.append(('%itanium_abi_triple', self.make_itanium_abi_triple(self.config.target_triple))) self.config.substitutions.append(('%ms_abi_triple', self.make_msabi_triple(self.config.target_triple))) self.config.substitutions.append( ('%resource_dir', builtin_include_dir)) # The host triple might not be set, at least if we're compiling clang from # an already installed llvm. if self.config.host_triple and self.config.host_triple != '@LLVM_HOST_TRIPLE@': self.config.substitutions.append(('%target_itanium_abi_host_triple', '--target=%s' % self.make_itanium_abi_triple(self.config.host_triple))) else: self.config.substitutions.append( ('%target_itanium_abi_host_triple', '')) self.config.substitutions.append( ('%src_include_dir', self.config.clang_src_dir + '/include')) # FIXME: Find nicer way to prohibit this. self.config.substitutions.append( (' clang ', """*** Do not use 'clang' in tests, use '%clang'. ***""")) self.config.substitutions.append( (' clang\+\+ ', """*** Do not use 'clang++' in tests, use '%clangxx'. ***""")) self.config.substitutions.append( (' clang-cc ', """*** Do not use 'clang-cc' in tests, use '%clang_cc1'. ***""")) self.config.substitutions.append( (' clang -cc1 -analyze ', """*** Do not use 'clang -cc1 -analyze' in tests, use '%clang_analyze_cc1'. ***""")) self.config.substitutions.append( (' clang -cc1 ', """*** Do not use 'clang -cc1' in tests, use '%clang_cc1'. ***""")) self.config.substitutions.append( (' %clang-cc1 ', """*** invalid substitution, use '%clang_cc1'. ***""")) self.config.substitutions.append( (' %clang-cpp ', """*** invalid substitution, use '%clang_cpp'. ***""")) self.config.substitutions.append( (' %clang-cl ', """*** invalid substitution, use '%clang_cl'. ***"""))
[ "def", "use_clang", "(", "self", ",", "required", "=", "True", ")", ":", "# Clear some environment variables that might affect Clang.", "#", "# This first set of vars are read by Clang, but shouldn't affect tests", "# that aren't specifically looking for these features, or are required", "# simply to run the tests at all.", "#", "# FIXME: Should we have a tool that enforces this?", "# safe_env_vars = ('TMPDIR', 'TEMP', 'TMP', 'USERPROFILE', 'PWD',", "# 'MACOSX_DEPLOYMENT_TARGET', 'IPHONEOS_DEPLOYMENT_TARGET',", "# 'VCINSTALLDIR', 'VC100COMNTOOLS', 'VC90COMNTOOLS',", "# 'VC80COMNTOOLS')", "possibly_dangerous_env_vars", "=", "[", "'COMPILER_PATH'", ",", "'RC_DEBUG_OPTIONS'", ",", "'CINDEXTEST_PREAMBLE_FILE'", ",", "'LIBRARY_PATH'", ",", "'CPATH'", ",", "'C_INCLUDE_PATH'", ",", "'CPLUS_INCLUDE_PATH'", ",", "'OBJC_INCLUDE_PATH'", ",", "'OBJCPLUS_INCLUDE_PATH'", ",", "'LIBCLANG_TIMING'", ",", "'LIBCLANG_OBJTRACKING'", ",", "'LIBCLANG_LOGGING'", ",", "'LIBCLANG_BGPRIO_INDEX'", ",", "'LIBCLANG_BGPRIO_EDIT'", ",", "'LIBCLANG_NOTHREADS'", ",", "'LIBCLANG_RESOURCE_USAGE'", ",", "'LIBCLANG_CODE_COMPLETION_LOGGING'", "]", "# Clang/Win32 may refer to %INCLUDE%. vsvarsall.bat sets it.", "if", "platform", ".", "system", "(", ")", "!=", "'Windows'", ":", "possibly_dangerous_env_vars", ".", "append", "(", "'INCLUDE'", ")", "self", ".", "clear_environment", "(", "possibly_dangerous_env_vars", ")", "# Tweak the PATH to include the tools dir and the scripts dir.", "# Put Clang first to avoid LLVM from overriding out-of-tree clang builds.", "possible_paths", "=", "[", "'clang_tools_dir'", ",", "'llvm_tools_dir'", "]", "paths", "=", "[", "getattr", "(", "self", ".", "config", ",", "pp", ")", "for", "pp", "in", "possible_paths", "if", "getattr", "(", "self", ".", "config", ",", "pp", ",", "None", ")", "]", "self", ".", "with_environment", "(", "'PATH'", ",", "paths", ",", "append_path", "=", "True", ")", "paths", "=", "[", "self", ".", "config", ".", "llvm_shlib_dir", ",", "self", ".", "config", ".", "llvm_libs_dir", "]", "self", ".", "with_environment", "(", "'LD_LIBRARY_PATH'", ",", "paths", ",", "append_path", "=", "True", ")", "# Discover the 'clang' and 'clangcc' to use.", "self", ".", "config", ".", "clang", "=", "self", ".", "use_llvm_tool", "(", "'clang'", ",", "search_env", "=", "'CLANG'", ",", "required", "=", "required", ")", "self", ".", "config", ".", "substitutions", ".", "append", "(", "(", "'%llvmshlibdir'", ",", "self", ".", "config", ".", "llvm_shlib_dir", ")", ")", "self", ".", "config", ".", "substitutions", ".", "append", "(", "(", "'%pluginext'", ",", "self", ".", "config", ".", "llvm_plugin_ext", ")", ")", "builtin_include_dir", "=", "self", ".", "get_clang_builtin_include_dir", "(", "self", ".", "config", ".", "clang", ")", "tool_substitutions", "=", "[", "ToolSubst", "(", "'%clang'", ",", "command", "=", "self", ".", "config", ".", "clang", ")", ",", "ToolSubst", "(", "'%clang_analyze_cc1'", ",", "command", "=", "'%clang_cc1'", ",", "extra_args", "=", "[", "'-analyze'", "]", ")", ",", "ToolSubst", "(", "'%clang_cc1'", ",", "command", "=", "self", ".", "config", ".", "clang", ",", "extra_args", "=", "[", "'-cc1'", ",", "'-internal-isystem'", ",", "builtin_include_dir", ",", "'-nostdsysteminc'", "]", ")", ",", "ToolSubst", "(", "'%clang_cpp'", ",", "command", "=", "self", ".", "config", ".", "clang", ",", "extra_args", "=", "[", "'--driver-mode=cpp'", "]", ")", ",", "ToolSubst", "(", "'%clang_cl'", ",", "command", "=", "self", ".", "config", ".", "clang", ",", "extra_args", "=", "[", "'--driver-mode=cl'", "]", ")", ",", "ToolSubst", "(", "'%clangxx'", ",", "command", "=", "self", ".", "config", ".", "clang", ",", "extra_args", "=", "[", "'--driver-mode=g++'", "]", ")", ",", "]", "self", ".", "add_tool_substitutions", "(", "tool_substitutions", ")", "self", ".", "config", ".", "substitutions", ".", "append", "(", "(", "'%itanium_abi_triple'", ",", "self", ".", "make_itanium_abi_triple", "(", "self", ".", "config", ".", "target_triple", ")", ")", ")", "self", ".", "config", ".", "substitutions", ".", "append", "(", "(", "'%ms_abi_triple'", ",", "self", ".", "make_msabi_triple", "(", "self", ".", "config", ".", "target_triple", ")", ")", ")", "self", ".", "config", ".", "substitutions", ".", "append", "(", "(", "'%resource_dir'", ",", "builtin_include_dir", ")", ")", "# The host triple might not be set, at least if we're compiling clang from", "# an already installed llvm.", "if", "self", ".", "config", ".", "host_triple", "and", "self", ".", "config", ".", "host_triple", "!=", "'@LLVM_HOST_TRIPLE@'", ":", "self", ".", "config", ".", "substitutions", ".", "append", "(", "(", "'%target_itanium_abi_host_triple'", ",", "'--target=%s'", "%", "self", ".", "make_itanium_abi_triple", "(", "self", ".", "config", ".", "host_triple", ")", ")", ")", "else", ":", "self", ".", "config", ".", "substitutions", ".", "append", "(", "(", "'%target_itanium_abi_host_triple'", ",", "''", ")", ")", "self", ".", "config", ".", "substitutions", ".", "append", "(", "(", "'%src_include_dir'", ",", "self", ".", "config", ".", "clang_src_dir", "+", "'/include'", ")", ")", "# FIXME: Find nicer way to prohibit this.", "self", ".", "config", ".", "substitutions", ".", "append", "(", "(", "' clang '", ",", "\"\"\"*** Do not use 'clang' in tests, use '%clang'. ***\"\"\"", ")", ")", "self", ".", "config", ".", "substitutions", ".", "append", "(", "(", "' clang\\+\\+ '", ",", "\"\"\"*** Do not use 'clang++' in tests, use '%clangxx'. ***\"\"\"", ")", ")", "self", ".", "config", ".", "substitutions", ".", "append", "(", "(", "' clang-cc '", ",", "\"\"\"*** Do not use 'clang-cc' in tests, use '%clang_cc1'. ***\"\"\"", ")", ")", "self", ".", "config", ".", "substitutions", ".", "append", "(", "(", "' clang -cc1 -analyze '", ",", "\"\"\"*** Do not use 'clang -cc1 -analyze' in tests, use '%clang_analyze_cc1'. ***\"\"\"", ")", ")", "self", ".", "config", ".", "substitutions", ".", "append", "(", "(", "' clang -cc1 '", ",", "\"\"\"*** Do not use 'clang -cc1' in tests, use '%clang_cc1'. ***\"\"\"", ")", ")", "self", ".", "config", ".", "substitutions", ".", "append", "(", "(", "' %clang-cc1 '", ",", "\"\"\"*** invalid substitution, use '%clang_cc1'. ***\"\"\"", ")", ")", "self", ".", "config", ".", "substitutions", ".", "append", "(", "(", "' %clang-cpp '", ",", "\"\"\"*** invalid substitution, use '%clang_cpp'. ***\"\"\"", ")", ")", "self", ".", "config", ".", "substitutions", ".", "append", "(", "(", "' %clang-cl '", ",", "\"\"\"*** invalid substitution, use '%clang_cl'. ***\"\"\"", ")", ")" ]
https://github.com/GoSSIP-SJTU/TripleDoggy/blob/03648d6b19c812504b14e8b98c8c7b3f443f4e54/utils/lit/lit/llvm/config.py#L337-L444
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/hfctables.py
python
SinglePtIntegrationTable.__init__
(self, parent)
return
initialization :param parent:
initialization :param parent:
[ "initialization", ":", "param", "parent", ":" ]
def __init__(self, parent): """ initialization :param parent: """ super(SinglePtIntegrationTable, self).__init__(parent) # class variables self._scan_index = None self._pt_index = None self._hkl_index = None self._height_index = None self._2theta_index = None self._fwhm_index = None self._intensity_index = None self._2thta_scans_index = None self._ref_scans_index = None self._roi_index = None self._pt_row_dict = dict() return
[ "def", "__init__", "(", "self", ",", "parent", ")", ":", "super", "(", "SinglePtIntegrationTable", ",", "self", ")", ".", "__init__", "(", "parent", ")", "# class variables", "self", ".", "_scan_index", "=", "None", "self", ".", "_pt_index", "=", "None", "self", ".", "_hkl_index", "=", "None", "self", ".", "_height_index", "=", "None", "self", ".", "_2theta_index", "=", "None", "self", ".", "_fwhm_index", "=", "None", "self", ".", "_intensity_index", "=", "None", "self", ".", "_2thta_scans_index", "=", "None", "self", ".", "_ref_scans_index", "=", "None", "self", ".", "_roi_index", "=", "None", "self", ".", "_pt_row_dict", "=", "dict", "(", ")", "return" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/hfctables.py#L1391-L1412
Samsung/veles
95ed733c2e49bc011ad98ccf2416ecec23fbf352
veles/external/prettytable.py
python
PrettyTable._get_horizontal_char
(self)
return self._horizontal_char
The charcter used when printing table borders to draw horizontal lines Arguments: horizontal_char - single character string used to draw horizontal lines
The charcter used when printing table borders to draw horizontal lines
[ "The", "charcter", "used", "when", "printing", "table", "borders", "to", "draw", "horizontal", "lines" ]
def _get_horizontal_char(self): """The charcter used when printing table borders to draw horizontal lines Arguments: horizontal_char - single character string used to draw horizontal lines""" return self._horizontal_char
[ "def", "_get_horizontal_char", "(", "self", ")", ":", "return", "self", ".", "_horizontal_char" ]
https://github.com/Samsung/veles/blob/95ed733c2e49bc011ad98ccf2416ecec23fbf352/veles/external/prettytable.py#L666-L672
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/multiprocessing/__init__.py
python
Lock
()
return Lock()
Returns a non-recursive lock object
Returns a non-recursive lock object
[ "Returns", "a", "non", "-", "recursive", "lock", "object" ]
def Lock(): ''' Returns a non-recursive lock object ''' from multiprocessing.synchronize import Lock return Lock()
[ "def", "Lock", "(", ")", ":", "from", "multiprocessing", ".", "synchronize", "import", "Lock", "return", "Lock", "(", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/multiprocessing/__init__.py#L171-L176
rootm0s/Protectors
5b3f4d11687a5955caf9c3af30666c4bfc2c19ab
OWASP-ZSC/module/readline_windows/pyreadline/modes/notemacs.py
python
NotEmacsMode.dump_functions
(self, e)
Print all of the functions and their key bindings to the Readline output stream. If a numeric argument is supplied, the output is formatted in such a way that it can be made part of an inputrc file. This command is unbound by default.
Print all of the functions and their key bindings to the Readline output stream. If a numeric argument is supplied, the output is formatted in such a way that it can be made part of an inputrc file. This command is unbound by default.
[ "Print", "all", "of", "the", "functions", "and", "their", "key", "bindings", "to", "the", "Readline", "output", "stream", ".", "If", "a", "numeric", "argument", "is", "supplied", "the", "output", "is", "formatted", "in", "such", "a", "way", "that", "it", "can", "be", "made", "part", "of", "an", "inputrc", "file", ".", "This", "command", "is", "unbound", "by", "default", "." ]
def dump_functions(self, e): # () '''Print all of the functions and their key bindings to the Readline output stream. If a numeric argument is supplied, the output is formatted in such a way that it can be made part of an inputrc file. This command is unbound by default.''' pass
[ "def", "dump_functions", "(", "self", ",", "e", ")", ":", "# ()", "pass" ]
https://github.com/rootm0s/Protectors/blob/5b3f4d11687a5955caf9c3af30666c4bfc2c19ab/OWASP-ZSC/module/readline_windows/pyreadline/modes/notemacs.py#L548-L553
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/dtypes/common.py
python
is_1d_only_ea_dtype
(dtype: Optional[DtypeObj])
return isinstance(dtype, ExtensionDtype) and not isinstance(dtype, DatetimeTZDtype)
Analogue to is_extension_array_dtype but excluding DatetimeTZDtype.
Analogue to is_extension_array_dtype but excluding DatetimeTZDtype.
[ "Analogue", "to", "is_extension_array_dtype", "but", "excluding", "DatetimeTZDtype", "." ]
def is_1d_only_ea_dtype(dtype: Optional[DtypeObj]) -> bool: """ Analogue to is_extension_array_dtype but excluding DatetimeTZDtype. """ # Note: if other EA dtypes are ever held in HybridBlock, exclude those # here too. # NB: need to check DatetimeTZDtype and not is_datetime64tz_dtype # to exclude ArrowTimestampUSDtype return isinstance(dtype, ExtensionDtype) and not isinstance(dtype, DatetimeTZDtype)
[ "def", "is_1d_only_ea_dtype", "(", "dtype", ":", "Optional", "[", "DtypeObj", "]", ")", "->", "bool", ":", "# Note: if other EA dtypes are ever held in HybridBlock, exclude those", "# here too.", "# NB: need to check DatetimeTZDtype and not is_datetime64tz_dtype", "# to exclude ArrowTimestampUSDtype", "return", "isinstance", "(", "dtype", ",", "ExtensionDtype", ")", "and", "not", "isinstance", "(", "dtype", ",", "DatetimeTZDtype", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/dtypes/common.py#L1409-L1417
deepmind/open_spiel
4ca53bea32bb2875c7385d215424048ae92f78c8
open_spiel/python/games/dynamic_routing.py
python
DynamicRoutingGameState.assert_valid_player
(self, vehicle: int)
Assert that a vehicle as a int between 0 and num_players.
Assert that a vehicle as a int between 0 and num_players.
[ "Assert", "that", "a", "vehicle", "as", "a", "int", "between", "0", "and", "num_players", "." ]
def assert_valid_player(self, vehicle: int): """Assert that a vehicle as a int between 0 and num_players.""" assert isinstance(vehicle, int), f"{vehicle} is not a int." assert vehicle >= 0, f"player: {vehicle}<0." assert vehicle < self.get_game().num_players(), ( f"player: {vehicle} >= num_players: {self.get_game().num_players()}")
[ "def", "assert_valid_player", "(", "self", ",", "vehicle", ":", "int", ")", ":", "assert", "isinstance", "(", "vehicle", ",", "int", ")", ",", "f\"{vehicle} is not a int.\"", "assert", "vehicle", ">=", "0", ",", "f\"player: {vehicle}<0.\"", "assert", "vehicle", "<", "self", ".", "get_game", "(", ")", ".", "num_players", "(", ")", ",", "(", "f\"player: {vehicle} >= num_players: {self.get_game().num_players()}\"", ")" ]
https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/games/dynamic_routing.py#L231-L236
ucla-vision/xivo
1b97bf5a3124e62bf4920429af5bb91c7a6de876
thirdparty/jsoncpp/devtools/batchbuild.py
python
fix_eol
(stdout)
return re.sub('\r*\n', os.linesep, stdout)
Fixes wrong EOL produced by cmake --build on Windows (\r\r\n instead of \r\n).
Fixes wrong EOL produced by cmake --build on Windows (\r\r\n instead of \r\n).
[ "Fixes", "wrong", "EOL", "produced", "by", "cmake", "--", "build", "on", "Windows", "(", "\\", "r", "\\", "r", "\\", "n", "instead", "of", "\\", "r", "\\", "n", ")", "." ]
def fix_eol(stdout): """Fixes wrong EOL produced by cmake --build on Windows (\r\r\n instead of \r\n). """ return re.sub('\r*\n', os.linesep, stdout)
[ "def", "fix_eol", "(", "stdout", ")", ":", "return", "re", ".", "sub", "(", "'\\r*\\n'", ",", "os", ".", "linesep", ",", "stdout", ")" ]
https://github.com/ucla-vision/xivo/blob/1b97bf5a3124e62bf4920429af5bb91c7a6de876/thirdparty/jsoncpp/devtools/batchbuild.py#L106-L109
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/optional.py
python
optional_to_optional
(context, builder, fromty, toty, val)
return outoptval._getvalue()
The handling of optional->optional cast must be special cased for correct propagation of None value. Given type T and U. casting of T? to U? (? denotes optional) should always succeed. If the from-value is None, the None value the casted value (U?) should be None; otherwise, the from-value is casted to U. This is different from casting T? to U, which requires the from-value must not be None.
The handling of optional->optional cast must be special cased for correct propagation of None value. Given type T and U. casting of T? to U? (? denotes optional) should always succeed. If the from-value is None, the None value the casted value (U?) should be None; otherwise, the from-value is casted to U. This is different from casting T? to U, which requires the from-value must not be None.
[ "The", "handling", "of", "optional", "-", ">", "optional", "cast", "must", "be", "special", "cased", "for", "correct", "propagation", "of", "None", "value", ".", "Given", "type", "T", "and", "U", ".", "casting", "of", "T?", "to", "U?", "(", "?", "denotes", "optional", ")", "should", "always", "succeed", ".", "If", "the", "from", "-", "value", "is", "None", "the", "None", "value", "the", "casted", "value", "(", "U?", ")", "should", "be", "None", ";", "otherwise", "the", "from", "-", "value", "is", "casted", "to", "U", ".", "This", "is", "different", "from", "casting", "T?", "to", "U", "which", "requires", "the", "from", "-", "value", "must", "not", "be", "None", "." ]
def optional_to_optional(context, builder, fromty, toty, val): """ The handling of optional->optional cast must be special cased for correct propagation of None value. Given type T and U. casting of T? to U? (? denotes optional) should always succeed. If the from-value is None, the None value the casted value (U?) should be None; otherwise, the from-value is casted to U. This is different from casting T? to U, which requires the from-value must not be None. """ optval = context.make_helper(builder, fromty, value=val) validbit = cgutils.as_bool_bit(builder, optval.valid) # Create uninitialized optional value outoptval = context.make_helper(builder, toty) with builder.if_else(validbit) as (is_valid, is_not_valid): with is_valid: # Cast internal value outoptval.valid = cgutils.true_bit outoptval.data = context.cast(builder, optval.data, fromty.type, toty.type) with is_not_valid: # Store None to result outoptval.valid = cgutils.false_bit outoptval.data = cgutils.get_null_value( outoptval.data.type) return outoptval._getvalue()
[ "def", "optional_to_optional", "(", "context", ",", "builder", ",", "fromty", ",", "toty", ",", "val", ")", ":", "optval", "=", "context", ".", "make_helper", "(", "builder", ",", "fromty", ",", "value", "=", "val", ")", "validbit", "=", "cgutils", ".", "as_bool_bit", "(", "builder", ",", "optval", ".", "valid", ")", "# Create uninitialized optional value", "outoptval", "=", "context", ".", "make_helper", "(", "builder", ",", "toty", ")", "with", "builder", ".", "if_else", "(", "validbit", ")", "as", "(", "is_valid", ",", "is_not_valid", ")", ":", "with", "is_valid", ":", "# Cast internal value", "outoptval", ".", "valid", "=", "cgutils", ".", "true_bit", "outoptval", ".", "data", "=", "context", ".", "cast", "(", "builder", ",", "optval", ".", "data", ",", "fromty", ".", "type", ",", "toty", ".", "type", ")", "with", "is_not_valid", ":", "# Store None to result", "outoptval", ".", "valid", "=", "cgutils", ".", "false_bit", "outoptval", ".", "data", "=", "cgutils", ".", "get_null_value", "(", "outoptval", ".", "data", ".", "type", ")", "return", "outoptval", ".", "_getvalue", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/optional.py#L74-L101
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/frame.py
python
DataFrame.dot
(self, other)
Compute the matrix multiplication between the DataFrame and other. This method computes the matrix product between the DataFrame and the values of an other Series, DataFrame or a numpy array. It can also be called using ``self @ other`` in Python >= 3.5. Parameters ---------- other : Series, DataFrame or array-like The other object to compute the matrix product with. Returns ------- Series or DataFrame If other is a Series, return the matrix product between self and other as a Serie. If other is a DataFrame or a numpy.array, return the matrix product of self and other in a DataFrame of a np.array. See Also -------- Series.dot: Similar method for Series. Notes ----- The dimensions of DataFrame and other must be compatible in order to compute the matrix multiplication. In addition, the column names of DataFrame and the index of other must contain the same values, as they will be aligned prior to the multiplication. The dot method for Series computes the inner product, instead of the matrix product here. Examples -------- Here we multiply a DataFrame with a Series. >>> df = pd.DataFrame([[0, 1, -2, -1], [1, 1, 1, 1]]) >>> s = pd.Series([1, 1, 2, 1]) >>> df.dot(s) 0 -4 1 5 dtype: int64 Here we multiply a DataFrame with another DataFrame. >>> other = pd.DataFrame([[0, 1], [1, 2], [-1, -1], [2, 0]]) >>> df.dot(other) 0 1 0 1 4 1 2 2 Note that the dot method give the same result as @ >>> df @ other 0 1 0 1 4 1 2 2 The dot method works also if other is an np.array. >>> arr = np.array([[0, 1], [1, 2], [-1, -1], [2, 0]]) >>> df.dot(arr) 0 1 0 1 4 1 2 2 Note how shuffling of the objects does not change the result. >>> s2 = s.reindex([1, 0, 2, 3]) >>> df.dot(s2) 0 -4 1 5 dtype: int64
Compute the matrix multiplication between the DataFrame and other.
[ "Compute", "the", "matrix", "multiplication", "between", "the", "DataFrame", "and", "other", "." ]
def dot(self, other): """ Compute the matrix multiplication between the DataFrame and other. This method computes the matrix product between the DataFrame and the values of an other Series, DataFrame or a numpy array. It can also be called using ``self @ other`` in Python >= 3.5. Parameters ---------- other : Series, DataFrame or array-like The other object to compute the matrix product with. Returns ------- Series or DataFrame If other is a Series, return the matrix product between self and other as a Serie. If other is a DataFrame or a numpy.array, return the matrix product of self and other in a DataFrame of a np.array. See Also -------- Series.dot: Similar method for Series. Notes ----- The dimensions of DataFrame and other must be compatible in order to compute the matrix multiplication. In addition, the column names of DataFrame and the index of other must contain the same values, as they will be aligned prior to the multiplication. The dot method for Series computes the inner product, instead of the matrix product here. Examples -------- Here we multiply a DataFrame with a Series. >>> df = pd.DataFrame([[0, 1, -2, -1], [1, 1, 1, 1]]) >>> s = pd.Series([1, 1, 2, 1]) >>> df.dot(s) 0 -4 1 5 dtype: int64 Here we multiply a DataFrame with another DataFrame. >>> other = pd.DataFrame([[0, 1], [1, 2], [-1, -1], [2, 0]]) >>> df.dot(other) 0 1 0 1 4 1 2 2 Note that the dot method give the same result as @ >>> df @ other 0 1 0 1 4 1 2 2 The dot method works also if other is an np.array. >>> arr = np.array([[0, 1], [1, 2], [-1, -1], [2, 0]]) >>> df.dot(arr) 0 1 0 1 4 1 2 2 Note how shuffling of the objects does not change the result. >>> s2 = s.reindex([1, 0, 2, 3]) >>> df.dot(s2) 0 -4 1 5 dtype: int64 """ if isinstance(other, (Series, DataFrame)): common = self.columns.union(other.index) if len(common) > len(self.columns) or len(common) > len(other.index): raise ValueError("matrices are not aligned") left = self.reindex(columns=common, copy=False) right = other.reindex(index=common, copy=False) lvals = left.values rvals = right.values else: left = self lvals = self.values rvals = np.asarray(other) if lvals.shape[1] != rvals.shape[0]: raise ValueError( f"Dot product shape mismatch, {lvals.shape} vs {rvals.shape}" ) if isinstance(other, DataFrame): return self._constructor( np.dot(lvals, rvals), index=left.index, columns=other.columns ) elif isinstance(other, Series): return Series(np.dot(lvals, rvals), index=left.index) elif isinstance(rvals, (np.ndarray, Index)): result = np.dot(lvals, rvals) if result.ndim == 2: return self._constructor(result, index=left.index) else: return Series(result, index=left.index) else: # pragma: no cover raise TypeError(f"unsupported type: {type(other)}")
[ "def", "dot", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "(", "Series", ",", "DataFrame", ")", ")", ":", "common", "=", "self", ".", "columns", ".", "union", "(", "other", ".", "index", ")", "if", "len", "(", "common", ")", ">", "len", "(", "self", ".", "columns", ")", "or", "len", "(", "common", ")", ">", "len", "(", "other", ".", "index", ")", ":", "raise", "ValueError", "(", "\"matrices are not aligned\"", ")", "left", "=", "self", ".", "reindex", "(", "columns", "=", "common", ",", "copy", "=", "False", ")", "right", "=", "other", ".", "reindex", "(", "index", "=", "common", ",", "copy", "=", "False", ")", "lvals", "=", "left", ".", "values", "rvals", "=", "right", ".", "values", "else", ":", "left", "=", "self", "lvals", "=", "self", ".", "values", "rvals", "=", "np", ".", "asarray", "(", "other", ")", "if", "lvals", ".", "shape", "[", "1", "]", "!=", "rvals", ".", "shape", "[", "0", "]", ":", "raise", "ValueError", "(", "f\"Dot product shape mismatch, {lvals.shape} vs {rvals.shape}\"", ")", "if", "isinstance", "(", "other", ",", "DataFrame", ")", ":", "return", "self", ".", "_constructor", "(", "np", ".", "dot", "(", "lvals", ",", "rvals", ")", ",", "index", "=", "left", ".", "index", ",", "columns", "=", "other", ".", "columns", ")", "elif", "isinstance", "(", "other", ",", "Series", ")", ":", "return", "Series", "(", "np", ".", "dot", "(", "lvals", ",", "rvals", ")", ",", "index", "=", "left", ".", "index", ")", "elif", "isinstance", "(", "rvals", ",", "(", "np", ".", "ndarray", ",", "Index", ")", ")", ":", "result", "=", "np", ".", "dot", "(", "lvals", ",", "rvals", ")", "if", "result", ".", "ndim", "==", "2", ":", "return", "self", ".", "_constructor", "(", "result", ",", "index", "=", "left", ".", "index", ")", "else", ":", "return", "Series", "(", "result", ",", "index", "=", "left", ".", "index", ")", "else", ":", "# pragma: no cover", "raise", "TypeError", "(", "f\"unsupported type: {type(other)}\"", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/frame.py#L1043-L1151
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/ultimatelistctrl.py
python
GeometryInfo.ExtendWidth
(self, w)
Extends all our rectangles to be centered inside the one of given width. :param `w`: the given width.
Extends all our rectangles to be centered inside the one of given width.
[ "Extends", "all", "our", "rectangles", "to", "be", "centered", "inside", "the", "one", "of", "given", "width", "." ]
def ExtendWidth(self, w): """ Extends all our rectangles to be centered inside the one of given width. :param `w`: the given width. """ if self._rectAll.width > w: raise Exception("width can only be increased") self._rectAll.width = w self._rectLabel.x = self._rectAll.x + (w - self._rectLabel.width)/2 self._rectIcon.x = self._rectAll.x + (w - self._rectIcon.width)/2 self._rectHighlight.x = self._rectAll.x + (w - self._rectHighlight.width)/2
[ "def", "ExtendWidth", "(", "self", ",", "w", ")", ":", "if", "self", ".", "_rectAll", ".", "width", ">", "w", ":", "raise", "Exception", "(", "\"width can only be increased\"", ")", "self", ".", "_rectAll", ".", "width", "=", "w", "self", ".", "_rectLabel", ".", "x", "=", "self", ".", "_rectAll", ".", "x", "+", "(", "w", "-", "self", ".", "_rectLabel", ".", "width", ")", "/", "2", "self", ".", "_rectIcon", ".", "x", "=", "self", ".", "_rectAll", ".", "x", "+", "(", "w", "-", "self", ".", "_rectIcon", ".", "width", ")", "/", "2", "self", ".", "_rectHighlight", ".", "x", "=", "self", ".", "_rectAll", ".", "x", "+", "(", "w", "-", "self", ".", "_rectHighlight", ".", "width", ")", "/", "2" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L3699-L3712
idaholab/moose
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
python/peacock/Input/InputFileEditorPlugin.py
python
InputFileEditorPlugin.addToMenu
(self, menu)
Register the menus specific to the InputTab. Input: menu[QMenu]: The menu to add the items to.
Register the menus specific to the InputTab. Input: menu[QMenu]: The menu to add the items to.
[ "Register", "the", "menus", "specific", "to", "the", "InputTab", ".", "Input", ":", "menu", "[", "QMenu", "]", ":", "The", "menu", "to", "add", "the", "items", "to", "." ]
def addToMenu(self, menu): """ Register the menus specific to the InputTab. Input: menu[QMenu]: The menu to add the items to. """ self._open_action = WidgetUtils.addAction(menu, "Open", self._openInputFile, "Ctrl+O") recentMenu = menu.addMenu("Recently opened") self._recently_used_menu = RecentlyUsedMenu(recentMenu, "input/recentlyUsed", "input/maxRecentlyUsed", 20, ) self._recently_used_menu.selected.connect(self.setInputFile) self._save_action = WidgetUtils.addAction(menu, "Save", self._saveInputFile) self._save_as_action = WidgetUtils.addAction(menu, "Save As", self._saveInputFileAs) self._clear_action = WidgetUtils.addAction(menu, "Clear", self._clearInputFile) self._check_action = WidgetUtils.addAction(menu, "Check", self._checkInputFile, "Ctrl+K") self._view_file = WidgetUtils.addAction(menu, "View current input file", self._viewInputFile, "Ctrl+V", True) self._menus_initialized = True self._setMenuStatus()
[ "def", "addToMenu", "(", "self", ",", "menu", ")", ":", "self", ".", "_open_action", "=", "WidgetUtils", ".", "addAction", "(", "menu", ",", "\"Open\"", ",", "self", ".", "_openInputFile", ",", "\"Ctrl+O\"", ")", "recentMenu", "=", "menu", ".", "addMenu", "(", "\"Recently opened\"", ")", "self", ".", "_recently_used_menu", "=", "RecentlyUsedMenu", "(", "recentMenu", ",", "\"input/recentlyUsed\"", ",", "\"input/maxRecentlyUsed\"", ",", "20", ",", ")", "self", ".", "_recently_used_menu", ".", "selected", ".", "connect", "(", "self", ".", "setInputFile", ")", "self", ".", "_save_action", "=", "WidgetUtils", ".", "addAction", "(", "menu", ",", "\"Save\"", ",", "self", ".", "_saveInputFile", ")", "self", ".", "_save_as_action", "=", "WidgetUtils", ".", "addAction", "(", "menu", ",", "\"Save As\"", ",", "self", ".", "_saveInputFileAs", ")", "self", ".", "_clear_action", "=", "WidgetUtils", ".", "addAction", "(", "menu", ",", "\"Clear\"", ",", "self", ".", "_clearInputFile", ")", "self", ".", "_check_action", "=", "WidgetUtils", ".", "addAction", "(", "menu", ",", "\"Check\"", ",", "self", ".", "_checkInputFile", ",", "\"Ctrl+K\"", ")", "self", ".", "_view_file", "=", "WidgetUtils", ".", "addAction", "(", "menu", ",", "\"View current input file\"", ",", "self", ".", "_viewInputFile", ",", "\"Ctrl+V\"", ",", "True", ")", "self", ".", "_menus_initialized", "=", "True", "self", ".", "_setMenuStatus", "(", ")" ]
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/peacock/Input/InputFileEditorPlugin.py#L165-L186
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/common.py
python
count_not_none
(*args)
return sum(x is not None for x in args)
Returns the count of arguments that are not None.
Returns the count of arguments that are not None.
[ "Returns", "the", "count", "of", "arguments", "that", "are", "not", "None", "." ]
def count_not_none(*args) -> int: """ Returns the count of arguments that are not None. """ return sum(x is not None for x in args)
[ "def", "count_not_none", "(", "*", "args", ")", "->", "int", ":", "return", "sum", "(", "x", "is", "not", "None", "for", "x", "in", "args", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/common.py#L217-L221
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/scipy/fftpack/realtransforms.py
python
dst
(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False)
return _dst(x, type, n, axis, normalize=norm, overwrite_x=overwrite_x)
Return the Discrete Sine Transform of arbitrary type sequence x. Parameters ---------- x : array_like The input array. type : {1, 2, 3}, optional Type of the DST (see Notes). Default type is 2. n : int, optional Length of the transform. If ``n < x.shape[axis]``, `x` is truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The default results in ``n = x.shape[axis]``. axis : int, optional Axis along which the dst is computed; the default is over the last axis (i.e., ``axis=-1``). norm : {None, 'ortho'}, optional Normalization mode (see Notes). Default is None. overwrite_x : bool, optional If True, the contents of `x` can be destroyed; the default is False. Returns ------- dst : ndarray of reals The transformed input array. See Also -------- idst : Inverse DST Notes ----- For a single dimension array ``x``. There are theoretically 8 types of the DST for different combinations of even/odd boundary conditions and boundary off sets [1]_, only the first 3 types are implemented in scipy. **Type I** There are several definitions of the DST-I; we use the following for ``norm=None``. DST-I assumes the input is odd around n=-1 and n=N. :: N-1 y[k] = 2 * sum x[n]*sin(pi*(k+1)*(n+1)/(N+1)) n=0 Only None is supported as normalization mode for DCT-I. Note also that the DCT-I is only supported for input size > 1 The (unnormalized) DCT-I is its own inverse, up to a factor `2(N+1)`. **Type II** There are several definitions of the DST-II; we use the following for ``norm=None``. DST-II assumes the input is odd around n=-1/2 and n=N-1/2; the output is odd around k=-1 and even around k=N-1 :: N-1 y[k] = 2* sum x[n]*sin(pi*(k+1)*(n+0.5)/N), 0 <= k < N. n=0 if ``norm='ortho'``, ``y[k]`` is multiplied by a scaling factor `f` :: f = sqrt(1/(4*N)) if k == 0 f = sqrt(1/(2*N)) otherwise. **Type III** There are several definitions of the DST-III, we use the following (for ``norm=None``). DST-III assumes the input is odd around n=-1 and even around n=N-1 :: N-2 y[k] = x[N-1]*(-1)**k + 2* sum x[n]*sin(pi*(k+0.5)*(n+1)/N), 0 <= k < N. n=0 The (unnormalized) DCT-III is the inverse of the (unnormalized) DCT-II, up to a factor `2N`. The orthonormalized DST-III is exactly the inverse of the orthonormalized DST-II. .. versionadded:: 0.11.0 References ---------- .. [1] Wikipedia, "Discrete sine transform", http://en.wikipedia.org/wiki/Discrete_sine_transform
Return the Discrete Sine Transform of arbitrary type sequence x.
[ "Return", "the", "Discrete", "Sine", "Transform", "of", "arbitrary", "type", "sequence", "x", "." ]
def dst(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False): """ Return the Discrete Sine Transform of arbitrary type sequence x. Parameters ---------- x : array_like The input array. type : {1, 2, 3}, optional Type of the DST (see Notes). Default type is 2. n : int, optional Length of the transform. If ``n < x.shape[axis]``, `x` is truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The default results in ``n = x.shape[axis]``. axis : int, optional Axis along which the dst is computed; the default is over the last axis (i.e., ``axis=-1``). norm : {None, 'ortho'}, optional Normalization mode (see Notes). Default is None. overwrite_x : bool, optional If True, the contents of `x` can be destroyed; the default is False. Returns ------- dst : ndarray of reals The transformed input array. See Also -------- idst : Inverse DST Notes ----- For a single dimension array ``x``. There are theoretically 8 types of the DST for different combinations of even/odd boundary conditions and boundary off sets [1]_, only the first 3 types are implemented in scipy. **Type I** There are several definitions of the DST-I; we use the following for ``norm=None``. DST-I assumes the input is odd around n=-1 and n=N. :: N-1 y[k] = 2 * sum x[n]*sin(pi*(k+1)*(n+1)/(N+1)) n=0 Only None is supported as normalization mode for DCT-I. Note also that the DCT-I is only supported for input size > 1 The (unnormalized) DCT-I is its own inverse, up to a factor `2(N+1)`. **Type II** There are several definitions of the DST-II; we use the following for ``norm=None``. DST-II assumes the input is odd around n=-1/2 and n=N-1/2; the output is odd around k=-1 and even around k=N-1 :: N-1 y[k] = 2* sum x[n]*sin(pi*(k+1)*(n+0.5)/N), 0 <= k < N. n=0 if ``norm='ortho'``, ``y[k]`` is multiplied by a scaling factor `f` :: f = sqrt(1/(4*N)) if k == 0 f = sqrt(1/(2*N)) otherwise. **Type III** There are several definitions of the DST-III, we use the following (for ``norm=None``). DST-III assumes the input is odd around n=-1 and even around n=N-1 :: N-2 y[k] = x[N-1]*(-1)**k + 2* sum x[n]*sin(pi*(k+0.5)*(n+1)/N), 0 <= k < N. n=0 The (unnormalized) DCT-III is the inverse of the (unnormalized) DCT-II, up to a factor `2N`. The orthonormalized DST-III is exactly the inverse of the orthonormalized DST-II. .. versionadded:: 0.11.0 References ---------- .. [1] Wikipedia, "Discrete sine transform", http://en.wikipedia.org/wiki/Discrete_sine_transform """ if type == 1 and norm is not None: raise NotImplementedError( "Orthonormalization not yet supported for IDCT-I") return _dst(x, type, n, axis, normalize=norm, overwrite_x=overwrite_x)
[ "def", "dst", "(", "x", ",", "type", "=", "2", ",", "n", "=", "None", ",", "axis", "=", "-", "1", ",", "norm", "=", "None", ",", "overwrite_x", "=", "False", ")", ":", "if", "type", "==", "1", "and", "norm", "is", "not", "None", ":", "raise", "NotImplementedError", "(", "\"Orthonormalization not yet supported for IDCT-I\"", ")", "return", "_dst", "(", "x", ",", "type", ",", "n", ",", "axis", ",", "normalize", "=", "norm", ",", "overwrite_x", "=", "overwrite_x", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/fftpack/realtransforms.py#L293-L385
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/xmlrpc/server.py
python
SimpleXMLRPCDispatcher.register_multicall_functions
(self)
Registers the XML-RPC multicall method in the system namespace. see http://www.xmlrpc.com/discuss/msgReader$1208
Registers the XML-RPC multicall method in the system namespace.
[ "Registers", "the", "XML", "-", "RPC", "multicall", "method", "in", "the", "system", "namespace", "." ]
def register_multicall_functions(self): """Registers the XML-RPC multicall method in the system namespace. see http://www.xmlrpc.com/discuss/msgReader$1208""" self.funcs.update({'system.multicall' : self.system_multicall})
[ "def", "register_multicall_functions", "(", "self", ")", ":", "self", ".", "funcs", ".", "update", "(", "{", "'system.multicall'", ":", "self", ".", "system_multicall", "}", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/xmlrpc/server.py#L236-L242
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/idlelib/CallTips.py
python
get_arg_text
(ob)
return arg_text
Get a string describing the arguments for the given object, only if it is callable.
Get a string describing the arguments for the given object, only if it is callable.
[ "Get", "a", "string", "describing", "the", "arguments", "for", "the", "given", "object", "only", "if", "it", "is", "callable", "." ]
def get_arg_text(ob): """Get a string describing the arguments for the given object, only if it is callable.""" arg_text = "" if ob is not None and hasattr(ob, '__call__'): arg_offset = 0 if type(ob) in (types.ClassType, types.TypeType): # Look for the highest __init__ in the class chain. fob = _find_constructor(ob) if fob is None: fob = lambda: None else: arg_offset = 1 elif type(ob)==types.MethodType: # bit of a hack for methods - turn it into a function # but we drop the "self" param. fob = ob.im_func arg_offset = 1 else: fob = ob # Try to build one for Python defined functions if type(fob) in [types.FunctionType, types.LambdaType]: argcount = fob.func_code.co_argcount real_args = fob.func_code.co_varnames[arg_offset:argcount] defaults = fob.func_defaults or [] defaults = list(map(lambda name: "=%s" % repr(name), defaults)) defaults = [""] * (len(real_args) - len(defaults)) + defaults items = map(lambda arg, dflt: arg + dflt, real_args, defaults) if fob.func_code.co_flags & 0x4: items.append("...") if fob.func_code.co_flags & 0x8: items.append("***") arg_text = ", ".join(items) arg_text = "(%s)" % re.sub("\.\d+", "<tuple>", arg_text) # See if we can use the docstring doc = getattr(ob, "__doc__", "") if doc: doc = doc.lstrip() pos = doc.find("\n") if pos < 0 or pos > 70: pos = 70 if arg_text: arg_text += "\n" arg_text += doc[:pos] return arg_text
[ "def", "get_arg_text", "(", "ob", ")", ":", "arg_text", "=", "\"\"", "if", "ob", "is", "not", "None", "and", "hasattr", "(", "ob", ",", "'__call__'", ")", ":", "arg_offset", "=", "0", "if", "type", "(", "ob", ")", "in", "(", "types", ".", "ClassType", ",", "types", ".", "TypeType", ")", ":", "# Look for the highest __init__ in the class chain.", "fob", "=", "_find_constructor", "(", "ob", ")", "if", "fob", "is", "None", ":", "fob", "=", "lambda", ":", "None", "else", ":", "arg_offset", "=", "1", "elif", "type", "(", "ob", ")", "==", "types", ".", "MethodType", ":", "# bit of a hack for methods - turn it into a function", "# but we drop the \"self\" param.", "fob", "=", "ob", ".", "im_func", "arg_offset", "=", "1", "else", ":", "fob", "=", "ob", "# Try to build one for Python defined functions", "if", "type", "(", "fob", ")", "in", "[", "types", ".", "FunctionType", ",", "types", ".", "LambdaType", "]", ":", "argcount", "=", "fob", ".", "func_code", ".", "co_argcount", "real_args", "=", "fob", ".", "func_code", ".", "co_varnames", "[", "arg_offset", ":", "argcount", "]", "defaults", "=", "fob", ".", "func_defaults", "or", "[", "]", "defaults", "=", "list", "(", "map", "(", "lambda", "name", ":", "\"=%s\"", "%", "repr", "(", "name", ")", ",", "defaults", ")", ")", "defaults", "=", "[", "\"\"", "]", "*", "(", "len", "(", "real_args", ")", "-", "len", "(", "defaults", ")", ")", "+", "defaults", "items", "=", "map", "(", "lambda", "arg", ",", "dflt", ":", "arg", "+", "dflt", ",", "real_args", ",", "defaults", ")", "if", "fob", ".", "func_code", ".", "co_flags", "&", "0x4", ":", "items", ".", "append", "(", "\"...\"", ")", "if", "fob", ".", "func_code", ".", "co_flags", "&", "0x8", ":", "items", ".", "append", "(", "\"***\"", ")", "arg_text", "=", "\", \"", ".", "join", "(", "items", ")", "arg_text", "=", "\"(%s)\"", "%", "re", ".", "sub", "(", "\"\\.\\d+\"", ",", "\"<tuple>\"", ",", "arg_text", ")", "# See if we can use the docstring", "doc", "=", "getattr", "(", "ob", ",", "\"__doc__\"", ",", "\"\"", ")", "if", "doc", ":", "doc", "=", "doc", ".", "lstrip", "(", ")", "pos", "=", "doc", ".", "find", "(", "\"\\n\"", ")", "if", "pos", "<", "0", "or", "pos", ">", "70", ":", "pos", "=", "70", "if", "arg_text", ":", "arg_text", "+=", "\"\\n\"", "arg_text", "+=", "doc", "[", ":", "pos", "]", "return", "arg_text" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/idlelib/CallTips.py#L133-L177
deepmind/open_spiel
4ca53bea32bb2875c7385d215424048ae92f78c8
open_spiel/python/algorithms/adidas_utils/solvers/nonsymmetric/ate_poly.py
python
Solver.init_polymatrix
(self, num_strats, num_players)
return init_pm
Initialize all pairwise bimatrix games to zero and return as dict.
Initialize all pairwise bimatrix games to zero and return as dict.
[ "Initialize", "all", "pairwise", "bimatrix", "games", "to", "zero", "and", "return", "as", "dict", "." ]
def init_polymatrix(self, num_strats, num_players): """Initialize all pairwise bimatrix games to zero and return as dict.""" init_pm = dict() for i, j in itertools.combinations(range(num_players), 2): init_pm[(i, j)] = np.zeros((2, num_strats[i], num_strats[j])) # i < j return init_pm
[ "def", "init_polymatrix", "(", "self", ",", "num_strats", ",", "num_players", ")", ":", "init_pm", "=", "dict", "(", ")", "for", "i", ",", "j", "in", "itertools", ".", "combinations", "(", "range", "(", "num_players", ")", ",", "2", ")", ":", "init_pm", "[", "(", "i", ",", "j", ")", "]", "=", "np", ".", "zeros", "(", "(", "2", ",", "num_strats", "[", "i", "]", ",", "num_strats", "[", "j", "]", ")", ")", "# i < j", "return", "init_pm" ]
https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/algorithms/adidas_utils/solvers/nonsymmetric/ate_poly.py#L74-L79
HKUST-Aerial-Robotics/Teach-Repeat-Replan
98505a7f74b13c8b501176ff838a38423dbef536
utils/quadrotor_msgs/src/quadrotor_msgs/msg/_Corrections.py
python
Corrections._get_types
(self)
return self._slot_types
internal API method
internal API method
[ "internal", "API", "method" ]
def _get_types(self): """ internal API method """ return self._slot_types
[ "def", "_get_types", "(", "self", ")", ":", "return", "self", ".", "_slot_types" ]
https://github.com/HKUST-Aerial-Robotics/Teach-Repeat-Replan/blob/98505a7f74b13c8b501176ff838a38423dbef536/utils/quadrotor_msgs/src/quadrotor_msgs/msg/_Corrections.py#L44-L48
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8_inspector/third_party/jinja2/jinja2/environment.py
python
Environment._parse
(self, source, name, filename)
return Parser(self, source, name, encode_filename(filename)).parse()
Internal parsing function used by `parse` and `compile`.
Internal parsing function used by `parse` and `compile`.
[ "Internal", "parsing", "function", "used", "by", "parse", "and", "compile", "." ]
def _parse(self, source, name, filename): """Internal parsing function used by `parse` and `compile`.""" return Parser(self, source, name, encode_filename(filename)).parse()
[ "def", "_parse", "(", "self", ",", "source", ",", "name", ",", "filename", ")", ":", "return", "Parser", "(", "self", ",", "source", ",", "name", ",", "encode_filename", "(", "filename", ")", ")", ".", "parse", "(", ")" ]
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8_inspector/third_party/jinja2/jinja2/environment.py#L468-L470
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distlib/locators.py
python
DependencyFinder.find_providers
(self, reqt)
return result
Find the distributions which can fulfill a requirement. :param reqt: The requirement. :type reqt: str :return: A set of distribution which can fulfill the requirement.
[]
def find_providers(self, reqt): """ Find the distributions which can fulfill a requirement. :param reqt: The requirement. :type reqt: str :return: A set of distribution which can fulfill the requirement. """ matcher = self.get_matcher(reqt) name = matcher.key # case-insensitive result = set() provided = self.provided if name in provided: for version, provider in provided[name]: try: match = matcher.match(version) except UnsupportedVersionError: match = False if match: result.add(provider) break return result
[ "def", "find_providers", "(", "self", ",", "reqt", ")", ":", "matcher", "=", "self", ".", "get_matcher", "(", "reqt", ")", "name", "=", "matcher", ".", "key", "# case-insensitive", "result", "=", "set", "(", ")", "provided", "=", "self", ".", "provided", "if", "name", "in", "provided", ":", "for", "version", ",", "provider", "in", "provided", "[", "name", "]", ":", "try", ":", "match", "=", "matcher", ".", "match", "(", "version", ")", "except", "UnsupportedVersionError", ":", "match", "=", "False", "if", "match", ":", "result", ".", "add", "(", "provider", ")", "break", "return", "result" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distlib/locators.py#L2259-L2303
facebookresearch/ELF
1f790173095cd910976d9f651b80beb872ec5d12
vendor/pybind11/tools/clang/cindex.py
python
Token.cursor
(self)
return cursor
The Cursor this Token corresponds to.
The Cursor this Token corresponds to.
[ "The", "Cursor", "this", "Token", "corresponds", "to", "." ]
def cursor(self): """The Cursor this Token corresponds to.""" cursor = Cursor() conf.lib.clang_annotateTokens(self._tu, byref(self), 1, byref(cursor)) return cursor
[ "def", "cursor", "(", "self", ")", ":", "cursor", "=", "Cursor", "(", ")", "conf", ".", "lib", ".", "clang_annotateTokens", "(", "self", ".", "_tu", ",", "byref", "(", "self", ")", ",", "1", ",", "byref", "(", "cursor", ")", ")", "return", "cursor" ]
https://github.com/facebookresearch/ELF/blob/1f790173095cd910976d9f651b80beb872ec5d12/vendor/pybind11/tools/clang/cindex.py#L3015-L3021
mhammond/pywin32
44afd86ba8485194df93234639243252deeb40d5
com/win32comext/mapi/demos/mapisend.py
python
SendEMAPIMail
( Subject="", Message="", SendTo=None, SendCC=None, SendBCC=None, MAPIProfile=None )
Sends an email to the recipient using the extended MAPI interface Subject and Message are strings Send{To,CC,BCC} are comma-separated address lists MAPIProfile is the name of the MAPI profile
Sends an email to the recipient using the extended MAPI interface Subject and Message are strings Send{To,CC,BCC} are comma-separated address lists MAPIProfile is the name of the MAPI profile
[ "Sends", "an", "email", "to", "the", "recipient", "using", "the", "extended", "MAPI", "interface", "Subject", "and", "Message", "are", "strings", "Send", "{", "To", "CC", "BCC", "}", "are", "comma", "-", "separated", "address", "lists", "MAPIProfile", "is", "the", "name", "of", "the", "MAPI", "profile" ]
def SendEMAPIMail( Subject="", Message="", SendTo=None, SendCC=None, SendBCC=None, MAPIProfile=None ): """Sends an email to the recipient using the extended MAPI interface Subject and Message are strings Send{To,CC,BCC} are comma-separated address lists MAPIProfile is the name of the MAPI profile""" # initialize and log on mapi.MAPIInitialize(None) session = mapi.MAPILogonEx( 0, MAPIProfile, None, mapi.MAPI_EXTENDED | mapi.MAPI_USE_DEFAULT ) messagestorestable = session.GetMsgStoresTable(0) messagestorestable.SetColumns( (mapitags.PR_ENTRYID, mapitags.PR_DISPLAY_NAME_A, mapitags.PR_DEFAULT_STORE), 0 ) while True: rows = messagestorestable.QueryRows(1, 0) # if this is the last row then stop if len(rows) != 1: break row = rows[0] # if this is the default store then stop if (mapitags.PR_DEFAULT_STORE, True) in row: break # unpack the row and open the message store (eid_tag, eid), (name_tag, name), (def_store_tag, def_store) = row msgstore = session.OpenMsgStore( 0, eid, None, mapi.MDB_NO_DIALOG | mapi.MAPI_BEST_ACCESS ) # get the outbox hr, props = msgstore.GetProps((mapitags.PR_IPM_OUTBOX_ENTRYID), 0) (tag, eid) = props[0] # check for errors if mapitags.PROP_TYPE(tag) == mapitags.PT_ERROR: raise TypeError("got PT_ERROR instead of PT_BINARY: %s" % eid) outboxfolder = msgstore.OpenEntry(eid, None, mapi.MAPI_BEST_ACCESS) # create the message and the addrlist message = outboxfolder.CreateMessage(None, 0) # note: you can use the resolveaddress functions for this. but you may get headaches pal = [] def makeentry(recipient, recipienttype): return ( (mapitags.PR_RECIPIENT_TYPE, recipienttype), (mapitags.PR_SEND_RICH_INFO, False), (mapitags.PR_DISPLAY_TYPE, 0), (mapitags.PR_OBJECT_TYPE, 6), (mapitags.PR_EMAIL_ADDRESS_A, recipient), (mapitags.PR_ADDRTYPE_A, "SMTP"), (mapitags.PR_DISPLAY_NAME_A, recipient), ) if SendTo: pal.extend( [makeentry(recipient, mapi.MAPI_TO) for recipient in SendTo.split(",")] ) if SendCC: pal.extend( [makeentry(recipient, mapi.MAPI_CC) for recipient in SendCC.split(",")] ) if SendBCC: pal.extend( [makeentry(recipient, mapi.MAPI_BCC) for recipient in SendBCC.split(",")] ) # add the resolved recipients to the message message.ModifyRecipients(mapi.MODRECIP_ADD, pal) message.SetProps([(mapitags.PR_BODY_A, Message), (mapitags.PR_SUBJECT_A, Subject)]) # save changes and submit outboxfolder.SaveChanges(0) message.SubmitMessage(0)
[ "def", "SendEMAPIMail", "(", "Subject", "=", "\"\"", ",", "Message", "=", "\"\"", ",", "SendTo", "=", "None", ",", "SendCC", "=", "None", ",", "SendBCC", "=", "None", ",", "MAPIProfile", "=", "None", ")", ":", "# initialize and log on", "mapi", ".", "MAPIInitialize", "(", "None", ")", "session", "=", "mapi", ".", "MAPILogonEx", "(", "0", ",", "MAPIProfile", ",", "None", ",", "mapi", ".", "MAPI_EXTENDED", "|", "mapi", ".", "MAPI_USE_DEFAULT", ")", "messagestorestable", "=", "session", ".", "GetMsgStoresTable", "(", "0", ")", "messagestorestable", ".", "SetColumns", "(", "(", "mapitags", ".", "PR_ENTRYID", ",", "mapitags", ".", "PR_DISPLAY_NAME_A", ",", "mapitags", ".", "PR_DEFAULT_STORE", ")", ",", "0", ")", "while", "True", ":", "rows", "=", "messagestorestable", ".", "QueryRows", "(", "1", ",", "0", ")", "# if this is the last row then stop", "if", "len", "(", "rows", ")", "!=", "1", ":", "break", "row", "=", "rows", "[", "0", "]", "# if this is the default store then stop", "if", "(", "mapitags", ".", "PR_DEFAULT_STORE", ",", "True", ")", "in", "row", ":", "break", "# unpack the row and open the message store", "(", "eid_tag", ",", "eid", ")", ",", "(", "name_tag", ",", "name", ")", ",", "(", "def_store_tag", ",", "def_store", ")", "=", "row", "msgstore", "=", "session", ".", "OpenMsgStore", "(", "0", ",", "eid", ",", "None", ",", "mapi", ".", "MDB_NO_DIALOG", "|", "mapi", ".", "MAPI_BEST_ACCESS", ")", "# get the outbox", "hr", ",", "props", "=", "msgstore", ".", "GetProps", "(", "(", "mapitags", ".", "PR_IPM_OUTBOX_ENTRYID", ")", ",", "0", ")", "(", "tag", ",", "eid", ")", "=", "props", "[", "0", "]", "# check for errors", "if", "mapitags", ".", "PROP_TYPE", "(", "tag", ")", "==", "mapitags", ".", "PT_ERROR", ":", "raise", "TypeError", "(", "\"got PT_ERROR instead of PT_BINARY: %s\"", "%", "eid", ")", "outboxfolder", "=", "msgstore", ".", "OpenEntry", "(", "eid", ",", "None", ",", "mapi", ".", "MAPI_BEST_ACCESS", ")", "# create the message and the addrlist", "message", "=", "outboxfolder", ".", "CreateMessage", "(", "None", ",", "0", ")", "# note: you can use the resolveaddress functions for this. but you may get headaches", "pal", "=", "[", "]", "def", "makeentry", "(", "recipient", ",", "recipienttype", ")", ":", "return", "(", "(", "mapitags", ".", "PR_RECIPIENT_TYPE", ",", "recipienttype", ")", ",", "(", "mapitags", ".", "PR_SEND_RICH_INFO", ",", "False", ")", ",", "(", "mapitags", ".", "PR_DISPLAY_TYPE", ",", "0", ")", ",", "(", "mapitags", ".", "PR_OBJECT_TYPE", ",", "6", ")", ",", "(", "mapitags", ".", "PR_EMAIL_ADDRESS_A", ",", "recipient", ")", ",", "(", "mapitags", ".", "PR_ADDRTYPE_A", ",", "\"SMTP\"", ")", ",", "(", "mapitags", ".", "PR_DISPLAY_NAME_A", ",", "recipient", ")", ",", ")", "if", "SendTo", ":", "pal", ".", "extend", "(", "[", "makeentry", "(", "recipient", ",", "mapi", ".", "MAPI_TO", ")", "for", "recipient", "in", "SendTo", ".", "split", "(", "\",\"", ")", "]", ")", "if", "SendCC", ":", "pal", ".", "extend", "(", "[", "makeentry", "(", "recipient", ",", "mapi", ".", "MAPI_CC", ")", "for", "recipient", "in", "SendCC", ".", "split", "(", "\",\"", ")", "]", ")", "if", "SendBCC", ":", "pal", ".", "extend", "(", "[", "makeentry", "(", "recipient", ",", "mapi", ".", "MAPI_BCC", ")", "for", "recipient", "in", "SendBCC", ".", "split", "(", "\",\"", ")", "]", ")", "# add the resolved recipients to the message", "message", ".", "ModifyRecipients", "(", "mapi", ".", "MODRECIP_ADD", ",", "pal", ")", "message", ".", "SetProps", "(", "[", "(", "mapitags", ".", "PR_BODY_A", ",", "Message", ")", ",", "(", "mapitags", ".", "PR_SUBJECT_A", ",", "Subject", ")", "]", ")", "# save changes and submit", "outboxfolder", ".", "SaveChanges", "(", "0", ")", "message", ".", "SubmitMessage", "(", "0", ")" ]
https://github.com/mhammond/pywin32/blob/44afd86ba8485194df93234639243252deeb40d5/com/win32comext/mapi/demos/mapisend.py#L13-L90
Slicer/SlicerGitSVNArchive
65e92bb16c2b32ea47a1a66bee71f238891ee1ca
Base/Python/slicer/util.py
python
findChildren
(widget=None, name="", text="", title="", className="")
return children
Return a list of child widgets that meet all the given criteria. If no criteria are provided, the function will return all widgets descendants. If no widget is provided, slicer.util.mainWindow() is used. :param widget: parent widget where the widgets will be searched :param name: name attribute of the widget :param text: text attribute of the widget :param title: title attribute of the widget :param className: className() attribute of the widget :return: list with all the widgets that meet all the given criteria.
Return a list of child widgets that meet all the given criteria. If no criteria are provided, the function will return all widgets descendants. If no widget is provided, slicer.util.mainWindow() is used. :param widget: parent widget where the widgets will be searched :param name: name attribute of the widget :param text: text attribute of the widget :param title: title attribute of the widget :param className: className() attribute of the widget :return: list with all the widgets that meet all the given criteria.
[ "Return", "a", "list", "of", "child", "widgets", "that", "meet", "all", "the", "given", "criteria", ".", "If", "no", "criteria", "are", "provided", "the", "function", "will", "return", "all", "widgets", "descendants", ".", "If", "no", "widget", "is", "provided", "slicer", ".", "util", ".", "mainWindow", "()", "is", "used", ".", ":", "param", "widget", ":", "parent", "widget", "where", "the", "widgets", "will", "be", "searched", ":", "param", "name", ":", "name", "attribute", "of", "the", "widget", ":", "param", "text", ":", "text", "attribute", "of", "the", "widget", ":", "param", "title", ":", "title", "attribute", "of", "the", "widget", ":", "param", "className", ":", "className", "()", "attribute", "of", "the", "widget", ":", "return", ":", "list", "with", "all", "the", "widgets", "that", "meet", "all", "the", "given", "criteria", "." ]
def findChildren(widget=None, name="", text="", title="", className=""): """ Return a list of child widgets that meet all the given criteria. If no criteria are provided, the function will return all widgets descendants. If no widget is provided, slicer.util.mainWindow() is used. :param widget: parent widget where the widgets will be searched :param name: name attribute of the widget :param text: text attribute of the widget :param title: title attribute of the widget :param className: className() attribute of the widget :return: list with all the widgets that meet all the given criteria. """ # TODO: figure out why the native QWidget.findChildren method does not seem to work from PythonQt import slicer, fnmatch if not widget: widget = mainWindow() if not widget: return [] children = [] parents = [widget] kwargs = {'name': name, 'text': text, 'title': title, 'className': className} expected_matches = [] for kwarg in kwargs.keys(): if kwargs[kwarg]: expected_matches.append(kwarg) while parents: p = parents.pop() # sometimes, p is null, f.e. when using --python-script or --python-code if not p: continue if not hasattr(p,'children'): continue parents += p.children() matched_filter_criteria = 0 for attribute in expected_matches: if hasattr(p, attribute): attr_name = getattr(p, attribute) if attribute == 'className': # className is a method, not a direct attribute. Invoke the method attr_name = attr_name() # Objects may have text attributes with non-string value (for example, # QUndoStack objects have text attribute of 'builtin_qt_slot' type. # We only consider string type attributes. if isinstance(attr_name, str): if fnmatch.fnmatchcase(attr_name, kwargs[attribute]): matched_filter_criteria = matched_filter_criteria + 1 if matched_filter_criteria == len(expected_matches): children.append(p) return children
[ "def", "findChildren", "(", "widget", "=", "None", ",", "name", "=", "\"\"", ",", "text", "=", "\"\"", ",", "title", "=", "\"\"", ",", "className", "=", "\"\"", ")", ":", "# TODO: figure out why the native QWidget.findChildren method does not seem to work from PythonQt", "import", "slicer", ",", "fnmatch", "if", "not", "widget", ":", "widget", "=", "mainWindow", "(", ")", "if", "not", "widget", ":", "return", "[", "]", "children", "=", "[", "]", "parents", "=", "[", "widget", "]", "kwargs", "=", "{", "'name'", ":", "name", ",", "'text'", ":", "text", ",", "'title'", ":", "title", ",", "'className'", ":", "className", "}", "expected_matches", "=", "[", "]", "for", "kwarg", "in", "kwargs", ".", "keys", "(", ")", ":", "if", "kwargs", "[", "kwarg", "]", ":", "expected_matches", ".", "append", "(", "kwarg", ")", "while", "parents", ":", "p", "=", "parents", ".", "pop", "(", ")", "# sometimes, p is null, f.e. when using --python-script or --python-code", "if", "not", "p", ":", "continue", "if", "not", "hasattr", "(", "p", ",", "'children'", ")", ":", "continue", "parents", "+=", "p", ".", "children", "(", ")", "matched_filter_criteria", "=", "0", "for", "attribute", "in", "expected_matches", ":", "if", "hasattr", "(", "p", ",", "attribute", ")", ":", "attr_name", "=", "getattr", "(", "p", ",", "attribute", ")", "if", "attribute", "==", "'className'", ":", "# className is a method, not a direct attribute. Invoke the method", "attr_name", "=", "attr_name", "(", ")", "# Objects may have text attributes with non-string value (for example,", "# QUndoStack objects have text attribute of 'builtin_qt_slot' type.", "# We only consider string type attributes.", "if", "isinstance", "(", "attr_name", ",", "str", ")", ":", "if", "fnmatch", ".", "fnmatchcase", "(", "attr_name", ",", "kwargs", "[", "attribute", "]", ")", ":", "matched_filter_criteria", "=", "matched_filter_criteria", "+", "1", "if", "matched_filter_criteria", "==", "len", "(", "expected_matches", ")", ":", "children", ".", "append", "(", "p", ")", "return", "children" ]
https://github.com/Slicer/SlicerGitSVNArchive/blob/65e92bb16c2b32ea47a1a66bee71f238891ee1ca/Base/Python/slicer/util.py#L204-L251
Slicer/SlicerGitSVNArchive
65e92bb16c2b32ea47a1a66bee71f238891ee1ca
Base/Python/slicer/util.py
python
updateVolumeFromArray
(volumeNode, narray)
Sets voxels of a volume node from a numpy array. Voxels values are deep-copied, therefore if the numpy array is modified after calling this method, voxel values in the volume node will not change. Dimensions and data size of the source numpy array does not have to match the current content of the volume node.
Sets voxels of a volume node from a numpy array. Voxels values are deep-copied, therefore if the numpy array is modified after calling this method, voxel values in the volume node will not change. Dimensions and data size of the source numpy array does not have to match the current content of the volume node.
[ "Sets", "voxels", "of", "a", "volume", "node", "from", "a", "numpy", "array", ".", "Voxels", "values", "are", "deep", "-", "copied", "therefore", "if", "the", "numpy", "array", "is", "modified", "after", "calling", "this", "method", "voxel", "values", "in", "the", "volume", "node", "will", "not", "change", ".", "Dimensions", "and", "data", "size", "of", "the", "source", "numpy", "array", "does", "not", "have", "to", "match", "the", "current", "content", "of", "the", "volume", "node", "." ]
def updateVolumeFromArray(volumeNode, narray): """Sets voxels of a volume node from a numpy array. Voxels values are deep-copied, therefore if the numpy array is modified after calling this method, voxel values in the volume node will not change. Dimensions and data size of the source numpy array does not have to match the current content of the volume node. """ vshape = tuple(reversed(narray.shape)) if len(vshape) == 3: # Scalar volume vcomponents = 1 elif len(vshape) == 4: # Vector volume vcomponents = vshape[0] vshape = vshape[1:4] else: # TODO: add support for tensor volumes raise RuntimeError("Unsupported numpy array shape: "+str(narray.shape)) vimage = volumeNode.GetImageData() if not vimage: import vtk vimage = vtk.vtkImageData() volumeNode.SetAndObserveImageData(vimage) import vtk.util.numpy_support vtype = vtk.util.numpy_support.get_vtk_array_type(narray.dtype) # Volumes with "long long" scalar type are not rendered corectly. # Probably this could be fixed in VTK or Slicer but for now just reject it. if vtype == vtk.VTK_LONG_LONG: raise RuntimeError("Unsupported numpy array type: long long") vimage.SetDimensions(vshape) vimage.AllocateScalars(vtype, vcomponents) narrayTarget = arrayFromVolume(volumeNode) narrayTarget[:] = narray # Notify the application that image data is changed # (same notifications as in vtkMRMLVolumeNode.SetImageDataConnection) import slicer volumeNode.StorableModified() volumeNode.Modified() volumeNode.InvokeEvent(slicer.vtkMRMLVolumeNode.ImageDataModifiedEvent, volumeNode)
[ "def", "updateVolumeFromArray", "(", "volumeNode", ",", "narray", ")", ":", "vshape", "=", "tuple", "(", "reversed", "(", "narray", ".", "shape", ")", ")", "if", "len", "(", "vshape", ")", "==", "3", ":", "# Scalar volume", "vcomponents", "=", "1", "elif", "len", "(", "vshape", ")", "==", "4", ":", "# Vector volume", "vcomponents", "=", "vshape", "[", "0", "]", "vshape", "=", "vshape", "[", "1", ":", "4", "]", "else", ":", "# TODO: add support for tensor volumes", "raise", "RuntimeError", "(", "\"Unsupported numpy array shape: \"", "+", "str", "(", "narray", ".", "shape", ")", ")", "vimage", "=", "volumeNode", ".", "GetImageData", "(", ")", "if", "not", "vimage", ":", "import", "vtk", "vimage", "=", "vtk", ".", "vtkImageData", "(", ")", "volumeNode", ".", "SetAndObserveImageData", "(", "vimage", ")", "import", "vtk", ".", "util", ".", "numpy_support", "vtype", "=", "vtk", ".", "util", ".", "numpy_support", ".", "get_vtk_array_type", "(", "narray", ".", "dtype", ")", "# Volumes with \"long long\" scalar type are not rendered corectly.", "# Probably this could be fixed in VTK or Slicer but for now just reject it.", "if", "vtype", "==", "vtk", ".", "VTK_LONG_LONG", ":", "raise", "RuntimeError", "(", "\"Unsupported numpy array type: long long\"", ")", "vimage", ".", "SetDimensions", "(", "vshape", ")", "vimage", ".", "AllocateScalars", "(", "vtype", ",", "vcomponents", ")", "narrayTarget", "=", "arrayFromVolume", "(", "volumeNode", ")", "narrayTarget", "[", ":", "]", "=", "narray", "# Notify the application that image data is changed", "# (same notifications as in vtkMRMLVolumeNode.SetImageDataConnection)", "import", "slicer", "volumeNode", ".", "StorableModified", "(", ")", "volumeNode", ".", "Modified", "(", ")", "volumeNode", ".", "InvokeEvent", "(", "slicer", ".", "vtkMRMLVolumeNode", ".", "ImageDataModifiedEvent", ",", "volumeNode", ")" ]
https://github.com/Slicer/SlicerGitSVNArchive/blob/65e92bb16c2b32ea47a1a66bee71f238891ee1ca/Base/Python/slicer/util.py#L1287-L1331
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_controls.py
python
PreToggleButton
(*args, **kwargs)
return val
PreToggleButton() -> ToggleButton
PreToggleButton() -> ToggleButton
[ "PreToggleButton", "()", "-", ">", "ToggleButton" ]
def PreToggleButton(*args, **kwargs): """PreToggleButton() -> ToggleButton""" val = _controls_.new_PreToggleButton(*args, **kwargs) return val
[ "def", "PreToggleButton", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "val", "=", "_controls_", ".", "new_PreToggleButton", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "val" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L3037-L3040
SFTtech/openage
d6a08c53c48dc1e157807471df92197f6ca9e04d
openage/convert/entity_object/conversion/modpack.py
python
Modpack.get_data_files
(self)
return self.data_export_files
Returns the data files for exporting.
Returns the data files for exporting.
[ "Returns", "the", "data", "files", "for", "exporting", "." ]
def get_data_files(self): """ Returns the data files for exporting. """ return self.data_export_files
[ "def", "get_data_files", "(", "self", ")", ":", "return", "self", ".", "data_export_files" ]
https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/convert/entity_object/conversion/modpack.py#L74-L78
linyouhappy/kongkongxiyou
7a69b2913eb29f4be77f9a62fb90cdd72c4160f1
cocosjs/frameworks/cocos2d-x/build/android-build.py
python
caculate_built_samples
(args)
return list(targets)
Compute the sampels to be built 'cpp' for short of all cpp tests 'lua' for short of all lua tests
Compute the sampels to be built 'cpp' for short of all cpp tests 'lua' for short of all lua tests
[ "Compute", "the", "sampels", "to", "be", "built", "cpp", "for", "short", "of", "all", "cpp", "tests", "lua", "for", "short", "of", "all", "lua", "tests" ]
def caculate_built_samples(args): ''' Compute the sampels to be built 'cpp' for short of all cpp tests 'lua' for short of all lua tests ''' if 'all' in args: return ALL_SAMPLES targets = [] if 'cpp' in args: targets += CPP_SAMPLES args.remove('cpp') if 'lua' in args: targets += LUA_SAMPLES args.remove('lua') if 'js' in args: targets += JS_SAMPLES args.remove('js') targets += args # remove duplicate elements, for example # python android-build.py cpp hellocpp targets = set(targets) return list(targets)
[ "def", "caculate_built_samples", "(", "args", ")", ":", "if", "'all'", "in", "args", ":", "return", "ALL_SAMPLES", "targets", "=", "[", "]", "if", "'cpp'", "in", "args", ":", "targets", "+=", "CPP_SAMPLES", "args", ".", "remove", "(", "'cpp'", ")", "if", "'lua'", "in", "args", ":", "targets", "+=", "LUA_SAMPLES", "args", ".", "remove", "(", "'lua'", ")", "if", "'js'", "in", "args", ":", "targets", "+=", "JS_SAMPLES", "args", ".", "remove", "(", "'js'", ")", "targets", "+=", "args", "# remove duplicate elements, for example", "# python android-build.py cpp hellocpp", "targets", "=", "set", "(", "targets", ")", "return", "list", "(", "targets", ")" ]
https://github.com/linyouhappy/kongkongxiyou/blob/7a69b2913eb29f4be77f9a62fb90cdd72c4160f1/cocosjs/frameworks/cocos2d-x/build/android-build.py#L14-L39
microsoft/CNTK
e9396480025b9ca457d26b6f33dd07c474c6aa04
bindings/python/cntk/debugging/__init__.py
python
force_deterministic
(seed)
Force most of the computation nodes to run deterministically. Args: seed (int): set the random seed for all random ops in the graph and readers.
Force most of the computation nodes to run deterministically. Args: seed (int): set the random seed for all random ops in the graph and readers.
[ "Force", "most", "of", "the", "computation", "nodes", "to", "run", "deterministically", ".", "Args", ":", "seed", "(", "int", ")", ":", "set", "the", "random", "seed", "for", "all", "random", "ops", "in", "the", "graph", "and", "readers", "." ]
def force_deterministic(seed): ''' Force most of the computation nodes to run deterministically. Args: seed (int): set the random seed for all random ops in the graph and readers. ''' from _cntk_py import set_fixed_random_seed, force_deterministic_algorithms import warnings warnings.warn("RNN based nodes don't run deterministically yet.", Warning) set_fixed_random_seed(seed) force_deterministic_algorithms()
[ "def", "force_deterministic", "(", "seed", ")", ":", "from", "_cntk_py", "import", "set_fixed_random_seed", ",", "force_deterministic_algorithms", "import", "warnings", "warnings", ".", "warn", "(", "\"RNN based nodes don't run deterministically yet.\"", ",", "Warning", ")", "set_fixed_random_seed", "(", "seed", ")", "force_deterministic_algorithms", "(", ")" ]
https://github.com/microsoft/CNTK/blob/e9396480025b9ca457d26b6f33dd07c474c6aa04/bindings/python/cntk/debugging/__init__.py#L14-L27
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/numbers.py
python
Integral.numerator
(self)
return +self
Integers are their own numerators.
Integers are their own numerators.
[ "Integers", "are", "their", "own", "numerators", "." ]
def numerator(self): """Integers are their own numerators.""" return +self
[ "def", "numerator", "(", "self", ")", ":", "return", "+", "self" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/numbers.py#L381-L383
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/composite/multitype_ops/pow_impl.py
python
_tuple_pow_tensor
(x, y)
return F.tensor_pow(x, y)
Returns x ** y where x is a tuple and y is a tensor.
Returns x ** y where x is a tuple and y is a tensor.
[ "Returns", "x", "**", "y", "where", "x", "is", "a", "tuple", "and", "y", "is", "a", "tensor", "." ]
def _tuple_pow_tensor(x, y): """Returns x ** y where x is a tuple and y is a tensor. """ x = utils.sequence_to_tensor(x, y.dtype) return F.tensor_pow(x, y)
[ "def", "_tuple_pow_tensor", "(", "x", ",", "y", ")", ":", "x", "=", "utils", ".", "sequence_to_tensor", "(", "x", ",", "y", ".", "dtype", ")", "return", "F", ".", "tensor_pow", "(", "x", ",", "y", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/composite/multitype_ops/pow_impl.py#L55-L58
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_controls.py
python
SpinButton.Create
(*args, **kwargs)
return _controls_.SpinButton_Create(*args, **kwargs)
Create(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=SP_HORIZONTAL, String name=SPIN_BUTTON_NAME) -> bool
Create(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=SP_HORIZONTAL, String name=SPIN_BUTTON_NAME) -> bool
[ "Create", "(", "self", "Window", "parent", "int", "id", "=", "-", "1", "Point", "pos", "=", "DefaultPosition", "Size", "size", "=", "DefaultSize", "long", "style", "=", "SP_HORIZONTAL", "String", "name", "=", "SPIN_BUTTON_NAME", ")", "-", ">", "bool" ]
def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=SP_HORIZONTAL, String name=SPIN_BUTTON_NAME) -> bool """ return _controls_.SpinButton_Create(*args, **kwargs)
[ "def", "Create", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "SpinButton_Create", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L2246-L2252
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/ensemble/partial_dependence.py
python
plot_partial_dependence
(gbrt, X, features, feature_names=None, label=None, n_cols=3, grid_resolution=100, percentiles=(0.05, 0.95), n_jobs=None, verbose=0, ax=None, line_kw=None, contour_kw=None, **fig_kw)
return fig, axs
Partial dependence plots for ``features``. The ``len(features)`` plots are arranged in a grid with ``n_cols`` columns. Two-way partial dependence plots are plotted as contour plots. Read more in the :ref:`User Guide <partial_dependence>`. .. deprecated:: 0.21 This function was deprecated in version 0.21 in favor of :func:`sklearn.inspection.plot_partial_dependence` and will be removed in 0.23. Parameters ---------- gbrt : BaseGradientBoosting A fitted gradient boosting model. X : array-like of shape (n_samples, n_features) The data on which ``gbrt`` was trained. features : seq of ints, strings, or tuples of ints or strings If seq[i] is an int or a tuple with one int value, a one-way PDP is created; if seq[i] is a tuple of two ints, a two-way PDP is created. If feature_names is specified and seq[i] is an int, seq[i] must be < len(feature_names). If seq[i] is a string, feature_names must be specified, and seq[i] must be in feature_names. feature_names : seq of str Name of each feature; feature_names[i] holds the name of the feature with index i. label : object The class label for which the PDPs should be computed. Only if gbrt is a multi-class model. Must be in ``gbrt.classes_``. n_cols : int The number of columns in the grid plot (default: 3). grid_resolution : int, default=100 The number of equally spaced points on the axes. percentiles : (low, high), default=(0.05, 0.95) The lower and upper percentile used to create the extreme values for the PDP axes. n_jobs : int or None, optional (default=None) ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. verbose : int Verbose output during PD computations. Defaults to 0. ax : Matplotlib axis object, default None An axis object onto which the plots will be drawn. line_kw : dict Dict with keywords passed to the ``matplotlib.pyplot.plot`` call. For one-way partial dependence plots. contour_kw : dict Dict with keywords passed to the ``matplotlib.pyplot.plot`` call. For two-way partial dependence plots. ``**fig_kw`` : dict Dict with keywords passed to the figure() call. Note that all keywords not recognized above will be automatically included here. Returns ------- fig : figure The Matplotlib Figure object. axs : seq of Axis objects A seq of Axis objects, one for each subplot. Examples -------- >>> from sklearn.datasets import make_friedman1 >>> from sklearn.ensemble import GradientBoostingRegressor >>> X, y = make_friedman1() >>> clf = GradientBoostingRegressor(n_estimators=10).fit(X, y) >>> fig, axs = plot_partial_dependence(clf, X, [0, (0, 1)]) #doctest: +SKIP ...
Partial dependence plots for ``features``.
[ "Partial", "dependence", "plots", "for", "features", "." ]
def plot_partial_dependence(gbrt, X, features, feature_names=None, label=None, n_cols=3, grid_resolution=100, percentiles=(0.05, 0.95), n_jobs=None, verbose=0, ax=None, line_kw=None, contour_kw=None, **fig_kw): """Partial dependence plots for ``features``. The ``len(features)`` plots are arranged in a grid with ``n_cols`` columns. Two-way partial dependence plots are plotted as contour plots. Read more in the :ref:`User Guide <partial_dependence>`. .. deprecated:: 0.21 This function was deprecated in version 0.21 in favor of :func:`sklearn.inspection.plot_partial_dependence` and will be removed in 0.23. Parameters ---------- gbrt : BaseGradientBoosting A fitted gradient boosting model. X : array-like of shape (n_samples, n_features) The data on which ``gbrt`` was trained. features : seq of ints, strings, or tuples of ints or strings If seq[i] is an int or a tuple with one int value, a one-way PDP is created; if seq[i] is a tuple of two ints, a two-way PDP is created. If feature_names is specified and seq[i] is an int, seq[i] must be < len(feature_names). If seq[i] is a string, feature_names must be specified, and seq[i] must be in feature_names. feature_names : seq of str Name of each feature; feature_names[i] holds the name of the feature with index i. label : object The class label for which the PDPs should be computed. Only if gbrt is a multi-class model. Must be in ``gbrt.classes_``. n_cols : int The number of columns in the grid plot (default: 3). grid_resolution : int, default=100 The number of equally spaced points on the axes. percentiles : (low, high), default=(0.05, 0.95) The lower and upper percentile used to create the extreme values for the PDP axes. n_jobs : int or None, optional (default=None) ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. verbose : int Verbose output during PD computations. Defaults to 0. ax : Matplotlib axis object, default None An axis object onto which the plots will be drawn. line_kw : dict Dict with keywords passed to the ``matplotlib.pyplot.plot`` call. For one-way partial dependence plots. contour_kw : dict Dict with keywords passed to the ``matplotlib.pyplot.plot`` call. For two-way partial dependence plots. ``**fig_kw`` : dict Dict with keywords passed to the figure() call. Note that all keywords not recognized above will be automatically included here. Returns ------- fig : figure The Matplotlib Figure object. axs : seq of Axis objects A seq of Axis objects, one for each subplot. Examples -------- >>> from sklearn.datasets import make_friedman1 >>> from sklearn.ensemble import GradientBoostingRegressor >>> X, y = make_friedman1() >>> clf = GradientBoostingRegressor(n_estimators=10).fit(X, y) >>> fig, axs = plot_partial_dependence(clf, X, [0, (0, 1)]) #doctest: +SKIP ... """ import matplotlib.pyplot as plt from matplotlib import transforms from matplotlib.ticker import MaxNLocator from matplotlib.ticker import ScalarFormatter if not isinstance(gbrt, BaseGradientBoosting): raise ValueError('gbrt has to be an instance of BaseGradientBoosting') check_is_fitted(gbrt) # set label_idx for multi-class GBRT if hasattr(gbrt, 'classes_') and np.size(gbrt.classes_) > 2: if label is None: raise ValueError('label is not given for multi-class PDP') label_idx = np.searchsorted(gbrt.classes_, label) if gbrt.classes_[label_idx] != label: raise ValueError('label %s not in ``gbrt.classes_``' % str(label)) else: # regression and binary classification label_idx = 0 X = check_array(X, dtype=DTYPE, order='C') if gbrt.n_features_ != X.shape[1]: raise ValueError('X.shape[1] does not match gbrt.n_features_') if line_kw is None: line_kw = {'color': 'green'} if contour_kw is None: contour_kw = {} # convert feature_names to list if feature_names is None: # if not feature_names use fx indices as name feature_names = [str(i) for i in range(gbrt.n_features_)] elif isinstance(feature_names, np.ndarray): feature_names = feature_names.tolist() def convert_feature(fx): if isinstance(fx, str): try: fx = feature_names.index(fx) except ValueError: raise ValueError('Feature %s not in feature_names' % fx) return fx # convert features into a seq of int tuples tmp_features = [] for fxs in features: if isinstance(fxs, (numbers.Integral, str)): fxs = (fxs,) try: fxs = np.array([convert_feature(fx) for fx in fxs], dtype=np.int32) except TypeError: raise ValueError('features must be either int, str, or tuple ' 'of int/str') if not (1 <= np.size(fxs) <= 2): raise ValueError('target features must be either one or two') tmp_features.append(fxs) features = tmp_features names = [] try: for fxs in features: l = [] # explicit loop so "i" is bound for exception below for i in fxs: l.append(feature_names[i]) names.append(l) except IndexError: raise ValueError('All entries of features must be less than ' 'len(feature_names) = {0}, got {1}.' .format(len(feature_names), i)) # compute PD functions pd_result = Parallel(n_jobs=n_jobs, verbose=verbose)( delayed(partial_dependence)(gbrt, fxs, X=X, grid_resolution=grid_resolution, percentiles=percentiles) for fxs in features) # get global min and max values of PD grouped by plot type pdp_lim = {} for pdp, axes in pd_result: min_pd, max_pd = pdp[label_idx].min(), pdp[label_idx].max() n_fx = len(axes) old_min_pd, old_max_pd = pdp_lim.get(n_fx, (min_pd, max_pd)) min_pd = min(min_pd, old_min_pd) max_pd = max(max_pd, old_max_pd) pdp_lim[n_fx] = (min_pd, max_pd) # create contour levels for two-way plots if 2 in pdp_lim: Z_level = np.linspace(*pdp_lim[2], num=8) if ax is None: fig = plt.figure(**fig_kw) else: fig = ax.get_figure() fig.clear() n_cols = min(n_cols, len(features)) n_rows = int(np.ceil(len(features) / float(n_cols))) axs = [] for i, fx, name, (pdp, axes) in zip(count(), features, names, pd_result): ax = fig.add_subplot(n_rows, n_cols, i + 1) if len(axes) == 1: ax.plot(axes[0], pdp[label_idx].ravel(), **line_kw) else: # make contour plot assert len(axes) == 2 XX, YY = np.meshgrid(axes[0], axes[1]) Z = pdp[label_idx].reshape(list(map(np.size, axes))).T CS = ax.contour(XX, YY, Z, levels=Z_level, linewidths=0.5, colors='k') ax.contourf(XX, YY, Z, levels=Z_level, vmax=Z_level[-1], vmin=Z_level[0], alpha=0.75, **contour_kw) ax.clabel(CS, fmt='%2.2f', colors='k', fontsize=10, inline=True) # plot data deciles + axes labels deciles = mquantiles(X[:, fx[0]], prob=np.arange(0.1, 1.0, 0.1)) trans = transforms.blended_transform_factory(ax.transData, ax.transAxes) ylim = ax.get_ylim() ax.vlines(deciles, [0], 0.05, transform=trans, color='k') ax.set_xlabel(name[0]) ax.set_ylim(ylim) # prevent x-axis ticks from overlapping ax.xaxis.set_major_locator(MaxNLocator(nbins=6, prune='lower')) tick_formatter = ScalarFormatter() tick_formatter.set_powerlimits((-3, 4)) ax.xaxis.set_major_formatter(tick_formatter) if len(axes) > 1: # two-way PDP - y-axis deciles + labels deciles = mquantiles(X[:, fx[1]], prob=np.arange(0.1, 1.0, 0.1)) trans = transforms.blended_transform_factory(ax.transAxes, ax.transData) xlim = ax.get_xlim() ax.hlines(deciles, [0], 0.05, transform=trans, color='k') ax.set_ylabel(name[1]) # hline erases xlim ax.set_xlim(xlim) else: ax.set_ylabel('Partial dependence') if len(axes) == 1: ax.set_ylim(pdp_lim[1]) axs.append(ax) fig.subplots_adjust(bottom=0.15, top=0.7, left=0.1, right=0.95, wspace=0.4, hspace=0.3) return fig, axs
[ "def", "plot_partial_dependence", "(", "gbrt", ",", "X", ",", "features", ",", "feature_names", "=", "None", ",", "label", "=", "None", ",", "n_cols", "=", "3", ",", "grid_resolution", "=", "100", ",", "percentiles", "=", "(", "0.05", ",", "0.95", ")", ",", "n_jobs", "=", "None", ",", "verbose", "=", "0", ",", "ax", "=", "None", ",", "line_kw", "=", "None", ",", "contour_kw", "=", "None", ",", "*", "*", "fig_kw", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "from", "matplotlib", "import", "transforms", "from", "matplotlib", ".", "ticker", "import", "MaxNLocator", "from", "matplotlib", ".", "ticker", "import", "ScalarFormatter", "if", "not", "isinstance", "(", "gbrt", ",", "BaseGradientBoosting", ")", ":", "raise", "ValueError", "(", "'gbrt has to be an instance of BaseGradientBoosting'", ")", "check_is_fitted", "(", "gbrt", ")", "# set label_idx for multi-class GBRT", "if", "hasattr", "(", "gbrt", ",", "'classes_'", ")", "and", "np", ".", "size", "(", "gbrt", ".", "classes_", ")", ">", "2", ":", "if", "label", "is", "None", ":", "raise", "ValueError", "(", "'label is not given for multi-class PDP'", ")", "label_idx", "=", "np", ".", "searchsorted", "(", "gbrt", ".", "classes_", ",", "label", ")", "if", "gbrt", ".", "classes_", "[", "label_idx", "]", "!=", "label", ":", "raise", "ValueError", "(", "'label %s not in ``gbrt.classes_``'", "%", "str", "(", "label", ")", ")", "else", ":", "# regression and binary classification", "label_idx", "=", "0", "X", "=", "check_array", "(", "X", ",", "dtype", "=", "DTYPE", ",", "order", "=", "'C'", ")", "if", "gbrt", ".", "n_features_", "!=", "X", ".", "shape", "[", "1", "]", ":", "raise", "ValueError", "(", "'X.shape[1] does not match gbrt.n_features_'", ")", "if", "line_kw", "is", "None", ":", "line_kw", "=", "{", "'color'", ":", "'green'", "}", "if", "contour_kw", "is", "None", ":", "contour_kw", "=", "{", "}", "# convert feature_names to list", "if", "feature_names", "is", "None", ":", "# if not feature_names use fx indices as name", "feature_names", "=", "[", "str", "(", "i", ")", "for", "i", "in", "range", "(", "gbrt", ".", "n_features_", ")", "]", "elif", "isinstance", "(", "feature_names", ",", "np", ".", "ndarray", ")", ":", "feature_names", "=", "feature_names", ".", "tolist", "(", ")", "def", "convert_feature", "(", "fx", ")", ":", "if", "isinstance", "(", "fx", ",", "str", ")", ":", "try", ":", "fx", "=", "feature_names", ".", "index", "(", "fx", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'Feature %s not in feature_names'", "%", "fx", ")", "return", "fx", "# convert features into a seq of int tuples", "tmp_features", "=", "[", "]", "for", "fxs", "in", "features", ":", "if", "isinstance", "(", "fxs", ",", "(", "numbers", ".", "Integral", ",", "str", ")", ")", ":", "fxs", "=", "(", "fxs", ",", ")", "try", ":", "fxs", "=", "np", ".", "array", "(", "[", "convert_feature", "(", "fx", ")", "for", "fx", "in", "fxs", "]", ",", "dtype", "=", "np", ".", "int32", ")", "except", "TypeError", ":", "raise", "ValueError", "(", "'features must be either int, str, or tuple '", "'of int/str'", ")", "if", "not", "(", "1", "<=", "np", ".", "size", "(", "fxs", ")", "<=", "2", ")", ":", "raise", "ValueError", "(", "'target features must be either one or two'", ")", "tmp_features", ".", "append", "(", "fxs", ")", "features", "=", "tmp_features", "names", "=", "[", "]", "try", ":", "for", "fxs", "in", "features", ":", "l", "=", "[", "]", "# explicit loop so \"i\" is bound for exception below", "for", "i", "in", "fxs", ":", "l", ".", "append", "(", "feature_names", "[", "i", "]", ")", "names", ".", "append", "(", "l", ")", "except", "IndexError", ":", "raise", "ValueError", "(", "'All entries of features must be less than '", "'len(feature_names) = {0}, got {1}.'", ".", "format", "(", "len", "(", "feature_names", ")", ",", "i", ")", ")", "# compute PD functions", "pd_result", "=", "Parallel", "(", "n_jobs", "=", "n_jobs", ",", "verbose", "=", "verbose", ")", "(", "delayed", "(", "partial_dependence", ")", "(", "gbrt", ",", "fxs", ",", "X", "=", "X", ",", "grid_resolution", "=", "grid_resolution", ",", "percentiles", "=", "percentiles", ")", "for", "fxs", "in", "features", ")", "# get global min and max values of PD grouped by plot type", "pdp_lim", "=", "{", "}", "for", "pdp", ",", "axes", "in", "pd_result", ":", "min_pd", ",", "max_pd", "=", "pdp", "[", "label_idx", "]", ".", "min", "(", ")", ",", "pdp", "[", "label_idx", "]", ".", "max", "(", ")", "n_fx", "=", "len", "(", "axes", ")", "old_min_pd", ",", "old_max_pd", "=", "pdp_lim", ".", "get", "(", "n_fx", ",", "(", "min_pd", ",", "max_pd", ")", ")", "min_pd", "=", "min", "(", "min_pd", ",", "old_min_pd", ")", "max_pd", "=", "max", "(", "max_pd", ",", "old_max_pd", ")", "pdp_lim", "[", "n_fx", "]", "=", "(", "min_pd", ",", "max_pd", ")", "# create contour levels for two-way plots", "if", "2", "in", "pdp_lim", ":", "Z_level", "=", "np", ".", "linspace", "(", "*", "pdp_lim", "[", "2", "]", ",", "num", "=", "8", ")", "if", "ax", "is", "None", ":", "fig", "=", "plt", ".", "figure", "(", "*", "*", "fig_kw", ")", "else", ":", "fig", "=", "ax", ".", "get_figure", "(", ")", "fig", ".", "clear", "(", ")", "n_cols", "=", "min", "(", "n_cols", ",", "len", "(", "features", ")", ")", "n_rows", "=", "int", "(", "np", ".", "ceil", "(", "len", "(", "features", ")", "/", "float", "(", "n_cols", ")", ")", ")", "axs", "=", "[", "]", "for", "i", ",", "fx", ",", "name", ",", "(", "pdp", ",", "axes", ")", "in", "zip", "(", "count", "(", ")", ",", "features", ",", "names", ",", "pd_result", ")", ":", "ax", "=", "fig", ".", "add_subplot", "(", "n_rows", ",", "n_cols", ",", "i", "+", "1", ")", "if", "len", "(", "axes", ")", "==", "1", ":", "ax", ".", "plot", "(", "axes", "[", "0", "]", ",", "pdp", "[", "label_idx", "]", ".", "ravel", "(", ")", ",", "*", "*", "line_kw", ")", "else", ":", "# make contour plot", "assert", "len", "(", "axes", ")", "==", "2", "XX", ",", "YY", "=", "np", ".", "meshgrid", "(", "axes", "[", "0", "]", ",", "axes", "[", "1", "]", ")", "Z", "=", "pdp", "[", "label_idx", "]", ".", "reshape", "(", "list", "(", "map", "(", "np", ".", "size", ",", "axes", ")", ")", ")", ".", "T", "CS", "=", "ax", ".", "contour", "(", "XX", ",", "YY", ",", "Z", ",", "levels", "=", "Z_level", ",", "linewidths", "=", "0.5", ",", "colors", "=", "'k'", ")", "ax", ".", "contourf", "(", "XX", ",", "YY", ",", "Z", ",", "levels", "=", "Z_level", ",", "vmax", "=", "Z_level", "[", "-", "1", "]", ",", "vmin", "=", "Z_level", "[", "0", "]", ",", "alpha", "=", "0.75", ",", "*", "*", "contour_kw", ")", "ax", ".", "clabel", "(", "CS", ",", "fmt", "=", "'%2.2f'", ",", "colors", "=", "'k'", ",", "fontsize", "=", "10", ",", "inline", "=", "True", ")", "# plot data deciles + axes labels", "deciles", "=", "mquantiles", "(", "X", "[", ":", ",", "fx", "[", "0", "]", "]", ",", "prob", "=", "np", ".", "arange", "(", "0.1", ",", "1.0", ",", "0.1", ")", ")", "trans", "=", "transforms", ".", "blended_transform_factory", "(", "ax", ".", "transData", ",", "ax", ".", "transAxes", ")", "ylim", "=", "ax", ".", "get_ylim", "(", ")", "ax", ".", "vlines", "(", "deciles", ",", "[", "0", "]", ",", "0.05", ",", "transform", "=", "trans", ",", "color", "=", "'k'", ")", "ax", ".", "set_xlabel", "(", "name", "[", "0", "]", ")", "ax", ".", "set_ylim", "(", "ylim", ")", "# prevent x-axis ticks from overlapping", "ax", ".", "xaxis", ".", "set_major_locator", "(", "MaxNLocator", "(", "nbins", "=", "6", ",", "prune", "=", "'lower'", ")", ")", "tick_formatter", "=", "ScalarFormatter", "(", ")", "tick_formatter", ".", "set_powerlimits", "(", "(", "-", "3", ",", "4", ")", ")", "ax", ".", "xaxis", ".", "set_major_formatter", "(", "tick_formatter", ")", "if", "len", "(", "axes", ")", ">", "1", ":", "# two-way PDP - y-axis deciles + labels", "deciles", "=", "mquantiles", "(", "X", "[", ":", ",", "fx", "[", "1", "]", "]", ",", "prob", "=", "np", ".", "arange", "(", "0.1", ",", "1.0", ",", "0.1", ")", ")", "trans", "=", "transforms", ".", "blended_transform_factory", "(", "ax", ".", "transAxes", ",", "ax", ".", "transData", ")", "xlim", "=", "ax", ".", "get_xlim", "(", ")", "ax", ".", "hlines", "(", "deciles", ",", "[", "0", "]", ",", "0.05", ",", "transform", "=", "trans", ",", "color", "=", "'k'", ")", "ax", ".", "set_ylabel", "(", "name", "[", "1", "]", ")", "# hline erases xlim", "ax", ".", "set_xlim", "(", "xlim", ")", "else", ":", "ax", ".", "set_ylabel", "(", "'Partial dependence'", ")", "if", "len", "(", "axes", ")", "==", "1", ":", "ax", ".", "set_ylim", "(", "pdp_lim", "[", "1", "]", ")", "axs", ".", "append", "(", "ax", ")", "fig", ".", "subplots_adjust", "(", "bottom", "=", "0.15", ",", "top", "=", "0.7", ",", "left", "=", "0.1", ",", "right", "=", "0.95", ",", "wspace", "=", "0.4", ",", "hspace", "=", "0.3", ")", "return", "fig", ",", "axs" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/ensemble/partial_dependence.py#L192-L441
logcabin/logcabin
ee6c55ae9744b82b451becd9707d26c7c1b6bbfb
scripts/enum_type_wrapper.py
python
EnumTypeWrapper.keys
(self)
return [value_descriptor.name for value_descriptor in self._enum_type.values]
Return a list of the string names in the enum. These are returned in the order they were defined in the .proto file.
Return a list of the string names in the enum.
[ "Return", "a", "list", "of", "the", "string", "names", "in", "the", "enum", "." ]
def keys(self): """Return a list of the string names in the enum. These are returned in the order they were defined in the .proto file. """ return [value_descriptor.name for value_descriptor in self._enum_type.values]
[ "def", "keys", "(", "self", ")", ":", "return", "[", "value_descriptor", ".", "name", "for", "value_descriptor", "in", "self", ".", "_enum_type", ".", "values", "]" ]
https://github.com/logcabin/logcabin/blob/ee6c55ae9744b82b451becd9707d26c7c1b6bbfb/scripts/enum_type_wrapper.py#L65-L72
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
PyApp.IsDisplayAvailable
(*args, **kwargs)
return _core_.PyApp_IsDisplayAvailable(*args, **kwargs)
IsDisplayAvailable() -> bool Tests if it is possible to create a GUI in the current environment. This will mean different things on the different platforms. * On X Windows systems this function will return ``False`` if it is not able to open a connection to the X server, which can happen if $DISPLAY is not set, or is not set correctly. * On Mac OS X a ``False`` return value will mean that wx is not able to access the window manager, which can happen if logged in remotely or if running from the normal version of python instead of the framework version, (i.e., pythonw.) * On MS Windows...
IsDisplayAvailable() -> bool
[ "IsDisplayAvailable", "()", "-", ">", "bool" ]
def IsDisplayAvailable(*args, **kwargs): """ IsDisplayAvailable() -> bool Tests if it is possible to create a GUI in the current environment. This will mean different things on the different platforms. * On X Windows systems this function will return ``False`` if it is not able to open a connection to the X server, which can happen if $DISPLAY is not set, or is not set correctly. * On Mac OS X a ``False`` return value will mean that wx is not able to access the window manager, which can happen if logged in remotely or if running from the normal version of python instead of the framework version, (i.e., pythonw.) * On MS Windows... """ return _core_.PyApp_IsDisplayAvailable(*args, **kwargs)
[ "def", "IsDisplayAvailable", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "PyApp_IsDisplayAvailable", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L8218-L8237
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/wsgiref/handlers.py
python
BaseHandler.start_response
(self, status, headers,exc_info=None)
return self.write
start_response()' callable as specified by PEP 333
start_response()' callable as specified by PEP 333
[ "start_response", "()", "callable", "as", "specified", "by", "PEP", "333" ]
def start_response(self, status, headers,exc_info=None): """'start_response()' callable as specified by PEP 333""" if exc_info: try: if self.headers_sent: # Re-raise original exception if headers sent raise exc_info[0], exc_info[1], exc_info[2] finally: exc_info = None # avoid dangling circular ref elif self.headers is not None: raise AssertionError("Headers already set!") assert type(status) is StringType,"Status must be a string" assert len(status)>=4,"Status must be at least 4 characters" assert int(status[:3]),"Status message must begin w/3-digit code" assert status[3]==" ", "Status message must have a space after code" if __debug__: for name,val in headers: assert type(name) is StringType,"Header names must be strings" assert type(val) is StringType,"Header values must be strings" assert not is_hop_by_hop(name),"Hop-by-hop headers not allowed" self.status = status self.headers = self.headers_class(headers) return self.write
[ "def", "start_response", "(", "self", ",", "status", ",", "headers", ",", "exc_info", "=", "None", ")", ":", "if", "exc_info", ":", "try", ":", "if", "self", ".", "headers_sent", ":", "# Re-raise original exception if headers sent", "raise", "exc_info", "[", "0", "]", ",", "exc_info", "[", "1", "]", ",", "exc_info", "[", "2", "]", "finally", ":", "exc_info", "=", "None", "# avoid dangling circular ref", "elif", "self", ".", "headers", "is", "not", "None", ":", "raise", "AssertionError", "(", "\"Headers already set!\"", ")", "assert", "type", "(", "status", ")", "is", "StringType", ",", "\"Status must be a string\"", "assert", "len", "(", "status", ")", ">=", "4", ",", "\"Status must be at least 4 characters\"", "assert", "int", "(", "status", "[", ":", "3", "]", ")", ",", "\"Status message must begin w/3-digit code\"", "assert", "status", "[", "3", "]", "==", "\" \"", ",", "\"Status message must have a space after code\"", "if", "__debug__", ":", "for", "name", ",", "val", "in", "headers", ":", "assert", "type", "(", "name", ")", "is", "StringType", ",", "\"Header names must be strings\"", "assert", "type", "(", "val", ")", "is", "StringType", ",", "\"Header values must be strings\"", "assert", "not", "is_hop_by_hop", "(", "name", ")", ",", "\"Hop-by-hop headers not allowed\"", "self", ".", "status", "=", "status", "self", ".", "headers", "=", "self", ".", "headers_class", "(", "headers", ")", "return", "self", ".", "write" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/wsgiref/handlers.py#L160-L184
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/cmd.py
python
Cmd.cmdloop
(self, intro=None)
Repeatedly issue a prompt, accept input, parse an initial prefix off the received input, and dispatch to action methods, passing them the remainder of the line as argument.
Repeatedly issue a prompt, accept input, parse an initial prefix off the received input, and dispatch to action methods, passing them the remainder of the line as argument.
[ "Repeatedly", "issue", "a", "prompt", "accept", "input", "parse", "an", "initial", "prefix", "off", "the", "received", "input", "and", "dispatch", "to", "action", "methods", "passing", "them", "the", "remainder", "of", "the", "line", "as", "argument", "." ]
def cmdloop(self, intro=None): """Repeatedly issue a prompt, accept input, parse an initial prefix off the received input, and dispatch to action methods, passing them the remainder of the line as argument. """ self.preloop() if self.use_rawinput and self.completekey: try: import readline self.old_completer = readline.get_completer() readline.set_completer(self.complete) readline.parse_and_bind(self.completekey+": complete") except ImportError: pass try: if intro is not None: self.intro = intro if self.intro: self.stdout.write(str(self.intro)+"\n") stop = None while not stop: if self.cmdqueue: line = self.cmdqueue.pop(0) else: if self.use_rawinput: try: line = raw_input(self.prompt) except EOFError: line = 'EOF' else: self.stdout.write(self.prompt) self.stdout.flush() line = self.stdin.readline() if not len(line): line = 'EOF' else: line = line.rstrip('\r\n') line = self.precmd(line) stop = self.onecmd(line) stop = self.postcmd(stop, line) self.postloop() finally: if self.use_rawinput and self.completekey: try: import readline readline.set_completer(self.old_completer) except ImportError: pass
[ "def", "cmdloop", "(", "self", ",", "intro", "=", "None", ")", ":", "self", ".", "preloop", "(", ")", "if", "self", ".", "use_rawinput", "and", "self", ".", "completekey", ":", "try", ":", "import", "readline", "self", ".", "old_completer", "=", "readline", ".", "get_completer", "(", ")", "readline", ".", "set_completer", "(", "self", ".", "complete", ")", "readline", ".", "parse_and_bind", "(", "self", ".", "completekey", "+", "\": complete\"", ")", "except", "ImportError", ":", "pass", "try", ":", "if", "intro", "is", "not", "None", ":", "self", ".", "intro", "=", "intro", "if", "self", ".", "intro", ":", "self", ".", "stdout", ".", "write", "(", "str", "(", "self", ".", "intro", ")", "+", "\"\\n\"", ")", "stop", "=", "None", "while", "not", "stop", ":", "if", "self", ".", "cmdqueue", ":", "line", "=", "self", ".", "cmdqueue", ".", "pop", "(", "0", ")", "else", ":", "if", "self", ".", "use_rawinput", ":", "try", ":", "line", "=", "raw_input", "(", "self", ".", "prompt", ")", "except", "EOFError", ":", "line", "=", "'EOF'", "else", ":", "self", ".", "stdout", ".", "write", "(", "self", ".", "prompt", ")", "self", ".", "stdout", ".", "flush", "(", ")", "line", "=", "self", ".", "stdin", ".", "readline", "(", ")", "if", "not", "len", "(", "line", ")", ":", "line", "=", "'EOF'", "else", ":", "line", "=", "line", ".", "rstrip", "(", "'\\r\\n'", ")", "line", "=", "self", ".", "precmd", "(", "line", ")", "stop", "=", "self", ".", "onecmd", "(", "line", ")", "stop", "=", "self", ".", "postcmd", "(", "stop", ",", "line", ")", "self", ".", "postloop", "(", ")", "finally", ":", "if", "self", ".", "use_rawinput", "and", "self", ".", "completekey", ":", "try", ":", "import", "readline", "readline", ".", "set_completer", "(", "self", ".", "old_completer", ")", "except", "ImportError", ":", "pass" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/cmd.py#L102-L151
KratosMultiphysics/Kratos
0000833054ed0503424eb28205d6508d9ca6cbbc
applications/ShallowWaterApplication/python_scripts/postprocess/convergence_plotter.py
python
ConvergencePlotter.__init__
(self, file_name, analysis_name='analysis_000', area=1.0)
Construct the plotter, read the file and initialize the variables. Parameters ---------- file_name : str The file name without extension analysis_name : str The name of the dataset inside the file area : float The area of the domain. It is used to compute the average element size
Construct the plotter, read the file and initialize the variables.
[ "Construct", "the", "plotter", "read", "the", "file", "and", "initialize", "the", "variables", "." ]
def __init__(self, file_name, analysis_name='analysis_000', area=1.0): '''Construct the plotter, read the file and initialize the variables. Parameters ---------- file_name : str The file name without extension analysis_name : str The name of the dataset inside the file area : float The area of the domain. It is used to compute the average element size ''' # Read the file file_name = file_name + '.hdf5' f = h5.File(file_name) self.ds = f[analysis_name] # General data self.dset_time_steps = self.ds["time_step"] self.dset_num_elems = self.ds["num_elems"] self.dset_num_nodes = self.ds["num_nodes"] self.dset_elem_sizes = np.sqrt(area / self.dset_num_elems) # Initialize the filter self.filter = self._TrueFilter()
[ "def", "__init__", "(", "self", ",", "file_name", ",", "analysis_name", "=", "'analysis_000'", ",", "area", "=", "1.0", ")", ":", "# Read the file", "file_name", "=", "file_name", "+", "'.hdf5'", "f", "=", "h5", ".", "File", "(", "file_name", ")", "self", ".", "ds", "=", "f", "[", "analysis_name", "]", "# General data", "self", ".", "dset_time_steps", "=", "self", ".", "ds", "[", "\"time_step\"", "]", "self", ".", "dset_num_elems", "=", "self", ".", "ds", "[", "\"num_elems\"", "]", "self", ".", "dset_num_nodes", "=", "self", ".", "ds", "[", "\"num_nodes\"", "]", "self", ".", "dset_elem_sizes", "=", "np", ".", "sqrt", "(", "area", "/", "self", ".", "dset_num_elems", ")", "# Initialize the filter", "self", ".", "filter", "=", "self", ".", "_TrueFilter", "(", ")" ]
https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/ShallowWaterApplication/python_scripts/postprocess/convergence_plotter.py#L12-L36
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
DQM/Integration/scripts/harvesting_tools/cmsHarvester.py
python
CMSHarvester.option_handler_force
(self, option, opt_str, value, parser)
Switch on `force mode' in which case we don't brake for nobody. In so-called `force mode' all sanity checks are performed but we don't halt on failure. Of course this requires some care from the user.
Switch on `force mode' in which case we don't brake for nobody.
[ "Switch", "on", "force", "mode", "in", "which", "case", "we", "don", "t", "brake", "for", "nobody", "." ]
def option_handler_force(self, option, opt_str, value, parser): """Switch on `force mode' in which case we don't brake for nobody. In so-called `force mode' all sanity checks are performed but we don't halt on failure. Of course this requires some care from the user. """ self.logger.debug("Switching on `force mode'.") self.force_running = True
[ "def", "option_handler_force", "(", "self", ",", "option", ",", "opt_str", ",", "value", ",", "parser", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Switching on `force mode'.\"", ")", "self", ".", "force_running", "=", "True" ]
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/DQM/Integration/scripts/harvesting_tools/cmsHarvester.py#L696-L706
asLody/whale
6a661b27cc4cf83b7b5a3b02451597ee1ac7f264
whale/cpplint.py
python
IsErrorSuppressedByNolint
(category, linenum)
return (_global_error_suppressions.get(category, False) or linenum in _error_suppressions.get(category, set()) or linenum in _error_suppressions.get(None, set()))
Returns true if the specified error category is suppressed on this line. Consults the global error_suppressions map populated by ParseNolintSuppressions/ProcessGlobalSuppresions/ResetNolintSuppressions. Args: category: str, the category of the error. linenum: int, the current line number. Returns: bool, True iff the error should be suppressed due to a NOLINT comment or global suppression.
Returns true if the specified error category is suppressed on this line.
[ "Returns", "true", "if", "the", "specified", "error", "category", "is", "suppressed", "on", "this", "line", "." ]
def IsErrorSuppressedByNolint(category, linenum): """Returns true if the specified error category is suppressed on this line. Consults the global error_suppressions map populated by ParseNolintSuppressions/ProcessGlobalSuppresions/ResetNolintSuppressions. Args: category: str, the category of the error. linenum: int, the current line number. Returns: bool, True iff the error should be suppressed due to a NOLINT comment or global suppression. """ return (_global_error_suppressions.get(category, False) or linenum in _error_suppressions.get(category, set()) or linenum in _error_suppressions.get(None, set()))
[ "def", "IsErrorSuppressedByNolint", "(", "category", ",", "linenum", ")", ":", "return", "(", "_global_error_suppressions", ".", "get", "(", "category", ",", "False", ")", "or", "linenum", "in", "_error_suppressions", ".", "get", "(", "category", ",", "set", "(", ")", ")", "or", "linenum", "in", "_error_suppressions", ".", "get", "(", "None", ",", "set", "(", ")", ")", ")" ]
https://github.com/asLody/whale/blob/6a661b27cc4cf83b7b5a3b02451597ee1ac7f264/whale/cpplint.py#L639-L654
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_misc.py
python
LogWindow.GetFrame
(*args, **kwargs)
return _misc_.LogWindow_GetFrame(*args, **kwargs)
GetFrame(self) -> wxFrame
GetFrame(self) -> wxFrame
[ "GetFrame", "(", "self", ")", "-", ">", "wxFrame" ]
def GetFrame(*args, **kwargs): """GetFrame(self) -> wxFrame""" return _misc_.LogWindow_GetFrame(*args, **kwargs)
[ "def", "GetFrame", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "LogWindow_GetFrame", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L1774-L1776
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/distribute/distribute_lib.py
python
get_update_replica_id
()
Get the current device if in a `tf.distribute.Strategy.update()` call.
Get the current device if in a `tf.distribute.Strategy.update()` call.
[ "Get", "the", "current", "device", "if", "in", "a", "tf", ".", "distribute", ".", "Strategy", ".", "update", "()", "call", "." ]
def get_update_replica_id(): """Get the current device if in a `tf.distribute.Strategy.update()` call.""" try: return _update_replica_id.current except AttributeError: return None
[ "def", "get_update_replica_id", "(", ")", ":", "try", ":", "return", "_update_replica_id", ".", "current", "except", "AttributeError", ":", "return", "None" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/distribute/distribute_lib.py#L239-L244
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
catboost/benchmarks/ranking/ndcg_kaggle.py
python
dcg_score
(y_true, y_score, k=5)
return np.sum(gain / discounts)
Discounted cumulative gain (DCG) at rank K. Parameters ---------- y_true : array, shape = [n_samples] Ground truth (true relevance labels). y_score : array, shape = [n_samples, n_classes] Predicted scores. k : int Rank. Returns ------- score : float
Discounted cumulative gain (DCG) at rank K.
[ "Discounted", "cumulative", "gain", "(", "DCG", ")", "at", "rank", "K", "." ]
def dcg_score(y_true, y_score, k=5): """Discounted cumulative gain (DCG) at rank K. Parameters ---------- y_true : array, shape = [n_samples] Ground truth (true relevance labels). y_score : array, shape = [n_samples, n_classes] Predicted scores. k : int Rank. Returns ------- score : float """ order = np.argsort(y_score)[::-1] y_true = np.take(y_true, order[:k]) gain = 2 ** y_true - 1 discounts = np.log2(np.arange(len(y_true)) + 2) return np.sum(gain / discounts)
[ "def", "dcg_score", "(", "y_true", ",", "y_score", ",", "k", "=", "5", ")", ":", "order", "=", "np", ".", "argsort", "(", "y_score", ")", "[", ":", ":", "-", "1", "]", "y_true", "=", "np", ".", "take", "(", "y_true", ",", "order", "[", ":", "k", "]", ")", "gain", "=", "2", "**", "y_true", "-", "1", "discounts", "=", "np", ".", "log2", "(", "np", ".", "arange", "(", "len", "(", "y_true", ")", ")", "+", "2", ")", "return", "np", ".", "sum", "(", "gain", "/", "discounts", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/catboost/benchmarks/ranking/ndcg_kaggle.py#L10-L32
OGRECave/ogre-next
287307980e6de8910f04f3cc0994451b075071fd
Tools/BlenderExport/ogrepkg/armatureexport.py
python
ArmatureExporter.getActions
(self)
return self.actionManager.getActions()
Returns list of available actions.
Returns list of available actions.
[ "Returns", "list", "of", "available", "actions", "." ]
def getActions(self): """Returns list of available actions. """ return self.actionManager.getActions()
[ "def", "getActions", "(", "self", ")", ":", "return", "self", ".", "actionManager", ".", "getActions", "(", ")" ]
https://github.com/OGRECave/ogre-next/blob/287307980e6de8910f04f3cc0994451b075071fd/Tools/BlenderExport/ogrepkg/armatureexport.py#L505-L508