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
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/propgrid.py
python
PGProperty.SetAttribute
(*args, **kwargs)
return _propgrid.PGProperty_SetAttribute(*args, **kwargs)
SetAttribute(self, String name, wxVariant value)
SetAttribute(self, String name, wxVariant value)
[ "SetAttribute", "(", "self", "String", "name", "wxVariant", "value", ")" ]
def SetAttribute(*args, **kwargs): """SetAttribute(self, String name, wxVariant value)""" return _propgrid.PGProperty_SetAttribute(*args, **kwargs)
[ "def", "SetAttribute", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PGProperty_SetAttribute", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/propgrid.py#L675-L677
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/src/robotsim.py
python
IKSolver.solve
(self, *args)
return _robotsim.IKSolver_solve(self, *args)
solve(IKSolver self) -> bool solve(IKSolver self, int iters, double tol) -> PyObject * Old-style: will be deprecated. Specify # of iterations and tolerance. Tries to find a configuration that satifies all simultaneous objectives up to the desired tolerance. Returns (res,iterations) where res is true if x converged.
solve(IKSolver self) -> bool solve(IKSolver self, int iters, double tol) -> PyObject *
[ "solve", "(", "IKSolver", "self", ")", "-", ">", "bool", "solve", "(", "IKSolver", "self", "int", "iters", "double", "tol", ")", "-", ">", "PyObject", "*" ]
def solve(self, *args): """ solve(IKSolver self) -> bool solve(IKSolver self, int iters, double tol) -> PyObject * Old-style: will be deprecated. Specify # of iterations and tolerance. Tries to find a configuration that satifies all simultaneous objectives up to the desired tolerance. Returns (res,iterations) where res is true if x converged. """ return _robotsim.IKSolver_solve(self, *args)
[ "def", "solve", "(", "self", ",", "*", "args", ")", ":", "return", "_robotsim", ".", "IKSolver_solve", "(", "self", ",", "*", "args", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/src/robotsim.py#L6791-L6803
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/devil/devil/utils/find_usb_devices.py
python
USBNode.AllNodes
(self)
Generator that yields this node and all of its descendants. Yields: [USBNode] First this node, then each of its descendants (recursively)
Generator that yields this node and all of its descendants.
[ "Generator", "that", "yields", "this", "node", "and", "all", "of", "its", "descendants", "." ]
def AllNodes(self): """Generator that yields this node and all of its descendants. Yields: [USBNode] First this node, then each of its descendants (recursively) """ yield self for child_node in self._port_to_node.values(): for descendant_node in child_node.AllNodes(): yield descendant_node
[ "def", "AllNodes", "(", "self", ")", ":", "yield", "self", "for", "child_node", "in", "self", ".", "_port_to_node", ".", "values", "(", ")", ":", "for", "descendant_node", "in", "child_node", ".", "AllNodes", "(", ")", ":", "yield", "descendant_node" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/devil/devil/utils/find_usb_devices.py#L111-L120
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/resolvelib/structs.py
python
DirectedGraph.connect
(self, f, t)
Connect two existing vertices. Nothing happens if the vertices are already connected.
Connect two existing vertices.
[ "Connect", "two", "existing", "vertices", "." ]
def connect(self, f, t): """Connect two existing vertices. Nothing happens if the vertices are already connected. """ if t not in self._vertices: raise KeyError(t) self._forwards[f].add(t) self._backwards[t].add(f)
[ "def", "connect", "(", "self", ",", "f", ",", "t", ")", ":", "if", "t", "not", "in", "self", ".", "_vertices", ":", "raise", "KeyError", "(", "t", ")", "self", ".", "_forwards", "[", "f", "]", ".", "add", "(", "t", ")", "self", ".", "_backwards...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/resolvelib/structs.py#L48-L56
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/extern/aui/auibar.py
python
AuiToolBar.GetToolEnabled
(self, tool_id)
return False
Returns whether the tool identified by `tool_id` is enabled or not. :param integer `tool_id`: the tool identifier.
Returns whether the tool identified by `tool_id` is enabled or not.
[ "Returns", "whether", "the", "tool", "identified", "by", "tool_id", "is", "enabled", "or", "not", "." ]
def GetToolEnabled(self, tool_id): """ Returns whether the tool identified by `tool_id` is enabled or not. :param integer `tool_id`: the tool identifier. """ tool = self.FindTool(tool_id) if tool: return (tool.state & AUI_BUTTON_STATE_DISABLED and [False] or [True])[0] return False
[ "def", "GetToolEnabled", "(", "self", ",", "tool_id", ")", ":", "tool", "=", "self", ".", "FindTool", "(", "tool_id", ")", "if", "tool", ":", "return", "(", "tool", ".", "state", "&", "AUI_BUTTON_STATE_DISABLED", "and", "[", "False", "]", "or", "[", "T...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/auibar.py#L2698-L2710
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/src/doxy2swig.py
python
Doxy2SWIG.make_constructor_list
(self, constructor_nodes, classname)
Produces the "Constructors" section and the constructor signatures (since swig does not do so for classes) for class docstrings.
Produces the "Constructors" section and the constructor signatures (since swig does not do so for classes) for class docstrings.
[ "Produces", "the", "Constructors", "section", "and", "the", "constructor", "signatures", "(", "since", "swig", "does", "not", "do", "so", "for", "classes", ")", "for", "class", "docstrings", "." ]
def make_constructor_list(self, constructor_nodes, classname): """Produces the "Constructors" section and the constructor signatures (since swig does not do so for classes) for class docstrings.""" if constructor_nodes == []: return self.add_text(['\n', 'Constructors', '\n', '------------']) for n in constructor_nodes: self.add_text('\n') self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n)) self.subnode_parse(n, pieces = [], indent=4, ignore=['definition', 'name'])
[ "def", "make_constructor_list", "(", "self", ",", "constructor_nodes", ",", "classname", ")", ":", "if", "constructor_nodes", "==", "[", "]", ":", "return", "self", ".", "add_text", "(", "[", "'\\n'", ",", "'Constructors'", ",", "'\\n'", ",", "'------------'",...
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/src/doxy2swig.py#L360-L370
chromiumembedded/cef
80caf947f3fe2210e5344713c5281d8af9bdc295
tools/automate/automate-git.py
python
apply_deps_patch
()
Patch the Chromium DEPS file before `gclient sync` if necessary.
Patch the Chromium DEPS file before `gclient sync` if necessary.
[ "Patch", "the", "Chromium", "DEPS", "file", "before", "gclient", "sync", "if", "necessary", "." ]
def apply_deps_patch(): """ Patch the Chromium DEPS file before `gclient sync` if necessary. """ deps_path = os.path.join(chromium_src_dir, deps_file) if os.path.isfile(deps_path): msg("Chromium DEPS file: %s" % (deps_path)) apply_patch(deps_file) else: raise Exception("Path does not exist: %s" % (deps_path))
[ "def", "apply_deps_patch", "(", ")", ":", "deps_path", "=", "os", ".", "path", ".", "join", "(", "chromium_src_dir", ",", "deps_file", ")", "if", "os", ".", "path", ".", "isfile", "(", "deps_path", ")", ":", "msg", "(", "\"Chromium DEPS file: %s\"", "%", ...
https://github.com/chromiumembedded/cef/blob/80caf947f3fe2210e5344713c5281d8af9bdc295/tools/automate/automate-git.py#L285-L292
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/copyright_scanner/copyright_scanner.py
python
_GetDeletedContents
(affected_file)
return deleted_lines
Returns a list of all deleted lines. AffectedFile class from presubmit_support is lacking this functionality.
Returns a list of all deleted lines. AffectedFile class from presubmit_support is lacking this functionality.
[ "Returns", "a", "list", "of", "all", "deleted", "lines", ".", "AffectedFile", "class", "from", "presubmit_support", "is", "lacking", "this", "functionality", "." ]
def _GetDeletedContents(affected_file): """Returns a list of all deleted lines. AffectedFile class from presubmit_support is lacking this functionality. """ deleted_lines = [] for line in affected_file.GenerateScmDiff().splitlines(): if line.startswith('-') and not line.startswith('--'): deleted_lines.append(line[1:]) return deleted_lines
[ "def", "_GetDeletedContents", "(", "affected_file", ")", ":", "deleted_lines", "=", "[", "]", "for", "line", "in", "affected_file", ".", "GenerateScmDiff", "(", ")", ".", "splitlines", "(", ")", ":", "if", "line", ".", "startswith", "(", "'-'", ")", "and",...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/copyright_scanner/copyright_scanner.py#L328-L336
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/fx/experimental/graph_gradual_typechecker.py
python
Refine.symbolic_relations
(self)
return True
Infers algebraic relations
Infers algebraic relations
[ "Infers", "algebraic", "relations" ]
def symbolic_relations(self): """ Infers algebraic relations """ graph = self.traced.graph for n in graph.nodes: self.infer_symbolic_relations(n) return True
[ "def", "symbolic_relations", "(", "self", ")", ":", "graph", "=", "self", ".", "traced", ".", "graph", "for", "n", "in", "graph", ".", "nodes", ":", "self", ".", "infer_symbolic_relations", "(", "n", ")", "return", "True" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/fx/experimental/graph_gradual_typechecker.py#L786-L793
Slicer/Slicer
ba9fadf332cb0303515b68d8d06a344c82e3e3e5
Modules/Scripted/DICOMLib/DICOMUtils.py
python
getDatabasePatientUIDByPatientID
(patientID)
return None
Get database patient UID by DICOM patient ID for easy loading of a patient
Get database patient UID by DICOM patient ID for easy loading of a patient
[ "Get", "database", "patient", "UID", "by", "DICOM", "patient", "ID", "for", "easy", "loading", "of", "a", "patient" ]
def getDatabasePatientUIDByPatientID(patientID): """ Get database patient UID by DICOM patient ID for easy loading of a patient """ if not slicer.dicomDatabase.isOpen: raise OSError('DICOM module or database cannot be accessed') patients = slicer.dicomDatabase.patients() for patientUID in patients: # Get first file of first series studies = slicer.dicomDatabase.studiesForPatient(patientUID) series = [slicer.dicomDatabase.seriesForStudy(study) for study in studies] seriesUIDs = [uid for uidList in series for uid in uidList] if len(seriesUIDs) == 0: continue filePaths = slicer.dicomDatabase.filesForSeries(seriesUIDs[0], 1) if len(filePaths) == 0: continue firstFile = filePaths[0] # Get PatientID from first file currentPatientID = slicer.dicomDatabase.fileValue(slicer.util.longPath(firstFile), "0010,0020") if currentPatientID == patientID: return patientUID return None
[ "def", "getDatabasePatientUIDByPatientID", "(", "patientID", ")", ":", "if", "not", "slicer", ".", "dicomDatabase", ".", "isOpen", ":", "raise", "OSError", "(", "'DICOM module or database cannot be accessed'", ")", "patients", "=", "slicer", ".", "dicomDatabase", ".",...
https://github.com/Slicer/Slicer/blob/ba9fadf332cb0303515b68d8d06a344c82e3e3e5/Modules/Scripted/DICOMLib/DICOMUtils.py#L100-L122
libornovax/master_thesis_code
6eca474ed3cae673afde010caef338cf7349f839
caffe/python/caffe/net_spec.py
python
param_name_dict
()
return dict(zip(param_type_names, param_names))
Find out the correspondence between layer names and parameter names.
Find out the correspondence between layer names and parameter names.
[ "Find", "out", "the", "correspondence", "between", "layer", "names", "and", "parameter", "names", "." ]
def param_name_dict(): """Find out the correspondence between layer names and parameter names.""" layer = caffe_pb2.LayerParameter() # get all parameter names (typically underscore case) and corresponding # type names (typically camel case), which contain the layer names # (note that not all parameters correspond to layers, but we'll ignore that) param_names = [f.name for f in layer.DESCRIPTOR.fields if f.name.endswith('_param')] param_type_names = [type(getattr(layer, s)).__name__ for s in param_names] # strip the final '_param' or 'Parameter' param_names = [s[:-len('_param')] for s in param_names] param_type_names = [s[:-len('Parameter')] for s in param_type_names] return dict(zip(param_type_names, param_names))
[ "def", "param_name_dict", "(", ")", ":", "layer", "=", "caffe_pb2", ".", "LayerParameter", "(", ")", "# get all parameter names (typically underscore case) and corresponding", "# type names (typically camel case), which contain the layer names", "# (note that not all parameters correspon...
https://github.com/libornovax/master_thesis_code/blob/6eca474ed3cae673afde010caef338cf7349f839/caffe/python/caffe/net_spec.py#L28-L40
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/ultimatelistctrl.py
python
UltimateListHeaderWindow.SetCustomRenderer
(self, renderer=None)
Associate a custom renderer with the header - all columns will use it :param `renderer`: a class able to correctly render header buttons :note: the renderer class **must** implement the methods `DrawHeaderButton` and `GetForegroundColor`.
Associate a custom renderer with the header - all columns will use it
[ "Associate", "a", "custom", "renderer", "with", "the", "header", "-", "all", "columns", "will", "use", "it" ]
def SetCustomRenderer(self, renderer=None): """ Associate a custom renderer with the header - all columns will use it :param `renderer`: a class able to correctly render header buttons :note: the renderer class **must** implement the methods `DrawHeaderButton` and `GetForegroundColor`. """ if not self._owner.HasAGWFlag(ULC_REPORT): raise Exception("Custom renderers can be used on with style = ULC_REPORT") self._headerCustomRenderer = renderer
[ "def", "SetCustomRenderer", "(", "self", ",", "renderer", "=", "None", ")", ":", "if", "not", "self", ".", "_owner", ".", "HasAGWFlag", "(", "ULC_REPORT", ")", ":", "raise", "Exception", "(", "\"Custom renderers can be used on with style = ULC_REPORT\"", ")", "sel...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L5018-L5031
uber/neuropod
de304c40ec0634a868d7ef41ba7bf89ebc364f10
source/python/neuropod/backends/python/packager.py
python
create_python_neuropod
( neuropod_path, data_paths, code_path_spec, entrypoint_package, entrypoint, requirements=None, **kwargs )
Packages arbitrary python code as a neuropod package. {common_doc_pre} :param data_paths: A list of dicts containing the paths to any data files that needs to be packaged. !!! note "" ***Example***: ``` [{ path: "/path/to/myfile.txt", packaged_name: "newfilename.txt" }] ``` :param code_path_spec: The folder paths of all the code that will be packaged. Note that *.pyc files are ignored. !!! note "" This is specified as follows: ``` [{ "python_root": "/some/path/to/a/python/root", "dirs_to_package": ["relative/path/to/package"] }, ...] ``` :param entrypoint_package: The python package containing the entrypoint (e.g. some.package.something). This must contain the entrypoint function specified below. :param entrypoint: The name of a function contained in the `entrypoint_package`. This function must return a callable that takes in the inputs specified in `input_spec` and returns a dict containing the outputs specified in `output_spec`. The `entrypoint` function will be provided the path to a directory containing the packaged data as its first parameter. !!! note "" For example, a function like: ``` def neuropod_init(data_path): def addition_model(x, y): return { "output": x + y } return addition_model ``` contained in the package 'my.awesome.addition_model' would have `entrypoint_package='my.awesome.addition_model'` and `entrypoint='neuropod_init'` :param requirements: An optional string containing the runtime requirements of this model (specified in a format that pip understands) !!! note "" ***Example***: ``` tensorflow=1.15.0 numpy=1.8 ``` {common_doc_post}
Packages arbitrary python code as a neuropod package.
[ "Packages", "arbitrary", "python", "code", "as", "a", "neuropod", "package", "." ]
def create_python_neuropod( neuropod_path, data_paths, code_path_spec, entrypoint_package, entrypoint, requirements=None, **kwargs ): """ Packages arbitrary python code as a neuropod package. {common_doc_pre} :param data_paths: A list of dicts containing the paths to any data files that needs to be packaged. !!! note "" ***Example***: ``` [{ path: "/path/to/myfile.txt", packaged_name: "newfilename.txt" }] ``` :param code_path_spec: The folder paths of all the code that will be packaged. Note that *.pyc files are ignored. !!! note "" This is specified as follows: ``` [{ "python_root": "/some/path/to/a/python/root", "dirs_to_package": ["relative/path/to/package"] }, ...] ``` :param entrypoint_package: The python package containing the entrypoint (e.g. some.package.something). This must contain the entrypoint function specified below. :param entrypoint: The name of a function contained in the `entrypoint_package`. This function must return a callable that takes in the inputs specified in `input_spec` and returns a dict containing the outputs specified in `output_spec`. The `entrypoint` function will be provided the path to a directory containing the packaged data as its first parameter. !!! note "" For example, a function like: ``` def neuropod_init(data_path): def addition_model(x, y): return { "output": x + y } return addition_model ``` contained in the package 'my.awesome.addition_model' would have `entrypoint_package='my.awesome.addition_model'` and `entrypoint='neuropod_init'` :param requirements: An optional string containing the runtime requirements of this model (specified in a format that pip understands) !!! note "" ***Example***: ``` tensorflow=1.15.0 numpy=1.8 ``` {common_doc_post} """ neuropod_data_path = os.path.join(neuropod_path, "0", "data") neuropod_code_path = os.path.join(neuropod_path, "0", "code") # Create a folder to store the packaged data os.makedirs(neuropod_data_path) # Copy the data to be packaged for data_path_spec in data_paths: shutil.copyfile( data_path_spec["path"], os.path.join(neuropod_data_path, data_path_spec["packaged_name"]), ) # Copy the specified source code while preserving package paths for copy_spec in code_path_spec: python_root = copy_spec["python_root"] if os.path.realpath(neuropod_path).startswith( os.path.realpath(python_root) + os.sep ): raise ValueError( "`neuropod_path` cannot be a subdirectory of `python_root`" ) for dir_to_package in copy_spec["dirs_to_package"]: shutil.copytree( os.path.join(python_root, dir_to_package), os.path.join(neuropod_code_path, dir_to_package), ignore=shutil.ignore_patterns("*.pyc"), ) # Add __init__.py files as needed for root, subdirs, files in os.walk(neuropod_code_path): if "__init__.py" not in files: with open(os.path.join(root, "__init__.py"), "w"): # We just need to create the file pass # Save requirements if specified if requirements is not None: # Write requirements to a temp file with tempfile.NamedTemporaryFile() as requirements_txt: requirements_txt.write(requirements.encode("utf-8")) requirements_txt.flush() # Write the lockfile lock_path = os.path.join(neuropod_path, "0", "requirements.lock") compile_requirements(requirements_txt.name, lock_path) # We also need to save the entrypoint package name so we know what to load at runtime # This is python specific config so it's not saved in the overall neuropod config with open(os.path.join(neuropod_path, "0", "config.json"), "w") as config_file: json.dump( {"entrypoint_package": entrypoint_package, "entrypoint": entrypoint}, config_file, )
[ "def", "create_python_neuropod", "(", "neuropod_path", ",", "data_paths", ",", "code_path_spec", ",", "entrypoint_package", ",", "entrypoint", ",", "requirements", "=", "None", ",", "*", "*", "kwargs", ")", ":", "neuropod_data_path", "=", "os", ".", "path", ".",...
https://github.com/uber/neuropod/blob/de304c40ec0634a868d7ef41ba7bf89ebc364f10/source/python/neuropod/backends/python/packager.py#L25-L157
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/compat/__init__.py
python
set_function_name
(f, name, cls)
return f
Bind the name/qualname attributes of the function.
Bind the name/qualname attributes of the function.
[ "Bind", "the", "name", "/", "qualname", "attributes", "of", "the", "function", "." ]
def set_function_name(f, name, cls): """ Bind the name/qualname attributes of the function. """ f.__name__ = name f.__qualname__ = f"{cls.__name__}.{name}" f.__module__ = cls.__module__ return f
[ "def", "set_function_name", "(", "f", ",", "name", ",", "cls", ")", ":", "f", ".", "__name__", "=", "name", "f", ".", "__qualname__", "=", "f\"{cls.__name__}.{name}\"", "f", ".", "__module__", "=", "cls", ".", "__module__", "return", "f" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/compat/__init__.py#L28-L35
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distro.py
python
LinuxDistribution.os_release_info
(self)
return self._os_release_info
Return a dictionary containing key-value pairs for the information items from the os-release file data source of the OS distribution. For details, see :func:`distro.os_release_info`.
[]
def os_release_info(self): """ Return a dictionary containing key-value pairs for the information items from the os-release file data source of the OS distribution. For details, see :func:`distro.os_release_info`. """ return self._os_release_info
[ "def", "os_release_info", "(", "self", ")", ":", "return", "self", ".", "_os_release_info" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distro.py#L1697-L1711
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/ElementalAnalysis/LoadWidget/load_utils.py
python
LModel._load
(self, inputs)
inputs is a dict mapping filepaths to output names
inputs is a dict mapping filepaths to output names
[ "inputs", "is", "a", "dict", "mapping", "filepaths", "to", "output", "names" ]
def _load(self, inputs): """ inputs is a dict mapping filepaths to output names """ for path, output in inputs.items(): workspace = mantid.LoadAscii(path, OutputWorkspace=output) workspace.getAxis(0).setUnit("Label").setLabel("Energy", "keV")
[ "def", "_load", "(", "self", ",", "inputs", ")", ":", "for", "path", ",", "output", "in", "inputs", ".", "items", "(", ")", ":", "workspace", "=", "mantid", ".", "LoadAscii", "(", "path", ",", "OutputWorkspace", "=", "output", ")", "workspace", ".", ...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/ElementalAnalysis/LoadWidget/load_utils.py#L27-L31
apache/impala
8ddac48f3428c86f2cbd037ced89cfb903298b12
shell/impala_shell.py
python
ImpalaShell.do_rerun
(self, args)
return self.onecmd(cmd.rstrip(";"))
Rerun a command with an command index in history Example: @1;
Rerun a command with an command index in history Example:
[ "Rerun", "a", "command", "with", "an", "command", "index", "in", "history", "Example", ":" ]
def do_rerun(self, args): """Rerun a command with an command index in history Example: @1; """ history_len = self.readline.get_current_history_length() # Rerun command shouldn't appear in history self.readline.remove_history_item(history_len - 1) history_len -= 1 if not self.readline: print(READLINE_UNAVAILABLE_ERROR, file=sys.stderr) return CmdStatus.ERROR try: cmd_idx = int(args) except ValueError: print("Command index to be rerun must be an integer.", file=sys.stderr) return CmdStatus.ERROR if not (0 < cmd_idx <= history_len or -history_len <= cmd_idx < 0): print("Command index out of range. Valid range: [1, {0}] and [-{0}, -1]" .format(history_len), file=sys.stderr) return CmdStatus.ERROR if cmd_idx < 0: cmd_idx += history_len + 1 cmd = self.readline.get_history_item(cmd_idx) print("Rerunning " + cmd, file=sys.stderr) return self.onecmd(cmd.rstrip(";"))
[ "def", "do_rerun", "(", "self", ",", "args", ")", ":", "history_len", "=", "self", ".", "readline", ".", "get_current_history_length", "(", ")", "# Rerun command shouldn't appear in history", "self", ".", "readline", ".", "remove_history_item", "(", "history_len", "...
https://github.com/apache/impala/blob/8ddac48f3428c86f2cbd037ced89cfb903298b12/shell/impala_shell.py#L1506-L1530
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/contrib/learn/python/learn/evaluable.py
python
Evaluable.evaluate
( self, x=None, y=None, input_fn=None, feed_fn=None, batch_size=None, steps=None, metrics=None, name=None)
Evaluates given model with provided evaluation data. Evaluates on the given input data. If `input_fn` is provided, that input function should raise an end-of-input exception (`OutOfRangeError` or `StopIteration`) after one epoch of the training data has been provided. By default, the whole evaluation dataset is used. If `steps` is provided, only `steps` batches of size `batch_size` are processed. The return value is a dict containing the metrics specified in `metrics`, as well as an entry `global_step` which contains the value of the global step for which this evaluation was performed. Args: x: Matrix of shape [n_samples, n_features...]. Can be iterator that returns arrays of features. The training input samples for fitting the model. If set, `input_fn` must be `None`. y: Vector or matrix [n_samples] or [n_samples, n_outputs]. Can be iterator that returns array of targets. The training target values (class labels in classification, real numbers in regression). If set, `input_fn` must be `None`. input_fn: Input function. If set, `x`, `y`, and `batch_size` must be `None`. feed_fn: Function creating a feed dict every time it is called. Called once per iteration. Must be `None` if `input_fn` is provided. batch_size: minibatch size to use on the input, defaults to first dimension of `x`, if specified. Must be `None` if `input_fn` is provided. steps: Number of steps for which to evaluate model. If `None`, evaluate until running tensors generated by `metrics` raises an exception. metrics: Dict of metric ops to run. If `None`, the default metric functions are used; if `{}`, no metrics are used. If model has one output (i.e., returning single predction), keys are `str`, e.g. `'accuracy'` - just a name of the metric that will show up in the logs / summaries. Otherwise, keys are tuple of two `str`, e.g. `('accuracy', 'classes')`- name of the metric and name of `Tensor` in the predictions to run this metric on. Metric ops should support streaming, e.g., returning update_op and value tensors. See more details in ../../../metrics/python/metrics/ops/streaming_metrics.py. name: Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Returns: Returns `dict` with evaluation results.
Evaluates given model with provided evaluation data.
[ "Evaluates", "given", "model", "with", "provided", "evaluation", "data", "." ]
def evaluate( self, x=None, y=None, input_fn=None, feed_fn=None, batch_size=None, steps=None, metrics=None, name=None): """Evaluates given model with provided evaluation data. Evaluates on the given input data. If `input_fn` is provided, that input function should raise an end-of-input exception (`OutOfRangeError` or `StopIteration`) after one epoch of the training data has been provided. By default, the whole evaluation dataset is used. If `steps` is provided, only `steps` batches of size `batch_size` are processed. The return value is a dict containing the metrics specified in `metrics`, as well as an entry `global_step` which contains the value of the global step for which this evaluation was performed. Args: x: Matrix of shape [n_samples, n_features...]. Can be iterator that returns arrays of features. The training input samples for fitting the model. If set, `input_fn` must be `None`. y: Vector or matrix [n_samples] or [n_samples, n_outputs]. Can be iterator that returns array of targets. The training target values (class labels in classification, real numbers in regression). If set, `input_fn` must be `None`. input_fn: Input function. If set, `x`, `y`, and `batch_size` must be `None`. feed_fn: Function creating a feed dict every time it is called. Called once per iteration. Must be `None` if `input_fn` is provided. batch_size: minibatch size to use on the input, defaults to first dimension of `x`, if specified. Must be `None` if `input_fn` is provided. steps: Number of steps for which to evaluate model. If `None`, evaluate until running tensors generated by `metrics` raises an exception. metrics: Dict of metric ops to run. If `None`, the default metric functions are used; if `{}`, no metrics are used. If model has one output (i.e., returning single predction), keys are `str`, e.g. `'accuracy'` - just a name of the metric that will show up in the logs / summaries. Otherwise, keys are tuple of two `str`, e.g. `('accuracy', 'classes')`- name of the metric and name of `Tensor` in the predictions to run this metric on. Metric ops should support streaming, e.g., returning update_op and value tensors. See more details in ../../../metrics/python/metrics/ops/streaming_metrics.py. name: Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Returns: Returns `dict` with evaluation results. """ raise NotImplementedError
[ "def", "evaluate", "(", "self", ",", "x", "=", "None", ",", "y", "=", "None", ",", "input_fn", "=", "None", ",", "feed_fn", "=", "None", ",", "batch_size", "=", "None", ",", "steps", "=", "None", ",", "metrics", "=", "None", ",", "name", "=", "No...
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/learn/python/learn/evaluable.py#L31-L81
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/smtplib.py
python
SMTP.help
(self, args='')
return self.getreply()[1]
SMTP 'help' command. Returns help text from server.
SMTP 'help' command. Returns help text from server.
[ "SMTP", "help", "command", ".", "Returns", "help", "text", "from", "server", "." ]
def help(self, args=''): """SMTP 'help' command. Returns help text from server.""" self.putcmd("help", args) return self.getreply()[1]
[ "def", "help", "(", "self", ",", "args", "=", "''", ")", ":", "self", ".", "putcmd", "(", "\"help\"", ",", "args", ")", "return", "self", ".", "getreply", "(", ")", "[", "1", "]" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/smtplib.py#L453-L457
Z3Prover/z3
d745d03afdfdf638d66093e2bfbacaf87187f35b
src/api/python/z3/z3num.py
python
Numeral.__ne__
(self, other)
return Z3_algebraic_neq(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast)
Return True if `self != other`. >>> Numeral(Sqrt(2)) != 2 True >>> Numeral(Sqrt(3)) != Numeral(Sqrt(2)) True >>> Numeral(Sqrt(2)) != Numeral(Sqrt(2)) False
Return True if `self != other`.
[ "Return", "True", "if", "self", "!", "=", "other", "." ]
def __ne__(self, other): """ Return True if `self != other`. >>> Numeral(Sqrt(2)) != 2 True >>> Numeral(Sqrt(3)) != Numeral(Sqrt(2)) True >>> Numeral(Sqrt(2)) != Numeral(Sqrt(2)) False """ return Z3_algebraic_neq(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast)
[ "def", "__ne__", "(", "self", ",", "other", ")", ":", "return", "Z3_algebraic_neq", "(", "self", ".", "ctx_ref", "(", ")", ",", "self", ".", "ast", ",", "_to_numeral", "(", "other", ",", "self", ".", "ctx", ")", ".", "ast", ")" ]
https://github.com/Z3Prover/z3/blob/d745d03afdfdf638d66093e2bfbacaf87187f35b/src/api/python/z3/z3num.py#L497-L507
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
demo/Grid_MegaExample.py
python
MegaGrid.rowPopup
(self, row, evt)
return
(row, evt) -> display a popup menu when a row label is right clicked
(row, evt) -> display a popup menu when a row label is right clicked
[ "(", "row", "evt", ")", "-", ">", "display", "a", "popup", "menu", "when", "a", "row", "label", "is", "right", "clicked" ]
def rowPopup(self, row, evt): """(row, evt) -> display a popup menu when a row label is right clicked""" appendID = wx.NewId() deleteID = wx.NewId() x = self.GetRowSize(row)/2 if not self.GetSelectedRows(): self.SelectRow(row) menu = wx.Menu() xo, yo = evt.GetPosition() menu.Append(appendID, "Append Row") menu.Append(deleteID, "Delete Row(s)") def append(event, self=self, row=row): self._table.AppendRow(row) self.Reset() def delete(event, self=self, row=row): rows = self.GetSelectedRows() self._table.DeleteRows(rows) self.Reset() self.Bind(wx.EVT_MENU, append, id=appendID) self.Bind(wx.EVT_MENU, delete, id=deleteID) self.PopupMenu(menu) menu.Destroy() return
[ "def", "rowPopup", "(", "self", ",", "row", ",", "evt", ")", ":", "appendID", "=", "wx", ".", "NewId", "(", ")", "deleteID", "=", "wx", ".", "NewId", "(", ")", "x", "=", "self", ".", "GetRowSize", "(", "row", ")", "/", "2", "if", "not", "self",...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/demo/Grid_MegaExample.py#L332-L359
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/contrib/distributions/python/ops/mvn.py
python
MultivariateNormalOperatorPD.validate_args
(self)
return self._validate_args
`Boolean` describing behavior on invalid input.
`Boolean` describing behavior on invalid input.
[ "Boolean", "describing", "behavior", "on", "invalid", "input", "." ]
def validate_args(self): """`Boolean` describing behavior on invalid input.""" return self._validate_args
[ "def", "validate_args", "(", "self", ")", ":", "return", "self", ".", "_validate_args" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/mvn.py#L174-L176
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/s3fs/core.py
python
S3FileSystem.checksum
(self, path, refresh=False)
Unique value for current version of file If the checksum is the same from one moment to another, the contents are guaranteed to be the same. If the checksum changes, the contents *might* have changed. Parameters ---------- path : string/bytes path of file to get checksum for refresh : bool (=False) if False, look in local cache for file details first
Unique value for current version of file
[ "Unique", "value", "for", "current", "version", "of", "file" ]
def checksum(self, path, refresh=False): """ Unique value for current version of file If the checksum is the same from one moment to another, the contents are guaranteed to be the same. If the checksum changes, the contents *might* have changed. Parameters ---------- path : string/bytes path of file to get checksum for refresh : bool (=False) if False, look in local cache for file details first """ info = self.info(path, refresh=refresh) if info["type"] != 'directory': return int(info["ETag"].strip('"'), 16) else: return int(tokenize(info), 16)
[ "def", "checksum", "(", "self", ",", "path", ",", "refresh", "=", "False", ")", ":", "info", "=", "self", ".", "info", "(", "path", ",", "refresh", "=", "refresh", ")", "if", "info", "[", "\"type\"", "]", "!=", "'directory'", ":", "return", "int", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/s3fs/core.py#L553-L575
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
src/pybind/mgr/dashboard/services/access_control.py
python
ac_user_delete_cmd
(_, username: str)
Delete user
Delete user
[ "Delete", "user" ]
def ac_user_delete_cmd(_, username: str): ''' Delete user ''' try: mgr.ACCESS_CTRL_DB.delete_user(username) mgr.ACCESS_CTRL_DB.save() return 0, "User '{}' deleted".format(username), "" except UserDoesNotExist as ex: return -errno.ENOENT, '', str(ex)
[ "def", "ac_user_delete_cmd", "(", "_", ",", "username", ":", "str", ")", ":", "try", ":", "mgr", ".", "ACCESS_CTRL_DB", ".", "delete_user", "(", "username", ")", "mgr", ".", "ACCESS_CTRL_DB", ".", "save", "(", ")", "return", "0", ",", "\"User '{}' deleted\...
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/pybind/mgr/dashboard/services/access_control.py#L787-L796
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/keras/engine/training_v1.py
python
Model.get_weights
(self)
return base_layer.Layer.get_weights(self)
Retrieves the weights of the model. Returns: A flat list of Numpy arrays.
Retrieves the weights of the model.
[ "Retrieves", "the", "weights", "of", "the", "model", "." ]
def get_weights(self): """Retrieves the weights of the model. Returns: A flat list of Numpy arrays. """ strategy = (self._distribution_strategy or self._compile_time_distribution_strategy) if strategy: with strategy.scope(): return base_layer.Layer.get_weights(self) return base_layer.Layer.get_weights(self)
[ "def", "get_weights", "(", "self", ")", ":", "strategy", "=", "(", "self", ".", "_distribution_strategy", "or", "self", ".", "_compile_time_distribution_strategy", ")", "if", "strategy", ":", "with", "strategy", ".", "scope", "(", ")", ":", "return", "base_lay...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/engine/training_v1.py#L168-L179
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/combo.py
python
ComboPopup.GetAdjustedSize
(*args, **kwargs)
return _combo.ComboPopup_GetAdjustedSize(*args, **kwargs)
GetAdjustedSize(self, int minWidth, int prefHeight, int maxHeight) -> Size The derived class may implement this method to return adjusted size for the popup control, according to the variables given. It is called on every popup, just prior to `OnPopup`. :param minWidth: Preferred minimum width. :param prefHeight: Preferred height. May be -1 to indicate no preference. :maxWidth: Max height for window, as limited by screen size, and should only be rounded down, if necessary.
GetAdjustedSize(self, int minWidth, int prefHeight, int maxHeight) -> Size
[ "GetAdjustedSize", "(", "self", "int", "minWidth", "int", "prefHeight", "int", "maxHeight", ")", "-", ">", "Size" ]
def GetAdjustedSize(*args, **kwargs): """ GetAdjustedSize(self, int minWidth, int prefHeight, int maxHeight) -> Size The derived class may implement this method to return adjusted size for the popup control, according to the variables given. It is called on every popup, just prior to `OnPopup`. :param minWidth: Preferred minimum width. :param prefHeight: Preferred height. May be -1 to indicate no preference. :maxWidth: Max height for window, as limited by screen size, and should only be rounded down, if necessary. """ return _combo.ComboPopup_GetAdjustedSize(*args, **kwargs)
[ "def", "GetAdjustedSize", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_combo", ".", "ComboPopup_GetAdjustedSize", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/combo.py#L721-L735
bulletphysics/bullet3
f0f2a952e146f016096db6f85cf0c44ed75b0b9a
examples/pybullet/gym/pybullet_envs/agents/tools/in_graph_batch_env.py
python
InGraphBatchEnv.reset
(self, indices=None)
Reset the batch of environments. Args: indices: The batch indices of the environments to reset; defaults to all. Returns: Batch tensor of the new observations.
Reset the batch of environments.
[ "Reset", "the", "batch", "of", "environments", "." ]
def reset(self, indices=None): """Reset the batch of environments. Args: indices: The batch indices of the environments to reset; defaults to all. Returns: Batch tensor of the new observations. """ if indices is None: indices = tf.range(len(self._batch_env)) observ_dtype = self._parse_dtype(self._batch_env.observation_space) observ = tf.py_func(self._batch_env.reset, [indices], observ_dtype, name='reset') observ = tf.check_numerics(observ, 'observ') reward = tf.zeros_like(indices, tf.float32) done = tf.zeros_like(indices, tf.bool) with tf.control_dependencies([ tf.scatter_update(self._observ, indices, observ), tf.scatter_update(self._reward, indices, reward), tf.scatter_update(self._done, indices, done) ]): return tf.identity(observ)
[ "def", "reset", "(", "self", ",", "indices", "=", "None", ")", ":", "if", "indices", "is", "None", ":", "indices", "=", "tf", ".", "range", "(", "len", "(", "self", ".", "_batch_env", ")", ")", "observ_dtype", "=", "self", ".", "_parse_dtype", "(", ...
https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/agents/tools/in_graph_batch_env.py#L102-L123
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/contrib/learn/python/learn/graph_actions.py
python
get_summary_writer
(logdir)
return summary_writer_cache.SummaryWriterCache.get(logdir)
Returns single SummaryWriter per logdir in current run. Args: logdir: str, folder to write summaries. Returns: Existing `SummaryWriter` object or new one if never wrote to given directory.
Returns single SummaryWriter per logdir in current run.
[ "Returns", "single", "SummaryWriter", "per", "logdir", "in", "current", "run", "." ]
def get_summary_writer(logdir): """Returns single SummaryWriter per logdir in current run. Args: logdir: str, folder to write summaries. Returns: Existing `SummaryWriter` object or new one if never wrote to given directory. """ return summary_writer_cache.SummaryWriterCache.get(logdir)
[ "def", "get_summary_writer", "(", "logdir", ")", ":", "return", "summary_writer_cache", ".", "SummaryWriterCache", ".", "get", "(", "logdir", ")" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/learn/python/learn/graph_actions.py#L65-L75
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/pkg_resources/_vendor/pyparsing.py
python
tokenMap
(func, *args)
return pa
Helper to define a parse action by mapping a function to all elements of a ParseResults list.If any additional args are passed, they are forwarded to the given function as additional arguments after the token, as in C{hex_integer = Word(hexnums).setParseAction(tokenMap(int, 16))}, which will convert the parsed data to an integer using base 16. Example (compare the last to example in L{ParserElement.transformString}:: hex_ints = OneOrMore(Word(hexnums)).setParseAction(tokenMap(int, 16)) hex_ints.runTests(''' 00 11 22 aa FF 0a 0d 1a ''') upperword = Word(alphas).setParseAction(tokenMap(str.upper)) OneOrMore(upperword).runTests(''' my kingdom for a horse ''') wd = Word(alphas).setParseAction(tokenMap(str.title)) OneOrMore(wd).setParseAction(' '.join).runTests(''' now is the winter of our discontent made glorious summer by this sun of york ''') prints:: 00 11 22 aa FF 0a 0d 1a [0, 17, 34, 170, 255, 10, 13, 26] my kingdom for a horse ['MY', 'KINGDOM', 'FOR', 'A', 'HORSE'] now is the winter of our discontent made glorious summer by this sun of york ['Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York']
Helper to define a parse action by mapping a function to all elements of a ParseResults list.If any additional args are passed, they are forwarded to the given function as additional arguments after the token, as in C{hex_integer = Word(hexnums).setParseAction(tokenMap(int, 16))}, which will convert the parsed data to an integer using base 16.
[ "Helper", "to", "define", "a", "parse", "action", "by", "mapping", "a", "function", "to", "all", "elements", "of", "a", "ParseResults", "list", ".", "If", "any", "additional", "args", "are", "passed", "they", "are", "forwarded", "to", "the", "given", "func...
def tokenMap(func, *args): """ Helper to define a parse action by mapping a function to all elements of a ParseResults list.If any additional args are passed, they are forwarded to the given function as additional arguments after the token, as in C{hex_integer = Word(hexnums).setParseAction(tokenMap(int, 16))}, which will convert the parsed data to an integer using base 16. Example (compare the last to example in L{ParserElement.transformString}:: hex_ints = OneOrMore(Word(hexnums)).setParseAction(tokenMap(int, 16)) hex_ints.runTests(''' 00 11 22 aa FF 0a 0d 1a ''') upperword = Word(alphas).setParseAction(tokenMap(str.upper)) OneOrMore(upperword).runTests(''' my kingdom for a horse ''') wd = Word(alphas).setParseAction(tokenMap(str.title)) OneOrMore(wd).setParseAction(' '.join).runTests(''' now is the winter of our discontent made glorious summer by this sun of york ''') prints:: 00 11 22 aa FF 0a 0d 1a [0, 17, 34, 170, 255, 10, 13, 26] my kingdom for a horse ['MY', 'KINGDOM', 'FOR', 'A', 'HORSE'] now is the winter of our discontent made glorious summer by this sun of york ['Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York'] """ def pa(s,l,t): return [func(tokn, *args) for tokn in t] try: func_name = getattr(func, '__name__', getattr(func, '__class__').__name__) except Exception: func_name = str(func) pa.__name__ = func_name return pa
[ "def", "tokenMap", "(", "func", ",", "*", "args", ")", ":", "def", "pa", "(", "s", ",", "l", ",", "t", ")", ":", "return", "[", "func", "(", "tokn", ",", "*", "args", ")", "for", "tokn", "in", "t", "]", "try", ":", "func_name", "=", "getattr"...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/pkg_resources/_vendor/pyparsing.py#L4825-L4867
sdhash/sdhash
b9eff63e4e5867e910f41fd69032bbb1c94a2a5e
sdhash-ui/cherrypy/lib/jsontools.py
python
json_in
(content_type=[ntou('application/json'), ntou('text/javascript')], force=True, debug=False, processor = json_processor)
Add a processor to parse JSON request entities: The default processor places the parsed data into request.json. Incoming request entities which match the given content_type(s) will be deserialized from JSON to the Python equivalent, and the result stored at cherrypy.request.json. The 'content_type' argument may be a Content-Type string or a list of allowable Content-Type strings. If the 'force' argument is True (the default), then entities of other content types will not be allowed; "415 Unsupported Media Type" is raised instead. Supply your own processor to use a custom decoder, or to handle the parsed data differently. The processor can be configured via tools.json_in.processor or via the decorator method. Note that the deserializer requires the client send a Content-Length request header, or it will raise "411 Length Required". If for any other reason the request entity cannot be deserialized from JSON, it will raise "400 Bad Request: Invalid JSON document". You must be using Python 2.6 or greater, or have the 'simplejson' package importable; otherwise, ValueError is raised during processing.
Add a processor to parse JSON request entities: The default processor places the parsed data into request.json.
[ "Add", "a", "processor", "to", "parse", "JSON", "request", "entities", ":", "The", "default", "processor", "places", "the", "parsed", "data", "into", "request", ".", "json", "." ]
def json_in(content_type=[ntou('application/json'), ntou('text/javascript')], force=True, debug=False, processor = json_processor): """Add a processor to parse JSON request entities: The default processor places the parsed data into request.json. Incoming request entities which match the given content_type(s) will be deserialized from JSON to the Python equivalent, and the result stored at cherrypy.request.json. The 'content_type' argument may be a Content-Type string or a list of allowable Content-Type strings. If the 'force' argument is True (the default), then entities of other content types will not be allowed; "415 Unsupported Media Type" is raised instead. Supply your own processor to use a custom decoder, or to handle the parsed data differently. The processor can be configured via tools.json_in.processor or via the decorator method. Note that the deserializer requires the client send a Content-Length request header, or it will raise "411 Length Required". If for any other reason the request entity cannot be deserialized from JSON, it will raise "400 Bad Request: Invalid JSON document". You must be using Python 2.6 or greater, or have the 'simplejson' package importable; otherwise, ValueError is raised during processing. """ request = cherrypy.serving.request if isinstance(content_type, basestring): content_type = [content_type] if force: if debug: cherrypy.log('Removing body processors %s' % repr(request.body.processors.keys()), 'TOOLS.JSON_IN') request.body.processors.clear() request.body.default_proc = cherrypy.HTTPError( 415, 'Expected an entity of content type %s' % ', '.join(content_type)) for ct in content_type: if debug: cherrypy.log('Adding body processor for %s' % ct, 'TOOLS.JSON_IN') request.body.processors[ct] = processor
[ "def", "json_in", "(", "content_type", "=", "[", "ntou", "(", "'application/json'", ")", ",", "ntou", "(", "'text/javascript'", ")", "]", ",", "force", "=", "True", ",", "debug", "=", "False", ",", "processor", "=", "json_processor", ")", ":", "request", ...
https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-ui/cherrypy/lib/jsontools.py#L16-L58
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/arrayobj.py
python
_array_copy
(context, builder, sig, args)
return impl_ret_new_ref(context, builder, sig.return_type, ret._getvalue())
Array copy.
Array copy.
[ "Array", "copy", "." ]
def _array_copy(context, builder, sig, args): """ Array copy. """ arytype = sig.args[0] ary = make_array(arytype)(context, builder, value=args[0]) shapes = cgutils.unpack_tuple(builder, ary.shape) rettype = sig.return_type ret = _empty_nd_impl(context, builder, rettype, shapes) src_data = ary.data dest_data = ret.data assert rettype.layout in "CF" if arytype.layout == rettype.layout: # Fast path: memcpy cgutils.raw_memcpy(builder, dest_data, src_data, ary.nitems, ary.itemsize, align=1) else: src_strides = cgutils.unpack_tuple(builder, ary.strides) dest_strides = cgutils.unpack_tuple(builder, ret.strides) intp_t = context.get_value_type(types.intp) with cgutils.loop_nest(builder, shapes, intp_t) as indices: src_ptr = cgutils.get_item_pointer2(context, builder, src_data, shapes, src_strides, arytype.layout, indices) dest_ptr = cgutils.get_item_pointer2(context, builder, dest_data, shapes, dest_strides, rettype.layout, indices) builder.store(builder.load(src_ptr), dest_ptr) return impl_ret_new_ref(context, builder, sig.return_type, ret._getvalue())
[ "def", "_array_copy", "(", "context", ",", "builder", ",", "sig", ",", "args", ")", ":", "arytype", "=", "sig", ".", "args", "[", "0", "]", "ary", "=", "make_array", "(", "arytype", ")", "(", "context", ",", "builder", ",", "value", "=", "args", "[...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/arrayobj.py#L3934-L3968
NervanaSystems/ngraph
f677a119765ca30636cf407009dabd118664951f
python/src/ngraph/ops.py
python
selu
( data: NodeInput, alpha: NodeInput, lambda_value: NodeInput, name: Optional[str] = None )
return _get_node_factory().create("Selu", as_nodes(data, alpha, lambda_value))
Perform a Scaled Exponential Linear Unit (SELU) operation on input node element-wise. :param data: input node, array or scalar. :param alpha: Alpha coefficient of SELU operation :param lambda_value: Lambda coefficient of SELU operation :param name: The optional output node name. :return: The new node performing relu operation on its input element-wise.
Perform a Scaled Exponential Linear Unit (SELU) operation on input node element-wise.
[ "Perform", "a", "Scaled", "Exponential", "Linear", "Unit", "(", "SELU", ")", "operation", "on", "input", "node", "element", "-", "wise", "." ]
def selu( data: NodeInput, alpha: NodeInput, lambda_value: NodeInput, name: Optional[str] = None ) -> Node: """Perform a Scaled Exponential Linear Unit (SELU) operation on input node element-wise. :param data: input node, array or scalar. :param alpha: Alpha coefficient of SELU operation :param lambda_value: Lambda coefficient of SELU operation :param name: The optional output node name. :return: The new node performing relu operation on its input element-wise. """ return _get_node_factory().create("Selu", as_nodes(data, alpha, lambda_value))
[ "def", "selu", "(", "data", ":", "NodeInput", ",", "alpha", ":", "NodeInput", ",", "lambda_value", ":", "NodeInput", ",", "name", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "Node", ":", "return", "_get_node_factory", "(", ")", ".", "crea...
https://github.com/NervanaSystems/ngraph/blob/f677a119765ca30636cf407009dabd118664951f/python/src/ngraph/ops.py#L932-L943
chipsalliance/verible
aa14e0074ff89945bf65eecfb9ef78684d996058
third_party/py/dataclasses/dataclasses/__init__.py
python
is_dataclass
(obj)
return hasattr(obj, _FIELDS)
Returns True if obj is a dataclass or an instance of a dataclass.
Returns True if obj is a dataclass or an instance of a dataclass.
[ "Returns", "True", "if", "obj", "is", "a", "dataclass", "or", "an", "instance", "of", "a", "dataclass", "." ]
def is_dataclass(obj): """Returns True if obj is a dataclass or an instance of a dataclass.""" return hasattr(obj, _FIELDS)
[ "def", "is_dataclass", "(", "obj", ")", ":", "return", "hasattr", "(", "obj", ",", "_FIELDS", ")" ]
https://github.com/chipsalliance/verible/blob/aa14e0074ff89945bf65eecfb9ef78684d996058/third_party/py/dataclasses/dataclasses/__init__.py#L879-L882
INK-USC/USC-DS-RelationExtraction
eebcfa7fd2eda5bba92f3ef8158797cdf91e6981
code/Classifier/DataIO.py
python
save_from_list
(filename, indexes, data)
Save data(a list of list) to a file. :param filename: :param data: :return:
Save data(a list of list) to a file. :param filename: :param data: :return:
[ "Save", "data", "(", "a", "list", "of", "list", ")", "to", "a", "file", ".", ":", "param", "filename", ":", ":", "param", "data", ":", ":", "return", ":" ]
def save_from_list(filename, indexes, data): """ Save data(a list of list) to a file. :param filename: :param data: :return: """ with open(filename, 'w') as f: for i in xrange(len(indexes)): index = indexes[i] labels = data[i] if len(labels) > 0: ### only detected RMs are written for l in labels: f.write(str(index) + '\t' +str(l) + '\t1\n')
[ "def", "save_from_list", "(", "filename", ",", "indexes", ",", "data", ")", ":", "with", "open", "(", "filename", ",", "'w'", ")", "as", "f", ":", "for", "i", "in", "xrange", "(", "len", "(", "indexes", ")", ")", ":", "index", "=", "indexes", "[", ...
https://github.com/INK-USC/USC-DS-RelationExtraction/blob/eebcfa7fd2eda5bba92f3ef8158797cdf91e6981/code/Classifier/DataIO.py#L47-L60
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/dtypes/cast.py
python
astype_nansafe
(arr, dtype, copy: bool = True, skipna: bool = False)
return arr.view(dtype)
Cast the elements of an array to a given dtype a nan-safe manner. Parameters ---------- arr : ndarray dtype : np.dtype copy : bool, default True If False, a view will be attempted but may fail, if e.g. the item sizes don't align. skipna: bool, default False Whether or not we should skip NaN when casting as a string-type. Raises ------ ValueError The dtype was a datetime64/timedelta64 dtype, but it had no unit.
Cast the elements of an array to a given dtype a nan-safe manner.
[ "Cast", "the", "elements", "of", "an", "array", "to", "a", "given", "dtype", "a", "nan", "-", "safe", "manner", "." ]
def astype_nansafe(arr, dtype, copy: bool = True, skipna: bool = False): """ Cast the elements of an array to a given dtype a nan-safe manner. Parameters ---------- arr : ndarray dtype : np.dtype copy : bool, default True If False, a view will be attempted but may fail, if e.g. the item sizes don't align. skipna: bool, default False Whether or not we should skip NaN when casting as a string-type. Raises ------ ValueError The dtype was a datetime64/timedelta64 dtype, but it had no unit. """ # dispatch on extension dtype if needed if is_extension_array_dtype(dtype): return dtype.construct_array_type()._from_sequence(arr, dtype=dtype, copy=copy) if not isinstance(dtype, np.dtype): dtype = pandas_dtype(dtype) if issubclass(dtype.type, str): return lib.astype_str(arr.ravel(), skipna=skipna).reshape(arr.shape) elif is_datetime64_dtype(arr): if is_object_dtype(dtype): return tslib.ints_to_pydatetime(arr.view(np.int64)) elif dtype == np.int64: if isna(arr).any(): raise ValueError("Cannot convert NaT values to integer") return arr.view(dtype) # allow frequency conversions if dtype.kind == "M": return arr.astype(dtype) raise TypeError(f"cannot astype a datetimelike from [{arr.dtype}] to [{dtype}]") elif is_timedelta64_dtype(arr): if is_object_dtype(dtype): return tslibs.ints_to_pytimedelta(arr.view(np.int64)) elif dtype == np.int64: if isna(arr).any(): raise ValueError("Cannot convert NaT values to integer") return arr.view(dtype) if dtype not in [_INT64_DTYPE, _TD_DTYPE]: # allow frequency conversions # we return a float here! if dtype.kind == "m": mask = isna(arr) result = arr.astype(dtype).astype(np.float64) result[mask] = np.nan return result elif dtype == _TD_DTYPE: return arr.astype(_TD_DTYPE, copy=copy) raise TypeError(f"cannot astype a timedelta from [{arr.dtype}] to [{dtype}]") elif np.issubdtype(arr.dtype, np.floating) and np.issubdtype(dtype, np.integer): if not np.isfinite(arr).all(): raise ValueError("Cannot convert non-finite values (NA or inf) to integer") elif is_object_dtype(arr): # work around NumPy brokenness, #1987 if np.issubdtype(dtype.type, np.integer): return lib.astype_intsafe(arr.ravel(), dtype).reshape(arr.shape) # if we have a datetime/timedelta array of objects # then coerce to a proper dtype and recall astype_nansafe elif is_datetime64_dtype(dtype): from pandas import to_datetime return astype_nansafe(to_datetime(arr).values, dtype, copy=copy) elif is_timedelta64_dtype(dtype): from pandas import to_timedelta return astype_nansafe(to_timedelta(arr).values, dtype, copy=copy) if dtype.name in ("datetime64", "timedelta64"): msg = ( f"The '{dtype.name}' dtype has no unit. Please pass in " f"'{dtype.name}[ns]' instead." ) raise ValueError(msg) if copy or is_object_dtype(arr) or is_object_dtype(dtype): # Explicit copy, or required since NumPy can't view from / to object. return arr.astype(dtype, copy=True) return arr.view(dtype)
[ "def", "astype_nansafe", "(", "arr", ",", "dtype", ",", "copy", ":", "bool", "=", "True", ",", "skipna", ":", "bool", "=", "False", ")", ":", "# dispatch on extension dtype if needed", "if", "is_extension_array_dtype", "(", "dtype", ")", ":", "return", "dtype"...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/dtypes/cast.py#L799-L899
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/ndarray/numpy/_op.py
python
rad2deg
(x, out=None, **kwargs)
return _pure_unary_func_helper(x, _api_internal.rad2deg, _np.rad2deg, out=out)
r""" Convert angles from radians to degrees. Parameters ---------- x : ndarray or scalar Angles in degrees. out : ndarray or None, optional A location into which the result is stored. If not provided or `None`, a freshly-allocated array is returned. Returns ------- y : ndarray or scalar The corresponding angle in radians. This is a scalar if `x` is a scalar. Notes ----- "rad2deg(x)" is "x *180 / pi". This function differs from the original numpy.arange in the following aspects: - Only support float32 and float64. - `out` must be in the same size of input. Examples -------- >>> np.rad2deg(np.pi/2) 90.0
r""" Convert angles from radians to degrees.
[ "r", "Convert", "angles", "from", "radians", "to", "degrees", "." ]
def rad2deg(x, out=None, **kwargs): r""" Convert angles from radians to degrees. Parameters ---------- x : ndarray or scalar Angles in degrees. out : ndarray or None, optional A location into which the result is stored. If not provided or `None`, a freshly-allocated array is returned. Returns ------- y : ndarray or scalar The corresponding angle in radians. This is a scalar if `x` is a scalar. Notes ----- "rad2deg(x)" is "x *180 / pi". This function differs from the original numpy.arange in the following aspects: - Only support float32 and float64. - `out` must be in the same size of input. Examples -------- >>> np.rad2deg(np.pi/2) 90.0 """ return _pure_unary_func_helper(x, _api_internal.rad2deg, _np.rad2deg, out=out)
[ "def", "rad2deg", "(", "x", ",", "out", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "_pure_unary_func_helper", "(", "x", ",", "_api_internal", ".", "rad2deg", ",", "_np", ".", "rad2deg", ",", "out", "=", "out", ")" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/ndarray/numpy/_op.py#L3284-L3315
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/ndarray/sparse.py
python
_check_shape
(s1, s2)
check s1 == s2 if both are not None
check s1 == s2 if both are not None
[ "check", "s1", "==", "s2", "if", "both", "are", "not", "None" ]
def _check_shape(s1, s2): """check s1 == s2 if both are not None""" if s1 and s2 and s1 != s2: raise ValueError("Shape mismatch detected. " + str(s1) + " v.s. " + str(s2))
[ "def", "_check_shape", "(", "s1", ",", "s2", ")", ":", "if", "s1", "and", "s2", "and", "s1", "!=", "s2", ":", "raise", "ValueError", "(", "\"Shape mismatch detected. \"", "+", "str", "(", "s1", ")", "+", "\" v.s. \"", "+", "str", "(", "s2", ")", ")" ...
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/ndarray/sparse.py#L834-L837
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/protobuf/py3/google/protobuf/internal/encoder.py
python
GroupEncoder
(field_number, is_repeated, is_packed)
Returns an encoder for a group field.
Returns an encoder for a group field.
[ "Returns", "an", "encoder", "for", "a", "group", "field", "." ]
def GroupEncoder(field_number, is_repeated, is_packed): """Returns an encoder for a group field.""" start_tag = TagBytes(field_number, wire_format.WIRETYPE_START_GROUP) end_tag = TagBytes(field_number, wire_format.WIRETYPE_END_GROUP) assert not is_packed if is_repeated: def EncodeRepeatedField(write, value, deterministic): for element in value: write(start_tag) element._InternalSerialize(write, deterministic) write(end_tag) return EncodeRepeatedField else: def EncodeField(write, value, deterministic): write(start_tag) value._InternalSerialize(write, deterministic) return write(end_tag) return EncodeField
[ "def", "GroupEncoder", "(", "field_number", ",", "is_repeated", ",", "is_packed", ")", ":", "start_tag", "=", "TagBytes", "(", "field_number", ",", "wire_format", ".", "WIRETYPE_START_GROUP", ")", "end_tag", "=", "TagBytes", "(", "field_number", ",", "wire_format"...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py3/google/protobuf/internal/encoder.py#L731-L749
HyeonwooNoh/caffe
d9e8494a2832d67b25dee37194c7bcb9d52d0e42
scripts/cpp_lint.py
python
FileInfo.IsSource
(self)
return self.Extension()[1:] in ('c', 'cc', 'cpp', 'cxx')
File has a source file extension.
File has a source file extension.
[ "File", "has", "a", "source", "file", "extension", "." ]
def IsSource(self): """File has a source file extension.""" return self.Extension()[1:] in ('c', 'cc', 'cpp', 'cxx')
[ "def", "IsSource", "(", "self", ")", ":", "return", "self", ".", "Extension", "(", ")", "[", "1", ":", "]", "in", "(", "'c'", ",", "'cc'", ",", "'cpp'", ",", "'cxx'", ")" ]
https://github.com/HyeonwooNoh/caffe/blob/d9e8494a2832d67b25dee37194c7bcb9d52d0e42/scripts/cpp_lint.py#L956-L958
quantOS-org/DataCore
e2ef9bd2c22ee9e2845675b6435a14fa607f3551
mdlink/deps/windows/protobuf-2.5.0/python/google/protobuf/service_reflection.py
python
_ServiceBuilder._GetRequestClass
(self, method_descriptor)
return method_descriptor.input_type._concrete_class
Returns the class of the request protocol message. Args: method_descriptor: Descriptor of the method for which to return the request protocol message class. Returns: A class that represents the input protocol message of the specified method.
Returns the class of the request protocol message.
[ "Returns", "the", "class", "of", "the", "request", "protocol", "message", "." ]
def _GetRequestClass(self, method_descriptor): """Returns the class of the request protocol message. Args: method_descriptor: Descriptor of the method for which to return the request protocol message class. Returns: A class that represents the input protocol message of the specified method. """ if method_descriptor.containing_service != self.descriptor: raise RuntimeError( 'GetRequestClass() given method descriptor for wrong service type.') return method_descriptor.input_type._concrete_class
[ "def", "_GetRequestClass", "(", "self", ",", "method_descriptor", ")", ":", "if", "method_descriptor", ".", "containing_service", "!=", "self", ".", "descriptor", ":", "raise", "RuntimeError", "(", "'GetRequestClass() given method descriptor for wrong service type.'", ")", ...
https://github.com/quantOS-org/DataCore/blob/e2ef9bd2c22ee9e2845675b6435a14fa607f3551/mdlink/deps/windows/protobuf-2.5.0/python/google/protobuf/service_reflection.py#L173-L187
kismetwireless/kismet
a7c0dc270c960fb1f58bd9cec4601c201885fd4e
capture_sdr_rtladsb/KismetCaptureRtladsb/kismetexternal/__init__.py
python
Datasource.send_datasource_configure_report
(self, seqno, success=False, channel=None, hop_rate=None, hop_channels=None, spectrum=None, message=None, full_hopping=None, warning=None, **kwargs)
When acting as a Kismet datasource, send a response to a configuration request. This is called with the response to the open datasource command. :param seqno: Sequence number of open source command :param success: Source configuration success :param channel: Optional source single-channel configuration :param hop_rate: Optional source hop speed, if hopping :param hop_channels: Optional vector of string channels, if hopping :param message: Optional message :param full_hopping: Optional full datasource_pb2.SubChanset :param warning: Optional warning text to be set in datasource detailed info :param spectrum: Optional spectral data :param kwargs: Unused additional arguments :return: None
When acting as a Kismet datasource, send a response to a configuration request. This is called with the response to the open datasource command.
[ "When", "acting", "as", "a", "Kismet", "datasource", "send", "a", "response", "to", "a", "configuration", "request", ".", "This", "is", "called", "with", "the", "response", "to", "the", "open", "datasource", "command", "." ]
def send_datasource_configure_report(self, seqno, success=False, channel=None, hop_rate=None, hop_channels=None, spectrum=None, message=None, full_hopping=None, warning=None, **kwargs): """ When acting as a Kismet datasource, send a response to a configuration request. This is called with the response to the open datasource command. :param seqno: Sequence number of open source command :param success: Source configuration success :param channel: Optional source single-channel configuration :param hop_rate: Optional source hop speed, if hopping :param hop_channels: Optional vector of string channels, if hopping :param message: Optional message :param full_hopping: Optional full datasource_pb2.SubChanset :param warning: Optional warning text to be set in datasource detailed info :param spectrum: Optional spectral data :param kwargs: Unused additional arguments :return: None """ report = datasource_pb2.ConfigureReport() report.success.success = success report.success.seqno = seqno if message: report.message.msgtext = message if success: report.message.msgtype = self.MSG_INFO else: report.message.msgtype = self.MSG_ERROR if hop_channels: report.hopping.channels.extend(hop_channels) if hop_rate: report.hopping.hop_rate = hop_rate if channel: report.channel.channel = channel if full_hopping: report.hopping.CopyFrom(full_hopping) if spectrum: report.spectrum.CopyFrom(spectrum) if warning: report.warning = warning self.write_ext_packet("KDSCONFIGUREREPORT", report)
[ "def", "send_datasource_configure_report", "(", "self", ",", "seqno", ",", "success", "=", "False", ",", "channel", "=", "None", ",", "hop_rate", "=", "None", ",", "hop_channels", "=", "None", ",", "spectrum", "=", "None", ",", "message", "=", "None", ",",...
https://github.com/kismetwireless/kismet/blob/a7c0dc270c960fb1f58bd9cec4601c201885fd4e/capture_sdr_rtladsb/KismetCaptureRtladsb/kismetexternal/__init__.py#L1052-L1103
acado/acado
b4e28f3131f79cadfd1a001e9fff061f361d3a0f
misc/cpplint.py
python
CheckVlogArguments
(filename, clean_lines, linenum, error)
Checks that VLOG() is only used for defining a logging level. For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and VLOG(FATAL) are not. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Checks that VLOG() is only used for defining a logging level.
[ "Checks", "that", "VLOG", "()", "is", "only", "used", "for", "defining", "a", "logging", "level", "." ]
def CheckVlogArguments(filename, clean_lines, linenum, error): """Checks that VLOG() is only used for defining a logging level. For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and VLOG(FATAL) are not. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] if Search(r'\bVLOG\((INFO|ERROR|WARNING|DFATAL|FATAL)\)', line): error(filename, linenum, 'runtime/vlog', 5, 'VLOG() should be used with numeric verbosity level. ' 'Use LOG() if you want symbolic severity levels.')
[ "def", "CheckVlogArguments", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "if", "Search", "(", "r'\\bVLOG\\((INFO|ERROR|WARNING|DFATAL|FATAL)\\)'", ",", "line", ")", ...
https://github.com/acado/acado/blob/b4e28f3131f79cadfd1a001e9fff061f361d3a0f/misc/cpplint.py#L1600-L1616
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/python/turicreate/toolkits/object_detector/_tf_model_architecture.py
python
ODTensorFlowModel.conv_layer
(self, inputs, shape, name, batch_name, init_weights, batch_norm=True)
return conv
Defines conv layer, batch norm and leaky ReLU Parameters ---------- inputs: TensorFlow Tensor 4d tensor of NHWC format shape: list Shape of the conv layer batch_norm: Bool (True or False) to add batch norm layer. This is used to add batch norm to all conv layers but the last. name: string Name for the conv layer init_weights: Dict of numpy arrays A mapping of layer names to init weights batch_name: string Name for the batch norm layer Returns ------- conv: TensorFlow Tensor Return result from combining conv, batch norm and leaky ReLU or conv and bias as needed
Defines conv layer, batch norm and leaky ReLU
[ "Defines", "conv", "layer", "batch", "norm", "and", "leaky", "ReLU" ]
def conv_layer(self, inputs, shape, name, batch_name, init_weights, batch_norm=True): """ Defines conv layer, batch norm and leaky ReLU Parameters ---------- inputs: TensorFlow Tensor 4d tensor of NHWC format shape: list Shape of the conv layer batch_norm: Bool (True or False) to add batch norm layer. This is used to add batch norm to all conv layers but the last. name: string Name for the conv layer init_weights: Dict of numpy arrays A mapping of layer names to init weights batch_name: string Name for the batch norm layer Returns ------- conv: TensorFlow Tensor Return result from combining conv, batch norm and leaky ReLU or conv and bias as needed """ _tf = _lazy_import_tensorflow() weight = _tf.Variable( init_weights[name + "weight"].transpose(2, 3, 1, 0), trainable=True, name=name + "weight", ) conv = _tf.nn.conv2d( inputs, weight, strides=[1, 1, 1, 1], padding="SAME", name=name ) if batch_norm: conv = self.batch_norm_wrapper(conv, batch_name, init_weights, is_training=self.is_train) alpha = 0.1 conv = _tf.maximum(alpha * conv, conv) else: bias = _tf.Variable(_tf.constant(0.1, shape=[shape[3]]), name=name + "bias") conv = _tf.add(conv, bias) return conv
[ "def", "conv_layer", "(", "self", ",", "inputs", ",", "shape", ",", "name", ",", "batch_name", ",", "init_weights", ",", "batch_norm", "=", "True", ")", ":", "_tf", "=", "_lazy_import_tensorflow", "(", ")", "weight", "=", "_tf", ".", "Variable", "(", "in...
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/toolkits/object_detector/_tf_model_architecture.py#L234-L278
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/ndarray/ndarray.py
python
logical_xor
(lhs, rhs)
return _ufunc_helper( lhs, rhs, op.broadcast_logical_xor, lambda x, y: 1 if bool(x) ^ bool(y) else 0, _internal._logical_xor_scalar, None)
Returns the result of element-wise **logical xor** comparison operation with broadcasting. For each element in input arrays, return 1(true) if lhs elements or rhs elements are true, otherwise return 0(false). Equivalent to ``bool(lhs) ^ bool(rhs)`` and ``mx.nd.broadcast_logical_xor(lhs, rhs)``. .. note:: If the corresponding dimensions of two arrays have the same size or one of them has size 1, then the arrays are broadcastable to a common shape. Parameters ---------- lhs : scalar or mxnet.ndarray.array First input of the function. rhs : scalar or mxnet.ndarray.array Second input of the function. If ``lhs.shape != rhs.shape``, they must be broadcastable to a common shape. Returns ------- NDArray Output array of boolean values. Examples -------- >>> x = mx.nd.ones((2,3)) >>> y = mx.nd.arange(2).reshape((2,1)) >>> z = mx.nd.arange(2).reshape((1,2)) >>> x.asnumpy() array([[ 1., 1., 1.], [ 1., 1., 1.]], dtype=float32) >>> y.asnumpy() array([[ 0.], [ 1.]], dtype=float32) >>> z.asnumpy() array([[ 0., 1.]], dtype=float32) >>> mx.nd.logical_xor(x, y).asnumpy() array([[ 1., 1., 1.], [ 0., 0., 0.]], dtype=float32)
Returns the result of element-wise **logical xor** comparison operation with broadcasting.
[ "Returns", "the", "result", "of", "element", "-", "wise", "**", "logical", "xor", "**", "comparison", "operation", "with", "broadcasting", "." ]
def logical_xor(lhs, rhs): """Returns the result of element-wise **logical xor** comparison operation with broadcasting. For each element in input arrays, return 1(true) if lhs elements or rhs elements are true, otherwise return 0(false). Equivalent to ``bool(lhs) ^ bool(rhs)`` and ``mx.nd.broadcast_logical_xor(lhs, rhs)``. .. note:: If the corresponding dimensions of two arrays have the same size or one of them has size 1, then the arrays are broadcastable to a common shape. Parameters ---------- lhs : scalar or mxnet.ndarray.array First input of the function. rhs : scalar or mxnet.ndarray.array Second input of the function. If ``lhs.shape != rhs.shape``, they must be broadcastable to a common shape. Returns ------- NDArray Output array of boolean values. Examples -------- >>> x = mx.nd.ones((2,3)) >>> y = mx.nd.arange(2).reshape((2,1)) >>> z = mx.nd.arange(2).reshape((1,2)) >>> x.asnumpy() array([[ 1., 1., 1.], [ 1., 1., 1.]], dtype=float32) >>> y.asnumpy() array([[ 0.], [ 1.]], dtype=float32) >>> z.asnumpy() array([[ 0., 1.]], dtype=float32) >>> mx.nd.logical_xor(x, y).asnumpy() array([[ 1., 1., 1.], [ 0., 0., 0.]], dtype=float32) """ # pylint: disable= no-member, protected-access return _ufunc_helper( lhs, rhs, op.broadcast_logical_xor, lambda x, y: 1 if bool(x) ^ bool(y) else 0, _internal._logical_xor_scalar, None)
[ "def", "logical_xor", "(", "lhs", ",", "rhs", ")", ":", "# pylint: disable= no-member, protected-access", "return", "_ufunc_helper", "(", "lhs", ",", "rhs", ",", "op", ".", "broadcast_logical_xor", ",", "lambda", "x", ",", "y", ":", "1", "if", "bool", "(", "...
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/ndarray/ndarray.py#L4640-L4691
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py
python
Scrollbar.fraction
(self, x, y)
return self.tk.getdouble(self.tk.call(self._w, 'fraction', x, y))
Return the fractional value which corresponds to a slider position of X,Y.
Return the fractional value which corresponds to a slider position of X,Y.
[ "Return", "the", "fractional", "value", "which", "corresponds", "to", "a", "slider", "position", "of", "X", "Y", "." ]
def fraction(self, x, y): """Return the fractional value which corresponds to a slider position of X,Y.""" return self.tk.getdouble(self.tk.call(self._w, 'fraction', x, y))
[ "def", "fraction", "(", "self", ",", "x", ",", "y", ")", ":", "return", "self", ".", "tk", ".", "getdouble", "(", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "'fraction'", ",", "x", ",", "y", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py#L3057-L3060
microsoft/clang
86d4513d3e0daa4d5a29b0b1de7c854ca15f9fe5
bindings/python/clang/cindex.py
python
Cursor.is_default_constructor
(self)
return conf.lib.clang_CXXConstructor_isDefaultConstructor(self)
Returns True if the cursor refers to a C++ default constructor.
Returns True if the cursor refers to a C++ default constructor.
[ "Returns", "True", "if", "the", "cursor", "refers", "to", "a", "C", "++", "default", "constructor", "." ]
def is_default_constructor(self): """Returns True if the cursor refers to a C++ default constructor. """ return conf.lib.clang_CXXConstructor_isDefaultConstructor(self)
[ "def", "is_default_constructor", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_CXXConstructor_isDefaultConstructor", "(", "self", ")" ]
https://github.com/microsoft/clang/blob/86d4513d3e0daa4d5a29b0b1de7c854ca15f9fe5/bindings/python/clang/cindex.py#L1442-L1445
facebookresearch/minirts
859e747a5e2fab2355bea083daffa6a36820a7f2
scripts/behavior_clone/rnn_coach.py
python
ConvRnnCoach.rl_forward
(self, batch)
return output
forward function use by RL
forward function use by RL
[ "forward", "function", "use", "by", "RL" ]
def rl_forward(self, batch): """forward function use by RL """ batch = self._format_rl_language_input(batch) glob_feat = self._forward(batch) v = self.value(glob_feat).squeeze() cont_prob = self.cont_cls.compute_prob(glob_feat) inst_prob = self.inst_selector.compute_prob( batch['cand_inst'], batch['cand_inst_len'], glob_feat) output = { 'cont_pi': cont_prob, 'inst_pi': inst_prob, 'v': v } return output
[ "def", "rl_forward", "(", "self", ",", "batch", ")", ":", "batch", "=", "self", ".", "_format_rl_language_input", "(", "batch", ")", "glob_feat", "=", "self", ".", "_forward", "(", "batch", ")", "v", "=", "self", ".", "value", "(", "glob_feat", ")", "....
https://github.com/facebookresearch/minirts/blob/859e747a5e2fab2355bea083daffa6a36820a7f2/scripts/behavior_clone/rnn_coach.py#L379-L394
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/telemetry/benchmark.py
python
Benchmark.Run
(self, finder_options)
return story_runner.RunBenchmark(self, finder_options)
Do not override this method.
Do not override this method.
[ "Do", "not", "override", "this", "method", "." ]
def Run(self, finder_options): """Do not override this method.""" return story_runner.RunBenchmark(self, finder_options)
[ "def", "Run", "(", "self", ",", "finder_options", ")", ":", "return", "story_runner", ".", "RunBenchmark", "(", "self", ",", "finder_options", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/benchmark.py#L89-L91
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/mixture/base.py
python
BaseMixture.sample
(self, n_samples=1)
return (X, y)
Generate random samples from the fitted Gaussian distribution. Parameters ---------- n_samples : int, optional Number of samples to generate. Defaults to 1. Returns ------- X : array, shape (n_samples, n_features) Randomly generated sample y : array, shape (nsamples,) Component labels
Generate random samples from the fitted Gaussian distribution.
[ "Generate", "random", "samples", "from", "the", "fitted", "Gaussian", "distribution", "." ]
def sample(self, n_samples=1): """Generate random samples from the fitted Gaussian distribution. Parameters ---------- n_samples : int, optional Number of samples to generate. Defaults to 1. Returns ------- X : array, shape (n_samples, n_features) Randomly generated sample y : array, shape (nsamples,) Component labels """ self._check_is_fitted() if n_samples < 1: raise ValueError( "Invalid value for 'n_samples': %d . The sampling requires at " "least one sample." % (self.n_components)) _, n_features = self.means_.shape rng = check_random_state(self.random_state) n_samples_comp = rng.multinomial(n_samples, self.weights_) if self.covariance_type == 'full': X = np.vstack([ rng.multivariate_normal(mean, covariance, int(sample)) for (mean, covariance, sample) in zip( self.means_, self.covariances_, n_samples_comp)]) elif self.covariance_type == "tied": X = np.vstack([ rng.multivariate_normal(mean, self.covariances_, int(sample)) for (mean, sample) in zip( self.means_, n_samples_comp)]) else: X = np.vstack([ mean + rng.randn(sample, n_features) * np.sqrt(covariance) for (mean, covariance, sample) in zip( self.means_, self.covariances_, n_samples_comp)]) y = np.concatenate([j * np.ones(sample, dtype=int) for j, sample in enumerate(n_samples_comp)]) return (X, y)
[ "def", "sample", "(", "self", ",", "n_samples", "=", "1", ")", ":", "self", ".", "_check_is_fitted", "(", ")", "if", "n_samples", "<", "1", ":", "raise", "ValueError", "(", "\"Invalid value for 'n_samples': %d . The sampling requires at \"", "\"least one sample.\"", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/mixture/base.py#L362-L409
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/eclib/finddlg.py
python
FindReplaceDlgBase.SetLookinPath
(self, path)
Set the lookin path, adding it to the collection if it is not in there. @param path: string (path of directory)
Set the lookin path, adding it to the collection if it is not in there. @param path: string (path of directory)
[ "Set", "the", "lookin", "path", "adding", "it", "to", "the", "collection", "if", "it", "is", "not", "in", "there", ".", "@param", "path", ":", "string", "(", "path", "of", "directory", ")" ]
def SetLookinPath(self, path): """Set the lookin path, adding it to the collection if it is not in there. @param path: string (path of directory) """ idx = self._panel.AddLookinPath(path) self.SetLookinSelection(idx)
[ "def", "SetLookinPath", "(", "self", ",", "path", ")", ":", "idx", "=", "self", ".", "_panel", ".", "AddLookinPath", "(", "path", ")", "self", ".", "SetLookinSelection", "(", "idx", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/eclib/finddlg.py#L537-L544
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/http/cookiejar.py
python
FileCookieJar.__init__
(self, filename=None, delayload=False, policy=None)
Cookies are NOT loaded from the named file until either the .load() or .revert() method is called.
Cookies are NOT loaded from the named file until either the .load() or .revert() method is called.
[ "Cookies", "are", "NOT", "loaded", "from", "the", "named", "file", "until", "either", "the", ".", "load", "()", "or", ".", "revert", "()", "method", "is", "called", "." ]
def __init__(self, filename=None, delayload=False, policy=None): """ Cookies are NOT loaded from the named file until either the .load() or .revert() method is called. """ CookieJar.__init__(self, policy) if filename is not None: try: filename+"" except: raise ValueError("filename must be string-like") self.filename = filename self.delayload = bool(delayload)
[ "def", "__init__", "(", "self", ",", "filename", "=", "None", ",", "delayload", "=", "False", ",", "policy", "=", "None", ")", ":", "CookieJar", ".", "__init__", "(", "self", ",", "policy", ")", "if", "filename", "is", "not", "None", ":", "try", ":",...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/http/cookiejar.py#L1773-L1786
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TAscFlt.Save
(self, *args)
return _snap.TAscFlt_Save(self, *args)
Save(TAscFlt self, TSOut SOut) Parameters: SOut: TSOut &
Save(TAscFlt self, TSOut SOut)
[ "Save", "(", "TAscFlt", "self", "TSOut", "SOut", ")" ]
def Save(self, *args): """ Save(TAscFlt self, TSOut SOut) Parameters: SOut: TSOut & """ return _snap.TAscFlt_Save(self, *args)
[ "def", "Save", "(", "self", ",", "*", "args", ")", ":", "return", "_snap", ".", "TAscFlt_Save", "(", "self", ",", "*", "args", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L14768-L14776
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/contrib/slim/python/slim/data/tfexample_decoder.py
python
TFExampleDecoder.list_items
(self)
return self._items_to_handlers.keys()
See base class.
See base class.
[ "See", "base", "class", "." ]
def list_items(self): """See base class.""" return self._items_to_handlers.keys()
[ "def", "list_items", "(", "self", ")", ":", "return", "self", ".", "_items_to_handlers", ".", "keys", "(", ")" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/slim/python/slim/data/tfexample_decoder.py#L313-L315
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
tools/code_coverage/croc.py
python
Coverage.AddFiles
(self, src_dir)
Adds files to coverage information. LCOV files only contains files which are compiled and instrumented as part of running coverage. This function finds missing files and adds them. Args: src_dir: Directory on disk at which to start search. May be a relative path on disk starting with '.' or '..', or an absolute path, or a path relative to an alt_name for one of the roots (for example, '_/src'). If the alt_name matches more than one root, all matches will be attempted. Note that dirs not underneath one of the root dirs and covered by an inclusion rule will be ignored.
Adds files to coverage information.
[ "Adds", "files", "to", "coverage", "information", "." ]
def AddFiles(self, src_dir): """Adds files to coverage information. LCOV files only contains files which are compiled and instrumented as part of running coverage. This function finds missing files and adds them. Args: src_dir: Directory on disk at which to start search. May be a relative path on disk starting with '.' or '..', or an absolute path, or a path relative to an alt_name for one of the roots (for example, '_/src'). If the alt_name matches more than one root, all matches will be attempted. Note that dirs not underneath one of the root dirs and covered by an inclusion rule will be ignored. """ # Check for root dir alt_names in the path and replace with the actual # root dirs, then recurse. found_root = False for root, alt_name in self.root_dirs: replaced_root = re.sub('^' + re.escape(alt_name) + '(?=(/|$))', root, src_dir) if replaced_root != src_dir: found_root = True self.AddFiles(replaced_root) if found_root: return # Replaced an alt_name with a root_dir, so already recursed. for (dirpath, dirnames, filenames) in self.add_files_walk(src_dir): # Make a copy of the dirnames list so we can modify the original to # prune subdirs we don't need to walk. for d in list(dirnames): # Add trailing '/' to directory names so dir-based regexps can match # '/' instead of needing to specify '(/|$)'. dpath = self.CleanupFilename(dirpath + '/' + d) + '/' attrs = self.ClassifyFile(dpath) if not attrs.get('include'): # Directory has been excluded, so don't traverse it # TODO: Document the slight weirdness caused by this: If you # AddFiles('./A'), and the rules include 'A/B/C/D' but not 'A/B', # then it won't recurse into './A/B' so won't find './A/B/C/D'. # Workarounds are to AddFiles('./A/B/C/D') or AddFiles('./A/B/C'). # The latter works because it explicitly walks the contents of the # path passed to AddFiles(), so it finds './A/B/C/D'. dirnames.remove(d) for f in filenames: local_path = dirpath + '/' + f covf = self.GetCoveredFile(local_path, add=True) if not covf: continue # Save where we found the file, for generating line-by-line HTML output covf.local_path = local_path if covf.in_lcov: # File already instrumented and doesn't need to be scanned continue if not covf.attrs.get('add_if_missing', 1): # Not allowed to add the file self.RemoveCoveredFile(covf) continue # Scan file to find potentially-executable lines lines = self.scan_file(covf.local_path, covf.attrs.get('language')) if lines: for l in lines: covf.lines[l] = None covf.UpdateCoverage() else: # File has no executable lines, so don't count it self.RemoveCoveredFile(covf)
[ "def", "AddFiles", "(", "self", ",", "src_dir", ")", ":", "# Check for root dir alt_names in the path and replace with the actual", "# root dirs, then recurse.", "found_root", "=", "False", "for", "root", ",", "alt_name", "in", "self", ".", "root_dirs", ":", "replaced_roo...
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/tools/code_coverage/croc.py#L430-L503
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/lib2to3/fixer_util.py
python
is_tuple
(node)
return (isinstance(node, Node) and len(node.children) == 3 and isinstance(node.children[0], Leaf) and isinstance(node.children[1], Node) and isinstance(node.children[2], Leaf) and node.children[0].value == "(" and node.children[2].value == ")")
Does the node represent a tuple literal?
Does the node represent a tuple literal?
[ "Does", "the", "node", "represent", "a", "tuple", "literal?" ]
def is_tuple(node): """Does the node represent a tuple literal?""" if isinstance(node, Node) and node.children == [LParen(), RParen()]: return True return (isinstance(node, Node) and len(node.children) == 3 and isinstance(node.children[0], Leaf) and isinstance(node.children[1], Node) and isinstance(node.children[2], Leaf) and node.children[0].value == "(" and node.children[2].value == ")")
[ "def", "is_tuple", "(", "node", ")", ":", "if", "isinstance", "(", "node", ",", "Node", ")", "and", "node", ".", "children", "==", "[", "LParen", "(", ")", ",", "RParen", "(", ")", "]", ":", "return", "True", "return", "(", "isinstance", "(", "node...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/lib2to3/fixer_util.py#L158-L168
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_gdi.py
python
Bitmap.SaveFile
(*args, **kwargs)
return _gdi_.Bitmap_SaveFile(*args, **kwargs)
SaveFile(self, String name, int type, Palette palette=None) -> bool Saves a bitmap in the named file. See `__init__` for a description of the ``type`` parameter.
SaveFile(self, String name, int type, Palette palette=None) -> bool
[ "SaveFile", "(", "self", "String", "name", "int", "type", "Palette", "palette", "=", "None", ")", "-", ">", "bool" ]
def SaveFile(*args, **kwargs): """ SaveFile(self, String name, int type, Palette palette=None) -> bool Saves a bitmap in the named file. See `__init__` for a description of the ``type`` parameter. """ return _gdi_.Bitmap_SaveFile(*args, **kwargs)
[ "def", "SaveFile", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "Bitmap_SaveFile", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_gdi.py#L735-L742
hfinkel/llvm-project-cxxjit
91084ef018240bbb8e24235ff5cd8c355a9c1a1e
clang/docs/tools/dump_ast_matchers.py
python
unify_arguments
(args)
return args
Gets rid of anything the user doesn't care about in the argument list.
Gets rid of anything the user doesn't care about in the argument list.
[ "Gets", "rid", "of", "anything", "the", "user", "doesn", "t", "care", "about", "in", "the", "argument", "list", "." ]
def unify_arguments(args): """Gets rid of anything the user doesn't care about in the argument list.""" args = re.sub(r'internal::', r'', args) args = re.sub(r'extern const\s+(.*)&', r'\1 ', args) args = re.sub(r'&', r' ', args) args = re.sub(r'(^|\s)M\d?(\s)', r'\1Matcher<*>\2', args) return args
[ "def", "unify_arguments", "(", "args", ")", ":", "args", "=", "re", ".", "sub", "(", "r'internal::'", ",", "r''", ",", "args", ")", "args", "=", "re", ".", "sub", "(", "r'extern const\\s+(.*)&'", ",", "r'\\1 '", ",", "args", ")", "args", "=", "re", "...
https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/clang/docs/tools/dump_ast_matchers.py#L98-L104
htcondor/htcondor
4829724575176d1d6c936e4693dfd78a728569b0
src/condor_contrib/campus_factory/python-lib/campus_factory/OfflineAds/OfflineAds.py
python
OfflineAds.GetOfflineAds
(self, site)
return ad_list
Get the full classads of the offline startds @param site: The site to restrict the offline ads @return: list of ClassAd objects
Get the full classads of the offline startds
[ "Get", "the", "full", "classads", "of", "the", "offline", "startds" ]
def GetOfflineAds(self, site): """ Get the full classads of the offline startds @param site: The site to restrict the offline ads @return: list of ClassAd objects """ #def OfflineAds(data): # if data.has_key("Offline"): # if data["Offline"] == True and data[self.siteunique] == site: # return True # return False #fetched = self.condor_status.fetchStored(OfflineAds) cmd = "condor_status -l -const '(IsUndefined(Offline) == FALSE) && (Offline == true) && (%(uniquesite)s =?= %(sitename)s)'" query_opts = {"uniquesite": self.siteunique, "sitename": site} new_cmd = cmd % query_opts (stdout, stderr) = RunExternal(new_cmd) ad_list = [] for str_classad in stdout.split('\n\n'): if len(str_classad) > 0: ad_list.append(ClassAd(str_classad)) return ad_list
[ "def", "GetOfflineAds", "(", "self", ",", "site", ")", ":", "#def OfflineAds(data):", "# if data.has_key(\"Offline\"):", "# if data[\"Offline\"] == True and data[self.siteunique] == site:", "# return True", "# return False", "#fetched = self.condor_status.fetchStore...
https://github.com/htcondor/htcondor/blob/4829724575176d1d6c936e4693dfd78a728569b0/src/condor_contrib/campus_factory/python-lib/campus_factory/OfflineAds/OfflineAds.py#L234-L261
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/fluid/dygraph/dygraph_to_static/convert_operators.py
python
convert_while_loop
(cond, body, loop_vars)
return loop_vars
A function representation of a Python ``while`` statement. Args: cond(Callable): A callable object that returns a boolean variable to control whether to execute the loop body. It takes ``loop_vars`` as arguments. body(Callable): A callable object that returns a tuple or list of variables with the same arguments ``loops_vars`` as ``cond`` . loop_vars(list|tuple): A list or tuple of variables passed to ``cond`` and ``body`` . Returns: A list or tuple of variables which returned by ``body``.
A function representation of a Python ``while`` statement.
[ "A", "function", "representation", "of", "a", "Python", "while", "statement", "." ]
def convert_while_loop(cond, body, loop_vars): """ A function representation of a Python ``while`` statement. Args: cond(Callable): A callable object that returns a boolean variable to control whether to execute the loop body. It takes ``loop_vars`` as arguments. body(Callable): A callable object that returns a tuple or list of variables with the same arguments ``loops_vars`` as ``cond`` . loop_vars(list|tuple): A list or tuple of variables passed to ``cond`` and ``body`` . Returns: A list or tuple of variables which returned by ``body``. """ # NOTE: It may be slower if cond is very expensive, but usually cond is just O(1). # If loop_vars is changed during cond callable, then it causes bug, but current logical_and/logical_not/... doesn't change the loop_vars. pred = cond(*loop_vars) if isinstance(pred, Variable): loop_vars = _run_paddle_while_loop(cond, body, loop_vars) else: loop_vars = _run_py_while(cond, body, loop_vars) return loop_vars
[ "def", "convert_while_loop", "(", "cond", ",", "body", ",", "loop_vars", ")", ":", "# NOTE: It may be slower if cond is very expensive, but usually cond is just O(1).", "# If loop_vars is changed during cond callable, then it causes bug, but current logical_and/logical_not/... doesn't change t...
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/dygraph/dygraph_to_static/convert_operators.py#L26-L47
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/urllib/request.py
python
urlretrieve
(url, filename=None, reporthook=None, data=None)
return result
Retrieve a URL into a temporary location on disk. Requires a URL argument. If a filename is passed, it is used as the temporary file location. The reporthook argument should be a callable that accepts a block number, a read size, and the total file size of the URL target. The data argument should be valid URL encoded data. If a filename is passed and the URL points to a local resource, the result is a copy from local file to new file. Returns a tuple containing the path to the newly created data file as well as the resulting HTTPMessage object.
Retrieve a URL into a temporary location on disk.
[ "Retrieve", "a", "URL", "into", "a", "temporary", "location", "on", "disk", "." ]
def urlretrieve(url, filename=None, reporthook=None, data=None): """ Retrieve a URL into a temporary location on disk. Requires a URL argument. If a filename is passed, it is used as the temporary file location. The reporthook argument should be a callable that accepts a block number, a read size, and the total file size of the URL target. The data argument should be valid URL encoded data. If a filename is passed and the URL points to a local resource, the result is a copy from local file to new file. Returns a tuple containing the path to the newly created data file as well as the resulting HTTPMessage object. """ url_type, path = _splittype(url) with contextlib.closing(urlopen(url, data)) as fp: headers = fp.info() # Just return the local path and the "headers" for file:// # URLs. No sense in performing a copy unless requested. if url_type == "file" and not filename: return os.path.normpath(path), headers # Handle temporary file setup. if filename: tfp = open(filename, 'wb') else: tfp = tempfile.NamedTemporaryFile(delete=False) filename = tfp.name _url_tempfiles.append(filename) with tfp: result = filename, headers bs = 1024*8 size = -1 read = 0 blocknum = 0 if "content-length" in headers: size = int(headers["Content-Length"]) if reporthook: reporthook(blocknum, bs, size) while True: block = fp.read(bs) if not block: break read += len(block) tfp.write(block) blocknum += 1 if reporthook: reporthook(blocknum, bs, size) if size >= 0 and read < size: raise ContentTooShortError( "retrieval incomplete: got only %i out of %i bytes" % (read, size), result) return result
[ "def", "urlretrieve", "(", "url", ",", "filename", "=", "None", ",", "reporthook", "=", "None", ",", "data", "=", "None", ")", ":", "url_type", ",", "path", "=", "_splittype", "(", "url", ")", "with", "contextlib", ".", "closing", "(", "urlopen", "(", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/urllib/request.py#L221-L282
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/telemetry/third_party/pyserial/serial/serialwin32.py
python
Win32Serial.inWaiting
(self)
return comstat.cbInQue
Return the number of characters currently in the input buffer.
Return the number of characters currently in the input buffer.
[ "Return", "the", "number", "of", "characters", "currently", "in", "the", "input", "buffer", "." ]
def inWaiting(self): """Return the number of characters currently in the input buffer.""" flags = win32.DWORD() comstat = win32.COMSTAT() if not win32.ClearCommError(self.hComPort, ctypes.byref(flags), ctypes.byref(comstat)): raise SerialException('call to ClearCommError failed') return comstat.cbInQue
[ "def", "inWaiting", "(", "self", ")", ":", "flags", "=", "win32", ".", "DWORD", "(", ")", "comstat", "=", "win32", ".", "COMSTAT", "(", ")", "if", "not", "win32", ".", "ClearCommError", "(", "self", ".", "hComPort", ",", "ctypes", ".", "byref", "(", ...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/telemetry/third_party/pyserial/serial/serialwin32.py#L234-L240
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/utils/multiclass.py
python
is_multilabel
(y)
Check if ``y`` is in a multilabel format. Parameters ---------- y : numpy array of shape [n_samples] Target values. Returns ------- out : bool, Return ``True``, if ``y`` is in a multilabel format, else ```False``. Examples -------- >>> import numpy as np >>> from sklearn.utils.multiclass import is_multilabel >>> is_multilabel([0, 1, 0, 1]) False >>> is_multilabel([[1], [0, 2], []]) False >>> is_multilabel(np.array([[1, 0], [0, 0]])) True >>> is_multilabel(np.array([[1], [0], [0]])) False >>> is_multilabel(np.array([[1, 0, 0]])) True
Check if ``y`` is in a multilabel format.
[ "Check", "if", "y", "is", "in", "a", "multilabel", "format", "." ]
def is_multilabel(y): """ Check if ``y`` is in a multilabel format. Parameters ---------- y : numpy array of shape [n_samples] Target values. Returns ------- out : bool, Return ``True``, if ``y`` is in a multilabel format, else ```False``. Examples -------- >>> import numpy as np >>> from sklearn.utils.multiclass import is_multilabel >>> is_multilabel([0, 1, 0, 1]) False >>> is_multilabel([[1], [0, 2], []]) False >>> is_multilabel(np.array([[1, 0], [0, 0]])) True >>> is_multilabel(np.array([[1], [0], [0]])) False >>> is_multilabel(np.array([[1, 0, 0]])) True """ if hasattr(y, '__array__'): y = np.asarray(y) if not (hasattr(y, "shape") and y.ndim == 2 and y.shape[1] > 1): return False if issparse(y): if isinstance(y, (dok_matrix, lil_matrix)): y = y.tocsr() return (len(y.data) == 0 or np.unique(y.data).size == 1 and (y.dtype.kind in 'biu' or # bool, int, uint _is_integral_float(np.unique(y.data)))) else: labels = np.unique(y) return len(labels) < 3 and (y.dtype.kind in 'biu' or # bool, int, uint _is_integral_float(labels))
[ "def", "is_multilabel", "(", "y", ")", ":", "if", "hasattr", "(", "y", ",", "'__array__'", ")", ":", "y", "=", "np", ".", "asarray", "(", "y", ")", "if", "not", "(", "hasattr", "(", "y", ",", "\"shape\"", ")", "and", "y", ".", "ndim", "==", "2"...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/utils/multiclass.py#L113-L156
nasa/fprime
595cf3682d8365943d86c1a6fe7c78f0a116acf0
Autocoders/Python/src/fprime_ac/generators/visitors/CommandVisitor.py
python
CommandVisitor._writeTmpl
(self, c, fp, visit_str)
Wrapper to write tmpl to files desc.
Wrapper to write tmpl to files desc.
[ "Wrapper", "to", "write", "tmpl", "to", "files", "desc", "." ]
def _writeTmpl(self, c, fp, visit_str): """ Wrapper to write tmpl to files desc. """ DEBUG.debug("CommandVisitor:%s" % visit_str) DEBUG.debug("===================================") DEBUG.debug(c) fp.writelines(c.__str__()) DEBUG.debug("===================================")
[ "def", "_writeTmpl", "(", "self", ",", "c", ",", "fp", ",", "visit_str", ")", ":", "DEBUG", ".", "debug", "(", "\"CommandVisitor:%s\"", "%", "visit_str", ")", "DEBUG", ".", "debug", "(", "\"===================================\"", ")", "DEBUG", ".", "debug", ...
https://github.com/nasa/fprime/blob/595cf3682d8365943d86c1a6fe7c78f0a116acf0/Autocoders/Python/src/fprime_ac/generators/visitors/CommandVisitor.py#L79-L87
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/closure_linter/closure_linter/tokenutil.py
python
TokensToString
(token_iterable)
return buf.getvalue()
Convert a number of tokens into a string. Newlines will be inserted whenever the line_number of two neighboring strings differ. Args: token_iterable: The tokens to turn to a string. Returns: A string representation of the given tokens.
Convert a number of tokens into a string.
[ "Convert", "a", "number", "of", "tokens", "into", "a", "string", "." ]
def TokensToString(token_iterable): """Convert a number of tokens into a string. Newlines will be inserted whenever the line_number of two neighboring strings differ. Args: token_iterable: The tokens to turn to a string. Returns: A string representation of the given tokens. """ buf = StringIO.StringIO() token_list = list(token_iterable) if not token_list: return '' line_number = token_list[0].line_number for token in token_list: while line_number < token.line_number: line_number += 1 buf.write('\n') if line_number > token.line_number: line_number = token.line_number buf.write('\n') buf.write(token.string) return buf.getvalue()
[ "def", "TokensToString", "(", "token_iterable", ")", ":", "buf", "=", "StringIO", ".", "StringIO", "(", ")", "token_list", "=", "list", "(", "token_iterable", ")", "if", "not", "token_list", ":", "return", "''", "line_number", "=", "token_list", "[", "0", ...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/closure_linter/closure_linter/tokenutil.py#L475-L507
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/factorization/python/ops/factorization_ops.py
python
WALSModel._create_factors
(cls, rows, cols, num_shards, init, name)
return sharded_matrix
Helper function to create row and column factors.
Helper function to create row and column factors.
[ "Helper", "function", "to", "create", "row", "and", "column", "factors", "." ]
def _create_factors(cls, rows, cols, num_shards, init, name): """Helper function to create row and column factors.""" if callable(init): init = init() if isinstance(init, list): assert len(init) == num_shards elif isinstance(init, str) and init == "random": pass elif num_shards == 1: init = [init] sharded_matrix = [] sizes = cls._shard_sizes(rows, num_shards) assert len(sizes) == num_shards def make_initializer(i, size): def initializer(): if init == "random": return random_ops.random_normal([size, cols]) else: return init[i] return initializer for i, size in enumerate(sizes): var_name = "%s_shard_%d" % (name, i) var_init = make_initializer(i, size) sharded_matrix.append( variable_scope.variable( var_init, dtype=dtypes.float32, name=var_name)) return sharded_matrix
[ "def", "_create_factors", "(", "cls", ",", "rows", ",", "cols", ",", "num_shards", ",", "init", ",", "name", ")", ":", "if", "callable", "(", "init", ")", ":", "init", "=", "init", "(", ")", "if", "isinstance", "(", "init", ",", "list", ")", ":", ...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/factorization/python/ops/factorization_ops.py#L310-L341
p4lang/p4c
3272e79369f20813cc1a555a5eb26f44432f84a4
tools/cpplint.py
python
RemoveMultiLineCommentsFromRange
(lines, begin, end)
Clears a range of lines for multi-line comments.
Clears a range of lines for multi-line comments.
[ "Clears", "a", "range", "of", "lines", "for", "multi", "-", "line", "comments", "." ]
def RemoveMultiLineCommentsFromRange(lines, begin, end): """Clears a range of lines for multi-line comments.""" # Having // <empty> comments makes the lines non-empty, so we will not get # unnecessary blank line warnings later in the code. for i in range(begin, end): lines[i] = '/**/'
[ "def", "RemoveMultiLineCommentsFromRange", "(", "lines", ",", "begin", ",", "end", ")", ":", "# Having // <empty> comments makes the lines non-empty, so we will not get", "# unnecessary blank line warnings later in the code.", "for", "i", "in", "range", "(", "begin", ",", "end"...
https://github.com/p4lang/p4c/blob/3272e79369f20813cc1a555a5eb26f44432f84a4/tools/cpplint.py#L1864-L1869
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/io/stata.py
python
StataWriter._write_expansion_fields
(self)
Write 5 zeros for expansion fields
Write 5 zeros for expansion fields
[ "Write", "5", "zeros", "for", "expansion", "fields" ]
def _write_expansion_fields(self): """Write 5 zeros for expansion fields""" self._write(_pad_bytes("", 5))
[ "def", "_write_expansion_fields", "(", "self", ")", ":", "self", ".", "_write", "(", "_pad_bytes", "(", "\"\"", ",", "5", ")", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/io/stata.py#L2266-L2268
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/model_selection/_validation.py
python
validation_curve
(estimator, X, y, param_name, param_range, groups=None, cv=None, scoring=None, n_jobs=None, pre_dispatch="all", verbose=0, error_score=np.nan)
return out[0], out[1]
Validation curve. Determine training and test scores for varying parameter values. Compute scores for an estimator with different values of a specified parameter. This is similar to grid search with one parameter. However, this will also compute training scores and is merely a utility for plotting the results. Read more in the :ref:`User Guide <learning_curve>`. Parameters ---------- estimator : object type that implements the "fit" and "predict" methods An object of that type which is cloned for each validation. X : array-like, shape (n_samples, n_features) Training vector, where n_samples is the number of samples and n_features is the number of features. y : array-like, shape (n_samples) or (n_samples, n_features), optional Target relative to X for classification or regression; None for unsupervised learning. param_name : string Name of the parameter that will be varied. param_range : array-like, shape (n_values,) The values of the parameter that will be evaluated. groups : array-like, with shape (n_samples,), optional Group labels for the samples used while splitting the dataset into train/test set. Only used in conjunction with a "Group" :term:`cv` instance (e.g., :class:`GroupKFold`). cv : int, cross-validation generator or an iterable, optional Determines the cross-validation splitting strategy. Possible inputs for cv are: - None, to use the default 5-fold cross validation, - integer, to specify the number of folds in a `(Stratified)KFold`, - :term:`CV splitter`, - An iterable yielding (train, test) splits as arrays of indices. For integer/None inputs, if the estimator is a classifier and ``y`` is either binary or multiclass, :class:`StratifiedKFold` is used. In all other cases, :class:`KFold` is used. Refer :ref:`User Guide <cross_validation>` for the various cross-validation strategies that can be used here. .. versionchanged:: 0.22 ``cv`` default value if None changed from 3-fold to 5-fold. scoring : string, callable or None, optional, default: None A string (see model evaluation documentation) or a scorer callable object / function with signature ``scorer(estimator, X, y)``. n_jobs : int or None, optional (default=None) Number of jobs to run in parallel. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. pre_dispatch : integer or string, optional Number of predispatched jobs for parallel execution (default is all). The option can reduce the allocated memory. The string can be an expression like '2*n_jobs'. verbose : integer, optional Controls the verbosity: the higher, the more messages. error_score : 'raise' or numeric Value to assign to the score if an error occurs in estimator fitting. If set to 'raise', the error is raised. If a numeric value is given, FitFailedWarning is raised. This parameter does not affect the refit step, which will always raise the error. Returns ------- train_scores : array, shape (n_ticks, n_cv_folds) Scores on training sets. test_scores : array, shape (n_ticks, n_cv_folds) Scores on test set. Notes ----- See :ref:`sphx_glr_auto_examples_model_selection_plot_validation_curve.py`
Validation curve.
[ "Validation", "curve", "." ]
def validation_curve(estimator, X, y, param_name, param_range, groups=None, cv=None, scoring=None, n_jobs=None, pre_dispatch="all", verbose=0, error_score=np.nan): """Validation curve. Determine training and test scores for varying parameter values. Compute scores for an estimator with different values of a specified parameter. This is similar to grid search with one parameter. However, this will also compute training scores and is merely a utility for plotting the results. Read more in the :ref:`User Guide <learning_curve>`. Parameters ---------- estimator : object type that implements the "fit" and "predict" methods An object of that type which is cloned for each validation. X : array-like, shape (n_samples, n_features) Training vector, where n_samples is the number of samples and n_features is the number of features. y : array-like, shape (n_samples) or (n_samples, n_features), optional Target relative to X for classification or regression; None for unsupervised learning. param_name : string Name of the parameter that will be varied. param_range : array-like, shape (n_values,) The values of the parameter that will be evaluated. groups : array-like, with shape (n_samples,), optional Group labels for the samples used while splitting the dataset into train/test set. Only used in conjunction with a "Group" :term:`cv` instance (e.g., :class:`GroupKFold`). cv : int, cross-validation generator or an iterable, optional Determines the cross-validation splitting strategy. Possible inputs for cv are: - None, to use the default 5-fold cross validation, - integer, to specify the number of folds in a `(Stratified)KFold`, - :term:`CV splitter`, - An iterable yielding (train, test) splits as arrays of indices. For integer/None inputs, if the estimator is a classifier and ``y`` is either binary or multiclass, :class:`StratifiedKFold` is used. In all other cases, :class:`KFold` is used. Refer :ref:`User Guide <cross_validation>` for the various cross-validation strategies that can be used here. .. versionchanged:: 0.22 ``cv`` default value if None changed from 3-fold to 5-fold. scoring : string, callable or None, optional, default: None A string (see model evaluation documentation) or a scorer callable object / function with signature ``scorer(estimator, X, y)``. n_jobs : int or None, optional (default=None) Number of jobs to run in parallel. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. pre_dispatch : integer or string, optional Number of predispatched jobs for parallel execution (default is all). The option can reduce the allocated memory. The string can be an expression like '2*n_jobs'. verbose : integer, optional Controls the verbosity: the higher, the more messages. error_score : 'raise' or numeric Value to assign to the score if an error occurs in estimator fitting. If set to 'raise', the error is raised. If a numeric value is given, FitFailedWarning is raised. This parameter does not affect the refit step, which will always raise the error. Returns ------- train_scores : array, shape (n_ticks, n_cv_folds) Scores on training sets. test_scores : array, shape (n_ticks, n_cv_folds) Scores on test set. Notes ----- See :ref:`sphx_glr_auto_examples_model_selection_plot_validation_curve.py` """ X, y, groups = indexable(X, y, groups) cv = check_cv(cv, y, classifier=is_classifier(estimator)) scorer = check_scoring(estimator, scoring=scoring) parallel = Parallel(n_jobs=n_jobs, pre_dispatch=pre_dispatch, verbose=verbose) out = parallel(delayed(_fit_and_score)( clone(estimator), X, y, scorer, train, test, verbose, parameters={param_name: v}, fit_params=None, return_train_score=True, error_score=error_score) # NOTE do not change order of iteration to allow one time cv splitters for train, test in cv.split(X, y, groups) for v in param_range) out = np.asarray(out) n_params = len(param_range) n_cv_folds = out.shape[0] // n_params out = out.reshape(n_cv_folds, n_params, 2).transpose((2, 1, 0)) return out[0], out[1]
[ "def", "validation_curve", "(", "estimator", ",", "X", ",", "y", ",", "param_name", ",", "param_range", ",", "groups", "=", "None", ",", "cv", "=", "None", ",", "scoring", "=", "None", ",", "n_jobs", "=", "None", ",", "pre_dispatch", "=", "\"all\"", ",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/model_selection/_validation.py#L1365-L1478
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/contrib/graph_editor/transform.py
python
Transformer._transform_t
(self, t)
return t_
Transform a tf.Tensor. Args: t: the tensor to be transformed. Returns: The transformed tensor.
Transform a tf.Tensor.
[ "Transform", "a", "tf", ".", "Tensor", "." ]
def _transform_t(self, t): """Transform a tf.Tensor. Args: t: the tensor to be transformed. Returns: The transformed tensor. """ if t in self._info.transformed_ts: return self._info.transformed_ts[t] op, op_index = t.op, t.value_index # If op is not in the subgraph: if op not in self._info.ops: # t_ is an input of the subgraph if t in self._info.sgv_inputs_set: t_ = self.transform_external_input_handler(self._info, t) # t_ is a hidden input of the subgraph else: t_ = self.transform_external_hidden_input_handler(self._info, t) # If op is in the subgraph, just transform it: else: op_ = self._transform_op(op) t_ = op_.outputs[op_index] # assign to collection if t is not t_: self.assign_collections_handler(self._info, t, t_) self._info.transformed_ts[t] = t_ return t_
[ "def", "_transform_t", "(", "self", ",", "t", ")", ":", "if", "t", "in", "self", ".", "_info", ".", "transformed_ts", ":", "return", "self", ".", "_info", ".", "transformed_ts", "[", "t", "]", "op", ",", "op_index", "=", "t", ".", "op", ",", "t", ...
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/graph_editor/transform.py#L502-L533
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/propgrid.py
python
PropertyGridInterface.GetFirstChild
(*args, **kwargs)
return _propgrid.PropertyGridInterface_GetFirstChild(*args, **kwargs)
GetFirstChild(self, PGPropArg id) -> PGProperty
GetFirstChild(self, PGPropArg id) -> PGProperty
[ "GetFirstChild", "(", "self", "PGPropArg", "id", ")", "-", ">", "PGProperty" ]
def GetFirstChild(*args, **kwargs): """GetFirstChild(self, PGPropArg id) -> PGProperty""" return _propgrid.PropertyGridInterface_GetFirstChild(*args, **kwargs)
[ "def", "GetFirstChild", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PropertyGridInterface_GetFirstChild", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L1162-L1164
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/ftplib.py
python
FTP.abort
(self)
return resp
Abort a file transfer. Uses out-of-band data. This does not follow the procedure from the RFC to send Telnet IP and Synch; that doesn't seem to work with the servers I've tried. Instead, just send the ABOR command as OOB data.
Abort a file transfer. Uses out-of-band data. This does not follow the procedure from the RFC to send Telnet IP and Synch; that doesn't seem to work with the servers I've tried. Instead, just send the ABOR command as OOB data.
[ "Abort", "a", "file", "transfer", ".", "Uses", "out", "-", "of", "-", "band", "data", ".", "This", "does", "not", "follow", "the", "procedure", "from", "the", "RFC", "to", "send", "Telnet", "IP", "and", "Synch", ";", "that", "doesn", "t", "seem", "to...
def abort(self): '''Abort a file transfer. Uses out-of-band data. This does not follow the procedure from the RFC to send Telnet IP and Synch; that doesn't seem to work with the servers I've tried. Instead, just send the ABOR command as OOB data.''' line = b'ABOR' + B_CRLF if self.debugging > 1: print('*put urgent*', self.sanitize(line)) self.sock.sendall(line, MSG_OOB) resp = self.getmultiline() if resp[:3] not in {'426', '225', '226'}: raise error_proto(resp) return resp
[ "def", "abort", "(", "self", ")", ":", "line", "=", "b'ABOR'", "+", "B_CRLF", "if", "self", ".", "debugging", ">", "1", ":", "print", "(", "'*put urgent*'", ",", "self", ".", "sanitize", "(", "line", ")", ")", "self", ".", "sock", ".", "sendall", "...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/ftplib.py#L264-L276
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/stata.py
python
StataWriter._prepare_categoricals
(self, data)
return DataFrame.from_dict(dict(data_formatted))
Check for categorical columns, retain categorical information for Stata file and convert categorical data to int
Check for categorical columns, retain categorical information for Stata file and convert categorical data to int
[ "Check", "for", "categorical", "columns", "retain", "categorical", "information", "for", "Stata", "file", "and", "convert", "categorical", "data", "to", "int" ]
def _prepare_categoricals(self, data): """Check for categorical columns, retain categorical information for Stata file and convert categorical data to int""" is_cat = [is_categorical_dtype(data[col]) for col in data] self._is_col_cat = is_cat self._value_labels = [] if not any(is_cat): return data get_base_missing_value = StataMissingValue.get_base_missing_value data_formatted = [] for col, col_is_cat in zip(data, is_cat): if col_is_cat: svl = StataValueLabel(data[col], encoding=self._encoding) self._value_labels.append(svl) dtype = data[col].cat.codes.dtype if dtype == np.int64: raise ValueError( "It is not possible to export " "int64-based categorical data to Stata." ) values = data[col].cat.codes.values.copy() # Upcast if needed so that correct missing values can be set if values.max() >= get_base_missing_value(dtype): if dtype == np.int8: dtype = np.int16 elif dtype == np.int16: dtype = np.int32 else: dtype = np.float64 values = np.array(values, dtype=dtype) # Replace missing values with Stata missing value for type values[values == -1] = get_base_missing_value(dtype) data_formatted.append((col, values)) else: data_formatted.append((col, data[col])) return DataFrame.from_dict(dict(data_formatted))
[ "def", "_prepare_categoricals", "(", "self", ",", "data", ")", ":", "is_cat", "=", "[", "is_categorical_dtype", "(", "data", "[", "col", "]", ")", "for", "col", "in", "data", "]", "self", ".", "_is_col_cat", "=", "is_cat", "self", ".", "_value_labels", "...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/stata.py#L2095-L2134
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/python/requests/requests/packages/urllib3/filepost.py
python
choose_boundary
()
return uuid4().hex
Our embarassingly-simple replacement for mimetools.choose_boundary.
Our embarassingly-simple replacement for mimetools.choose_boundary.
[ "Our", "embarassingly", "-", "simple", "replacement", "for", "mimetools", ".", "choose_boundary", "." ]
def choose_boundary(): """ Our embarassingly-simple replacement for mimetools.choose_boundary. """ return uuid4().hex
[ "def", "choose_boundary", "(", ")", ":", "return", "uuid4", "(", ")", ".", "hex" ]
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/requests/requests/packages/urllib3/filepost.py#L13-L17
MythTV/mythtv
d282a209cb8be85d036f85a62a8ec971b67d45f4
mythtv/programs/scripts/internetcontent/nv_python_libs/mashups/mashups_api.py
python
OutStreamEncoder.__getattr__
(self, attr)
return getattr(self.out, attr)
Delegate everything but write to the stream
Delegate everything but write to the stream
[ "Delegate", "everything", "but", "write", "to", "the", "stream" ]
def __getattr__(self, attr): """Delegate everything but write to the stream""" return getattr(self.out, attr)
[ "def", "__getattr__", "(", "self", ",", "attr", ")", ":", "return", "getattr", "(", "self", ".", "out", ",", "attr", ")" ]
https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/programs/scripts/internetcontent/nv_python_libs/mashups/mashups_api.py#L54-L56
moflow/moflow
2dfb27c799c90c6caf1477508eca3eec616ef7d2
bap/libtracewrap/libtrace/protobuf/python/google/protobuf/internal/python_message.py
python
_ExtensionDict.__setitem__
(self, extension_handle, value)
If extension_handle specifies a non-repeated, scalar extension field, sets the value of that field.
If extension_handle specifies a non-repeated, scalar extension field, sets the value of that field.
[ "If", "extension_handle", "specifies", "a", "non", "-", "repeated", "scalar", "extension", "field", "sets", "the", "value", "of", "that", "field", "." ]
def __setitem__(self, extension_handle, value): """If extension_handle specifies a non-repeated, scalar extension field, sets the value of that field. """ _VerifyExtensionHandle(self._extended_message, extension_handle) if (extension_handle.label == _FieldDescriptor.LABEL_REPEATED or extension_handle.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE): raise TypeError( 'Cannot assign to extension "%s" because it is a repeated or ' 'composite type.' % extension_handle.full_name) # It's slightly wasteful to lookup the type checker each time, # but we expect this to be a vanishingly uncommon case anyway. type_checker = type_checkers.GetTypeChecker( extension_handle.cpp_type, extension_handle.type) type_checker.CheckValue(value) self._extended_message._fields[extension_handle] = value self._extended_message._Modified()
[ "def", "__setitem__", "(", "self", ",", "extension_handle", ",", "value", ")", ":", "_VerifyExtensionHandle", "(", "self", ".", "_extended_message", ",", "extension_handle", ")", "if", "(", "extension_handle", ".", "label", "==", "_FieldDescriptor", ".", "LABEL_RE...
https://github.com/moflow/moflow/blob/2dfb27c799c90c6caf1477508eca3eec616ef7d2/bap/libtracewrap/libtrace/protobuf/python/google/protobuf/internal/python_message.py#L1120-L1139
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/closure_linter/closure_linter/common/erroraccumulator.py
python
ErrorAccumulator.HandleError
(self, error)
Append the error to the list. Args: error: The error object
Append the error to the list.
[ "Append", "the", "error", "to", "the", "list", "." ]
def HandleError(self, error): """Append the error to the list. Args: error: The error object """ self._errors.append(error)
[ "def", "HandleError", "(", "self", ",", "error", ")", ":", "self", ".", "_errors", ".", "append", "(", "error", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/closure_linter/closure_linter/common/erroraccumulator.py#L32-L38
etotheipi/BitcoinArmory
2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98
armoryengine/ArmoryUtils.py
python
checkAddrBinValid
(addrBin, validPrefixes=None)
return (checkAddrType(addrBin) in validPrefixes)
Checks whether this address is valid for the given network (set at the top of pybtcengine.py)
Checks whether this address is valid for the given network (set at the top of pybtcengine.py)
[ "Checks", "whether", "this", "address", "is", "valid", "for", "the", "given", "network", "(", "set", "at", "the", "top", "of", "pybtcengine", ".", "py", ")" ]
def checkAddrBinValid(addrBin, validPrefixes=None): """ Checks whether this address is valid for the given network (set at the top of pybtcengine.py) """ if validPrefixes is None: validPrefixes = [ADDRBYTE, P2SHBYTE] if not isinstance(validPrefixes, list): validPrefixes = [validPrefixes] return (checkAddrType(addrBin) in validPrefixes)
[ "def", "checkAddrBinValid", "(", "addrBin", ",", "validPrefixes", "=", "None", ")", ":", "if", "validPrefixes", "is", "None", ":", "validPrefixes", "=", "[", "ADDRBYTE", ",", "P2SHBYTE", "]", "if", "not", "isinstance", "(", "validPrefixes", ",", "list", ")",...
https://github.com/etotheipi/BitcoinArmory/blob/2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98/armoryengine/ArmoryUtils.py#L2760-L2771
xhzdeng/crpn
a5aef0f80dbe486103123f740c634fb01e6cc9a1
lib/setup.py
python
locate_cuda
()
return cudaconfig
Locate the CUDA environment on the system Returns a dict with keys 'home', 'nvcc', 'include', and 'lib64' and values giving the absolute path to each directory. Starts by looking for the CUDAHOME env variable. If not found, everything is based on finding 'nvcc' in the PATH.
Locate the CUDA environment on the system
[ "Locate", "the", "CUDA", "environment", "on", "the", "system" ]
def locate_cuda(): """Locate the CUDA environment on the system Returns a dict with keys 'home', 'nvcc', 'include', and 'lib64' and values giving the absolute path to each directory. Starts by looking for the CUDAHOME env variable. If not found, everything is based on finding 'nvcc' in the PATH. """ # first check if the CUDAHOME env variable is in use if 'CUDAHOME' in os.environ: home = os.environ['CUDAHOME'] nvcc = pjoin(home, 'bin', 'nvcc') else: # otherwise, search the PATH for NVCC default_path = pjoin(os.sep, 'usr', 'local', 'cuda', 'bin') nvcc = find_in_path('nvcc', os.environ['PATH'] + os.pathsep + default_path) if nvcc is None: raise EnvironmentError('The nvcc binary could not be ' 'located in your $PATH. Either add it to your path, or set $CUDAHOME') home = os.path.dirname(os.path.dirname(nvcc)) cudaconfig = {'home':home, 'nvcc':nvcc, 'include': pjoin(home, 'include'), 'lib64': pjoin(home, 'lib64')} for k, v in cudaconfig.iteritems(): if not os.path.exists(v): raise EnvironmentError('The CUDA %s path could not be located in %s' % (k, v)) return cudaconfig
[ "def", "locate_cuda", "(", ")", ":", "# first check if the CUDAHOME env variable is in use", "if", "'CUDAHOME'", "in", "os", ".", "environ", ":", "home", "=", "os", ".", "environ", "[", "'CUDAHOME'", "]", "nvcc", "=", "pjoin", "(", "home", ",", "'bin'", ",", ...
https://github.com/xhzdeng/crpn/blob/a5aef0f80dbe486103123f740c634fb01e6cc9a1/lib/setup.py#L27-L57
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/jira/client.py
python
JIRA.resolutions
(self)
return resolutions
Get a list of resolution Resources from the server.
Get a list of resolution Resources from the server.
[ "Get", "a", "list", "of", "resolution", "Resources", "from", "the", "server", "." ]
def resolutions(self): """Get a list of resolution Resources from the server.""" r_json = self._get_json('resolution') resolutions = [Resolution( self._options, self._session, raw_res_json) for raw_res_json in r_json] return resolutions
[ "def", "resolutions", "(", "self", ")", ":", "r_json", "=", "self", ".", "_get_json", "(", "'resolution'", ")", "resolutions", "=", "[", "Resolution", "(", "self", ".", "_options", ",", "self", ".", "_session", ",", "raw_res_json", ")", "for", "raw_res_jso...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/jira/client.py#L2019-L2024
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/telemetry/benchmark.py
python
Benchmark.CustomizeBrowserOptions
(self, options)
Add browser options that are required by this benchmark.
Add browser options that are required by this benchmark.
[ "Add", "browser", "options", "that", "are", "required", "by", "this", "benchmark", "." ]
def CustomizeBrowserOptions(self, options): """Add browser options that are required by this benchmark."""
[ "def", "CustomizeBrowserOptions", "(", "self", ",", "options", ")", ":" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/benchmark.py#L205-L206
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/polynomial/chebyshev.py
python
chebfit
(x, y, deg, rcond=None, full=False, w=None)
Least squares fit of Chebyshev series to data. Return the coefficients of a Legendre series of degree `deg` that is the least squares fit to the data values `y` given at points `x`. If `y` is 1-D the returned coefficients will also be 1-D. If `y` is 2-D multiple fits are done, one for each column of `y`, and the resulting coefficients are stored in the corresponding columns of a 2-D return. The fitted polynomial(s) are in the form .. math:: p(x) = c_0 + c_1 * T_1(x) + ... + c_n * T_n(x), where `n` is `deg`. Since numpy version 1.7.0, chebfit also supports NA. If any of the elements of `x`, `y`, or `w` are NA, then the corresponding rows of the linear least squares problem (see Notes) are set to 0. If `y` is 2-D, then an NA in any row of `y` invalidates that whole row. Parameters ---------- x : array_like, shape (M,) x-coordinates of the M sample points ``(x[i], y[i])``. y : array_like, shape (M,) or (M, K) y-coordinates of the sample points. Several data sets of sample points sharing the same x-coordinates can be fitted at once by passing in a 2D-array that contains one dataset per column. deg : int Degree of the fitting series rcond : float, optional Relative condition number of the fit. Singular values smaller than this relative to the largest singular value will be ignored. The default value is len(x)*eps, where eps is the relative precision of the float type, about 2e-16 in most cases. full : bool, optional Switch determining nature of return value. When it is False (the default) just the coefficients are returned, when True diagnostic information from the singular value decomposition is also returned. w : array_like, shape (`M`,), optional Weights. If not None, the contribution of each point ``(x[i],y[i])`` to the fit is weighted by `w[i]`. Ideally the weights are chosen so that the errors of the products ``w[i]*y[i]`` all have the same variance. The default value is None. .. versionadded:: 1.5.0 Returns ------- coef : ndarray, shape (M,) or (M, K) Chebyshev coefficients ordered from low to high. If `y` was 2-D, the coefficients for the data in column k of `y` are in column `k`. [residuals, rank, singular_values, rcond] : present when `full` = True Residuals of the least-squares fit, the effective rank of the scaled Vandermonde matrix and its singular values, and the specified value of `rcond`. For more details, see `linalg.lstsq`. Warns ----- RankWarning The rank of the coefficient matrix in the least-squares fit is deficient. The warning is only raised if `full` = False. The warnings can be turned off by >>> import warnings >>> warnings.simplefilter('ignore', RankWarning) See Also -------- polyfit, legfit, lagfit, hermfit, hermefit chebval : Evaluates a Chebyshev series. chebvander : Vandermonde matrix of Chebyshev series. chebweight : Chebyshev weight function. linalg.lstsq : Computes a least-squares fit from the matrix. scipy.interpolate.UnivariateSpline : Computes spline fits. Notes ----- The solution is the coefficients of the Chebyshev series `p` that minimizes the sum of the weighted squared errors .. math:: E = \\sum_j w_j^2 * |y_j - p(x_j)|^2, where :math:`w_j` are the weights. This problem is solved by setting up as the (typically) overdetermined matrix equation .. math:: V(x) * c = w * y, where `V` is the weighted pseudo Vandermonde matrix of `x`, `c` are the coefficients to be solved for, `w` are the weights, and `y` are the observed values. This equation is then solved using the singular value decomposition of `V`. If some of the singular values of `V` are so small that they are neglected, then a `RankWarning` will be issued. This means that the coefficient values may be poorly determined. Using a lower order fit will usually get rid of the warning. The `rcond` parameter can also be set to a value smaller than its default, but the resulting fit may be spurious and have large contributions from roundoff error. Fits using Chebyshev series are usually better conditioned than fits using power series, but much can depend on the distribution of the sample points and the smoothness of the data. If the quality of the fit is inadequate splines may be a good alternative. References ---------- .. [1] Wikipedia, "Curve fitting", http://en.wikipedia.org/wiki/Curve_fitting Examples --------
Least squares fit of Chebyshev series to data.
[ "Least", "squares", "fit", "of", "Chebyshev", "series", "to", "data", "." ]
def chebfit(x, y, deg, rcond=None, full=False, w=None): """ Least squares fit of Chebyshev series to data. Return the coefficients of a Legendre series of degree `deg` that is the least squares fit to the data values `y` given at points `x`. If `y` is 1-D the returned coefficients will also be 1-D. If `y` is 2-D multiple fits are done, one for each column of `y`, and the resulting coefficients are stored in the corresponding columns of a 2-D return. The fitted polynomial(s) are in the form .. math:: p(x) = c_0 + c_1 * T_1(x) + ... + c_n * T_n(x), where `n` is `deg`. Since numpy version 1.7.0, chebfit also supports NA. If any of the elements of `x`, `y`, or `w` are NA, then the corresponding rows of the linear least squares problem (see Notes) are set to 0. If `y` is 2-D, then an NA in any row of `y` invalidates that whole row. Parameters ---------- x : array_like, shape (M,) x-coordinates of the M sample points ``(x[i], y[i])``. y : array_like, shape (M,) or (M, K) y-coordinates of the sample points. Several data sets of sample points sharing the same x-coordinates can be fitted at once by passing in a 2D-array that contains one dataset per column. deg : int Degree of the fitting series rcond : float, optional Relative condition number of the fit. Singular values smaller than this relative to the largest singular value will be ignored. The default value is len(x)*eps, where eps is the relative precision of the float type, about 2e-16 in most cases. full : bool, optional Switch determining nature of return value. When it is False (the default) just the coefficients are returned, when True diagnostic information from the singular value decomposition is also returned. w : array_like, shape (`M`,), optional Weights. If not None, the contribution of each point ``(x[i],y[i])`` to the fit is weighted by `w[i]`. Ideally the weights are chosen so that the errors of the products ``w[i]*y[i]`` all have the same variance. The default value is None. .. versionadded:: 1.5.0 Returns ------- coef : ndarray, shape (M,) or (M, K) Chebyshev coefficients ordered from low to high. If `y` was 2-D, the coefficients for the data in column k of `y` are in column `k`. [residuals, rank, singular_values, rcond] : present when `full` = True Residuals of the least-squares fit, the effective rank of the scaled Vandermonde matrix and its singular values, and the specified value of `rcond`. For more details, see `linalg.lstsq`. Warns ----- RankWarning The rank of the coefficient matrix in the least-squares fit is deficient. The warning is only raised if `full` = False. The warnings can be turned off by >>> import warnings >>> warnings.simplefilter('ignore', RankWarning) See Also -------- polyfit, legfit, lagfit, hermfit, hermefit chebval : Evaluates a Chebyshev series. chebvander : Vandermonde matrix of Chebyshev series. chebweight : Chebyshev weight function. linalg.lstsq : Computes a least-squares fit from the matrix. scipy.interpolate.UnivariateSpline : Computes spline fits. Notes ----- The solution is the coefficients of the Chebyshev series `p` that minimizes the sum of the weighted squared errors .. math:: E = \\sum_j w_j^2 * |y_j - p(x_j)|^2, where :math:`w_j` are the weights. This problem is solved by setting up as the (typically) overdetermined matrix equation .. math:: V(x) * c = w * y, where `V` is the weighted pseudo Vandermonde matrix of `x`, `c` are the coefficients to be solved for, `w` are the weights, and `y` are the observed values. This equation is then solved using the singular value decomposition of `V`. If some of the singular values of `V` are so small that they are neglected, then a `RankWarning` will be issued. This means that the coefficient values may be poorly determined. Using a lower order fit will usually get rid of the warning. The `rcond` parameter can also be set to a value smaller than its default, but the resulting fit may be spurious and have large contributions from roundoff error. Fits using Chebyshev series are usually better conditioned than fits using power series, but much can depend on the distribution of the sample points and the smoothness of the data. If the quality of the fit is inadequate splines may be a good alternative. References ---------- .. [1] Wikipedia, "Curve fitting", http://en.wikipedia.org/wiki/Curve_fitting Examples -------- """ order = int(deg) + 1 x = np.asarray(x) + 0.0 y = np.asarray(y) + 0.0 # check arguments. if deg < 0 : raise ValueError("expected deg >= 0") if x.ndim != 1: raise TypeError("expected 1D vector for x") if x.size == 0: raise TypeError("expected non-empty vector for x") if y.ndim < 1 or y.ndim > 2 : raise TypeError("expected 1D or 2D array for y") if len(x) != len(y): raise TypeError("expected x and y to have same length") # set up the least squares matrices in transposed form lhs = chebvander(x, deg).T rhs = y.T if w is not None: w = np.asarray(w) + 0.0 if w.ndim != 1: raise TypeError("expected 1D vector for w") if len(x) != len(w): raise TypeError("expected x and w to have same length") # apply weights. Don't use inplace operations as they # can cause problems with NA. lhs = lhs * w rhs = rhs * w # set rcond if rcond is None : rcond = len(x)*np.finfo(x.dtype).eps # Determine the norms of the design matrix columns. if issubclass(lhs.dtype.type, np.complexfloating): scl = np.sqrt((np.square(lhs.real) + np.square(lhs.imag)).sum(1)) else: scl = np.sqrt(np.square(lhs).sum(1)) scl[scl == 0] = 1 # Solve the least squares problem. c, resids, rank, s = la.lstsq(lhs.T/scl, rhs.T, rcond) c = (c.T/scl).T # warn on rank reduction if rank != order and not full: msg = "The fit may be poorly conditioned" warnings.warn(msg, pu.RankWarning) if full : return c, [resids, rank, s, rcond] else : return c
[ "def", "chebfit", "(", "x", ",", "y", ",", "deg", ",", "rcond", "=", "None", ",", "full", "=", "False", ",", "w", "=", "None", ")", ":", "order", "=", "int", "(", "deg", ")", "+", "1", "x", "=", "np", ".", "asarray", "(", "x", ")", "+", "...
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/polynomial/chebyshev.py#L1595-L1764
stellar-deprecated/stellard
67eabb2217bdfa9a6ea317f62338fb6bca458c90
src/protobuf/python/google/protobuf/descriptor_pool.py
python
DescriptorPool._ExtractMessages
(self, desc_protos)
Pulls out all the message protos from descriptos. Args: desc_protos: The protos to extract symbols from. Yields: Descriptor protos.
Pulls out all the message protos from descriptos.
[ "Pulls", "out", "all", "the", "message", "protos", "from", "descriptos", "." ]
def _ExtractMessages(self, desc_protos): """Pulls out all the message protos from descriptos. Args: desc_protos: The protos to extract symbols from. Yields: Descriptor protos. """ for desc_proto in desc_protos: yield desc_proto for message in self._ExtractMessages(desc_proto.nested_type): yield message
[ "def", "_ExtractMessages", "(", "self", ",", "desc_protos", ")", ":", "for", "desc_proto", "in", "desc_protos", ":", "yield", "desc_proto", "for", "message", "in", "self", ".", "_ExtractMessages", "(", "desc_proto", ".", "nested_type", ")", ":", "yield", "mess...
https://github.com/stellar-deprecated/stellard/blob/67eabb2217bdfa9a6ea317f62338fb6bca458c90/src/protobuf/python/google/protobuf/descriptor_pool.py#L496-L509
infinit/memo
3a8394d0f647efe03ccb8bfe885a7279cb8be8a6
elle/drake/src/drake/__init__.py
python
include
(path, *args, **kwargs)
Include a sub-drakefile. path -- Path to the directory where the drakefile is located. args, kwargs -- Arguments for the drakefile's configure. Load the drakefile found in the specified directory, merge its graph with ours and return an object that has all variables defined globally by the sub-drakefile as attributes.
Include a sub-drakefile.
[ "Include", "a", "sub", "-", "drakefile", "." ]
def include(path, *args, **kwargs): """Include a sub-drakefile. path -- Path to the directory where the drakefile is located. args, kwargs -- Arguments for the drakefile's configure. Load the drakefile found in the specified directory, merge its graph with ours and return an object that has all variables defined globally by the sub-drakefile as attributes. """ path = Path(path) with Drake.current.recurse(path): drakefile = None names = ['drakefile', 'drakefile.py'] for name in names: path = drake.path_source(name) if path.exists(): drakefile = path break if drakefile is None: raise Exception('cannot find %s or %s in %s' % \ (', '.join(names[:-1]), names[-1], path)) res = _raw_include(str(drakefile), *args, **kwargs) return res
[ "def", "include", "(", "path", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "path", "=", "Path", "(", "path", ")", "with", "Drake", ".", "current", ".", "recurse", "(", "path", ")", ":", "drakefile", "=", "None", "names", "=", "[", "'drak...
https://github.com/infinit/memo/blob/3a8394d0f647efe03ccb8bfe885a7279cb8be8a6/elle/drake/src/drake/__init__.py#L2861-L2885
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/mailbox.py
python
_ProxyFile._read
(self, size, read_method)
return result
Read size bytes using read_method.
Read size bytes using read_method.
[ "Read", "size", "bytes", "using", "read_method", "." ]
def _read(self, size, read_method): """Read size bytes using read_method.""" if size is None: size = -1 self._file.seek(self._pos) result = read_method(size) self._pos = self._file.tell() return result
[ "def", "_read", "(", "self", ",", "size", ",", "read_method", ")", ":", "if", "size", "is", "None", ":", "size", "=", "-", "1", "self", ".", "_file", ".", "seek", "(", "self", ".", "_pos", ")", "result", "=", "read_method", "(", "size", ")", "sel...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/mailbox.py#L1982-L1989
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
samples/pydocview/FindService.py
python
FindService.GetReplaceString
(self)
return wx.ConfigBase_Get().Read(FIND_MATCHREPLACE, "")
Load the replace pattern from registry
Load the replace pattern from registry
[ "Load", "the", "replace", "pattern", "from", "registry" ]
def GetReplaceString(self): """ Load the replace pattern from registry """ return wx.ConfigBase_Get().Read(FIND_MATCHREPLACE, "")
[ "def", "GetReplaceString", "(", "self", ")", ":", "return", "wx", ".", "ConfigBase_Get", "(", ")", ".", "Read", "(", "FIND_MATCHREPLACE", ",", "\"\"", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/samples/pydocview/FindService.py#L297-L299
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py3/numpy/lib/recfunctions.py
python
_izip_fields
(iterable)
Returns an iterator of concatenated fields from a sequence of arrays.
Returns an iterator of concatenated fields from a sequence of arrays.
[ "Returns", "an", "iterator", "of", "concatenated", "fields", "from", "a", "sequence", "of", "arrays", "." ]
def _izip_fields(iterable): """ Returns an iterator of concatenated fields from a sequence of arrays. """ for element in iterable: if (hasattr(element, '__iter__') and not isinstance(element, str)): yield from _izip_fields(element) elif isinstance(element, np.void) and len(tuple(element)) == 1: # this statement is the same from the previous expression yield from _izip_fields(element) else: yield element
[ "def", "_izip_fields", "(", "iterable", ")", ":", "for", "element", "in", "iterable", ":", "if", "(", "hasattr", "(", "element", ",", "'__iter__'", ")", "and", "not", "isinstance", "(", "element", ",", "str", ")", ")", ":", "yield", "from", "_izip_fields...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/lib/recfunctions.py#L293-L306
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/_grad/grad_array_ops.py
python
get_bprop_flatten
(self)
return bprop
Generate bprop for Flatten
Generate bprop for Flatten
[ "Generate", "bprop", "for", "Flatten" ]
def get_bprop_flatten(self): """Generate bprop for Flatten""" flatten_grad = P.Reshape() def bprop(x, out, dout): dx = flatten_grad(dout, shape_op(x)) return (dx,) return bprop
[ "def", "get_bprop_flatten", "(", "self", ")", ":", "flatten_grad", "=", "P", ".", "Reshape", "(", ")", "def", "bprop", "(", "x", ",", "out", ",", "dout", ")", ":", "dx", "=", "flatten_grad", "(", "dout", ",", "shape_op", "(", "x", ")", ")", "return...
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_grad/grad_array_ops.py#L217-L225
idaholab/moose
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
python/moosesqa/check_syntax.py
python
file_is_stub
(filename)
return False
Helper for getting stub status for markdown file
Helper for getting stub status for markdown file
[ "Helper", "for", "getting", "stub", "status", "for", "markdown", "file" ]
def file_is_stub(filename): """Helper for getting stub status for markdown file""" with open(filename, 'r') as fid: content = fid.read() # Empty is considered a stub if not content: return True # Old template method elif '.md.template' in content: return True # Even older comment method elif '!! MOOSE Documentation Stub (remove this when content is added)' in content: return True # Current alert method elif '!alert! construction title=Undocumented' in content: return True # Even more current alert method elif '!alert construction title=Undocumented' in content: return True return False
[ "def", "file_is_stub", "(", "filename", ")", ":", "with", "open", "(", "filename", ",", "'r'", ")", "as", "fid", ":", "content", "=", "fid", ".", "read", "(", ")", "# Empty is considered a stub", "if", "not", "content", ":", "return", "True", "# Old templa...
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/moosesqa/check_syntax.py#L104-L124
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/linalg/linalg.py
python
_multi_dot_matrix_chain_order
(arrays, return_costs=False)
return (s, m) if return_costs else s
Return a np.array that encodes the optimal order of mutiplications. The optimal order array is then used by `_multi_dot()` to do the multiplication. Also return the cost matrix if `return_costs` is `True` The implementation CLOSELY follows Cormen, "Introduction to Algorithms", Chapter 15.2, p. 370-378. Note that Cormen uses 1-based indices. cost[i, j] = min([ cost[prefix] + cost[suffix] + cost_mult(prefix, suffix) for k in range(i, j)])
Return a np.array that encodes the optimal order of mutiplications.
[ "Return", "a", "np", ".", "array", "that", "encodes", "the", "optimal", "order", "of", "mutiplications", "." ]
def _multi_dot_matrix_chain_order(arrays, return_costs=False): """ Return a np.array that encodes the optimal order of mutiplications. The optimal order array is then used by `_multi_dot()` to do the multiplication. Also return the cost matrix if `return_costs` is `True` The implementation CLOSELY follows Cormen, "Introduction to Algorithms", Chapter 15.2, p. 370-378. Note that Cormen uses 1-based indices. cost[i, j] = min([ cost[prefix] + cost[suffix] + cost_mult(prefix, suffix) for k in range(i, j)]) """ n = len(arrays) # p stores the dimensions of the matrices # Example for p: A_{10x100}, B_{100x5}, C_{5x50} --> p = [10, 100, 5, 50] p = [a.shape[0] for a in arrays] + [arrays[-1].shape[1]] # m is a matrix of costs of the subproblems # m[i,j]: min number of scalar multiplications needed to compute A_{i..j} m = zeros((n, n), dtype=double) # s is the actual ordering # s[i, j] is the value of k at which we split the product A_i..A_j s = empty((n, n), dtype=intp) for l in range(1, n): for i in range(n - l): j = i + l m[i, j] = Inf for k in range(i, j): q = m[i, k] + m[k+1, j] + p[i]*p[k+1]*p[j+1] if q < m[i, j]: m[i, j] = q s[i, j] = k # Note that Cormen uses 1-based index return (s, m) if return_costs else s
[ "def", "_multi_dot_matrix_chain_order", "(", "arrays", ",", "return_costs", "=", "False", ")", ":", "n", "=", "len", "(", "arrays", ")", "# p stores the dimensions of the matrices", "# Example for p: A_{10x100}, B_{100x5}, C_{5x50} --> p = [10, 100, 5, 50]", "p", "=", "[", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/linalg/linalg.py#L2699-L2737
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py
python
PanedWindow.sash_place
(self, index, x, y)
return self.sash("place", index, x, y)
Place the sash given by index at the given coordinates
Place the sash given by index at the given coordinates
[ "Place", "the", "sash", "given", "by", "index", "at", "the", "given", "coordinates" ]
def sash_place(self, index, x, y): """Place the sash given by index at the given coordinates """ return self.sash("place", index, x, y)
[ "def", "sash_place", "(", "self", ",", "index", ",", "x", ",", "y", ")", ":", "return", "self", ".", "sash", "(", "\"place\"", ",", "index", ",", "x", ",", "y", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py#L3891-L3894
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/mapreduce/mapreduce/input_readers.py
python
BlobstoreZipLineInputReader.validate
(cls, mapper_spec)
Validates mapper spec and all mapper parameters. Args: mapper_spec: The MapperSpec for this InputReader. Raises: BadReaderParamsError: required parameters are missing or invalid.
Validates mapper spec and all mapper parameters.
[ "Validates", "mapper", "spec", "and", "all", "mapper", "parameters", "." ]
def validate(cls, mapper_spec): """Validates mapper spec and all mapper parameters. Args: mapper_spec: The MapperSpec for this InputReader. Raises: BadReaderParamsError: required parameters are missing or invalid. """ if mapper_spec.input_reader_class() != cls: raise BadReaderParamsError("Mapper input reader class mismatch") params = _get_params(mapper_spec) if cls.BLOB_KEYS_PARAM not in params: raise BadReaderParamsError("Must specify 'blob_keys' for mapper input") blob_keys = params[cls.BLOB_KEYS_PARAM] if isinstance(blob_keys, basestring): # This is a mechanism to allow multiple blob keys (which do not contain # commas) in a single string. It may go away. blob_keys = blob_keys.split(",") if len(blob_keys) > cls._MAX_BLOB_KEYS_COUNT: raise BadReaderParamsError("Too many 'blob_keys' for mapper input") if not blob_keys: raise BadReaderParamsError("No 'blob_keys' specified for mapper input") for blob_key in blob_keys: blob_info = blobstore.BlobInfo.get(blobstore.BlobKey(blob_key)) if not blob_info: raise BadReaderParamsError("Could not find blobinfo for key %s" % blob_key)
[ "def", "validate", "(", "cls", ",", "mapper_spec", ")", ":", "if", "mapper_spec", ".", "input_reader_class", "(", ")", "!=", "cls", ":", "raise", "BadReaderParamsError", "(", "\"Mapper input reader class mismatch\"", ")", "params", "=", "_get_params", "(", "mapper...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/mapreduce/mapreduce/input_readers.py#L1657-L1685
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/graphviz/py2/graphviz/backend.py
python
run
(cmd, input=None, capture_output=False, check=False, encoding=None, quiet=False, **kwargs)
return out, err
Run the command described by cmd and return its (stdout, stderr) tuple.
Run the command described by cmd and return its (stdout, stderr) tuple.
[ "Run", "the", "command", "described", "by", "cmd", "and", "return", "its", "(", "stdout", "stderr", ")", "tuple", "." ]
def run(cmd, input=None, capture_output=False, check=False, encoding=None, quiet=False, **kwargs): """Run the command described by cmd and return its (stdout, stderr) tuple.""" log.debug('run %r', cmd) if input is not None: kwargs['stdin'] = subprocess.PIPE if encoding is not None: input = input.encode(encoding) if capture_output: kwargs['stdout'] = kwargs['stderr'] = subprocess.PIPE try: proc = subprocess.Popen(cmd, startupinfo=get_startupinfo(), **kwargs) except OSError as e: if e.errno == errno.ENOENT: raise ExecutableNotFound(cmd) else: raise out, err = proc.communicate(input) if not quiet and err: _compat.stderr_write_bytes(err, flush=True) if encoding is not None: if out is not None: out = out.decode(encoding) if err is not None: err = err.decode(encoding) if check and proc.returncode: raise CalledProcessError(proc.returncode, cmd, output=out, stderr=err) return out, err
[ "def", "run", "(", "cmd", ",", "input", "=", "None", ",", "capture_output", "=", "False", ",", "check", "=", "False", ",", "encoding", "=", "None", ",", "quiet", "=", "False", ",", "*", "*", "kwargs", ")", ":", "log", ".", "debug", "(", "'run %r'",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/graphviz/py2/graphviz/backend.py#L150-L186
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/series.py
python
Series.to_timestamp
(self, freq=None, how="start", copy=True)
return self._constructor(new_values, index=new_index).__finalize__(self)
Cast to DatetimeIndex of Timestamps, at *beginning* of period. Parameters ---------- freq : str, default frequency of PeriodIndex Desired frequency. how : {'s', 'e', 'start', 'end'} Convention for converting period to timestamp; start of period vs. end. copy : bool, default True Whether or not to return a copy. Returns ------- Series with DatetimeIndex
Cast to DatetimeIndex of Timestamps, at *beginning* of period.
[ "Cast", "to", "DatetimeIndex", "of", "Timestamps", "at", "*", "beginning", "*", "of", "period", "." ]
def to_timestamp(self, freq=None, how="start", copy=True): """ Cast to DatetimeIndex of Timestamps, at *beginning* of period. Parameters ---------- freq : str, default frequency of PeriodIndex Desired frequency. how : {'s', 'e', 'start', 'end'} Convention for converting period to timestamp; start of period vs. end. copy : bool, default True Whether or not to return a copy. Returns ------- Series with DatetimeIndex """ new_values = self._values if copy: new_values = new_values.copy() new_index = self.index.to_timestamp(freq=freq, how=how) return self._constructor(new_values, index=new_index).__finalize__(self)
[ "def", "to_timestamp", "(", "self", ",", "freq", "=", "None", ",", "how", "=", "\"start\"", ",", "copy", "=", "True", ")", ":", "new_values", "=", "self", ".", "_values", "if", "copy", ":", "new_values", "=", "new_values", ".", "copy", "(", ")", "new...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/series.py#L4507-L4530
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/controls.py
python
TokenListControl.mouse_handler
(self, cli, mouse_event)
return NotImplemented
Handle mouse events. (When the token list contained mouse handlers and the user clicked on on any of these, the matching handler is called. This handler can still return `NotImplemented` in case we want the `Window` to handle this particular event.)
Handle mouse events.
[ "Handle", "mouse", "events", "." ]
def mouse_handler(self, cli, mouse_event): """ Handle mouse events. (When the token list contained mouse handlers and the user clicked on on any of these, the matching handler is called. This handler can still return `NotImplemented` in case we want the `Window` to handle this particular event.) """ if self._tokens: # Read the generator. tokens_for_line = list(split_lines(self._tokens)) try: tokens = tokens_for_line[mouse_event.position.y] except IndexError: return NotImplemented else: # Find position in the token list. xpos = mouse_event.position.x # Find mouse handler for this character. count = 0 for item in tokens: count += len(item[1]) if count >= xpos: if len(item) >= 3: # Handler found. Call it. # (Handler can return NotImplemented, so return # that result.) handler = item[2] return handler(cli, mouse_event) else: break # Otherwise, don't handle here. return NotImplemented
[ "def", "mouse_handler", "(", "self", ",", "cli", ",", "mouse_event", ")", ":", "if", "self", ".", "_tokens", ":", "# Read the generator.", "tokens_for_line", "=", "list", "(", "split_lines", "(", "self", ".", "_tokens", ")", ")", "try", ":", "tokens", "=",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/controls.py#L324-L360
linyouhappy/kongkongxiyou
7a69b2913eb29f4be77f9a62fb90cdd72c4160f1
cocosjs/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py
python
TranslationUnit.save
(self, filename)
Saves the TranslationUnit to a file. This is equivalent to passing -emit-ast to the clang frontend. The saved file can be loaded back into a TranslationUnit. Or, if it corresponds to a header, it can be used as a pre-compiled header file. If an error occurs while saving, a TranslationUnitSaveError is raised. If the error was TranslationUnitSaveError.ERROR_INVALID_TU, this means the constructed TranslationUnit was not valid at time of save. In this case, the reason(s) why should be available via TranslationUnit.diagnostics(). filename -- The path to save the translation unit to.
Saves the TranslationUnit to a file.
[ "Saves", "the", "TranslationUnit", "to", "a", "file", "." ]
def save(self, filename): """Saves the TranslationUnit to a file. This is equivalent to passing -emit-ast to the clang frontend. The saved file can be loaded back into a TranslationUnit. Or, if it corresponds to a header, it can be used as a pre-compiled header file. If an error occurs while saving, a TranslationUnitSaveError is raised. If the error was TranslationUnitSaveError.ERROR_INVALID_TU, this means the constructed TranslationUnit was not valid at time of save. In this case, the reason(s) why should be available via TranslationUnit.diagnostics(). filename -- The path to save the translation unit to. """ options = conf.lib.clang_defaultSaveOptions(self) result = int(conf.lib.clang_saveTranslationUnit(self, filename, options)) if result != 0: raise TranslationUnitSaveError(result, 'Error saving TranslationUnit.')
[ "def", "save", "(", "self", ",", "filename", ")", ":", "options", "=", "conf", ".", "lib", ".", "clang_defaultSaveOptions", "(", "self", ")", "result", "=", "int", "(", "conf", ".", "lib", ".", "clang_saveTranslationUnit", "(", "self", ",", "filename", "...
https://github.com/linyouhappy/kongkongxiyou/blob/7a69b2913eb29f4be77f9a62fb90cdd72c4160f1/cocosjs/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py#L2404-L2424
sonyxperiadev/WebGL
0299b38196f78c6d5f74bcf6fa312a3daee6de60
Tools/Scripts/webkitpy/style/checkers/cpp.py
python
check_check
(clean_lines, line_number, error)
Checks the use of CHECK and EXPECT macros. Args: clean_lines: A CleansedLines instance containing the file. line_number: The number of the line to check. error: The function to call with any errors found.
Checks the use of CHECK and EXPECT macros.
[ "Checks", "the", "use", "of", "CHECK", "and", "EXPECT", "macros", "." ]
def check_check(clean_lines, line_number, error): """Checks the use of CHECK and EXPECT macros. Args: clean_lines: A CleansedLines instance containing the file. line_number: The number of the line to check. error: The function to call with any errors found. """ # Decide the set of replacement macros that should be suggested raw_lines = clean_lines.raw_lines current_macro = '' for macro in _CHECK_MACROS: if raw_lines[line_number].find(macro) >= 0: current_macro = macro break if not current_macro: # Don't waste time here if line doesn't contain 'CHECK' or 'EXPECT' return line = clean_lines.elided[line_number] # get rid of comments and strings # Encourage replacing plain CHECKs with CHECK_EQ/CHECK_NE/etc. for operator in ['==', '!=', '>=', '>', '<=', '<']: if replaceable_check(operator, current_macro, line): error(line_number, 'readability/check', 2, 'Consider using %s instead of %s(a %s b)' % ( _CHECK_REPLACEMENT[current_macro][operator], current_macro, operator)) break
[ "def", "check_check", "(", "clean_lines", ",", "line_number", ",", "error", ")", ":", "# Decide the set of replacement macros that should be suggested", "raw_lines", "=", "clean_lines", ".", "raw_lines", "current_macro", "=", "''", "for", "macro", "in", "_CHECK_MACROS", ...
https://github.com/sonyxperiadev/WebGL/blob/0299b38196f78c6d5f74bcf6fa312a3daee6de60/Tools/Scripts/webkitpy/style/checkers/cpp.py#L2300-L2329
openmm/openmm
cb293447c4fc8b03976dfe11399f107bab70f3d9
wrappers/python/openmm/app/pdbreporter.py
python
PDBxReporter.report
(self, simulation, state)
Generate a report. Parameters ---------- simulation : Simulation The Simulation to generate a report for state : State The current state of the simulation
Generate a report.
[ "Generate", "a", "report", "." ]
def report(self, simulation, state): """Generate a report. Parameters ---------- simulation : Simulation The Simulation to generate a report for state : State The current state of the simulation """ if self._nextModel == 0: PDBxFile.writeHeader(simulation.topology, self._out) self._nextModel += 1 PDBxFile.writeModel(simulation.topology, state.getPositions(), self._out, self._nextModel) self._nextModel += 1 if hasattr(self._out, 'flush') and callable(self._out.flush): self._out.flush()
[ "def", "report", "(", "self", ",", "simulation", ",", "state", ")", ":", "if", "self", ".", "_nextModel", "==", "0", ":", "PDBxFile", ".", "writeHeader", "(", "simulation", ".", "topology", ",", "self", ".", "_out", ")", "self", ".", "_nextModel", "+="...
https://github.com/openmm/openmm/blob/cb293447c4fc8b03976dfe11399f107bab70f3d9/wrappers/python/openmm/app/pdbreporter.py#L114-L130
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_windows.py
python
PyWindow.DoSetVirtualSize
(*args, **kwargs)
return _windows_.PyWindow_DoSetVirtualSize(*args, **kwargs)
DoSetVirtualSize(self, int x, int y)
DoSetVirtualSize(self, int x, int y)
[ "DoSetVirtualSize", "(", "self", "int", "x", "int", "y", ")" ]
def DoSetVirtualSize(*args, **kwargs): """DoSetVirtualSize(self, int x, int y)""" return _windows_.PyWindow_DoSetVirtualSize(*args, **kwargs)
[ "def", "DoSetVirtualSize", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "PyWindow_DoSetVirtualSize", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_windows.py#L4158-L4160
SpenceKonde/megaTinyCore
1c4a70b18a149fe6bcb551dfa6db11ca50b8997b
megaavr/tools/libs/pymcuprog/pymcuprog.py
python
_parse_literal
(literal)
Literals can either be integers or float values. Default is Integer
Literals can either be integers or float values. Default is Integer
[ "Literals", "can", "either", "be", "integers", "or", "float", "values", ".", "Default", "is", "Integer" ]
def _parse_literal(literal): """ Literals can either be integers or float values. Default is Integer """ try: return int(literal, 0) except ValueError: return float(literal)
[ "def", "_parse_literal", "(", "literal", ")", ":", "try", ":", "return", "int", "(", "literal", ",", "0", ")", "except", "ValueError", ":", "return", "float", "(", "literal", ")" ]
https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/pymcuprog/pymcuprog.py#L90-L97
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TNEANet.AttrValueEI
(self, *args)
return _snap.TNEANet_AttrValueEI(self, *args)
AttrValueEI(TNEANet self, TInt EId, TStrV Values) Parameters: EId: TInt const & Values: TStrV & AttrValueEI(TNEANet self, TInt EId, TStrIntPrH::TIter EdgeHI, TStrV Values) Parameters: EId: TInt const & EdgeHI: TStrIntPrH::TIter Values: TStrV &
AttrValueEI(TNEANet self, TInt EId, TStrV Values)
[ "AttrValueEI", "(", "TNEANet", "self", "TInt", "EId", "TStrV", "Values", ")" ]
def AttrValueEI(self, *args): """ AttrValueEI(TNEANet self, TInt EId, TStrV Values) Parameters: EId: TInt const & Values: TStrV & AttrValueEI(TNEANet self, TInt EId, TStrIntPrH::TIter EdgeHI, TStrV Values) Parameters: EId: TInt const & EdgeHI: TStrIntPrH::TIter Values: TStrV & """ return _snap.TNEANet_AttrValueEI(self, *args)
[ "def", "AttrValueEI", "(", "self", ",", "*", "args", ")", ":", "return", "_snap", ".", "TNEANet_AttrValueEI", "(", "self", ",", "*", "args", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L21599-L21615