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
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/protobuf/python/google/protobuf/internal/cpp_message.py
python
InitMessage
(message_descriptor, cls)
Constructs a new message instance (called before instance's __init__).
Constructs a new message instance (called before instance's __init__).
[ "Constructs", "a", "new", "message", "instance", "(", "called", "before", "instance", "s", "__init__", ")", "." ]
def InitMessage(message_descriptor, cls): """Constructs a new message instance (called before instance's __init__).""" cls._extensions_by_name = {} _AddInitMethod(message_descriptor, cls) _AddMessageMethods(message_descriptor, cls) _AddPropertiesForExtensions(message_descriptor, cls) copy_reg.pickle(cls, lambda obj: (cls, (), obj.__getstate__()))
[ "def", "InitMessage", "(", "message_descriptor", ",", "cls", ")", ":", "cls", ".", "_extensions_by_name", "=", "{", "}", "_AddInitMethod", "(", "message_descriptor", ",", "cls", ")", "_AddMessageMethods", "(", "message_descriptor", ",", "cls", ")", "_AddProperties...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/protobuf/python/google/protobuf/internal/cpp_message.py#L382-L388
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py3/IPython/core/inputtransformer.py
python
_strip_prompts
(prompt_re, initial_re=None, turnoff_re=None)
Remove matching input prompts from a block of input. Parameters ---------- prompt_re : regular expression A regular expression matching any input prompt (including continuation) initial_re : regular expression, optional A regular expression matching only the initial prompt, but not continuation. If no initial expression is given, prompt_re will be used everywhere. Used mainly for plain Python prompts, where the continuation prompt ``...`` is a valid Python expression in Python 3, so shouldn't be stripped. If initial_re and prompt_re differ, only initial_re will be tested against the first line. If any prompt is found on the first two lines, prompts will be stripped from the rest of the block.
Remove matching input prompts from a block of input. Parameters ---------- prompt_re : regular expression A regular expression matching any input prompt (including continuation) initial_re : regular expression, optional A regular expression matching only the initial prompt, but not continuation. If no initial expression is given, prompt_re will be used everywhere. Used mainly for plain Python prompts, where the continuation prompt ``...`` is a valid Python expression in Python 3, so shouldn't be stripped. If initial_re and prompt_re differ, only initial_re will be tested against the first line. If any prompt is found on the first two lines, prompts will be stripped from the rest of the block.
[ "Remove", "matching", "input", "prompts", "from", "a", "block", "of", "input", ".", "Parameters", "----------", "prompt_re", ":", "regular", "expression", "A", "regular", "expression", "matching", "any", "input", "prompt", "(", "including", "continuation", ")", ...
def _strip_prompts(prompt_re, initial_re=None, turnoff_re=None): """Remove matching input prompts from a block of input. Parameters ---------- prompt_re : regular expression A regular expression matching any input prompt (including continuation) initial_re : regular expression, optional A regular expression matching only the initial prompt, but not continuation. If no initial expression is given, prompt_re will be used everywhere. Used mainly for plain Python prompts, where the continuation prompt ``...`` is a valid Python expression in Python 3, so shouldn't be stripped. If initial_re and prompt_re differ, only initial_re will be tested against the first line. If any prompt is found on the first two lines, prompts will be stripped from the rest of the block. """ if initial_re is None: initial_re = prompt_re line = '' while True: line = (yield line) # First line of cell if line is None: continue out, n1 = initial_re.subn('', line, count=1) if turnoff_re and not n1: if turnoff_re.match(line): # We're in e.g. a cell magic; disable this transformer for # the rest of the cell. while line is not None: line = (yield line) continue line = (yield out) if line is None: continue # check for any prompt on the second line of the cell, # because people often copy from just after the first prompt, # so we might not see it in the first line. out, n2 = prompt_re.subn('', line, count=1) line = (yield out) if n1 or n2: # Found a prompt in the first two lines - check for it in # the rest of the cell as well. while line is not None: line = (yield prompt_re.sub('', line, count=1)) else: # Prompts not in input - wait for reset while line is not None: line = (yield line)
[ "def", "_strip_prompts", "(", "prompt_re", ",", "initial_re", "=", "None", ",", "turnoff_re", "=", "None", ")", ":", "if", "initial_re", "is", "None", ":", "initial_re", "=", "prompt_re", "line", "=", "''", "while", "True", ":", "line", "=", "(", "yield"...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/core/inputtransformer.py#L398-L453
bryanyzhu/Hidden-Two-Stream
f7f684adbdacb6df6b1cf196c3a476cd23484a0f
scripts/cpp_lint.py
python
GetLineWidth
(line)
Determines the width of the line in column positions. Args: line: A string, which may be a Unicode string. Returns: The width of the line in column positions, accounting for Unicode combining characters and wide characters.
Determines the width of the line in column positions.
[ "Determines", "the", "width", "of", "the", "line", "in", "column", "positions", "." ]
def GetLineWidth(line): """Determines the width of the line in column positions. Args: line: A string, which may be a Unicode string. Returns: The width of the line in column positions, accounting for Unicode combining characters and wide characters. """ if isinstance(line, unicode): width = 0 for uc in unicodedata.normalize('NFC', line): if unicodedata.east_asian_width(uc) in ('W', 'F'): width += 2 elif not unicodedata.combining(uc): width += 1 return width else: return len(line)
[ "def", "GetLineWidth", "(", "line", ")", ":", "if", "isinstance", "(", "line", ",", "unicode", ")", ":", "width", "=", "0", "for", "uc", "in", "unicodedata", ".", "normalize", "(", "'NFC'", ",", "line", ")", ":", "if", "unicodedata", ".", "east_asian_w...
https://github.com/bryanyzhu/Hidden-Two-Stream/blob/f7f684adbdacb6df6b1cf196c3a476cd23484a0f/scripts/cpp_lint.py#L3437-L3456
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
ChildFocusEvent.__init__
(self, *args, **kwargs)
__init__(self, Window win=None) -> ChildFocusEvent Constructor
__init__(self, Window win=None) -> ChildFocusEvent
[ "__init__", "(", "self", "Window", "win", "=", "None", ")", "-", ">", "ChildFocusEvent" ]
def __init__(self, *args, **kwargs): """ __init__(self, Window win=None) -> ChildFocusEvent Constructor """ _core_.ChildFocusEvent_swiginit(self,_core_.new_ChildFocusEvent(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_core_", ".", "ChildFocusEvent_swiginit", "(", "self", ",", "_core_", ".", "new_ChildFocusEvent", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L6342-L6348
RegrowthStudios/SoACode-Public
c3ddd69355b534d5e70e2e6d0c489b4e93ab1ffe
utils/git-hooks/cpplint/cpplint.py
python
FindNextMultiLineCommentStart
(lines, lineix)
return len(lines)
Find the beginning marker for a multiline comment.
Find the beginning marker for a multiline comment.
[ "Find", "the", "beginning", "marker", "for", "a", "multiline", "comment", "." ]
def FindNextMultiLineCommentStart(lines, lineix): """Find the beginning marker for a multiline comment.""" while lineix < len(lines): if lines[lineix].strip().startswith('/*'): # Only return this marker if the comment goes beyond this line if lines[lineix].strip().find('*/', 2) < 0: return lineix lineix += 1 return len(lines)
[ "def", "FindNextMultiLineCommentStart", "(", "lines", ",", "lineix", ")", ":", "while", "lineix", "<", "len", "(", "lines", ")", ":", "if", "lines", "[", "lineix", "]", ".", "strip", "(", ")", ".", "startswith", "(", "'/*'", ")", ":", "# Only return this...
https://github.com/RegrowthStudios/SoACode-Public/blob/c3ddd69355b534d5e70e2e6d0c489b4e93ab1ffe/utils/git-hooks/cpplint/cpplint.py#L883-L891
apache/thrift
0b29261a4f3c6882ef3b09aae47914f0012b0472
lib/py/src/Thrift.py
python
TProcessor.process
(self, iprot, oprot)
Process a request. The normal behvaior is to have the processor invoke the correct handler and then it is the server's responsibility to write the response to oprot.
Process a request. The normal behvaior is to have the processor invoke the correct handler and then it is the server's responsibility to write the response to oprot.
[ "Process", "a", "request", ".", "The", "normal", "behvaior", "is", "to", "have", "the", "processor", "invoke", "the", "correct", "handler", "and", "then", "it", "is", "the", "server", "s", "responsibility", "to", "write", "the", "response", "to", "oprot", ...
def process(self, iprot, oprot): """ Process a request. The normal behvaior is to have the processor invoke the correct handler and then it is the server's responsibility to write the response to oprot. """ pass
[ "def", "process", "(", "self", ",", "iprot", ",", "oprot", ")", ":", "pass" ]
https://github.com/apache/thrift/blob/0b29261a4f3c6882ef3b09aae47914f0012b0472/lib/py/src/Thrift.py#L72-L78
cmu-db/noisepage
79276e68fe83322f1249e8a8be96bd63c583ae56
script/self_driving/forecasting/forecaster.py
python
Forecaster.__init__
( self, trace_file: str, trace_sequence: List, interval_us: int, test_mode: bool, eval_size: int, seq_len: int, horizon_len: int)
Initializer :param trace_file: trace file for the forecaster :param interval_us: number of microseconds for the time-series interval :param test_mode: True If the Loader is for testing :param eval_size: Number of data points used for evaluation(testing) :param seq_len: Length of a sequence :param horizon_len: Horizon length
Initializer :param trace_file: trace file for the forecaster :param interval_us: number of microseconds for the time-series interval :param test_mode: True If the Loader is for testing :param eval_size: Number of data points used for evaluation(testing) :param seq_len: Length of a sequence :param horizon_len: Horizon length
[ "Initializer", ":", "param", "trace_file", ":", "trace", "file", "for", "the", "forecaster", ":", "param", "interval_us", ":", "number", "of", "microseconds", "for", "the", "time", "-", "series", "interval", ":", "param", "test_mode", ":", "True", "If", "the...
def __init__( self, trace_file: str, trace_sequence: List, interval_us: int, test_mode: bool, eval_size: int, seq_len: int, horizon_len: int) -> None: """ Initializer :param trace_file: trace file for the forecaster :param interval_us: number of microseconds for the time-series interval :param test_mode: True If the Loader is for testing :param eval_size: Number of data points used for evaluation(testing) :param seq_len: Length of a sequence :param horizon_len: Horizon length """ self._seq_len = seq_len self._horizon_len = horizon_len self._test_mode = test_mode self._eval_data_size = eval_size self._data_loader = DataLoader( query_trace_file=trace_file, query_sequence=trace_sequence, interval_us=interval_us) self._make_clusters()
[ "def", "__init__", "(", "self", ",", "trace_file", ":", "str", ",", "trace_sequence", ":", "List", ",", "interval_us", ":", "int", ",", "test_mode", ":", "bool", ",", "eval_size", ":", "int", ",", "seq_len", ":", "int", ",", "horizon_len", ":", "int", ...
https://github.com/cmu-db/noisepage/blob/79276e68fe83322f1249e8a8be96bd63c583ae56/script/self_driving/forecasting/forecaster.py#L17-L45
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
build/android/android_commands.py
python
AndroidCommands.SetupPerformanceTest
(self)
Sets up performance tests.
Sets up performance tests.
[ "Sets", "up", "performance", "tests", "." ]
def SetupPerformanceTest(self): """Sets up performance tests.""" # Disable CPU scaling to reduce noise in tests if not self._original_governor: self._original_governor = self.RunShellCommand('cat ' + SCALING_GOVERNOR) self.RunShellCommand('echo performance > ' + SCALING_GOVERNOR) self.DropRamCaches()
[ "def", "SetupPerformanceTest", "(", "self", ")", ":", "# Disable CPU scaling to reduce noise in tests", "if", "not", "self", ".", "_original_governor", ":", "self", ".", "_original_governor", "=", "self", ".", "RunShellCommand", "(", "'cat '", "+", "SCALING_GOVERNOR", ...
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/build/android/android_commands.py#L472-L478
google/shaka-packager
e1b0c7c45431327fd3ce193514a5407d07b39b22
packager/third_party/protobuf/python/google/protobuf/internal/well_known_types.py
python
_FieldMaskTree.AddPath
(self, path)
Adds a field path into the tree. If the field path to add is a sub-path of an existing field path in the tree (i.e., a leaf node), it means the tree already matches the given path so nothing will be added to the tree. If the path matches an existing non-leaf node in the tree, that non-leaf node will be turned into a leaf node with all its children removed because the path matches all the node's children. Otherwise, a new path will be added. Args: path: The field path to add.
Adds a field path into the tree.
[ "Adds", "a", "field", "path", "into", "the", "tree", "." ]
def AddPath(self, path): """Adds a field path into the tree. If the field path to add is a sub-path of an existing field path in the tree (i.e., a leaf node), it means the tree already matches the given path so nothing will be added to the tree. If the path matches an existing non-leaf node in the tree, that non-leaf node will be turned into a leaf node with all its children removed because the path matches all the node's children. Otherwise, a new path will be added. Args: path: The field path to add. """ node = self._root for name in path.split('.'): if name not in node: node[name] = {} elif not node[name]: # Pre-existing empty node implies we already have this entire tree. return node = node[name] # Remove any sub-trees we might have had. node.clear()
[ "def", "AddPath", "(", "self", ",", "path", ")", ":", "node", "=", "self", ".", "_root", "for", "name", "in", "path", ".", "split", "(", "'.'", ")", ":", "if", "name", "not", "in", "node", ":", "node", "[", "name", "]", "=", "{", "}", "elif", ...
https://github.com/google/shaka-packager/blob/e1b0c7c45431327fd3ce193514a5407d07b39b22/packager/third_party/protobuf/python/google/protobuf/internal/well_known_types.py#L560-L583
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/frame.py
python
DataFrame.to_feather
(self, path)
Write out the binary feather-format for DataFrames. Parameters ---------- path : str String file path.
Write out the binary feather-format for DataFrames.
[ "Write", "out", "the", "binary", "feather", "-", "format", "for", "DataFrames", "." ]
def to_feather(self, path) -> None: """ Write out the binary feather-format for DataFrames. Parameters ---------- path : str String file path. """ from pandas.io.feather_format import to_feather to_feather(self, path)
[ "def", "to_feather", "(", "self", ",", "path", ")", "->", "None", ":", "from", "pandas", ".", "io", ".", "feather_format", "import", "to_feather", "to_feather", "(", "self", ",", "path", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/frame.py#L1983-L1994
larroy/clearskies_core
3574ddf0edc8555454c7044126e786a6c29444dc
tools/gyp/pylib/gyp/generator/msvs.py
python
_InitNinjaFlavor
(options, target_list, target_dicts)
Initialize targets for the ninja flavor. This sets up the necessary variables in the targets to generate msvs projects that use ninja as an external builder. The variables in the spec are only set if they have not been set. This allows individual specs to override the default values initialized here. Arguments: options: Options provided to the generator. target_list: List of target pairs: 'base/base.gyp:base'. target_dicts: Dict of target properties keyed on target pair.
Initialize targets for the ninja flavor.
[ "Initialize", "targets", "for", "the", "ninja", "flavor", "." ]
def _InitNinjaFlavor(options, target_list, target_dicts): """Initialize targets for the ninja flavor. This sets up the necessary variables in the targets to generate msvs projects that use ninja as an external builder. The variables in the spec are only set if they have not been set. This allows individual specs to override the default values initialized here. Arguments: options: Options provided to the generator. target_list: List of target pairs: 'base/base.gyp:base'. target_dicts: Dict of target properties keyed on target pair. """ for qualified_target in target_list: spec = target_dicts[qualified_target] if spec.get('msvs_external_builder'): # The spec explicitly defined an external builder, so don't change it. continue path_to_ninja = spec.get('msvs_path_to_ninja', 'ninja.exe') spec['msvs_external_builder'] = 'ninja' if not spec.get('msvs_external_builder_out_dir'): spec['msvs_external_builder_out_dir'] = \ options.depth + '/out/$(Configuration)' if not spec.get('msvs_external_builder_build_cmd'): spec['msvs_external_builder_build_cmd'] = [ path_to_ninja, '-C', '$(OutDir)', '$(ProjectName)', ] if not spec.get('msvs_external_builder_clean_cmd'): spec['msvs_external_builder_clean_cmd'] = [ path_to_ninja, '-C', '$(OutDir)', '-t', 'clean', '$(ProjectName)', ]
[ "def", "_InitNinjaFlavor", "(", "options", ",", "target_list", ",", "target_dicts", ")", ":", "for", "qualified_target", "in", "target_list", ":", "spec", "=", "target_dicts", "[", "qualified_target", "]", "if", "spec", ".", "get", "(", "'msvs_external_builder'", ...
https://github.com/larroy/clearskies_core/blob/3574ddf0edc8555454c7044126e786a6c29444dc/tools/gyp/pylib/gyp/generator/msvs.py#L1819-L1858
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/index/package_finder.py
python
PackageFinder._sort_links
(self, links)
return no_eggs + eggs
Returns elements of links in order, non-egg links first, egg links second, while eliminating duplicates
Returns elements of links in order, non-egg links first, egg links second, while eliminating duplicates
[ "Returns", "elements", "of", "links", "in", "order", "non", "-", "egg", "links", "first", "egg", "links", "second", "while", "eliminating", "duplicates" ]
def _sort_links(self, links): # type: (Iterable[Link]) -> List[Link] """ Returns elements of links in order, non-egg links first, egg links second, while eliminating duplicates """ eggs, no_eggs = [], [] seen = set() # type: Set[Link] for link in links: if link not in seen: seen.add(link) if link.egg_fragment: eggs.append(link) else: no_eggs.append(link) return no_eggs + eggs
[ "def", "_sort_links", "(", "self", ",", "links", ")", ":", "# type: (Iterable[Link]) -> List[Link]", "eggs", ",", "no_eggs", "=", "[", "]", ",", "[", "]", "seen", "=", "set", "(", ")", "# type: Set[Link]", "for", "link", "in", "links", ":", "if", "link", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/index/package_finder.py#L718-L733
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/difflib.py
python
IS_CHARACTER_JUNK
(ch, ws=" \t")
return ch in ws
r""" Return 1 for ignorable character: iff `ch` is a space or tab. Examples: >>> IS_CHARACTER_JUNK(' ') True >>> IS_CHARACTER_JUNK('\t') True >>> IS_CHARACTER_JUNK('\n') False >>> IS_CHARACTER_JUNK('x') False
r""" Return 1 for ignorable character: iff `ch` is a space or tab.
[ "r", "Return", "1", "for", "ignorable", "character", ":", "iff", "ch", "is", "a", "space", "or", "tab", "." ]
def IS_CHARACTER_JUNK(ch, ws=" \t"): r""" Return 1 for ignorable character: iff `ch` is a space or tab. Examples: >>> IS_CHARACTER_JUNK(' ') True >>> IS_CHARACTER_JUNK('\t') True >>> IS_CHARACTER_JUNK('\n') False >>> IS_CHARACTER_JUNK('x') False """ return ch in ws
[ "def", "IS_CHARACTER_JUNK", "(", "ch", ",", "ws", "=", "\" \\t\"", ")", ":", "return", "ch", "in", "ws" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/difflib.py#L1122-L1138
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/mixins/listctrl.py
python
ListCtrlSelectionManagerMix.setPopupMenu
(self, menu)
Must be set for default behaviour
Must be set for default behaviour
[ "Must", "be", "set", "for", "default", "behaviour" ]
def setPopupMenu(self, menu): """ Must be set for default behaviour """ self._menu = menu
[ "def", "setPopupMenu", "(", "self", ",", "menu", ")", ":", "self", ".", "_menu", "=", "menu" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/mixins/listctrl.py#L379-L381
dmlc/treelite
df56babb6a4a2d7c29d719c28ce53acfa7dbab3c
python/treelite/contrib/__init__.py
python
create_shared
(toolchain, dirpath, *, nthread=None, verbose=False, options=None, long_build_time_warning=True)
return libpath
Create shared library. Parameters ---------- toolchain : :py:class:`str <python:str>` which toolchain to use. You may choose one of 'msvc', 'clang', and 'gcc'. You may also specify a specific variation of clang or gcc (e.g. 'gcc-7') dirpath : :py:class:`str <python:str>` directory containing the header and source files previously generated by :py:meth:`Model.compile`. The directory must contain recipe.json which specifies build dependencies. nthread : :py:class:`int <python:int>`, optional number of threads to use in creating the shared library. Defaults to the number of cores in the system. verbose : :py:class:`bool <python:bool>`, optional whether to produce extra messages options : :py:class:`list <python:list>` of :py:class:`str <python:str>`, \ optional Additional options to pass to toolchain long_build_time_warning : :py:class:`bool <python:bool>`, optional If set to False, suppress the warning about potentially long build time Returns ------- libpath : :py:class:`str <python:str>` absolute path of created shared library Example ------- The following command uses Visual C++ toolchain to generate ``./my/model/model.dll``: .. code-block:: python model.compile(dirpath='./my/model', params={}, verbose=True) create_shared(toolchain='msvc', dirpath='./my/model', verbose=True) Later, the shared library can be referred to by its directory name: .. code-block:: python predictor = Predictor(libpath='./my/model', verbose=True) # looks for ./my/model/model.dll Alternatively, one may specify the library down to its file name: .. code-block:: python predictor = Predictor(libpath='./my/model/model.dll', verbose=True)
Create shared library.
[ "Create", "shared", "library", "." ]
def create_shared(toolchain, dirpath, *, nthread=None, verbose=False, options=None, long_build_time_warning=True): """Create shared library. Parameters ---------- toolchain : :py:class:`str <python:str>` which toolchain to use. You may choose one of 'msvc', 'clang', and 'gcc'. You may also specify a specific variation of clang or gcc (e.g. 'gcc-7') dirpath : :py:class:`str <python:str>` directory containing the header and source files previously generated by :py:meth:`Model.compile`. The directory must contain recipe.json which specifies build dependencies. nthread : :py:class:`int <python:int>`, optional number of threads to use in creating the shared library. Defaults to the number of cores in the system. verbose : :py:class:`bool <python:bool>`, optional whether to produce extra messages options : :py:class:`list <python:list>` of :py:class:`str <python:str>`, \ optional Additional options to pass to toolchain long_build_time_warning : :py:class:`bool <python:bool>`, optional If set to False, suppress the warning about potentially long build time Returns ------- libpath : :py:class:`str <python:str>` absolute path of created shared library Example ------- The following command uses Visual C++ toolchain to generate ``./my/model/model.dll``: .. code-block:: python model.compile(dirpath='./my/model', params={}, verbose=True) create_shared(toolchain='msvc', dirpath='./my/model', verbose=True) Later, the shared library can be referred to by its directory name: .. code-block:: python predictor = Predictor(libpath='./my/model', verbose=True) # looks for ./my/model/model.dll Alternatively, one may specify the library down to its file name: .. code-block:: python predictor = Predictor(libpath='./my/model/model.dll', verbose=True) """ # pylint: disable=R0912 if nthread is not None and nthread <= 0: raise TreeliteError('nthread must be positive integer') dirpath = expand_windows_path(dirpath) if not os.path.isdir(dirpath): raise TreeliteError('Directory {} does not exist'.format(dirpath)) try: with open(os.path.join(dirpath, 'recipe.json'), 'r', encoding='UTF-8') as f: recipe = json.load(f) except IOError as e: raise TreeliteError('Failed to open recipe.json') from e if 'sources' not in recipe or 'target' not in recipe: raise TreeliteError('Malformed recipe.json') if options is not None: try: _ = iter(options) options = [str(x) for x in options] except TypeError as e: raise TreeliteError('options must be a list of string') from e else: options = [] # Write warning for potentially long compile time if long_build_time_warning: warn = False for source in recipe['sources']: if int(source['length']) > 10000: warn = True break if warn: log_info(__file__, lineno(), '\033[1;31mWARNING: some of the source files are long. ' + \ 'Expect long build time.\u001B[0m ' + \ 'You may want to adjust the parameter ' + \ '\x1B[33mparallel_comp\u001B[0m.\n') tstart = time.time() _toolchain_exist_check(toolchain) if toolchain == 'msvc': from .msvc import _create_shared else: from .gcc import _create_shared libpath = \ _create_shared(dirpath, toolchain, recipe, nthread, options, verbose) if verbose: log_info(__file__, lineno(), 'Generated shared library in ' + \ '{0:.2f} seconds'.format(time.time() - tstart)) return libpath
[ "def", "create_shared", "(", "toolchain", ",", "dirpath", ",", "*", ",", "nthread", "=", "None", ",", "verbose", "=", "False", ",", "options", "=", "None", ",", "long_build_time_warning", "=", "True", ")", ":", "# pylint: disable=R0912", "if", "nthread", "is...
https://github.com/dmlc/treelite/blob/df56babb6a4a2d7c29d719c28ce53acfa7dbab3c/python/treelite/contrib/__init__.py#L182-L285
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/wsgiref/handlers.py
python
BaseHandler.client_is_modern
(self)
return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9'
True if client can accept status and headers
True if client can accept status and headers
[ "True", "if", "client", "can", "accept", "status", "and", "headers" ]
def client_is_modern(self): """True if client can accept status and headers""" return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9'
[ "def", "client_is_modern", "(", "self", ")", ":", "return", "self", ".", "environ", "[", "'SERVER_PROTOCOL'", "]", ".", "upper", "(", ")", "!=", "'HTTP/0.9'" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/wsgiref/handlers.py#L355-L357
pytorch/ELF
e851e786ced8d26cf470f08a6b9bf7e413fc63f7
src_py/elf/utils_elf.py
python
Batch.transfer_cpu2cpu
(self, batch_dst, non_blocking=True)
transfer batch data to cpu
transfer batch data to cpu
[ "transfer", "batch", "data", "to", "cpu" ]
def transfer_cpu2cpu(self, batch_dst, non_blocking=True): ''' transfer batch data to cpu ''' # For each time step for k, v in self.batch.items(): batch_dst[k].copy_(v)
[ "def", "transfer_cpu2cpu", "(", "self", ",", "batch_dst", ",", "non_blocking", "=", "True", ")", ":", "# For each time step", "for", "k", ",", "v", "in", "self", ".", "batch", ".", "items", "(", ")", ":", "batch_dst", "[", "k", "]", ".", "copy_", "(", ...
https://github.com/pytorch/ELF/blob/e851e786ced8d26cf470f08a6b9bf7e413fc63f7/src_py/elf/utils_elf.py#L269-L274
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py2/numpy/polynomial/_polybase.py
python
ABCPolyBase.degree
(self)
return len(self) - 1
The degree of the series. .. versionadded:: 1.5.0 Returns ------- degree : int Degree of the series, one less than the number of coefficients.
The degree of the series.
[ "The", "degree", "of", "the", "series", "." ]
def degree(self): """The degree of the series. .. versionadded:: 1.5.0 Returns ------- degree : int Degree of the series, one less than the number of coefficients. """ return len(self) - 1
[ "def", "degree", "(", "self", ")", ":", "return", "len", "(", "self", ")", "-", "1" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/polynomial/_polybase.py#L534-L545
mamedev/mame
02cd26d37ee11191f3e311e19e805d872cb1e3a4
3rdparty/portmidi/pm_python/pyportmidi/midi.py
python
Input.__init__
(self, device_id, buffer_size=4096)
The buffer_size specifies the number of input events to be buffered waiting to be read using Input.read().
The buffer_size specifies the number of input events to be buffered waiting to be read using Input.read().
[ "The", "buffer_size", "specifies", "the", "number", "of", "input", "events", "to", "be", "buffered", "waiting", "to", "be", "read", "using", "Input", ".", "read", "()", "." ]
def __init__(self, device_id, buffer_size=4096): """ The buffer_size specifies the number of input events to be buffered waiting to be read using Input.read(). """ _check_init() if device_id == -1: raise MidiException("Device id is -1, not a valid output id. -1 usually means there were no default Output devices.") try: r = get_device_info(device_id) except TypeError: raise TypeError("an integer is required") except OverflowError: raise OverflowError("long int too large to convert to int") # and now some nasty looking error checking, to provide nice error # messages to the kind, lovely, midi using people of whereever. if r: interf, name, input, output, opened = r if input: try: self._input = _pypm.Input(device_id, buffer_size) except TypeError: raise TypeError("an integer is required") self.device_id = device_id elif output: raise MidiException("Device id given is not a valid input id, it is an output id.") else: raise MidiException("Device id given is not a valid input id.") else: raise MidiException("Device id invalid, out of range.")
[ "def", "__init__", "(", "self", ",", "device_id", ",", "buffer_size", "=", "4096", ")", ":", "_check_init", "(", ")", "if", "device_id", "==", "-", "1", ":", "raise", "MidiException", "(", "\"Device id is -1, not a valid output id. -1 usually means there were no defa...
https://github.com/mamedev/mame/blob/02cd26d37ee11191f3e311e19e805d872cb1e3a4/3rdparty/portmidi/pm_python/pyportmidi/midi.py#L213-L246
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/utils/data/gen_pyi.py
python
extract_method_name
(line: str)
return line[start:end]
Extracts method name from decorator in the form of "@functional_datapipe({method_name})"
Extracts method name from decorator in the form of "
[ "Extracts", "method", "name", "from", "decorator", "in", "the", "form", "of" ]
def extract_method_name(line: str) -> str: """ Extracts method name from decorator in the form of "@functional_datapipe({method_name})" """ if "(\"" in line: start_token, end_token = "(\"", "\")" elif "(\'" in line: start_token, end_token = "(\'", "\')" else: raise RuntimeError(f"Unable to find appropriate method name within line:\n{line}") start, end = line.find(start_token) + len(start_token), line.find(end_token) return line[start:end]
[ "def", "extract_method_name", "(", "line", ":", "str", ")", "->", "str", ":", "if", "\"(\\\"\"", "in", "line", ":", "start_token", ",", "end_token", "=", "\"(\\\"\"", ",", "\"\\\")\"", "elif", "\"(\\'\"", "in", "line", ":", "start_token", ",", "end_token", ...
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/utils/data/gen_pyi.py#L21-L32
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/distribute/distribute_lib.py
python
ReplicaContextBase._merge_call
(self, merge_fn, args, kwargs)
Default implementation for single replica.
Default implementation for single replica.
[ "Default", "implementation", "for", "single", "replica", "." ]
def _merge_call(self, merge_fn, args, kwargs): """Default implementation for single replica.""" _push_per_thread_mode( # thread-local, so not needed with multiple threads distribution_strategy_context._CrossReplicaThreadMode(self._strategy)) # pylint: disable=protected-access try: return merge_fn(self._strategy, *args, **kwargs) finally: _pop_per_thread_mode()
[ "def", "_merge_call", "(", "self", ",", "merge_fn", ",", "args", ",", "kwargs", ")", ":", "_push_per_thread_mode", "(", "# thread-local, so not needed with multiple threads", "distribution_strategy_context", ".", "_CrossReplicaThreadMode", "(", "self", ".", "_strategy", "...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/distribute/distribute_lib.py#L3105-L3112
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/botocore/signers.py
python
CloudFrontSigner.build_policy
(self, resource, date_less_than, date_greater_than=None, ip_address=None)
return json.dumps(custom_policy, separators=(',', ':'))
A helper to build policy. :type resource: str :param resource: The URL or the stream filename of the protected object :type date_less_than: datetime :param date_less_than: The URL will expire after the time has passed :type date_greater_than: datetime :param date_greater_than: The URL will not be valid until this time :type ip_address: str :param ip_address: Use 'x.x.x.x' for an IP, or 'x.x.x.x/x' for a subnet :rtype: str :return: The policy in a compact string.
A helper to build policy.
[ "A", "helper", "to", "build", "policy", "." ]
def build_policy(self, resource, date_less_than, date_greater_than=None, ip_address=None): """A helper to build policy. :type resource: str :param resource: The URL or the stream filename of the protected object :type date_less_than: datetime :param date_less_than: The URL will expire after the time has passed :type date_greater_than: datetime :param date_greater_than: The URL will not be valid until this time :type ip_address: str :param ip_address: Use 'x.x.x.x' for an IP, or 'x.x.x.x/x' for a subnet :rtype: str :return: The policy in a compact string. """ # Note: # 1. Order in canned policy is significant. Special care has been taken # to ensure the output will match the order defined by the document. # There is also a test case to ensure that order. # SEE: http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-creating-signed-url-canned-policy.html#private-content-canned-policy-creating-policy-statement # 2. Albeit the order in custom policy is not required by CloudFront, # we still use OrderedDict internally to ensure the result is stable # and also matches canned policy requirement. # SEE: http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-creating-signed-url-custom-policy.html moment = int(datetime2timestamp(date_less_than)) condition = OrderedDict({"DateLessThan": {"AWS:EpochTime": moment}}) if ip_address: if '/' not in ip_address: ip_address += '/32' condition["IpAddress"] = {"AWS:SourceIp": ip_address} if date_greater_than: moment = int(datetime2timestamp(date_greater_than)) condition["DateGreaterThan"] = {"AWS:EpochTime": moment} ordered_payload = [('Resource', resource), ('Condition', condition)] custom_policy = {"Statement": [OrderedDict(ordered_payload)]} return json.dumps(custom_policy, separators=(',', ':'))
[ "def", "build_policy", "(", "self", ",", "resource", ",", "date_less_than", ",", "date_greater_than", "=", "None", ",", "ip_address", "=", "None", ")", ":", "# Note:", "# 1. Order in canned policy is significant. Special care has been taken", "# to ensure the output will m...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/botocore/signers.py#L355-L394
Cantera/cantera
0119484b261967ccb55a0066c020599cacc312e4
platform/posix/coverage.py
python
test
()
Run the full test suite.
Run the full test suite.
[ "Run", "the", "full", "test", "suite", "." ]
def test(): """ Run the full test suite. """ subprocess.call(['scons', 'test-reset']) subprocess.call(['scons', 'test'])
[ "def", "test", "(", ")", ":", "subprocess", ".", "call", "(", "[", "'scons'", ",", "'test-reset'", "]", ")", "subprocess", ".", "call", "(", "[", "'scons'", ",", "'test'", "]", ")" ]
https://github.com/Cantera/cantera/blob/0119484b261967ccb55a0066c020599cacc312e4/platform/posix/coverage.py#L44-L49
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/numpy/linalg.py
python
cholesky
(a, upper=False)
return _mx_nd_np.linalg.cholesky(a, upper)
r""" Cholesky decomposition. Notes ----- `upper` param is requested by API standardization in https://data-apis.org/array-api/latest/extensions/generated/signatures.linalg.cholesky.html instead of parameter in official NumPy operator. Return the Cholesky decomposition, `L * L.T`, of the square matrix `a`, where `L` is lower-triangular and .T is the transpose operator. `a` must be symmetric and positive-definite. Only `L` is actually returned. Complex-valued input is currently not supported. Parameters ---------- a : (..., M, M) ndarray Symmetric, positive-definite input matrix. upper : bool If `True`, the result must be the upper-triangular Cholesky factor. If `False`, the result must be the lower-triangular Cholesky factor. Default: `False`. Returns ------- L : (..., M, M) ndarray Lower-triangular Cholesky factor of `a`. Raises ------ MXNetError If the decomposition fails, for example, if `a` is not positive-definite. Notes ----- Broadcasting rules apply. The Cholesky decomposition is often used as a fast way of solving .. math:: A \mathbf{x} = \mathbf{b} (when `A` is both symmetric and positive-definite). First, we solve for :math:`\mathbf{y}` in .. math:: L \mathbf{y} = \mathbf{b}, and then for :math:`\mathbf{x}` in .. math:: L.T \mathbf{x} = \mathbf{y}. Examples -------- >>> A = np.array([[16, 4], [4, 10]]) >>> A array([[16., 4.], [ 4., 10.]]) >>> L = np.linalg.cholesky(A) >>> L array([[4., 0.], [1., 3.]]) >>> np.dot(L, L.T) array([[16., 4.], [ 4., 10.]])
r""" Cholesky decomposition.
[ "r", "Cholesky", "decomposition", "." ]
def cholesky(a, upper=False): r""" Cholesky decomposition. Notes ----- `upper` param is requested by API standardization in https://data-apis.org/array-api/latest/extensions/generated/signatures.linalg.cholesky.html instead of parameter in official NumPy operator. Return the Cholesky decomposition, `L * L.T`, of the square matrix `a`, where `L` is lower-triangular and .T is the transpose operator. `a` must be symmetric and positive-definite. Only `L` is actually returned. Complex-valued input is currently not supported. Parameters ---------- a : (..., M, M) ndarray Symmetric, positive-definite input matrix. upper : bool If `True`, the result must be the upper-triangular Cholesky factor. If `False`, the result must be the lower-triangular Cholesky factor. Default: `False`. Returns ------- L : (..., M, M) ndarray Lower-triangular Cholesky factor of `a`. Raises ------ MXNetError If the decomposition fails, for example, if `a` is not positive-definite. Notes ----- Broadcasting rules apply. The Cholesky decomposition is often used as a fast way of solving .. math:: A \mathbf{x} = \mathbf{b} (when `A` is both symmetric and positive-definite). First, we solve for :math:`\mathbf{y}` in .. math:: L \mathbf{y} = \mathbf{b}, and then for :math:`\mathbf{x}` in .. math:: L.T \mathbf{x} = \mathbf{y}. Examples -------- >>> A = np.array([[16, 4], [4, 10]]) >>> A array([[16., 4.], [ 4., 10.]]) >>> L = np.linalg.cholesky(A) >>> L array([[4., 0.], [1., 3.]]) >>> np.dot(L, L.T) array([[16., 4.], [ 4., 10.]]) """ return _mx_nd_np.linalg.cholesky(a, upper)
[ "def", "cholesky", "(", "a", ",", "upper", "=", "False", ")", ":", "return", "_mx_nd_np", ".", "linalg", ".", "cholesky", "(", "a", ",", "upper", ")" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/numpy/linalg.py#L826-L892
praydog/REFramework
c12cdd921e4beb5e3398f8afe0376e446be91344
reversing/rsz/emulation-dumper.py
python
hook_code
(emu, address, size, frame)
try: emu.mem_read(address, 4) except unicorn.UcError as e: #frame["call_stack"].pop() return False
try: emu.mem_read(address, 4) except unicorn.UcError as e: #frame["call_stack"].pop() return False
[ "try", ":", "emu", ".", "mem_read", "(", "address", "4", ")", "except", "unicorn", ".", "UcError", "as", "e", ":", "#frame", "[", "call_stack", "]", ".", "pop", "()", "return", "False" ]
def hook_code(emu, address, size, frame): frame["context"] = pickle.dumps(emu.context_save()) cs = frame["cs"] deserialize_arg = frame["deserialize_arg"] # We don't want to do this. We manually call each parent deserializer to mark where in the structure they start. # It's also easier to manage this way, we don't have to worry about nested shit. if len(frame["call_stack"]) > 1 and address in frame["deserializers"]: print("STOPPING EXECUTION!!!!") invalidate_and_return_call(emu, frame) emu.emu_stop() return # Upon first address in a call if len(frame["call_stack"]) > 0 and frame["call_stack"][-1]["first"] == True: frame["call_stack"][-1]["first"] = False # When the deserialize function calls another function, # We only care when it calls a function that reads the stream for deserialization # Any other function is irrelevant to us if emu.reg_read(UC_X86_REG_RCX) != deserialize_arg: invalidate_and_return_call(emu, frame) emu.emu_stop() return ''' try: emu.mem_read(address, 4) except unicorn.UcError as e: #frame["call_stack"].pop() return False ''' # print("%X %i" % (address, size)) try: dis = next(cs.disasm(emu.mem_read(address, size), address, 1)) except Exception as e: print(traceback.format_exc(), "EXCEPTION 0x%X" % address) print(" ", emu.mem_read(address, 0x100).hex()) print("%X" % frame["call_stack"][-1]["last_executed_addr"]) os.system("pause") # print("0x%x: %s %s" % (address, dis.mnemonic, dis.op_str)) lex = 0 if len(frame["call_stack"]) > 0: lex = frame["call_stack"][-1]["last_executed_addr"] if len(frame["call_stack"]) == 1: cur_hist = frame["call_stack"][0]["history"] # We just left a loop if address not in cur_hist.keys() and lex in cur_hist.keys() and cur_hist[lex] > 1: list_size = cur_hist[lex] - 1 # Loop count matches the integer we filled the whole buffer with if list_size == FILL_BYTE: try: element_layout = frame["layout"][-1] except IndexError as e: cs.detail = True dis_g = cs.disasm(emu.mem_read(lex, 0x100), address, 1) dis = next(dis_g) print("LEX: 0x%x" % lex) print("0x%x: %s %s" % (address, dis.mnemonic, dis.op_str)) print("Instruction at %X didn't read bytes from stream?" % address) os.system("pause") return # Erase the elements that were added to the layout, keep list only frame["layout"] = frame["layout"][0:len(frame["layout"]) - FILL_BYTE] frame["was_string"] = False list_layout = frame["layout"][-1] list_layout["list"] = True list_layout["element"] = element_layout list_layout["element_size"] = int((element_layout["offset"] - list_layout["offset"]) / FILL_BYTE) # print("LIST DETECTED") # easy way to wait until after insn executes to read stuff if lex > 0: cs.detail = True try: last_dis_g = cs.disasm(emu.mem_read(lex, 0x100), address, 1) except Exception as e: print(traceback.format_exc(), "LEX EXCEPTION 0x%X 0x%X" % (address, lex)) for i in range(0, len(frame["call_stack"])): print("0x%X" % frame["call_stack"][i]["last_executed_addr"]) print(" ", emu.mem_read(address, 0x100).hex()) print("%X" % frame["call_stack"][-1]["last_executed_addr"]) os.system("pause") last_dis = next(last_dis_g) deserialize_cur = int.from_bytes(emu.mem_read(frame["deserialize_arg"] + 0x8, 8), sys.byteorder) has_operands = len(last_dis.operands) > 0 if last_dis.mnemonic == "mov" and has_operands and last_dis.operands[0].type == X86_OP_REG: val = emu.reg_read(last_dis.operands[0].reg) if val == deserialize_cur: # print("0x%X" % val) frame["last_deserialize_reg"] = last_dis.operands[0].reg frame["last_deserialize_reg_val"] = val # print("0x%x: %s %s" % (address, last_dis.mnemonic, last_dis.op_str)) # print("0x%x: %s %s %s" % (address, dis.mnemonic, dis.op_str, dis.reg_name(dis.operands[0].reg))) elif frame["last_deserialize_reg"] != -1: if deserialize_cur != frame["last_deserialize_cur"]: frame["last_deserialize_reg"] = -1 frame["last_deserialize_reg_val"] = 0 # print("0x%x: %s %s" % (address, last_dis.mnemonic, last_dis.op_str)) elif has_operands and last_dis.operands[0].type == X86_OP_REG: val = emu.reg_read(last_dis.operands[0].reg) if val != frame["last_deserialize_reg_val"]: delta = val - frame["last_deserialize_reg_val"] if abs(delta) > 0x10000: print("Huge delta detected. Register overwritten? 0x%X" % lex) # frame["last_deserialize_reg"] = -1 # frame["last_deserialize_reg_val"] = 0 # invalidate_and_return_call(emu, frame) # os.system("pause") if last_dis.mnemonic == "and" and last_dis.operands[1].type == X86_OP_IMM and last_dis.operands[0].reg == frame["last_deserialize_reg"]: # print("0x%X alignment detected" % (~last_dis.operands[1].imm + 1)) # Set this because we don't want the actual byte count screwing up frame["last_deserialize_cur"] = val frame["last_alignment"] = (~last_dis.operands[1].imm + 1) frame["last_deserialize_reg_val"] = val elif frame["last_alignment"] == 4 and last_dis.group(X86_GRP_BRANCH_RELATIVE): frame["was_string"] = True elif frame["last_alignment"] == 4 and last_dis.bytes == bytearray(b"\x4B\x8D\x0C\x41"): # this means "lea rcx, [r9+r8*2]", e.g. reading a wide string frame["was_string"] = True #print("String or list detected") cs.detail = False # Keep track of how many times we've executed the instruction at this address if dis.mnemonic != "ret": counter = 0 # SNEAKY! # unicorn runs this instruction multiple times through the callback to emulate it if dis.mnemonic == "rep movsb": counter = emu.reg_read(UC_X86_REG_ECX) if len(frame["call_stack"]) > 0: # Keep track of all the bytes of the instruction because we NOP them out sometimes for i in range(address, address + dis.size): history = frame["call_stack"][-1]["history"] if i not in history: history[i] = 0 if counter == 0: history[i] = history[i] + 1 if len(frame["call_stack"]) == 1 and counter > FILL_BYTE: print("YUP", history[i]) # if dis.mnemonic == "rep movsb": # print("YUP", history[i]) if dis.mnemonic == "call": is_normal_call = dis.bytes[0] == 0xE8 frame["call_stack"].append({ "addr": address + dis.size, "context": pickle.dumps(emu.context_save()), "history": {}, "last_executed_addr": 0, "first": is_normal_call }) # Potential return from read func if dis.mnemonic == "ret": frame["last_return_val"] = emu.reg_read(UC_X86_REG_RAX) if len(frame["call_stack"]) > 0: frame["call_stack"].pop() deserialize_cur = int.from_bytes(emu.mem_read(deserialize_arg + 0x8, 8), sys.byteorder) if deserialize_cur != frame["last_deserialize_cur"]: delta = deserialize_cur - frame["last_deserialize_cur"] # print("0x%X bytes, 0x%X alignment" % (delta, frame["last_alignment"])) frame["layout"].append({ "size": delta, "element_size": delta, "element": None, "align": frame["last_alignment"], "string": frame["was_string"], "list": False, "offset": deserialize_cur }) frame["last_layout_size"] = len(frame["layout"]) frame["was_string"] = False frame["last_deserialize_reg"] = -1 frame["last_deserialize_reg_val"] = 0 frame["last_deserialize_cur"] = deserialize_cur frame["last_alignment"] = 1 if len(frame["call_stack"]) == 0: # print("Reached end of function call") frame["start"] = EMU_END emu.emu_stop() else: print("Reached end of function call in a BAD WAY") frame["start"] = EMU_END emu.emu_stop() if len(frame["call_stack"]) > 0: frame["call_stack"][-1]["last_executed_addr"] = address frame["last_disasm"] = dis
[ "def", "hook_code", "(", "emu", ",", "address", ",", "size", ",", "frame", ")", ":", "frame", "[", "\"context\"", "]", "=", "pickle", ".", "dumps", "(", "emu", ".", "context_save", "(", ")", ")", "cs", "=", "frame", "[", "\"cs\"", "]", "deserialize_a...
https://github.com/praydog/REFramework/blob/c12cdd921e4beb5e3398f8afe0376e446be91344/reversing/rsz/emulation-dumper.py#L247-L477
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
DQM/SiStripMonitorClient/scripts/submitDQMOfflineCAF.py
python
Func_MkDir
(str_path)
Function Func_MkDir(): Create new directory
Function Func_MkDir(): Create new directory
[ "Function", "Func_MkDir", "()", ":", "Create", "new", "directory" ]
def Func_MkDir(str_path): """ Function Func_MkDir(): Create new directory """ shutil.rmtree(str_path, True) os.mkdir(str_path)
[ "def", "Func_MkDir", "(", "str_path", ")", ":", "shutil", ".", "rmtree", "(", "str_path", ",", "True", ")", "os", ".", "mkdir", "(", "str_path", ")" ]
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/DQM/SiStripMonitorClient/scripts/submitDQMOfflineCAF.py#L280-L285
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/pytables.py
python
Selection.generate
(self, where)
where can be a : dict,list,tuple,string
where can be a : dict,list,tuple,string
[ "where", "can", "be", "a", ":", "dict", "list", "tuple", "string" ]
def generate(self, where): """ where can be a : dict,list,tuple,string """ if where is None: return None q = self.table.queryables() try: return PyTablesExpr(where, queryables=q, encoding=self.table.encoding) except NameError: # raise a nice message, suggesting that the user should use # data_columns qkeys = ",".join(q.keys()) raise ValueError( f"The passed where expression: {where}\n" " contains an invalid variable reference\n" " all of the variable references must be a " "reference to\n" " an axis (e.g. 'index' or 'columns'), or a " "data_column\n" f" The currently defined references are: {qkeys}\n" )
[ "def", "generate", "(", "self", ",", "where", ")", ":", "if", "where", "is", "None", ":", "return", "None", "q", "=", "self", ".", "table", ".", "queryables", "(", ")", "try", ":", "return", "PyTablesExpr", "(", "where", ",", "queryables", "=", "q", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/pytables.py#L5067-L5087
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
qa/tasks/ceph_manager.py
python
CephManager.remove_pool
(self, pool_name)
Remove the indicated pool :param pool_name: Pool to be removed
Remove the indicated pool :param pool_name: Pool to be removed
[ "Remove", "the", "indicated", "pool", ":", "param", "pool_name", ":", "Pool", "to", "be", "removed" ]
def remove_pool(self, pool_name): """ Remove the indicated pool :param pool_name: Pool to be removed """ with self.lock: assert isinstance(pool_name, str) assert pool_name in self.pools self.log("removing pool_name %s" % (pool_name,)) del self.pools[pool_name] self.raw_cluster_cmd('osd', 'pool', 'rm', pool_name, pool_name, "--yes-i-really-really-mean-it")
[ "def", "remove_pool", "(", "self", ",", "pool_name", ")", ":", "with", "self", ".", "lock", ":", "assert", "isinstance", "(", "pool_name", ",", "str", ")", "assert", "pool_name", "in", "self", ".", "pools", "self", ".", "log", "(", "\"removing pool_name %s...
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/qa/tasks/ceph_manager.py#L2151-L2162
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/buildscripts/resmokelib/parser.py
python
_expand_user
(pathname)
return os.path.expanduser(pathname)
Wrapper around os.path.expanduser() to do nothing when given None.
Wrapper around os.path.expanduser() to do nothing when given None.
[ "Wrapper", "around", "os", ".", "path", ".", "expanduser", "()", "to", "do", "nothing", "when", "given", "None", "." ]
def _expand_user(pathname): """ Wrapper around os.path.expanduser() to do nothing when given None. """ if pathname is None: return None return os.path.expanduser(pathname)
[ "def", "_expand_user", "(", "pathname", ")", ":", "if", "pathname", "is", "None", ":", "return", "None", "return", "os", ".", "path", ".", "expanduser", "(", "pathname", ")" ]
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/resmokelib/parser.py#L513-L519
idaholab/moose
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
python/MooseDocs/tree/base.py
python
NodeBase.__repr__
(self)
return mooseutils.colorText(moosetree.Node.__repr__(self), self.COLOR)
Prints the name of the token, this works in union with __str__ to print the tree structure of any given node.
Prints the name of the token, this works in union with __str__ to print the tree structure of any given node.
[ "Prints", "the", "name", "of", "the", "token", "this", "works", "in", "union", "with", "__str__", "to", "print", "the", "tree", "structure", "of", "any", "given", "node", "." ]
def __repr__(self): """ Prints the name of the token, this works in union with __str__ to print the tree structure of any given node. """ return mooseutils.colorText(moosetree.Node.__repr__(self), self.COLOR)
[ "def", "__repr__", "(", "self", ")", ":", "return", "mooseutils", ".", "colorText", "(", "moosetree", ".", "Node", ".", "__repr__", "(", "self", ")", ",", "self", ".", "COLOR", ")" ]
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/MooseDocs/tree/base.py#L26-L31
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_misc.py
python
AboutBox
(*args, **kwargs)
return _misc_.AboutBox(*args, **kwargs)
AboutBox(AboutDialogInfo info, Window parent=None) This function shows the standard about dialog containing the information specified in ``info``. If the current platform has a native about dialog which is capable of showing all the fields in `wx.AboutDialogInfo`, the native dialog is used, otherwise the function falls back to the generic wxWidgets version of the dialog.
AboutBox(AboutDialogInfo info, Window parent=None)
[ "AboutBox", "(", "AboutDialogInfo", "info", "Window", "parent", "=", "None", ")" ]
def AboutBox(*args, **kwargs): """ AboutBox(AboutDialogInfo info, Window parent=None) This function shows the standard about dialog containing the information specified in ``info``. If the current platform has a native about dialog which is capable of showing all the fields in `wx.AboutDialogInfo`, the native dialog is used, otherwise the function falls back to the generic wxWidgets version of the dialog. """ return _misc_.AboutBox(*args, **kwargs)
[ "def", "AboutBox", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "AboutBox", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L6946-L6956
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/fluid/dygraph/amp/auto_cast.py
python
amp_decorate
(models, optimizers=None, level='O1', master_weight=None, save_dtype=None)
Decorate models and optimizers for auto-mixed-precision. When level is O1(amp), the decorate will do nothing. When level is O2(pure fp16), the decorate will cast all parameters of models to FP16, except BatchNorm and LayerNorm. Commonly, it is used together with `amp_guard` to achieve Pure fp16 in imperative mode. Args: models(Layer|list of Layer, optional): The defined models by user, models must be either a single model or a list of models. Default is None. optimizers(Optimizer|list of Optimizer, optional): The defined optimizers by user, optimizers must be either a single optimizer or a list of optimizers. Default is None. level(str, optional): Auto mixed precision level. Accepted values are "O1" and "O2": O1 represent mixed precision, the decorator will do nothing; O2 represent Pure fp16, the decorator will cast all parameters of models to FP16, except BatchNorm and LayerNorm. Default is O1(amp) master_weight(bool, optinal): For level='O2', whether to use multi-precision during weight updating. If master_weight is None, in O2 level optimizer will use multi-precision. Default is None. save_dtype(float, optional): The save model parameter dtype when use `paddle.save` or `paddle.jit.save`,it should be float16, float32, float64 or None. The save_dtype will not change model parameters dtype, it just change the state_dict dtype. When save_dtype is None, the save dtype is same as model dtype. Default is None. Examples: .. code-block:: python # required: gpu # Demo1: single model and optimizer: import paddle model = paddle.nn.Conv2D(3, 2, 3, bias_attr=False) optimzier = paddle.optimizer.SGD(parameters=model.parameters()) model, optimizer = paddle.fluid.dygraph.amp_decorate(models=model, optimizers=optimzier, level='O2') data = paddle.rand([10, 3, 32, 32]) with paddle.fluid.dygraph.amp_guard(enable=True, custom_white_list=None, custom_black_list=None, level='O2'): output = model(data) print(output.dtype) # FP16 # required: gpu # Demo2: multi models and optimizers: model2 = paddle.nn.Conv2D(3, 2, 3, bias_attr=False) optimizer2 = paddle.optimizer.Adam(parameters=model2.parameters()) models, optimizers = paddle.fluid.dygraph.amp_decorate(models=[model, model2], optimizers=[optimzier, optimizer2], level='O2') data = paddle.rand([10, 3, 32, 32]) with paddle.fluid.dygraph.amp_guard(enable=True, custom_white_list=None, custom_black_list=None, level='O2'): output = models[0](data) output2 = models[1](data) print(output.dtype) # FP16 print(output2.dtype) # FP16 # required: gpu # Demo3: optimizers is None: model3 = paddle.nn.Conv2D(3, 2, 3, bias_attr=False) optimizer3 = paddle.optimizer.Adam(parameters=model2.parameters()) model = paddle.fluid.dygraph.amp_decorate(models=model3, level='O2') data = paddle.rand([10, 3, 32, 32]) with paddle.fluid.dygraph.amp_guard(enable=True, custom_white_list=None, custom_black_list=None, level='O2'): output = model(data) print(output.dtype) # FP16
Decorate models and optimizers for auto-mixed-precision. When level is O1(amp), the decorate will do nothing. When level is O2(pure fp16), the decorate will cast all parameters of models to FP16, except BatchNorm and LayerNorm. Commonly, it is used together with `amp_guard` to achieve Pure fp16 in imperative mode.
[ "Decorate", "models", "and", "optimizers", "for", "auto", "-", "mixed", "-", "precision", ".", "When", "level", "is", "O1", "(", "amp", ")", "the", "decorate", "will", "do", "nothing", ".", "When", "level", "is", "O2", "(", "pure", "fp16", ")", "the", ...
def amp_decorate(models, optimizers=None, level='O1', master_weight=None, save_dtype=None): """ Decorate models and optimizers for auto-mixed-precision. When level is O1(amp), the decorate will do nothing. When level is O2(pure fp16), the decorate will cast all parameters of models to FP16, except BatchNorm and LayerNorm. Commonly, it is used together with `amp_guard` to achieve Pure fp16 in imperative mode. Args: models(Layer|list of Layer, optional): The defined models by user, models must be either a single model or a list of models. Default is None. optimizers(Optimizer|list of Optimizer, optional): The defined optimizers by user, optimizers must be either a single optimizer or a list of optimizers. Default is None. level(str, optional): Auto mixed precision level. Accepted values are "O1" and "O2": O1 represent mixed precision, the decorator will do nothing; O2 represent Pure fp16, the decorator will cast all parameters of models to FP16, except BatchNorm and LayerNorm. Default is O1(amp) master_weight(bool, optinal): For level='O2', whether to use multi-precision during weight updating. If master_weight is None, in O2 level optimizer will use multi-precision. Default is None. save_dtype(float, optional): The save model parameter dtype when use `paddle.save` or `paddle.jit.save`,it should be float16, float32, float64 or None. The save_dtype will not change model parameters dtype, it just change the state_dict dtype. When save_dtype is None, the save dtype is same as model dtype. Default is None. Examples: .. code-block:: python # required: gpu # Demo1: single model and optimizer: import paddle model = paddle.nn.Conv2D(3, 2, 3, bias_attr=False) optimzier = paddle.optimizer.SGD(parameters=model.parameters()) model, optimizer = paddle.fluid.dygraph.amp_decorate(models=model, optimizers=optimzier, level='O2') data = paddle.rand([10, 3, 32, 32]) with paddle.fluid.dygraph.amp_guard(enable=True, custom_white_list=None, custom_black_list=None, level='O2'): output = model(data) print(output.dtype) # FP16 # required: gpu # Demo2: multi models and optimizers: model2 = paddle.nn.Conv2D(3, 2, 3, bias_attr=False) optimizer2 = paddle.optimizer.Adam(parameters=model2.parameters()) models, optimizers = paddle.fluid.dygraph.amp_decorate(models=[model, model2], optimizers=[optimzier, optimizer2], level='O2') data = paddle.rand([10, 3, 32, 32]) with paddle.fluid.dygraph.amp_guard(enable=True, custom_white_list=None, custom_black_list=None, level='O2'): output = models[0](data) output2 = models[1](data) print(output.dtype) # FP16 print(output2.dtype) # FP16 # required: gpu # Demo3: optimizers is None: model3 = paddle.nn.Conv2D(3, 2, 3, bias_attr=False) optimizer3 = paddle.optimizer.Adam(parameters=model2.parameters()) model = paddle.fluid.dygraph.amp_decorate(models=model3, level='O2') data = paddle.rand([10, 3, 32, 32]) with paddle.fluid.dygraph.amp_guard(enable=True, custom_white_list=None, custom_black_list=None, level='O2'): output = model(data) print(output.dtype) # FP16 """ if not (level in ['O1', 'O2']): raise ValueError( "level should be O1 or O2, O1 represent AMP train mode, O2 represent Pure fp16 train mode." ) if level == 'O1': if optimizers is None: return models else: return models, optimizers models_is_list = False if isinstance(models, paddle.nn.Layer): models_is_list = False models = [models] check_models(models) elif isinstance(models, list): check_models(models) models_is_list = True else: raise TypeError( "models must be either a single model or a list of models.") models = pure_fp16_initialize(models=models) if optimizers is not None: # check optimizers optimizers_is_list = False if isinstance(optimizers, (paddle.optimizer.Optimizer, paddle.fluid.optimizer.Optimizer)): optimizers_is_list = False optimizers = [optimizers] check_optimizers(optimizers) elif isinstance(optimizers, list): check_optimizers(optimizers) optimizers_is_list = True else: raise TypeError( "optimizers must be either a single optimizer or a list of optimizers." ) # supprot master_weight for idx_opt in range(len(optimizers)): if hasattr(optimizers[idx_opt], '_multi_precision'): if master_weight is False: optimizers[idx_opt]._multi_precision = False else: optimizers[idx_opt]._multi_precision = True if save_dtype is not None: if not (save_dtype in ['float16', 'float32', 'float64']): raise ValueError( "save_dtype can only be float16 float32 or float64, but your input save_dtype is %s." % save_dtype) for idx in range(len(models)): for layer in models[idx].sublayers(include_self=True): layer.register_state_dict_hook(StateDictHook(save_dtype)) if models_is_list: if optimizers is not None: if optimizers_is_list: return models, optimizers else: return models, optimizers[0] else: return models else: if optimizers is not None: if optimizers_is_list: return models[0], optimizers else: return models[0], optimizers[0] else: return models[0]
[ "def", "amp_decorate", "(", "models", ",", "optimizers", "=", "None", ",", "level", "=", "'O1'", ",", "master_weight", "=", "None", ",", "save_dtype", "=", "None", ")", ":", "if", "not", "(", "level", "in", "[", "'O1'", ",", "'O2'", "]", ")", ":", ...
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/dygraph/amp/auto_cast.py#L295-L434
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/FilterEvents/eventFilterGUI.py
python
MainWindow.move_rightSlider
(self)
Re-setup left range line in figure. Triggered by a change in Qt Widget. NO EVENT is required.
Re-setup left range line in figure. Triggered by a change in Qt Widget. NO EVENT is required.
[ "Re", "-", "setup", "left", "range", "line", "in", "figure", ".", "Triggered", "by", "a", "change", "in", "Qt", "Widget", ".", "NO", "EVENT", "is", "required", "." ]
def move_rightSlider(self): """ Re-setup left range line in figure. Triggered by a change in Qt Widget. NO EVENT is required. """ newx = self.ui.horizontalSlider_2.value() if newx >= self._leftSlideValue and newx != self._rightSlideValue: # Allowed value: move the value bar self._rightSlideValue = newx xlim = self.ui.mainplot.get_xlim() if self.ui.lineEdit_3.text(): # that is not entirely fool proof, as the user could still remove the value in the field after putting # a non round percent, but this a) is unlikely and b) will not crash mantid, only show an artifact newx = max(xlim[0] + newx*(xlim[1] - xlim[0])*0.01, float(self.ui.lineEdit_3.text())) else: newx = xlim[0] + newx*(xlim[1] - xlim[0])*0.01 leftx = [newx, newx] lefty = self.ui.mainplot.get_ylim() setp(self.rightslideline, xdata=leftx, ydata=lefty) self.canvas.draw() # Change value self.ui.lineEdit_4.setText(str(newx)) else: # Reset the value self.ui.horizontalSlider_2.setValue(self._rightSlideValue)
[ "def", "move_rightSlider", "(", "self", ")", ":", "newx", "=", "self", ".", "ui", ".", "horizontalSlider_2", ".", "value", "(", ")", "if", "newx", ">=", "self", ".", "_leftSlideValue", "and", "newx", "!=", "self", ".", "_rightSlideValue", ":", "# Allowed v...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/FilterEvents/eventFilterGUI.py#L326-L354
htcondor/htcondor
4829724575176d1d6c936e4693dfd78a728569b0
src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/conversion.py
python
IConversion.ChatMessageStatusToText
(self, Status)
return self._ToText('cms', Status)
Returns message status as text. @param Status: Chat message status. @type Status: L{Chat message status<enums.cmsUnknown>} @return: Text describing the chat message status. @rtype: unicode
Returns message status as text.
[ "Returns", "message", "status", "as", "text", "." ]
def ChatMessageStatusToText(self, Status): '''Returns message status as text. @param Status: Chat message status. @type Status: L{Chat message status<enums.cmsUnknown>} @return: Text describing the chat message status. @rtype: unicode ''' return self._ToText('cms', Status)
[ "def", "ChatMessageStatusToText", "(", "self", ",", "Status", ")", ":", "return", "self", ".", "_ToText", "(", "'cms'", ",", "Status", ")" ]
https://github.com/htcondor/htcondor/blob/4829724575176d1d6c936e4693dfd78a728569b0/src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/conversion.py#L128-L136
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_windows.py
python
PreHVScrolledWindow
(*args, **kwargs)
return val
PreHVScrolledWindow() -> HVScrolledWindow
PreHVScrolledWindow() -> HVScrolledWindow
[ "PreHVScrolledWindow", "()", "-", ">", "HVScrolledWindow" ]
def PreHVScrolledWindow(*args, **kwargs): """PreHVScrolledWindow() -> HVScrolledWindow""" val = _windows_.new_PreHVScrolledWindow(*args, **kwargs) return val
[ "def", "PreHVScrolledWindow", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "val", "=", "_windows_", ".", "new_PreHVScrolledWindow", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "val" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L2576-L2579
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/deep_memory_profiler/lib/policy.py
python
Policy.find_mmap
(self, region, bucket_set, pageframe=None, group_pfn_counts=None)
Finds a matching component which a given mmap |region| belongs to. It uses |bucket_set| to match with backtraces. If |pageframe| is given, it considers memory sharing among processes. NOTE: Don't use Bucket's |component_cache| for mmap regions because they're classified not only with bucket information (mappedpathname for example). Args: region: A tuple representing a memory region. bucket_set: A BucketSet object to look up backtraces. pageframe: A PageFrame object representing a pageframe maybe including a pagecount. group_pfn_counts: A dict mapping a PFN to the number of times the the pageframe is mapped by the known "group (Chrome)" processes. Returns: A string representing a component name.
Finds a matching component which a given mmap |region| belongs to.
[ "Finds", "a", "matching", "component", "which", "a", "given", "mmap", "|region|", "belongs", "to", "." ]
def find_mmap(self, region, bucket_set, pageframe=None, group_pfn_counts=None): """Finds a matching component which a given mmap |region| belongs to. It uses |bucket_set| to match with backtraces. If |pageframe| is given, it considers memory sharing among processes. NOTE: Don't use Bucket's |component_cache| for mmap regions because they're classified not only with bucket information (mappedpathname for example). Args: region: A tuple representing a memory region. bucket_set: A BucketSet object to look up backtraces. pageframe: A PageFrame object representing a pageframe maybe including a pagecount. group_pfn_counts: A dict mapping a PFN to the number of times the the pageframe is mapped by the known "group (Chrome)" processes. Returns: A string representing a component name. """ assert region[0] == 'hooked' bucket = bucket_set.get(region[1]['bucket_id']) assert not bucket or bucket.allocator_type == 'mmap' if not bucket: return 'no-bucket', None stackfunction = bucket.symbolized_joined_stackfunction stacksourcefile = bucket.symbolized_joined_stacksourcefile sharedwith = self._categorize_pageframe(pageframe, group_pfn_counts) for rule in self._rules: if (rule.allocator_type == 'mmap' and (not rule.stackfunction_pattern or rule.stackfunction_pattern.match(stackfunction)) and (not rule.stacksourcefile_pattern or rule.stacksourcefile_pattern.match(stacksourcefile)) and (not rule.mappedpathname_pattern or rule.mappedpathname_pattern.match(region[1]['vma']['name'])) and (not rule.mappedpermission_pattern or rule.mappedpermission_pattern.match( region[1]['vma']['readable'] + region[1]['vma']['writable'] + region[1]['vma']['executable'] + region[1]['vma']['private'])) and (not rule.sharedwith or not pageframe or sharedwith in rule.sharedwith)): return rule.name, bucket assert False
[ "def", "find_mmap", "(", "self", ",", "region", ",", "bucket_set", ",", "pageframe", "=", "None", ",", "group_pfn_counts", "=", "None", ")", ":", "assert", "region", "[", "0", "]", "==", "'hooked'", "bucket", "=", "bucket_set", ".", "get", "(", "region",...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/deep_memory_profiler/lib/policy.py#L169-L219
NVIDIAGameWorks/kaolin
e5148d05e9c1e2ce92a07881ce3593b1c5c3f166
kaolin/ops/batch.py
python
padded_to_packed
(padded_tensor, shape_per_tensor)
return torch.cat([t.reshape(-1, padded_tensor.shape[-1]) for t in padded_to_list(padded_tensor, shape_per_tensor)], dim=0)
Converts a single padded tensor into a packed tensor. Args: padded_tensor (torch.Tensor): a :ref:`padded tensor<padded>`. shape_per_tensor (torch.LongTensor): the :ref:`shape_per_tensor<padded_shape_per_tensor>` tensor associated to the padded tensor. Returns: (torch.Tensor): the :ref:`packed tensor<packed>`.
Converts a single padded tensor into a packed tensor.
[ "Converts", "a", "single", "padded", "tensor", "into", "a", "packed", "tensor", "." ]
def padded_to_packed(padded_tensor, shape_per_tensor): """Converts a single padded tensor into a packed tensor. Args: padded_tensor (torch.Tensor): a :ref:`padded tensor<padded>`. shape_per_tensor (torch.LongTensor): the :ref:`shape_per_tensor<padded_shape_per_tensor>` tensor associated to the padded tensor. Returns: (torch.Tensor): the :ref:`packed tensor<packed>`. """ return torch.cat([t.reshape(-1, padded_tensor.shape[-1]) for t in padded_to_list(padded_tensor, shape_per_tensor)], dim=0)
[ "def", "padded_to_packed", "(", "padded_tensor", ",", "shape_per_tensor", ")", ":", "return", "torch", ".", "cat", "(", "[", "t", ".", "reshape", "(", "-", "1", ",", "padded_tensor", ".", "shape", "[", "-", "1", "]", ")", "for", "t", "in", "padded_to_l...
https://github.com/NVIDIAGameWorks/kaolin/blob/e5148d05e9c1e2ce92a07881ce3593b1c5c3f166/kaolin/ops/batch.py#L360-L372
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/psutil/_pssunos.py
python
cpu_count_logical
()
Return the number of logical CPUs in the system.
Return the number of logical CPUs in the system.
[ "Return", "the", "number", "of", "logical", "CPUs", "in", "the", "system", "." ]
def cpu_count_logical(): """Return the number of logical CPUs in the system.""" try: return os.sysconf("SC_NPROCESSORS_ONLN") except ValueError: # mimic os.cpu_count() behavior return None
[ "def", "cpu_count_logical", "(", ")", ":", "try", ":", "return", "os", ".", "sysconf", "(", "\"SC_NPROCESSORS_ONLN\"", ")", "except", "ValueError", ":", "# mimic os.cpu_count() behavior", "return", "None" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/psutil/_pssunos.py#L184-L190
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/ribbon/gallery.py
python
RibbonGallery.SetItemClientData
(self, item, data)
Set the client data associated with a gallery item. :param `item`: an instance of :class:`RibbonGalleryItem`; :param `data`: any Python object.
Set the client data associated with a gallery item. :param `item`: an instance of :class:`RibbonGalleryItem`; :param `data`: any Python object.
[ "Set", "the", "client", "data", "associated", "with", "a", "gallery", "item", ".", ":", "param", "item", ":", "an", "instance", "of", ":", "class", ":", "RibbonGalleryItem", ";", ":", "param", "data", ":", "any", "Python", "object", "." ]
def SetItemClientData(self, item, data): """ Set the client data associated with a gallery item. :param `item`: an instance of :class:`RibbonGalleryItem`; :param `data`: any Python object. """ item.SetClientData(data)
[ "def", "SetItemClientData", "(", "self", ",", "item", ",", "data", ")", ":", "item", ".", "SetClientData", "(", "data", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ribbon/gallery.py#L441-L450
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Plot/Plot.py
python
Plot.__init__
(self, winTitle="plot", parent=None, flags=PySide.QtCore.Qt.WindowFlags(0))
Construct a new plot widget. Keyword arguments: winTitle -- Tab title. parent -- Widget parent. flags -- QWidget flags
Construct a new plot widget.
[ "Construct", "a", "new", "plot", "widget", "." ]
def __init__(self, winTitle="plot", parent=None, flags=PySide.QtCore.Qt.WindowFlags(0)): """Construct a new plot widget. Keyword arguments: winTitle -- Tab title. parent -- Widget parent. flags -- QWidget flags """ PySide.QtGui.QWidget.__init__(self, parent, flags) self.setWindowTitle(winTitle) # Create matplotlib canvas self.fig = Figure() self.canvas = FigureCanvas(self.fig) self.canvas.setParent(self) # Get axes self.axes = self.fig.add_subplot(111) self.axesList = [self.axes] self.axes.xaxis.set_ticks_position('bottom') self.axes.spines['top'].set_color('none') self.axes.yaxis.set_ticks_position('left') self.axes.spines['right'].set_color('none') # Add the navigation toolbar by default self.mpl_toolbar = NavigationToolbar(self.canvas, self) # Setup layout vbox = PySide.QtGui.QVBoxLayout() vbox.addWidget(self.canvas) vbox.addWidget(self.mpl_toolbar) self.setLayout(vbox) # Active series self.series = [] # Indicators self.skip = False self.legend = False self.legPos = (1.0, 1.0) self.legSiz = 14 self.grid = False
[ "def", "__init__", "(", "self", ",", "winTitle", "=", "\"plot\"", ",", "parent", "=", "None", ",", "flags", "=", "PySide", ".", "QtCore", ".", "Qt", ".", "WindowFlags", "(", "0", ")", ")", ":", "PySide", ".", "QtGui", ".", "QWidget", ".", "__init__",...
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Plot/Plot.py#L408-L446
danxuhk/ContinuousCRF-CNN
2b6dcaf179620f118b225ed12c890414ca828e21
python/caffe/MultilabelDataLayer.py
python
print_info
(name, params)
Output some info regarding the class
Output some info regarding the class
[ "Output", "some", "info", "regarding", "the", "class" ]
def print_info(name, params): """ Output some info regarding the class """ print "{} initialized for split: {}, with bs: {}, image cropped to size: {}.".format( name, params['split'], params['batch_size'], params['crop_size'])
[ "def", "print_info", "(", "name", ",", "params", ")", ":", "print", "\"{} initialized for split: {}, with bs: {}, image cropped to size: {}.\"", ".", "format", "(", "name", ",", "params", "[", "'split'", "]", ",", "params", "[", "'batch_size'", "]", ",", "params", ...
https://github.com/danxuhk/ContinuousCRF-CNN/blob/2b6dcaf179620f118b225ed12c890414ca828e21/python/caffe/MultilabelDataLayer.py#L179-L187
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/shutil.py
python
_get_uid
(name)
return None
Returns an uid, given a user name.
Returns an uid, given a user name.
[ "Returns", "an", "uid", "given", "a", "user", "name", "." ]
def _get_uid(name): """Returns an uid, given a user name.""" if getpwnam is None or name is None: return None try: result = getpwnam(name) except KeyError: result = None if result is not None: return result[2] return None
[ "def", "_get_uid", "(", "name", ")", ":", "if", "getpwnam", "is", "None", "or", "name", "is", "None", ":", "return", "None", "try", ":", "result", "=", "getpwnam", "(", "name", ")", "except", "KeyError", ":", "result", "=", "None", "if", "result", "i...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/shutil.py#L865-L875
nasa/fprime
595cf3682d8365943d86c1a6fe7c78f0a116acf0
Autocoders/Python/src/fprime_ac/generators/visitors/PortCppVisitor.py
python
PortCppVisitor.__init__
(self)
Constructor.
Constructor.
[ "Constructor", "." ]
def __init__(self): """ Constructor. """ super().__init__() self.__config = ConfigManager.ConfigManager.getInstance() self.__form = formatters.Formatters() self.__form_comment = formatters.CommentFormatters() DEBUG.info("PortCppVisitor: Instanced.") self.bodytext = "" self.prototypetext = ""
[ "def", "__init__", "(", "self", ")", ":", "super", "(", ")", ".", "__init__", "(", ")", "self", ".", "__config", "=", "ConfigManager", ".", "ConfigManager", ".", "getInstance", "(", ")", "self", ".", "__form", "=", "formatters", ".", "Formatters", "(", ...
https://github.com/nasa/fprime/blob/595cf3682d8365943d86c1a6fe7c78f0a116acf0/Autocoders/Python/src/fprime_ac/generators/visitors/PortCppVisitor.py#L66-L76
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/third_party/pyfakefs/pyfakefs/fake_filesystem.py
python
FakeFilesystem.JoinPaths
(self, *paths)
return ''.join(joined_path_segments)
Mimics os.path.join using the specified path_separator. Mimics os.path.join using the path_separator that was specified for this FakeFilesystem. Args: *paths: (str) Zero or more paths to join. Returns: (str) The paths joined by the path separator, starting with the last absolute path in paths.
Mimics os.path.join using the specified path_separator.
[ "Mimics", "os", ".", "path", ".", "join", "using", "the", "specified", "path_separator", "." ]
def JoinPaths(self, *paths): """Mimics os.path.join using the specified path_separator. Mimics os.path.join using the path_separator that was specified for this FakeFilesystem. Args: *paths: (str) Zero or more paths to join. Returns: (str) The paths joined by the path separator, starting with the last absolute path in paths. """ if len(paths) == 1: return paths[0] joined_path_segments = [] for path_segment in paths: if path_segment.startswith(self.path_separator): # An absolute path joined_path_segments = [path_segment] else: if (joined_path_segments and not joined_path_segments[-1].endswith(self.path_separator)): joined_path_segments.append(self.path_separator) if path_segment: joined_path_segments.append(path_segment) return ''.join(joined_path_segments)
[ "def", "JoinPaths", "(", "self", ",", "*", "paths", ")", ":", "if", "len", "(", "paths", ")", "==", "1", ":", "return", "paths", "[", "0", "]", "joined_path_segments", "=", "[", "]", "for", "path_segment", "in", "paths", ":", "if", "path_segment", "....
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/pyfakefs/pyfakefs/fake_filesystem.py#L510-L536
openthread/openthread
9fcdbed9c526c70f1556d1ed84099c1535c7cd32
tools/harness-thci/OpenThread_WpanCtl.py
python
OpenThread_WpanCtl.removeRouterPrefix
(self, prefixEntry)
remove the configured prefix on a border router Args: prefixEntry: a on-mesh prefix entry Returns: True: successful to remove the prefix entry from border router False: fail to remove the prefix entry from border router @todo: required if as reference device
remove the configured prefix on a border router
[ "remove", "the", "configured", "prefix", "on", "a", "border", "router" ]
def removeRouterPrefix(self, prefixEntry): """remove the configured prefix on a border router Args: prefixEntry: a on-mesh prefix entry Returns: True: successful to remove the prefix entry from border router False: fail to remove the prefix entry from border router @todo: required if as reference device """
[ "def", "removeRouterPrefix", "(", "self", ",", "prefixEntry", ")", ":" ]
https://github.com/openthread/openthread/blob/9fcdbed9c526c70f1556d1ed84099c1535c7cd32/tools/harness-thci/OpenThread_WpanCtl.py#L1564-L1575
microsoft/ivy
9f3c7ecc0b2383129fdd0953e10890d98d09a82d
ivy/ivy_cpp.py
python
CppType.instantiate
(self,name,initializer=None)
return '{} {};'.format(self.short_name(),name)
Returns a declaration for a symbol of this type
Returns a declaration for a symbol of this type
[ "Returns", "a", "declaration", "for", "a", "symbol", "of", "this", "type" ]
def instantiate(self,name,initializer=None): """ Returns a declaration for a symbol of this type """ if initializer: return '{} {}={};'.format(self.short_name(),name,initializer.get()) return '{} {};'.format(self.short_name(),name)
[ "def", "instantiate", "(", "self", ",", "name", ",", "initializer", "=", "None", ")", ":", "if", "initializer", ":", "return", "'{} {}={};'", ".", "format", "(", "self", ".", "short_name", "(", ")", ",", "name", ",", "initializer", ".", "get", "(", ")"...
https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/ivy_cpp.py#L149-L153
PaddlePaddle/PaddleOCR
b756bf5f8c90142e0d89d3db0163965c686b6ffe
ppocr/data/imaug/sast_process.py
python
SASTProcessTrain.shrink_poly_along_width
(self, quads, shrink_ratio_of_width, expand_height_ratio=1.0)
return np.array(out_quad_list), list(range(left_idx, right_idx + 1))
shrink poly with given length.
shrink poly with given length.
[ "shrink", "poly", "with", "given", "length", "." ]
def shrink_poly_along_width(self, quads, shrink_ratio_of_width, expand_height_ratio=1.0): """ shrink poly with given length. """ upper_edge_list = [] def get_cut_info(edge_len_list, cut_len): for idx, edge_len in enumerate(edge_len_list): cut_len -= edge_len if cut_len <= 0.000001: ratio = (cut_len + edge_len_list[idx]) / edge_len_list[idx] return idx, ratio for quad in quads: upper_edge_len = np.linalg.norm(quad[0] - quad[1]) upper_edge_list.append(upper_edge_len) # length of left edge and right edge. left_length = np.linalg.norm(quads[0][0] - quads[0][ 3]) * expand_height_ratio right_length = np.linalg.norm(quads[-1][1] - quads[-1][ 2]) * expand_height_ratio shrink_length = min(left_length, right_length, sum(upper_edge_list)) * shrink_ratio_of_width # shrinking length upper_len_left = shrink_length upper_len_right = sum(upper_edge_list) - shrink_length left_idx, left_ratio = get_cut_info(upper_edge_list, upper_len_left) left_quad = self.shrink_quad_along_width( quads[left_idx], begin_width_ratio=left_ratio, end_width_ratio=1) right_idx, right_ratio = get_cut_info(upper_edge_list, upper_len_right) right_quad = self.shrink_quad_along_width( quads[right_idx], begin_width_ratio=0, end_width_ratio=right_ratio) out_quad_list = [] if left_idx == right_idx: out_quad_list.append( [left_quad[0], right_quad[1], right_quad[2], left_quad[3]]) else: out_quad_list.append(left_quad) for idx in range(left_idx + 1, right_idx): out_quad_list.append(quads[idx]) out_quad_list.append(right_quad) return np.array(out_quad_list), list(range(left_idx, right_idx + 1))
[ "def", "shrink_poly_along_width", "(", "self", ",", "quads", ",", "shrink_ratio_of_width", ",", "expand_height_ratio", "=", "1.0", ")", ":", "upper_edge_list", "=", "[", "]", "def", "get_cut_info", "(", "edge_len_list", ",", "cut_len", ")", ":", "for", "idx", ...
https://github.com/PaddlePaddle/PaddleOCR/blob/b756bf5f8c90142e0d89d3db0163965c686b6ffe/ppocr/data/imaug/sast_process.py#L471-L520
KratosMultiphysics/Kratos
0000833054ed0503424eb28205d6508d9ca6cbbc
kratos/python_scripts/sympy_fe_utilities.py
python
DefineVector
( name, m)
return Matrix( m,1, lambda i,j: var(name+'_%d' % (i)) )
This method defines a symbolic vector Keyword arguments: name -- Name of variables. m -- Number of components.
This method defines a symbolic vector
[ "This", "method", "defines", "a", "symbolic", "vector" ]
def DefineVector( name, m): """ This method defines a symbolic vector Keyword arguments: name -- Name of variables. m -- Number of components. """ return Matrix( m,1, lambda i,j: var(name+'_%d' % (i)) )
[ "def", "DefineVector", "(", "name", ",", "m", ")", ":", "return", "Matrix", "(", "m", ",", "1", ",", "lambda", "i", ",", "j", ":", "var", "(", "name", "+", "'_%d'", "%", "(", "i", ")", ")", ")" ]
https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/kratos/python_scripts/sympy_fe_utilities.py#L30-L37
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/build/waf-1.7.13/lmbrwaflib/gems.py
python
load_gems_from_gem_spec
(ctx, gem_spec_file, add_to_manager=False)
return gems_list
Load gems from a specific gem-spec file. :param ctx: :param gem_spec_file: The path of the gem spec file to read :param add_to_manager: Option to add any missing gem that is discovered in the spec file but not in the manager :return: List of gems from the gem spec
Load gems from a specific gem-spec file. :param ctx: :param gem_spec_file: The path of the gem spec file to read :param add_to_manager: Option to add any missing gem that is discovered in the spec file but not in the manager :return: List of gems from the gem spec
[ "Load", "gems", "from", "a", "specific", "gem", "-", "spec", "file", ".", ":", "param", "ctx", ":", ":", "param", "gem_spec_file", ":", "The", "path", "of", "the", "gem", "spec", "file", "to", "read", ":", "param", "add_to_manager", ":", "Option", "to"...
def load_gems_from_gem_spec(ctx, gem_spec_file, add_to_manager=False): """ Load gems from a specific gem-spec file. :param ctx: :param gem_spec_file: The path of the gem spec file to read :param add_to_manager: Option to add any missing gem that is discovered in the spec file but not in the manager :return: List of gems from the gem spec """ if not gem_spec_file or not os.path.exists(gem_spec_file): raise Errors.WafError('Invalid empty gem_spec_file {}'.format(gem_spec_file or "")) # Read the gem spec file gem_info_list = utils.parse_json_file(gem_spec_file) list_reader = _create_field_reader(ctx, gem_info_list, 'Gems from {}'.format(gem_spec_file)) # Verify that the project file is an up-to-date format gem_format_version = list_reader.field_int('GemListFormatVersion') if gem_format_version != GEMS_FORMAT_VERSION: raise Errors.WafError('Gems list file at {} is of version {}, not expected version {}. Please update your project file.'.format(gem_spec_file, gem_format_version, GEMS_FORMAT_VERSION)) manager = GemManager.GetInstance(ctx) gems_list = list() for idx, gem_info_obj in enumerate(list_reader.field_req('Gems')): # String for error reporting. gem_context_msg = 'Gem {} from gems spec {}'.format(idx, gem_spec_file) reader = _create_field_reader(ctx, gem_info_obj, gem_context_msg) gem_id = reader.uuid() version = reader.version() path = os.path.normpath(reader.field_req('Path')) gem = manager.get_gem_by_spec(gem_id, version, path) if not gem: if add_to_manager: gems_list_context_msg = 'Gems list {}'.format(gem_spec_file) manager.load_gem_from_disk(gem_id, version, path, gems_list_context_msg) else: raise Errors.WafError('Invalid gem {}'.format(gem_id)) gems_list.append(gem) return gems_list
[ "def", "load_gems_from_gem_spec", "(", "ctx", ",", "gem_spec_file", ",", "add_to_manager", "=", "False", ")", ":", "if", "not", "gem_spec_file", "or", "not", "os", ".", "path", ".", "exists", "(", "gem_spec_file", ")", ":", "raise", "Errors", ".", "WafError"...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/lmbrwaflib/gems.py#L1276-L1321
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/common/tensor.py
python
Tensor.argmax
(self, axis=None)
return tensor_operator_registry.get('argmax')(axis)(a)
Return the indices of the maximum values along an axis. Args: axis (int, optional): By default, the index is into the flattened tensor, otherwise along the specified axis. Default: None. Returns: Tensor, indices into the input tensor. It has the same shape as self.shape with the dimension along axis removed. Raises: ValueError: If the axis is out of range. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` See also: :func:`mindspore.Tensor.argmin`: Return the indices of the minimum values along an axis. :func:`mindspore.Tensor.min`: Return the minimum of a tensor or minimum along an axis. :func:`mindspore.Tensor.max`: Return the maximum of a tensor or maximum along an axis. Examples: >>> import numpy as np >>> from mindspore import Tensor >>> a = Tensor(np.arange(10, 16).reshape(2, 3).astype("float32")) >>> print(a.argmax()) 5
Return the indices of the maximum values along an axis.
[ "Return", "the", "indices", "of", "the", "maximum", "values", "along", "an", "axis", "." ]
def argmax(self, axis=None): """ Return the indices of the maximum values along an axis. Args: axis (int, optional): By default, the index is into the flattened tensor, otherwise along the specified axis. Default: None. Returns: Tensor, indices into the input tensor. It has the same shape as self.shape with the dimension along axis removed. Raises: ValueError: If the axis is out of range. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` See also: :func:`mindspore.Tensor.argmin`: Return the indices of the minimum values along an axis. :func:`mindspore.Tensor.min`: Return the minimum of a tensor or minimum along an axis. :func:`mindspore.Tensor.max`: Return the maximum of a tensor or maximum along an axis. Examples: >>> import numpy as np >>> from mindspore import Tensor >>> a = Tensor(np.arange(10, 16).reshape(2, 3).astype("float32")) >>> print(a.argmax()) 5 """ # P.Argmax only supports float a = self.astype(mstype.float32) if axis is None: a = a.ravel() axis = 0 else: axis = validator.check_axis_in_range(axis, a.ndim) return tensor_operator_registry.get('argmax')(axis)(a)
[ "def", "argmax", "(", "self", ",", "axis", "=", "None", ")", ":", "# P.Argmax only supports float", "a", "=", "self", ".", "astype", "(", "mstype", ".", "float32", ")", "if", "axis", "is", "None", ":", "a", "=", "a", ".", "ravel", "(", ")", "axis", ...
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/common/tensor.py#L1029-L1068
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/mailbox.py
python
Babyl.__init__
(self, path, factory=None, create=True)
Initialize a Babyl mailbox.
Initialize a Babyl mailbox.
[ "Initialize", "a", "Babyl", "mailbox", "." ]
def __init__(self, path, factory=None, create=True): """Initialize a Babyl mailbox.""" _singlefileMailbox.__init__(self, path, factory, create) self._labels = {}
[ "def", "__init__", "(", "self", ",", "path", ",", "factory", "=", "None", ",", "create", "=", "True", ")", ":", "_singlefileMailbox", ".", "__init__", "(", "self", ",", "path", ",", "factory", ",", "create", ")", "self", ".", "_labels", "=", "{", "}"...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/mailbox.py#L1234-L1237
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
deps/src/libxml2-2.9.1/python/libxml2class.py
python
inputBuffer.grow
(self, len)
return ret
Grow up the content of the input buffer, the old data are preserved This routine handle the I18N transcoding to internal UTF-8 This routine is used when operating the parser in normal (pull) mode TODO: one should be able to remove one extra copy by copying directly onto in->buffer or in->raw
Grow up the content of the input buffer, the old data are preserved This routine handle the I18N transcoding to internal UTF-8 This routine is used when operating the parser in normal (pull) mode TODO: one should be able to remove one extra copy by copying directly onto in->buffer or in->raw
[ "Grow", "up", "the", "content", "of", "the", "input", "buffer", "the", "old", "data", "are", "preserved", "This", "routine", "handle", "the", "I18N", "transcoding", "to", "internal", "UTF", "-", "8", "This", "routine", "is", "used", "when", "operating", "t...
def grow(self, len): """Grow up the content of the input buffer, the old data are preserved This routine handle the I18N transcoding to internal UTF-8 This routine is used when operating the parser in normal (pull) mode TODO: one should be able to remove one extra copy by copying directly onto in->buffer or in->raw """ ret = libxml2mod.xmlParserInputBufferGrow(self._o, len) return ret
[ "def", "grow", "(", "self", ",", "len", ")", ":", "ret", "=", "libxml2mod", ".", "xmlParserInputBufferGrow", "(", "self", ".", "_o", ",", "len", ")", "return", "ret" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2class.py#L5352-L5360
Cantera/cantera
0119484b261967ccb55a0066c020599cacc312e4
interfaces/cython/cantera/composite.py
python
SolutionArray.write_hdf
(self, filename, *args, cols=None, group=None, subgroup=None, attrs={}, mode='a', append=False, compression=None, compression_opts=None, **kwargs)
return group
Write data specified by *cols* to a HDF container file named *filename*. Note that it is possible to write multiple data entries to a single HDF container file, where *group* is used to differentiate data. An example for the default HDF file structure is::: / Group /group0 Group /group0/some_attr Attribute ... /group0/T Dataset ... /group0/phase Group /group0/phase/name Attribute /group0/phase/source Attribute where ``group0`` is the default name for the top level HDF entry. In addition to datasets, information stored in `SolutionArray.meta` is saved in form of HDF attributes. An additional intermediate layer may be created using the *subgroup* argument. :param filename: Name of the HDF container file; typical file extensions are ``.hdf``, ``.hdf5`` or ``.h5``. :param cols: A list of any properties of the solution being exported. :param group: Identifier for the group in the container file. If no subgroup is specified, a group represents a `SolutionArray`. If 'None', group names default to 'groupN', with N being the number of pre-existing groups within the HDF container file. :param subgroup: Name identifier for an optional subgroup, with subgroups representing individual `SolutionArray` objects. If 'None', no subgroup is created. :param attrs: Dictionary of user-defined attributes added at the group level (typically used in conjunction with a subgroup argument). :param mode: Mode h5py uses to open the output file {'a' to read/write if file exists, create otherwise (default); 'w' to create file, truncate if exists; 'r+' to read/write, file must exist}. :param append: If False, the content of a pre-existing group is deleted before writing the `SolutionArray` in the first position. If True, the current `SolutionArray` objects is appended to the group. :param compression: Pre-defined h5py compression filters {None, 'gzip', 'lzf', 'szip'} used for data compression. :param compression_opts: Options for the h5py compression filter; for 'gzip', this corresponds to the compression level {None, 0-9}. :return: Group identifier used for storing HDF data. Arguments *compression*, and *compression_opts* are mapped to parameters for `h5py.create_dataset`; in both cases, the choices of `None` results in default values set by h5py. Additional arguments (i.e. *args* and *kwargs*) are passed on to `collect_data`; see `collect_data` for further information. This method requires a working installation of h5py (`h5py` can be installed using pip or conda).
Write data specified by *cols* to a HDF container file named *filename*. Note that it is possible to write multiple data entries to a single HDF container file, where *group* is used to differentiate data.
[ "Write", "data", "specified", "by", "*", "cols", "*", "to", "a", "HDF", "container", "file", "named", "*", "filename", "*", ".", "Note", "that", "it", "is", "possible", "to", "write", "multiple", "data", "entries", "to", "a", "single", "HDF", "container"...
def write_hdf(self, filename, *args, cols=None, group=None, subgroup=None, attrs={}, mode='a', append=False, compression=None, compression_opts=None, **kwargs): """ Write data specified by *cols* to a HDF container file named *filename*. Note that it is possible to write multiple data entries to a single HDF container file, where *group* is used to differentiate data. An example for the default HDF file structure is::: / Group /group0 Group /group0/some_attr Attribute ... /group0/T Dataset ... /group0/phase Group /group0/phase/name Attribute /group0/phase/source Attribute where ``group0`` is the default name for the top level HDF entry. In addition to datasets, information stored in `SolutionArray.meta` is saved in form of HDF attributes. An additional intermediate layer may be created using the *subgroup* argument. :param filename: Name of the HDF container file; typical file extensions are ``.hdf``, ``.hdf5`` or ``.h5``. :param cols: A list of any properties of the solution being exported. :param group: Identifier for the group in the container file. If no subgroup is specified, a group represents a `SolutionArray`. If 'None', group names default to 'groupN', with N being the number of pre-existing groups within the HDF container file. :param subgroup: Name identifier for an optional subgroup, with subgroups representing individual `SolutionArray` objects. If 'None', no subgroup is created. :param attrs: Dictionary of user-defined attributes added at the group level (typically used in conjunction with a subgroup argument). :param mode: Mode h5py uses to open the output file {'a' to read/write if file exists, create otherwise (default); 'w' to create file, truncate if exists; 'r+' to read/write, file must exist}. :param append: If False, the content of a pre-existing group is deleted before writing the `SolutionArray` in the first position. If True, the current `SolutionArray` objects is appended to the group. :param compression: Pre-defined h5py compression filters {None, 'gzip', 'lzf', 'szip'} used for data compression. :param compression_opts: Options for the h5py compression filter; for 'gzip', this corresponds to the compression level {None, 0-9}. :return: Group identifier used for storing HDF data. Arguments *compression*, and *compression_opts* are mapped to parameters for `h5py.create_dataset`; in both cases, the choices of `None` results in default values set by h5py. Additional arguments (i.e. *args* and *kwargs*) are passed on to `collect_data`; see `collect_data` for further information. This method requires a working installation of h5py (`h5py` can be installed using pip or conda). """ if isinstance(_h5py, ImportError): raise _h5py # collect data data = self.collect_data(*args, cols=cols, **kwargs) hdf_kwargs = {'compression': compression, 'compression_opts': compression_opts} hdf_kwargs = {k: v for k, v in hdf_kwargs.items() if v is not None} # save to container file with _h5py.File(filename, mode) as hdf: # check existence of tagged item if not group: # add group with default name group = 'group{}'.format(len(hdf.keys())) root = hdf.create_group(group) elif group not in hdf.keys(): # add group with custom name root = hdf.create_group(group) elif append and subgroup is not None: # add subgroup to existing subgroup(s) root = hdf[group] else: # reset data in existing group root = hdf[group] for sub in root.keys(): del root[sub] # save attributes for attr, value in attrs.items(): root.attrs[attr] = value # add subgroup if specified if subgroup is not None: dgroup = root.create_group(subgroup) else: dgroup = root # add subgroup containing information on gas sol = dgroup.create_group('phase') sol.attrs['name'] = self.name sol.attrs['source'] = self.source # store SolutionArray data for key, val in self._meta.items(): dgroup.attrs[key] = val for header, value in data.items(): if value.dtype.type == np.str_: dgroup.create_dataset(header, data=value.astype('S'), **hdf_kwargs) else: dgroup.create_dataset(header, data=value, **hdf_kwargs) return group
[ "def", "write_hdf", "(", "self", ",", "filename", ",", "*", "args", ",", "cols", "=", "None", ",", "group", "=", "None", ",", "subgroup", "=", "None", ",", "attrs", "=", "{", "}", ",", "mode", "=", "'a'", ",", "append", "=", "False", ",", "compre...
https://github.com/Cantera/cantera/blob/0119484b261967ccb55a0066c020599cacc312e4/interfaces/cython/cantera/composite.py#L1170-L1293
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/dummy_thread.py
python
LockType.acquire
(self, waitflag=None)
Dummy implementation of acquire(). For blocking calls, self.locked_status is automatically set to True and returned appropriately based on value of ``waitflag``. If it is non-blocking, then the value is actually checked and not set if it is already acquired. This is all done so that threading.Condition's assert statements aren't triggered and throw a little fit.
Dummy implementation of acquire().
[ "Dummy", "implementation", "of", "acquire", "()", "." ]
def acquire(self, waitflag=None): """Dummy implementation of acquire(). For blocking calls, self.locked_status is automatically set to True and returned appropriately based on value of ``waitflag``. If it is non-blocking, then the value is actually checked and not set if it is already acquired. This is all done so that threading.Condition's assert statements aren't triggered and throw a little fit. """ if waitflag is None or waitflag: self.locked_status = True return True else: if not self.locked_status: self.locked_status = True return True else: return False
[ "def", "acquire", "(", "self", ",", "waitflag", "=", "None", ")", ":", "if", "waitflag", "is", "None", "or", "waitflag", ":", "self", ".", "locked_status", "=", "True", "return", "True", "else", ":", "if", "not", "self", ".", "locked_status", ":", "sel...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/dummy_thread.py#L95-L114
zerollzeng/tiny-tensorrt
e7bdb8f82934342a0f22ce68dfefdb8e15eb72b2
third_party/pybind11/tools/clang/cindex.py
python
TranslationUnit.reparse
(self, unsaved_files=None, options=0)
Reparse an already parsed translation unit. In-memory contents for files can be provided by passing a list of pairs as unsaved_files, the first items should be the filenames to be mapped and the second should be the contents to be substituted for the file. The contents may be passed as strings or file objects.
Reparse an already parsed translation unit.
[ "Reparse", "an", "already", "parsed", "translation", "unit", "." ]
def reparse(self, unsaved_files=None, options=0): """ Reparse an already parsed translation unit. In-memory contents for files can be provided by passing a list of pairs as unsaved_files, the first items should be the filenames to be mapped and the second should be the contents to be substituted for the file. The contents may be passed as strings or file objects. """ if unsaved_files is None: unsaved_files = [] unsaved_files_array = 0 if len(unsaved_files): unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))() for i,(name,value) in enumerate(unsaved_files): if not isinstance(value, str): # FIXME: It would be great to support an efficient version # of this, one day. value = value.read() print(value) if not isinstance(value, str): raise TypeError('Unexpected unsaved file contents.') unsaved_files_array[i].name = name unsaved_files_array[i].contents = value unsaved_files_array[i].length = len(value) ptr = conf.lib.clang_reparseTranslationUnit(self, len(unsaved_files), unsaved_files_array, options)
[ "def", "reparse", "(", "self", ",", "unsaved_files", "=", "None", ",", "options", "=", "0", ")", ":", "if", "unsaved_files", "is", "None", ":", "unsaved_files", "=", "[", "]", "unsaved_files_array", "=", "0", "if", "len", "(", "unsaved_files", ")", ":", ...
https://github.com/zerollzeng/tiny-tensorrt/blob/e7bdb8f82934342a0f22ce68dfefdb8e15eb72b2/third_party/pybind11/tools/clang/cindex.py#L2686-L2713
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Source/ThirdParty/CEF3/cef_source/tools/cef_parser.py
python
obj_argument.get_types
(self, list)
Return a dictionary mapping data types to analyzed values.
Return a dictionary mapping data types to analyzed values.
[ "Return", "a", "dictionary", "mapping", "data", "types", "to", "analyzed", "values", "." ]
def get_types(self, list): """ Return a dictionary mapping data types to analyzed values. """ name = self.type.get_type() if not name in list: list[name] = self.type
[ "def", "get_types", "(", "self", ",", "list", ")", ":", "name", "=", "self", ".", "type", ".", "get_type", "(", ")", "if", "not", "name", "in", "list", ":", "list", "[", "name", "]", "=", "self", ".", "type" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Source/ThirdParty/CEF3/cef_source/tools/cef_parser.py#L1327-L1331
RegrowthStudios/SoACode-Public
c3ddd69355b534d5e70e2e6d0c489b4e93ab1ffe
utils/git-hooks/pep8.py
python
explicit_line_join
(logical_line, tokens)
r""" Avoid explicit line join between brackets. The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation. E502: aaa = [123, \\n 123] E502: aaa = ("bbb " \\n "ccc") Okay: aaa = [123,\n 123] Okay: aaa = ("bbb "\n "ccc") Okay: aaa = "bbb " \\n "ccc"
r""" Avoid explicit line join between brackets.
[ "r", "Avoid", "explicit", "line", "join", "between", "brackets", "." ]
def explicit_line_join(logical_line, tokens): r""" Avoid explicit line join between brackets. The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation. E502: aaa = [123, \\n 123] E502: aaa = ("bbb " \\n "ccc") Okay: aaa = [123,\n 123] Okay: aaa = ("bbb "\n "ccc") Okay: aaa = "bbb " \\n "ccc" """ prev_start = prev_end = parens = 0 for token_type, text, start, end, line in tokens: if start[0] != prev_start and parens and backslash: yield backslash, "E502 the backslash is redundant between brackets" if end[0] != prev_end: if line.rstrip('\r\n').endswith('\\'): backslash = (end[0], len(line.splitlines()[-1]) - 1) else: backslash = None prev_start = prev_end = end[0] else: prev_start = start[0] if token_type == tokenize.OP: if text in '([{': parens += 1 elif text in ')]}': parens -= 1
[ "def", "explicit_line_join", "(", "logical_line", ",", "tokens", ")", ":", "prev_start", "=", "prev_end", "=", "parens", "=", "0", "for", "token_type", ",", "text", ",", "start", ",", "end", ",", "line", "in", "tokens", ":", "if", "start", "[", "0", "]...
https://github.com/RegrowthStudios/SoACode-Public/blob/c3ddd69355b534d5e70e2e6d0c489b4e93ab1ffe/utils/git-hooks/pep8.py#L866-L898
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/dataview.py
python
DataViewCtrl.GetItemRect
(*args, **kwargs)
return _dataview.DataViewCtrl_GetItemRect(*args, **kwargs)
GetItemRect(self, DataViewItem item, DataViewColumn column=None) -> Rect
GetItemRect(self, DataViewItem item, DataViewColumn column=None) -> Rect
[ "GetItemRect", "(", "self", "DataViewItem", "item", "DataViewColumn", "column", "=", "None", ")", "-", ">", "Rect" ]
def GetItemRect(*args, **kwargs): """GetItemRect(self, DataViewItem item, DataViewColumn column=None) -> Rect""" return _dataview.DataViewCtrl_GetItemRect(*args, **kwargs)
[ "def", "GetItemRect", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_dataview", ".", "DataViewCtrl_GetItemRect", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/dataview.py#L1824-L1826
CNugteren/CLBlast
4500a03440e2cc54998c0edab366babf5e504d67
scripts/generator/generator/routine.py
python
Routine.options_def_wrapper_cblas
(self)
return []
As above, but now using CBLAS data-types
As above, but now using CBLAS data-types
[ "As", "above", "but", "now", "using", "CBLAS", "data", "-", "types" ]
def options_def_wrapper_cblas(self): """As above, but now using CBLAS data-types""" if self.options: definitions = ["const " + convert.option_to_cblas(o) + " " + o for o in self.options] return [", ".join(definitions)] return []
[ "def", "options_def_wrapper_cblas", "(", "self", ")", ":", "if", "self", ".", "options", ":", "definitions", "=", "[", "\"const \"", "+", "convert", ".", "option_to_cblas", "(", "o", ")", "+", "\" \"", "+", "o", "for", "o", "in", "self", ".", "options", ...
https://github.com/CNugteren/CLBlast/blob/4500a03440e2cc54998c0edab366babf5e504d67/scripts/generator/generator/routine.py#L612-L617
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/external/coremltools_wrap/coremltools/coremltools/converters/mil/frontend/tensorflow/converter.py
python
TFConverter.__init__
(self, tfssa, inputs=None, outputs=None, **kwargs)
tfssa: TensorFlow IR. inputs: list of TensorType or ImageType, optional, defaults to None. outputs: list of str or str, optional, defaults to None. A list of names of the output nodes or a str for single output name. If None, the converter will try to extract the output information from TensorFlow model.
tfssa: TensorFlow IR. inputs: list of TensorType or ImageType, optional, defaults to None. outputs: list of str or str, optional, defaults to None. A list of names of the output nodes or a str for single output name. If None, the converter will try to extract the output information from TensorFlow model.
[ "tfssa", ":", "TensorFlow", "IR", ".", "inputs", ":", "list", "of", "TensorType", "or", "ImageType", "optional", "defaults", "to", "None", ".", "outputs", ":", "list", "of", "str", "or", "str", "optional", "defaults", "to", "None", ".", "A", "list", "of"...
def __init__(self, tfssa, inputs=None, outputs=None, **kwargs): """ tfssa: TensorFlow IR. inputs: list of TensorType or ImageType, optional, defaults to None. outputs: list of str or str, optional, defaults to None. A list of names of the output nodes or a str for single output name. If None, the converter will try to extract the output information from TensorFlow model. """ self.tfssa = tfssa self.global_type = {} self.inputs = None main_func = tfssa.functions["main"] graph = main_func.graph # Filter the inputs to only Placeholder names tf_placeholder_names = [n for n in graph if graph[n].op == "Placeholder"] placeholder_names = [] if inputs is not None: # Check inputs format if not isinstance(inputs, (list, tuple)): raise ValueError( "Type of inputs should be list or tuple, got {} instead.".format( type(inputs) ) ) if not all([isinstance(i, InputType) for i in inputs]): raise ValueError( "Type of inputs should be list or tuple of TensorType or ImageType, got {} instead.".format( [type(i) for i in inputs] ) ) # Special case: if there's only 1 input and 1 placeholder, we match them. if len(tf_placeholder_names) == 1 and len(inputs) == 1: if inputs[0].name is None: inputs[0].name = tf_placeholder_names[0] # filter out those inputs which is not in tf_placeholder_names inputs = [x for x in inputs if x.name in tf_placeholder_names] # We fill in shapes for user-specified input that doesn't have shape for inp in inputs: # Check inputs existence if inp.name is None: raise ValueError( "Unable to infer input's name or input name was not provided" ) if inp.name not in tf_placeholder_names: raise ValueError( "Input ({}) provided is not found in given tensorflow graph. Placeholders in graph are: {}".format( inp.name, tf_placeholder_names ) ) if inp.shape is None: if graph[inp.name].attr.get("_output_shapes", None) is not None: shape = graph[inp.name].attr["_output_shapes"][0] if shape is None: # Scalar is given as None shape = [] elif graph[inp.name].attr.get("shape", None) is not None: shape = graph[inp.name].attr["shape"] else: raise ValueError( "Can't extract shape from attribute of ({})".format( inp.name ) ) inp.shape = _get_shaping_class(shape) # Extract placeholders that users didn't specify. user_input_names = [inp.name for inp in inputs] for name in tf_placeholder_names: if name not in user_input_names: placeholder_names.append(name) else: inputs = [] placeholder_names = tf_placeholder_names placeholder_inputs = {} for inp in main_func.inputs: if inp not in placeholder_names: continue if graph[inp].attr.get("_output_shapes", None) is not None: placeholder_inputs.update({inp: graph[inp].attr["_output_shapes"][0]}) elif graph[inp].attr.get("shape", None) is not None: placeholder_inputs.update({inp: graph[inp].attr["shape"]}) else: raise ValueError("Can't find input shape for ({})".format(inp)) if len(placeholder_inputs) > 0: logging.info( "Adding Input not specified by users: '{}'".format(placeholder_inputs) ) for k, v in placeholder_inputs.items(): inputs.append(TensorType(name=k, shape=v)) for idx, inp in enumerate(inputs): # We set the default image format in TF as NHWC, since NHWC is used # for TF unless GPU is specified as device. if isinstance(inp, ImageType) and inputs[idx].channel_first is None: inputs[idx].channel_first = False self.inputs = tuple(inputs) for inputtype in self.inputs: if not isinstance(inputtype.shape, InputShape): continue if any([isinstance(s, RangeDim) for s in inputtype.shape.shape]): continue node = graph[inputtype.name] shape = [-1 if is_symbolic(s) else s for s in inputtype.shape.shape] node.attr["_output_shapes"] = [shape] # list of length 1 # infer outputs if not provided self._validate_outputs(tfssa, outputs) outputs = main_func.outputs if outputs is None else outputs outputs = outputs if isinstance(outputs, (tuple, list)) else [outputs] outputs = [x if isinstance(x, six.string_types) else x.name for x in outputs] self.outputs = outputs # We would like a stack so that we run conversion sequentially. self.graph_stack = self._get_stack(tfssa, root="main") self.context = TranscriptionContext() self.tensorflow_passes = tensorflow_passes
[ "def", "__init__", "(", "self", ",", "tfssa", ",", "inputs", "=", "None", ",", "outputs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "tfssa", "=", "tfssa", "self", ".", "global_type", "=", "{", "}", "self", ".", "inputs", "=", "...
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/coremltools/converters/mil/frontend/tensorflow/converter.py#L120-L244
KratosMultiphysics/Kratos
0000833054ed0503424eb28205d6508d9ca6cbbc
applications/WindEngineeringApplication/python_scripts/compute_level_force_process.py
python
ComputeLevelForceProcess.__init__
(self, model: KratosMultiphysics.Model, parameters: KratosMultiphysics.Parameters)
Reduce nodal reaction forces and torques on stacked slab domains. A region of space between 'bottom_point' and 'top_point' is subdivided into 'number_of_slabs' parallel slabs. Then, nodes from the specified model part are sorted into sub model parts based on which slab they are located in. Finally, for each sub model part, the reaction forces are summed up, and their torque (plus MOMENT if applicable) is reduced to 'moment_reference_point'. The reduced values are written to output files for each sub model part. Default parameters: { "model_part_name" : "", "moment_reference_point" : [0.0, 0.0, 0.0], "bottom_point" : [0.0, 0.0, 0.0], "top_point" : [0.0, 0.0, 0.0], "number_of_slabs" : 1, "open_domain" : false, "time_domain" : [0.0, 1e100], "output_name_stub" : "slab_" }
Reduce nodal reaction forces and torques on stacked slab domains. A region of space between 'bottom_point' and 'top_point' is subdivided into 'number_of_slabs' parallel slabs. Then, nodes from the specified model part are sorted into sub model parts based on which slab they are located in. Finally, for each sub model part, the reaction forces are summed up, and their torque (plus MOMENT if applicable) is reduced to 'moment_reference_point'. The reduced values are written to output files for each sub model part. Default parameters: { "model_part_name" : "", "moment_reference_point" : [0.0, 0.0, 0.0], "bottom_point" : [0.0, 0.0, 0.0], "top_point" : [0.0, 0.0, 0.0], "number_of_slabs" : 1, "open_domain" : false, "time_domain" : [0.0, 1e100], "output_name_stub" : "slab_" }
[ "Reduce", "nodal", "reaction", "forces", "and", "torques", "on", "stacked", "slab", "domains", ".", "A", "region", "of", "space", "between", "bottom_point", "and", "top_point", "is", "subdivided", "into", "number_of_slabs", "parallel", "slabs", ".", "Then", "nod...
def __init__(self, model: KratosMultiphysics.Model, parameters: KratosMultiphysics.Parameters): """Reduce nodal reaction forces and torques on stacked slab domains. A region of space between 'bottom_point' and 'top_point' is subdivided into 'number_of_slabs' parallel slabs. Then, nodes from the specified model part are sorted into sub model parts based on which slab they are located in. Finally, for each sub model part, the reaction forces are summed up, and their torque (plus MOMENT if applicable) is reduced to 'moment_reference_point'. The reduced values are written to output files for each sub model part. Default parameters: { "model_part_name" : "", "moment_reference_point" : [0.0, 0.0, 0.0], "bottom_point" : [0.0, 0.0, 0.0], "top_point" : [0.0, 0.0, 0.0], "number_of_slabs" : 1, "open_domain" : false, "time_domain" : [0.0, 1e100], "output_name_stub" : "slab_" }""" KratosMultiphysics.Process.__init__(self) self.model_part = model[parameters["model_part_name"].GetString()] parameters.ValidateAndAssignDefaults(self.GetDefaultParameters()) self.moment_reference_point = parameters["moment_reference_point"].GetVector() self.bottom_point = parameters["bottom_point"].GetVector() self.top_point = parameters["top_point"].GetVector() self.time_domain = parameters["time_domain"].GetVector() self.number_of_slabs = parameters["number_of_slabs"].GetInt() self.is_open_domain = parameters["open_domain"].GetBool() self.output_name_stub = pathlib.Path(parameters["output_name_stub"].GetString())
[ "def", "__init__", "(", "self", ",", "model", ":", "KratosMultiphysics", ".", "Model", ",", "parameters", ":", "KratosMultiphysics", ".", "Parameters", ")", ":", "KratosMultiphysics", ".", "Process", ".", "__init__", "(", "self", ")", "self", ".", "model_part"...
https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/WindEngineeringApplication/python_scripts/compute_level_force_process.py#L17-L46
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
PhysicsTools/HeppyCore/python/utils/dataset.py
python
Dataset.extractFileSizes
(self)
Get the file size for each file, from the eos ls -l command.
Get the file size for each file, from the eos ls -l command.
[ "Get", "the", "file", "size", "for", "each", "file", "from", "the", "eos", "ls", "-", "l", "command", "." ]
def extractFileSizes(self): '''Get the file size for each file, from the eos ls -l command.''' # EOS command does not work in tier3 lsout = castortools.runXRDCommand(self.castorDir,'dirlist')[0] lsout = lsout.split('\n') self.filesAndSizes = {} for entry in lsout: values = entry.split() if( len(values) != 5): continue # using full abs path as a key. file = '/'.join([self.lfnDir, values[4].split("/")[-1]]) size = values[1] self.filesAndSizes[file] = size
[ "def", "extractFileSizes", "(", "self", ")", ":", "# EOS command does not work in tier3", "lsout", "=", "castortools", ".", "runXRDCommand", "(", "self", ".", "castorDir", ",", "'dirlist'", ")", "[", "0", "]", "lsout", "=", "lsout", ".", "split", "(", "'\\n'",...
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/PhysicsTools/HeppyCore/python/utils/dataset.py#L309-L322
trailofbits/llvm-sanitizer-tutorial
d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99
llvm/tools/clang/tools/scan-view/share/ScanView.py
python
ScanViewRequestHandler.do_POST
(self)
Serve a POST request.
Serve a POST request.
[ "Serve", "a", "POST", "request", "." ]
def do_POST(self): """Serve a POST request.""" try: length = self.headers.getheader('content-length') or "0" try: length = int(length) except: length = 0 content = self.rfile.read(length) fields = parse_query(content) f = self.send_head(fields) if f: self.copyfile(f, self.wfile) f.close() except Exception as e: self.handle_exception(e)
[ "def", "do_POST", "(", "self", ")", ":", "try", ":", "length", "=", "self", ".", "headers", ".", "getheader", "(", "'content-length'", ")", "or", "\"0\"", "try", ":", "length", "=", "int", "(", "length", ")", "except", ":", "length", "=", "0", "conte...
https://github.com/trailofbits/llvm-sanitizer-tutorial/blob/d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99/llvm/tools/clang/tools/scan-view/share/ScanView.py#L236-L251
kushview/Element
1cc16380caa2ab79461246ba758b9de1f46db2a5
waflib/Build.py
python
inst.get_install_path
(self, destdir=True)
return dest
Returns the destination path where files will be installed, pre-pending `destdir`. Relative paths will be interpreted relative to `PREFIX` if no `destdir` is given. :rtype: string
Returns the destination path where files will be installed, pre-pending `destdir`.
[ "Returns", "the", "destination", "path", "where", "files", "will", "be", "installed", "pre", "-", "pending", "destdir", "." ]
def get_install_path(self, destdir=True): """ Returns the destination path where files will be installed, pre-pending `destdir`. Relative paths will be interpreted relative to `PREFIX` if no `destdir` is given. :rtype: string """ if isinstance(self.install_to, Node.Node): dest = self.install_to.abspath() else: dest = os.path.normpath(Utils.subst_vars(self.install_to, self.env)) if not os.path.isabs(dest): dest = os.path.join(self.env.PREFIX, dest) if destdir and Options.options.destdir: dest = Options.options.destdir.rstrip(os.sep) + os.sep + os.path.splitdrive(dest)[1].lstrip(os.sep) return dest
[ "def", "get_install_path", "(", "self", ",", "destdir", "=", "True", ")", ":", "if", "isinstance", "(", "self", ".", "install_to", ",", "Node", ".", "Node", ")", ":", "dest", "=", "self", ".", "install_to", ".", "abspath", "(", ")", "else", ":", "des...
https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/Build.py#L1056-L1072
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/multiprocessing/connection.py
python
_ConnectionBase.close
(self)
Close the connection
Close the connection
[ "Close", "the", "connection" ]
def close(self): """Close the connection""" if self._handle is not None: try: self._close() finally: self._handle = None
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_handle", "is", "not", "None", ":", "try", ":", "self", ".", "_close", "(", ")", "finally", ":", "self", ".", "_handle", "=", "None" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/multiprocessing/connection.py#L173-L179
macchina-io/macchina.io
ef24ba0e18379c3dd48fb84e6dbf991101cb8db0
platform/JS/V8/tools/gyp/pylib/gyp/msvs_emulation.py
python
MsvsSettings._ConfigAttrib
(self, path, config, default=None, prefix='', append=None, map=None)
return self._GetAndMunge( self.msvs_configuration_attributes[config], path, default, prefix, append, map)
_GetAndMunge for msvs_configuration_attributes.
_GetAndMunge for msvs_configuration_attributes.
[ "_GetAndMunge", "for", "msvs_configuration_attributes", "." ]
def _ConfigAttrib(self, path, config, default=None, prefix='', append=None, map=None): """_GetAndMunge for msvs_configuration_attributes.""" return self._GetAndMunge( self.msvs_configuration_attributes[config], path, default, prefix, append, map)
[ "def", "_ConfigAttrib", "(", "self", ",", "path", ",", "config", ",", "default", "=", "None", ",", "prefix", "=", "''", ",", "append", "=", "None", ",", "map", "=", "None", ")", ":", "return", "self", ".", "_GetAndMunge", "(", "self", ".", "msvs_conf...
https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/tools/gyp/pylib/gyp/msvs_emulation.py#L333-L338
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/base.py
python
BaseContext.active_code_library
(self)
return self._codelib_stack[-1]
Get the active code library
Get the active code library
[ "Get", "the", "active", "code", "library" ]
def active_code_library(self): """Get the active code library """ return self._codelib_stack[-1]
[ "def", "active_code_library", "(", "self", ")", ":", "return", "self", ".", "_codelib_stack", "[", "-", "1", "]" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/base.py#L1109-L1112
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8/tools/stats-viewer.py
python
Counter.Value
(self)
return self.data.IntAt(self.offset)
Return the integer value of this counter.
Return the integer value of this counter.
[ "Return", "the", "integer", "value", "of", "this", "counter", "." ]
def Value(self): """Return the integer value of this counter.""" return self.data.IntAt(self.offset)
[ "def", "Value", "(", "self", ")", ":", "return", "self", ".", "data", ".", "IntAt", "(", "self", ".", "offset", ")" ]
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8/tools/stats-viewer.py#L340-L342
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
python/mxnet/gluon/block.py
python
Block.save_params
(self, filename)
Save parameters to file. filename : str Path to file.
Save parameters to file.
[ "Save", "parameters", "to", "file", "." ]
def save_params(self, filename): """Save parameters to file. filename : str Path to file. """ self.collect_params().save(filename, strip_prefix=self.prefix)
[ "def", "save_params", "(", "self", ",", "filename", ")", ":", "self", ".", "collect_params", "(", ")", ".", "save", "(", "filename", ",", "strip_prefix", "=", "self", ".", "prefix", ")" ]
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/gluon/block.py#L239-L245
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
python/mxnet/gluon/block.py
python
Block.register_child
(self, block)
Registers block as a child of self. :py:class:`Block` s assigned to self as attributes will be registered automatically.
Registers block as a child of self. :py:class:`Block` s assigned to self as attributes will be registered automatically.
[ "Registers", "block", "as", "a", "child", "of", "self", ".", ":", "py", ":", "class", ":", "Block", "s", "assigned", "to", "self", "as", "attributes", "will", "be", "registered", "automatically", "." ]
def register_child(self, block): """Registers block as a child of self. :py:class:`Block` s assigned to self as attributes will be registered automatically.""" self._children.append(block)
[ "def", "register_child", "(", "self", ",", "block", ")", ":", "self", ".", "_children", ".", "append", "(", "block", ")" ]
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/gluon/block.py#L265-L268
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/media/webrtc/trunk/tools/gyp/pylib/gyp/sun_tool.py
python
SunTool.Dispatch
(self, args)
Dispatches a string command to a method.
Dispatches a string command to a method.
[ "Dispatches", "a", "string", "command", "to", "a", "method", "." ]
def Dispatch(self, args): """Dispatches a string command to a method.""" if len(args) < 1: raise Exception("Not enough arguments") method = "Exec%s" % self._CommandifyName(args[0]) getattr(self, method)(*args[1:])
[ "def", "Dispatch", "(", "self", ",", "args", ")", ":", "if", "len", "(", "args", ")", "<", "1", ":", "raise", "Exception", "(", "\"Not enough arguments\"", ")", "method", "=", "\"Exec%s\"", "%", "self", ".", "_CommandifyName", "(", "args", "[", "0", "]...
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/media/webrtc/trunk/tools/gyp/pylib/gyp/sun_tool.py#L25-L31
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/multiprocessing/context.py
python
BaseContext.Semaphore
(self, value=1)
return Semaphore(value, ctx=self.get_context())
Returns a semaphore object
Returns a semaphore object
[ "Returns", "a", "semaphore", "object" ]
def Semaphore(self, value=1): '''Returns a semaphore object''' from .synchronize import Semaphore return Semaphore(value, ctx=self.get_context())
[ "def", "Semaphore", "(", "self", ",", "value", "=", "1", ")", ":", "from", ".", "synchronize", "import", "Semaphore", "return", "Semaphore", "(", "value", ",", "ctx", "=", "self", ".", "get_context", "(", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/multiprocessing/context.py#L79-L82
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_controls.py
python
TreeCtrl.SetIndent
(*args, **kwargs)
return _controls_.TreeCtrl_SetIndent(*args, **kwargs)
SetIndent(self, unsigned int indent)
SetIndent(self, unsigned int indent)
[ "SetIndent", "(", "self", "unsigned", "int", "indent", ")" ]
def SetIndent(*args, **kwargs): """SetIndent(self, unsigned int indent)""" return _controls_.TreeCtrl_SetIndent(*args, **kwargs)
[ "def", "SetIndent", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "TreeCtrl_SetIndent", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L5217-L5219
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/Inelastic/CrystalField/fitting.py
python
CrystalField.Symmetry
(self)
return self.crystalFieldFunction.getAttributeValue('Symmetry')
Get value of Symmetry attribute. For example: cf = CrystalField(...) ... symm = cf.Symmetry
Get value of Symmetry attribute. For example:
[ "Get", "value", "of", "Symmetry", "attribute", ".", "For", "example", ":" ]
def Symmetry(self): """Get value of Symmetry attribute. For example: cf = CrystalField(...) ... symm = cf.Symmetry """ return self.crystalFieldFunction.getAttributeValue('Symmetry')
[ "def", "Symmetry", "(", "self", ")", ":", "return", "self", ".", "crystalFieldFunction", ".", "getAttributeValue", "(", "'Symmetry'", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/Inelastic/CrystalField/fitting.py#L368-L375
ukoethe/vigra
093d57d15c8c237adf1704d96daa6393158ce299
vigranumpy/lib/pyqt/imagewindow.py
python
ImageViewer.contextMenuEvent
(self, e)
handles pop-up menu
handles pop-up menu
[ "handles", "pop", "-", "up", "menu" ]
def contextMenuEvent(self, e): "handles pop-up menu" self.overlayMenu.setEnabled(len(self.overlays) > 0) self.mousepos = e.pos() self.popup.exec_(e.globalPos())
[ "def", "contextMenuEvent", "(", "self", ",", "e", ")", ":", "self", ".", "overlayMenu", ".", "setEnabled", "(", "len", "(", "self", ".", "overlays", ")", ">", "0", ")", "self", ".", "mousepos", "=", "e", ".", "pos", "(", ")", "self", ".", "popup", ...
https://github.com/ukoethe/vigra/blob/093d57d15c8c237adf1704d96daa6393158ce299/vigranumpy/lib/pyqt/imagewindow.py#L437-L441
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/contrib/slim/python/slim/data/tfexample_decoder.py
python
TFExampleDecoder.__init__
(self, keys_to_features, items_to_handlers)
Constructs the decoder. Args: keys_to_features: a dictionary from TF-Example keys to either tf.VarLenFeature or tf.FixedLenFeature instances. See tensorflow's parsing_ops.py. items_to_handlers: a dictionary from items (strings) to ItemHandler instances. Note that the ItemHandler's are provided the keys that they use to return the final item Tensors.
Constructs the decoder.
[ "Constructs", "the", "decoder", "." ]
def __init__(self, keys_to_features, items_to_handlers): """Constructs the decoder. Args: keys_to_features: a dictionary from TF-Example keys to either tf.VarLenFeature or tf.FixedLenFeature instances. See tensorflow's parsing_ops.py. items_to_handlers: a dictionary from items (strings) to ItemHandler instances. Note that the ItemHandler's are provided the keys that they use to return the final item Tensors. """ self._keys_to_features = keys_to_features self._items_to_handlers = items_to_handlers
[ "def", "__init__", "(", "self", ",", "keys_to_features", ",", "items_to_handlers", ")", ":", "self", ".", "_keys_to_features", "=", "keys_to_features", "self", ".", "_items_to_handlers", "=", "items_to_handlers" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/slim/python/slim/data/tfexample_decoder.py#L299-L311
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/propgrid.py
python
PyComboBoxEditor._SetSelf
(*args, **kwargs)
return _propgrid.PyComboBoxEditor__SetSelf(*args, **kwargs)
_SetSelf(self, PyObject self)
_SetSelf(self, PyObject self)
[ "_SetSelf", "(", "self", "PyObject", "self", ")" ]
def _SetSelf(*args, **kwargs): """_SetSelf(self, PyObject self)""" return _propgrid.PyComboBoxEditor__SetSelf(*args, **kwargs)
[ "def", "_SetSelf", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PyComboBoxEditor__SetSelf", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/propgrid.py#L3976-L3978
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/robotsim.py
python
Geometry3D.rayCast
(self, s: Point, d: Point)
return _robotsim.Geometry3D_rayCast(self, s, d)
r""" Performs a ray cast. Args: s (:obj:`list of 3 floats`) d (:obj:`list of 3 floats`) Supported types: * GeometricPrimitive * TriangleMesh * PointCloud (need a positive collision margin, or points need to have a 'radius' property assigned) * VolumeGrid * Group (groups of the aforementioned types) Returns: (hit,pt) where hit is true if the ray starting at s and pointing in direction d hits the geometry (given in world coordinates); pt is the hit point, in world coordinates.
r""" Performs a ray cast.
[ "r", "Performs", "a", "ray", "cast", "." ]
def rayCast(self, s: Point, d: Point) ->bool: r""" Performs a ray cast. Args: s (:obj:`list of 3 floats`) d (:obj:`list of 3 floats`) Supported types: * GeometricPrimitive * TriangleMesh * PointCloud (need a positive collision margin, or points need to have a 'radius' property assigned) * VolumeGrid * Group (groups of the aforementioned types) Returns: (hit,pt) where hit is true if the ray starting at s and pointing in direction d hits the geometry (given in world coordinates); pt is the hit point, in world coordinates. """ return _robotsim.Geometry3D_rayCast(self, s, d)
[ "def", "rayCast", "(", "self", ",", "s", ":", "Point", ",", "d", ":", "Point", ")", "->", "bool", ":", "return", "_robotsim", ".", "Geometry3D_rayCast", "(", "self", ",", "s", ",", "d", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/robotsim.py#L2515-L2539
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_controls.py
python
ListView.Focus
(*args, **kwargs)
return _controls_.ListView_Focus(*args, **kwargs)
Focus(self, long index)
Focus(self, long index)
[ "Focus", "(", "self", "long", "index", ")" ]
def Focus(*args, **kwargs): """Focus(self, long index)""" return _controls_.ListView_Focus(*args, **kwargs)
[ "def", "Focus", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "ListView_Focus", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L4919-L4921
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/webkit.py
python
WebKitNewWindowEvent.__init__
(self, *args, **kwargs)
__init__(self, Window win=None) -> WebKitNewWindowEvent
__init__(self, Window win=None) -> WebKitNewWindowEvent
[ "__init__", "(", "self", "Window", "win", "=", "None", ")", "-", ">", "WebKitNewWindowEvent" ]
def __init__(self, *args, **kwargs): """__init__(self, Window win=None) -> WebKitNewWindowEvent""" _webkit.WebKitNewWindowEvent_swiginit(self,_webkit.new_WebKitNewWindowEvent(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_webkit", ".", "WebKitNewWindowEvent_swiginit", "(", "self", ",", "_webkit", ".", "new_WebKitNewWindowEvent", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/webkit.py#L278-L280
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/corrections_tab_widget/dead_time_corrections_presenter.py
python
DeadTimeCorrectionsPresenter._handle_selected_table_is_invalid
(self)
Handles when the selected dead time table workspace is invalid.
Handles when the selected dead time table workspace is invalid.
[ "Handles", "when", "the", "selected", "dead", "time", "table", "workspace", "is", "invalid", "." ]
def _handle_selected_table_is_invalid(self) -> None: """Handles when the selected dead time table workspace is invalid.""" # Triggers handle_dead_time_from_selector_changed self.view.set_dead_time_from_data_file_selected()
[ "def", "_handle_selected_table_is_invalid", "(", "self", ")", "->", "None", ":", "# Triggers handle_dead_time_from_selector_changed", "self", ".", "view", ".", "set_dead_time_from_data_file_selected", "(", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/corrections_tab_widget/dead_time_corrections_presenter.py#L91-L94
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
GBSizerItem.SetGBSizer
(*args, **kwargs)
return _core_.GBSizerItem_SetGBSizer(*args, **kwargs)
SetGBSizer(self, GridBagSizer sizer) Set the sizer this item is a member of.
SetGBSizer(self, GridBagSizer sizer)
[ "SetGBSizer", "(", "self", "GridBagSizer", "sizer", ")" ]
def SetGBSizer(*args, **kwargs): """ SetGBSizer(self, GridBagSizer sizer) Set the sizer this item is a member of. """ return _core_.GBSizerItem_SetGBSizer(*args, **kwargs)
[ "def", "SetGBSizer", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "GBSizerItem_SetGBSizer", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L15810-L15816
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/distutils/text_file.py
python
TextFile.unreadline
(self, line)
Push 'line' (a string) onto an internal buffer that will be checked by future 'readline()' calls. Handy for implementing a parser with line-at-a-time lookahead.
Push 'line' (a string) onto an internal buffer that will be checked by future 'readline()' calls. Handy for implementing a parser with line-at-a-time lookahead.
[ "Push", "line", "(", "a", "string", ")", "onto", "an", "internal", "buffer", "that", "will", "be", "checked", "by", "future", "readline", "()", "calls", ".", "Handy", "for", "implementing", "a", "parser", "with", "line", "-", "at", "-", "a", "-", "time...
def unreadline(self, line): """Push 'line' (a string) onto an internal buffer that will be checked by future 'readline()' calls. Handy for implementing a parser with line-at-a-time lookahead.""" self.linebuf.append(line)
[ "def", "unreadline", "(", "self", ",", "line", ")", ":", "self", ".", "linebuf", ".", "append", "(", "line", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/distutils/text_file.py#L282-L286
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/traci/_vehicle.py
python
VehicleDomain.getMaxSpeed
(self, vehID)
return self._getUniversal(tc.VAR_MAXSPEED, vehID)
getMaxSpeed(string) -> double Returns the maximum speed in m/s of this vehicle.
getMaxSpeed(string) -> double
[ "getMaxSpeed", "(", "string", ")", "-", ">", "double" ]
def getMaxSpeed(self, vehID): """getMaxSpeed(string) -> double Returns the maximum speed in m/s of this vehicle. """ return self._getUniversal(tc.VAR_MAXSPEED, vehID)
[ "def", "getMaxSpeed", "(", "self", ",", "vehID", ")", ":", "return", "self", ".", "_getUniversal", "(", "tc", ".", "VAR_MAXSPEED", ",", "vehID", ")" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/traci/_vehicle.py#L483-L488
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
Size.Get
(*args, **kwargs)
return _core_.Size_Get(*args, **kwargs)
Get() -> (width,height) Returns the width and height properties as a tuple.
Get() -> (width,height)
[ "Get", "()", "-", ">", "(", "width", "height", ")" ]
def Get(*args, **kwargs): """ Get() -> (width,height) Returns the width and height properties as a tuple. """ return _core_.Size_Get(*args, **kwargs)
[ "def", "Get", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Size_Get", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L1051-L1057
BitMEX/api-connectors
37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812
auto-generated/python/swagger_client/models/execution.py
python
Execution.exec_inst
(self)
return self._exec_inst
Gets the exec_inst of this Execution. # noqa: E501 :return: The exec_inst of this Execution. # noqa: E501 :rtype: str
Gets the exec_inst of this Execution. # noqa: E501
[ "Gets", "the", "exec_inst", "of", "this", "Execution", ".", "#", "noqa", ":", "E501" ]
def exec_inst(self): """Gets the exec_inst of this Execution. # noqa: E501 :return: The exec_inst of this Execution. # noqa: E501 :rtype: str """ return self._exec_inst
[ "def", "exec_inst", "(", "self", ")", ":", "return", "self", ".", "_exec_inst" ]
https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/execution.py#L786-L793
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/StdSuites/Standard_Suite.py
python
Standard_Suite_Events.count
(self, _object, _attributes={}, **_arguments)
count: Return the number of elements of an object Required argument: the object whose elements are to be counted Keyword argument each: if specified, restricts counting to objects of this class Keyword argument _attributes: AppleEvent attribute dictionary Returns: the number of elements
count: Return the number of elements of an object Required argument: the object whose elements are to be counted Keyword argument each: if specified, restricts counting to objects of this class Keyword argument _attributes: AppleEvent attribute dictionary Returns: the number of elements
[ "count", ":", "Return", "the", "number", "of", "elements", "of", "an", "object", "Required", "argument", ":", "the", "object", "whose", "elements", "are", "to", "be", "counted", "Keyword", "argument", "each", ":", "if", "specified", "restricts", "counting", ...
def count(self, _object, _attributes={}, **_arguments): """count: Return the number of elements of an object Required argument: the object whose elements are to be counted Keyword argument each: if specified, restricts counting to objects of this class Keyword argument _attributes: AppleEvent attribute dictionary Returns: the number of elements """ _code = 'core' _subcode = 'cnte' aetools.keysubst(_arguments, self._argmap_count) _arguments['----'] = _object _reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes) if _arguments.get('errn', 0): raise aetools.Error, aetools.decodeerror(_arguments) # XXXX Optionally decode result if _arguments.has_key('----'): return _arguments['----']
[ "def", "count", "(", "self", ",", "_object", ",", "_attributes", "=", "{", "}", ",", "*", "*", "_arguments", ")", ":", "_code", "=", "'core'", "_subcode", "=", "'cnte'", "aetools", ".", "keysubst", "(", "_arguments", ",", "self", ".", "_argmap_count", ...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/StdSuites/Standard_Suite.py#L74-L94
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/formats/format.py
python
Datetime64Formatter._format_strings
(self)
return fmt_values.tolist()
we by definition have DO NOT have a TZ
we by definition have DO NOT have a TZ
[ "we", "by", "definition", "have", "DO", "NOT", "have", "a", "TZ" ]
def _format_strings(self) -> List[str]: """ we by definition have DO NOT have a TZ """ values = self.values if not isinstance(values, DatetimeIndex): values = DatetimeIndex(values) if self.formatter is not None and callable(self.formatter): return [self.formatter(x) for x in values] fmt_values = format_array_from_datetime( values.asi8.ravel(), format=_get_format_datetime64_from_values(values, self.date_format), na_rep=self.nat_rep, ).reshape(values.shape) return fmt_values.tolist()
[ "def", "_format_strings", "(", "self", ")", "->", "List", "[", "str", "]", ":", "values", "=", "self", ".", "values", "if", "not", "isinstance", "(", "values", ",", "DatetimeIndex", ")", ":", "values", "=", "DatetimeIndex", "(", "values", ")", "if", "s...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/formats/format.py#L1458-L1474
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/bincount_ops.py
python
bincount_v1
(arr, weights=None, minlength=None, maxlength=None, dtype=dtypes.int32)
return bincount(arr, weights, minlength, maxlength, dtype)
Counts the number of occurrences of each value in an integer array. If `minlength` and `maxlength` are not given, returns a vector with length `tf.reduce_max(arr) + 1` if `arr` is non-empty, and length 0 otherwise. If `weights` are non-None, then index `i` of the output stores the sum of the value in `weights` at each index where the corresponding value in `arr` is `i`. Args: arr: An int32 tensor of non-negative values. weights: If non-None, must be the same shape as arr. For each value in `arr`, the bin will be incremented by the corresponding weight instead of 1. minlength: If given, ensures the output has length at least `minlength`, padding with zeros at the end if necessary. maxlength: If given, skips values in `arr` that are equal or greater than `maxlength`, ensuring that the output has length at most `maxlength`. dtype: If `weights` is None, determines the type of the output bins. Returns: A vector with the same dtype as `weights` or the given `dtype`. The bin values.
Counts the number of occurrences of each value in an integer array.
[ "Counts", "the", "number", "of", "occurrences", "of", "each", "value", "in", "an", "integer", "array", "." ]
def bincount_v1(arr, weights=None, minlength=None, maxlength=None, dtype=dtypes.int32): """Counts the number of occurrences of each value in an integer array. If `minlength` and `maxlength` are not given, returns a vector with length `tf.reduce_max(arr) + 1` if `arr` is non-empty, and length 0 otherwise. If `weights` are non-None, then index `i` of the output stores the sum of the value in `weights` at each index where the corresponding value in `arr` is `i`. Args: arr: An int32 tensor of non-negative values. weights: If non-None, must be the same shape as arr. For each value in `arr`, the bin will be incremented by the corresponding weight instead of 1. minlength: If given, ensures the output has length at least `minlength`, padding with zeros at the end if necessary. maxlength: If given, skips values in `arr` that are equal or greater than `maxlength`, ensuring that the output has length at most `maxlength`. dtype: If `weights` is None, determines the type of the output bins. Returns: A vector with the same dtype as `weights` or the given `dtype`. The bin values. """ return bincount(arr, weights, minlength, maxlength, dtype)
[ "def", "bincount_v1", "(", "arr", ",", "weights", "=", "None", ",", "minlength", "=", "None", ",", "maxlength", "=", "None", ",", "dtype", "=", "dtypes", ".", "int32", ")", ":", "return", "bincount", "(", "arr", ",", "weights", ",", "minlength", ",", ...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/bincount_ops.py#L220-L248
INK-USC/USC-DS-RelationExtraction
eebcfa7fd2eda5bba92f3ef8158797cdf91e6981
code/Classifier/Logistic.py
python
Logistic.fit
(self, train_x, train_y)
train_x: list of feature ids train_y: list of [labels]
train_x: list of feature ids train_y: list of [labels]
[ "train_x", ":", "list", "of", "feature", "ids", "train_y", ":", "list", "of", "[", "labels", "]" ]
def fit(self, train_x, train_y): """ train_x: list of feature ids train_y: list of [labels] """ assert len(train_x) == len(train_y) y = [] x = [] for i in range(len(train_x)): feature = {} for fid in train_x[i]: feature[fid + 1] = 1.0 for j in range(len(train_y[i])): y.append(float(train_y[i][j])) x.append(feature) prob = problem(y, x) param = parameter('-s 0 -c 1 -n 35 -q') self.model = train(prob, param) # L2-Logistic print('Finish training.')
[ "def", "fit", "(", "self", ",", "train_x", ",", "train_y", ")", ":", "assert", "len", "(", "train_x", ")", "==", "len", "(", "train_y", ")", "y", "=", "[", "]", "x", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "train_x", ")", "...
https://github.com/INK-USC/USC-DS-RelationExtraction/blob/eebcfa7fd2eda5bba92f3ef8158797cdf91e6981/code/Classifier/Logistic.py#L15-L34
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/resource_variable_ops.py
python
ResourceVariable._init_from_proto
(self, variable_def, import_scope=None)
Initializes from `VariableDef` proto.
Initializes from `VariableDef` proto.
[ "Initializes", "from", "VariableDef", "proto", "." ]
def _init_from_proto(self, variable_def, import_scope=None): """Initializes from `VariableDef` proto.""" # Note that init_from_proto is currently not supported in Eager mode. assert not context.executing_eagerly() self._in_graph_mode = True assert isinstance(variable_def, variable_pb2.VariableDef) if not variable_def.is_resource: raise ValueError("Trying to restore Variable as ResourceVariable.") # Create from variable_def. g = ops.get_default_graph() self._handle = g.as_graph_element( ops.prepend_name_scope( variable_def.variable_name, import_scope=import_scope)) self._shape = tensor_shape.TensorShape( self._handle.op.get_attr("shape")) self._handle_name = self._handle.name self._unique_id = self._handle_name self._initializer_op = g.as_graph_element( ops.prepend_name_scope( variable_def.initializer_name, import_scope=import_scope)) # Check whether initial_value_name exists for backwards compatibility. if (hasattr(variable_def, "initial_value_name") and variable_def.initial_value_name): self._initial_value = g.as_graph_element( ops.prepend_name_scope(variable_def.initial_value_name, import_scope=import_scope)) else: self._initial_value = None synchronization, aggregation, trainable = ( variables.validate_synchronization_aggregation_trainable( variable_def.synchronization, variable_def.aggregation, variable_def.trainable, variable_def.variable_name)) self._synchronization = synchronization self._aggregation = aggregation self._trainable = trainable if variable_def.snapshot_name: snapshot = g.as_graph_element( ops.prepend_name_scope( variable_def.snapshot_name, import_scope=import_scope)) if snapshot.op.type != "ReadVariableOp": self._cached_value = snapshot else: self._cached_value = None while snapshot.op.type != "ReadVariableOp": snapshot = snapshot.op.inputs[0] self._graph_element = snapshot else: self._cached_value = None # Legacy case for protos without the snapshot name; assume it's the # following. self._graph_element = g.get_tensor_by_name( self._handle.op.name + "/Read/ReadVariableOp:0") if variable_def.HasField("save_slice_info_def"): self._save_slice_info = variables.Variable.SaveSliceInfo( save_slice_info_def=variable_def.save_slice_info_def, import_scope=import_scope) else: self._save_slice_info = None self._caching_device = None self._dtype = dtypes.as_dtype(self._handle.op.get_attr("dtype")) self._constraint = None
[ "def", "_init_from_proto", "(", "self", ",", "variable_def", ",", "import_scope", "=", "None", ")", ":", "# Note that init_from_proto is currently not supported in Eager mode.", "assert", "not", "context", ".", "executing_eagerly", "(", ")", "self", ".", "_in_graph_mode",...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/resource_variable_ops.py#L1632-L1695
google/mozc
7329757e1ad30e327c1ae823a8302c79482d6b9c
src/prediction/gen_zero_query_data.py
python
ReadSymbolTsv
(stream)
return zero_query_dict
Reads emoji data from stream and returns zero query data.
Reads emoji data from stream and returns zero query data.
[ "Reads", "emoji", "data", "from", "stream", "and", "returns", "zero", "query", "data", "." ]
def ReadSymbolTsv(stream): """Reads emoji data from stream and returns zero query data.""" zero_query_dict = collections.defaultdict(list) stream = code_generator_util.SkipLineComment(stream) for columns in code_generator_util.ParseColumnStream(stream, delimiter='\t'): if len(columns) < 3: logging.warning('format error: %s', '\t'.join(columns)) continue symbol = columns[1] readings = columns[2] symbol_unicode = symbol if len(symbol_unicode) != 1: continue symbol_code_point = ord(symbol_unicode) # Selects emoji symbols from symbol dictionary. # TODO(toshiyuki): Update the range if we need. # from "☀"(black sun with rays) to "❧"(rotated floral heart). if not (0x2600 <= symbol_code_point and symbol_code_point <= 0x2767): continue for reading in re.split(RE_SPLIT, readings.strip()): if not reading: continue zero_query_dict[reading].append( util.ZeroQueryEntry(util.ZERO_QUERY_TYPE_NONE, symbol, util.EMOJI_TYPE_NONE, 0)) if len(columns) >= 4 and columns[3]: # description: "天気", etc. description = columns[3] zero_query_dict[description].append( util.ZeroQueryEntry(util.ZERO_QUERY_TYPE_NONE, symbol, util.EMOJI_TYPE_NONE, 0)) if len(columns) >= 5 and columns[4]: # additional_description: "傘", etc. additional_description = columns[4] zero_query_dict[additional_description].append( util.ZeroQueryEntry(util.ZERO_QUERY_TYPE_NONE, symbol, util.EMOJI_TYPE_NONE, 0)) return zero_query_dict
[ "def", "ReadSymbolTsv", "(", "stream", ")", ":", "zero_query_dict", "=", "collections", ".", "defaultdict", "(", "list", ")", "stream", "=", "code_generator_util", ".", "SkipLineComment", "(", "stream", ")", "for", "columns", "in", "code_generator_util", ".", "P...
https://github.com/google/mozc/blob/7329757e1ad30e327c1ae823a8302c79482d6b9c/src/prediction/gen_zero_query_data.py#L205-L248
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/contributed/sumopy/plugins/mapmatching/mapmatching.py
python
GpsPoints.get_ids_selected
(self)
return self.select_ids(self.parent.trips.are_selected[self.ids_trip.get_value()] )
Returns point ids of selected traces
Returns point ids of selected traces
[ "Returns", "point", "ids", "of", "selected", "traces" ]
def get_ids_selected(self): """ Returns point ids of selected traces """ #print 'GpsPoints.get_ids_selected' #print ' ??ids_points = ',self.select_ids(self.parent.trips.are_selected[self.ids_trip.get_value()] ) # TODO: why is this working??? do we need trips.ids_points???? return self.select_ids(self.parent.trips.are_selected[self.ids_trip.get_value()] )
[ "def", "get_ids_selected", "(", "self", ")", ":", "#print 'GpsPoints.get_ids_selected'", "#print ' ??ids_points = ',self.select_ids(self.parent.trips.are_selected[self.ids_trip.get_value()] )", "# TODO: why is this working??? do we need trips.ids_points????", "return", "self", ".", "select_...
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/plugins/mapmatching/mapmatching.py#L9332-L9339
google/shaka-packager
e1b0c7c45431327fd3ce193514a5407d07b39b22
packager/third_party/protobuf/python/google/protobuf/internal/decoder.py
python
MapDecoder
(field_descriptor, new_default, is_message_map)
return DecodeMap
Returns a decoder for a map field.
Returns a decoder for a map field.
[ "Returns", "a", "decoder", "for", "a", "map", "field", "." ]
def MapDecoder(field_descriptor, new_default, is_message_map): """Returns a decoder for a map field.""" key = field_descriptor tag_bytes = encoder.TagBytes(field_descriptor.number, wire_format.WIRETYPE_LENGTH_DELIMITED) tag_len = len(tag_bytes) local_DecodeVarint = _DecodeVarint # Can't read _concrete_class yet; might not be initialized. message_type = field_descriptor.message_type def DecodeMap(buffer, pos, end, message, field_dict): submsg = message_type._concrete_class() value = field_dict.get(key) if value is None: value = field_dict.setdefault(key, new_default(message)) while 1: # Read length. (size, pos) = local_DecodeVarint(buffer, pos) new_pos = pos + size if new_pos > end: raise _DecodeError('Truncated message.') # Read sub-message. submsg.Clear() if submsg._InternalParse(buffer, pos, new_pos) != new_pos: # The only reason _InternalParse would return early is if it # encountered an end-group tag. raise _DecodeError('Unexpected end-group tag.') if is_message_map: value[submsg.key].MergeFrom(submsg.value) else: value[submsg.key] = submsg.value # Predict that the next tag is another copy of the same repeated field. pos = new_pos + tag_len if buffer[new_pos:pos] != tag_bytes or new_pos == end: # Prediction failed. Return. return new_pos return DecodeMap
[ "def", "MapDecoder", "(", "field_descriptor", ",", "new_default", ",", "is_message_map", ")", ":", "key", "=", "field_descriptor", "tag_bytes", "=", "encoder", ".", "TagBytes", "(", "field_descriptor", ".", "number", ",", "wire_format", ".", "WIRETYPE_LENGTH_DELIMIT...
https://github.com/google/shaka-packager/blob/e1b0c7c45431327fd3ce193514a5407d07b39b22/packager/third_party/protobuf/python/google/protobuf/internal/decoder.py#L719-L759
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/plotting/_matplotlib/hist.py
python
_grouped_hist
( data, column=None, by=None, ax=None, bins=50, figsize=None, layout=None, sharex=False, sharey=False, rot=90, grid=True, xlabelsize=None, xrot=None, ylabelsize=None, yrot=None, legend=False, **kwargs, )
return axes
Grouped histogram Parameters ---------- data : Series/DataFrame column : object, optional by : object, optional ax : axes, optional bins : int, default 50 figsize : tuple, optional layout : optional sharex : bool, default False sharey : bool, default False rot : int, default 90 grid : bool, default True legend: : bool, default False kwargs : dict, keyword arguments passed to matplotlib.Axes.hist Returns ------- collection of Matplotlib Axes
Grouped histogram
[ "Grouped", "histogram" ]
def _grouped_hist( data, column=None, by=None, ax=None, bins=50, figsize=None, layout=None, sharex=False, sharey=False, rot=90, grid=True, xlabelsize=None, xrot=None, ylabelsize=None, yrot=None, legend=False, **kwargs, ): """ Grouped histogram Parameters ---------- data : Series/DataFrame column : object, optional by : object, optional ax : axes, optional bins : int, default 50 figsize : tuple, optional layout : optional sharex : bool, default False sharey : bool, default False rot : int, default 90 grid : bool, default True legend: : bool, default False kwargs : dict, keyword arguments passed to matplotlib.Axes.hist Returns ------- collection of Matplotlib Axes """ if legend: assert "label" not in kwargs if data.ndim == 1: kwargs["label"] = data.name elif column is None: kwargs["label"] = data.columns else: kwargs["label"] = column def plot_group(group, ax): ax.hist(group.dropna().values, bins=bins, **kwargs) if legend: ax.legend() if xrot is None: xrot = rot fig, axes = _grouped_plot( plot_group, data, column=column, by=by, sharex=sharex, sharey=sharey, ax=ax, figsize=figsize, layout=layout, rot=rot, ) set_ticks_props( axes, xlabelsize=xlabelsize, xrot=xrot, ylabelsize=ylabelsize, yrot=yrot ) maybe_adjust_figure( fig, bottom=0.15, top=0.9, left=0.1, right=0.9, hspace=0.5, wspace=0.3 ) return axes
[ "def", "_grouped_hist", "(", "data", ",", "column", "=", "None", ",", "by", "=", "None", ",", "ax", "=", "None", ",", "bins", "=", "50", ",", "figsize", "=", "None", ",", "layout", "=", "None", ",", "sharex", "=", "False", ",", "sharey", "=", "Fa...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/plotting/_matplotlib/hist.py#L237-L316
Kitware/ParaView
f760af9124ff4634b23ebbeab95a4f56e0261955
ThirdParty/cinema/paraview/tpl/cinema_python/database/store.py
python
Store.get_parameter_values
(self, name)
return values
Get all values of type value :param name: Name for the parameter.
Get all values of type value :param name: Name for the parameter.
[ "Get", "all", "values", "of", "type", "value", ":", "param", "name", ":", "Name", "for", "the", "parameter", "." ]
def get_parameter_values(self, name): """ Get all values of type value :param name: Name for the parameter. """ values = [] if ('values' in self.__parameter_list[name] and 'types' in self.__parameter_list[name]): for val, typ in zip(self.__parameter_list[name]['values'], self.__parameter_list[name]['types']): if typ == 'value': values.append(val) return values
[ "def", "get_parameter_values", "(", "self", ",", "name", ")", ":", "values", "=", "[", "]", "if", "(", "'values'", "in", "self", ".", "__parameter_list", "[", "name", "]", "and", "'types'", "in", "self", ".", "__parameter_list", "[", "name", "]", ")", ...
https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/ThirdParty/cinema/paraview/tpl/cinema_python/database/store.py#L203-L215
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/scipy/special/basic.py
python
assoc_laguerre
(x, n, k=0.0)
return orthogonal.eval_genlaguerre(n, k, x)
Compute the generalized (associated) Laguerre polynomial of degree n and order k. The polynomial :math:`L^{(k)}_n(x)` is orthogonal over ``[0, inf)``, with weighting function ``exp(-x) * x**k`` with ``k > -1``. Notes ----- `assoc_laguerre` is a simple wrapper around `eval_genlaguerre`, with reversed argument order ``(x, n, k=0.0) --> (n, k, x)``.
Compute the generalized (associated) Laguerre polynomial of degree n and order k.
[ "Compute", "the", "generalized", "(", "associated", ")", "Laguerre", "polynomial", "of", "degree", "n", "and", "order", "k", "." ]
def assoc_laguerre(x, n, k=0.0): """Compute the generalized (associated) Laguerre polynomial of degree n and order k. The polynomial :math:`L^{(k)}_n(x)` is orthogonal over ``[0, inf)``, with weighting function ``exp(-x) * x**k`` with ``k > -1``. Notes ----- `assoc_laguerre` is a simple wrapper around `eval_genlaguerre`, with reversed argument order ``(x, n, k=0.0) --> (n, k, x)``. """ return orthogonal.eval_genlaguerre(n, k, x)
[ "def", "assoc_laguerre", "(", "x", ",", "n", ",", "k", "=", "0.0", ")", ":", "return", "orthogonal", ".", "eval_genlaguerre", "(", "n", ",", "k", ",", "x", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/special/basic.py#L1173-L1185
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/commands/list.py
python
format_for_columns
(pkgs, options)
return data, header
Convert the package data into something usable by output_package_listing_columns.
Convert the package data into something usable by output_package_listing_columns.
[ "Convert", "the", "package", "data", "into", "something", "usable", "by", "output_package_listing_columns", "." ]
def format_for_columns(pkgs, options): # type: (List[Distribution], Values) -> Tuple[List[List[str]], List[str]] """ Convert the package data into something usable by output_package_listing_columns. """ running_outdated = options.outdated # Adjust the header for the `pip list --outdated` case. if running_outdated: header = ["Package", "Version", "Latest", "Type"] else: header = ["Package", "Version"] data = [] if options.verbose >= 1 or any(dist_is_editable(x) for x in pkgs): header.append("Location") if options.verbose >= 1: header.append("Installer") for proj in pkgs: # if we're working on the 'outdated' list, separate out the # latest_version and type row = [proj.project_name, proj.version] if running_outdated: row.append(proj.latest_version) row.append(proj.latest_filetype) if options.verbose >= 1 or dist_is_editable(proj): row.append(proj.location) if options.verbose >= 1: row.append(get_installer(proj)) data.append(row) return data, header
[ "def", "format_for_columns", "(", "pkgs", ",", "options", ")", ":", "# type: (List[Distribution], Values) -> Tuple[List[List[str]], List[str]]", "running_outdated", "=", "options", ".", "outdated", "# Adjust the header for the `pip list --outdated` case.", "if", "running_outdated", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/commands/list.py#L270-L305
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
python/mxnet/contrib/autograd.py
python
grad
(func, argnum=None)
return wrapped
Return function that computes gradient of arguments. Parameters ---------- func: a python function The forward (loss) function. argnum: an int or a list of int The index of argument to calculate gradient for. Returns ------- grad_func: a python function A function that would compute the gradient of arguments. Examples -------- >>> # autograd supports dynamic graph which is changed >>> # every instance >>> def func(x): >>> r = random.randint(0, 1) >>> if r % 2: >>> return x**2 >>> else: >>> return x/3 >>> # use `grad(func)` to get the gradient function >>> for x in range(10): >>> grad_func = grad(func) >>> inputs = nd.array([[1, 2, 3], [4, 5, 6]]) >>> grad_vals = grad_func(inputs)
Return function that computes gradient of arguments.
[ "Return", "function", "that", "computes", "gradient", "of", "arguments", "." ]
def grad(func, argnum=None): """Return function that computes gradient of arguments. Parameters ---------- func: a python function The forward (loss) function. argnum: an int or a list of int The index of argument to calculate gradient for. Returns ------- grad_func: a python function A function that would compute the gradient of arguments. Examples -------- >>> # autograd supports dynamic graph which is changed >>> # every instance >>> def func(x): >>> r = random.randint(0, 1) >>> if r % 2: >>> return x**2 >>> else: >>> return x/3 >>> # use `grad(func)` to get the gradient function >>> for x in range(10): >>> grad_func = grad(func) >>> inputs = nd.array([[1, 2, 3], [4, 5, 6]]) >>> grad_vals = grad_func(inputs) """ grad_with_loss_func = grad_and_loss(func, argnum) @functools.wraps(grad_with_loss_func) def wrapped(*args): return grad_with_loss_func(*args)[0] return wrapped
[ "def", "grad", "(", "func", ",", "argnum", "=", "None", ")", ":", "grad_with_loss_func", "=", "grad_and_loss", "(", "func", ",", "argnum", ")", "@", "functools", ".", "wraps", "(", "grad_with_loss_func", ")", "def", "wrapped", "(", "*", "args", ")", ":",...
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/contrib/autograd.py#L195-L230
bareos/bareos
56a10bb368b0a81e977bb51304033fe49d59efb0
contrib/dir-plugins/graphite/BareosDirPluginGraphiteSender.py
python
BareosDirPluginGraphiteSender.parse_plugin_definition
(self, context, plugindef)
return bRCs['bRC_OK']
Check, if mandatory monitoringHost is set and set default for other unset parameters
Check, if mandatory monitoringHost is set and set default for other unset parameters
[ "Check", "if", "mandatory", "monitoringHost", "is", "set", "and", "set", "default", "for", "other", "unset", "parameters" ]
def parse_plugin_definition(self, context, plugindef): ''' Check, if mandatory monitoringHost is set and set default for other unset parameters ''' super(BareosDirPluginGraphiteSender, self).parse_plugin_definition( context, plugindef) # monitoring Host is mandatory if 'collectorHost' not in self.options: self.collectorHost = "graphite" else: self.collectorHost = self.options['collectorHost'] if 'collectorPort' not in self.options: self.collectorPort = 2003 else: self.collectorPort = int(self.options['collectorPort']) if 'metricPrefix' not in self.options: self.metricPrefix = 'apps' else: self.metricPrefix = self.options['metricPrefix'] # we return OK in anyway, we do not want to produce Bareos errors just because of failing # Nagios notifications return bRCs['bRC_OK']
[ "def", "parse_plugin_definition", "(", "self", ",", "context", ",", "plugindef", ")", ":", "super", "(", "BareosDirPluginGraphiteSender", ",", "self", ")", ".", "parse_plugin_definition", "(", "context", ",", "plugindef", ")", "# monitoring Host is mandatory", "if", ...
https://github.com/bareos/bareos/blob/56a10bb368b0a81e977bb51304033fe49d59efb0/contrib/dir-plugins/graphite/BareosDirPluginGraphiteSender.py#L37-L58