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
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/share/gdb/python/gdb/FrameDecorator.py
python
SymValueWrapper.value
(self)
return self.val
Return the value associated with this symbol, or None
Return the value associated with this symbol, or None
[ "Return", "the", "value", "associated", "with", "this", "symbol", "or", "None" ]
def value(self): """ Return the value associated with this symbol, or None""" return self.val
[ "def", "value", "(", "self", ")", ":", "return", "self", ".", "val" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/share/gdb/python/gdb/FrameDecorator.py#L213-L215
FeatherCoin/Feathercoin
8dad11707024149029bb9bfdd7bc5e10385e0e77
contrib/devtools/security-check.py
python
check_PE_NX
(executable)
return (bits & IMAGE_DLL_CHARACTERISTICS_NX_COMPAT) == IMAGE_DLL_CHARACTERISTICS_NX_COMPAT
NX: DllCharacteristics bit 0x100 signifies nxcompat (DEP)
NX: DllCharacteristics bit 0x100 signifies nxcompat (DEP)
[ "NX", ":", "DllCharacteristics", "bit", "0x100", "signifies", "nxcompat", "(", "DEP", ")" ]
def check_PE_NX(executable): '''NX: DllCharacteristics bit 0x100 signifies nxcompat (DEP)''' (arch,bits) = get_PE_dll_characteristics(executable) return (bits & IMAGE_DLL_CHARACTERISTICS_NX_COMPAT) == IMAGE_DLL_CHARACTERISTICS_NX_COMPAT
[ "def", "check_PE_NX", "(", "executable", ")", ":", "(", "arch", ",", "bits", ")", "=", "get_PE_dll_characteristics", "(", "executable", ")", "return", "(", "bits", "&", "IMAGE_DLL_CHARACTERISTICS_NX_COMPAT", ")", "==", "IMAGE_DLL_CHARACTERISTICS_NX_COMPAT" ]
https://github.com/FeatherCoin/Feathercoin/blob/8dad11707024149029bb9bfdd7bc5e10385e0e77/contrib/devtools/security-check.py#L160-L163
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/predictor/contrib_estimator_predictor.py
python
ContribEstimatorPredictor.__init__
(self, estimator, prediction_input_fn, input_alternative_key=None, output_alternative_key=None, graph=None)
Initialize a `ContribEstimatorPredictor`. Args: estimator: an instance of `tf.contrib.learn.Estimator`. prediction_input_fn: a function that takes no arguments and returns an instance of `InputFnOps`. input_alternative_key: Optional. Specify the input alternative used for prediction. output_alternative_key: Specify the output alternative used for prediction. Not needed for single-headed models but required for multi-headed models. graph: Optional. The Tensorflow `graph` in which prediction should be done.
Initialize a `ContribEstimatorPredictor`.
[ "Initialize", "a", "ContribEstimatorPredictor", "." ]
def __init__(self, estimator, prediction_input_fn, input_alternative_key=None, output_alternative_key=None, graph=None): """Initialize a `ContribEstimatorPredictor`. Args: estimator: an instance of `tf.contrib.learn.Estimator`. prediction_input_fn: a function that takes no arguments and returns an instance of `InputFnOps`. input_alternative_key: Optional. Specify the input alternative used for prediction. output_alternative_key: Specify the output alternative used for prediction. Not needed for single-headed models but required for multi-headed models. graph: Optional. The Tensorflow `graph` in which prediction should be done. """ self._graph = graph or ops.Graph() with self._graph.as_default(): input_fn_ops = prediction_input_fn() # pylint: disable=protected-access model_fn_ops = estimator._get_predict_ops(input_fn_ops.features) # pylint: enable=protected-access checkpoint_path = saver.latest_checkpoint(estimator.model_dir) self._session = monitored_session.MonitoredSession( session_creator=monitored_session.ChiefSessionCreator( checkpoint_filename_with_path=checkpoint_path)) input_alternative_key = ( input_alternative_key or saved_model_export_utils.DEFAULT_INPUT_ALTERNATIVE_KEY) input_alternatives, _ = saved_model_export_utils.get_input_alternatives( input_fn_ops) self._feed_tensors = input_alternatives[input_alternative_key] (output_alternatives, output_alternative_key) = saved_model_export_utils.get_output_alternatives( model_fn_ops, output_alternative_key) _, fetch_tensors = output_alternatives[output_alternative_key] self._fetch_tensors = fetch_tensors
[ "def", "__init__", "(", "self", ",", "estimator", ",", "prediction_input_fn", ",", "input_alternative_key", "=", "None", ",", "output_alternative_key", "=", "None", ",", "graph", "=", "None", ")", ":", "self", ".", "_graph", "=", "graph", "or", "ops", ".", "Graph", "(", ")", "with", "self", ".", "_graph", ".", "as_default", "(", ")", ":", "input_fn_ops", "=", "prediction_input_fn", "(", ")", "# pylint: disable=protected-access", "model_fn_ops", "=", "estimator", ".", "_get_predict_ops", "(", "input_fn_ops", ".", "features", ")", "# pylint: enable=protected-access", "checkpoint_path", "=", "saver", ".", "latest_checkpoint", "(", "estimator", ".", "model_dir", ")", "self", ".", "_session", "=", "monitored_session", ".", "MonitoredSession", "(", "session_creator", "=", "monitored_session", ".", "ChiefSessionCreator", "(", "checkpoint_filename_with_path", "=", "checkpoint_path", ")", ")", "input_alternative_key", "=", "(", "input_alternative_key", "or", "saved_model_export_utils", ".", "DEFAULT_INPUT_ALTERNATIVE_KEY", ")", "input_alternatives", ",", "_", "=", "saved_model_export_utils", ".", "get_input_alternatives", "(", "input_fn_ops", ")", "self", ".", "_feed_tensors", "=", "input_alternatives", "[", "input_alternative_key", "]", "(", "output_alternatives", ",", "output_alternative_key", ")", "=", "saved_model_export_utils", ".", "get_output_alternatives", "(", "model_fn_ops", ",", "output_alternative_key", ")", "_", ",", "fetch_tensors", "=", "output_alternatives", "[", "output_alternative_key", "]", "self", ".", "_fetch_tensors", "=", "fetch_tensors" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/predictor/contrib_estimator_predictor.py#L32-L74
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/mailbox.py
python
_ProxyFile.seek
(self, offset, whence=0)
Change position.
Change position.
[ "Change", "position", "." ]
def seek(self, offset, whence=0): """Change position.""" if whence == 1: self._file.seek(self._pos) self._file.seek(offset, whence) self._pos = self._file.tell()
[ "def", "seek", "(", "self", ",", "offset", ",", "whence", "=", "0", ")", ":", "if", "whence", "==", "1", ":", "self", ".", "_file", ".", "seek", "(", "self", ".", "_pos", ")", "self", ".", "_file", ".", "seek", "(", "offset", ",", "whence", ")", "self", ".", "_pos", "=", "self", ".", "_file", ".", "tell", "(", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/mailbox.py#L1898-L1903
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/wsgiref/handlers.py
python
BaseHandler.add_cgi_vars
(self)
Override in subclass to insert CGI variables in 'self.environ
Override in subclass to insert CGI variables in 'self.environ
[ "Override", "in", "subclass", "to", "insert", "CGI", "variables", "in", "self", ".", "environ" ]
def add_cgi_vars(self): """Override in subclass to insert CGI variables in 'self.environ'""" raise NotImplementedError
[ "def", "add_cgi_vars", "(", "self", ")", ":", "raise", "NotImplementedError" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/wsgiref/handlers.py#L353-L355
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/compiler/pyassem.py
python
Block.getContainedGraphs
(self)
return contained
Return all graphs contained within this block. For example, a MAKE_FUNCTION block will contain a reference to the graph for the function body.
Return all graphs contained within this block.
[ "Return", "all", "graphs", "contained", "within", "this", "block", "." ]
def getContainedGraphs(self): """Return all graphs contained within this block. For example, a MAKE_FUNCTION block will contain a reference to the graph for the function body. """ contained = [] for inst in self.insts: if len(inst) == 1: continue op = inst[1] if hasattr(op, 'graph'): contained.append(op.graph) return contained
[ "def", "getContainedGraphs", "(", "self", ")", ":", "contained", "=", "[", "]", "for", "inst", "in", "self", ".", "insts", ":", "if", "len", "(", "inst", ")", "==", "1", ":", "continue", "op", "=", "inst", "[", "1", "]", "if", "hasattr", "(", "op", ",", "'graph'", ")", ":", "contained", ".", "append", "(", "op", ".", "graph", ")", "return", "contained" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/compiler/pyassem.py#L231-L244
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_controls.py
python
TreeItemId.IsOk
(*args, **kwargs)
return _controls_.TreeItemId_IsOk(*args, **kwargs)
IsOk(self) -> bool
IsOk(self) -> bool
[ "IsOk", "(", "self", ")", "-", ">", "bool" ]
def IsOk(*args, **kwargs): """IsOk(self) -> bool""" return _controls_.TreeItemId_IsOk(*args, **kwargs)
[ "def", "IsOk", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "TreeItemId_IsOk", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L5001-L5003
chipsalliance/verible
aa14e0074ff89945bf65eecfb9ef78684d996058
verilog/tools/syntax/export_json_examples/verible_verilog_syntax.py
python
BranchNode.find_all
(self, filter_: Union[CallableFilter, KeyValueFilter, None], max_count: int = 0, iter_: TreeIterator = LevelOrderTreeIterator, **kwargs)
return list(self.iter_find_all(filter_, max_count=max_count, iter_=iter_, **kwargs))
Find all nodes matching specified filter. Args: filter_: Describes what to search for. Might be: * Callable taking Node as an argument and returning True for accepted nodes. * Dict mapping Node attribute names to searched value or list of searched values. max_count: Stop searching after finding that many matching nodes. iter_: Tree iterator. Decides in what order nodes are visited. Returns: List of nodes matching specified filter.
Find all nodes matching specified filter.
[ "Find", "all", "nodes", "matching", "specified", "filter", "." ]
def find_all(self, filter_: Union[CallableFilter, KeyValueFilter, None], max_count: int = 0, iter_: TreeIterator = LevelOrderTreeIterator, **kwargs) -> List[Node]: """Find all nodes matching specified filter. Args: filter_: Describes what to search for. Might be: * Callable taking Node as an argument and returning True for accepted nodes. * Dict mapping Node attribute names to searched value or list of searched values. max_count: Stop searching after finding that many matching nodes. iter_: Tree iterator. Decides in what order nodes are visited. Returns: List of nodes matching specified filter. """ return list(self.iter_find_all(filter_, max_count=max_count, iter_=iter_, **kwargs))
[ "def", "find_all", "(", "self", ",", "filter_", ":", "Union", "[", "CallableFilter", ",", "KeyValueFilter", ",", "None", "]", ",", "max_count", ":", "int", "=", "0", ",", "iter_", ":", "TreeIterator", "=", "LevelOrderTreeIterator", ",", "*", "*", "kwargs", ")", "->", "List", "[", "Node", "]", ":", "return", "list", "(", "self", ".", "iter_find_all", "(", "filter_", ",", "max_count", "=", "max_count", ",", "iter_", "=", "iter_", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/chipsalliance/verible/blob/aa14e0074ff89945bf65eecfb9ef78684d996058/verilog/tools/syntax/export_json_examples/verible_verilog_syntax.py#L218-L236
arangodb/arangodb
0d658689c7d1b721b314fa3ca27d38303e1570c8
3rdParty/V8/v7.9.317/third_party/jinja2/runtime.py
python
LoopContextBase.changed
(self, *value)
return False
Checks whether the value has changed since the last call.
Checks whether the value has changed since the last call.
[ "Checks", "whether", "the", "value", "has", "changed", "since", "the", "last", "call", "." ]
def changed(self, *value): """Checks whether the value has changed since the last call.""" if self._last_checked_value != value: self._last_checked_value = value return True return False
[ "def", "changed", "(", "self", ",", "*", "value", ")", ":", "if", "self", ".", "_last_checked_value", "!=", "value", ":", "self", ".", "_last_checked_value", "=", "value", "return", "True", "return", "False" ]
https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/v7.9.317/third_party/jinja2/runtime.py#L372-L377
arangodb/arangodb
0d658689c7d1b721b314fa3ca27d38303e1570c8
3rdParty/V8/gyp/msvs_emulation.py
python
MsvsSettings.GetDefFile
(self, gyp_to_build_path)
return None
Returns the .def file from sources, if any. Otherwise returns None.
Returns the .def file from sources, if any. Otherwise returns None.
[ "Returns", "the", ".", "def", "file", "from", "sources", "if", "any", ".", "Otherwise", "returns", "None", "." ]
def GetDefFile(self, gyp_to_build_path): """Returns the .def file from sources, if any. Otherwise returns None.""" spec = self.spec if spec['type'] in ('shared_library', 'loadable_module', 'executable'): def_files = [s for s in spec.get('sources', []) if s.lower().endswith('.def')] if len(def_files) == 1: return gyp_to_build_path(def_files[0]) elif len(def_files) > 1: raise Exception("Multiple .def files") return None
[ "def", "GetDefFile", "(", "self", ",", "gyp_to_build_path", ")", ":", "spec", "=", "self", ".", "spec", "if", "spec", "[", "'type'", "]", "in", "(", "'shared_library'", ",", "'loadable_module'", ",", "'executable'", ")", ":", "def_files", "=", "[", "s", "for", "s", "in", "spec", ".", "get", "(", "'sources'", ",", "[", "]", ")", "if", "s", ".", "lower", "(", ")", ".", "endswith", "(", "'.def'", ")", "]", "if", "len", "(", "def_files", ")", "==", "1", ":", "return", "gyp_to_build_path", "(", "def_files", "[", "0", "]", ")", "elif", "len", "(", "def_files", ")", ">", "1", ":", "raise", "Exception", "(", "\"Multiple .def files\"", ")", "return", "None" ]
https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/gyp/msvs_emulation.py#L493-L502
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/llvmlite/ir/builder.py
python
IRBuilder.bswap
(self, cond)
Used to byte swap integer values with an even number of bytes (positive multiple of 16 bits)
Used to byte swap integer values with an even number of bytes (positive multiple of 16 bits)
[ "Used", "to", "byte", "swap", "integer", "values", "with", "an", "even", "number", "of", "bytes", "(", "positive", "multiple", "of", "16", "bits", ")" ]
def bswap(self, cond): """ Used to byte swap integer values with an even number of bytes (positive multiple of 16 bits) """
[ "def", "bswap", "(", "self", ",", "cond", ")", ":" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/llvmlite/ir/builder.py#L1001-L1004
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/propgrid.py
python
PropertyGridInterface.Properties
(self)
This attribute is a pythonic iterator over all properties in this `PropertyGrid` property container. It will only skip categories and private child properties. Usage is simple:: for prop in propGrid.Properties: print(prop) :see: `wx.propgrid.PropertyGridInterface.Items` `wx.propgrid.PropertyGridInterface.GetPyIterator`
This attribute is a pythonic iterator over all properties in this `PropertyGrid` property container. It will only skip categories and private child properties. Usage is simple::
[ "This", "attribute", "is", "a", "pythonic", "iterator", "over", "all", "properties", "in", "this", "PropertyGrid", "property", "container", ".", "It", "will", "only", "skip", "categories", "and", "private", "child", "properties", ".", "Usage", "is", "simple", "::" ]
def Properties(self): """ This attribute is a pythonic iterator over all properties in this `PropertyGrid` property container. It will only skip categories and private child properties. Usage is simple:: for prop in propGrid.Properties: print(prop) :see: `wx.propgrid.PropertyGridInterface.Items` `wx.propgrid.PropertyGridInterface.GetPyIterator` """ it = self.GetVIterator(PG_ITERATE_NORMAL) while not it.AtEnd(): yield it.GetProperty() it.Next()
[ "def", "Properties", "(", "self", ")", ":", "it", "=", "self", ".", "GetVIterator", "(", "PG_ITERATE_NORMAL", ")", "while", "not", "it", ".", "AtEnd", "(", ")", ":", "yield", "it", ".", "GetProperty", "(", ")", "it", ".", "Next", "(", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L1765-L1780
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Arch/ArchCommands.py
python
survey
(callback=False)
survey(): starts survey mode, where you can click edges and faces to get their lengths or area. Clicking on no object (on an empty area) resets the count.
survey(): starts survey mode, where you can click edges and faces to get their lengths or area. Clicking on no object (on an empty area) resets the count.
[ "survey", "()", ":", "starts", "survey", "mode", "where", "you", "can", "click", "edges", "and", "faces", "to", "get", "their", "lengths", "or", "area", ".", "Clicking", "on", "no", "object", "(", "on", "an", "empty", "area", ")", "resets", "the", "count", "." ]
def survey(callback=False): """survey(): starts survey mode, where you can click edges and faces to get their lengths or area. Clicking on no object (on an empty area) resets the count.""" if not callback: if hasattr(FreeCAD,"SurveyObserver"): for label in FreeCAD.SurveyObserver.labels: FreeCAD.ActiveDocument.removeObject(label) FreeCADGui.Selection.removeObserver(FreeCAD.SurveyObserver) del FreeCAD.SurveyObserver FreeCADGui.Control.closeDialog() if hasattr(FreeCAD,"SurveyDialog"): del FreeCAD.SurveyDialog else: FreeCAD.SurveyObserver = _SurveyObserver(callback=survey) FreeCADGui.Selection.addObserver(FreeCAD.SurveyObserver) FreeCAD.SurveyDialog = SurveyTaskPanel() FreeCADGui.Control.showDialog(FreeCAD.SurveyDialog) else: sel = FreeCADGui.Selection.getSelectionEx() if hasattr(FreeCAD,"SurveyObserver"): if not sel: if FreeCAD.SurveyObserver.labels: for label in FreeCAD.SurveyObserver.labels: FreeCAD.ActiveDocument.removeObject(label) tl = FreeCAD.SurveyObserver.totalLength ta = FreeCAD.SurveyObserver.totalArea FreeCAD.SurveyObserver.labels = [] FreeCAD.SurveyObserver.selection = [] FreeCAD.SurveyObserver.totalLength = 0 FreeCAD.SurveyObserver.totalArea = 0 FreeCAD.SurveyObserver.totalVolume = 0 if not FreeCAD.SurveyObserver.cancellable: FreeCAD.Console.PrintMessage("\n---- Reset ----\n\n") FreeCAD.SurveyObserver.cancellable = True if hasattr(FreeCAD,"SurveyDialog"): FreeCAD.SurveyDialog.newline(tl,ta) else: FreeCADGui.Selection.removeObserver(FreeCAD.SurveyObserver) del FreeCAD.SurveyObserver FreeCADGui.Control.closeDialog() if hasattr(FreeCAD,"SurveyDialog"): del FreeCAD.SurveyDialog else: FreeCAD.SurveyObserver.cancellable = False basesel = FreeCAD.SurveyObserver.selection newsels = [] for o in sel: found = False for eo in basesel: if o.ObjectName == eo.ObjectName: if o.SubElementNames == eo.SubElementNames: found = True if not found: newsels.append(o) if newsels: for o in newsels: if hasattr(o.Object, 'Shape'): n = o.Object.Label showUnit = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch").GetBool("surveyUnits",True) t = "" u = FreeCAD.Units.Quantity() if not o.HasSubObjects: # entire object anno = FreeCAD.ActiveDocument.addObject("App::AnnotationLabel","surveyLabel") if hasattr(o.Object.Shape,"CenterOfMass"): anno.BasePosition = o.Object.Shape.CenterOfMass else: anno.BasePosition = o.Object.Shape.BoundBox.Center FreeCAD.SurveyObserver.labels.append(anno.Name) if o.Object.Shape.Solids: u = FreeCAD.Units.Quantity(o.Object.Shape.Volume,FreeCAD.Units.Volume) t = u.getUserPreferred()[0] t = string_replace(t, "^3","³") anno.LabelText = "v " + t FreeCAD.Console.PrintMessage("Object: " + n + ", Element: Whole, Volume: " + utf8_decode(t) + "\n") FreeCAD.SurveyObserver.totalVolume += u.Value elif o.Object.Shape.Faces: u = FreeCAD.Units.Quantity(o.Object.Shape.Area,FreeCAD.Units.Area) t = u.getUserPreferred()[0] t = string_replace(t, "^2","²") anno.LabelText = "a " + t FreeCAD.Console.PrintMessage("Object: " + n + ", Element: Whole, Area: " + utf8_decode(t) + "\n") FreeCAD.SurveyObserver.totalArea += u.Value if hasattr(FreeCAD,"SurveyDialog"): FreeCAD.SurveyDialog.update(2,t) else: u = FreeCAD.Units.Quantity(o.Object.Shape.Length,FreeCAD.Units.Length) t = u.getUserPreferred()[0] t = t.encode("utf8") anno.LabelText = "l " + t FreeCAD.Console.PrintMessage("Object: " + n + ", Element: Whole, Length: " + utf8_decode(t) + "\n") FreeCAD.SurveyObserver.totalLength += u.Value if hasattr(FreeCAD,"SurveyDialog"): FreeCAD.SurveyDialog.update(1,t) if FreeCAD.GuiUp and t: if showUnit: QtGui.QApplication.clipboard().setText(t) else: QtGui.QApplication.clipboard().setText(str(u.Value)) else: # single element(s) for el in o.SubElementNames: e = getattr(o.Object.Shape,el) anno = FreeCAD.ActiveDocument.addObject("App::AnnotationLabel","surveyLabel") if "Vertex" in el: anno.BasePosition = e.Point else: if hasattr(e,"CenterOfMass"): anno.BasePosition = e.CenterOfMass else: anno.BasePosition = e.BoundBox.Center FreeCAD.SurveyObserver.labels.append(anno.Name) if "Face" in el: u = FreeCAD.Units.Quantity(e.Area,FreeCAD.Units.Area) t = u.getUserPreferred()[0] t = string_replace(t, "^2","²") anno.LabelText = "a " + t FreeCAD.Console.PrintMessage("Object: " + n + ", Element: " + el + ", Area: "+ utf8_decode(t) + "\n") FreeCAD.SurveyObserver.totalArea += u.Value if hasattr(FreeCAD,"SurveyDialog"): FreeCAD.SurveyDialog.update(2,t) elif "Edge" in el: u= FreeCAD.Units.Quantity(e.Length,FreeCAD.Units.Length) t = u.getUserPreferred()[0] if sys.version_info.major < 3: t = t.encode("utf8") anno.LabelText = "l " + t FreeCAD.Console.PrintMessage("Object: " + n + ", Element: " + el + ", Length: " + utf8_decode(t) + "\n") FreeCAD.SurveyObserver.totalLength += u.Value if hasattr(FreeCAD,"SurveyDialog"): FreeCAD.SurveyDialog.update(1,t) elif "Vertex" in el: u = FreeCAD.Units.Quantity(e.Z,FreeCAD.Units.Length) t = u.getUserPreferred()[0] t = t.encode("utf8") anno.LabelText = "z " + t FreeCAD.Console.PrintMessage("Object: " + n + ", Element: " + el + ", Zcoord: " + utf8_decode(t) + "\n") if FreeCAD.GuiUp and t: if showUnit: QtGui.QApplication.clipboard().setText(t) else: QtGui.QApplication.clipboard().setText(str(u.Value)) FreeCAD.SurveyObserver.selection.extend(newsels) if hasattr(FreeCAD,"SurveyObserver"): if FreeCAD.SurveyObserver.totalLength or FreeCAD.SurveyObserver.totalArea or FreeCAD.SurveyObserver.totalVolume: msg = " Total:" if FreeCAD.SurveyObserver.totalLength: u = FreeCAD.Units.Quantity(FreeCAD.SurveyObserver.totalLength,FreeCAD.Units.Length) t = u.getUserPreferred()[0] if sys.version_info.major < 3: t = t.encode("utf8") msg += " Length: " + t if FreeCAD.SurveyObserver.totalArea: u = FreeCAD.Units.Quantity(FreeCAD.SurveyObserver.totalArea,FreeCAD.Units.Area) t = u.getUserPreferred()[0] t = string_replace(t, "^2","²") msg += " Area: " + t if FreeCAD.SurveyObserver.totalVolume: u = FreeCAD.Units.Quantity(FreeCAD.SurveyObserver.totalVolume,FreeCAD.Units.Volume) t = u.getUserPreferred()[0] t = string_replace(t, "^3","³") msg += " Volume: " + t FreeCAD.Console.PrintMessage(msg+"\n")
[ "def", "survey", "(", "callback", "=", "False", ")", ":", "if", "not", "callback", ":", "if", "hasattr", "(", "FreeCAD", ",", "\"SurveyObserver\"", ")", ":", "for", "label", "in", "FreeCAD", ".", "SurveyObserver", ".", "labels", ":", "FreeCAD", ".", "ActiveDocument", ".", "removeObject", "(", "label", ")", "FreeCADGui", ".", "Selection", ".", "removeObserver", "(", "FreeCAD", ".", "SurveyObserver", ")", "del", "FreeCAD", ".", "SurveyObserver", "FreeCADGui", ".", "Control", ".", "closeDialog", "(", ")", "if", "hasattr", "(", "FreeCAD", ",", "\"SurveyDialog\"", ")", ":", "del", "FreeCAD", ".", "SurveyDialog", "else", ":", "FreeCAD", ".", "SurveyObserver", "=", "_SurveyObserver", "(", "callback", "=", "survey", ")", "FreeCADGui", ".", "Selection", ".", "addObserver", "(", "FreeCAD", ".", "SurveyObserver", ")", "FreeCAD", ".", "SurveyDialog", "=", "SurveyTaskPanel", "(", ")", "FreeCADGui", ".", "Control", ".", "showDialog", "(", "FreeCAD", ".", "SurveyDialog", ")", "else", ":", "sel", "=", "FreeCADGui", ".", "Selection", ".", "getSelectionEx", "(", ")", "if", "hasattr", "(", "FreeCAD", ",", "\"SurveyObserver\"", ")", ":", "if", "not", "sel", ":", "if", "FreeCAD", ".", "SurveyObserver", ".", "labels", ":", "for", "label", "in", "FreeCAD", ".", "SurveyObserver", ".", "labels", ":", "FreeCAD", ".", "ActiveDocument", ".", "removeObject", "(", "label", ")", "tl", "=", "FreeCAD", ".", "SurveyObserver", ".", "totalLength", "ta", "=", "FreeCAD", ".", "SurveyObserver", ".", "totalArea", "FreeCAD", ".", "SurveyObserver", ".", "labels", "=", "[", "]", "FreeCAD", ".", "SurveyObserver", ".", "selection", "=", "[", "]", "FreeCAD", ".", "SurveyObserver", ".", "totalLength", "=", "0", "FreeCAD", ".", "SurveyObserver", ".", "totalArea", "=", "0", "FreeCAD", ".", "SurveyObserver", ".", "totalVolume", "=", "0", "if", "not", "FreeCAD", ".", "SurveyObserver", ".", "cancellable", ":", "FreeCAD", ".", "Console", ".", "PrintMessage", "(", "\"\\n---- Reset ----\\n\\n\"", ")", "FreeCAD", ".", "SurveyObserver", ".", "cancellable", "=", "True", "if", "hasattr", "(", "FreeCAD", ",", "\"SurveyDialog\"", ")", ":", "FreeCAD", ".", "SurveyDialog", ".", "newline", "(", "tl", ",", "ta", ")", "else", ":", "FreeCADGui", ".", "Selection", ".", "removeObserver", "(", "FreeCAD", ".", "SurveyObserver", ")", "del", "FreeCAD", ".", "SurveyObserver", "FreeCADGui", ".", "Control", ".", "closeDialog", "(", ")", "if", "hasattr", "(", "FreeCAD", ",", "\"SurveyDialog\"", ")", ":", "del", "FreeCAD", ".", "SurveyDialog", "else", ":", "FreeCAD", ".", "SurveyObserver", ".", "cancellable", "=", "False", "basesel", "=", "FreeCAD", ".", "SurveyObserver", ".", "selection", "newsels", "=", "[", "]", "for", "o", "in", "sel", ":", "found", "=", "False", "for", "eo", "in", "basesel", ":", "if", "o", ".", "ObjectName", "==", "eo", ".", "ObjectName", ":", "if", "o", ".", "SubElementNames", "==", "eo", ".", "SubElementNames", ":", "found", "=", "True", "if", "not", "found", ":", "newsels", ".", "append", "(", "o", ")", "if", "newsels", ":", "for", "o", "in", "newsels", ":", "if", "hasattr", "(", "o", ".", "Object", ",", "'Shape'", ")", ":", "n", "=", "o", ".", "Object", ".", "Label", "showUnit", "=", "FreeCAD", ".", "ParamGet", "(", "\"User parameter:BaseApp/Preferences/Mod/Arch\"", ")", ".", "GetBool", "(", "\"surveyUnits\"", ",", "True", ")", "t", "=", "\"\"", "u", "=", "FreeCAD", ".", "Units", ".", "Quantity", "(", ")", "if", "not", "o", ".", "HasSubObjects", ":", "# entire object", "anno", "=", "FreeCAD", ".", "ActiveDocument", ".", "addObject", "(", "\"App::AnnotationLabel\"", ",", "\"surveyLabel\"", ")", "if", "hasattr", "(", "o", ".", "Object", ".", "Shape", ",", "\"CenterOfMass\"", ")", ":", "anno", ".", "BasePosition", "=", "o", ".", "Object", ".", "Shape", ".", "CenterOfMass", "else", ":", "anno", ".", "BasePosition", "=", "o", ".", "Object", ".", "Shape", ".", "BoundBox", ".", "Center", "FreeCAD", ".", "SurveyObserver", ".", "labels", ".", "append", "(", "anno", ".", "Name", ")", "if", "o", ".", "Object", ".", "Shape", ".", "Solids", ":", "u", "=", "FreeCAD", ".", "Units", ".", "Quantity", "(", "o", ".", "Object", ".", "Shape", ".", "Volume", ",", "FreeCAD", ".", "Units", ".", "Volume", ")", "t", "=", "u", ".", "getUserPreferred", "(", ")", "[", "0", "]", "t", "=", "string_replace", "(", "t", ",", "\"^3\"", ",", "\"³\")", "", "anno", ".", "LabelText", "=", "\"v \"", "+", "t", "FreeCAD", ".", "Console", ".", "PrintMessage", "(", "\"Object: \"", "+", "n", "+", "\", Element: Whole, Volume: \"", "+", "utf8_decode", "(", "t", ")", "+", "\"\\n\"", ")", "FreeCAD", ".", "SurveyObserver", ".", "totalVolume", "+=", "u", ".", "Value", "elif", "o", ".", "Object", ".", "Shape", ".", "Faces", ":", "u", "=", "FreeCAD", ".", "Units", ".", "Quantity", "(", "o", ".", "Object", ".", "Shape", ".", "Area", ",", "FreeCAD", ".", "Units", ".", "Area", ")", "t", "=", "u", ".", "getUserPreferred", "(", ")", "[", "0", "]", "t", "=", "string_replace", "(", "t", ",", "\"^2\"", ",", "\"²\")", "", "anno", ".", "LabelText", "=", "\"a \"", "+", "t", "FreeCAD", ".", "Console", ".", "PrintMessage", "(", "\"Object: \"", "+", "n", "+", "\", Element: Whole, Area: \"", "+", "utf8_decode", "(", "t", ")", "+", "\"\\n\"", ")", "FreeCAD", ".", "SurveyObserver", ".", "totalArea", "+=", "u", ".", "Value", "if", "hasattr", "(", "FreeCAD", ",", "\"SurveyDialog\"", ")", ":", "FreeCAD", ".", "SurveyDialog", ".", "update", "(", "2", ",", "t", ")", "else", ":", "u", "=", "FreeCAD", ".", "Units", ".", "Quantity", "(", "o", ".", "Object", ".", "Shape", ".", "Length", ",", "FreeCAD", ".", "Units", ".", "Length", ")", "t", "=", "u", ".", "getUserPreferred", "(", ")", "[", "0", "]", "t", "=", "t", ".", "encode", "(", "\"utf8\"", ")", "anno", ".", "LabelText", "=", "\"l \"", "+", "t", "FreeCAD", ".", "Console", ".", "PrintMessage", "(", "\"Object: \"", "+", "n", "+", "\", Element: Whole, Length: \"", "+", "utf8_decode", "(", "t", ")", "+", "\"\\n\"", ")", "FreeCAD", ".", "SurveyObserver", ".", "totalLength", "+=", "u", ".", "Value", "if", "hasattr", "(", "FreeCAD", ",", "\"SurveyDialog\"", ")", ":", "FreeCAD", ".", "SurveyDialog", ".", "update", "(", "1", ",", "t", ")", "if", "FreeCAD", ".", "GuiUp", "and", "t", ":", "if", "showUnit", ":", "QtGui", ".", "QApplication", ".", "clipboard", "(", ")", ".", "setText", "(", "t", ")", "else", ":", "QtGui", ".", "QApplication", ".", "clipboard", "(", ")", ".", "setText", "(", "str", "(", "u", ".", "Value", ")", ")", "else", ":", "# single element(s)", "for", "el", "in", "o", ".", "SubElementNames", ":", "e", "=", "getattr", "(", "o", ".", "Object", ".", "Shape", ",", "el", ")", "anno", "=", "FreeCAD", ".", "ActiveDocument", ".", "addObject", "(", "\"App::AnnotationLabel\"", ",", "\"surveyLabel\"", ")", "if", "\"Vertex\"", "in", "el", ":", "anno", ".", "BasePosition", "=", "e", ".", "Point", "else", ":", "if", "hasattr", "(", "e", ",", "\"CenterOfMass\"", ")", ":", "anno", ".", "BasePosition", "=", "e", ".", "CenterOfMass", "else", ":", "anno", ".", "BasePosition", "=", "e", ".", "BoundBox", ".", "Center", "FreeCAD", ".", "SurveyObserver", ".", "labels", ".", "append", "(", "anno", ".", "Name", ")", "if", "\"Face\"", "in", "el", ":", "u", "=", "FreeCAD", ".", "Units", ".", "Quantity", "(", "e", ".", "Area", ",", "FreeCAD", ".", "Units", ".", "Area", ")", "t", "=", "u", ".", "getUserPreferred", "(", ")", "[", "0", "]", "t", "=", "string_replace", "(", "t", ",", "\"^2\"", ",", "\"²\")", "", "anno", ".", "LabelText", "=", "\"a \"", "+", "t", "FreeCAD", ".", "Console", ".", "PrintMessage", "(", "\"Object: \"", "+", "n", "+", "\", Element: \"", "+", "el", "+", "\", Area: \"", "+", "utf8_decode", "(", "t", ")", "+", "\"\\n\"", ")", "FreeCAD", ".", "SurveyObserver", ".", "totalArea", "+=", "u", ".", "Value", "if", "hasattr", "(", "FreeCAD", ",", "\"SurveyDialog\"", ")", ":", "FreeCAD", ".", "SurveyDialog", ".", "update", "(", "2", ",", "t", ")", "elif", "\"Edge\"", "in", "el", ":", "u", "=", "FreeCAD", ".", "Units", ".", "Quantity", "(", "e", ".", "Length", ",", "FreeCAD", ".", "Units", ".", "Length", ")", "t", "=", "u", ".", "getUserPreferred", "(", ")", "[", "0", "]", "if", "sys", ".", "version_info", ".", "major", "<", "3", ":", "t", "=", "t", ".", "encode", "(", "\"utf8\"", ")", "anno", ".", "LabelText", "=", "\"l \"", "+", "t", "FreeCAD", ".", "Console", ".", "PrintMessage", "(", "\"Object: \"", "+", "n", "+", "\", Element: \"", "+", "el", "+", "\", Length: \"", "+", "utf8_decode", "(", "t", ")", "+", "\"\\n\"", ")", "FreeCAD", ".", "SurveyObserver", ".", "totalLength", "+=", "u", ".", "Value", "if", "hasattr", "(", "FreeCAD", ",", "\"SurveyDialog\"", ")", ":", "FreeCAD", ".", "SurveyDialog", ".", "update", "(", "1", ",", "t", ")", "elif", "\"Vertex\"", "in", "el", ":", "u", "=", "FreeCAD", ".", "Units", ".", "Quantity", "(", "e", ".", "Z", ",", "FreeCAD", ".", "Units", ".", "Length", ")", "t", "=", "u", ".", "getUserPreferred", "(", ")", "[", "0", "]", "t", "=", "t", ".", "encode", "(", "\"utf8\"", ")", "anno", ".", "LabelText", "=", "\"z \"", "+", "t", "FreeCAD", ".", "Console", ".", "PrintMessage", "(", "\"Object: \"", "+", "n", "+", "\", Element: \"", "+", "el", "+", "\", Zcoord: \"", "+", "utf8_decode", "(", "t", ")", "+", "\"\\n\"", ")", "if", "FreeCAD", ".", "GuiUp", "and", "t", ":", "if", "showUnit", ":", "QtGui", ".", "QApplication", ".", "clipboard", "(", ")", ".", "setText", "(", "t", ")", "else", ":", "QtGui", ".", "QApplication", ".", "clipboard", "(", ")", ".", "setText", "(", "str", "(", "u", ".", "Value", ")", ")", "FreeCAD", ".", "SurveyObserver", ".", "selection", ".", "extend", "(", "newsels", ")", "if", "hasattr", "(", "FreeCAD", ",", "\"SurveyObserver\"", ")", ":", "if", "FreeCAD", ".", "SurveyObserver", ".", "totalLength", "or", "FreeCAD", ".", "SurveyObserver", ".", "totalArea", "or", "FreeCAD", ".", "SurveyObserver", ".", "totalVolume", ":", "msg", "=", "\" Total:\"", "if", "FreeCAD", ".", "SurveyObserver", ".", "totalLength", ":", "u", "=", "FreeCAD", ".", "Units", ".", "Quantity", "(", "FreeCAD", ".", "SurveyObserver", ".", "totalLength", ",", "FreeCAD", ".", "Units", ".", "Length", ")", "t", "=", "u", ".", "getUserPreferred", "(", ")", "[", "0", "]", "if", "sys", ".", "version_info", ".", "major", "<", "3", ":", "t", "=", "t", ".", "encode", "(", "\"utf8\"", ")", "msg", "+=", "\" Length: \"", "+", "t", "if", "FreeCAD", ".", "SurveyObserver", ".", "totalArea", ":", "u", "=", "FreeCAD", ".", "Units", ".", "Quantity", "(", "FreeCAD", ".", "SurveyObserver", ".", "totalArea", ",", "FreeCAD", ".", "Units", ".", "Area", ")", "t", "=", "u", ".", "getUserPreferred", "(", ")", "[", "0", "]", "t", "=", "string_replace", "(", "t", ",", "\"^2\"", ",", "\"²\")", "", "msg", "+=", "\" Area: \"", "+", "t", "if", "FreeCAD", ".", "SurveyObserver", ".", "totalVolume", ":", "u", "=", "FreeCAD", ".", "Units", ".", "Quantity", "(", "FreeCAD", ".", "SurveyObserver", ".", "totalVolume", ",", "FreeCAD", ".", "Units", ".", "Volume", ")", "t", "=", "u", ".", "getUserPreferred", "(", ")", "[", "0", "]", "t", "=", "string_replace", "(", "t", ",", "\"^3\"", ",", "\"³\")", "", "msg", "+=", "\" Volume: \"", "+", "t", "FreeCAD", ".", "Console", ".", "PrintMessage", "(", "msg", "+", "\"\\n\"", ")" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Arch/ArchCommands.py#L792-L955
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/debug/lib/debug_data.py
python
DebugDumpDir.t0
(self)
return self._t0
Absolute timestamp of the first dumped tensor across all devices. Returns: (`int`) absolute timestamp of the first dumped tensor, in microseconds.
Absolute timestamp of the first dumped tensor across all devices.
[ "Absolute", "timestamp", "of", "the", "first", "dumped", "tensor", "across", "all", "devices", "." ]
def t0(self): """Absolute timestamp of the first dumped tensor across all devices. Returns: (`int`) absolute timestamp of the first dumped tensor, in microseconds. """ return self._t0
[ "def", "t0", "(", "self", ")", ":", "return", "self", ".", "_t0" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/debug/lib/debug_data.py#L733-L739
tfwu/FaceDetection-ConvNet-3D
f9251c48eb40c5aec8fba7455115c355466555be
python/build/lib.linux-x86_64-2.7/mxnet/executor_manager.py
python
DataParallelExecutorGroup.update_metric
(self, metric, labels)
Update evaluation metric with label and current outputs
Update evaluation metric with label and current outputs
[ "Update", "evaluation", "metric", "with", "label", "and", "current", "outputs" ]
def update_metric(self, metric, labels): """ Update evaluation metric with label and current outputs """ for texec, islice in zip(self.train_execs, self.slices): labels_slice = [label[islice] for label in labels] metric.update(labels_slice, texec.outputs)
[ "def", "update_metric", "(", "self", ",", "metric", ",", "labels", ")", ":", "for", "texec", ",", "islice", "in", "zip", "(", "self", ".", "train_execs", ",", "self", ".", "slices", ")", ":", "labels_slice", "=", "[", "label", "[", "islice", "]", "for", "label", "in", "labels", "]", "metric", ".", "update", "(", "labels_slice", ",", "texec", ".", "outputs", ")" ]
https://github.com/tfwu/FaceDetection-ConvNet-3D/blob/f9251c48eb40c5aec8fba7455115c355466555be/python/build/lib.linux-x86_64-2.7/mxnet/executor_manager.py#L245-L249
NicknineTheEagle/TF2-Base
20459c5a7fbc995b6bf54fa85c2f62a101e9fb64
src/thirdparty/protobuf-2.3.0/python/google/protobuf/internal/wire_format.py
python
_VarUInt64ByteSizeNoTag
(uint64)
return 10
Returns the number of bytes required to serialize a single varint using boundary value comparisons. (unrolled loop optimization -WPierce) uint64 must be unsigned.
Returns the number of bytes required to serialize a single varint using boundary value comparisons. (unrolled loop optimization -WPierce) uint64 must be unsigned.
[ "Returns", "the", "number", "of", "bytes", "required", "to", "serialize", "a", "single", "varint", "using", "boundary", "value", "comparisons", ".", "(", "unrolled", "loop", "optimization", "-", "WPierce", ")", "uint64", "must", "be", "unsigned", "." ]
def _VarUInt64ByteSizeNoTag(uint64): """Returns the number of bytes required to serialize a single varint using boundary value comparisons. (unrolled loop optimization -WPierce) uint64 must be unsigned. """ if uint64 <= 0x7f: return 1 if uint64 <= 0x3fff: return 2 if uint64 <= 0x1fffff: return 3 if uint64 <= 0xfffffff: return 4 if uint64 <= 0x7ffffffff: return 5 if uint64 <= 0x3ffffffffff: return 6 if uint64 <= 0x1ffffffffffff: return 7 if uint64 <= 0xffffffffffffff: return 8 if uint64 <= 0x7fffffffffffffff: return 9 if uint64 > UINT64_MAX: raise message.EncodeError('Value out of range: %d' % uint64) return 10
[ "def", "_VarUInt64ByteSizeNoTag", "(", "uint64", ")", ":", "if", "uint64", "<=", "0x7f", ":", "return", "1", "if", "uint64", "<=", "0x3fff", ":", "return", "2", "if", "uint64", "<=", "0x1fffff", ":", "return", "3", "if", "uint64", "<=", "0xfffffff", ":", "return", "4", "if", "uint64", "<=", "0x7ffffffff", ":", "return", "5", "if", "uint64", "<=", "0x3ffffffffff", ":", "return", "6", "if", "uint64", "<=", "0x1ffffffffffff", ":", "return", "7", "if", "uint64", "<=", "0xffffffffffffff", ":", "return", "8", "if", "uint64", "<=", "0x7fffffffffffffff", ":", "return", "9", "if", "uint64", ">", "UINT64_MAX", ":", "raise", "message", ".", "EncodeError", "(", "'Value out of range: %d'", "%", "uint64", ")", "return", "10" ]
https://github.com/NicknineTheEagle/TF2-Base/blob/20459c5a7fbc995b6bf54fa85c2f62a101e9fb64/src/thirdparty/protobuf-2.3.0/python/google/protobuf/internal/wire_format.py#L232-L248
D-X-Y/caffe-faster-rcnn
eb50c97ff48f3df115d0e85fe0a32b0c7e2aa4cb
scripts/cpp_lint.py
python
FindNextMultiLineCommentStart
(lines, lineix)
return len(lines)
Find the beginning marker for a multiline comment.
Find the beginning marker for a multiline comment.
[ "Find", "the", "beginning", "marker", "for", "a", "multiline", "comment", "." ]
def FindNextMultiLineCommentStart(lines, lineix): """Find the beginning marker for a multiline comment.""" while lineix < len(lines): if lines[lineix].strip().startswith('/*'): # Only return this marker if the comment goes beyond this line if lines[lineix].strip().find('*/', 2) < 0: return lineix lineix += 1 return len(lines)
[ "def", "FindNextMultiLineCommentStart", "(", "lines", ",", "lineix", ")", ":", "while", "lineix", "<", "len", "(", "lines", ")", ":", "if", "lines", "[", "lineix", "]", ".", "strip", "(", ")", ".", "startswith", "(", "'/*'", ")", ":", "# Only return this marker if the comment goes beyond this line", "if", "lines", "[", "lineix", "]", ".", "strip", "(", ")", ".", "find", "(", "'*/'", ",", "2", ")", "<", "0", ":", "return", "lineix", "lineix", "+=", "1", "return", "len", "(", "lines", ")" ]
https://github.com/D-X-Y/caffe-faster-rcnn/blob/eb50c97ff48f3df115d0e85fe0a32b0c7e2aa4cb/scripts/cpp_lint.py#L1127-L1135
potassco/clingo
e0c91d8f95cc28de1c480a871f9c97c30de83d40
libpyclingo/clingo/ast.py
python
ShowTerm
(location: Location, term: AST, body: Sequence[AST], csp: int)
return AST(p_ast[0])
Construct an AST node of type `ASTType.ShowTerm`.
Construct an AST node of type `ASTType.ShowTerm`.
[ "Construct", "an", "AST", "node", "of", "type", "ASTType", ".", "ShowTerm", "." ]
def ShowTerm(location: Location, term: AST, body: Sequence[AST], csp: int) -> AST: ''' Construct an AST node of type `ASTType.ShowTerm`. ''' p_ast = _ffi.new('clingo_ast_t**') c_location = _c_location(location) _handle_error(_lib.clingo_ast_build( _lib.clingo_ast_type_show_term, p_ast, c_location[0], term._rep, _ffi.new('clingo_ast_t*[]', [ x._rep for x in body ]), _ffi.cast('size_t', len(body)), _ffi.cast('int', csp))) return AST(p_ast[0])
[ "def", "ShowTerm", "(", "location", ":", "Location", ",", "term", ":", "AST", ",", "body", ":", "Sequence", "[", "AST", "]", ",", "csp", ":", "int", ")", "->", "AST", ":", "p_ast", "=", "_ffi", ".", "new", "(", "'clingo_ast_t**'", ")", "c_location", "=", "_c_location", "(", "location", ")", "_handle_error", "(", "_lib", ".", "clingo_ast_build", "(", "_lib", ".", "clingo_ast_type_show_term", ",", "p_ast", ",", "c_location", "[", "0", "]", ",", "term", ".", "_rep", ",", "_ffi", ".", "new", "(", "'clingo_ast_t*[]'", ",", "[", "x", ".", "_rep", "for", "x", "in", "body", "]", ")", ",", "_ffi", ".", "cast", "(", "'size_t'", ",", "len", "(", "body", ")", ")", ",", "_ffi", ".", "cast", "(", "'int'", ",", "csp", ")", ")", ")", "return", "AST", "(", "p_ast", "[", "0", "]", ")" ]
https://github.com/potassco/clingo/blob/e0c91d8f95cc28de1c480a871f9c97c30de83d40/libpyclingo/clingo/ast.py#L1732-L1745
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/textwrap.py
python
TextWrapper._fix_sentence_endings
(self, chunks)
_fix_sentence_endings(chunks : [string]) Correct for sentence endings buried in 'chunks'. Eg. when the original text contains "... foo.\\nBar ...", munge_whitespace() and split() will convert that to [..., "foo.", " ", "Bar", ...] which has one too few spaces; this method simply changes the one space to two.
_fix_sentence_endings(chunks : [string])
[ "_fix_sentence_endings", "(", "chunks", ":", "[", "string", "]", ")" ]
def _fix_sentence_endings(self, chunks): """_fix_sentence_endings(chunks : [string]) Correct for sentence endings buried in 'chunks'. Eg. when the original text contains "... foo.\\nBar ...", munge_whitespace() and split() will convert that to [..., "foo.", " ", "Bar", ...] which has one too few spaces; this method simply changes the one space to two. """ i = 0 patsearch = self.sentence_end_re.search while i < len(chunks)-1: if chunks[i+1] == " " and patsearch(chunks[i]): chunks[i+1] = " " i += 2 else: i += 1
[ "def", "_fix_sentence_endings", "(", "self", ",", "chunks", ")", ":", "i", "=", "0", "patsearch", "=", "self", ".", "sentence_end_re", ".", "search", "while", "i", "<", "len", "(", "chunks", ")", "-", "1", ":", "if", "chunks", "[", "i", "+", "1", "]", "==", "\" \"", "and", "patsearch", "(", "chunks", "[", "i", "]", ")", ":", "chunks", "[", "i", "+", "1", "]", "=", "\" \"", "i", "+=", "2", "else", ":", "i", "+=", "1" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/textwrap.py#L182-L198
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/cuda/cudadrv/driver.py
python
device_memset
(dst, val, size, stream=0)
Memset on the device. If stream is not zero, asynchronous mode is used. dst: device memory val: byte value to be written size: number of byte to be written stream: a CUDA stream
Memset on the device. If stream is not zero, asynchronous mode is used.
[ "Memset", "on", "the", "device", ".", "If", "stream", "is", "not", "zero", "asynchronous", "mode", "is", "used", "." ]
def device_memset(dst, val, size, stream=0): """Memset on the device. If stream is not zero, asynchronous mode is used. dst: device memory val: byte value to be written size: number of byte to be written stream: a CUDA stream """ varargs = [] if stream: assert isinstance(stream, Stream) fn = driver.cuMemsetD8Async varargs.append(stream.handle) else: fn = driver.cuMemsetD8 fn(device_pointer(dst), val, size, *varargs)
[ "def", "device_memset", "(", "dst", ",", "val", ",", "size", ",", "stream", "=", "0", ")", ":", "varargs", "=", "[", "]", "if", "stream", ":", "assert", "isinstance", "(", "stream", ",", "Stream", ")", "fn", "=", "driver", ".", "cuMemsetD8Async", "varargs", ".", "append", "(", "stream", ".", "handle", ")", "else", ":", "fn", "=", "driver", ".", "cuMemsetD8", "fn", "(", "device_pointer", "(", "dst", ")", ",", "val", ",", "size", ",", "*", "varargs", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/cuda/cudadrv/driver.py#L1939-L1957
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/contrib/factorization/python/ops/gmm.py
python
GMM.__init__
(self, num_clusters, model_dir=None, random_seed=0, params='wmc', initial_clusters='random', covariance_type='full', batch_size=128, steps=10, continue_training=False, config=None, verbose=1)
Creates a model for running GMM training and inference. Args: num_clusters: number of clusters to train. model_dir: the directory to save the model results and log files. random_seed: Python integer. Seed for PRNG used to initialize centers. params: Controls which parameters are updated in the training process. Can contain any combination of "w" for weights, "m" for means, and "c" for covars. initial_clusters: specifies how to initialize the clusters for training. See gmm_ops.gmm for the possible values. covariance_type: one of "full", "diag". batch_size: See TensorFlowEstimator steps: See TensorFlowEstimator continue_training: See TensorFlowEstimator config: See TensorFlowEstimator verbose: See TensorFlowEstimator
Creates a model for running GMM training and inference.
[ "Creates", "a", "model", "for", "running", "GMM", "training", "and", "inference", "." ]
def __init__(self, num_clusters, model_dir=None, random_seed=0, params='wmc', initial_clusters='random', covariance_type='full', batch_size=128, steps=10, continue_training=False, config=None, verbose=1): """Creates a model for running GMM training and inference. Args: num_clusters: number of clusters to train. model_dir: the directory to save the model results and log files. random_seed: Python integer. Seed for PRNG used to initialize centers. params: Controls which parameters are updated in the training process. Can contain any combination of "w" for weights, "m" for means, and "c" for covars. initial_clusters: specifies how to initialize the clusters for training. See gmm_ops.gmm for the possible values. covariance_type: one of "full", "diag". batch_size: See TensorFlowEstimator steps: See TensorFlowEstimator continue_training: See TensorFlowEstimator config: See TensorFlowEstimator verbose: See TensorFlowEstimator """ super(GMM, self).__init__( model_dir=model_dir, config=config) self.batch_size = batch_size self.steps = steps self.continue_training = continue_training self.verbose = verbose self._num_clusters = num_clusters self._params = params self._training_initial_clusters = initial_clusters self._covariance_type = covariance_type self._training_graph = None self._random_seed = random_seed
[ "def", "__init__", "(", "self", ",", "num_clusters", ",", "model_dir", "=", "None", ",", "random_seed", "=", "0", ",", "params", "=", "'wmc'", ",", "initial_clusters", "=", "'random'", ",", "covariance_type", "=", "'full'", ",", "batch_size", "=", "128", ",", "steps", "=", "10", ",", "continue_training", "=", "False", ",", "config", "=", "None", ",", "verbose", "=", "1", ")", ":", "super", "(", "GMM", ",", "self", ")", ".", "__init__", "(", "model_dir", "=", "model_dir", ",", "config", "=", "config", ")", "self", ".", "batch_size", "=", "batch_size", "self", ".", "steps", "=", "steps", "self", ".", "continue_training", "=", "continue_training", "self", ".", "verbose", "=", "verbose", "self", ".", "_num_clusters", "=", "num_clusters", "self", ".", "_params", "=", "params", "self", ".", "_training_initial_clusters", "=", "initial_clusters", "self", ".", "_covariance_type", "=", "covariance_type", "self", ".", "_training_graph", "=", "None", "self", ".", "_random_seed", "=", "random_seed" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/factorization/python/ops/gmm.py#L43-L85
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_controls.py
python
ToolBarToolBase.SetToggle
(*args, **kwargs)
return _controls_.ToolBarToolBase_SetToggle(*args, **kwargs)
SetToggle(self, bool toggle) -> bool
SetToggle(self, bool toggle) -> bool
[ "SetToggle", "(", "self", "bool", "toggle", ")", "-", ">", "bool" ]
def SetToggle(*args, **kwargs): """SetToggle(self, bool toggle) -> bool""" return _controls_.ToolBarToolBase_SetToggle(*args, **kwargs)
[ "def", "SetToggle", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "ToolBarToolBase_SetToggle", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L3521-L3523
lammps/lammps
b75c3065430a75b1b5543a10e10f46d9b4c91913
tools/i-pi/ipi/engine/ensembles.py
python
NPTEnsemble.step
(self)
NPT time step. Note that the barostat only propagates the centroid coordinates. If this approximation is made a centroid virial pressure and stress estimator can be defined, so this gives the best statistical convergence. This is allowed as the normal mode propagation is approximately unaffected by volume fluctuations as long as the system box is much larger than the radius of gyration of the ring polymers.
NPT time step.
[ "NPT", "time", "step", "." ]
def step(self): """NPT time step. Note that the barostat only propagates the centroid coordinates. If this approximation is made a centroid virial pressure and stress estimator can be defined, so this gives the best statistical convergence. This is allowed as the normal mode propagation is approximately unaffected by volume fluctuations as long as the system box is much larger than the radius of gyration of the ring polymers. """ self.ttime = -time.time() self.thermostat.step() self.barostat.thermostat.step() self.rmcom() self.ttime += time.time() self.ptime = -time.time() self.barostat.pstep() self.ptime += time.time() self.qtime = -time.time() self.barostat.qcstep() self.nm.free_qstep() self.qtime += time.time() self.ptime -= time.time() self.barostat.pstep() self.ptime += time.time() self.ttime -= time.time() self.barostat.thermostat.step() self.thermostat.step() self.rmcom() self.ttime += time.time()
[ "def", "step", "(", "self", ")", ":", "self", ".", "ttime", "=", "-", "time", ".", "time", "(", ")", "self", ".", "thermostat", ".", "step", "(", ")", "self", ".", "barostat", ".", "thermostat", ".", "step", "(", ")", "self", ".", "rmcom", "(", ")", "self", ".", "ttime", "+=", "time", ".", "time", "(", ")", "self", ".", "ptime", "=", "-", "time", ".", "time", "(", ")", "self", ".", "barostat", ".", "pstep", "(", ")", "self", ".", "ptime", "+=", "time", ".", "time", "(", ")", "self", ".", "qtime", "=", "-", "time", ".", "time", "(", ")", "self", ".", "barostat", ".", "qcstep", "(", ")", "self", ".", "nm", ".", "free_qstep", "(", ")", "self", ".", "qtime", "+=", "time", ".", "time", "(", ")", "self", ".", "ptime", "-=", "time", ".", "time", "(", ")", "self", ".", "barostat", ".", "pstep", "(", ")", "self", ".", "ptime", "+=", "time", ".", "time", "(", ")", "self", ".", "ttime", "-=", "time", ".", "time", "(", ")", "self", ".", "barostat", ".", "thermostat", ".", "step", "(", ")", "self", ".", "thermostat", ".", "step", "(", ")", "self", ".", "rmcom", "(", ")", "self", ".", "ttime", "+=", "time", ".", "time", "(", ")" ]
https://github.com/lammps/lammps/blob/b75c3065430a75b1b5543a10e10f46d9b4c91913/tools/i-pi/ipi/engine/ensembles.py#L455-L489
google/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
earth_enterprise/src/google/protobuf-py/google/protobuf/descriptor.py
python
FileDescriptor.CopyToProto
(self, proto)
Copies this to a descriptor_pb2.FileDescriptorProto. Args: proto: An empty descriptor_pb2.FileDescriptorProto.
Copies this to a descriptor_pb2.FileDescriptorProto.
[ "Copies", "this", "to", "a", "descriptor_pb2", ".", "FileDescriptorProto", "." ]
def CopyToProto(self, proto): """Copies this to a descriptor_pb2.FileDescriptorProto. Args: proto: An empty descriptor_pb2.FileDescriptorProto. """ proto.ParseFromString(self.serialized_pb)
[ "def", "CopyToProto", "(", "self", ",", "proto", ")", ":", "proto", ".", "ParseFromString", "(", "self", ".", "serialized_pb", ")" ]
https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/google/protobuf-py/google/protobuf/descriptor.py#L581-L587
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
tools/update-packaging/make_incremental_updates.py
python
create_add_patch_for_file
(to_marfile_entry, patch_info)
Copy the file to the working dir, add the add instruction, and add it to the list of archive files
Copy the file to the working dir, add the add instruction, and add it to the list of archive files
[ "Copy", "the", "file", "to", "the", "working", "dir", "add", "the", "add", "instruction", "and", "add", "it", "to", "the", "list", "of", "archive", "files" ]
def create_add_patch_for_file(to_marfile_entry, patch_info): """ Copy the file to the working dir, add the add instruction, and add it to the list of archive files """ copy_file(to_marfile_entry.abs_path, os.path.join(patch_info.work_dir, to_marfile_entry.name)) patch_info.append_add_instruction(to_marfile_entry.name) patch_info.archive_files.append('"'+to_marfile_entry.name+'"')
[ "def", "create_add_patch_for_file", "(", "to_marfile_entry", ",", "patch_info", ")", ":", "copy_file", "(", "to_marfile_entry", ".", "abs_path", ",", "os", ".", "path", ".", "join", "(", "patch_info", ".", "work_dir", ",", "to_marfile_entry", ".", "name", ")", ")", "patch_info", ".", "append_add_instruction", "(", "to_marfile_entry", ".", "name", ")", "patch_info", ".", "archive_files", ".", "append", "(", "'\"'", "+", "to_marfile_entry", ".", "name", "+", "'\"'", ")" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/tools/update-packaging/make_incremental_updates.py#L284-L288
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/plan/robotcspace.py
python
ClosedLoopRobotCSpace.setIKActiveDofs
(self,activeSet)
Marks that only a subset of the DOFs of the robot are to be used for solving the IK constraint.
Marks that only a subset of the DOFs of the robot are to be used for solving the IK constraint.
[ "Marks", "that", "only", "a", "subset", "of", "the", "DOFs", "of", "the", "robot", "are", "to", "be", "used", "for", "solving", "the", "IK", "constraint", "." ]
def setIKActiveDofs(self,activeSet): """Marks that only a subset of the DOFs of the robot are to be used for solving the IK constraint.""" self.solver.setActiveDofs(activeSet)
[ "def", "setIKActiveDofs", "(", "self", ",", "activeSet", ")", ":", "self", ".", "solver", ".", "setActiveDofs", "(", "activeSet", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/plan/robotcspace.py#L211-L214
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/shutil.py
python
unpack_archive
(filename, extract_dir=None, format=None)
Unpack an archive. `filename` is the name of the archive. `extract_dir` is the name of the target directory, where the archive is unpacked. If not provided, the current working directory is used. `format` is the archive format: one of "zip", "tar", "gztar", "bztar", or "xztar". Or any other registered format. If not provided, unpack_archive will use the filename extension and see if an unpacker was registered for that extension. In case none is found, a ValueError is raised.
Unpack an archive.
[ "Unpack", "an", "archive", "." ]
def unpack_archive(filename, extract_dir=None, format=None): """Unpack an archive. `filename` is the name of the archive. `extract_dir` is the name of the target directory, where the archive is unpacked. If not provided, the current working directory is used. `format` is the archive format: one of "zip", "tar", "gztar", "bztar", or "xztar". Or any other registered format. If not provided, unpack_archive will use the filename extension and see if an unpacker was registered for that extension. In case none is found, a ValueError is raised. """ if extract_dir is None: extract_dir = os.getcwd() extract_dir = os.fspath(extract_dir) filename = os.fspath(filename) if format is not None: try: format_info = _UNPACK_FORMATS[format] except KeyError: raise ValueError("Unknown unpack format '{0}'".format(format)) from None func = format_info[1] func(filename, extract_dir, **dict(format_info[2])) else: # we need to look at the registered unpackers supported extensions format = _find_unpack_format(filename) if format is None: raise ReadError("Unknown archive format '{0}'".format(filename)) func = _UNPACK_FORMATS[format][1] kwargs = dict(_UNPACK_FORMATS[format][2]) func(filename, extract_dir, **kwargs)
[ "def", "unpack_archive", "(", "filename", ",", "extract_dir", "=", "None", ",", "format", "=", "None", ")", ":", "if", "extract_dir", "is", "None", ":", "extract_dir", "=", "os", ".", "getcwd", "(", ")", "extract_dir", "=", "os", ".", "fspath", "(", "extract_dir", ")", "filename", "=", "os", ".", "fspath", "(", "filename", ")", "if", "format", "is", "not", "None", ":", "try", ":", "format_info", "=", "_UNPACK_FORMATS", "[", "format", "]", "except", "KeyError", ":", "raise", "ValueError", "(", "\"Unknown unpack format '{0}'\"", ".", "format", "(", "format", ")", ")", "from", "None", "func", "=", "format_info", "[", "1", "]", "func", "(", "filename", ",", "extract_dir", ",", "*", "*", "dict", "(", "format_info", "[", "2", "]", ")", ")", "else", ":", "# we need to look at the registered unpackers supported extensions", "format", "=", "_find_unpack_format", "(", "filename", ")", "if", "format", "is", "None", ":", "raise", "ReadError", "(", "\"Unknown archive format '{0}'\"", ".", "format", "(", "filename", ")", ")", "func", "=", "_UNPACK_FORMATS", "[", "format", "]", "[", "1", "]", "kwargs", "=", "dict", "(", "_UNPACK_FORMATS", "[", "format", "]", "[", "2", "]", ")", "func", "(", "filename", ",", "extract_dir", ",", "*", "*", "kwargs", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/shutil.py#L965-L1002
arangodb/arangodb
0d658689c7d1b721b314fa3ca27d38303e1570c8
3rdParty/V8/v7.9.317/third_party/jinja2/utils.py
python
clear_caches
()
Jinja2 keeps internal caches for environments and lexers. These are used so that Jinja2 doesn't have to recreate environments and lexers all the time. Normally you don't have to care about that but if you are measuring memory consumption you may want to clean the caches.
Jinja2 keeps internal caches for environments and lexers. These are used so that Jinja2 doesn't have to recreate environments and lexers all the time. Normally you don't have to care about that but if you are measuring memory consumption you may want to clean the caches.
[ "Jinja2", "keeps", "internal", "caches", "for", "environments", "and", "lexers", ".", "These", "are", "used", "so", "that", "Jinja2", "doesn", "t", "have", "to", "recreate", "environments", "and", "lexers", "all", "the", "time", ".", "Normally", "you", "don", "t", "have", "to", "care", "about", "that", "but", "if", "you", "are", "measuring", "memory", "consumption", "you", "may", "want", "to", "clean", "the", "caches", "." ]
def clear_caches(): """Jinja2 keeps internal caches for environments and lexers. These are used so that Jinja2 doesn't have to recreate environments and lexers all the time. Normally you don't have to care about that but if you are measuring memory consumption you may want to clean the caches. """ from jinja2.environment import _spontaneous_environments from jinja2.lexer import _lexer_cache _spontaneous_environments.clear() _lexer_cache.clear()
[ "def", "clear_caches", "(", ")", ":", "from", "jinja2", ".", "environment", "import", "_spontaneous_environments", "from", "jinja2", ".", "lexer", "import", "_lexer_cache", "_spontaneous_environments", ".", "clear", "(", ")", "_lexer_cache", ".", "clear", "(", ")" ]
https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/v7.9.317/third_party/jinja2/utils.py#L111-L120
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_misc.py
python
Log_DoCreateOnDemand
(*args)
return _misc_.Log_DoCreateOnDemand(*args)
Log_DoCreateOnDemand()
Log_DoCreateOnDemand()
[ "Log_DoCreateOnDemand", "()" ]
def Log_DoCreateOnDemand(*args): """Log_DoCreateOnDemand()""" return _misc_.Log_DoCreateOnDemand(*args)
[ "def", "Log_DoCreateOnDemand", "(", "*", "args", ")", ":", "return", "_misc_", ".", "Log_DoCreateOnDemand", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L1684-L1686
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/computation/pytables.py
python
BinOp.is_in_table
(self)
return self.queryables.get(self.lhs) is not None
return True if this is a valid column name for generation (e.g. an actual column in the table)
return True if this is a valid column name for generation (e.g. an actual column in the table)
[ "return", "True", "if", "this", "is", "a", "valid", "column", "name", "for", "generation", "(", "e", ".", "g", ".", "an", "actual", "column", "in", "the", "table", ")" ]
def is_in_table(self) -> bool: """ return True if this is a valid column name for generation (e.g. an actual column in the table) """ return self.queryables.get(self.lhs) is not None
[ "def", "is_in_table", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "queryables", ".", "get", "(", "self", ".", "lhs", ")", "is", "not", "None" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/computation/pytables.py#L170-L175
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
chrome/common/extensions/docs/server2/compiled_file_system.py
python
SingleFile
(fn)
return fn
A decorator which can be optionally applied to the compilation function passed to CompiledFileSystem.Create, indicating that the function only needs access to the file which is given in the function's callback. When this is the case some optimisations can be done. Note that this decorator must be listed first in any list of decorators to have any effect.
A decorator which can be optionally applied to the compilation function passed to CompiledFileSystem.Create, indicating that the function only needs access to the file which is given in the function's callback. When this is the case some optimisations can be done.
[ "A", "decorator", "which", "can", "be", "optionally", "applied", "to", "the", "compilation", "function", "passed", "to", "CompiledFileSystem", ".", "Create", "indicating", "that", "the", "function", "only", "needs", "access", "to", "the", "file", "which", "is", "given", "in", "the", "function", "s", "callback", ".", "When", "this", "is", "the", "case", "some", "optimisations", "can", "be", "done", "." ]
def SingleFile(fn): '''A decorator which can be optionally applied to the compilation function passed to CompiledFileSystem.Create, indicating that the function only needs access to the file which is given in the function's callback. When this is the case some optimisations can be done. Note that this decorator must be listed first in any list of decorators to have any effect. ''' _SINGLE_FILE_FUNCTIONS.add(fn) return fn
[ "def", "SingleFile", "(", "fn", ")", ":", "_SINGLE_FILE_FUNCTIONS", ".", "add", "(", "fn", ")", "return", "fn" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/chrome/common/extensions/docs/server2/compiled_file_system.py#L20-L30
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/cython/Cython/Compiler/ExprNodes.py
python
BufferIndexNode.buffer_lookup_code
(self, code)
return buffer_entry, Buffer.put_buffer_lookup_code( entry=buffer_entry, index_signeds=[ivar.type.signed for ivar in self.indices], index_cnames=index_temps, directives=code.globalstate.directives, pos=self.pos, code=code, negative_indices=negative_indices, in_nogil_context=self.in_nogil_context)
ndarray[1, 2, 3] and memslice[1, 2, 3]
ndarray[1, 2, 3] and memslice[1, 2, 3]
[ "ndarray", "[", "1", "2", "3", "]", "and", "memslice", "[", "1", "2", "3", "]" ]
def buffer_lookup_code(self, code): """ ndarray[1, 2, 3] and memslice[1, 2, 3] """ if self.in_nogil_context: if self.is_buffer_access or self.is_memview_index: if code.globalstate.directives['boundscheck']: warning(self.pos, "Use boundscheck(False) for faster access", level=1) # Assign indices to temps of at least (s)size_t to allow further index calculations. self.index_temps = index_temps = [self.get_index_in_temp(code,ivar) for ivar in self.indices] # Generate buffer access code using these temps from . import Buffer buffer_entry = self.buffer_entry() if buffer_entry.type.is_buffer: negative_indices = buffer_entry.type.negative_indices else: negative_indices = Buffer.buffer_defaults['negative_indices'] return buffer_entry, Buffer.put_buffer_lookup_code( entry=buffer_entry, index_signeds=[ivar.type.signed for ivar in self.indices], index_cnames=index_temps, directives=code.globalstate.directives, pos=self.pos, code=code, negative_indices=negative_indices, in_nogil_context=self.in_nogil_context)
[ "def", "buffer_lookup_code", "(", "self", ",", "code", ")", ":", "if", "self", ".", "in_nogil_context", ":", "if", "self", ".", "is_buffer_access", "or", "self", ".", "is_memview_index", ":", "if", "code", ".", "globalstate", ".", "directives", "[", "'boundscheck'", "]", ":", "warning", "(", "self", ".", "pos", ",", "\"Use boundscheck(False) for faster access\"", ",", "level", "=", "1", ")", "# Assign indices to temps of at least (s)size_t to allow further index calculations.", "self", ".", "index_temps", "=", "index_temps", "=", "[", "self", ".", "get_index_in_temp", "(", "code", ",", "ivar", ")", "for", "ivar", "in", "self", ".", "indices", "]", "# Generate buffer access code using these temps", "from", ".", "import", "Buffer", "buffer_entry", "=", "self", ".", "buffer_entry", "(", ")", "if", "buffer_entry", ".", "type", ".", "is_buffer", ":", "negative_indices", "=", "buffer_entry", ".", "type", ".", "negative_indices", "else", ":", "negative_indices", "=", "Buffer", ".", "buffer_defaults", "[", "'negative_indices'", "]", "return", "buffer_entry", ",", "Buffer", ".", "put_buffer_lookup_code", "(", "entry", "=", "buffer_entry", ",", "index_signeds", "=", "[", "ivar", ".", "type", ".", "signed", "for", "ivar", "in", "self", ".", "indices", "]", ",", "index_cnames", "=", "index_temps", ",", "directives", "=", "code", ".", "globalstate", ".", "directives", ",", "pos", "=", "self", ".", "pos", ",", "code", "=", "code", ",", "negative_indices", "=", "negative_indices", ",", "in_nogil_context", "=", "self", ".", "in_nogil_context", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/cython/Cython/Compiler/ExprNodes.py#L4287-L4314
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/WebKit/Source/bindings/scripts/generate_global_constructors.py
python
interface_name_to_constructors
(interface_name)
return flatten_list(global_name_to_constructors[global_name] for global_name in global_names)
Returns constructors for an interface.
Returns constructors for an interface.
[ "Returns", "constructors", "for", "an", "interface", "." ]
def interface_name_to_constructors(interface_name): """Returns constructors for an interface.""" global_names = interface_name_to_global_names[interface_name] return flatten_list(global_name_to_constructors[global_name] for global_name in global_names)
[ "def", "interface_name_to_constructors", "(", "interface_name", ")", ":", "global_names", "=", "interface_name_to_global_names", "[", "interface_name", "]", "return", "flatten_list", "(", "global_name_to_constructors", "[", "global_name", "]", "for", "global_name", "in", "global_names", ")" ]
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Source/bindings/scripts/generate_global_constructors.py#L64-L68
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/botocore/docs/method.py
python
document_custom_signature
(section, name, method, include=None, exclude=None)
Documents the signature of a custom method :param section: The section to write the documentation to. :param name: The name of the method :param method: The handle to the method being documented :type include: Dictionary where keys are parameter names and values are the shapes of the parameter names. :param include: The parameter shapes to include in the documentation. :type exclude: List of the names of the parameters to exclude. :param exclude: The names of the parameters to exclude from documentation.
Documents the signature of a custom method
[ "Documents", "the", "signature", "of", "a", "custom", "method" ]
def document_custom_signature(section, name, method, include=None, exclude=None): """Documents the signature of a custom method :param section: The section to write the documentation to. :param name: The name of the method :param method: The handle to the method being documented :type include: Dictionary where keys are parameter names and values are the shapes of the parameter names. :param include: The parameter shapes to include in the documentation. :type exclude: List of the names of the parameters to exclude. :param exclude: The names of the parameters to exclude from documentation. """ args, varargs, keywords, defaults = inspect.getargspec(method) args = args[1:] signature_params = inspect.formatargspec( args, varargs, keywords, defaults) signature_params = signature_params.lstrip('(') signature_params = signature_params.rstrip(')') section.style.start_sphinx_py_method(name, signature_params)
[ "def", "document_custom_signature", "(", "section", ",", "name", ",", "method", ",", "include", "=", "None", ",", "exclude", "=", "None", ")", ":", "args", ",", "varargs", ",", "keywords", ",", "defaults", "=", "inspect", ".", "getargspec", "(", "method", ")", "args", "=", "args", "[", "1", ":", "]", "signature_params", "=", "inspect", ".", "formatargspec", "(", "args", ",", "varargs", ",", "keywords", ",", "defaults", ")", "signature_params", "=", "signature_params", ".", "lstrip", "(", "'('", ")", "signature_params", "=", "signature_params", ".", "rstrip", "(", "')'", ")", "section", ".", "style", ".", "start_sphinx_py_method", "(", "name", ",", "signature_params", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/botocore/docs/method.py#L81-L105
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/robotparser.py
python
RobotFileParser.mtime
(self)
return self.last_checked
Returns the time the robots.txt file was last fetched. This is useful for long-running web spiders that need to check for new robots.txt files periodically.
Returns the time the robots.txt file was last fetched.
[ "Returns", "the", "time", "the", "robots", ".", "txt", "file", "was", "last", "fetched", "." ]
def mtime(self): """Returns the time the robots.txt file was last fetched. This is useful for long-running web spiders that need to check for new robots.txt files periodically. """ return self.last_checked
[ "def", "mtime", "(", "self", ")", ":", "return", "self", ".", "last_checked" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/robotparser.py#L33-L40
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/dummy.py
python
DummyRegressor.predict
(self, X)
return y
Perform classification on test vectors X. Parameters ---------- X : {array-like, sparse matrix}, shape = [n_samples, n_features] Input vectors, where n_samples is the number of samples and n_features is the number of features. Returns ------- y : array, shape = [n_samples] or [n_samples, n_outputs] Predicted target values for X.
Perform classification on test vectors X.
[ "Perform", "classification", "on", "test", "vectors", "X", "." ]
def predict(self, X): """ Perform classification on test vectors X. Parameters ---------- X : {array-like, sparse matrix}, shape = [n_samples, n_features] Input vectors, where n_samples is the number of samples and n_features is the number of features. Returns ------- y : array, shape = [n_samples] or [n_samples, n_outputs] Predicted target values for X. """ check_is_fitted(self, "constant_") X = check_array(X, accept_sparse=['csr', 'csc', 'coo']) n_samples = X.shape[0] y = np.ones((n_samples, 1)) * self.constant_ if self.n_outputs_ == 1 and not self.output_2d_: y = np.ravel(y) return y
[ "def", "predict", "(", "self", ",", "X", ")", ":", "check_is_fitted", "(", "self", ",", "\"constant_\"", ")", "X", "=", "check_array", "(", "X", ",", "accept_sparse", "=", "[", "'csr'", ",", "'csc'", ",", "'coo'", "]", ")", "n_samples", "=", "X", ".", "shape", "[", "0", "]", "y", "=", "np", ".", "ones", "(", "(", "n_samples", ",", "1", ")", ")", "*", "self", ".", "constant_", "if", "self", ".", "n_outputs_", "==", "1", "and", "not", "self", ".", "output_2d_", ":", "y", "=", "np", ".", "ravel", "(", "y", ")", "return", "y" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/dummy.py#L452-L476
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/wizard.py
python
WizardEvent.GetDirection
(*args, **kwargs)
return _wizard.WizardEvent_GetDirection(*args, **kwargs)
GetDirection(self) -> bool
GetDirection(self) -> bool
[ "GetDirection", "(", "self", ")", "-", ">", "bool" ]
def GetDirection(*args, **kwargs): """GetDirection(self) -> bool""" return _wizard.WizardEvent_GetDirection(*args, **kwargs)
[ "def", "GetDirection", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_wizard", ".", "WizardEvent_GetDirection", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/wizard.py#L96-L98
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Tools/Scripts/logmerge.py
python
digest_chunk
(chunk, branch=None)
return records
Digest a chunk -- extract working file name and revisions
Digest a chunk -- extract working file name and revisions
[ "Digest", "a", "chunk", "--", "extract", "working", "file", "name", "and", "revisions" ]
def digest_chunk(chunk, branch=None): """Digest a chunk -- extract working file name and revisions""" lines = chunk[0] key = 'Working file:' keylen = len(key) for line in lines: if line[:keylen] == key: working_file = line[keylen:].strip() break else: working_file = None if branch is None: pass elif branch == "HEAD": branch = re.compile(r"^\d+\.\d+$") else: revisions = {} key = 'symbolic names:\n' found = 0 for line in lines: if line == key: found = 1 elif found: if line[0] in '\t ': tag, rev = line.split() if tag[-1] == ':': tag = tag[:-1] revisions[tag] = rev else: found = 0 rev = revisions.get(branch) branch = re.compile(r"^<>$") # <> to force a mismatch by default if rev: if rev.find('.0.') >= 0: rev = rev.replace('.0.', '.') branch = re.compile(r"^" + re.escape(rev) + r"\.\d+$") records = [] for lines in chunk[1:]: revline = lines[0] dateline = lines[1] text = lines[2:] words = dateline.split() author = None if len(words) >= 3 and words[0] == 'date:': dateword = words[1] timeword = words[2] if timeword[-1:] == ';': timeword = timeword[:-1] date = dateword + ' ' + timeword if len(words) >= 5 and words[3] == 'author:': author = words[4] if author[-1:] == ';': author = author[:-1] else: date = None text.insert(0, revline) words = revline.split() if len(words) >= 2 and words[0] == 'revision': rev = words[1] else: # No 'revision' line -- weird... rev = None text.insert(0, revline) if branch: if rev is None or not branch.match(rev): continue records.append((date, working_file, rev, author, text)) return records
[ "def", "digest_chunk", "(", "chunk", ",", "branch", "=", "None", ")", ":", "lines", "=", "chunk", "[", "0", "]", "key", "=", "'Working file:'", "keylen", "=", "len", "(", "key", ")", "for", "line", "in", "lines", ":", "if", "line", "[", ":", "keylen", "]", "==", "key", ":", "working_file", "=", "line", "[", "keylen", ":", "]", ".", "strip", "(", ")", "break", "else", ":", "working_file", "=", "None", "if", "branch", "is", "None", ":", "pass", "elif", "branch", "==", "\"HEAD\"", ":", "branch", "=", "re", ".", "compile", "(", "r\"^\\d+\\.\\d+$\"", ")", "else", ":", "revisions", "=", "{", "}", "key", "=", "'symbolic names:\\n'", "found", "=", "0", "for", "line", "in", "lines", ":", "if", "line", "==", "key", ":", "found", "=", "1", "elif", "found", ":", "if", "line", "[", "0", "]", "in", "'\\t '", ":", "tag", ",", "rev", "=", "line", ".", "split", "(", ")", "if", "tag", "[", "-", "1", "]", "==", "':'", ":", "tag", "=", "tag", "[", ":", "-", "1", "]", "revisions", "[", "tag", "]", "=", "rev", "else", ":", "found", "=", "0", "rev", "=", "revisions", ".", "get", "(", "branch", ")", "branch", "=", "re", ".", "compile", "(", "r\"^<>$\"", ")", "# <> to force a mismatch by default", "if", "rev", ":", "if", "rev", ".", "find", "(", "'.0.'", ")", ">=", "0", ":", "rev", "=", "rev", ".", "replace", "(", "'.0.'", ",", "'.'", ")", "branch", "=", "re", ".", "compile", "(", "r\"^\"", "+", "re", ".", "escape", "(", "rev", ")", "+", "r\"\\.\\d+$\"", ")", "records", "=", "[", "]", "for", "lines", "in", "chunk", "[", "1", ":", "]", ":", "revline", "=", "lines", "[", "0", "]", "dateline", "=", "lines", "[", "1", "]", "text", "=", "lines", "[", "2", ":", "]", "words", "=", "dateline", ".", "split", "(", ")", "author", "=", "None", "if", "len", "(", "words", ")", ">=", "3", "and", "words", "[", "0", "]", "==", "'date:'", ":", "dateword", "=", "words", "[", "1", "]", "timeword", "=", "words", "[", "2", "]", "if", "timeword", "[", "-", "1", ":", "]", "==", "';'", ":", "timeword", "=", "timeword", "[", ":", "-", "1", "]", "date", "=", "dateword", "+", "' '", "+", "timeword", "if", "len", "(", "words", ")", ">=", "5", "and", "words", "[", "3", "]", "==", "'author:'", ":", "author", "=", "words", "[", "4", "]", "if", "author", "[", "-", "1", ":", "]", "==", "';'", ":", "author", "=", "author", "[", ":", "-", "1", "]", "else", ":", "date", "=", "None", "text", ".", "insert", "(", "0", ",", "revline", ")", "words", "=", "revline", ".", "split", "(", ")", "if", "len", "(", "words", ")", ">=", "2", "and", "words", "[", "0", "]", "==", "'revision'", ":", "rev", "=", "words", "[", "1", "]", "else", ":", "# No 'revision' line -- weird...", "rev", "=", "None", "text", ".", "insert", "(", "0", ",", "revline", ")", "if", "branch", ":", "if", "rev", "is", "None", "or", "not", "branch", ".", "match", "(", "rev", ")", ":", "continue", "records", ".", "append", "(", "(", "date", ",", "working_file", ",", "rev", ",", "author", ",", "text", ")", ")", "return", "records" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Tools/Scripts/logmerge.py#L96-L163
psi4/psi4
be533f7f426b6ccc263904e55122899b16663395
psi4/driver/procrouting/proc.py
python
select_mp2
(name, **kwargs)
Function selecting the algorithm for a MP2 energy call and directing to specified or best-performance default modules.
Function selecting the algorithm for a MP2 energy call and directing to specified or best-performance default modules.
[ "Function", "selecting", "the", "algorithm", "for", "a", "MP2", "energy", "call", "and", "directing", "to", "specified", "or", "best", "-", "performance", "default", "modules", "." ]
def select_mp2(name, **kwargs): """Function selecting the algorithm for a MP2 energy call and directing to specified or best-performance default modules. """ reference = core.get_option('SCF', 'REFERENCE') mtd_type = core.get_global_option('MP2_TYPE') module = core.get_global_option('QC_MODULE') # Considering only [df]occ/dfmp2/detci/fnocc # MP2_TYPE exists largely for py-side reasoning, so must manage it # here rather than passing to c-side unprepared for validation func = None if reference == 'RHF': if mtd_type == 'CONV': if module == 'DETCI': func = run_detci elif module == 'FNOCC': func = run_fnocc elif module in ['', 'OCC']: func = run_occ elif mtd_type == 'DF': if module == 'OCC': func = run_dfocc elif module in ['', 'DFMP2']: func = run_dfmp2 elif mtd_type == 'CD': if module in ['', 'OCC']: func = run_dfocc elif reference == 'UHF': if mtd_type == 'CONV': if module in ['', 'OCC']: func = run_occ elif mtd_type == 'DF': if module == 'OCC': func = run_dfocc elif module in ['', 'DFMP2']: func = run_dfmp2 elif mtd_type == 'CD': if module in ['', 'OCC']: func = run_dfocc elif reference == 'ROHF': if mtd_type == 'CONV': if module == 'DETCI': func = run_detci elif module in ['', 'OCC']: func = run_occ elif mtd_type == 'DF': if module == 'OCC': func = run_dfocc elif module in ['', 'DFMP2']: func = run_dfmp2 elif mtd_type == 'CD': if module in ['', 'OCC']: func = run_dfocc elif reference in ['RKS', 'UKS']: if mtd_type == 'DF': if module in ['', 'DFMP2']: func = run_dfmp2 if module == 'DETCI': core.print_out("""\nDETCI is ill-advised for method MP2 as it is available inefficiently as a """ """byproduct of a CISD computation.\n DETCI ROHF MP2 will produce non-standard results.\n""") if func is None: raise ManagedMethodError(['select_mp2', name, 'MP2_TYPE', mtd_type, reference, module]) if kwargs.pop('probe', False): return else: return func(name, **kwargs)
[ "def", "select_mp2", "(", "name", ",", "*", "*", "kwargs", ")", ":", "reference", "=", "core", ".", "get_option", "(", "'SCF'", ",", "'REFERENCE'", ")", "mtd_type", "=", "core", ".", "get_global_option", "(", "'MP2_TYPE'", ")", "module", "=", "core", ".", "get_global_option", "(", "'QC_MODULE'", ")", "# Considering only [df]occ/dfmp2/detci/fnocc", "# MP2_TYPE exists largely for py-side reasoning, so must manage it", "# here rather than passing to c-side unprepared for validation", "func", "=", "None", "if", "reference", "==", "'RHF'", ":", "if", "mtd_type", "==", "'CONV'", ":", "if", "module", "==", "'DETCI'", ":", "func", "=", "run_detci", "elif", "module", "==", "'FNOCC'", ":", "func", "=", "run_fnocc", "elif", "module", "in", "[", "''", ",", "'OCC'", "]", ":", "func", "=", "run_occ", "elif", "mtd_type", "==", "'DF'", ":", "if", "module", "==", "'OCC'", ":", "func", "=", "run_dfocc", "elif", "module", "in", "[", "''", ",", "'DFMP2'", "]", ":", "func", "=", "run_dfmp2", "elif", "mtd_type", "==", "'CD'", ":", "if", "module", "in", "[", "''", ",", "'OCC'", "]", ":", "func", "=", "run_dfocc", "elif", "reference", "==", "'UHF'", ":", "if", "mtd_type", "==", "'CONV'", ":", "if", "module", "in", "[", "''", ",", "'OCC'", "]", ":", "func", "=", "run_occ", "elif", "mtd_type", "==", "'DF'", ":", "if", "module", "==", "'OCC'", ":", "func", "=", "run_dfocc", "elif", "module", "in", "[", "''", ",", "'DFMP2'", "]", ":", "func", "=", "run_dfmp2", "elif", "mtd_type", "==", "'CD'", ":", "if", "module", "in", "[", "''", ",", "'OCC'", "]", ":", "func", "=", "run_dfocc", "elif", "reference", "==", "'ROHF'", ":", "if", "mtd_type", "==", "'CONV'", ":", "if", "module", "==", "'DETCI'", ":", "func", "=", "run_detci", "elif", "module", "in", "[", "''", ",", "'OCC'", "]", ":", "func", "=", "run_occ", "elif", "mtd_type", "==", "'DF'", ":", "if", "module", "==", "'OCC'", ":", "func", "=", "run_dfocc", "elif", "module", "in", "[", "''", ",", "'DFMP2'", "]", ":", "func", "=", "run_dfmp2", "elif", "mtd_type", "==", "'CD'", ":", "if", "module", "in", "[", "''", ",", "'OCC'", "]", ":", "func", "=", "run_dfocc", "elif", "reference", "in", "[", "'RKS'", ",", "'UKS'", "]", ":", "if", "mtd_type", "==", "'DF'", ":", "if", "module", "in", "[", "''", ",", "'DFMP2'", "]", ":", "func", "=", "run_dfmp2", "if", "module", "==", "'DETCI'", ":", "core", ".", "print_out", "(", "\"\"\"\\nDETCI is ill-advised for method MP2 as it is available inefficiently as a \"\"\"", "\"\"\"byproduct of a CISD computation.\\n DETCI ROHF MP2 will produce non-standard results.\\n\"\"\"", ")", "if", "func", "is", "None", ":", "raise", "ManagedMethodError", "(", "[", "'select_mp2'", ",", "name", ",", "'MP2_TYPE'", ",", "mtd_type", ",", "reference", ",", "module", "]", ")", "if", "kwargs", ".", "pop", "(", "'probe'", ",", "False", ")", ":", "return", "else", ":", "return", "func", "(", "name", ",", "*", "*", "kwargs", ")" ]
https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/procrouting/proc.py#L65-L136
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/protobuf/py3/google/protobuf/json_format.py
python
MessageToDict
( message, including_default_value_fields=False, preserving_proto_field_name=False, use_integers_for_enums=False, descriptor_pool=None, float_precision=None)
return printer._MessageToJsonObject(message)
Converts protobuf message to a dictionary. When the dictionary is encoded to JSON, it conforms to proto3 JSON spec. Args: message: The protocol buffers message instance to serialize. including_default_value_fields: If True, singular primitive fields, repeated fields, and map fields will always be serialized. If False, only serialize non-empty fields. Singular message fields and oneof fields are not affected by this option. preserving_proto_field_name: If True, use the original proto field names as defined in the .proto file. If False, convert the field names to lowerCamelCase. use_integers_for_enums: If true, print integers instead of enum names. descriptor_pool: A Descriptor Pool for resolving types. If None use the default. float_precision: If set, use this to specify float field valid digits. Returns: A dict representation of the protocol buffer message.
Converts protobuf message to a dictionary.
[ "Converts", "protobuf", "message", "to", "a", "dictionary", "." ]
def MessageToDict( message, including_default_value_fields=False, preserving_proto_field_name=False, use_integers_for_enums=False, descriptor_pool=None, float_precision=None): """Converts protobuf message to a dictionary. When the dictionary is encoded to JSON, it conforms to proto3 JSON spec. Args: message: The protocol buffers message instance to serialize. including_default_value_fields: If True, singular primitive fields, repeated fields, and map fields will always be serialized. If False, only serialize non-empty fields. Singular message fields and oneof fields are not affected by this option. preserving_proto_field_name: If True, use the original proto field names as defined in the .proto file. If False, convert the field names to lowerCamelCase. use_integers_for_enums: If true, print integers instead of enum names. descriptor_pool: A Descriptor Pool for resolving types. If None use the default. float_precision: If set, use this to specify float field valid digits. Returns: A dict representation of the protocol buffer message. """ printer = _Printer( including_default_value_fields, preserving_proto_field_name, use_integers_for_enums, descriptor_pool, float_precision=float_precision) # pylint: disable=protected-access return printer._MessageToJsonObject(message)
[ "def", "MessageToDict", "(", "message", ",", "including_default_value_fields", "=", "False", ",", "preserving_proto_field_name", "=", "False", ",", "use_integers_for_enums", "=", "False", ",", "descriptor_pool", "=", "None", ",", "float_precision", "=", "None", ")", ":", "printer", "=", "_Printer", "(", "including_default_value_fields", ",", "preserving_proto_field_name", ",", "use_integers_for_enums", ",", "descriptor_pool", ",", "float_precision", "=", "float_precision", ")", "# pylint: disable=protected-access", "return", "printer", ".", "_MessageToJsonObject", "(", "message", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py3/google/protobuf/json_format.py#L140-L175
jeog/TOSDataBridge
6a5a08ca5cf3883db1f12e9bc89ef374d098df5a
python/tosdb/__init__.py
python
VInit
(address, dllpath=None, root="C:\\", password=None, timeout=DEF_TIMEOUT)
Manage a virtual 'session' with a host system's C lib, engine, and TOS platform. The context manager handles initialization of the virtual admin interface and the host C Lib, then tries to connect the latter with the engine and TOS platform on the host. On exiting the context block it automatically cleans up the host system and closes down the connection. with VInit(...): # (automatically initializes, connects etc.) # use virtual admin interface, create data blocks etc. # (automatically cleans up, closes etc.) VInit(address, dllpath=None, root="C:\\", password=None, timeout=DEF_TIMEOUT) address :: (str,int) :: (address of the host system, port) dllpath :: str :: exact path of the DLL -or- root :: str :: directory to start walking/searching to find the DLL password :: str :: password for authentication(None for no authentication) timeout :: int :: timeout used by the underlying socket throws TOSDB_VirtualizationError TOSDB_InitError
Manage a virtual 'session' with a host system's C lib, engine, and TOS platform.
[ "Manage", "a", "virtual", "session", "with", "a", "host", "system", "s", "C", "lib", "engine", "and", "TOS", "platform", "." ]
def VInit(address, dllpath=None, root="C:\\", password=None, timeout=DEF_TIMEOUT): """ Manage a virtual 'session' with a host system's C lib, engine, and TOS platform. The context manager handles initialization of the virtual admin interface and the host C Lib, then tries to connect the latter with the engine and TOS platform on the host. On exiting the context block it automatically cleans up the host system and closes down the connection. with VInit(...): # (automatically initializes, connects etc.) # use virtual admin interface, create data blocks etc. # (automatically cleans up, closes etc.) VInit(address, dllpath=None, root="C:\\", password=None, timeout=DEF_TIMEOUT) address :: (str,int) :: (address of the host system, port) dllpath :: str :: exact path of the DLL -or- root :: str :: directory to start walking/searching to find the DLL password :: str :: password for authentication(None for no authentication) timeout :: int :: timeout used by the underlying socket throws TOSDB_VirtualizationError TOSDB_InitError """ try: admin_init(address, password, timeout) if not vinit(dllpath, root): raise TOSDB_InitError("failed to initilize library (virtual)") if not vconnected(): if not vconnect(): # try again raise TOSDB_InitError("failed to connect to library (virtual)") yield finally: vclean_up() admin_close()
[ "def", "VInit", "(", "address", ",", "dllpath", "=", "None", ",", "root", "=", "\"C:\\\\\"", ",", "password", "=", "None", ",", "timeout", "=", "DEF_TIMEOUT", ")", ":", "try", ":", "admin_init", "(", "address", ",", "password", ",", "timeout", ")", "if", "not", "vinit", "(", "dllpath", ",", "root", ")", ":", "raise", "TOSDB_InitError", "(", "\"failed to initilize library (virtual)\"", ")", "if", "not", "vconnected", "(", ")", ":", "if", "not", "vconnect", "(", ")", ":", "# try again", "raise", "TOSDB_InitError", "(", "\"failed to connect to library (virtual)\"", ")", "yield", "finally", ":", "vclean_up", "(", ")", "admin_close", "(", ")" ]
https://github.com/jeog/TOSDataBridge/blob/6a5a08ca5cf3883db1f12e9bc89ef374d098df5a/python/tosdb/__init__.py#L266-L299
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/mimetools.py
python
decode
(input, output, encoding)
Decode common content-transfer-encodings (base64, quopri, uuencode).
Decode common content-transfer-encodings (base64, quopri, uuencode).
[ "Decode", "common", "content", "-", "transfer", "-", "encodings", "(", "base64", "quopri", "uuencode", ")", "." ]
def decode(input, output, encoding): """Decode common content-transfer-encodings (base64, quopri, uuencode).""" if encoding == 'base64': import base64 return base64.decode(input, output) if encoding == 'quoted-printable': import quopri return quopri.decode(input, output) if encoding in ('uuencode', 'x-uuencode', 'uue', 'x-uue'): import uu return uu.decode(input, output) if encoding in ('7bit', '8bit'): return output.write(input.read()) if encoding in decodetab: pipethrough(input, decodetab[encoding], output) else: raise ValueError, \ 'unknown Content-Transfer-Encoding: %s' % encoding
[ "def", "decode", "(", "input", ",", "output", ",", "encoding", ")", ":", "if", "encoding", "==", "'base64'", ":", "import", "base64", "return", "base64", ".", "decode", "(", "input", ",", "output", ")", "if", "encoding", "==", "'quoted-printable'", ":", "import", "quopri", "return", "quopri", ".", "decode", "(", "input", ",", "output", ")", "if", "encoding", "in", "(", "'uuencode'", ",", "'x-uuencode'", ",", "'uue'", ",", "'x-uue'", ")", ":", "import", "uu", "return", "uu", ".", "decode", "(", "input", ",", "output", ")", "if", "encoding", "in", "(", "'7bit'", ",", "'8bit'", ")", ":", "return", "output", ".", "write", "(", "input", ".", "read", "(", ")", ")", "if", "encoding", "in", "decodetab", ":", "pipethrough", "(", "input", ",", "decodetab", "[", "encoding", "]", ",", "output", ")", "else", ":", "raise", "ValueError", ",", "'unknown Content-Transfer-Encoding: %s'", "%", "encoding" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/mimetools.py#L157-L174
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/win/toolchain/toolchain.py
python
CopyToFinalLocation2010
(extracted, target_dir)
Copy all the directories we need to the target location.
Copy all the directories we need to the target location.
[ "Copy", "all", "the", "directories", "we", "need", "to", "the", "target", "location", "." ]
def CopyToFinalLocation2010(extracted, target_dir): """Copy all the directories we need to the target location.""" sys.stdout.write('Pulling together required pieces...\n') # Note that order is important because some of the older ones are # overwritten by updates. from_sdk = [(r'Windows Kits\8.0', r'win8sdk')] PullFrom(from_sdk, extracted.sdk_path, target_dir) from_metro_sdk = [(r'Windows Kits\8.0', r'win8sdk')] PullFrom(from_sdk, extracted.metro_sdk_path, target_dir) from_buildtools_x86 = [ (r'WinDDK\7600.16385.win7_wdk.100208-1538\bin\x86', r'WDK\bin'), ] PullFrom(from_buildtools_x86, extracted.buildtools_x86, target_dir) from_buildtools_x64 = [ (r'WinDDK\7600.16385.win7_wdk.100208-1538\bin\amd64', r'WDK\bin'), ] PullFrom(from_buildtools_x64, extracted.buildtools_x64, target_dir) from_libs_x86 = [ (r'WinDDK\7600.16385.win7_wdk.100208-1538\lib', r'WDK\lib'), ] PullFrom(from_libs_x86, extracted.libs_x86, target_dir) from_libs_x64 = [ (r'WinDDK\7600.16385.win7_wdk.100208-1538\lib', r'WDK\lib'), ] PullFrom(from_libs_x64, extracted.libs_x64, target_dir) from_headers = [ (r'WinDDK\7600.16385.win7_wdk.100208-1538\inc', r'WDK\inc'), ] PullFrom(from_headers, extracted.headers, target_dir) # The compiler update to get the SP1 compiler is a bit of a mess. See # http://goo.gl/n1DeO. The summary is that update for the standalone compiler # binary installs a broken set of headers. So, add an empty ammintrin.h since # we don't actually need the contents of it (for Chromium). from_sdk7_x86 = [ (r'Program Files\Microsoft Visual Studio 10.0', '.'), (r'Win\System', r'VC\bin'), ] PullFrom(from_sdk7_x86, extracted.vc_x86, target_dir) from_sdk7_x64 =[ (r'Program Files(64)\Microsoft Visual Studio 10.0', '.'), (r'Win\System64', r'VC\bin\amd64'), ] PullFrom(from_sdk7_x64, extracted.vc_x64, target_dir) from_vcupdate_x86 = [ (r'Program Files\Microsoft Visual Studio 10.0', '.'), (r'Win\System', r'VC\bin'), ] PullFrom(from_vcupdate_x86, extracted.update_x86, target_dir) from_vcupdate_x64 = [ (r'Program Files(64)\Microsoft Visual Studio 10.0', '.'), (r'Win\System64', r'VC\bin\amd64'), ] PullFrom(from_vcupdate_x64, extracted.update_x64, target_dir) sys.stdout.write('Stubbing ammintrin.h...\n') open(os.path.join(target_dir, r'VC\include\ammintrin.h'), 'w').close() from_dxsdk = [ (r'DXSDK\Include', r'DXSDK\Include'), (r'DXSDK\Lib', r'DXSDK\Lib'), (r'DXSDK\Redist', r'DXSDK\Redist'), ] PullFrom(from_dxsdk, extracted.dxsdk, target_dir)
[ "def", "CopyToFinalLocation2010", "(", "extracted", ",", "target_dir", ")", ":", "sys", ".", "stdout", ".", "write", "(", "'Pulling together required pieces...\\n'", ")", "# Note that order is important because some of the older ones are", "# overwritten by updates.", "from_sdk", "=", "[", "(", "r'Windows Kits\\8.0'", ",", "r'win8sdk'", ")", "]", "PullFrom", "(", "from_sdk", ",", "extracted", ".", "sdk_path", ",", "target_dir", ")", "from_metro_sdk", "=", "[", "(", "r'Windows Kits\\8.0'", ",", "r'win8sdk'", ")", "]", "PullFrom", "(", "from_sdk", ",", "extracted", ".", "metro_sdk_path", ",", "target_dir", ")", "from_buildtools_x86", "=", "[", "(", "r'WinDDK\\7600.16385.win7_wdk.100208-1538\\bin\\x86'", ",", "r'WDK\\bin'", ")", ",", "]", "PullFrom", "(", "from_buildtools_x86", ",", "extracted", ".", "buildtools_x86", ",", "target_dir", ")", "from_buildtools_x64", "=", "[", "(", "r'WinDDK\\7600.16385.win7_wdk.100208-1538\\bin\\amd64'", ",", "r'WDK\\bin'", ")", ",", "]", "PullFrom", "(", "from_buildtools_x64", ",", "extracted", ".", "buildtools_x64", ",", "target_dir", ")", "from_libs_x86", "=", "[", "(", "r'WinDDK\\7600.16385.win7_wdk.100208-1538\\lib'", ",", "r'WDK\\lib'", ")", ",", "]", "PullFrom", "(", "from_libs_x86", ",", "extracted", ".", "libs_x86", ",", "target_dir", ")", "from_libs_x64", "=", "[", "(", "r'WinDDK\\7600.16385.win7_wdk.100208-1538\\lib'", ",", "r'WDK\\lib'", ")", ",", "]", "PullFrom", "(", "from_libs_x64", ",", "extracted", ".", "libs_x64", ",", "target_dir", ")", "from_headers", "=", "[", "(", "r'WinDDK\\7600.16385.win7_wdk.100208-1538\\inc'", ",", "r'WDK\\inc'", ")", ",", "]", "PullFrom", "(", "from_headers", ",", "extracted", ".", "headers", ",", "target_dir", ")", "# The compiler update to get the SP1 compiler is a bit of a mess. See", "# http://goo.gl/n1DeO. The summary is that update for the standalone compiler", "# binary installs a broken set of headers. So, add an empty ammintrin.h since", "# we don't actually need the contents of it (for Chromium).", "from_sdk7_x86", "=", "[", "(", "r'Program Files\\Microsoft Visual Studio 10.0'", ",", "'.'", ")", ",", "(", "r'Win\\System'", ",", "r'VC\\bin'", ")", ",", "]", "PullFrom", "(", "from_sdk7_x86", ",", "extracted", ".", "vc_x86", ",", "target_dir", ")", "from_sdk7_x64", "=", "[", "(", "r'Program Files(64)\\Microsoft Visual Studio 10.0'", ",", "'.'", ")", ",", "(", "r'Win\\System64'", ",", "r'VC\\bin\\amd64'", ")", ",", "]", "PullFrom", "(", "from_sdk7_x64", ",", "extracted", ".", "vc_x64", ",", "target_dir", ")", "from_vcupdate_x86", "=", "[", "(", "r'Program Files\\Microsoft Visual Studio 10.0'", ",", "'.'", ")", ",", "(", "r'Win\\System'", ",", "r'VC\\bin'", ")", ",", "]", "PullFrom", "(", "from_vcupdate_x86", ",", "extracted", ".", "update_x86", ",", "target_dir", ")", "from_vcupdate_x64", "=", "[", "(", "r'Program Files(64)\\Microsoft Visual Studio 10.0'", ",", "'.'", ")", ",", "(", "r'Win\\System64'", ",", "r'VC\\bin\\amd64'", ")", ",", "]", "PullFrom", "(", "from_vcupdate_x64", ",", "extracted", ".", "update_x64", ",", "target_dir", ")", "sys", ".", "stdout", ".", "write", "(", "'Stubbing ammintrin.h...\\n'", ")", "open", "(", "os", ".", "path", ".", "join", "(", "target_dir", ",", "r'VC\\include\\ammintrin.h'", ")", ",", "'w'", ")", ".", "close", "(", ")", "from_dxsdk", "=", "[", "(", "r'DXSDK\\Include'", ",", "r'DXSDK\\Include'", ")", ",", "(", "r'DXSDK\\Lib'", ",", "r'DXSDK\\Lib'", ")", ",", "(", "r'DXSDK\\Redist'", ",", "r'DXSDK\\Redist'", ")", ",", "]", "PullFrom", "(", "from_dxsdk", ",", "extracted", ".", "dxsdk", ",", "target_dir", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/win/toolchain/toolchain.py#L426-L500
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/html.py
python
HtmlRenderingInfo.__init__
(self, *args, **kwargs)
__init__(self) -> HtmlRenderingInfo
__init__(self) -> HtmlRenderingInfo
[ "__init__", "(", "self", ")", "-", ">", "HtmlRenderingInfo" ]
def __init__(self, *args, **kwargs): """__init__(self) -> HtmlRenderingInfo""" _html.HtmlRenderingInfo_swiginit(self,_html.new_HtmlRenderingInfo(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_html", ".", "HtmlRenderingInfo_swiginit", "(", "self", ",", "_html", ".", "new_HtmlRenderingInfo", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/html.py#L566-L568
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/platform/benchmark.py
python
_global_report_benchmark
( name, iters=None, cpu_time=None, wall_time=None, throughput=None, extras=None, metrics=None)
Method for recording a benchmark directly. Args: name: The BenchmarkEntry name. iters: (optional) How many iterations were run cpu_time: (optional) Total cpu time in seconds wall_time: (optional) Total wall time in seconds throughput: (optional) Throughput (in MB/s) extras: (optional) Dict mapping string keys to additional benchmark info. metrics: (optional) A list of dict representing metrics generated by the benchmark. Each dict should contain keys 'name' and'value'. A dict can optionally contain keys 'min_value' and 'max_value'. Raises: TypeError: if extras is not a dict. IOError: if the benchmark output file already exists.
Method for recording a benchmark directly.
[ "Method", "for", "recording", "a", "benchmark", "directly", "." ]
def _global_report_benchmark( name, iters=None, cpu_time=None, wall_time=None, throughput=None, extras=None, metrics=None): """Method for recording a benchmark directly. Args: name: The BenchmarkEntry name. iters: (optional) How many iterations were run cpu_time: (optional) Total cpu time in seconds wall_time: (optional) Total wall time in seconds throughput: (optional) Throughput (in MB/s) extras: (optional) Dict mapping string keys to additional benchmark info. metrics: (optional) A list of dict representing metrics generated by the benchmark. Each dict should contain keys 'name' and'value'. A dict can optionally contain keys 'min_value' and 'max_value'. Raises: TypeError: if extras is not a dict. IOError: if the benchmark output file already exists. """ logging.info("Benchmark [%s] iters: %d, wall_time: %g, cpu_time: %g," "throughput: %g, extras: %s, metrics: %s", name, iters if iters is not None else -1, wall_time if wall_time is not None else -1, cpu_time if cpu_time is not None else -1, throughput if throughput is not None else -1, str(extras) if extras else "None", str(metrics) if metrics else "None") entries = test_log_pb2.BenchmarkEntries() entry = entries.entry.add() entry.name = name if iters is not None: entry.iters = iters if cpu_time is not None: entry.cpu_time = cpu_time if wall_time is not None: entry.wall_time = wall_time if throughput is not None: entry.throughput = throughput if extras is not None: if not isinstance(extras, dict): raise TypeError("extras must be a dict") for (k, v) in extras.items(): if isinstance(v, numbers.Number): entry.extras[k].double_value = v else: entry.extras[k].string_value = str(v) if metrics is not None: if not isinstance(metrics, list): raise TypeError("metrics must be a list") for metric in metrics: if "name" not in metric: raise TypeError("metric must has a 'name' field") if "value" not in metric: raise TypeError("metric must has a 'value' field") metric_entry = entry.metrics.add() metric_entry.name = metric["name"] metric_entry.value = metric["value"] if "min_value" in metric: metric_entry.min_value.value = metric["min_value"] if "max_value" in metric: metric_entry.max_value.value = metric["max_value"] test_env = os.environ.get(TEST_REPORTER_TEST_ENV, None) if test_env is None: # Reporting was not requested, just print the proto print(str(entries)) return serialized_entry = entries.SerializeToString() mangled_name = name.replace("/", "__") output_path = "%s%s" % (test_env, mangled_name) if gfile.Exists(output_path): raise IOError("File already exists: %s" % output_path) with gfile.GFile(output_path, "wb") as out: out.write(serialized_entry)
[ "def", "_global_report_benchmark", "(", "name", ",", "iters", "=", "None", ",", "cpu_time", "=", "None", ",", "wall_time", "=", "None", ",", "throughput", "=", "None", ",", "extras", "=", "None", ",", "metrics", "=", "None", ")", ":", "logging", ".", "info", "(", "\"Benchmark [%s] iters: %d, wall_time: %g, cpu_time: %g,\"", "\"throughput: %g, extras: %s, metrics: %s\"", ",", "name", ",", "iters", "if", "iters", "is", "not", "None", "else", "-", "1", ",", "wall_time", "if", "wall_time", "is", "not", "None", "else", "-", "1", ",", "cpu_time", "if", "cpu_time", "is", "not", "None", "else", "-", "1", ",", "throughput", "if", "throughput", "is", "not", "None", "else", "-", "1", ",", "str", "(", "extras", ")", "if", "extras", "else", "\"None\"", ",", "str", "(", "metrics", ")", "if", "metrics", "else", "\"None\"", ")", "entries", "=", "test_log_pb2", ".", "BenchmarkEntries", "(", ")", "entry", "=", "entries", ".", "entry", ".", "add", "(", ")", "entry", ".", "name", "=", "name", "if", "iters", "is", "not", "None", ":", "entry", ".", "iters", "=", "iters", "if", "cpu_time", "is", "not", "None", ":", "entry", ".", "cpu_time", "=", "cpu_time", "if", "wall_time", "is", "not", "None", ":", "entry", ".", "wall_time", "=", "wall_time", "if", "throughput", "is", "not", "None", ":", "entry", ".", "throughput", "=", "throughput", "if", "extras", "is", "not", "None", ":", "if", "not", "isinstance", "(", "extras", ",", "dict", ")", ":", "raise", "TypeError", "(", "\"extras must be a dict\"", ")", "for", "(", "k", ",", "v", ")", "in", "extras", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "numbers", ".", "Number", ")", ":", "entry", ".", "extras", "[", "k", "]", ".", "double_value", "=", "v", "else", ":", "entry", ".", "extras", "[", "k", "]", ".", "string_value", "=", "str", "(", "v", ")", "if", "metrics", "is", "not", "None", ":", "if", "not", "isinstance", "(", "metrics", ",", "list", ")", ":", "raise", "TypeError", "(", "\"metrics must be a list\"", ")", "for", "metric", "in", "metrics", ":", "if", "\"name\"", "not", "in", "metric", ":", "raise", "TypeError", "(", "\"metric must has a 'name' field\"", ")", "if", "\"value\"", "not", "in", "metric", ":", "raise", "TypeError", "(", "\"metric must has a 'value' field\"", ")", "metric_entry", "=", "entry", ".", "metrics", ".", "add", "(", ")", "metric_entry", ".", "name", "=", "metric", "[", "\"name\"", "]", "metric_entry", ".", "value", "=", "metric", "[", "\"value\"", "]", "if", "\"min_value\"", "in", "metric", ":", "metric_entry", ".", "min_value", ".", "value", "=", "metric", "[", "\"min_value\"", "]", "if", "\"max_value\"", "in", "metric", ":", "metric_entry", ".", "max_value", ".", "value", "=", "metric", "[", "\"max_value\"", "]", "test_env", "=", "os", ".", "environ", ".", "get", "(", "TEST_REPORTER_TEST_ENV", ",", "None", ")", "if", "test_env", "is", "None", ":", "# Reporting was not requested, just print the proto", "print", "(", "str", "(", "entries", ")", ")", "return", "serialized_entry", "=", "entries", ".", "SerializeToString", "(", ")", "mangled_name", "=", "name", ".", "replace", "(", "\"/\"", ",", "\"__\"", ")", "output_path", "=", "\"%s%s\"", "%", "(", "test_env", ",", "mangled_name", ")", "if", "gfile", ".", "Exists", "(", "output_path", ")", ":", "raise", "IOError", "(", "\"File already exists: %s\"", "%", "output_path", ")", "with", "gfile", ".", "GFile", "(", "output_path", ",", "\"wb\"", ")", "as", "out", ":", "out", ".", "write", "(", "serialized_entry", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/platform/benchmark.py#L54-L132
kushview/Element
1cc16380caa2ab79461246ba758b9de1f46db2a5
waflib/Logs.py
python
init_log
()
Initializes the logger :py:attr:`waflib.Logs.log`
Initializes the logger :py:attr:`waflib.Logs.log`
[ "Initializes", "the", "logger", ":", "py", ":", "attr", ":", "waflib", ".", "Logs", ".", "log" ]
def init_log(): """ Initializes the logger :py:attr:`waflib.Logs.log` """ global log log = logging.getLogger('waflib') log.handlers = [] log.filters = [] hdlr = log_handler() hdlr.setFormatter(formatter()) log.addHandler(hdlr) log.addFilter(log_filter()) log.setLevel(logging.DEBUG)
[ "def", "init_log", "(", ")", ":", "global", "log", "log", "=", "logging", ".", "getLogger", "(", "'waflib'", ")", "log", ".", "handlers", "=", "[", "]", "log", ".", "filters", "=", "[", "]", "hdlr", "=", "log_handler", "(", ")", "hdlr", ".", "setFormatter", "(", "formatter", "(", ")", ")", "log", ".", "addHandler", "(", "hdlr", ")", "log", ".", "addFilter", "(", "log_filter", "(", ")", ")", "log", ".", "setLevel", "(", "logging", ".", "DEBUG", ")" ]
https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/Logs.py#L292-L304
KhronosGroup/Vulkan-Headers
b32da5329b50e3cb96229aaecba9ded032fe29cc
registry/generator.py
python
OutputGenerator.newline
(self)
Print a newline to the output file (utility function)
Print a newline to the output file (utility function)
[ "Print", "a", "newline", "to", "the", "output", "file", "(", "utility", "function", ")" ]
def newline(self): """Print a newline to the output file (utility function)""" write('', file=self.outFile)
[ "def", "newline", "(", "self", ")", ":", "write", "(", "''", ",", "file", "=", "self", ".", "outFile", ")" ]
https://github.com/KhronosGroup/Vulkan-Headers/blob/b32da5329b50e3cb96229aaecba9ded032fe29cc/registry/generator.py#L1220-L1222
hyperledger-archives/iroha
ed579f85126d0e86532a1f4f1f6ce5681bbcd3a9
docs/permissions_compiler/rst.py
python
excerpt
(permission)
return result
Renders source file listing :param permission: name of permission to list, used as a part of filename :return: rst lines
Renders source file listing :param permission: name of permission to list, used as a part of filename :return: rst lines
[ "Renders", "source", "file", "listing", ":", "param", "permission", ":", "name", "of", "permission", "to", "list", "used", "as", "a", "part", "of", "filename", ":", "return", ":", "rst", "lines" ]
def excerpt(permission): """ Renders source file listing :param permission: name of permission to list, used as a part of filename :return: rst lines """ compile_time_path = [os.path.pardir, os.path.pardir, 'example', 'python', 'permissions', '{}.py'.format(permission)] path = os.path.join(*compile_time_path) result = [] if not os.path.isfile(path): print(path) return result window = excerpt_boundaries(path) result.extend(listing(compile_time_path, lines_range=window)) return result
[ "def", "excerpt", "(", "permission", ")", ":", "compile_time_path", "=", "[", "os", ".", "path", ".", "pardir", ",", "os", ".", "path", ".", "pardir", ",", "'example'", ",", "'python'", ",", "'permissions'", ",", "'{}.py'", ".", "format", "(", "permission", ")", "]", "path", "=", "os", ".", "path", ".", "join", "(", "*", "compile_time_path", ")", "result", "=", "[", "]", "if", "not", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "print", "(", "path", ")", "return", "result", "window", "=", "excerpt_boundaries", "(", "path", ")", "result", ".", "extend", "(", "listing", "(", "compile_time_path", ",", "lines_range", "=", "window", ")", ")", "return", "result" ]
https://github.com/hyperledger-archives/iroha/blob/ed579f85126d0e86532a1f4f1f6ce5681bbcd3a9/docs/permissions_compiler/rst.py#L140-L154
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/contrib/learn/python/learn/monitors.py
python
EveryN.every_n_step_begin
(self, step)
return []
Callback before every n'th step begins. Args: step: `int`, the current value of the global step. Returns: A `list` of tensors that will be evaluated at this step.
Callback before every n'th step begins.
[ "Callback", "before", "every", "n", "th", "step", "begins", "." ]
def every_n_step_begin(self, step): # pylint: disable=unused-argument """Callback before every n'th step begins. Args: step: `int`, the current value of the global step. Returns: A `list` of tensors that will be evaluated at this step. """ return []
[ "def", "every_n_step_begin", "(", "self", ",", "step", ")", ":", "# pylint: disable=unused-argument", "return", "[", "]" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/learn/python/learn/monitors.py#L315-L324
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/distributed/fleet/dataset/dataset.py
python
InMemoryDataset.load_into_memory
(self, is_shuffle=False)
:api_attr: Static Graph Load data into memory Args: is_shuffle(bool): whether to use local shuffle, default is False Examples: .. code-block:: python import paddle paddle.enable_static() dataset = paddle.distributed.InMemoryDataset() slots = ["slot1", "slot2", "slot3", "slot4"] slots_vars = [] for slot in slots: var = paddle.static.data( name=slot, shape=[None, 1], dtype="int64", lod_level=1) slots_vars.append(var) dataset.init( batch_size=1, thread_num=2, input_type=1, pipe_command="cat", use_var=slots_vars) filelist = ["a.txt", "b.txt"] dataset.set_filelist(filelist) dataset.load_into_memory()
:api_attr: Static Graph Load data into memory
[ ":", "api_attr", ":", "Static", "Graph", "Load", "data", "into", "memory" ]
def load_into_memory(self, is_shuffle=False): """ :api_attr: Static Graph Load data into memory Args: is_shuffle(bool): whether to use local shuffle, default is False Examples: .. code-block:: python import paddle paddle.enable_static() dataset = paddle.distributed.InMemoryDataset() slots = ["slot1", "slot2", "slot3", "slot4"] slots_vars = [] for slot in slots: var = paddle.static.data( name=slot, shape=[None, 1], dtype="int64", lod_level=1) slots_vars.append(var) dataset.init( batch_size=1, thread_num=2, input_type=1, pipe_command="cat", use_var=slots_vars) filelist = ["a.txt", "b.txt"] dataset.set_filelist(filelist) dataset.load_into_memory() """ self._prepare_to_run() if not self.use_ps_gpu: self.dataset.load_into_memory() elif core._is_compiled_with_heterps(): self.psgpu.set_dataset(self.dataset) self.psgpu.load_into_memory(is_shuffle)
[ "def", "load_into_memory", "(", "self", ",", "is_shuffle", "=", "False", ")", ":", "self", ".", "_prepare_to_run", "(", ")", "if", "not", "self", ".", "use_ps_gpu", ":", "self", ".", "dataset", ".", "load_into_memory", "(", ")", "elif", "core", ".", "_is_compiled_with_heterps", "(", ")", ":", "self", ".", "psgpu", ".", "set_dataset", "(", "self", ".", "dataset", ")", "self", ".", "psgpu", ".", "load_into_memory", "(", "is_shuffle", ")" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/distributed/fleet/dataset/dataset.py#L827-L864
bumptop/BumpTop
466d23597a07ae738f4265262fa01087fc6e257c
trunk/win/Source/bin/jinja2/utils.py
python
LRUCache.keys
(self)
return list(self)
Return a list of all keys ordered by most recent usage.
Return a list of all keys ordered by most recent usage.
[ "Return", "a", "list", "of", "all", "keys", "ordered", "by", "most", "recent", "usage", "." ]
def keys(self): """Return a list of all keys ordered by most recent usage.""" return list(self)
[ "def", "keys", "(", "self", ")", ":", "return", "list", "(", "self", ")" ]
https://github.com/bumptop/BumpTop/blob/466d23597a07ae738f4265262fa01087fc6e257c/trunk/win/Source/bin/jinja2/utils.py#L672-L674
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_gdi.py
python
Locale.GetLanguageInfo
(*args, **kwargs)
return _gdi_.Locale_GetLanguageInfo(*args, **kwargs)
GetLanguageInfo(int lang) -> LanguageInfo
GetLanguageInfo(int lang) -> LanguageInfo
[ "GetLanguageInfo", "(", "int", "lang", ")", "-", ">", "LanguageInfo" ]
def GetLanguageInfo(*args, **kwargs): """GetLanguageInfo(int lang) -> LanguageInfo""" return _gdi_.Locale_GetLanguageInfo(*args, **kwargs)
[ "def", "GetLanguageInfo", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "Locale_GetLanguageInfo", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L3152-L3154
fabianschenk/REVO
eb949c0fdbcdf0be09a38464eb0592a90803947f
thirdparty/Sophus/py/sophus/se3.py
python
Se3.matrix
(self)
return (R.row_join(self.t)).col_join(sympy.Matrix(1, 4, [0, 0, 0, 1]))
returns matrix representation
returns matrix representation
[ "returns", "matrix", "representation" ]
def matrix(self): """ returns matrix representation """ R = self.so3.matrix() return (R.row_join(self.t)).col_join(sympy.Matrix(1, 4, [0, 0, 0, 1]))
[ "def", "matrix", "(", "self", ")", ":", "R", "=", "self", ".", "so3", ".", "matrix", "(", ")", "return", "(", "R", ".", "row_join", "(", "self", ".", "t", ")", ")", ".", "col_join", "(", "sympy", ".", "Matrix", "(", "1", ",", "4", ",", "[", "0", ",", "0", ",", "0", ",", "1", "]", ")", ")" ]
https://github.com/fabianschenk/REVO/blob/eb949c0fdbcdf0be09a38464eb0592a90803947f/thirdparty/Sophus/py/sophus/se3.py#L60-L63
CoolProp/CoolProp
381c8535e5dec3eec27ad430ebbfff8bc9dfc008
wrappers/Python/CoolProp/Plots/Common.py
python
BasePlot._set_axis_limits
(self, limits)
Set the limits of the internal axis object based on SI units, takes [xmin, xmax, ymin, ymax]
Set the limits of the internal axis object based on SI units, takes [xmin, xmax, ymin, ymax]
[ "Set", "the", "limits", "of", "the", "internal", "axis", "object", "based", "on", "SI", "units", "takes", "[", "xmin", "xmax", "ymin", "ymax", "]" ]
def _set_axis_limits(self, limits): """Set the limits of the internal axis object based on SI units, takes [xmin, xmax, ymin, ymax]""" dim = self._system[self._x_index] self.axis.set_xlim([dim.from_SI(limits[0]), dim.from_SI(limits[1])]) dim = self._system[self._y_index] self.axis.set_ylim([dim.from_SI(limits[2]), dim.from_SI(limits[3])])
[ "def", "_set_axis_limits", "(", "self", ",", "limits", ")", ":", "dim", "=", "self", ".", "_system", "[", "self", ".", "_x_index", "]", "self", ".", "axis", ".", "set_xlim", "(", "[", "dim", ".", "from_SI", "(", "limits", "[", "0", "]", ")", ",", "dim", ".", "from_SI", "(", "limits", "[", "1", "]", ")", "]", ")", "dim", "=", "self", ".", "_system", "[", "self", ".", "_y_index", "]", "self", ".", "axis", ".", "set_ylim", "(", "[", "dim", ".", "from_SI", "(", "limits", "[", "2", "]", ")", ",", "dim", ".", "from_SI", "(", "limits", "[", "3", "]", ")", "]", ")" ]
https://github.com/CoolProp/CoolProp/blob/381c8535e5dec3eec27ad430ebbfff8bc9dfc008/wrappers/Python/CoolProp/Plots/Common.py#L939-L945
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/tools/inspector_protocol/jinja2/runtime.py
python
Context.super
(self, name, current)
return BlockReference(name, self, blocks, index)
Render a parent block.
Render a parent block.
[ "Render", "a", "parent", "block", "." ]
def super(self, name, current): """Render a parent block.""" try: blocks = self.blocks[name] index = blocks.index(current) + 1 blocks[index] except LookupError: return self.environment.undefined('there is no parent block ' 'called %r.' % name, name='super') return BlockReference(name, self, blocks, index)
[ "def", "super", "(", "self", ",", "name", ",", "current", ")", ":", "try", ":", "blocks", "=", "self", ".", "blocks", "[", "name", "]", "index", "=", "blocks", ".", "index", "(", "current", ")", "+", "1", "blocks", "[", "index", "]", "except", "LookupError", ":", "return", "self", ".", "environment", ".", "undefined", "(", "'there is no parent block '", "'called %r.'", "%", "name", ",", "name", "=", "'super'", ")", "return", "BlockReference", "(", "name", ",", "self", ",", "blocks", ",", "index", ")" ]
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/inspector_protocol/jinja2/runtime.py#L175-L185
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/asyncio/base_events.py
python
BaseEventLoop.set_exception_handler
(self, handler)
Set handler as the new event loop exception handler. If handler is None, the default exception handler will be set. If handler is a callable object, it should have a signature matching '(loop, context)', where 'loop' will be a reference to the active event loop, 'context' will be a dict object (see `call_exception_handler()` documentation for details about context).
Set handler as the new event loop exception handler.
[ "Set", "handler", "as", "the", "new", "event", "loop", "exception", "handler", "." ]
def set_exception_handler(self, handler): """Set handler as the new event loop exception handler. If handler is None, the default exception handler will be set. If handler is a callable object, it should have a signature matching '(loop, context)', where 'loop' will be a reference to the active event loop, 'context' will be a dict object (see `call_exception_handler()` documentation for details about context). """ if handler is not None and not callable(handler): raise TypeError(f'A callable object or None is expected, ' f'got {handler!r}') self._exception_handler = handler
[ "def", "set_exception_handler", "(", "self", ",", "handler", ")", ":", "if", "handler", "is", "not", "None", "and", "not", "callable", "(", "handler", ")", ":", "raise", "TypeError", "(", "f'A callable object or None is expected, '", "f'got {handler!r}'", ")", "self", ".", "_exception_handler", "=", "handler" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/asyncio/base_events.py#L1673-L1688
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
PhysicsTools/PythonAnalysis/python/rootplot/root2matplotlib.py
python
replace
(string, replacements)
return string
Modify a string based on a list of patterns and substitutions. replacements should be a list of two-entry tuples, the first entry giving a string to search for and the second entry giving the string with which to replace it. If replacements includes a pattern entry containing 'use_regexp', then all patterns will be treated as regular expressions using re.sub.
Modify a string based on a list of patterns and substitutions.
[ "Modify", "a", "string", "based", "on", "a", "list", "of", "patterns", "and", "substitutions", "." ]
def replace(string, replacements): """ Modify a string based on a list of patterns and substitutions. replacements should be a list of two-entry tuples, the first entry giving a string to search for and the second entry giving the string with which to replace it. If replacements includes a pattern entry containing 'use_regexp', then all patterns will be treated as regular expressions using re.sub. """ if not replacements: return string if 'use_regexp' in [x for x,y in replacements]: for pattern, repl in [x for x in replacements if x[0] != 'use_regexp']: string = re.sub(pattern, repl, string) else: for pattern, repl in replacements: string = string.replace(pattern, repl) if re.match(_all_whitespace_string, string): return "" return string
[ "def", "replace", "(", "string", ",", "replacements", ")", ":", "if", "not", "replacements", ":", "return", "string", "if", "'use_regexp'", "in", "[", "x", "for", "x", ",", "y", "in", "replacements", "]", ":", "for", "pattern", ",", "repl", "in", "[", "x", "for", "x", "in", "replacements", "if", "x", "[", "0", "]", "!=", "'use_regexp'", "]", ":", "string", "=", "re", ".", "sub", "(", "pattern", ",", "repl", ",", "string", ")", "else", ":", "for", "pattern", ",", "repl", "in", "replacements", ":", "string", "=", "string", ".", "replace", "(", "pattern", ",", "repl", ")", "if", "re", ".", "match", "(", "_all_whitespace_string", ",", "string", ")", ":", "return", "\"\"", "return", "string" ]
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/PhysicsTools/PythonAnalysis/python/rootplot/root2matplotlib.py#L444-L465
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py
python
_AppendOrReturn
(append, element)
If |append| is None, simply return |element|. If |append| is not None, then add |element| to it, adding each item in |element| if it's a list or tuple.
If |append| is None, simply return |element|. If |append| is not None, then add |element| to it, adding each item in |element| if it's a list or tuple.
[ "If", "|append|", "is", "None", "simply", "return", "|element|", ".", "If", "|append|", "is", "not", "None", "then", "add", "|element|", "to", "it", "adding", "each", "item", "in", "|element|", "if", "it", "s", "a", "list", "or", "tuple", "." ]
def _AppendOrReturn(append, element): """If |append| is None, simply return |element|. If |append| is not None, then add |element| to it, adding each item in |element| if it's a list or tuple.""" if append is not None and element is not None: if isinstance(element, list) or isinstance(element, tuple): append.extend(element) else: append.append(element) else: return element
[ "def", "_AppendOrReturn", "(", "append", ",", "element", ")", ":", "if", "append", "is", "not", "None", "and", "element", "is", "not", "None", ":", "if", "isinstance", "(", "element", ",", "list", ")", "or", "isinstance", "(", "element", ",", "tuple", ")", ":", "append", ".", "extend", "(", "element", ")", "else", ":", "append", ".", "append", "(", "element", ")", "else", ":", "return", "element" ]
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py#L103-L113
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/grid.py
python
GridRangeSelectEvent.GetBottomRightCoords
(*args, **kwargs)
return _grid.GridRangeSelectEvent_GetBottomRightCoords(*args, **kwargs)
GetBottomRightCoords(self) -> GridCellCoords
GetBottomRightCoords(self) -> GridCellCoords
[ "GetBottomRightCoords", "(", "self", ")", "-", ">", "GridCellCoords" ]
def GetBottomRightCoords(*args, **kwargs): """GetBottomRightCoords(self) -> GridCellCoords""" return _grid.GridRangeSelectEvent_GetBottomRightCoords(*args, **kwargs)
[ "def", "GetBottomRightCoords", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "GridRangeSelectEvent_GetBottomRightCoords", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/grid.py#L2405-L2407
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py2/pkg_resources/_vendor/pyparsing.py
python
matchOnlyAtCol
(n)
return verifyCol
Helper method for defining parse actions that require matching at a specific column in the input text.
Helper method for defining parse actions that require matching at a specific column in the input text.
[ "Helper", "method", "for", "defining", "parse", "actions", "that", "require", "matching", "at", "a", "specific", "column", "in", "the", "input", "text", "." ]
def matchOnlyAtCol(n): """ Helper method for defining parse actions that require matching at a specific column in the input text. """ def verifyCol(strg,locn,toks): if col(locn,strg) != n: raise ParseException(strg,locn,"matched token not at column %d" % n) return verifyCol
[ "def", "matchOnlyAtCol", "(", "n", ")", ":", "def", "verifyCol", "(", "strg", ",", "locn", ",", "toks", ")", ":", "if", "col", "(", "locn", ",", "strg", ")", "!=", "n", ":", "raise", "ParseException", "(", "strg", ",", "locn", ",", "\"matched token not at column %d\"", "%", "n", ")", "return", "verifyCol" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/pkg_resources/_vendor/pyparsing.py#L4787-L4795
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/xml/sax/__init__.py
python
make_parser
(parser_list = [])
Creates and returns a SAX parser. Creates the first parser it is able to instantiate of the ones given in the list created by doing parser_list + default_parser_list. The lists must contain the names of Python modules containing both a SAX parser and a create_parser function.
Creates and returns a SAX parser.
[ "Creates", "and", "returns", "a", "SAX", "parser", "." ]
def make_parser(parser_list = []): """Creates and returns a SAX parser. Creates the first parser it is able to instantiate of the ones given in the list created by doing parser_list + default_parser_list. The lists must contain the names of Python modules containing both a SAX parser and a create_parser function.""" for parser_name in parser_list + default_parser_list: try: return _create_parser(parser_name) except ImportError,e: import sys if parser_name in sys.modules: # The parser module was found, but importing it # failed unexpectedly, pass this exception through raise except SAXReaderNotAvailable: # The parser module detected that it won't work properly, # so try the next one pass raise SAXReaderNotAvailable("No parsers found", None)
[ "def", "make_parser", "(", "parser_list", "=", "[", "]", ")", ":", "for", "parser_name", "in", "parser_list", "+", "default_parser_list", ":", "try", ":", "return", "_create_parser", "(", "parser_name", ")", "except", "ImportError", ",", "e", ":", "import", "sys", "if", "parser_name", "in", "sys", ".", "modules", ":", "# The parser module was found, but importing it", "# failed unexpectedly, pass this exception through", "raise", "except", "SAXReaderNotAvailable", ":", "# The parser module detected that it won't work properly,", "# so try the next one", "pass", "raise", "SAXReaderNotAvailable", "(", "\"No parsers found\"", ",", "None", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/xml/sax/__init__.py#L71-L93
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_pytorch/pytorch_binding/pytorch_nndct/utils/logging.py
python
get_logger
()
Return logger instance.
Return logger instance.
[ "Return", "logger", "instance", "." ]
def get_logger(): """Return logger instance.""" global _logger # Use double-checked locking to avoid taking lock unnecessarily. if _logger: return _logger _logger_lock.acquire() try: if _logger: return _logger # Scope the TensorFlow logger to not conflict with users' loggers. logger = _logging.getLogger('nndct') logger.setLevel(1) # Override findCaller on the logger to skip internal helper functions logger.findCaller = _logger_find_caller # Don't further configure the TensorFlow logger if the root logger is # already configured. This prevents double logging in those cases. if not _logging.getLogger().handlers: # Determine whether we are in an interactive environment _interactive = False try: # This is only defined in interactive shells. if _sys.ps1: _interactive = True except AttributeError: # Even now, we may be in an interactive shell with `python -i`. _interactive = _sys.flags.interactive # If we are in an interactive environment (like Jupyter), set loglevel # to INFO and pipe the output to stdout. if _interactive: #logger.setLevel(INFO) _logging_target = _sys.stdout else: _logging_target = _sys.stderr # Add the output handler. _handler = _logging.StreamHandler(_logging_target) _handler.setFormatter(_logging.Formatter(_logging_fmt, None)) logger.addHandler(_handler) _logger = logger return _logger finally: _logger_lock.release()
[ "def", "get_logger", "(", ")", ":", "global", "_logger", "# Use double-checked locking to avoid taking lock unnecessarily.", "if", "_logger", ":", "return", "_logger", "_logger_lock", ".", "acquire", "(", ")", "try", ":", "if", "_logger", ":", "return", "_logger", "# Scope the TensorFlow logger to not conflict with users' loggers.", "logger", "=", "_logging", ".", "getLogger", "(", "'nndct'", ")", "logger", ".", "setLevel", "(", "1", ")", "# Override findCaller on the logger to skip internal helper functions", "logger", ".", "findCaller", "=", "_logger_find_caller", "# Don't further configure the TensorFlow logger if the root logger is", "# already configured. This prevents double logging in those cases.", "if", "not", "_logging", ".", "getLogger", "(", ")", ".", "handlers", ":", "# Determine whether we are in an interactive environment", "_interactive", "=", "False", "try", ":", "# This is only defined in interactive shells.", "if", "_sys", ".", "ps1", ":", "_interactive", "=", "True", "except", "AttributeError", ":", "# Even now, we may be in an interactive shell with `python -i`.", "_interactive", "=", "_sys", ".", "flags", ".", "interactive", "# If we are in an interactive environment (like Jupyter), set loglevel", "# to INFO and pipe the output to stdout.", "if", "_interactive", ":", "#logger.setLevel(INFO)", "_logging_target", "=", "_sys", ".", "stdout", "else", ":", "_logging_target", "=", "_sys", ".", "stderr", "# Add the output handler.", "_handler", "=", "_logging", ".", "StreamHandler", "(", "_logging_target", ")", "_handler", ".", "setFormatter", "(", "_logging", ".", "Formatter", "(", "_logging_fmt", ",", "None", ")", ")", "logger", ".", "addHandler", "(", "_handler", ")", "_logger", "=", "logger", "return", "_logger", "finally", ":", "_logger_lock", ".", "release", "(", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_pytorch/pytorch_binding/pytorch_nndct/utils/logging.py#L130-L181
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Fem/femtools/femutils.py
python
get_part_to_mesh
(mesh_obj)
gmsh mesh object: the Attribute is Part netgen mesh object: the Attribute is Shape other mesh objects: do not have a Attribute which holds the part to mesh
gmsh mesh object: the Attribute is Part netgen mesh object: the Attribute is Shape other mesh objects: do not have a Attribute which holds the part to mesh
[ "gmsh", "mesh", "object", ":", "the", "Attribute", "is", "Part", "netgen", "mesh", "object", ":", "the", "Attribute", "is", "Shape", "other", "mesh", "objects", ":", "do", "not", "have", "a", "Attribute", "which", "holds", "the", "part", "to", "mesh" ]
def get_part_to_mesh(mesh_obj): """ gmsh mesh object: the Attribute is Part netgen mesh object: the Attribute is Shape other mesh objects: do not have a Attribute which holds the part to mesh """ if is_derived_from(mesh_obj, "Fem::FemMeshGmsh"): return mesh_obj.Part elif is_derived_from(mesh_obj, "Fem::FemMeshShapeNetgenObject"): return mesh_obj.Shape else: return None
[ "def", "get_part_to_mesh", "(", "mesh_obj", ")", ":", "if", "is_derived_from", "(", "mesh_obj", ",", "\"Fem::FemMeshGmsh\"", ")", ":", "return", "mesh_obj", ".", "Part", "elif", "is_derived_from", "(", "mesh_obj", ",", "\"Fem::FemMeshShapeNetgenObject\"", ")", ":", "return", "mesh_obj", ".", "Shape", "else", ":", "return", "None" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Fem/femtools/femutils.py#L246-L257
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/utils/saved_model_export_utils.py
python
BestModelSelector._get_best_eval_result
(self, event_files)
return best_eval_result
Get the best eval result from event files. Args: event_files: Absolute pattern of event files. Returns: The best eval result.
Get the best eval result from event files.
[ "Get", "the", "best", "eval", "result", "from", "event", "files", "." ]
def _get_best_eval_result(self, event_files): """Get the best eval result from event files. Args: event_files: Absolute pattern of event files. Returns: The best eval result. """ if not event_files: return None best_eval_result = None for event_file in gfile.Glob(os.path.join(event_files)): for event in summary_iterator.summary_iterator(event_file): if event.HasField('summary'): event_eval_result = {} for value in event.summary.value: if value.HasField('simple_value'): event_eval_result[value.tag] = value.simple_value if best_eval_result is None or self._compare_fn( best_eval_result, event_eval_result): best_eval_result = event_eval_result return best_eval_result
[ "def", "_get_best_eval_result", "(", "self", ",", "event_files", ")", ":", "if", "not", "event_files", ":", "return", "None", "best_eval_result", "=", "None", "for", "event_file", "in", "gfile", ".", "Glob", "(", "os", ".", "path", ".", "join", "(", "event_files", ")", ")", ":", "for", "event", "in", "summary_iterator", ".", "summary_iterator", "(", "event_file", ")", ":", "if", "event", ".", "HasField", "(", "'summary'", ")", ":", "event_eval_result", "=", "{", "}", "for", "value", "in", "event", ".", "summary", ".", "value", ":", "if", "value", ".", "HasField", "(", "'simple_value'", ")", ":", "event_eval_result", "[", "value", ".", "tag", "]", "=", "value", ".", "simple_value", "if", "best_eval_result", "is", "None", "or", "self", ".", "_compare_fn", "(", "best_eval_result", ",", "event_eval_result", ")", ":", "best_eval_result", "=", "event_eval_result", "return", "best_eval_result" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/utils/saved_model_export_utils.py#L622-L645
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/DirectILLReduction.py
python
DirectILLReduction._convertToDistribution
(self, mainWS)
return mainWS
Convert the workspace into a distribution.
Convert the workspace into a distribution.
[ "Convert", "the", "workspace", "into", "a", "distribution", "." ]
def _convertToDistribution(self, mainWS): """Convert the workspace into a distribution.""" ConvertToDistribution(Workspace=mainWS, EnableLogging=self._subalgLogging) return mainWS
[ "def", "_convertToDistribution", "(", "self", ",", "mainWS", ")", ":", "ConvertToDistribution", "(", "Workspace", "=", "mainWS", ",", "EnableLogging", "=", "self", ".", "_subalgLogging", ")", "return", "mainWS" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/DirectILLReduction.py#L409-L413
google/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
earth_enterprise/src/server/wsgi/serve/snippets/util/sparse_tree.py
python
_SetAbstractThroughRepeated
(parts, value, store, log)
Set value at parts, when the top of store is 'repeated'. Complements _GeneralSetAbstract. It is different from normal setting, in that we set corresponding field in repeated elements (and their descendants). In case we have pre-existing items of repeated element in store, we set corresponding field in all the items. If there are no items of repeated element in store, we add new item with index value of zero and set field in that item. It is the case when corresponding repeated snippet is only present in hard-masked snippets list. Args: parts: list of the elements of the path we're setting. value: value we're setting at the path. store: the multi-level dict representing our protobuf. log: logging obj.
Set value at parts, when the top of store is 'repeated'.
[ "Set", "value", "at", "parts", "when", "the", "top", "of", "store", "is", "repeated", "." ]
def _SetAbstractThroughRepeated(parts, value, store, log): """Set value at parts, when the top of store is 'repeated'. Complements _GeneralSetAbstract. It is different from normal setting, in that we set corresponding field in repeated elements (and their descendants). In case we have pre-existing items of repeated element in store, we set corresponding field in all the items. If there are no items of repeated element in store, we add new item with index value of zero and set field in that item. It is the case when corresponding repeated snippet is only present in hard-masked snippets list. Args: parts: list of the elements of the path we're setting. value: value we're setting at the path. store: the multi-level dict representing our protobuf. log: logging obj. """ assert (parts and parts[0] == "[]"), "expected element of path to be abstract index." assert isinstance(store, dict) if store: # set field in pre-existing items of repeated element. for index in store: assert index.isdigit(), "expected store keys to be indexes." substore = store.get(index, None) if isinstance(substore, dict): _GeneralSetAbstract(parts[1:], value, substore, log) else: # It breaks an invariant of the protobuf => sparse tree, to replace # a primitive value with a subtree. Eg, trying to write # 'a.b' = 2 to {'a': 1}. 'b' cannot be a sibling of 2. That would be # the error we're trying to do here. log.error( "Programmer or data error; cannot write a subtree ([%s]) over" " a primitive value (%s); that\'s an invariant of protobufs =>" " sparse trees. Value ignored, but no further damage done. " "%s" % (str(index), str(store), repr(traceback.extract_stack()))) else: # Corresponding repeated element is only present in hard-masked snippets # list. # Note: hard-masked snippets list may only contain one item of repeated # element. key = "0" # There are no items so we set index value to zero. store[key] = {} substore = store[key] _GeneralSetAbstract(parts[1:], value, substore, log)
[ "def", "_SetAbstractThroughRepeated", "(", "parts", ",", "value", ",", "store", ",", "log", ")", ":", "assert", "(", "parts", "and", "parts", "[", "0", "]", "==", "\"[]\"", ")", ",", "\"expected element of path to be abstract index.\"", "assert", "isinstance", "(", "store", ",", "dict", ")", "if", "store", ":", "# set field in pre-existing items of repeated element.", "for", "index", "in", "store", ":", "assert", "index", ".", "isdigit", "(", ")", ",", "\"expected store keys to be indexes.\"", "substore", "=", "store", ".", "get", "(", "index", ",", "None", ")", "if", "isinstance", "(", "substore", ",", "dict", ")", ":", "_GeneralSetAbstract", "(", "parts", "[", "1", ":", "]", ",", "value", ",", "substore", ",", "log", ")", "else", ":", "# It breaks an invariant of the protobuf => sparse tree, to replace", "# a primitive value with a subtree. Eg, trying to write", "# 'a.b' = 2 to {'a': 1}. 'b' cannot be a sibling of 2. That would be", "# the error we're trying to do here.", "log", ".", "error", "(", "\"Programmer or data error; cannot write a subtree ([%s]) over\"", "\" a primitive value (%s); that\\'s an invariant of protobufs =>\"", "\" sparse trees. Value ignored, but no further damage done. \"", "\"%s\"", "%", "(", "str", "(", "index", ")", ",", "str", "(", "store", ")", ",", "repr", "(", "traceback", ".", "extract_stack", "(", ")", ")", ")", ")", "else", ":", "# Corresponding repeated element is only present in hard-masked snippets", "# list.", "# Note: hard-masked snippets list may only contain one item of repeated", "# element.", "key", "=", "\"0\"", "# There are no items so we set index value to zero.", "store", "[", "key", "]", "=", "{", "}", "substore", "=", "store", "[", "key", "]", "_GeneralSetAbstract", "(", "parts", "[", "1", ":", "]", ",", "value", ",", "substore", ",", "log", ")" ]
https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/server/wsgi/serve/snippets/util/sparse_tree.py#L282-L330
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/external/bazel_tools/tools/build_defs/docker/rewrite_json.py
python
DeepCopySkipNull
(data)
return copy.deepcopy(data)
Do a deep copy, skipping null entry.
Do a deep copy, skipping null entry.
[ "Do", "a", "deep", "copy", "skipping", "null", "entry", "." ]
def DeepCopySkipNull(data): """Do a deep copy, skipping null entry.""" if type(data) == type(dict()): return dict((DeepCopySkipNull(k), DeepCopySkipNull(v)) for k, v in data.iteritems() if v is not None) return copy.deepcopy(data)
[ "def", "DeepCopySkipNull", "(", "data", ")", ":", "if", "type", "(", "data", ")", "==", "type", "(", "dict", "(", ")", ")", ":", "return", "dict", "(", "(", "DeepCopySkipNull", "(", "k", ")", ",", "DeepCopySkipNull", "(", "v", ")", ")", "for", "k", ",", "v", "in", "data", ".", "iteritems", "(", ")", "if", "v", "is", "not", "None", ")", "return", "copy", ".", "deepcopy", "(", "data", ")" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/external/bazel_tools/tools/build_defs/docker/rewrite_json.py#L121-L126
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/llvmlite/binding/executionengine.py
python
ExecutionEngine.get_function_address
(self, name)
return ffi.lib.LLVMPY_GetFunctionAddress(self, name.encode("ascii"))
Return the address of the function named *name* as an integer. It's a fatal error in LLVM if the symbol of *name* doesn't exist.
Return the address of the function named *name* as an integer.
[ "Return", "the", "address", "of", "the", "function", "named", "*", "name", "*", "as", "an", "integer", "." ]
def get_function_address(self, name): """ Return the address of the function named *name* as an integer. It's a fatal error in LLVM if the symbol of *name* doesn't exist. """ return ffi.lib.LLVMPY_GetFunctionAddress(self, name.encode("ascii"))
[ "def", "get_function_address", "(", "self", ",", "name", ")", ":", "return", "ffi", ".", "lib", ".", "LLVMPY_GetFunctionAddress", "(", "self", ",", "name", ".", "encode", "(", "\"ascii\"", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/llvmlite/binding/executionengine.py#L60-L66
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/requests/cookies.py
python
get_cookie_header
(jar, request)
return r.get_new_headers().get('Cookie')
Produce an appropriate Cookie header string to be sent with `request`, or None. :rtype: str
Produce an appropriate Cookie header string to be sent with `request`, or None.
[ "Produce", "an", "appropriate", "Cookie", "header", "string", "to", "be", "sent", "with", "request", "or", "None", "." ]
def get_cookie_header(jar, request): """ Produce an appropriate Cookie header string to be sent with `request`, or None. :rtype: str """ r = MockRequest(request) jar.add_cookie_header(r) return r.get_new_headers().get('Cookie')
[ "def", "get_cookie_header", "(", "jar", ",", "request", ")", ":", "r", "=", "MockRequest", "(", "request", ")", "jar", ".", "add_cookie_header", "(", "r", ")", "return", "r", ".", "get_new_headers", "(", ")", ".", "get", "(", "'Cookie'", ")" ]
https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/requests/cookies.py#L135-L143
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/PSDraw.py
python
PSDraw.end_document
(self)
Ends printing. (Write Postscript DSC footer.)
Ends printing. (Write Postscript DSC footer.)
[ "Ends", "printing", ".", "(", "Write", "Postscript", "DSC", "footer", ".", ")" ]
def end_document(self): """Ends printing. (Write Postscript DSC footer.)""" self._fp_write("%%EndDocument\nrestore showpage\n%%End\n") if hasattr(self.fp, "flush"): self.fp.flush()
[ "def", "end_document", "(", "self", ")", ":", "self", ".", "_fp_write", "(", "\"%%EndDocument\\nrestore showpage\\n%%End\\n\"", ")", "if", "hasattr", "(", "self", ".", "fp", ",", "\"flush\"", ")", ":", "self", ".", "fp", ".", "flush", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/PSDraw.py#L59-L63
OpenGenus/cosmos
1a94e8880068e51d571543be179c323936bd0936
code/languages/python/web_programming/world_covid19_stats.py
python
world_covid19_stats
(url: str = "https://www.worldometers.info/coronavirus")
return {key.text.strip(): value.text.strip() for key, value in zip(keys, values)}
Return a dict of current worldwide COVID-19 statistics
Return a dict of current worldwide COVID-19 statistics
[ "Return", "a", "dict", "of", "current", "worldwide", "COVID", "-", "19", "statistics" ]
def world_covid19_stats(url: str = "https://www.worldometers.info/coronavirus") -> dict: """ Return a dict of current worldwide COVID-19 statistics """ soup = BeautifulSoup(requests.get(url).text, "html.parser") keys = soup.findAll("h1") values = soup.findAll("div", {"class": "maincounter-number"}) keys += soup.findAll("span", {"class": "panel-title"}) values += soup.findAll("div", {"class": "number-table-main"}) return {key.text.strip(): value.text.strip() for key, value in zip(keys, values)}
[ "def", "world_covid19_stats", "(", "url", ":", "str", "=", "\"https://www.worldometers.info/coronavirus\"", ")", "->", "dict", ":", "soup", "=", "BeautifulSoup", "(", "requests", ".", "get", "(", "url", ")", ".", "text", ",", "\"html.parser\"", ")", "keys", "=", "soup", ".", "findAll", "(", "\"h1\"", ")", "values", "=", "soup", ".", "findAll", "(", "\"div\"", ",", "{", "\"class\"", ":", "\"maincounter-number\"", "}", ")", "keys", "+=", "soup", ".", "findAll", "(", "\"span\"", ",", "{", "\"class\"", ":", "\"panel-title\"", "}", ")", "values", "+=", "soup", ".", "findAll", "(", "\"div\"", ",", "{", "\"class\"", ":", "\"number-table-main\"", "}", ")", "return", "{", "key", ".", "text", ".", "strip", "(", ")", ":", "value", ".", "text", ".", "strip", "(", ")", "for", "key", ",", "value", "in", "zip", "(", "keys", ",", "values", ")", "}" ]
https://github.com/OpenGenus/cosmos/blob/1a94e8880068e51d571543be179c323936bd0936/code/languages/python/web_programming/world_covid19_stats.py#L12-L21
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
gpu/command_buffer/build_gles2_cmd_buffer.py
python
Function.WriteServiceUnitTest
(self, file)
Writes the service implementation for a command.
Writes the service implementation for a command.
[ "Writes", "the", "service", "implementation", "for", "a", "command", "." ]
def WriteServiceUnitTest(self, file): """Writes the service implementation for a command.""" self.type_handler.WriteServiceUnitTest(self, file)
[ "def", "WriteServiceUnitTest", "(", "self", ",", "file", ")", ":", "self", ".", "type_handler", ".", "WriteServiceUnitTest", "(", "self", ",", "file", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/gpu/command_buffer/build_gles2_cmd_buffer.py#L6585-L6587
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/decomposition/nmf.py
python
NMF.fit_transform
(self, X, y=None, W=None, H=None)
return W
Learn a NMF model for the data X and returns the transformed data. This is more efficient than calling fit followed by transform. Parameters ---------- X: {array-like, sparse matrix}, shape (n_samples, n_features) Data matrix to be decomposed W : array-like, shape (n_samples, n_components) If init='custom', it is used as initial guess for the solution. H : array-like, shape (n_components, n_features) If init='custom', it is used as initial guess for the solution. Returns ------- W: array, shape (n_samples, n_components) Transformed data.
Learn a NMF model for the data X and returns the transformed data.
[ "Learn", "a", "NMF", "model", "for", "the", "data", "X", "and", "returns", "the", "transformed", "data", "." ]
def fit_transform(self, X, y=None, W=None, H=None): """Learn a NMF model for the data X and returns the transformed data. This is more efficient than calling fit followed by transform. Parameters ---------- X: {array-like, sparse matrix}, shape (n_samples, n_features) Data matrix to be decomposed W : array-like, shape (n_samples, n_components) If init='custom', it is used as initial guess for the solution. H : array-like, shape (n_components, n_features) If init='custom', it is used as initial guess for the solution. Returns ------- W: array, shape (n_samples, n_components) Transformed data. """ X = check_array(X, accept_sparse=('csr', 'csc')) W, H, n_iter_ = non_negative_factorization( X=X, W=W, H=H, n_components=self.n_components, init=self.init, update_H=True, solver=self.solver, tol=self.tol, max_iter=self.max_iter, alpha=self.alpha, l1_ratio=self.l1_ratio, regularization='both', random_state=self.random_state, verbose=self.verbose, shuffle=self.shuffle, nls_max_iter=self.nls_max_iter, sparseness=self.sparseness, beta=self.beta, eta=self.eta) if self.solver == 'pg': self.comp_sparseness_ = _sparseness(H.ravel()) self.data_sparseness_ = _sparseness(W.ravel()) self.reconstruction_err_ = _safe_compute_error(X, W, H) self.n_components_ = H.shape[0] self.components_ = H self.n_iter_ = n_iter_ return W
[ "def", "fit_transform", "(", "self", ",", "X", ",", "y", "=", "None", ",", "W", "=", "None", ",", "H", "=", "None", ")", ":", "X", "=", "check_array", "(", "X", ",", "accept_sparse", "=", "(", "'csr'", ",", "'csc'", ")", ")", "W", ",", "H", ",", "n_iter_", "=", "non_negative_factorization", "(", "X", "=", "X", ",", "W", "=", "W", ",", "H", "=", "H", ",", "n_components", "=", "self", ".", "n_components", ",", "init", "=", "self", ".", "init", ",", "update_H", "=", "True", ",", "solver", "=", "self", ".", "solver", ",", "tol", "=", "self", ".", "tol", ",", "max_iter", "=", "self", ".", "max_iter", ",", "alpha", "=", "self", ".", "alpha", ",", "l1_ratio", "=", "self", ".", "l1_ratio", ",", "regularization", "=", "'both'", ",", "random_state", "=", "self", ".", "random_state", ",", "verbose", "=", "self", ".", "verbose", ",", "shuffle", "=", "self", ".", "shuffle", ",", "nls_max_iter", "=", "self", ".", "nls_max_iter", ",", "sparseness", "=", "self", ".", "sparseness", ",", "beta", "=", "self", ".", "beta", ",", "eta", "=", "self", ".", "eta", ")", "if", "self", ".", "solver", "==", "'pg'", ":", "self", ".", "comp_sparseness_", "=", "_sparseness", "(", "H", ".", "ravel", "(", ")", ")", "self", ".", "data_sparseness_", "=", "_sparseness", "(", "W", ".", "ravel", "(", ")", ")", "self", ".", "reconstruction_err_", "=", "_safe_compute_error", "(", "X", ",", "W", ",", "H", ")", "self", ".", "n_components_", "=", "H", ".", "shape", "[", "0", "]", "self", ".", "components_", "=", "H", "self", ".", "n_iter_", "=", "n_iter_", "return", "W" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/decomposition/nmf.py#L1003-L1046
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/ops/control_flow_ops.py
python
ZerosLikeOutsideLoop
(op, index)
Create zeros_like for the specified output of an op.
Create zeros_like for the specified output of an op.
[ "Create", "zeros_like", "for", "the", "specified", "output", "of", "an", "op", "." ]
def ZerosLikeOutsideLoop(op, index): """Create zeros_like for the specified output of an op.""" val = op.outputs[index] if not IsSwitch(op): return array_ops.zeros_like(val) else: op_ctxt = op._get_control_flow_context() pred = op_ctxt.pred branch = op_ctxt.branch switch_val = switch(op.inputs[0], pred)[1 - branch] zeros_shape = array_ops.shape(switch_val) return array_ops.zeros(zeros_shape, dtype=val.dtype)
[ "def", "ZerosLikeOutsideLoop", "(", "op", ",", "index", ")", ":", "val", "=", "op", ".", "outputs", "[", "index", "]", "if", "not", "IsSwitch", "(", "op", ")", ":", "return", "array_ops", ".", "zeros_like", "(", "val", ")", "else", ":", "op_ctxt", "=", "op", ".", "_get_control_flow_context", "(", ")", "pred", "=", "op_ctxt", ".", "pred", "branch", "=", "op_ctxt", ".", "branch", "switch_val", "=", "switch", "(", "op", ".", "inputs", "[", "0", "]", ",", "pred", ")", "[", "1", "-", "branch", "]", "zeros_shape", "=", "array_ops", ".", "shape", "(", "switch_val", ")", "return", "array_ops", ".", "zeros", "(", "zeros_shape", ",", "dtype", "=", "val", ".", "dtype", ")" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/control_flow_ops.py#L1053-L1064
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/SConf.py
python
Streamer.getvalue
(self)
return self.s.getvalue()
Return everything written to orig since the Streamer was created.
Return everything written to orig since the Streamer was created.
[ "Return", "everything", "written", "to", "orig", "since", "the", "Streamer", "was", "created", "." ]
def getvalue(self): """ Return everything written to orig since the Streamer was created. """ return self.s.getvalue()
[ "def", "getvalue", "(", "self", ")", ":", "return", "self", ".", "s", ".", "getvalue", "(", ")" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/SConf.py#L215-L219
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/keras/_impl/keras/applications/mobilenet.py
python
_conv_block
(inputs, filters, alpha, kernel=(3, 3), strides=(1, 1))
return Activation(relu6, name='conv1_relu')(x)
Adds an initial convolution layer (with batch normalization and relu6). Arguments: inputs: Input tensor of shape `(rows, cols, 3)` (with `channels_last` data format) or (3, rows, cols) (with `channels_first` data format). It should have exactly 3 inputs channels, and width and height should be no smaller than 32. E.g. `(224, 224, 3)` would be one valid value. filters: Integer, the dimensionality of the output space (i.e. the number output of filters in the convolution). alpha: controls the width of the network. - If `alpha` < 1.0, proportionally decreases the number of filters in each layer. - If `alpha` > 1.0, proportionally increases the number of filters in each layer. - If `alpha` = 1, default number of filters from the paper are used at each layer. kernel: An integer or tuple/list of 2 integers, specifying the width and height of the 2D convolution window. Can be a single integer to specify the same value for all spatial dimensions. strides: An integer or tuple/list of 2 integers, specifying the strides of the convolution along the width and height. Can be a single integer to specify the same value for all spatial dimensions. Specifying any stride value != 1 is incompatible with specifying any `dilation_rate` value != 1. Input shape: 4D tensor with shape: `(samples, channels, rows, cols)` if data_format='channels_first' or 4D tensor with shape: `(samples, rows, cols, channels)` if data_format='channels_last'. Output shape: 4D tensor with shape: `(samples, filters, new_rows, new_cols)` if data_format='channels_first' or 4D tensor with shape: `(samples, new_rows, new_cols, filters)` if data_format='channels_last'. `rows` and `cols` values might have changed due to stride. Returns: Output tensor of block.
Adds an initial convolution layer (with batch normalization and relu6).
[ "Adds", "an", "initial", "convolution", "layer", "(", "with", "batch", "normalization", "and", "relu6", ")", "." ]
def _conv_block(inputs, filters, alpha, kernel=(3, 3), strides=(1, 1)): """Adds an initial convolution layer (with batch normalization and relu6). Arguments: inputs: Input tensor of shape `(rows, cols, 3)` (with `channels_last` data format) or (3, rows, cols) (with `channels_first` data format). It should have exactly 3 inputs channels, and width and height should be no smaller than 32. E.g. `(224, 224, 3)` would be one valid value. filters: Integer, the dimensionality of the output space (i.e. the number output of filters in the convolution). alpha: controls the width of the network. - If `alpha` < 1.0, proportionally decreases the number of filters in each layer. - If `alpha` > 1.0, proportionally increases the number of filters in each layer. - If `alpha` = 1, default number of filters from the paper are used at each layer. kernel: An integer or tuple/list of 2 integers, specifying the width and height of the 2D convolution window. Can be a single integer to specify the same value for all spatial dimensions. strides: An integer or tuple/list of 2 integers, specifying the strides of the convolution along the width and height. Can be a single integer to specify the same value for all spatial dimensions. Specifying any stride value != 1 is incompatible with specifying any `dilation_rate` value != 1. Input shape: 4D tensor with shape: `(samples, channels, rows, cols)` if data_format='channels_first' or 4D tensor with shape: `(samples, rows, cols, channels)` if data_format='channels_last'. Output shape: 4D tensor with shape: `(samples, filters, new_rows, new_cols)` if data_format='channels_first' or 4D tensor with shape: `(samples, new_rows, new_cols, filters)` if data_format='channels_last'. `rows` and `cols` values might have changed due to stride. Returns: Output tensor of block. """ channel_axis = 1 if K.image_data_format() == 'channels_first' else -1 filters = int(filters * alpha) x = Conv2D( filters, kernel, padding='same', use_bias=False, strides=strides, name='conv1')(inputs) x = BatchNormalization(axis=channel_axis, name='conv1_bn')(x) return Activation(relu6, name='conv1_relu')(x)
[ "def", "_conv_block", "(", "inputs", ",", "filters", ",", "alpha", ",", "kernel", "=", "(", "3", ",", "3", ")", ",", "strides", "=", "(", "1", ",", "1", ")", ")", ":", "channel_axis", "=", "1", "if", "K", ".", "image_data_format", "(", ")", "==", "'channels_first'", "else", "-", "1", "filters", "=", "int", "(", "filters", "*", "alpha", ")", "x", "=", "Conv2D", "(", "filters", ",", "kernel", ",", "padding", "=", "'same'", ",", "use_bias", "=", "False", ",", "strides", "=", "strides", ",", "name", "=", "'conv1'", ")", "(", "inputs", ")", "x", "=", "BatchNormalization", "(", "axis", "=", "channel_axis", ",", "name", "=", "'conv1_bn'", ")", "(", "x", ")", "return", "Activation", "(", "relu6", ",", "name", "=", "'conv1_relu'", ")", "(", "x", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/keras/_impl/keras/applications/mobilenet.py#L537-L593
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/python/bitstring/bitstring.py
python
Bits._readfloatle
(self, length, start)
Read bits and interpret as a little-endian float.
Read bits and interpret as a little-endian float.
[ "Read", "bits", "and", "interpret", "as", "a", "little", "-", "endian", "float", "." ]
def _readfloatle(self, length, start): """Read bits and interpret as a little-endian float.""" startbyte, offset = divmod(start + self._offset, 8) if not offset: if length == 32: f, = struct.unpack('<f', bytes(self._datastore.getbyteslice(startbyte, startbyte + 4))) elif length == 64: f, = struct.unpack('<d', bytes(self._datastore.getbyteslice(startbyte, startbyte + 8))) else: if length == 32: f, = struct.unpack('<f', self._readbytes(32, start)) elif length == 64: f, = struct.unpack('<d', self._readbytes(64, start)) try: return f except NameError: raise InterpretError("floats can only be 32 or 64 bits long, " "not {0} bits", length)
[ "def", "_readfloatle", "(", "self", ",", "length", ",", "start", ")", ":", "startbyte", ",", "offset", "=", "divmod", "(", "start", "+", "self", ".", "_offset", ",", "8", ")", "if", "not", "offset", ":", "if", "length", "==", "32", ":", "f", ",", "=", "struct", ".", "unpack", "(", "'<f'", ",", "bytes", "(", "self", ".", "_datastore", ".", "getbyteslice", "(", "startbyte", ",", "startbyte", "+", "4", ")", ")", ")", "elif", "length", "==", "64", ":", "f", ",", "=", "struct", ".", "unpack", "(", "'<d'", ",", "bytes", "(", "self", ".", "_datastore", ".", "getbyteslice", "(", "startbyte", ",", "startbyte", "+", "8", ")", ")", ")", "else", ":", "if", "length", "==", "32", ":", "f", ",", "=", "struct", ".", "unpack", "(", "'<f'", ",", "self", ".", "_readbytes", "(", "32", ",", "start", ")", ")", "elif", "length", "==", "64", ":", "f", ",", "=", "struct", ".", "unpack", "(", "'<d'", ",", "self", ".", "_readbytes", "(", "64", ",", "start", ")", ")", "try", ":", "return", "f", "except", "NameError", ":", "raise", "InterpretError", "(", "\"floats can only be 32 or 64 bits long, \"", "\"not {0} bits\"", ",", "length", ")" ]
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/bitstring/bitstring.py#L1591-L1608
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/google_appengine_cloudstorage/cloudstorage/cloudstorage_api.py
python
open
(filename, mode='r', content_type=None, options=None, read_buffer_size=storage_api.ReadBuffer.DEFAULT_BUFFER_SIZE, retry_params=None, _account_id=None)
Opens a Google Cloud Storage file and returns it as a File-like object. Args: filename: A Google Cloud Storage filename of form '/bucket/filename'. mode: 'r' for reading mode. 'w' for writing mode. In reading mode, the file must exist. In writing mode, a file will be created or be overrode. content_type: The MIME type of the file. str. Only valid in writing mode. options: A str->basestring dict to specify additional headers to pass to GCS e.g. {'x-goog-acl': 'private', 'x-goog-meta-foo': 'foo'}. Supported options are x-goog-acl, x-goog-meta-, cache-control, content-disposition, and content-encoding. Only valid in writing mode. See https://developers.google.com/storage/docs/reference-headers for details. read_buffer_size: The buffer size for read. Read keeps a buffer and prefetches another one. To minimize blocking for large files, always read by buffer size. To minimize number of RPC requests for small files, set a large buffer size. Max is 30MB. retry_params: An instance of api_utils.RetryParams for subsequent calls to GCS from this file handle. If None, the default one is used. _account_id: Internal-use only. Returns: A reading or writing buffer that supports File-like interface. Buffer must be closed after operations are done. Raises: errors.AuthorizationError: if authorization failed. errors.NotFoundError: if an object that's expected to exist doesn't. ValueError: invalid open mode or if content_type or options are specified in reading mode.
Opens a Google Cloud Storage file and returns it as a File-like object.
[ "Opens", "a", "Google", "Cloud", "Storage", "file", "and", "returns", "it", "as", "a", "File", "-", "like", "object", "." ]
def open(filename, mode='r', content_type=None, options=None, read_buffer_size=storage_api.ReadBuffer.DEFAULT_BUFFER_SIZE, retry_params=None, _account_id=None): """Opens a Google Cloud Storage file and returns it as a File-like object. Args: filename: A Google Cloud Storage filename of form '/bucket/filename'. mode: 'r' for reading mode. 'w' for writing mode. In reading mode, the file must exist. In writing mode, a file will be created or be overrode. content_type: The MIME type of the file. str. Only valid in writing mode. options: A str->basestring dict to specify additional headers to pass to GCS e.g. {'x-goog-acl': 'private', 'x-goog-meta-foo': 'foo'}. Supported options are x-goog-acl, x-goog-meta-, cache-control, content-disposition, and content-encoding. Only valid in writing mode. See https://developers.google.com/storage/docs/reference-headers for details. read_buffer_size: The buffer size for read. Read keeps a buffer and prefetches another one. To minimize blocking for large files, always read by buffer size. To minimize number of RPC requests for small files, set a large buffer size. Max is 30MB. retry_params: An instance of api_utils.RetryParams for subsequent calls to GCS from this file handle. If None, the default one is used. _account_id: Internal-use only. Returns: A reading or writing buffer that supports File-like interface. Buffer must be closed after operations are done. Raises: errors.AuthorizationError: if authorization failed. errors.NotFoundError: if an object that's expected to exist doesn't. ValueError: invalid open mode or if content_type or options are specified in reading mode. """ common.validate_file_path(filename) api = storage_api._get_storage_api(retry_params=retry_params, account_id=_account_id) filename = api_utils._quote_filename(filename) if mode == 'w': common.validate_options(options) return storage_api.StreamingBuffer(api, filename, content_type, options) elif mode == 'r': if content_type or options: raise ValueError('Options and content_type can only be specified ' 'for writing mode.') return storage_api.ReadBuffer(api, filename, buffer_size=read_buffer_size) else: raise ValueError('Invalid mode %s.' % mode)
[ "def", "open", "(", "filename", ",", "mode", "=", "'r'", ",", "content_type", "=", "None", ",", "options", "=", "None", ",", "read_buffer_size", "=", "storage_api", ".", "ReadBuffer", ".", "DEFAULT_BUFFER_SIZE", ",", "retry_params", "=", "None", ",", "_account_id", "=", "None", ")", ":", "common", ".", "validate_file_path", "(", "filename", ")", "api", "=", "storage_api", ".", "_get_storage_api", "(", "retry_params", "=", "retry_params", ",", "account_id", "=", "_account_id", ")", "filename", "=", "api_utils", ".", "_quote_filename", "(", "filename", ")", "if", "mode", "==", "'w'", ":", "common", ".", "validate_options", "(", "options", ")", "return", "storage_api", ".", "StreamingBuffer", "(", "api", ",", "filename", ",", "content_type", ",", "options", ")", "elif", "mode", "==", "'r'", ":", "if", "content_type", "or", "options", ":", "raise", "ValueError", "(", "'Options and content_type can only be specified '", "'for writing mode.'", ")", "return", "storage_api", ".", "ReadBuffer", "(", "api", ",", "filename", ",", "buffer_size", "=", "read_buffer_size", ")", "else", ":", "raise", "ValueError", "(", "'Invalid mode %s.'", "%", "mode", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/google_appengine_cloudstorage/cloudstorage/cloudstorage_api.py#L40-L96
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/ttk.py
python
Treeview.set_children
(self, item, *newchildren)
Replaces item's child with newchildren. Children present in item that are not present in newchildren are detached from tree. No items in newchildren may be an ancestor of item.
Replaces item's child with newchildren.
[ "Replaces", "item", "s", "child", "with", "newchildren", "." ]
def set_children(self, item, *newchildren): """Replaces item's child with newchildren. Children present in item that are not present in newchildren are detached from tree. No items in newchildren may be an ancestor of item.""" self.tk.call(self._w, "children", item, newchildren)
[ "def", "set_children", "(", "self", ",", "item", ",", "*", "newchildren", ")", ":", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "\"children\"", ",", "item", ",", "newchildren", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/ttk.py#L1194-L1200
nasa/astrobee
9241e67e6692810d6e275abb3165b6d02f4ca5ef
scripts/git/cpplint.py
python
FindNextMultiLineCommentEnd
(lines, lineix)
return len(lines)
We are inside a comment, find the end marker.
We are inside a comment, find the end marker.
[ "We", "are", "inside", "a", "comment", "find", "the", "end", "marker", "." ]
def FindNextMultiLineCommentEnd(lines, lineix): """We are inside a comment, find the end marker.""" while lineix < len(lines): if lines[lineix].strip().endswith("*/"): return lineix lineix += 1 return len(lines)
[ "def", "FindNextMultiLineCommentEnd", "(", "lines", ",", "lineix", ")", ":", "while", "lineix", "<", "len", "(", "lines", ")", ":", "if", "lines", "[", "lineix", "]", ".", "strip", "(", ")", ".", "endswith", "(", "\"*/\"", ")", ":", "return", "lineix", "lineix", "+=", "1", "return", "len", "(", "lines", ")" ]
https://github.com/nasa/astrobee/blob/9241e67e6692810d6e275abb3165b6d02f4ca5ef/scripts/git/cpplint.py#L1304-L1310
bulletphysics/bullet3
f0f2a952e146f016096db6f85cf0c44ed75b0b9a
examples/pybullet/gym/pybullet_envs/agents/networks.py
python
feed_forward_gaussian
(config, action_size, observations, unused_length, state=None)
return NetworkOutput(policy, mean, logstd, value, state)
Independent feed forward networks for policy and value. The policy network outputs the mean action and the log standard deviation is learned as independent parameter vector. Args: config: Configuration object. action_size: Length of the action vector. observations: Sequences of observations. unused_length: Batch of sequence lengths. state: Batch of initial recurrent states. Returns: NetworkOutput tuple.
Independent feed forward networks for policy and value.
[ "Independent", "feed", "forward", "networks", "for", "policy", "and", "value", "." ]
def feed_forward_gaussian(config, action_size, observations, unused_length, state=None): """Independent feed forward networks for policy and value. The policy network outputs the mean action and the log standard deviation is learned as independent parameter vector. Args: config: Configuration object. action_size: Length of the action vector. observations: Sequences of observations. unused_length: Batch of sequence lengths. state: Batch of initial recurrent states. Returns: NetworkOutput tuple. """ mean_weights_initializer = tf.contrib.layers.variance_scaling_initializer( factor=config.init_mean_factor) logstd_initializer = tf.random_normal_initializer(config.init_logstd, 1e-10) flat_observations = tf.reshape(observations, [ tf.shape(observations)[0], tf.shape(observations)[1], functools.reduce(operator.mul, observations.shape.as_list()[2:], 1) ]) with tf.variable_scope('policy'): x = flat_observations for size in config.policy_layers: x = tf.contrib.layers.fully_connected(x, size, tf.nn.relu) mean = tf.contrib.layers.fully_connected(x, action_size, tf.tanh, weights_initializer=mean_weights_initializer) logstd = tf.get_variable('logstd', mean.shape[2:], tf.float32, logstd_initializer) logstd = tf.tile(logstd[None, None], [tf.shape(mean)[0], tf.shape(mean)[1]] + [1] * (mean.shape.ndims - 2)) with tf.variable_scope('value'): x = flat_observations for size in config.value_layers: x = tf.contrib.layers.fully_connected(x, size, tf.nn.relu) value = tf.contrib.layers.fully_connected(x, 1, None)[..., 0] mean = tf.check_numerics(mean, 'mean') logstd = tf.check_numerics(logstd, 'logstd') value = tf.check_numerics(value, 'value') policy = tf.contrib.distributions.MultivariateNormalDiag(mean, tf.exp(logstd)) return NetworkOutput(policy, mean, logstd, value, state)
[ "def", "feed_forward_gaussian", "(", "config", ",", "action_size", ",", "observations", ",", "unused_length", ",", "state", "=", "None", ")", ":", "mean_weights_initializer", "=", "tf", ".", "contrib", ".", "layers", ".", "variance_scaling_initializer", "(", "factor", "=", "config", ".", "init_mean_factor", ")", "logstd_initializer", "=", "tf", ".", "random_normal_initializer", "(", "config", ".", "init_logstd", ",", "1e-10", ")", "flat_observations", "=", "tf", ".", "reshape", "(", "observations", ",", "[", "tf", ".", "shape", "(", "observations", ")", "[", "0", "]", ",", "tf", ".", "shape", "(", "observations", ")", "[", "1", "]", ",", "functools", ".", "reduce", "(", "operator", ".", "mul", ",", "observations", ".", "shape", ".", "as_list", "(", ")", "[", "2", ":", "]", ",", "1", ")", "]", ")", "with", "tf", ".", "variable_scope", "(", "'policy'", ")", ":", "x", "=", "flat_observations", "for", "size", "in", "config", ".", "policy_layers", ":", "x", "=", "tf", ".", "contrib", ".", "layers", ".", "fully_connected", "(", "x", ",", "size", ",", "tf", ".", "nn", ".", "relu", ")", "mean", "=", "tf", ".", "contrib", ".", "layers", ".", "fully_connected", "(", "x", ",", "action_size", ",", "tf", ".", "tanh", ",", "weights_initializer", "=", "mean_weights_initializer", ")", "logstd", "=", "tf", ".", "get_variable", "(", "'logstd'", ",", "mean", ".", "shape", "[", "2", ":", "]", ",", "tf", ".", "float32", ",", "logstd_initializer", ")", "logstd", "=", "tf", ".", "tile", "(", "logstd", "[", "None", ",", "None", "]", ",", "[", "tf", ".", "shape", "(", "mean", ")", "[", "0", "]", ",", "tf", ".", "shape", "(", "mean", ")", "[", "1", "]", "]", "+", "[", "1", "]", "*", "(", "mean", ".", "shape", ".", "ndims", "-", "2", ")", ")", "with", "tf", ".", "variable_scope", "(", "'value'", ")", ":", "x", "=", "flat_observations", "for", "size", "in", "config", ".", "value_layers", ":", "x", "=", "tf", ".", "contrib", ".", "layers", ".", "fully_connected", "(", "x", ",", "size", ",", "tf", ".", "nn", ".", "relu", ")", "value", "=", "tf", ".", "contrib", ".", "layers", ".", "fully_connected", "(", "x", ",", "1", ",", "None", ")", "[", "...", ",", "0", "]", "mean", "=", "tf", ".", "check_numerics", "(", "mean", ",", "'mean'", ")", "logstd", "=", "tf", ".", "check_numerics", "(", "logstd", ",", "'logstd'", ")", "value", "=", "tf", ".", "check_numerics", "(", "value", ",", "'value'", ")", "policy", "=", "tf", ".", "contrib", ".", "distributions", ".", "MultivariateNormalDiag", "(", "mean", ",", "tf", ".", "exp", "(", "logstd", ")", ")", "return", "NetworkOutput", "(", "policy", ",", "mean", ",", "logstd", ",", "value", ",", "state", ")" ]
https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/agents/networks.py#L32-L77
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tix.py
python
Grid.entrycget
(self, x, y, option)
return self.tk.call(self, 'entrycget', x, y, option)
Get the option value for cell at (x,y)
Get the option value for cell at (x,y)
[ "Get", "the", "option", "value", "for", "cell", "at", "(", "x", "y", ")" ]
def entrycget(self, x, y, option): "Get the option value for cell at (x,y)" if option and option[0] != '-': option = '-' + option return self.tk.call(self, 'entrycget', x, y, option)
[ "def", "entrycget", "(", "self", ",", "x", ",", "y", ",", "option", ")", ":", "if", "option", "and", "option", "[", "0", "]", "!=", "'-'", ":", "option", "=", "'-'", "+", "option", "return", "self", ".", "tk", ".", "call", "(", "self", ",", "'entrycget'", ",", "x", ",", "y", ",", "option", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tix.py#L1856-L1860
neopenx/Dragon
0e639a7319035ddc81918bd3df059230436ee0a1
Dragon/python/dragon/io/blob_fetcher.py
python
BlobFetcher.__init__
(self, **kwargs)
Construct a ``BlobFetcher``. Parameters ---------- batch_size : int The size of a training batch. partition : boolean Whether to partition batch. Default is ``False``. prefetch : int The prefetch count. Default is ``5``.
Construct a ``BlobFetcher``.
[ "Construct", "a", "BlobFetcher", "." ]
def __init__(self, **kwargs): """Construct a ``BlobFetcher``. Parameters ---------- batch_size : int The size of a training batch. partition : boolean Whether to partition batch. Default is ``False``. prefetch : int The prefetch count. Default is ``5``. """ super(BlobFetcher, self).__init__() self._batch_size = GetProperty(kwargs, 'batch_size', 100) self._partition = GetProperty(kwargs, 'partition', False) if self._partition: self._batch_size = int(self._batch_size / kwargs['group_size']) self.Q_in = self.Q_out = None self.daemon = True
[ "def", "__init__", "(", "self", ",", "*", "*", "kwargs", ")", ":", "super", "(", "BlobFetcher", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "_batch_size", "=", "GetProperty", "(", "kwargs", ",", "'batch_size'", ",", "100", ")", "self", ".", "_partition", "=", "GetProperty", "(", "kwargs", ",", "'partition'", ",", "False", ")", "if", "self", ".", "_partition", ":", "self", ".", "_batch_size", "=", "int", "(", "self", ".", "_batch_size", "/", "kwargs", "[", "'group_size'", "]", ")", "self", ".", "Q_in", "=", "self", ".", "Q_out", "=", "None", "self", ".", "daemon", "=", "True" ]
https://github.com/neopenx/Dragon/blob/0e639a7319035ddc81918bd3df059230436ee0a1/Dragon/python/dragon/io/blob_fetcher.py#L19-L38
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TStr.GetHex
(self)
return _snap.TStr_GetHex(self)
GetHex(TStr self) -> TStr Parameters: self: TStr const *
GetHex(TStr self) -> TStr
[ "GetHex", "(", "TStr", "self", ")", "-", ">", "TStr" ]
def GetHex(self): """ GetHex(TStr self) -> TStr Parameters: self: TStr const * """ return _snap.TStr_GetHex(self)
[ "def", "GetHex", "(", "self", ")", ":", "return", "_snap", ".", "TStr_GetHex", "(", "self", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L9853-L9861
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Source/ThirdParty/CEF3/cef_source/tools/cef_parser.py
python
obj_function.get_capi_proto
(self, defined_structs = [], prefix = None)
return result
Return the prototype of the C API function.
Return the prototype of the C API function.
[ "Return", "the", "prototype", "of", "the", "C", "API", "function", "." ]
def get_capi_proto(self, defined_structs = [], prefix = None): """ Return the prototype of the C API function. """ parts = self.get_capi_parts(defined_structs, prefix) result = parts['retval']+' '+parts['name']+ \ '('+string.join(parts['args'], ', ')+')' return result
[ "def", "get_capi_proto", "(", "self", ",", "defined_structs", "=", "[", "]", ",", "prefix", "=", "None", ")", ":", "parts", "=", "self", ".", "get_capi_parts", "(", "defined_structs", ",", "prefix", ")", "result", "=", "parts", "[", "'retval'", "]", "+", "' '", "+", "parts", "[", "'name'", "]", "+", "'('", "+", "string", ".", "join", "(", "parts", "[", "'args'", "]", ",", "', '", ")", "+", "')'", "return", "result" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Source/ThirdParty/CEF3/cef_source/tools/cef_parser.py#L1187-L1192
AndroidAdvanceWithGeektime/Chapter01
da2bc56d708fa74035c64564b134189045f51213
breakpad-build/src/main/cpp/external/libbreakpad/src/tools/python/filter_syms.py
python
SymbolFileParser._AdjustPath
(self, path)
return path[len(filter(path.startswith, self.ignored_prefixes + [''])[0]):]
Adjusts the supplied path after performing path de-duplication. This may be used to perform secondary adjustments, such as removing a common prefix, such as "/D/build", or replacing the file system path with information from the version control system. Returns: The actual path to use when writing the FILE record.
Adjusts the supplied path after performing path de-duplication.
[ "Adjusts", "the", "supplied", "path", "after", "performing", "path", "de", "-", "duplication", "." ]
def _AdjustPath(self, path): """Adjusts the supplied path after performing path de-duplication. This may be used to perform secondary adjustments, such as removing a common prefix, such as "/D/build", or replacing the file system path with information from the version control system. Returns: The actual path to use when writing the FILE record. """ return path[len(filter(path.startswith, self.ignored_prefixes + [''])[0]):]
[ "def", "_AdjustPath", "(", "self", ",", "path", ")", ":", "return", "path", "[", "len", "(", "filter", "(", "path", ".", "startswith", ",", "self", ".", "ignored_prefixes", "+", "[", "''", "]", ")", "[", "0", "]", ")", ":", "]" ]
https://github.com/AndroidAdvanceWithGeektime/Chapter01/blob/da2bc56d708fa74035c64564b134189045f51213/breakpad-build/src/main/cpp/external/libbreakpad/src/tools/python/filter_syms.py#L126-L137
sc0ty/subsync
be5390d00ff475b6543eb0140c7e65b34317d95b
subsync/assets/downloader.py
python
AssetDownloader.run
(self, timeout=None)
return True
Start downloader (asynchronously). Could be called multiple times, has no effect if downloader is already in progress. If downloader is already running, timeout will not be updated. See `AssetDownloade.registerCallbacks`. Parameters ---------- timeout: float, optional How often `onUpdate` callback should be called (in seconds). Returns ------- bool `True` if new update was started, `False` if update is already in progress.
Start downloader (asynchronously).
[ "Start", "downloader", "(", "asynchronously", ")", "." ]
def run(self, timeout=None): """Start downloader (asynchronously). Could be called multiple times, has no effect if downloader is already in progress. If downloader is already running, timeout will not be updated. See `AssetDownloade.registerCallbacks`. Parameters ---------- timeout: float, optional How often `onUpdate` callback should be called (in seconds). Returns ------- bool `True` if new update was started, `False` if update is already in progress. """ if self._thread: return False if not self._asset.hasUpdate(): raise RuntimeError('No update available') self._terminated = False self._exception = None self._thread = threading.Thread( target=self._run, args=(timeout,), name="Download") self._thread.start() return True
[ "def", "run", "(", "self", ",", "timeout", "=", "None", ")", ":", "if", "self", ".", "_thread", ":", "return", "False", "if", "not", "self", ".", "_asset", ".", "hasUpdate", "(", ")", ":", "raise", "RuntimeError", "(", "'No update available'", ")", "self", ".", "_terminated", "=", "False", "self", ".", "_exception", "=", "None", "self", ".", "_thread", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "_run", ",", "args", "=", "(", "timeout", ",", ")", ",", "name", "=", "\"Download\"", ")", "self", ".", "_thread", ".", "start", "(", ")", "return", "True" ]
https://github.com/sc0ty/subsync/blob/be5390d00ff475b6543eb0140c7e65b34317d95b/subsync/assets/downloader.py#L32-L63
GJDuck/LowFat
ecf6a0f0fa1b73a27a626cf493cc39e477b6faea
llvm-4.0.0.src/projects/compiler-rt/lib/sanitizer_common/scripts/cpplint.py
python
CheckSectionSpacing
(filename, clean_lines, class_info, linenum, error)
Checks for additional blank line issues related to sections. Currently the only thing checked here is blank line before protected/private. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. class_info: A _ClassInfo objects. linenum: The number of the line to check. error: The function to call with any errors found.
Checks for additional blank line issues related to sections.
[ "Checks", "for", "additional", "blank", "line", "issues", "related", "to", "sections", "." ]
def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error): """Checks for additional blank line issues related to sections. Currently the only thing checked here is blank line before protected/private. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. class_info: A _ClassInfo objects. linenum: The number of the line to check. error: The function to call with any errors found. """ # Skip checks if the class is small, where small means 25 lines or less. # 25 lines seems like a good cutoff since that's the usual height of # terminals, and any class that can't fit in one screen can't really # be considered "small". # # Also skip checks if we are on the first line. This accounts for # classes that look like # class Foo { public: ... }; # # If we didn't find the end of the class, last_line would be zero, # and the check will be skipped by the first condition. if (class_info.last_line - class_info.starting_linenum <= 24 or linenum <= class_info.starting_linenum): return matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum]) if matched: # Issue warning if the line before public/protected/private was # not a blank line, but don't do this if the previous line contains # "class" or "struct". This can happen two ways: # - We are at the beginning of the class. # - We are forward-declaring an inner class that is semantically # private, but needed to be public for implementation reasons. # Also ignores cases where the previous line ends with a backslash as can be # common when defining classes in C macros. prev_line = clean_lines.lines[linenum - 1] if (not IsBlankLine(prev_line) and not Search(r'\b(class|struct)\b', prev_line) and not Search(r'\\$', prev_line)): # Try a bit harder to find the beginning of the class. This is to # account for multi-line base-specifier lists, e.g.: # class Derived # : public Base { end_class_head = class_info.starting_linenum for i in range(class_info.starting_linenum, linenum): if Search(r'\{\s*$', clean_lines.lines[i]): end_class_head = i break if end_class_head < linenum - 1: error(filename, linenum, 'whitespace/blank_line', 3, '"%s:" should be preceded by a blank line' % matched.group(1))
[ "def", "CheckSectionSpacing", "(", "filename", ",", "clean_lines", ",", "class_info", ",", "linenum", ",", "error", ")", ":", "# Skip checks if the class is small, where small means 25 lines or less.", "# 25 lines seems like a good cutoff since that's the usual height of", "# terminals, and any class that can't fit in one screen can't really", "# be considered \"small\".", "#", "# Also skip checks if we are on the first line. This accounts for", "# classes that look like", "# class Foo { public: ... };", "#", "# If we didn't find the end of the class, last_line would be zero,", "# and the check will be skipped by the first condition.", "if", "(", "class_info", ".", "last_line", "-", "class_info", ".", "starting_linenum", "<=", "24", "or", "linenum", "<=", "class_info", ".", "starting_linenum", ")", ":", "return", "matched", "=", "Match", "(", "r'\\s*(public|protected|private):'", ",", "clean_lines", ".", "lines", "[", "linenum", "]", ")", "if", "matched", ":", "# Issue warning if the line before public/protected/private was", "# not a blank line, but don't do this if the previous line contains", "# \"class\" or \"struct\". This can happen two ways:", "# - We are at the beginning of the class.", "# - We are forward-declaring an inner class that is semantically", "# private, but needed to be public for implementation reasons.", "# Also ignores cases where the previous line ends with a backslash as can be", "# common when defining classes in C macros.", "prev_line", "=", "clean_lines", ".", "lines", "[", "linenum", "-", "1", "]", "if", "(", "not", "IsBlankLine", "(", "prev_line", ")", "and", "not", "Search", "(", "r'\\b(class|struct)\\b'", ",", "prev_line", ")", "and", "not", "Search", "(", "r'\\\\$'", ",", "prev_line", ")", ")", ":", "# Try a bit harder to find the beginning of the class. This is to", "# account for multi-line base-specifier lists, e.g.:", "# class Derived", "# : public Base {", "end_class_head", "=", "class_info", ".", "starting_linenum", "for", "i", "in", "range", "(", "class_info", ".", "starting_linenum", ",", "linenum", ")", ":", "if", "Search", "(", "r'\\{\\s*$'", ",", "clean_lines", ".", "lines", "[", "i", "]", ")", ":", "end_class_head", "=", "i", "break", "if", "end_class_head", "<", "linenum", "-", "1", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/blank_line'", ",", "3", ",", "'\"%s:\" should be preceded by a blank line'", "%", "matched", ".", "group", "(", "1", ")", ")" ]
https://github.com/GJDuck/LowFat/blob/ecf6a0f0fa1b73a27a626cf493cc39e477b6faea/llvm-4.0.0.src/projects/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L2489-L2541
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/math/symbolic_io.py
python
exprToStr
(expr,parseCompatible=True,expandSubexprs='auto')
Converts an Expression to a printable or parseable string. Args: expr (Expression): the Expression to convert parseCompatible (bool, optional): if True, the result is readable via exprFromStr() expandSubexprs (str or bool, optional): whether to expand subexpressions. Can be: * 'auto': if parseCompatible, equivalent to False. if parseCompatible=False, equivalent to True. * True: expands all common subexpressions * False: does not expand common subexpressions. * 'show': Internally used. Returns: (str): a printable or parsable string representing expr.
Converts an Expression to a printable or parseable string.
[ "Converts", "an", "Expression", "to", "a", "printable", "or", "parseable", "string", "." ]
def exprToStr(expr,parseCompatible=True,expandSubexprs='auto'): """Converts an Expression to a printable or parseable string. Args: expr (Expression): the Expression to convert parseCompatible (bool, optional): if True, the result is readable via exprFromStr() expandSubexprs (str or bool, optional): whether to expand subexpressions. Can be: * 'auto': if parseCompatible, equivalent to False. if parseCompatible=False, equivalent to True. * True: expands all common subexpressions * False: does not expand common subexpressions. * 'show': Internally used. Returns: (str): a printable or parsable string representing expr. """ if isinstance(expr,ConstantExpression): if isinstance(expr.value,slice): start,stop,step = expr.value.start,expr.value.stop,expr.value.step return "%s:%s%s"%(("" if start is None else str(start)), ("" if (stop is None or stop > 900000000000) else str(stop)), ("" if step is None else ":"+str(step))) try: jsonval = _to_jsonobj(expr.value) except: return str(expr.value) if parseCompatible: return json.dumps(jsonval) else: #Note: DOESNT WORK IN Python 3 #original_float_repr = encoder.FLOAT_REPR encoder.FLOAT_REPR = lambda o:format(o,'.14g') try: if _json_complex(jsonval): res = json.dumps(jsonval,sort_keys=True, indent=4, separators=(',', ': ')) else: res = json.dumps(jsonval,sort_keys=True) except Exception: print("Unable to dump constant expression",expr.value,"of type",expr.value.__class__.__name__) def print_recursive(v,indent=0): if hasattr(v,'__iter__'): print(indent*' ',"Sub objects have type",[a.__class__.__name__ for a in v]) for a in v: print_recursive(a,indent+2) print_recursive(expr.value) return "___JSON_ENCODE_ERROR___" #encoder.FLOAT_REPR = original_float_repr return res elif isinstance(expr,VariableExpression): if parseCompatible: return VAR_PREFIX+expr.var.name else: return str(expr.var) elif isinstance(expr,UserDataExpression): return USER_DATA_PREFIX+expr.name elif isinstance(expr,OperatorExpression): if expandSubexprs == 'auto': expandSubexprs = not parseCompatible if expandSubexprs: astr = [] for i,a in enumerate(expr.args): a._parent = (weakref.ref(expr),i) astr.append(exprToStr(a,parseCompatible,expandSubexprs)) if not isinstance(a,OperatorExpression) and expandSubexprs == 'show' and ('id' in a._cache or 'name' in a._cache): #tagged subexprs need parenthesies if astr[-1][-1] != ')': astr[-1] = '('+astr[-1]+')' astr[-1] = astr[-1] + NAMED_EXPRESSION_TAG + a._cache.get('id',a._cache.get('name')) a._parent = None res = _prettyPrintExpr(expr,astr,parseCompatible) if expandSubexprs == 'show' and ('id' in expr._cache or 'name' in expr._cache): #tagged subexprs need parenthesies if res[-1] != ')': res = '('+res+')' return res + NAMED_EXPRESSION_TAG + expr._cache.get('id',expr._cache.get('name')) oldparent = expr._parent iscomplex = expr.depth() >= 0 and (expr.functionInfo.name in _operator_precedence) expr._parent = oldparent if iscomplex and (expr._parent is not None and not isinstance(expr._parent,str)): if parseCompatible: return '(' + res + ')' else: parent = expr._parent[0]() if parent.functionInfo.name in _operator_precedence: expr_precedence = _operator_precedence[expr.functionInfo.name] parent_precedence = _operator_precedence[parent.functionInfo.name] #if - is the first in a summation, don't parenthesize it if expr._parent[1] == 0 and expr.functionInfo.name == 'neg' and parent.functionInfo.name in ['sum','add','sub']: return res if expr_precedence > parent_precedence: return '(' + res + ')' if expr_precedence == parent_precedence: if expr.functionInfo is parent.functionInfo and expr.functionInfo.properties.get('associative',False): return res else: return '(' + res + ')' return res else: if not parseCompatible: taggedexpr = _make_tagged(expr,"") else: taggedexpr = _make_tagged(expr) res = exprToStr(taggedexpr,parseCompatible,'show') if taggedexpr is not expr: expr._clearCache('id',deep=True) return res elif isinstance(expr,_TaggedExpression): return NAMED_EXPRESSION_PREFIX+expr.name elif is_const(expr): return str(expr) else: raise ValueError("Unknown type "+expr.__class__.__name__)
[ "def", "exprToStr", "(", "expr", ",", "parseCompatible", "=", "True", ",", "expandSubexprs", "=", "'auto'", ")", ":", "if", "isinstance", "(", "expr", ",", "ConstantExpression", ")", ":", "if", "isinstance", "(", "expr", ".", "value", ",", "slice", ")", ":", "start", ",", "stop", ",", "step", "=", "expr", ".", "value", ".", "start", ",", "expr", ".", "value", ".", "stop", ",", "expr", ".", "value", ".", "step", "return", "\"%s:%s%s\"", "%", "(", "(", "\"\"", "if", "start", "is", "None", "else", "str", "(", "start", ")", ")", ",", "(", "\"\"", "if", "(", "stop", "is", "None", "or", "stop", ">", "900000000000", ")", "else", "str", "(", "stop", ")", ")", ",", "(", "\"\"", "if", "step", "is", "None", "else", "\":\"", "+", "str", "(", "step", ")", ")", ")", "try", ":", "jsonval", "=", "_to_jsonobj", "(", "expr", ".", "value", ")", "except", ":", "return", "str", "(", "expr", ".", "value", ")", "if", "parseCompatible", ":", "return", "json", ".", "dumps", "(", "jsonval", ")", "else", ":", "#Note: DOESNT WORK IN Python 3", "#original_float_repr = encoder.FLOAT_REPR", "encoder", ".", "FLOAT_REPR", "=", "lambda", "o", ":", "format", "(", "o", ",", "'.14g'", ")", "try", ":", "if", "_json_complex", "(", "jsonval", ")", ":", "res", "=", "json", ".", "dumps", "(", "jsonval", ",", "sort_keys", "=", "True", ",", "indent", "=", "4", ",", "separators", "=", "(", "','", ",", "': '", ")", ")", "else", ":", "res", "=", "json", ".", "dumps", "(", "jsonval", ",", "sort_keys", "=", "True", ")", "except", "Exception", ":", "print", "(", "\"Unable to dump constant expression\"", ",", "expr", ".", "value", ",", "\"of type\"", ",", "expr", ".", "value", ".", "__class__", ".", "__name__", ")", "def", "print_recursive", "(", "v", ",", "indent", "=", "0", ")", ":", "if", "hasattr", "(", "v", ",", "'__iter__'", ")", ":", "print", "(", "indent", "*", "' '", ",", "\"Sub objects have type\"", ",", "[", "a", ".", "__class__", ".", "__name__", "for", "a", "in", "v", "]", ")", "for", "a", "in", "v", ":", "print_recursive", "(", "a", ",", "indent", "+", "2", ")", "print_recursive", "(", "expr", ".", "value", ")", "return", "\"___JSON_ENCODE_ERROR___\"", "#encoder.FLOAT_REPR = original_float_repr", "return", "res", "elif", "isinstance", "(", "expr", ",", "VariableExpression", ")", ":", "if", "parseCompatible", ":", "return", "VAR_PREFIX", "+", "expr", ".", "var", ".", "name", "else", ":", "return", "str", "(", "expr", ".", "var", ")", "elif", "isinstance", "(", "expr", ",", "UserDataExpression", ")", ":", "return", "USER_DATA_PREFIX", "+", "expr", ".", "name", "elif", "isinstance", "(", "expr", ",", "OperatorExpression", ")", ":", "if", "expandSubexprs", "==", "'auto'", ":", "expandSubexprs", "=", "not", "parseCompatible", "if", "expandSubexprs", ":", "astr", "=", "[", "]", "for", "i", ",", "a", "in", "enumerate", "(", "expr", ".", "args", ")", ":", "a", ".", "_parent", "=", "(", "weakref", ".", "ref", "(", "expr", ")", ",", "i", ")", "astr", ".", "append", "(", "exprToStr", "(", "a", ",", "parseCompatible", ",", "expandSubexprs", ")", ")", "if", "not", "isinstance", "(", "a", ",", "OperatorExpression", ")", "and", "expandSubexprs", "==", "'show'", "and", "(", "'id'", "in", "a", ".", "_cache", "or", "'name'", "in", "a", ".", "_cache", ")", ":", "#tagged subexprs need parenthesies", "if", "astr", "[", "-", "1", "]", "[", "-", "1", "]", "!=", "')'", ":", "astr", "[", "-", "1", "]", "=", "'('", "+", "astr", "[", "-", "1", "]", "+", "')'", "astr", "[", "-", "1", "]", "=", "astr", "[", "-", "1", "]", "+", "NAMED_EXPRESSION_TAG", "+", "a", ".", "_cache", ".", "get", "(", "'id'", ",", "a", ".", "_cache", ".", "get", "(", "'name'", ")", ")", "a", ".", "_parent", "=", "None", "res", "=", "_prettyPrintExpr", "(", "expr", ",", "astr", ",", "parseCompatible", ")", "if", "expandSubexprs", "==", "'show'", "and", "(", "'id'", "in", "expr", ".", "_cache", "or", "'name'", "in", "expr", ".", "_cache", ")", ":", "#tagged subexprs need parenthesies", "if", "res", "[", "-", "1", "]", "!=", "')'", ":", "res", "=", "'('", "+", "res", "+", "')'", "return", "res", "+", "NAMED_EXPRESSION_TAG", "+", "expr", ".", "_cache", ".", "get", "(", "'id'", ",", "expr", ".", "_cache", ".", "get", "(", "'name'", ")", ")", "oldparent", "=", "expr", ".", "_parent", "iscomplex", "=", "expr", ".", "depth", "(", ")", ">=", "0", "and", "(", "expr", ".", "functionInfo", ".", "name", "in", "_operator_precedence", ")", "expr", ".", "_parent", "=", "oldparent", "if", "iscomplex", "and", "(", "expr", ".", "_parent", "is", "not", "None", "and", "not", "isinstance", "(", "expr", ".", "_parent", ",", "str", ")", ")", ":", "if", "parseCompatible", ":", "return", "'('", "+", "res", "+", "')'", "else", ":", "parent", "=", "expr", ".", "_parent", "[", "0", "]", "(", ")", "if", "parent", ".", "functionInfo", ".", "name", "in", "_operator_precedence", ":", "expr_precedence", "=", "_operator_precedence", "[", "expr", ".", "functionInfo", ".", "name", "]", "parent_precedence", "=", "_operator_precedence", "[", "parent", ".", "functionInfo", ".", "name", "]", "#if - is the first in a summation, don't parenthesize it", "if", "expr", ".", "_parent", "[", "1", "]", "==", "0", "and", "expr", ".", "functionInfo", ".", "name", "==", "'neg'", "and", "parent", ".", "functionInfo", ".", "name", "in", "[", "'sum'", ",", "'add'", ",", "'sub'", "]", ":", "return", "res", "if", "expr_precedence", ">", "parent_precedence", ":", "return", "'('", "+", "res", "+", "')'", "if", "expr_precedence", "==", "parent_precedence", ":", "if", "expr", ".", "functionInfo", "is", "parent", ".", "functionInfo", "and", "expr", ".", "functionInfo", ".", "properties", ".", "get", "(", "'associative'", ",", "False", ")", ":", "return", "res", "else", ":", "return", "'('", "+", "res", "+", "')'", "return", "res", "else", ":", "if", "not", "parseCompatible", ":", "taggedexpr", "=", "_make_tagged", "(", "expr", ",", "\"\"", ")", "else", ":", "taggedexpr", "=", "_make_tagged", "(", "expr", ")", "res", "=", "exprToStr", "(", "taggedexpr", ",", "parseCompatible", ",", "'show'", ")", "if", "taggedexpr", "is", "not", "expr", ":", "expr", ".", "_clearCache", "(", "'id'", ",", "deep", "=", "True", ")", "return", "res", "elif", "isinstance", "(", "expr", ",", "_TaggedExpression", ")", ":", "return", "NAMED_EXPRESSION_PREFIX", "+", "expr", ".", "name", "elif", "is_const", "(", "expr", ")", ":", "return", "str", "(", "expr", ")", "else", ":", "raise", "ValueError", "(", "\"Unknown type \"", "+", "expr", ".", "__class__", ".", "__name__", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/math/symbolic_io.py#L202-L314
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/traci/_vehicle.py
python
VehicleDomain.setVehicleClass
(self, vehID, clazz)
setVehicleClass(string, string) -> None Sets the vehicle class for this vehicle.
setVehicleClass(string, string) -> None
[ "setVehicleClass", "(", "string", "string", ")", "-", ">", "None" ]
def setVehicleClass(self, vehID, clazz): """setVehicleClass(string, string) -> None Sets the vehicle class for this vehicle. """ self._setCmd(tc.VAR_VEHICLECLASS, vehID, "s", clazz)
[ "def", "setVehicleClass", "(", "self", ",", "vehID", ",", "clazz", ")", ":", "self", ".", "_setCmd", "(", "tc", ".", "VAR_VEHICLECLASS", ",", "vehID", ",", "\"s\"", ",", "clazz", ")" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/traci/_vehicle.py#L1380-L1385
genn-team/genn
75e1eb218cafa228bf36ae4613d1ce26e877b12c
pygenn/genn_model.py
python
create_var_ref
(pop, var_name)
return (genn_wrapper.create_var_ref(pop.pop, var_name), pop)
This helper function creates a Models::VarReference pointing to a neuron or current source variable for initialising variable references. Args: pop -- population, either a NeuronGroup or CurrentSource object var_name -- name of variable in population to reference
This helper function creates a Models::VarReference pointing to a neuron or current source variable for initialising variable references.
[ "This", "helper", "function", "creates", "a", "Models", "::", "VarReference", "pointing", "to", "a", "neuron", "or", "current", "source", "variable", "for", "initialising", "variable", "references", "." ]
def create_var_ref(pop, var_name): """This helper function creates a Models::VarReference pointing to a neuron or current source variable for initialising variable references. Args: pop -- population, either a NeuronGroup or CurrentSource object var_name -- name of variable in population to reference """ return (genn_wrapper.create_var_ref(pop.pop, var_name), pop)
[ "def", "create_var_ref", "(", "pop", ",", "var_name", ")", ":", "return", "(", "genn_wrapper", ".", "create_var_ref", "(", "pop", ".", "pop", ",", "var_name", ")", ",", "pop", ")" ]
https://github.com/genn-team/genn/blob/75e1eb218cafa228bf36ae4613d1ce26e877b12c/pygenn/genn_model.py#L965-L974
netket/netket
0d534e54ecbf25b677ea72af6b85947979420652
netket/optimizer/qgt/qgt_jacobian_pytree.py
python
QGTJacobianPyTree
( vstate=None, *, mode: str = None, holomorphic: bool = None, rescale_shift=False, **kwargs, )
return QGTJacobianPyTreeT( O=O, scale=scale, params=vstate.parameters, mode=mode, **kwargs )
Semi-lazy representation of an S Matrix where the Jacobian O_k is precomputed and stored as a PyTree. The matrix of gradients O is computed on initialisation, but not S, which can be computed by calling :code:`to_dense`. The details on how the ⟨S⟩⁻¹⟨F⟩ system is solved are contaianed in the field `sr`. Args: vstate: The variational state mode: "real", "complex" or "holomorphic": specifies the implementation used to compute the jacobian. "real" discards the imaginary part of the output of the model. "complex" splits the real and imaginary part of the parameters and output. It works also for non holomorphic models. holomorphic works for any function assuming it's holomorphic or real valued. holomorphic: a flag to indicate that the function is holomorphic. rescale_shift: If True rescales the diagonal shift.
Semi-lazy representation of an S Matrix where the Jacobian O_k is precomputed and stored as a PyTree.
[ "Semi", "-", "lazy", "representation", "of", "an", "S", "Matrix", "where", "the", "Jacobian", "O_k", "is", "precomputed", "and", "stored", "as", "a", "PyTree", "." ]
def QGTJacobianPyTree( vstate=None, *, mode: str = None, holomorphic: bool = None, rescale_shift=False, **kwargs, ) -> "QGTJacobianPyTreeT": """ Semi-lazy representation of an S Matrix where the Jacobian O_k is precomputed and stored as a PyTree. The matrix of gradients O is computed on initialisation, but not S, which can be computed by calling :code:`to_dense`. The details on how the ⟨S⟩⁻¹⟨F⟩ system is solved are contaianed in the field `sr`. Args: vstate: The variational state mode: "real", "complex" or "holomorphic": specifies the implementation used to compute the jacobian. "real" discards the imaginary part of the output of the model. "complex" splits the real and imaginary part of the parameters and output. It works also for non holomorphic models. holomorphic works for any function assuming it's holomorphic or real valued. holomorphic: a flag to indicate that the function is holomorphic. rescale_shift: If True rescales the diagonal shift. """ if vstate is None: return partial( QGTJacobianPyTree, mode=mode, holomorphic=holomorphic, rescale_shift=rescale_shift, **kwargs, ) # TODO: Find a better way to handle this case from netket.vqs import ExactState if isinstance(vstate, ExactState): samples = split_array_mpi(vstate._all_states) pdf = split_array_mpi(vstate.probability_distribution()) else: samples = vstate.samples pdf = None # Choose sensible default mode if mode is None: mode = choose_jacobian_mode( vstate._apply_fun, vstate.parameters, vstate.model_state, samples, mode=mode, holomorphic=holomorphic, ) elif holomorphic is not None: raise ValueError("Cannot specify both `mode` and `holomorphic`.") if hasattr(vstate, "chunk_size"): chunk_size = vstate.chunk_size else: chunk_size = None O, scale = prepare_centered_oks( vstate._apply_fun, vstate.parameters, samples.reshape(-1, samples.shape[-1]), vstate.model_state, mode, rescale_shift, pdf, chunk_size, ) return QGTJacobianPyTreeT( O=O, scale=scale, params=vstate.parameters, mode=mode, **kwargs )
[ "def", "QGTJacobianPyTree", "(", "vstate", "=", "None", ",", "*", ",", "mode", ":", "str", "=", "None", ",", "holomorphic", ":", "bool", "=", "None", ",", "rescale_shift", "=", "False", ",", "*", "*", "kwargs", ",", ")", "->", "\"QGTJacobianPyTreeT\"", ":", "if", "vstate", "is", "None", ":", "return", "partial", "(", "QGTJacobianPyTree", ",", "mode", "=", "mode", ",", "holomorphic", "=", "holomorphic", ",", "rescale_shift", "=", "rescale_shift", ",", "*", "*", "kwargs", ",", ")", "# TODO: Find a better way to handle this case", "from", "netket", ".", "vqs", "import", "ExactState", "if", "isinstance", "(", "vstate", ",", "ExactState", ")", ":", "samples", "=", "split_array_mpi", "(", "vstate", ".", "_all_states", ")", "pdf", "=", "split_array_mpi", "(", "vstate", ".", "probability_distribution", "(", ")", ")", "else", ":", "samples", "=", "vstate", ".", "samples", "pdf", "=", "None", "# Choose sensible default mode", "if", "mode", "is", "None", ":", "mode", "=", "choose_jacobian_mode", "(", "vstate", ".", "_apply_fun", ",", "vstate", ".", "parameters", ",", "vstate", ".", "model_state", ",", "samples", ",", "mode", "=", "mode", ",", "holomorphic", "=", "holomorphic", ",", ")", "elif", "holomorphic", "is", "not", "None", ":", "raise", "ValueError", "(", "\"Cannot specify both `mode` and `holomorphic`.\"", ")", "if", "hasattr", "(", "vstate", ",", "\"chunk_size\"", ")", ":", "chunk_size", "=", "vstate", ".", "chunk_size", "else", ":", "chunk_size", "=", "None", "O", ",", "scale", "=", "prepare_centered_oks", "(", "vstate", ".", "_apply_fun", ",", "vstate", ".", "parameters", ",", "samples", ".", "reshape", "(", "-", "1", ",", "samples", ".", "shape", "[", "-", "1", "]", ")", ",", "vstate", ".", "model_state", ",", "mode", ",", "rescale_shift", ",", "pdf", ",", "chunk_size", ",", ")", "return", "QGTJacobianPyTreeT", "(", "O", "=", "O", ",", "scale", "=", "scale", ",", "params", "=", "vstate", ".", "parameters", ",", "mode", "=", "mode", ",", "*", "*", "kwargs", ")" ]
https://github.com/netket/netket/blob/0d534e54ecbf25b677ea72af6b85947979420652/netket/optimizer/qgt/qgt_jacobian_pytree.py#L35-L113
gnuradio/gnuradio
09c3c4fa4bfb1a02caac74cb5334dfe065391e3b
gr-utils/blocktool/core/parseheader_generic.py
python
GenericHeaderParser.run_blocktool
(self)
Run, run, run.
Run, run, run.
[ "Run", "run", "run", "." ]
def run_blocktool(self): """ Run, run, run. """ pass
[ "def", "run_blocktool", "(", "self", ")", ":", "pass" ]
https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/gr-utils/blocktool/core/parseheader_generic.py#L350-L352
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/models/wheel.py
python
Wheel.support_index_min
(self, tags)
return min(tags.index(tag) for tag in self.file_tags if tag in tags)
Return the lowest index that one of the wheel's file_tag combinations achieves in the given list of supported tags. For example, if there are 8 supported tags and one of the file tags is first in the list, then return 0. :param tags: the PEP 425 tags to check the wheel against, in order with most preferred first. :raises ValueError: If none of the wheel's file tags match one of the supported tags.
Return the lowest index that one of the wheel's file_tag combinations
[ "Return", "the", "lowest", "index", "that", "one", "of", "the", "wheel", "s", "file_tag", "combinations" ]
def support_index_min(self, tags): # type: (List[Tag]) -> int """Return the lowest index that one of the wheel's file_tag combinations achieves in the given list of supported tags. For example, if there are 8 supported tags and one of the file tags is first in the list, then return 0. :param tags: the PEP 425 tags to check the wheel against, in order with most preferred first. :raises ValueError: If none of the wheel's file tags match one of the supported tags. """ return min(tags.index(tag) for tag in self.file_tags if tag in tags)
[ "def", "support_index_min", "(", "self", ",", "tags", ")", ":", "# type: (List[Tag]) -> int", "return", "min", "(", "tags", ".", "index", "(", "tag", ")", "for", "tag", "in", "self", ".", "file_tags", "if", "tag", "in", "tags", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/models/wheel.py#L111-L139
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/robotsim.py
python
SimRobotController.getControlType
(self)
return _robotsim.SimRobotController_getControlType(self)
getControlType(SimRobotController self) -> std::string Returns the control type for the active controller. Possible return values are: * unknown * off * torque * PID * locked_velocity
getControlType(SimRobotController self) -> std::string
[ "getControlType", "(", "SimRobotController", "self", ")", "-", ">", "std", "::", "string" ]
def getControlType(self): """ getControlType(SimRobotController self) -> std::string Returns the control type for the active controller. Possible return values are: * unknown * off * torque * PID * locked_velocity """ return _robotsim.SimRobotController_getControlType(self)
[ "def", "getControlType", "(", "self", ")", ":", "return", "_robotsim", ".", "SimRobotController_getControlType", "(", "self", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/robotsim.py#L7756-L7773
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
DataFormats/FWLite/python/__init__.py
python
Lumis._next
(self)
(Internal) Iterator internals
(Internal) Iterator internals
[ "(", "Internal", ")", "Iterator", "internals" ]
def _next (self): """(Internal) Iterator internals""" while True: if self._lumi.atEnd(): if not self._createFWLiteLumi(): # there are no more files here, so we are done break yield self self._lumiCounts += 1 if self._maxLumis > 0 and self._lumiCounts >= self._maxLumis: break self._lumi.__preinc__()
[ "def", "_next", "(", "self", ")", ":", "while", "True", ":", "if", "self", ".", "_lumi", ".", "atEnd", "(", ")", ":", "if", "not", "self", ".", "_createFWLiteLumi", "(", ")", ":", "# there are no more files here, so we are done", "break", "yield", "self", "self", ".", "_lumiCounts", "+=", "1", "if", "self", ".", "_maxLumis", ">", "0", "and", "self", ".", "_lumiCounts", ">=", "self", ".", "_maxLumis", ":", "break", "self", ".", "_lumi", ".", "__preinc__", "(", ")" ]
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/DataFormats/FWLite/python/__init__.py#L276-L287
wujian16/Cornell-MOE
df299d1be882d2af9796d7a68b3f9505cac7a53e
moe/optimal_learning/python/cpp_wrappers/domain.py
python
SimplexIntersectTensorProductDomain.__init__
(self, domain_bounds)
Construct a SimplexIntersectTensorProductDomain that can be used with cpp_wrappers.* functions/classes. :param domain_bounds: the boundaries of a dim-dimensional tensor-product domain. :type domain_bounds: iterable of dim ClosedInterval
Construct a SimplexIntersectTensorProductDomain that can be used with cpp_wrappers.* functions/classes.
[ "Construct", "a", "SimplexIntersectTensorProductDomain", "that", "can", "be", "used", "with", "cpp_wrappers", ".", "*", "functions", "/", "classes", "." ]
def __init__(self, domain_bounds): """Construct a SimplexIntersectTensorProductDomain that can be used with cpp_wrappers.* functions/classes. :param domain_bounds: the boundaries of a dim-dimensional tensor-product domain. :type domain_bounds: iterable of dim ClosedInterval """ self._tensor_product_domain = TensorProductDomain(domain_bounds) self._domain_type = C_GP.DomainTypes.simplex
[ "def", "__init__", "(", "self", ",", "domain_bounds", ")", ":", "self", ".", "_tensor_product_domain", "=", "TensorProductDomain", "(", "domain_bounds", ")", "self", ".", "_domain_type", "=", "C_GP", ".", "DomainTypes", ".", "simplex" ]
https://github.com/wujian16/Cornell-MOE/blob/df299d1be882d2af9796d7a68b3f9505cac7a53e/moe/optimal_learning/python/cpp_wrappers/domain.py#L130-L138
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/six.py
python
_SixMetaPathImporter.get_code
(self, fullname)
return None
Return None Required, if is_package is implemented
Return None
[ "Return", "None" ]
def get_code(self, fullname): """Return None Required, if is_package is implemented""" self.__get_module(fullname) # eventually raises ImportError return None
[ "def", "get_code", "(", "self", ",", "fullname", ")", ":", "self", ".", "__get_module", "(", "fullname", ")", "# eventually raises ImportError", "return", "None" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/six.py#L435-L445
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/pubsub/utils/topictreeprinter.py
python
printTreeDocs
(rootTopic=None, topicMgr=None, **kwargs)
Print out the topic tree to a file (or file-like object like a StringIO), starting at rootTopic. If root topic should be root of whole tree, get it from pub.getDefaultTopicTreeRoot(). The treeVisitor is an instance of pub.TopicTreeTraverser. Printing the tree docs would normally involve this:: from pubsub import pub from pubsub.utils.topictreeprinter import TopicTreePrinter traverser = pub.TopicTreeTraverser( TopicTreePrinter(**kwargs) ) traverser.traverse( pub.getDefaultTopicTreeRoot() ) With printTreeDocs, it looks like this:: from pubsub import pub from pubsub.utils import printTreeDocs printTreeDocs() The kwargs are the same as for TopicTreePrinter constructor: extra(None), width(70), indentStep(4), bulletTopic, bulletTopicItem, bulletTopicArg, fileObj(stdout). If fileObj not given, stdout is used.
Print out the topic tree to a file (or file-like object like a StringIO), starting at rootTopic. If root topic should be root of whole tree, get it from pub.getDefaultTopicTreeRoot(). The treeVisitor is an instance of pub.TopicTreeTraverser.
[ "Print", "out", "the", "topic", "tree", "to", "a", "file", "(", "or", "file", "-", "like", "object", "like", "a", "StringIO", ")", "starting", "at", "rootTopic", ".", "If", "root", "topic", "should", "be", "root", "of", "whole", "tree", "get", "it", "from", "pub", ".", "getDefaultTopicTreeRoot", "()", ".", "The", "treeVisitor", "is", "an", "instance", "of", "pub", ".", "TopicTreeTraverser", "." ]
def printTreeDocs(rootTopic=None, topicMgr=None, **kwargs): """Print out the topic tree to a file (or file-like object like a StringIO), starting at rootTopic. If root topic should be root of whole tree, get it from pub.getDefaultTopicTreeRoot(). The treeVisitor is an instance of pub.TopicTreeTraverser. Printing the tree docs would normally involve this:: from pubsub import pub from pubsub.utils.topictreeprinter import TopicTreePrinter traverser = pub.TopicTreeTraverser( TopicTreePrinter(**kwargs) ) traverser.traverse( pub.getDefaultTopicTreeRoot() ) With printTreeDocs, it looks like this:: from pubsub import pub from pubsub.utils import printTreeDocs printTreeDocs() The kwargs are the same as for TopicTreePrinter constructor: extra(None), width(70), indentStep(4), bulletTopic, bulletTopicItem, bulletTopicArg, fileObj(stdout). If fileObj not given, stdout is used.""" if rootTopic is None: if topicMgr is None: from .. import pub topicMgr = pub.getDefaultTopicMgr() rootTopic = topicMgr.getRootAllTopics() printer = TopicTreePrinter(**kwargs) traverser = TopicTreeTraverser(printer) traverser.traverse(rootTopic)
[ "def", "printTreeDocs", "(", "rootTopic", "=", "None", ",", "topicMgr", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "rootTopic", "is", "None", ":", "if", "topicMgr", "is", "None", ":", "from", ".", ".", "import", "pub", "topicMgr", "=", "pub", ".", "getDefaultTopicMgr", "(", ")", "rootTopic", "=", "topicMgr", ".", "getRootAllTopics", "(", ")", "printer", "=", "TopicTreePrinter", "(", "*", "*", "kwargs", ")", "traverser", "=", "TopicTreeTraverser", "(", "printer", ")", "traverser", ".", "traverse", "(", "rootTopic", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/pubsub/utils/topictreeprinter.py#L163-L193
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/src/motionplanning.py
python
CSpaceInterface.setFeasibility
(self, pyFeas)
return _motionplanning.CSpaceInterface_setFeasibility(self, pyFeas)
setFeasibility(CSpaceInterface self, PyObject * pyFeas)
setFeasibility(CSpaceInterface self, PyObject * pyFeas)
[ "setFeasibility", "(", "CSpaceInterface", "self", "PyObject", "*", "pyFeas", ")" ]
def setFeasibility(self, pyFeas): """ setFeasibility(CSpaceInterface self, PyObject * pyFeas) """ return _motionplanning.CSpaceInterface_setFeasibility(self, pyFeas)
[ "def", "setFeasibility", "(", "self", ",", "pyFeas", ")", ":", "return", "_motionplanning", ".", "CSpaceInterface_setFeasibility", "(", "self", ",", "pyFeas", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/src/motionplanning.py#L336-L343