nwo
stringlengths
5
86
sha
stringlengths
40
40
path
stringlengths
4
189
language
stringclasses
1 value
identifier
stringlengths
1
94
parameters
stringlengths
2
4.03k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
11.5k
docstring
stringlengths
1
33.2k
docstring_summary
stringlengths
0
5.15k
docstring_tokens
list
function
stringlengths
34
151k
function_tokens
list
url
stringlengths
90
278
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/symbol/symbol.py
python
Symbol.softmin
(self, *args, **kwargs)
return op.softmin(self, *args, **kwargs)
Convenience fluent method for :py:func:`softmin`. The arguments are the same as for :py:func:`softmin`, with this array as data.
Convenience fluent method for :py:func:`softmin`.
[ "Convenience", "fluent", "method", "for", ":", "py", ":", "func", ":", "softmin", "." ]
def softmin(self, *args, **kwargs): """Convenience fluent method for :py:func:`softmin`. The arguments are the same as for :py:func:`softmin`, with this array as data. """ return op.softmin(self, *args, **kwargs)
[ "def", "softmin", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "op", ".", "softmin", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/symbol/symbol.py#L2621-L2627
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/tix.py
python
Grid.delete_row
(self, from_, to=None)
Delete rows between from_ and to inclusive. If to is not provided, delete only row at from_
Delete rows between from_ and to inclusive. If to is not provided, delete only row at from_
[ "Delete", "rows", "between", "from_", "and", "to", "inclusive", ".", "If", "to", "is", "not", "provided", "delete", "only", "row", "at", "from_" ]
def delete_row(self, from_, to=None): """Delete rows between from_ and to inclusive. If to is not provided, delete only row at from_""" if to is None: self.tk.call(self, 'delete', 'row', from_) else: self.tk.call(self, 'delete', 'row', from_, to)
[ "def", "delete_row", "(", "self", ",", "from_", ",", "to", "=", "None", ")", ":", "if", "to", "is", "None", ":", "self", ".", "tk", ".", "call", "(", "self", ",", "'delete'", ",", "'row'", ",", "from_", ")", "else", ":", "self", ".", "tk", ".", "call", "(", "self", ",", "'delete'", ",", "'row'", ",", "from_", ",", "to", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/tix.py#L1809-L1815
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/rosdep2/sources_list.py
python
CachedDataSource.origin
(self)
return self.source.origin
:returns: data source origin, if set, or ``None``
:returns: data source origin, if set, or ``None``
[ ":", "returns", ":", "data", "source", "origin", "if", "set", "or", "None" ]
def origin(self): """ :returns: data source origin, if set, or ``None`` """ return self.source.origin
[ "def", "origin", "(", "self", ")", ":", "return", "self", ".", "source", ".", "origin" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/rosdep2/sources_list.py#L249-L253
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_controls.py
python
PreChoicebook
(*args, **kwargs)
return val
PreChoicebook() -> Choicebook
PreChoicebook() -> Choicebook
[ "PreChoicebook", "()", "-", ">", "Choicebook" ]
def PreChoicebook(*args, **kwargs): """PreChoicebook() -> Choicebook""" val = _controls_.new_PreChoicebook(*args, **kwargs) return val
[ "def", "PreChoicebook", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "val", "=", "_controls_", ".", "new_PreChoicebook", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "val" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L3277-L3280
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/wsgiref/util.py
python
is_hop_by_hop
(header_name)
return _hoppish(header_name.lower())
Return true if 'header_name' is an HTTP/1.1 "Hop-by-Hop" header
Return true if 'header_name' is an HTTP/1.1 "Hop-by-Hop" header
[ "Return", "true", "if", "header_name", "is", "an", "HTTP", "/", "1", ".", "1", "Hop", "-", "by", "-", "Hop", "header" ]
def is_hop_by_hop(header_name): """Return true if 'header_name' is an HTTP/1.1 "Hop-by-Hop" header""" return _hoppish(header_name.lower())
[ "def", "is_hop_by_hop", "(", "header_name", ")", ":", "return", "_hoppish", "(", "header_name", ".", "lower", "(", ")", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/wsgiref/util.py#L163-L165
smilehao/xlua-framework
a03801538be2b0e92d39332d445b22caca1ef61f
ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/build/lib/google/protobuf/internal/python_message.py
python
_AddSerializeToStringMethod
(message_descriptor, cls)
Helper for _AddMessageMethods().
Helper for _AddMessageMethods().
[ "Helper", "for", "_AddMessageMethods", "()", "." ]
def _AddSerializeToStringMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def SerializeToString(self): # Check if the message has all of its required fields set. errors = [] if not self.IsInitialized(): raise message_mod.EncodeError( 'Message %s is missing required fields: %s' % ( self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors()))) return self.SerializePartialToString() cls.SerializeToString = SerializeToString
[ "def", "_AddSerializeToStringMethod", "(", "message_descriptor", ",", "cls", ")", ":", "def", "SerializeToString", "(", "self", ")", ":", "# Check if the message has all of its required fields set.", "errors", "=", "[", "]", "if", "not", "self", ".", "IsInitialized", "(", ")", ":", "raise", "message_mod", ".", "EncodeError", "(", "'Message %s is missing required fields: %s'", "%", "(", "self", ".", "DESCRIPTOR", ".", "full_name", ",", "','", ".", "join", "(", "self", ".", "FindInitializationErrors", "(", ")", ")", ")", ")", "return", "self", ".", "SerializePartialToString", "(", ")", "cls", ".", "SerializeToString", "=", "SerializeToString" ]
https://github.com/smilehao/xlua-framework/blob/a03801538be2b0e92d39332d445b22caca1ef61f/ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/build/lib/google/protobuf/internal/python_message.py#L758-L769
gem5/gem5
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
src/mem/slicc/parser.py
python
SLICC.p_pairsx__many
(self, p)
pairsx : pair ',' pairsx
pairsx : pair ',' pairsx
[ "pairsx", ":", "pair", "pairsx" ]
def p_pairsx__many(self, p): "pairsx : pair ',' pairsx" p[0] = p[3] p[0].addPair(p[1])
[ "def", "p_pairsx__many", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "p", "[", "3", "]", "p", "[", "0", "]", ".", "addPair", "(", "p", "[", "1", "]", ")" ]
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/src/mem/slicc/parser.py#L547-L550
f4exb/sdrangel
fce235b2bc59b932f93d2cb8784055d51b3b8424
scriptsapi/ptt_active.py
python
getInputOptions
()
return options.addr, options.port, options.sdrangel_port, options.delay, options.freq_sync, other_dict, options.limerfe_dev
This is the argument line parser
This is the argument line parser
[ "This", "is", "the", "argument", "line", "parser" ]
def getInputOptions(): """ This is the argument line parser """ # ---------------------------------------------------------------------- parser = argparse.ArgumentParser(description="Manages PTT from an SDRangel instance automatically") parser.add_argument("-A", "--address", dest="addr", help="listening address", metavar="IP", type=str) parser.add_argument("-P", "--port", dest="port", help="listening port", metavar="PORT", type=int) parser.add_argument("-p", "--port-sdr", dest="sdrangel_port", help="SDRangel REST API port", metavar="PORT", type=int) parser.add_argument("-l", "--link", dest="linked_devices", help="pair of indexes of devices to link", metavar="LIST", type=int, nargs=2) parser.add_argument("-d", "--delay", dest="delay", help="switchover delay in seconds", metavar="SECONDS", type=int) parser.add_argument("-f", "--freq-sync", dest="freq_sync", help="synchronize linked devices frequencies", action="store_true") parser.add_argument("-L", "--limerfe-dev", dest="limerfe_dev", help="LimeRFE USB serial device (optional)", metavar="DEVICE", type=str) options = parser.parse_args() if options.addr == None: options.addr = "0.0.0.0" if options.port == None: options.port = 8000 if options.sdrangel_port == None: options.sdrangel_port = 8091 if options.linked_devices == None: options.linked_devices = [0, 1] if options.delay == None: options.delay = 1 if options.freq_sync == None: options.freq_sync = False other_dict = { options.linked_devices[0]: options.linked_devices[1], options.linked_devices[1]: options.linked_devices[0] } return options.addr, options.port, options.sdrangel_port, options.delay, options.freq_sync, other_dict, options.limerfe_dev
[ "def", "getInputOptions", "(", ")", ":", "# ----------------------------------------------------------------------", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Manages PTT from an SDRangel instance automatically\"", ")", "parser", ".", "add_argument", "(", "\"-A\"", ",", "\"--address\"", ",", "dest", "=", "\"addr\"", ",", "help", "=", "\"listening address\"", ",", "metavar", "=", "\"IP\"", ",", "type", "=", "str", ")", "parser", ".", "add_argument", "(", "\"-P\"", ",", "\"--port\"", ",", "dest", "=", "\"port\"", ",", "help", "=", "\"listening port\"", ",", "metavar", "=", "\"PORT\"", ",", "type", "=", "int", ")", "parser", ".", "add_argument", "(", "\"-p\"", ",", "\"--port-sdr\"", ",", "dest", "=", "\"sdrangel_port\"", ",", "help", "=", "\"SDRangel REST API port\"", ",", "metavar", "=", "\"PORT\"", ",", "type", "=", "int", ")", "parser", ".", "add_argument", "(", "\"-l\"", ",", "\"--link\"", ",", "dest", "=", "\"linked_devices\"", ",", "help", "=", "\"pair of indexes of devices to link\"", ",", "metavar", "=", "\"LIST\"", ",", "type", "=", "int", ",", "nargs", "=", "2", ")", "parser", ".", "add_argument", "(", "\"-d\"", ",", "\"--delay\"", ",", "dest", "=", "\"delay\"", ",", "help", "=", "\"switchover delay in seconds\"", ",", "metavar", "=", "\"SECONDS\"", ",", "type", "=", "int", ")", "parser", ".", "add_argument", "(", "\"-f\"", ",", "\"--freq-sync\"", ",", "dest", "=", "\"freq_sync\"", ",", "help", "=", "\"synchronize linked devices frequencies\"", ",", "action", "=", "\"store_true\"", ")", "parser", ".", "add_argument", "(", "\"-L\"", ",", "\"--limerfe-dev\"", ",", "dest", "=", "\"limerfe_dev\"", ",", "help", "=", "\"LimeRFE USB serial device (optional)\"", ",", "metavar", "=", "\"DEVICE\"", ",", "type", "=", "str", ")", "options", "=", "parser", ".", "parse_args", "(", ")", "if", "options", ".", "addr", "==", "None", ":", "options", ".", "addr", "=", "\"0.0.0.0\"", "if", "options", ".", "port", "==", "None", ":", "options", ".", "port", "=", "8000", "if", "options", ".", "sdrangel_port", "==", "None", ":", "options", ".", "sdrangel_port", "=", "8091", "if", "options", ".", "linked_devices", "==", "None", ":", "options", ".", "linked_devices", "=", "[", "0", ",", "1", "]", "if", "options", ".", "delay", "==", "None", ":", "options", ".", "delay", "=", "1", "if", "options", ".", "freq_sync", "==", "None", ":", "options", ".", "freq_sync", "=", "False", "other_dict", "=", "{", "options", ".", "linked_devices", "[", "0", "]", ":", "options", ".", "linked_devices", "[", "1", "]", ",", "options", ".", "linked_devices", "[", "1", "]", ":", "options", ".", "linked_devices", "[", "0", "]", "}", "return", "options", ".", "addr", ",", "options", ".", "port", ",", "options", ".", "sdrangel_port", ",", "options", ".", "delay", ",", "options", ".", "freq_sync", ",", "other_dict", ",", "options", ".", "limerfe_dev" ]
https://github.com/f4exb/sdrangel/blob/fce235b2bc59b932f93d2cb8784055d51b3b8424/scriptsapi/ptt_active.py#L271-L302
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/multidirdialog.py
python
MultiDirDialog.RecurseTopDir
(self, treeCtrl, item, itemText)
return itemText
Recurse a directory tree to include the parent-folder. :param `treeCtrl`: the tree control associated with teh internal :class:`GenericDirCtrl`; :param `item`: the selected tree control item; :param `itemText`: the selected tree control item text.
Recurse a directory tree to include the parent-folder.
[ "Recurse", "a", "directory", "tree", "to", "include", "the", "parent", "-", "folder", "." ]
def RecurseTopDir(self, treeCtrl, item, itemText): """ Recurse a directory tree to include the parent-folder. :param `treeCtrl`: the tree control associated with teh internal :class:`GenericDirCtrl`; :param `item`: the selected tree control item; :param `itemText`: the selected tree control item text. """ # Get the item parent parent = treeCtrl.GetItemParent(item) if parent != treeCtrl.GetRootItem(): # Not the root item, recurse again on it itemText = treeCtrl.GetItemText(parent) + "/" + itemText itemText = self.RecurseTopDir(treeCtrl, parent, itemText) return itemText
[ "def", "RecurseTopDir", "(", "self", ",", "treeCtrl", ",", "item", ",", "itemText", ")", ":", "# Get the item parent ", "parent", "=", "treeCtrl", ".", "GetItemParent", "(", "item", ")", "if", "parent", "!=", "treeCtrl", ".", "GetRootItem", "(", ")", ":", "# Not the root item, recurse again on it", "itemText", "=", "treeCtrl", ".", "GetItemText", "(", "parent", ")", "+", "\"/\"", "+", "itemText", "itemText", "=", "self", ".", "RecurseTopDir", "(", "treeCtrl", ",", "parent", ",", "itemText", ")", "return", "itemText" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/multidirdialog.py#L466-L482
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/saved_model/load.py
python
Loader._recreate
(self, proto, node_id, nodes)
Creates a Python object from a SavedObject protocol buffer. Args: proto: a SavedObject proto node_id: int, the index of this object in the SavedObjectGraph node list. nodes: dict mapping int node_ids -> created objects. Returns: The recreated object, and the set-attribute function for reconnecting the trackable children.
Creates a Python object from a SavedObject protocol buffer.
[ "Creates", "a", "Python", "object", "from", "a", "SavedObject", "protocol", "buffer", "." ]
def _recreate(self, proto, node_id, nodes): """Creates a Python object from a SavedObject protocol buffer. Args: proto: a SavedObject proto node_id: int, the index of this object in the SavedObjectGraph node list. nodes: dict mapping int node_ids -> created objects. Returns: The recreated object, and the set-attribute function for reconnecting the trackable children. """ registered_class = registration.get_registered_class(proto.registered_name) if registered_class is None: registered_class = _BUILT_IN_REGISTRATIONS.get(proto.WhichOneof("kind")) dependencies = {} for key, dep_node_id in self._get_node_dependencies(proto).items(): dependencies[key] = nodes[dep_node_id] if registered_class: obj = registered_class._deserialize_from_proto( # pylint: disable=protected-access proto=proto.serialized_user_proto, object_proto=proto, dependencies=dependencies, export_dir=self._export_dir, asset_file_def=self._asset_file_def) return obj, type(obj)._add_trackable_child # pylint: disable=protected-access else: return self._recreate_default(proto, node_id, dependencies)
[ "def", "_recreate", "(", "self", ",", "proto", ",", "node_id", ",", "nodes", ")", ":", "registered_class", "=", "registration", ".", "get_registered_class", "(", "proto", ".", "registered_name", ")", "if", "registered_class", "is", "None", ":", "registered_class", "=", "_BUILT_IN_REGISTRATIONS", ".", "get", "(", "proto", ".", "WhichOneof", "(", "\"kind\"", ")", ")", "dependencies", "=", "{", "}", "for", "key", ",", "dep_node_id", "in", "self", ".", "_get_node_dependencies", "(", "proto", ")", ".", "items", "(", ")", ":", "dependencies", "[", "key", "]", "=", "nodes", "[", "dep_node_id", "]", "if", "registered_class", ":", "obj", "=", "registered_class", ".", "_deserialize_from_proto", "(", "# pylint: disable=protected-access", "proto", "=", "proto", ".", "serialized_user_proto", ",", "object_proto", "=", "proto", ",", "dependencies", "=", "dependencies", ",", "export_dir", "=", "self", ".", "_export_dir", ",", "asset_file_def", "=", "self", ".", "_asset_file_def", ")", "return", "obj", ",", "type", "(", "obj", ")", ".", "_add_trackable_child", "# pylint: disable=protected-access", "else", ":", "return", "self", ".", "_recreate_default", "(", "proto", ",", "node_id", ",", "dependencies", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/saved_model/load.py#L558-L587
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/grid.py
python
GridStringTable.__init__
(self, *args, **kwargs)
__init__(self, int numRows=0, int numCols=0) -> GridStringTable
__init__(self, int numRows=0, int numCols=0) -> GridStringTable
[ "__init__", "(", "self", "int", "numRows", "=", "0", "int", "numCols", "=", "0", ")", "-", ">", "GridStringTable" ]
def __init__(self, *args, **kwargs): """__init__(self, int numRows=0, int numCols=0) -> GridStringTable""" _grid.GridStringTable_swiginit(self,_grid.new_GridStringTable(*args, **kwargs)) self._setOORInfo(self)
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_grid", ".", "GridStringTable_swiginit", "(", "self", ",", "_grid", ".", "new_GridStringTable", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", "self", ".", "_setOORInfo", "(", "self", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/grid.py#L1051-L1054
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/traci/_poi.py
python
PoiDomain.getColor
(self, poiID)
return self._getUniversal(tc.VAR_COLOR, poiID)
getColor(string) -> (integer, integer, integer, integer) Returns the rgba color of the given poi.
getColor(string) -> (integer, integer, integer, integer)
[ "getColor", "(", "string", ")", "-", ">", "(", "integer", "integer", "integer", "integer", ")" ]
def getColor(self, poiID): """getColor(string) -> (integer, integer, integer, integer) Returns the rgba color of the given poi. """ return self._getUniversal(tc.VAR_COLOR, poiID)
[ "def", "getColor", "(", "self", ",", "poiID", ")", ":", "return", "self", ".", "_getUniversal", "(", "tc", ".", "VAR_COLOR", ",", "poiID", ")" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/traci/_poi.py#L46-L51
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/protorpc/protorpc/descriptor.py
python
describe_field
(field_definition)
return field_descriptor
Build descriptor for Field instance. Args: field_definition: Field instance to provide descriptor for. Returns: Initialized FieldDescriptor instance describing the Field instance.
Build descriptor for Field instance.
[ "Build", "descriptor", "for", "Field", "instance", "." ]
def describe_field(field_definition): """Build descriptor for Field instance. Args: field_definition: Field instance to provide descriptor for. Returns: Initialized FieldDescriptor instance describing the Field instance. """ field_descriptor = FieldDescriptor() field_descriptor.name = field_definition.name field_descriptor.number = field_definition.number field_descriptor.variant = field_definition.variant if isinstance(field_definition, messages.EnumField): field_descriptor.type_name = field_definition.type.definition_name() if isinstance(field_definition, messages.MessageField): field_descriptor.type_name = field_definition.message_type.definition_name() if field_definition.default is not None: field_descriptor.default_value = _DEFAULT_TO_STRING_MAP[ type(field_definition)](field_definition.default) # Set label. if field_definition.repeated: field_descriptor.label = FieldDescriptor.Label.REPEATED elif field_definition.required: field_descriptor.label = FieldDescriptor.Label.REQUIRED else: field_descriptor.label = FieldDescriptor.Label.OPTIONAL return field_descriptor
[ "def", "describe_field", "(", "field_definition", ")", ":", "field_descriptor", "=", "FieldDescriptor", "(", ")", "field_descriptor", ".", "name", "=", "field_definition", ".", "name", "field_descriptor", ".", "number", "=", "field_definition", ".", "number", "field_descriptor", ".", "variant", "=", "field_definition", ".", "variant", "if", "isinstance", "(", "field_definition", ",", "messages", ".", "EnumField", ")", ":", "field_descriptor", ".", "type_name", "=", "field_definition", ".", "type", ".", "definition_name", "(", ")", "if", "isinstance", "(", "field_definition", ",", "messages", ".", "MessageField", ")", ":", "field_descriptor", ".", "type_name", "=", "field_definition", ".", "message_type", ".", "definition_name", "(", ")", "if", "field_definition", ".", "default", "is", "not", "None", ":", "field_descriptor", ".", "default_value", "=", "_DEFAULT_TO_STRING_MAP", "[", "type", "(", "field_definition", ")", "]", "(", "field_definition", ".", "default", ")", "# Set label.", "if", "field_definition", ".", "repeated", ":", "field_descriptor", ".", "label", "=", "FieldDescriptor", ".", "Label", ".", "REPEATED", "elif", "field_definition", ".", "required", ":", "field_descriptor", ".", "label", "=", "FieldDescriptor", ".", "Label", ".", "REQUIRED", "else", ":", "field_descriptor", ".", "label", "=", "FieldDescriptor", ".", "Label", ".", "OPTIONAL", "return", "field_descriptor" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/protorpc/protorpc/descriptor.py#L341-L373
continental/ecal
204dab80a24fe01abca62541133b311bf0c09608
lang/python/core/ecal/core/core.py
python
pub_set_qos_reliability
(topic_handle, qpolicy)
return _ecal.pub_set_qos_reliability(topic_handle, qpolicy)
set publisher quality of service reliability mode :param topic_handle: the topic handle :param qpolicy: 0 = best_effort_reliability_qos, 1 = reliable_reliability_qos :type qpolicy: int :param depth: history kind buffer depth
set publisher quality of service reliability mode
[ "set", "publisher", "quality", "of", "service", "reliability", "mode" ]
def pub_set_qos_reliability(topic_handle, qpolicy): """ set publisher quality of service reliability mode :param topic_handle: the topic handle :param qpolicy: 0 = best_effort_reliability_qos, 1 = reliable_reliability_qos :type qpolicy: int :param depth: history kind buffer depth """ return _ecal.pub_set_qos_reliability(topic_handle, qpolicy)
[ "def", "pub_set_qos_reliability", "(", "topic_handle", ",", "qpolicy", ")", ":", "return", "_ecal", ".", "pub_set_qos_reliability", "(", "topic_handle", ",", "qpolicy", ")" ]
https://github.com/continental/ecal/blob/204dab80a24fe01abca62541133b311bf0c09608/lang/python/core/ecal/core/core.py#L203-L213
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/coverage/coverage/collector.py
python
Collector.stop
(self)
Stop collecting trace information.
Stop collecting trace information.
[ "Stop", "collecting", "trace", "information", "." ]
def stop(self): """Stop collecting trace information.""" assert self._collectors assert self._collectors[-1] is self, ( "Expected current collector to be %r, but it's %r" % (self, self._collectors[-1]) ) self.pause() self.tracers = [] # Remove this Collector from the stack, and resume the one underneath # (if any). self._collectors.pop() if self._collectors: self._collectors[-1].resume()
[ "def", "stop", "(", "self", ")", ":", "assert", "self", ".", "_collectors", "assert", "self", ".", "_collectors", "[", "-", "1", "]", "is", "self", ",", "(", "\"Expected current collector to be %r, but it's %r\"", "%", "(", "self", ",", "self", ".", "_collectors", "[", "-", "1", "]", ")", ")", "self", ".", "pause", "(", ")", "self", ".", "tracers", "=", "[", "]", "# Remove this Collector from the stack, and resume the one underneath", "# (if any).", "self", ".", "_collectors", ".", "pop", "(", ")", "if", "self", ".", "_collectors", ":", "self", ".", "_collectors", "[", "-", "1", "]", ".", "resume", "(", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/coverage/coverage/collector.py#L273-L287
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/training/python/training/hparam.py
python
HParams.set_hparam
(self, name, value)
Set the value of an existing hyperparameter. This function verifies that the type of the value matches the type of the existing hyperparameter. Args: name: Name of the hyperparameter. value: New value of the hyperparameter. Raises: ValueError: If there is a type mismatch.
Set the value of an existing hyperparameter.
[ "Set", "the", "value", "of", "an", "existing", "hyperparameter", "." ]
def set_hparam(self, name, value): """Set the value of an existing hyperparameter. This function verifies that the type of the value matches the type of the existing hyperparameter. Args: name: Name of the hyperparameter. value: New value of the hyperparameter. Raises: ValueError: If there is a type mismatch. """ _, is_list = self._hparam_types[name] if isinstance(value, list): if not is_list: raise ValueError( 'Must not pass a list for single-valued parameter: %s' % name) setattr(self, name, value) else: if is_list: raise ValueError( 'Must pass a list for multi-valued parameter: %s.' % name) setattr(self, name, value)
[ "def", "set_hparam", "(", "self", ",", "name", ",", "value", ")", ":", "_", ",", "is_list", "=", "self", ".", "_hparam_types", "[", "name", "]", "if", "isinstance", "(", "value", ",", "list", ")", ":", "if", "not", "is_list", ":", "raise", "ValueError", "(", "'Must not pass a list for single-valued parameter: %s'", "%", "name", ")", "setattr", "(", "self", ",", "name", ",", "value", ")", "else", ":", "if", "is_list", ":", "raise", "ValueError", "(", "'Must pass a list for multi-valued parameter: %s.'", "%", "name", ")", "setattr", "(", "self", ",", "name", ",", "value", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/training/python/training/hparam.py#L428-L451
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/_vendor/ordered_set.py
python
OrderedSet.difference_update
(self, *sets)
Update this OrderedSet to remove items from one or more other sets. Example: >>> this = OrderedSet([1, 2, 3]) >>> this.difference_update(OrderedSet([2, 4])) >>> print(this) OrderedSet([1, 3]) >>> this = OrderedSet([1, 2, 3, 4, 5]) >>> this.difference_update(OrderedSet([2, 4]), OrderedSet([1, 4, 6])) >>> print(this) OrderedSet([3, 5])
Update this OrderedSet to remove items from one or more other sets.
[ "Update", "this", "OrderedSet", "to", "remove", "items", "from", "one", "or", "more", "other", "sets", "." ]
def difference_update(self, *sets): """ Update this OrderedSet to remove items from one or more other sets. Example: >>> this = OrderedSet([1, 2, 3]) >>> this.difference_update(OrderedSet([2, 4])) >>> print(this) OrderedSet([1, 3]) >>> this = OrderedSet([1, 2, 3, 4, 5]) >>> this.difference_update(OrderedSet([2, 4]), OrderedSet([1, 4, 6])) >>> print(this) OrderedSet([3, 5]) """ items_to_remove = set() for other in sets: items_to_remove |= set(other) self._update_items([item for item in self.items if item not in items_to_remove])
[ "def", "difference_update", "(", "self", ",", "*", "sets", ")", ":", "items_to_remove", "=", "set", "(", ")", "for", "other", "in", "sets", ":", "items_to_remove", "|=", "set", "(", "other", ")", "self", ".", "_update_items", "(", "[", "item", "for", "item", "in", "self", ".", "items", "if", "item", "not", "in", "items_to_remove", "]", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/_vendor/ordered_set.py#L437-L455
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/io/mmio.py
python
MMFile._open
(filespec, mode='rb')
return stream, close_it
Return an open file stream for reading based on source. If source is a file name, open it (after trying to find it with mtx and gzipped mtx extensions). Otherwise, just return source. Parameters ---------- filespec : str or file-like String giving file name or file-like object mode : str, optional Mode with which to open file, if `filespec` is a file name. Returns ------- fobj : file-like Open file-like object. close_it : bool True if the calling function should close this file when done, false otherwise.
Return an open file stream for reading based on source.
[ "Return", "an", "open", "file", "stream", "for", "reading", "based", "on", "source", "." ]
def _open(filespec, mode='rb'): """ Return an open file stream for reading based on source. If source is a file name, open it (after trying to find it with mtx and gzipped mtx extensions). Otherwise, just return source. Parameters ---------- filespec : str or file-like String giving file name or file-like object mode : str, optional Mode with which to open file, if `filespec` is a file name. Returns ------- fobj : file-like Open file-like object. close_it : bool True if the calling function should close this file when done, false otherwise. """ close_it = False if isinstance(filespec, string_types): close_it = True # open for reading if mode[0] == 'r': # determine filename plus extension if not os.path.isfile(filespec): if os.path.isfile(filespec+'.mtx'): filespec = filespec + '.mtx' elif os.path.isfile(filespec+'.mtx.gz'): filespec = filespec + '.mtx.gz' elif os.path.isfile(filespec+'.mtx.bz2'): filespec = filespec + '.mtx.bz2' # open filename if filespec.endswith('.gz'): import gzip stream = gzip.open(filespec, mode) elif filespec.endswith('.bz2'): import bz2 stream = bz2.BZ2File(filespec, 'rb') else: stream = open(filespec, mode) # open for writing else: if filespec[-4:] != '.mtx': filespec = filespec + '.mtx' stream = open(filespec, mode) else: stream = filespec return stream, close_it
[ "def", "_open", "(", "filespec", ",", "mode", "=", "'rb'", ")", ":", "close_it", "=", "False", "if", "isinstance", "(", "filespec", ",", "string_types", ")", ":", "close_it", "=", "True", "# open for reading", "if", "mode", "[", "0", "]", "==", "'r'", ":", "# determine filename plus extension", "if", "not", "os", ".", "path", ".", "isfile", "(", "filespec", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "filespec", "+", "'.mtx'", ")", ":", "filespec", "=", "filespec", "+", "'.mtx'", "elif", "os", ".", "path", ".", "isfile", "(", "filespec", "+", "'.mtx.gz'", ")", ":", "filespec", "=", "filespec", "+", "'.mtx.gz'", "elif", "os", ".", "path", ".", "isfile", "(", "filespec", "+", "'.mtx.bz2'", ")", ":", "filespec", "=", "filespec", "+", "'.mtx.bz2'", "# open filename", "if", "filespec", ".", "endswith", "(", "'.gz'", ")", ":", "import", "gzip", "stream", "=", "gzip", ".", "open", "(", "filespec", ",", "mode", ")", "elif", "filespec", ".", "endswith", "(", "'.bz2'", ")", ":", "import", "bz2", "stream", "=", "bz2", ".", "BZ2File", "(", "filespec", ",", "'rb'", ")", "else", ":", "stream", "=", "open", "(", "filespec", ",", "mode", ")", "# open for writing", "else", ":", "if", "filespec", "[", "-", "4", ":", "]", "!=", "'.mtx'", ":", "filespec", "=", "filespec", "+", "'.mtx'", "stream", "=", "open", "(", "filespec", ",", "mode", ")", "else", ":", "stream", "=", "filespec", "return", "stream", ",", "close_it" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/io/mmio.py#L269-L323
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/cookielib.py
python
CookieJar.__len__
(self)
return i
Return number of contained cookies.
Return number of contained cookies.
[ "Return", "number", "of", "contained", "cookies", "." ]
def __len__(self): """Return number of contained cookies.""" i = 0 for cookie in self: i = i + 1 return i
[ "def", "__len__", "(", "self", ")", ":", "i", "=", "0", "for", "cookie", "in", "self", ":", "i", "=", "i", "+", "1", "return", "i" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/cookielib.py#L1713-L1717
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/tokenize.py
python
tokenize
(readline, tokeneater=printtoken)
The tokenize() function accepts two parameters: one representing the input stream, and one providing an output mechanism for tokenize(). The first parameter, readline, must be a callable object which provides the same interface as the readline() method of built-in file objects. Each call to the function should return one line of input as a string. The second parameter, tokeneater, must also be a callable object. It is called once for each token, with five arguments, corresponding to the tuples generated by generate_tokens().
The tokenize() function accepts two parameters: one representing the input stream, and one providing an output mechanism for tokenize().
[ "The", "tokenize", "()", "function", "accepts", "two", "parameters", ":", "one", "representing", "the", "input", "stream", "and", "one", "providing", "an", "output", "mechanism", "for", "tokenize", "()", "." ]
def tokenize(readline, tokeneater=printtoken): """ The tokenize() function accepts two parameters: one representing the input stream, and one providing an output mechanism for tokenize(). The first parameter, readline, must be a callable object which provides the same interface as the readline() method of built-in file objects. Each call to the function should return one line of input as a string. The second parameter, tokeneater, must also be a callable object. It is called once for each token, with five arguments, corresponding to the tuples generated by generate_tokens(). """ try: tokenize_loop(readline, tokeneater) except StopTokenizing: pass
[ "def", "tokenize", "(", "readline", ",", "tokeneater", "=", "printtoken", ")", ":", "try", ":", "tokenize_loop", "(", "readline", ",", "tokeneater", ")", "except", "StopTokenizing", ":", "pass" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/tokenize.py#L155-L171
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Arch/ArchGrid.py
python
makeGrid
(name="Grid")
return obj
makeGrid(): makes a grid object
makeGrid(): makes a grid object
[ "makeGrid", "()", ":", "makes", "a", "grid", "object" ]
def makeGrid(name="Grid"): '''makeGrid(): makes a grid object''' obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Grid") obj.Label = translate("Arch",name) ArchGrid(obj) if FreeCAD.GuiUp: ViewProviderArchGrid(obj.ViewObject) obj.ViewObject.Transparency = 85 FreeCAD.ActiveDocument.recompute() return obj
[ "def", "makeGrid", "(", "name", "=", "\"Grid\"", ")", ":", "obj", "=", "FreeCAD", ".", "ActiveDocument", ".", "addObject", "(", "\"Part::FeaturePython\"", ",", "\"Grid\"", ")", "obj", ".", "Label", "=", "translate", "(", "\"Arch\"", ",", "name", ")", "ArchGrid", "(", "obj", ")", "if", "FreeCAD", ".", "GuiUp", ":", "ViewProviderArchGrid", "(", "obj", ".", "ViewObject", ")", "obj", ".", "ViewObject", ".", "Transparency", "=", "85", "FreeCAD", ".", "ActiveDocument", ".", "recompute", "(", ")", "return", "obj" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Arch/ArchGrid.py#L47-L58
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/_strptime.py
python
TimeRE.pattern
(self, format)
return "%s%s" % (processed_format, format)
Return regex pattern for the format string. Need to make sure that any characters that might be interpreted as regex syntax are escaped.
Return regex pattern for the format string.
[ "Return", "regex", "pattern", "for", "the", "format", "string", "." ]
def pattern(self, format): """Return regex pattern for the format string. Need to make sure that any characters that might be interpreted as regex syntax are escaped. """ processed_format = '' # The sub() call escapes all characters that might be misconstrued # as regex syntax. Cannot use re.escape since we have to deal with # format directives (%m, etc.). regex_chars = re_compile(r"([\\.^$*+?\(\){}\[\]|])") format = regex_chars.sub(r"\\\1", format) whitespace_replacement = re_compile('\s+') format = whitespace_replacement.sub('\s+', format) while '%' in format: directive_index = format.index('%')+1 processed_format = "%s%s%s" % (processed_format, format[:directive_index-1], self[format[directive_index]]) format = format[directive_index+1:] return "%s%s" % (processed_format, format)
[ "def", "pattern", "(", "self", ",", "format", ")", ":", "processed_format", "=", "''", "# The sub() call escapes all characters that might be misconstrued", "# as regex syntax. Cannot use re.escape since we have to deal with", "# format directives (%m, etc.).", "regex_chars", "=", "re_compile", "(", "r\"([\\\\.^$*+?\\(\\){}\\[\\]|])\"", ")", "format", "=", "regex_chars", ".", "sub", "(", "r\"\\\\\\1\"", ",", "format", ")", "whitespace_replacement", "=", "re_compile", "(", "'\\s+'", ")", "format", "=", "whitespace_replacement", ".", "sub", "(", "'\\s+'", ",", "format", ")", "while", "'%'", "in", "format", ":", "directive_index", "=", "format", ".", "index", "(", "'%'", ")", "+", "1", "processed_format", "=", "\"%s%s%s\"", "%", "(", "processed_format", ",", "format", "[", ":", "directive_index", "-", "1", "]", ",", "self", "[", "format", "[", "directive_index", "]", "]", ")", "format", "=", "format", "[", "directive_index", "+", "1", ":", "]", "return", "\"%s%s\"", "%", "(", "processed_format", ",", "format", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/_strptime.py#L240-L261
zju3dv/clean-pvnet
5870c509e3cc205e1bb28910a7b1a9a3c8add9a8
lib/utils/pysixd/view_sampler.py
python
save_vis
(path, views, views_level=None)
Creates a PLY file visualizing the views. :param path: Path to output PLY file. :param views: Views as returned by sample_views(). :param views_level: View levels as returned by sample_views(). :return: -
Creates a PLY file visualizing the views.
[ "Creates", "a", "PLY", "file", "visualizing", "the", "views", "." ]
def save_vis(path, views, views_level=None): ''' Creates a PLY file visualizing the views. :param path: Path to output PLY file. :param views: Views as returned by sample_views(). :param views_level: View levels as returned by sample_views(). :return: - ''' # Visualization (saved as a PLY file) pts = [] normals = [] colors = [] for view_id, view in enumerate(views): R_inv = np.linalg.inv(view['R']) pts += [R_inv.dot(-view['t']).squeeze(), # R_inv.dot(np.array([[0.01, 0, 0]]).T - view['t']).squeeze(), # R_inv.dot(np.array([[0, 0.01, 0]]).T - view['t']).squeeze(), # R_inv.dot(np.array([[0, 0, 0.01]]).T - view['t']).squeeze() ] normal = R_inv.dot(np.array([0, 0, 1]).reshape((3, 1))) normals += [normal.squeeze(), # np.array([0, 0, 0]), # np.array([0, 0, 0]), # np.array([0, 0, 0]) ] if views_level: intens = (255 * views_level[view_id]) / float(max(views_level)) else: intens = 255 * view_id / float(len(views)) colors += [[intens, intens, intens], # [255, 0, 0], # [0, 255, 0], # [0, 0, 255] ] inout.save_ply(path, pts=np.array(pts), pts_normals=np.array(normals), pts_colors=np.array(colors))
[ "def", "save_vis", "(", "path", ",", "views", ",", "views_level", "=", "None", ")", ":", "# Visualization (saved as a PLY file)", "pts", "=", "[", "]", "normals", "=", "[", "]", "colors", "=", "[", "]", "for", "view_id", ",", "view", "in", "enumerate", "(", "views", ")", ":", "R_inv", "=", "np", ".", "linalg", ".", "inv", "(", "view", "[", "'R'", "]", ")", "pts", "+=", "[", "R_inv", ".", "dot", "(", "-", "view", "[", "'t'", "]", ")", ".", "squeeze", "(", ")", ",", "# R_inv.dot(np.array([[0.01, 0, 0]]).T - view['t']).squeeze(),", "# R_inv.dot(np.array([[0, 0.01, 0]]).T - view['t']).squeeze(),", "# R_inv.dot(np.array([[0, 0, 0.01]]).T - view['t']).squeeze()", "]", "normal", "=", "R_inv", ".", "dot", "(", "np", ".", "array", "(", "[", "0", ",", "0", ",", "1", "]", ")", ".", "reshape", "(", "(", "3", ",", "1", ")", ")", ")", "normals", "+=", "[", "normal", ".", "squeeze", "(", ")", ",", "# np.array([0, 0, 0]),", "# np.array([0, 0, 0]),", "# np.array([0, 0, 0])", "]", "if", "views_level", ":", "intens", "=", "(", "255", "*", "views_level", "[", "view_id", "]", ")", "/", "float", "(", "max", "(", "views_level", ")", ")", "else", ":", "intens", "=", "255", "*", "view_id", "/", "float", "(", "len", "(", "views", ")", ")", "colors", "+=", "[", "[", "intens", ",", "intens", ",", "intens", "]", ",", "# [255, 0, 0],", "# [0, 255, 0],", "# [0, 0, 255]", "]", "inout", ".", "save_ply", "(", "path", ",", "pts", "=", "np", ".", "array", "(", "pts", ")", ",", "pts_normals", "=", "np", ".", "array", "(", "normals", ")", ",", "pts_colors", "=", "np", ".", "array", "(", "colors", ")", ")" ]
https://github.com/zju3dv/clean-pvnet/blob/5870c509e3cc205e1bb28910a7b1a9a3c8add9a8/lib/utils/pysixd/view_sampler.py#L232-L273
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/pseudo-palindromic-paths-in-a-binary-tree.py
python
Solution2.pseudoPalindromicPaths
(self, root)
return dfs(root, 0)
:type root: TreeNode :rtype: int
:type root: TreeNode :rtype: int
[ ":", "type", "root", ":", "TreeNode", ":", "rtype", ":", "int" ]
def pseudoPalindromicPaths (self, root): """ :type root: TreeNode :rtype: int """ def dfs(node, count): if not root: return 0 count ^= 1 << (node.val-1) return int(node.left == node.right and count&(count-1) == 0) + \ dfs(node.left, count) + dfs(node.right, count) return dfs(root, 0)
[ "def", "pseudoPalindromicPaths", "(", "self", ",", "root", ")", ":", "def", "dfs", "(", "node", ",", "count", ")", ":", "if", "not", "root", ":", "return", "0", "count", "^=", "1", "<<", "(", "node", ".", "val", "-", "1", ")", "return", "int", "(", "node", ".", "left", "==", "node", ".", "right", "and", "count", "&", "(", "count", "-", "1", ")", "==", "0", ")", "+", "dfs", "(", "node", ".", "left", ",", "count", ")", "+", "dfs", "(", "node", ".", "right", ",", "count", ")", "return", "dfs", "(", "root", ",", "0", ")" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/pseudo-palindromic-paths-in-a-binary-tree.py#L34-L45
alibaba/weex_js_engine
2bdf4b6f020c1fc99c63f649718f6faf7e27fdde
jni/v8core/v8/build/gyp/pylib/gyp/mac_tool.py
python
MacTool.ExecPackageFramework
(self, framework, version)
Takes a path to Something.framework and the Current version of that and sets up all the symlinks.
Takes a path to Something.framework and the Current version of that and sets up all the symlinks.
[ "Takes", "a", "path", "to", "Something", ".", "framework", "and", "the", "Current", "version", "of", "that", "and", "sets", "up", "all", "the", "symlinks", "." ]
def ExecPackageFramework(self, framework, version): """Takes a path to Something.framework and the Current version of that and sets up all the symlinks.""" # Find the name of the binary based on the part before the ".framework". binary = os.path.basename(framework).split('.')[0] CURRENT = 'Current' RESOURCES = 'Resources' VERSIONS = 'Versions' if not os.path.exists(os.path.join(framework, VERSIONS, version, binary)): # Binary-less frameworks don't seem to contain symlinks (see e.g. # chromium's out/Debug/org.chromium.Chromium.manifest/ bundle). return # Move into the framework directory to set the symlinks correctly. pwd = os.getcwd() os.chdir(framework) # Set up the Current version. self._Relink(version, os.path.join(VERSIONS, CURRENT)) # Set up the root symlinks. self._Relink(os.path.join(VERSIONS, CURRENT, binary), binary) self._Relink(os.path.join(VERSIONS, CURRENT, RESOURCES), RESOURCES) # Back to where we were before! os.chdir(pwd)
[ "def", "ExecPackageFramework", "(", "self", ",", "framework", ",", "version", ")", ":", "# Find the name of the binary based on the part before the \".framework\".", "binary", "=", "os", ".", "path", ".", "basename", "(", "framework", ")", ".", "split", "(", "'.'", ")", "[", "0", "]", "CURRENT", "=", "'Current'", "RESOURCES", "=", "'Resources'", "VERSIONS", "=", "'Versions'", "if", "not", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "framework", ",", "VERSIONS", ",", "version", ",", "binary", ")", ")", ":", "# Binary-less frameworks don't seem to contain symlinks (see e.g.", "# chromium's out/Debug/org.chromium.Chromium.manifest/ bundle).", "return", "# Move into the framework directory to set the symlinks correctly.", "pwd", "=", "os", ".", "getcwd", "(", ")", "os", ".", "chdir", "(", "framework", ")", "# Set up the Current version.", "self", ".", "_Relink", "(", "version", ",", "os", ".", "path", ".", "join", "(", "VERSIONS", ",", "CURRENT", ")", ")", "# Set up the root symlinks.", "self", ".", "_Relink", "(", "os", ".", "path", ".", "join", "(", "VERSIONS", ",", "CURRENT", ",", "binary", ")", ",", "binary", ")", "self", ".", "_Relink", "(", "os", ".", "path", ".", "join", "(", "VERSIONS", ",", "CURRENT", ",", "RESOURCES", ")", ",", "RESOURCES", ")", "# Back to where we were before!", "os", ".", "chdir", "(", "pwd", ")" ]
https://github.com/alibaba/weex_js_engine/blob/2bdf4b6f020c1fc99c63f649718f6faf7e27fdde/jni/v8core/v8/build/gyp/pylib/gyp/mac_tool.py#L172-L199
cornell-zhang/heterocl
6d9e4b4acc2ee2707b2d25b27298c0335bccedfd
python/heterocl/tvm/module.py
python
Module.imported_modules
(self)
return [_GetImport(self, i) for i in range(nmod)]
Get imported modules Returns ---------- modules : list of Module The module
Get imported modules
[ "Get", "imported", "modules" ]
def imported_modules(self): """Get imported modules Returns ---------- modules : list of Module The module """ nmod = _ImportsSize(self) return [_GetImport(self, i) for i in range(nmod)]
[ "def", "imported_modules", "(", "self", ")", ":", "nmod", "=", "_ImportsSize", "(", "self", ")", "return", "[", "_GetImport", "(", "self", ",", "i", ")", "for", "i", "in", "range", "(", "nmod", ")", "]" ]
https://github.com/cornell-zhang/heterocl/blob/6d9e4b4acc2ee2707b2d25b27298c0335bccedfd/python/heterocl/tvm/module.py#L50-L59
naver/sling
5671cd445a2caae0b4dd0332299e4cfede05062c
webkit/Tools/Scripts/webkitpy/thirdparty/irc/irclib.py
python
ServerConnection.remove_global_handler
(self, *args)
Remove global handler. See documentation for IRC.remove_global_handler.
Remove global handler.
[ "Remove", "global", "handler", "." ]
def remove_global_handler(self, *args): """Remove global handler. See documentation for IRC.remove_global_handler. """ self.irclibobj.remove_global_handler(*args)
[ "def", "remove_global_handler", "(", "self", ",", "*", "args", ")", ":", "self", ".", "irclibobj", ".", "remove_global_handler", "(", "*", "args", ")" ]
https://github.com/naver/sling/blob/5671cd445a2caae0b4dd0332299e4cfede05062c/webkit/Tools/Scripts/webkitpy/thirdparty/irc/irclib.py#L623-L628
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TFlt.SaveXml
(self, *args)
return _snap.TFlt_SaveXml(self, *args)
SaveXml(TFlt self, TSOut SOut, TStr Nm) Parameters: SOut: TSOut & Nm: TStr const &
SaveXml(TFlt self, TSOut SOut, TStr Nm)
[ "SaveXml", "(", "TFlt", "self", "TSOut", "SOut", "TStr", "Nm", ")" ]
def SaveXml(self, *args): """ SaveXml(TFlt self, TSOut SOut, TStr Nm) Parameters: SOut: TSOut & Nm: TStr const & """ return _snap.TFlt_SaveXml(self, *args)
[ "def", "SaveXml", "(", "self", ",", "*", "args", ")", ":", "return", "_snap", ".", "TFlt_SaveXml", "(", "self", ",", "*", "args", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L14265-L14274
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/smtplib.py
python
SMTP.send_message
(self, msg, from_addr=None, to_addrs=None, mail_options=(), rcpt_options=())
return self.sendmail(from_addr, to_addrs, flatmsg, mail_options, rcpt_options)
Converts message to a bytestring and passes it to sendmail. The arguments are as for sendmail, except that msg is an email.message.Message object. If from_addr is None or to_addrs is None, these arguments are taken from the headers of the Message as described in RFC 2822 (a ValueError is raised if there is more than one set of 'Resent-' headers). Regardless of the values of from_addr and to_addr, any Bcc field (or Resent-Bcc field, when the Message is a resent) of the Message object won't be transmitted. The Message object is then serialized using email.generator.BytesGenerator and sendmail is called to transmit the message. If the sender or any of the recipient addresses contain non-ASCII and the server advertises the SMTPUTF8 capability, the policy is cloned with utf8 set to True for the serialization, and SMTPUTF8 and BODY=8BITMIME are asserted on the send. If the server does not support SMTPUTF8, an SMTPNotSupported error is raised. Otherwise the generator is called without modifying the policy.
Converts message to a bytestring and passes it to sendmail.
[ "Converts", "message", "to", "a", "bytestring", "and", "passes", "it", "to", "sendmail", "." ]
def send_message(self, msg, from_addr=None, to_addrs=None, mail_options=(), rcpt_options=()): """Converts message to a bytestring and passes it to sendmail. The arguments are as for sendmail, except that msg is an email.message.Message object. If from_addr is None or to_addrs is None, these arguments are taken from the headers of the Message as described in RFC 2822 (a ValueError is raised if there is more than one set of 'Resent-' headers). Regardless of the values of from_addr and to_addr, any Bcc field (or Resent-Bcc field, when the Message is a resent) of the Message object won't be transmitted. The Message object is then serialized using email.generator.BytesGenerator and sendmail is called to transmit the message. If the sender or any of the recipient addresses contain non-ASCII and the server advertises the SMTPUTF8 capability, the policy is cloned with utf8 set to True for the serialization, and SMTPUTF8 and BODY=8BITMIME are asserted on the send. If the server does not support SMTPUTF8, an SMTPNotSupported error is raised. Otherwise the generator is called without modifying the policy. """ # 'Resent-Date' is a mandatory field if the Message is resent (RFC 2822 # Section 3.6.6). In such a case, we use the 'Resent-*' fields. However, # if there is more than one 'Resent-' block there's no way to # unambiguously determine which one is the most recent in all cases, # so rather than guess we raise a ValueError in that case. # # TODO implement heuristics to guess the correct Resent-* block with an # option allowing the user to enable the heuristics. (It should be # possible to guess correctly almost all of the time.) self.ehlo_or_helo_if_needed() resent = msg.get_all('Resent-Date') if resent is None: header_prefix = '' elif len(resent) == 1: header_prefix = 'Resent-' else: raise ValueError("message has more than one 'Resent-' header block") if from_addr is None: # Prefer the sender field per RFC 2822:3.6.2. from_addr = (msg[header_prefix + 'Sender'] if (header_prefix + 'Sender') in msg else msg[header_prefix + 'From']) from_addr = email.utils.getaddresses([from_addr])[0][1] if to_addrs is None: addr_fields = [f for f in (msg[header_prefix + 'To'], msg[header_prefix + 'Bcc'], msg[header_prefix + 'Cc']) if f is not None] to_addrs = [a[1] for a in email.utils.getaddresses(addr_fields)] # Make a local copy so we can delete the bcc headers. msg_copy = copy.copy(msg) del msg_copy['Bcc'] del msg_copy['Resent-Bcc'] international = False try: ''.join([from_addr, *to_addrs]).encode('ascii') except UnicodeEncodeError: if not self.has_extn('smtputf8'): raise SMTPNotSupportedError( "One or more source or delivery addresses require" " internationalized email support, but the server" " does not advertise the required SMTPUTF8 capability") international = True with io.BytesIO() as bytesmsg: if international: g = email.generator.BytesGenerator( bytesmsg, policy=msg.policy.clone(utf8=True)) mail_options = (*mail_options, 'SMTPUTF8', 'BODY=8BITMIME') else: g = email.generator.BytesGenerator(bytesmsg) g.flatten(msg_copy, linesep='\r\n') flatmsg = bytesmsg.getvalue() return self.sendmail(from_addr, to_addrs, flatmsg, mail_options, rcpt_options)
[ "def", "send_message", "(", "self", ",", "msg", ",", "from_addr", "=", "None", ",", "to_addrs", "=", "None", ",", "mail_options", "=", "(", ")", ",", "rcpt_options", "=", "(", ")", ")", ":", "# 'Resent-Date' is a mandatory field if the Message is resent (RFC 2822", "# Section 3.6.6). In such a case, we use the 'Resent-*' fields. However,", "# if there is more than one 'Resent-' block there's no way to", "# unambiguously determine which one is the most recent in all cases,", "# so rather than guess we raise a ValueError in that case.", "#", "# TODO implement heuristics to guess the correct Resent-* block with an", "# option allowing the user to enable the heuristics. (It should be", "# possible to guess correctly almost all of the time.)", "self", ".", "ehlo_or_helo_if_needed", "(", ")", "resent", "=", "msg", ".", "get_all", "(", "'Resent-Date'", ")", "if", "resent", "is", "None", ":", "header_prefix", "=", "''", "elif", "len", "(", "resent", ")", "==", "1", ":", "header_prefix", "=", "'Resent-'", "else", ":", "raise", "ValueError", "(", "\"message has more than one 'Resent-' header block\"", ")", "if", "from_addr", "is", "None", ":", "# Prefer the sender field per RFC 2822:3.6.2.", "from_addr", "=", "(", "msg", "[", "header_prefix", "+", "'Sender'", "]", "if", "(", "header_prefix", "+", "'Sender'", ")", "in", "msg", "else", "msg", "[", "header_prefix", "+", "'From'", "]", ")", "from_addr", "=", "email", ".", "utils", ".", "getaddresses", "(", "[", "from_addr", "]", ")", "[", "0", "]", "[", "1", "]", "if", "to_addrs", "is", "None", ":", "addr_fields", "=", "[", "f", "for", "f", "in", "(", "msg", "[", "header_prefix", "+", "'To'", "]", ",", "msg", "[", "header_prefix", "+", "'Bcc'", "]", ",", "msg", "[", "header_prefix", "+", "'Cc'", "]", ")", "if", "f", "is", "not", "None", "]", "to_addrs", "=", "[", "a", "[", "1", "]", "for", "a", "in", "email", ".", "utils", ".", "getaddresses", "(", "addr_fields", ")", "]", "# Make a local copy so we can delete the bcc headers.", "msg_copy", "=", "copy", ".", "copy", "(", "msg", ")", "del", "msg_copy", "[", "'Bcc'", "]", "del", "msg_copy", "[", "'Resent-Bcc'", "]", "international", "=", "False", "try", ":", "''", ".", "join", "(", "[", "from_addr", ",", "*", "to_addrs", "]", ")", ".", "encode", "(", "'ascii'", ")", "except", "UnicodeEncodeError", ":", "if", "not", "self", ".", "has_extn", "(", "'smtputf8'", ")", ":", "raise", "SMTPNotSupportedError", "(", "\"One or more source or delivery addresses require\"", "\" internationalized email support, but the server\"", "\" does not advertise the required SMTPUTF8 capability\"", ")", "international", "=", "True", "with", "io", ".", "BytesIO", "(", ")", "as", "bytesmsg", ":", "if", "international", ":", "g", "=", "email", ".", "generator", ".", "BytesGenerator", "(", "bytesmsg", ",", "policy", "=", "msg", ".", "policy", ".", "clone", "(", "utf8", "=", "True", ")", ")", "mail_options", "=", "(", "*", "mail_options", ",", "'SMTPUTF8'", ",", "'BODY=8BITMIME'", ")", "else", ":", "g", "=", "email", ".", "generator", ".", "BytesGenerator", "(", "bytesmsg", ")", "g", ".", "flatten", "(", "msg_copy", ",", "linesep", "=", "'\\r\\n'", ")", "flatmsg", "=", "bytesmsg", ".", "getvalue", "(", ")", "return", "self", ".", "sendmail", "(", "from_addr", ",", "to_addrs", ",", "flatmsg", ",", "mail_options", ",", "rcpt_options", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/smtplib.py#L892-L967
bulletphysics/bullet3
f0f2a952e146f016096db6f85cf0c44ed75b0b9a
examples/pybullet/gym/pybullet_envs/examples/minitaur_gym_env_example.py
python
SineStandExample
()
An example of minitaur standing and squatting on the floor. To validate the accurate motor model we command the robot and sit and stand up periodically in both simulation and experiment. We compare the measured motor trajectories, torques and gains.
An example of minitaur standing and squatting on the floor.
[ "An", "example", "of", "minitaur", "standing", "and", "squatting", "on", "the", "floor", "." ]
def SineStandExample(): """An example of minitaur standing and squatting on the floor. To validate the accurate motor model we command the robot and sit and stand up periodically in both simulation and experiment. We compare the measured motor trajectories, torques and gains. """ environment = minitaur_gym_env.MinitaurBulletEnv(render=True, leg_model_enabled=False, motor_velocity_limit=np.inf, motor_overheat_protection=True, accurate_motor_model_enabled=True, motor_kp=1.20, motor_kd=0.02, on_rack=False) steps = 1000 amplitude = 0.5 speed = 3 actions_and_observations = [] for step_counter in range(steps): # Matches the internal timestep. time_step = 0.01 t = step_counter * time_step current_row = [t] action = [math.sin(speed * t) * amplitude + math.pi / 2] * 8 current_row.extend(action) observation, _, _, _ = environment.step(action) current_row.extend(observation.tolist()) actions_and_observations.append(current_row) environment.reset()
[ "def", "SineStandExample", "(", ")", ":", "environment", "=", "minitaur_gym_env", ".", "MinitaurBulletEnv", "(", "render", "=", "True", ",", "leg_model_enabled", "=", "False", ",", "motor_velocity_limit", "=", "np", ".", "inf", ",", "motor_overheat_protection", "=", "True", ",", "accurate_motor_model_enabled", "=", "True", ",", "motor_kp", "=", "1.20", ",", "motor_kd", "=", "0.02", ",", "on_rack", "=", "False", ")", "steps", "=", "1000", "amplitude", "=", "0.5", "speed", "=", "3", "actions_and_observations", "=", "[", "]", "for", "step_counter", "in", "range", "(", "steps", ")", ":", "# Matches the internal timestep.", "time_step", "=", "0.01", "t", "=", "step_counter", "*", "time_step", "current_row", "=", "[", "t", "]", "action", "=", "[", "math", ".", "sin", "(", "speed", "*", "t", ")", "*", "amplitude", "+", "math", ".", "pi", "/", "2", "]", "*", "8", "current_row", ".", "extend", "(", "action", ")", "observation", ",", "_", ",", "_", ",", "_", "=", "environment", ".", "step", "(", "action", ")", "current_row", ".", "extend", "(", "observation", ".", "tolist", "(", ")", ")", "actions_and_observations", ".", "append", "(", "current_row", ")", "environment", ".", "reset", "(", ")" ]
https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/examples/minitaur_gym_env_example.py#L72-L106
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/email/mime/multipart.py
python
MIMEMultipart.__init__
(self, _subtype='mixed', boundary=None, _subparts=None, **_params)
Creates a multipart/* type message. By default, creates a multipart/mixed message, with proper Content-Type and MIME-Version headers. _subtype is the subtype of the multipart content type, defaulting to `mixed'. boundary is the multipart boundary string. By default it is calculated as needed. _subparts is a sequence of initial subparts for the payload. It must be an iterable object, such as a list. You can always attach new subparts to the message by using the attach() method. Additional parameters for the Content-Type header are taken from the keyword arguments (or passed into the _params argument).
Creates a multipart/* type message.
[ "Creates", "a", "multipart", "/", "*", "type", "message", "." ]
def __init__(self, _subtype='mixed', boundary=None, _subparts=None, **_params): """Creates a multipart/* type message. By default, creates a multipart/mixed message, with proper Content-Type and MIME-Version headers. _subtype is the subtype of the multipart content type, defaulting to `mixed'. boundary is the multipart boundary string. By default it is calculated as needed. _subparts is a sequence of initial subparts for the payload. It must be an iterable object, such as a list. You can always attach new subparts to the message by using the attach() method. Additional parameters for the Content-Type header are taken from the keyword arguments (or passed into the _params argument). """ MIMEBase.__init__(self, 'multipart', _subtype, **_params) # Initialise _payload to an empty list as the Message superclass's # implementation of is_multipart assumes that _payload is a list for # multipart messages. self._payload = [] if _subparts: for p in _subparts: self.attach(p) if boundary: self.set_boundary(boundary)
[ "def", "__init__", "(", "self", ",", "_subtype", "=", "'mixed'", ",", "boundary", "=", "None", ",", "_subparts", "=", "None", ",", "*", "*", "_params", ")", ":", "MIMEBase", ".", "__init__", "(", "self", ",", "'multipart'", ",", "_subtype", ",", "*", "*", "_params", ")", "# Initialise _payload to an empty list as the Message superclass's", "# implementation of is_multipart assumes that _payload is a list for", "# multipart messages.", "self", ".", "_payload", "=", "[", "]", "if", "_subparts", ":", "for", "p", "in", "_subparts", ":", "self", ".", "attach", "(", "p", ")", "if", "boundary", ":", "self", ".", "set_boundary", "(", "boundary", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/email/mime/multipart.py#L16-L47
apache/mesos
97d9a4063332aae3825d78de71611657e05cf5e2
src/python/cli_new/lib/cli/mesos.py
python
get_frameworks
(master, config)
return get_key_endpoint(key, endpoint, master, config)
Get the frameworks in a Mesos cluster.
Get the frameworks in a Mesos cluster.
[ "Get", "the", "frameworks", "in", "a", "Mesos", "cluster", "." ]
def get_frameworks(master, config): """ Get the frameworks in a Mesos cluster. """ endpoint = "master/frameworks/" key = "frameworks" return get_key_endpoint(key, endpoint, master, config)
[ "def", "get_frameworks", "(", "master", ",", "config", ")", ":", "endpoint", "=", "\"master/frameworks/\"", "key", "=", "\"frameworks\"", "return", "get_key_endpoint", "(", "key", ",", "endpoint", ",", "master", ",", "config", ")" ]
https://github.com/apache/mesos/blob/97d9a4063332aae3825d78de71611657e05cf5e2/src/python/cli_new/lib/cli/mesos.py#L82-L88
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/coverage/coverage/execfile.py
python
make_code_from_py
(filename)
return code
Get source from `filename` and make a code object of it.
Get source from `filename` and make a code object of it.
[ "Get", "source", "from", "filename", "and", "make", "a", "code", "object", "of", "it", "." ]
def make_code_from_py(filename): """Get source from `filename` and make a code object of it.""" # Open the source file. try: source = get_python_source(filename) except (IOError, NoSource): raise NoSource("No file to run: '%s'" % filename) code = compile_unicode(source, filename, "exec") return code
[ "def", "make_code_from_py", "(", "filename", ")", ":", "# Open the source file.", "try", ":", "source", "=", "get_python_source", "(", "filename", ")", "except", "(", "IOError", ",", "NoSource", ")", ":", "raise", "NoSource", "(", "\"No file to run: '%s'\"", "%", "filename", ")", "code", "=", "compile_unicode", "(", "source", ",", "filename", ",", "\"exec\"", ")", "return", "code" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/coverage/coverage/execfile.py#L204-L213
tum-vision/fusenet
a1451be2971b348a01b0f525c2a3a7a0e215a591
python/caffe/draw.py
python
choose_color_by_layertype
(layertype)
return color
Define colors for nodes based on the layer type.
Define colors for nodes based on the layer type.
[ "Define", "colors", "for", "nodes", "based", "on", "the", "layer", "type", "." ]
def choose_color_by_layertype(layertype): """Define colors for nodes based on the layer type. """ color = '#6495ED' # Default if layertype == 'Convolution' or layertype == 'Deconvolution': color = '#FF5050' elif layertype == 'Pooling': color = '#FF9900' elif layertype == 'InnerProduct': color = '#CC33FF' return color
[ "def", "choose_color_by_layertype", "(", "layertype", ")", ":", "color", "=", "'#6495ED'", "# Default", "if", "layertype", "==", "'Convolution'", "or", "layertype", "==", "'Deconvolution'", ":", "color", "=", "'#FF5050'", "elif", "layertype", "==", "'Pooling'", ":", "color", "=", "'#FF9900'", "elif", "layertype", "==", "'InnerProduct'", ":", "color", "=", "'#CC33FF'", "return", "color" ]
https://github.com/tum-vision/fusenet/blob/a1451be2971b348a01b0f525c2a3a7a0e215a591/python/caffe/draw.py#L117-L127
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py
python
uCSIsSinhala
(code)
return ret
Check whether the character is part of Sinhala UCS Block
Check whether the character is part of Sinhala UCS Block
[ "Check", "whether", "the", "character", "is", "part", "of", "Sinhala", "UCS", "Block" ]
def uCSIsSinhala(code): """Check whether the character is part of Sinhala UCS Block """ ret = libxml2mod.xmlUCSIsSinhala(code) return ret
[ "def", "uCSIsSinhala", "(", "code", ")", ":", "ret", "=", "libxml2mod", ".", "xmlUCSIsSinhala", "(", "code", ")", "return", "ret" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L2056-L2059
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/train/train_thor/convert_utils.py
python
ConvertNetUtils._convert_embedding
(subcell)
return new_subcell
Convert embedding cell to second-order cell
Convert embedding cell to second-order cell
[ "Convert", "embedding", "cell", "to", "second", "-", "order", "cell" ]
def _convert_embedding(subcell): """ Convert embedding cell to second-order cell """ new_subcell = nn.EmbeddingThor(vocab_size=subcell.vocab_size, embedding_size=subcell.embedding_size, use_one_hot=False) new_subcell.embedding_table = subcell.embedding_table return new_subcell
[ "def", "_convert_embedding", "(", "subcell", ")", ":", "new_subcell", "=", "nn", ".", "EmbeddingThor", "(", "vocab_size", "=", "subcell", ".", "vocab_size", ",", "embedding_size", "=", "subcell", ".", "embedding_size", ",", "use_one_hot", "=", "False", ")", "new_subcell", ".", "embedding_table", "=", "subcell", ".", "embedding_table", "return", "new_subcell" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/train/train_thor/convert_utils.py#L70-L78
facebook/wangle
2e7e3fbb3a15c4986d6fe0e36c31daeeba614ce3
build/fbcode_builder/getdeps/envfuncs.py
python
path_search
(env, exename, defval=None)
return result
Search for exename in the PATH specified in env. exename is eg: `ninja` and this function knows to append a .exe to the end on windows. Returns the path to the exe if found, or None if either no PATH is set in env or no executable is found.
Search for exename in the PATH specified in env. exename is eg: `ninja` and this function knows to append a .exe to the end on windows. Returns the path to the exe if found, or None if either no PATH is set in env or no executable is found.
[ "Search", "for", "exename", "in", "the", "PATH", "specified", "in", "env", ".", "exename", "is", "eg", ":", "ninja", "and", "this", "function", "knows", "to", "append", "a", ".", "exe", "to", "the", "end", "on", "windows", ".", "Returns", "the", "path", "to", "the", "exe", "if", "found", "or", "None", "if", "either", "no", "PATH", "is", "set", "in", "env", "or", "no", "executable", "is", "found", "." ]
def path_search(env, exename, defval=None): """Search for exename in the PATH specified in env. exename is eg: `ninja` and this function knows to append a .exe to the end on windows. Returns the path to the exe if found, or None if either no PATH is set in env or no executable is found.""" path = env.get("PATH", None) if path is None: return defval # The project hash computation code searches for C++ compilers (g++, clang, etc) # repeatedly. Cache the result so we don't end up searching for these over and over # again. cache_key = (path, exename) result = _path_search_cache.get(cache_key, _not_found) if result is _not_found: result = _perform_path_search(path, exename) _path_search_cache[cache_key] = result return result
[ "def", "path_search", "(", "env", ",", "exename", ",", "defval", "=", "None", ")", ":", "path", "=", "env", ".", "get", "(", "\"PATH\"", ",", "None", ")", "if", "path", "is", "None", ":", "return", "defval", "# The project hash computation code searches for C++ compilers (g++, clang, etc)", "# repeatedly. Cache the result so we don't end up searching for these over and over", "# again.", "cache_key", "=", "(", "path", ",", "exename", ")", "result", "=", "_path_search_cache", ".", "get", "(", "cache_key", ",", "_not_found", ")", "if", "result", "is", "_not_found", ":", "result", "=", "_perform_path_search", "(", "path", ",", "exename", ")", "_path_search_cache", "[", "cache_key", "]", "=", "result", "return", "result" ]
https://github.com/facebook/wangle/blob/2e7e3fbb3a15c4986d6fe0e36c31daeeba614ce3/build/fbcode_builder/getdeps/envfuncs.py#L159-L178
grpc/grpc
27bc6fe7797e43298dc931b96dc57322d0852a9f
examples/python/route_guide/route_guide_server.py
python
get_feature
(feature_db, point)
return None
Returns Feature at given location or None.
Returns Feature at given location or None.
[ "Returns", "Feature", "at", "given", "location", "or", "None", "." ]
def get_feature(feature_db, point): """Returns Feature at given location or None.""" for feature in feature_db: if feature.location == point: return feature return None
[ "def", "get_feature", "(", "feature_db", ",", "point", ")", ":", "for", "feature", "in", "feature_db", ":", "if", "feature", ".", "location", "==", "point", ":", "return", "feature", "return", "None" ]
https://github.com/grpc/grpc/blob/27bc6fe7797e43298dc931b96dc57322d0852a9f/examples/python/route_guide/route_guide_server.py#L27-L32
openvinotoolkit/openvino
dedcbeafa8b84cccdc55ca64b8da516682b381c7
tools/mo/openvino/tools/mo/back/ReverseInputChannels.py
python
ReverseChannelsPropagationUp.lift_up_through_eltwise
(node: Node, reverse_channels: Node)
return True, copies
r""" BEFORE AFTER previous_op previous_op' \ / previous_op previous_op' ReverseChannels ReverseChannels \ / \ / Eltwise Eltwise | | ReverseChannels next_op | next_op returns two objects: first - boolean value whatever we should continue propagating current ReverseChannels operation up or not second - list of new ReverseChannels operations that were produced while propagating reverse_channels up
r""" BEFORE AFTER
[ "r", "BEFORE", "AFTER" ]
def lift_up_through_eltwise(node: Node, reverse_channels: Node): r""" BEFORE AFTER previous_op previous_op' \ / previous_op previous_op' ReverseChannels ReverseChannels \ / \ / Eltwise Eltwise | | ReverseChannels next_op | next_op returns two objects: first - boolean value whatever we should continue propagating current ReverseChannels operation up or not second - list of new ReverseChannels operations that were produced while propagating reverse_channels up """ before_shape = reverse_channels.in_port(0).data.get_shape() port_axis = [] for idx, port in node.in_ports().items(): shape = port.data.get_shape() non_one_dims = np.where(shape != 1)[0] if shape[reverse_channels.axis] == 1: continue # nothing to flip for this input if len(non_one_dims) == 1 and shape[non_one_dims.item()] == reverse_channels.order.size: axis = non_one_dims.item() elif np.array_equal(before_shape, shape): axis = reverse_channels.axis else: # shape has multiple non-one values and shape is not fully broadcasted to value port shape # it is safe not to propagate reverse channels return False, [] port_axis.append((port, axis)) copies = [] for port, axis in port_axis: reverse_channels_copy = reverse_channels.copy_node({'axis': mo_array(axis)}) src = port.get_connection().get_source() if src.node.soft_get('type') == 'Parameter': # For Parameter nodes tensor debug attributes should not move to the last node # of subgraph. It is needed for the proper mapping of input framework name. # For this reason "source" mode is used to keep tensor debug attributes at Parameter node. port.get_connection().set_source(reverse_channels_copy.out_port(0), attributes_save_mode="source") else: port.get_connection().set_source(reverse_channels_copy.out_port(0)) src.connect(reverse_channels_copy.in_port(0)) copies.append(reverse_channels_copy) reverse_channels.out_port(0).get_connection().set_source( reverse_channels.in_port(0).get_connection().get_source()) reverse_channels.in_port(0).disconnect() # propagated reverse_channels successfully through current node, will continue propagation return True, copies
[ "def", "lift_up_through_eltwise", "(", "node", ":", "Node", ",", "reverse_channels", ":", "Node", ")", ":", "before_shape", "=", "reverse_channels", ".", "in_port", "(", "0", ")", ".", "data", ".", "get_shape", "(", ")", "port_axis", "=", "[", "]", "for", "idx", ",", "port", "in", "node", ".", "in_ports", "(", ")", ".", "items", "(", ")", ":", "shape", "=", "port", ".", "data", ".", "get_shape", "(", ")", "non_one_dims", "=", "np", ".", "where", "(", "shape", "!=", "1", ")", "[", "0", "]", "if", "shape", "[", "reverse_channels", ".", "axis", "]", "==", "1", ":", "continue", "# nothing to flip for this input", "if", "len", "(", "non_one_dims", ")", "==", "1", "and", "shape", "[", "non_one_dims", ".", "item", "(", ")", "]", "==", "reverse_channels", ".", "order", ".", "size", ":", "axis", "=", "non_one_dims", ".", "item", "(", ")", "elif", "np", ".", "array_equal", "(", "before_shape", ",", "shape", ")", ":", "axis", "=", "reverse_channels", ".", "axis", "else", ":", "# shape has multiple non-one values and shape is not fully broadcasted to value port shape", "# it is safe not to propagate reverse channels", "return", "False", ",", "[", "]", "port_axis", ".", "append", "(", "(", "port", ",", "axis", ")", ")", "copies", "=", "[", "]", "for", "port", ",", "axis", "in", "port_axis", ":", "reverse_channels_copy", "=", "reverse_channels", ".", "copy_node", "(", "{", "'axis'", ":", "mo_array", "(", "axis", ")", "}", ")", "src", "=", "port", ".", "get_connection", "(", ")", ".", "get_source", "(", ")", "if", "src", ".", "node", ".", "soft_get", "(", "'type'", ")", "==", "'Parameter'", ":", "# For Parameter nodes tensor debug attributes should not move to the last node", "# of subgraph. It is needed for the proper mapping of input framework name.", "# For this reason \"source\" mode is used to keep tensor debug attributes at Parameter node.", "port", ".", "get_connection", "(", ")", ".", "set_source", "(", "reverse_channels_copy", ".", "out_port", "(", "0", ")", ",", "attributes_save_mode", "=", "\"source\"", ")", "else", ":", "port", ".", "get_connection", "(", ")", ".", "set_source", "(", "reverse_channels_copy", ".", "out_port", "(", "0", ")", ")", "src", ".", "connect", "(", "reverse_channels_copy", ".", "in_port", "(", "0", ")", ")", "copies", ".", "append", "(", "reverse_channels_copy", ")", "reverse_channels", ".", "out_port", "(", "0", ")", ".", "get_connection", "(", ")", ".", "set_source", "(", "reverse_channels", ".", "in_port", "(", "0", ")", ".", "get_connection", "(", ")", ".", "get_source", "(", ")", ")", "reverse_channels", ".", "in_port", "(", "0", ")", ".", "disconnect", "(", ")", "# propagated reverse_channels successfully through current node, will continue propagation", "return", "True", ",", "copies" ]
https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/mo/openvino/tools/mo/back/ReverseInputChannels.py#L424-L482
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/graphy/graphy/backends/google_chart_api/util.py
python
ScaleData
(data, old_min, old_max, new_min, new_max)
return map(ScalePoint, data)
Scale the input data so that the range old_min-old_max maps to new_min-new_max.
Scale the input data so that the range old_min-old_max maps to new_min-new_max.
[ "Scale", "the", "input", "data", "so", "that", "the", "range", "old_min", "-", "old_max", "maps", "to", "new_min", "-", "new_max", "." ]
def ScaleData(data, old_min, old_max, new_min, new_max): """Scale the input data so that the range old_min-old_max maps to new_min-new_max. """ def ScalePoint(x): if x is None: return None return scale * x + translate if old_min == old_max: scale = 1 else: scale = (new_max - new_min) / float(old_max - old_min) translate = new_min - scale * old_min return map(ScalePoint, data)
[ "def", "ScaleData", "(", "data", ",", "old_min", ",", "old_max", ",", "new_min", ",", "new_max", ")", ":", "def", "ScalePoint", "(", "x", ")", ":", "if", "x", "is", "None", ":", "return", "None", "return", "scale", "*", "x", "+", "translate", "if", "old_min", "==", "old_max", ":", "scale", "=", "1", "else", ":", "scale", "=", "(", "new_max", "-", "new_min", ")", "/", "float", "(", "old_max", "-", "old_min", ")", "translate", "=", "new_min", "-", "scale", "*", "old_min", "return", "map", "(", "ScalePoint", ",", "data", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/graphy/graphy/backends/google_chart_api/util.py#L217-L231
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py
python
Text.compare
(self, index1, op, index2)
return self.tk.getboolean(self.tk.call( self._w, 'compare', index1, op, index2))
Return whether between index INDEX1 and index INDEX2 the relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=.
Return whether between index INDEX1 and index INDEX2 the relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=.
[ "Return", "whether", "between", "index", "INDEX1", "and", "index", "INDEX2", "the", "relation", "OP", "is", "satisfied", ".", "OP", "is", "one", "of", "<", "<", "=", "==", ">", "=", ">", "or", "!", "=", "." ]
def compare(self, index1, op, index2): """Return whether between index INDEX1 and index INDEX2 the relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=.""" return self.tk.getboolean(self.tk.call( self._w, 'compare', index1, op, index2))
[ "def", "compare", "(", "self", ",", "index1", ",", "op", ",", "index2", ")", ":", "return", "self", ".", "tk", ".", "getboolean", "(", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "'compare'", ",", "index1", ",", "op", ",", "index2", ")", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py#L2903-L2907
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/stc.py
python
StyledTextCtrl.PageUpExtend
(*args, **kwargs)
return _stc.StyledTextCtrl_PageUpExtend(*args, **kwargs)
PageUpExtend(self) Move caret one page up extending selection to new caret position.
PageUpExtend(self)
[ "PageUpExtend", "(", "self", ")" ]
def PageUpExtend(*args, **kwargs): """ PageUpExtend(self) Move caret one page up extending selection to new caret position. """ return _stc.StyledTextCtrl_PageUpExtend(*args, **kwargs)
[ "def", "PageUpExtend", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_PageUpExtend", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/stc.py#L4497-L4503
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/framework/ops.py
python
Graph.device
(self, device_name_or_function)
Returns a context manager that specifies the default device to use. The `device_name_or_function` argument may either be a device name string, a device function, or None: * If it is a device name string, all operations constructed in this context will be assigned to the device with that name, unless overridden by a nested `device()` context. * If it is a function, it will be treated as a function from Operation objects to device name strings, and invoked each time a new Operation is created. The Operation will be assigned to the device with the returned name. * If it is None, all `device()` invocations from the enclosing context will be ignored. For information about the valid syntax of device name strings, see the documentation in [`DeviceNameUtils`](https://www.tensorflow.org/code/tensorflow/core/util/device_name_utils.h). For example: ```python with g.device('/device:GPU:0'): # All operations constructed in this context will be placed # on GPU 0. with g.device(None): # All operations constructed in this context will have no # assigned device. # Defines a function from `Operation` to device string. def matmul_on_gpu(n): if n.type == "MatMul": return "/device:GPU:0" else: return "/cpu:0" with g.device(matmul_on_gpu): # All operations of type "MatMul" constructed in this context # will be placed on GPU 0; all other operations will be placed # on CPU 0. ``` **N.B.** The device scope may be overridden by op wrappers or other library code. For example, a variable assignment op `v.assign()` must be colocated with the `tf.Variable` `v`, and incompatible device scopes will be ignored. Args: device_name_or_function: The device name or function to use in the context. Yields: A context manager that specifies the default device to use for newly created ops.
Returns a context manager that specifies the default device to use.
[ "Returns", "a", "context", "manager", "that", "specifies", "the", "default", "device", "to", "use", "." ]
def device(self, device_name_or_function): # pylint: disable=line-too-long """Returns a context manager that specifies the default device to use. The `device_name_or_function` argument may either be a device name string, a device function, or None: * If it is a device name string, all operations constructed in this context will be assigned to the device with that name, unless overridden by a nested `device()` context. * If it is a function, it will be treated as a function from Operation objects to device name strings, and invoked each time a new Operation is created. The Operation will be assigned to the device with the returned name. * If it is None, all `device()` invocations from the enclosing context will be ignored. For information about the valid syntax of device name strings, see the documentation in [`DeviceNameUtils`](https://www.tensorflow.org/code/tensorflow/core/util/device_name_utils.h). For example: ```python with g.device('/device:GPU:0'): # All operations constructed in this context will be placed # on GPU 0. with g.device(None): # All operations constructed in this context will have no # assigned device. # Defines a function from `Operation` to device string. def matmul_on_gpu(n): if n.type == "MatMul": return "/device:GPU:0" else: return "/cpu:0" with g.device(matmul_on_gpu): # All operations of type "MatMul" constructed in this context # will be placed on GPU 0; all other operations will be placed # on CPU 0. ``` **N.B.** The device scope may be overridden by op wrappers or other library code. For example, a variable assignment op `v.assign()` must be colocated with the `tf.Variable` `v`, and incompatible device scopes will be ignored. Args: device_name_or_function: The device name or function to use in the context. Yields: A context manager that specifies the default device to use for newly created ops. """ # pylint: enable=line-too-long if (device_name_or_function is not None and not callable(device_name_or_function)): device_function = pydev.merge_device(device_name_or_function) else: device_function = device_name_or_function try: self._device_function_stack.append(device_function) yield finally: self._device_function_stack.pop()
[ "def", "device", "(", "self", ",", "device_name_or_function", ")", ":", "# pylint: disable=line-too-long", "# pylint: enable=line-too-long", "if", "(", "device_name_or_function", "is", "not", "None", "and", "not", "callable", "(", "device_name_or_function", ")", ")", ":", "device_function", "=", "pydev", ".", "merge_device", "(", "device_name_or_function", ")", "else", ":", "device_function", "=", "device_name_or_function", "try", ":", "self", ".", "_device_function_stack", ".", "append", "(", "device_function", ")", "yield", "finally", ":", "self", ".", "_device_function_stack", ".", "pop", "(", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/framework/ops.py#L3721-L3790
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/llvmlite/binding/value.py
python
ValueRef.instructions
(self)
return _InstructionsIterator(it, parents)
Return an iterator over this block's instructions. The iterator will yield a ValueRef for each instruction.
Return an iterator over this block's instructions. The iterator will yield a ValueRef for each instruction.
[ "Return", "an", "iterator", "over", "this", "block", "s", "instructions", ".", "The", "iterator", "will", "yield", "a", "ValueRef", "for", "each", "instruction", "." ]
def instructions(self): """ Return an iterator over this block's instructions. The iterator will yield a ValueRef for each instruction. """ if not self.is_block: raise ValueError('expected block value, got %s' % (self._kind,)) it = ffi.lib.LLVMPY_BlockInstructionsIter(self) parents = self._parents.copy() parents.update(block=self) return _InstructionsIterator(it, parents)
[ "def", "instructions", "(", "self", ")", ":", "if", "not", "self", ".", "is_block", ":", "raise", "ValueError", "(", "'expected block value, got %s'", "%", "(", "self", ".", "_kind", ",", ")", ")", "it", "=", "ffi", ".", "lib", ".", "LLVMPY_BlockInstructionsIter", "(", "self", ")", "parents", "=", "self", ".", "_parents", ".", "copy", "(", ")", "parents", ".", "update", "(", "block", "=", "self", ")", "return", "_InstructionsIterator", "(", "it", ",", "parents", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/llvmlite/binding/value.py#L269-L279
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/richtext.py
python
RichTextAttr.SetTextBoxAttr
(*args, **kwargs)
return _richtext.RichTextAttr_SetTextBoxAttr(*args, **kwargs)
SetTextBoxAttr(self, TextBoxAttr attr)
SetTextBoxAttr(self, TextBoxAttr attr)
[ "SetTextBoxAttr", "(", "self", "TextBoxAttr", "attr", ")" ]
def SetTextBoxAttr(*args, **kwargs): """SetTextBoxAttr(self, TextBoxAttr attr)""" return _richtext.RichTextAttr_SetTextBoxAttr(*args, **kwargs)
[ "def", "SetTextBoxAttr", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextAttr_SetTextBoxAttr", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L900-L902
rrwick/Unicycler
96ffea71e3a78d63ade19d6124946773e65cf129
unicycler/bridge_long_read.py
python
reduce_expected_count
(expected_count, a, b)
return expected_count * ((a / (a + expected_count)) * (1.0 - b) + b)
This function reduces the expected read count. It reduces by a factor which is a function of the read count, so low expected values aren't reduced much, but high expected values are reduced more. This is to help with high read depth cases where expected counts get quite high. https://www.desmos.com/calculator y=x\cdot \left(\left(\frac{a}{a+x}\right)\cdot \left(1-b\right)+b\right)
This function reduces the expected read count. It reduces by a factor which is a function of the read count, so low expected values aren't reduced much, but high expected values are reduced more. This is to help with high read depth cases where expected counts get quite high.
[ "This", "function", "reduces", "the", "expected", "read", "count", ".", "It", "reduces", "by", "a", "factor", "which", "is", "a", "function", "of", "the", "read", "count", "so", "low", "expected", "values", "aren", "t", "reduced", "much", "but", "high", "expected", "values", "are", "reduced", "more", ".", "This", "is", "to", "help", "with", "high", "read", "depth", "cases", "where", "expected", "counts", "get", "quite", "high", "." ]
def reduce_expected_count(expected_count, a, b): """ This function reduces the expected read count. It reduces by a factor which is a function of the read count, so low expected values aren't reduced much, but high expected values are reduced more. This is to help with high read depth cases where expected counts get quite high. https://www.desmos.com/calculator y=x\cdot \left(\left(\frac{a}{a+x}\right)\cdot \left(1-b\right)+b\right) """ return expected_count * ((a / (a + expected_count)) * (1.0 - b) + b)
[ "def", "reduce_expected_count", "(", "expected_count", ",", "a", ",", "b", ")", ":", "return", "expected_count", "*", "(", "(", "a", "/", "(", "a", "+", "expected_count", ")", ")", "*", "(", "1.0", "-", "b", ")", "+", "b", ")" ]
https://github.com/rrwick/Unicycler/blob/96ffea71e3a78d63ade19d6124946773e65cf129/unicycler/bridge_long_read.py#L618-L627
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
PyApp_GetMacSupportPCMenuShortcuts
(*args)
return _core_.PyApp_GetMacSupportPCMenuShortcuts(*args)
PyApp_GetMacSupportPCMenuShortcuts() -> bool
PyApp_GetMacSupportPCMenuShortcuts() -> bool
[ "PyApp_GetMacSupportPCMenuShortcuts", "()", "-", ">", "bool" ]
def PyApp_GetMacSupportPCMenuShortcuts(*args): """PyApp_GetMacSupportPCMenuShortcuts() -> bool""" return _core_.PyApp_GetMacSupportPCMenuShortcuts(*args)
[ "def", "PyApp_GetMacSupportPCMenuShortcuts", "(", "*", "args", ")", ":", "return", "_core_", ".", "PyApp_GetMacSupportPCMenuShortcuts", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L8274-L8276
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/jitclass/base.py
python
ctor_impl
(context, builder, sig, args)
return imputils.impl_ret_new_ref(context, builder, inst_typ, ret)
Generic constructor (__new__) for jitclasses.
Generic constructor (__new__) for jitclasses.
[ "Generic", "constructor", "(", "__new__", ")", "for", "jitclasses", "." ]
def ctor_impl(context, builder, sig, args): """ Generic constructor (__new__) for jitclasses. """ # Allocate the instance inst_typ = sig.return_type alloc_type = context.get_data_type(inst_typ.get_data_type()) alloc_size = context.get_abi_sizeof(alloc_type) meminfo = context.nrt.meminfo_alloc_dtor( builder, context.get_constant(types.uintp, alloc_size), imp_dtor(context, builder.module, inst_typ), ) data_pointer = context.nrt.meminfo_data(builder, meminfo) data_pointer = builder.bitcast(data_pointer, alloc_type.as_pointer()) # Nullify all data builder.store(cgutils.get_null_value(alloc_type), data_pointer) inst_struct = context.make_helper(builder, inst_typ) inst_struct.meminfo = meminfo inst_struct.data = data_pointer # Call the jitted __init__ # TODO: extract the following into a common util init_sig = (sig.return_type,) + sig.args init = inst_typ.jitmethods['__init__'] disp_type = types.Dispatcher(init) call = context.get_function(disp_type, types.void(*init_sig)) _add_linking_libs(context, call) realargs = [inst_struct._getvalue()] + list(args) call(builder, realargs) # Prepare return value ret = inst_struct._getvalue() return imputils.impl_ret_new_ref(context, builder, inst_typ, ret)
[ "def", "ctor_impl", "(", "context", ",", "builder", ",", "sig", ",", "args", ")", ":", "# Allocate the instance", "inst_typ", "=", "sig", ".", "return_type", "alloc_type", "=", "context", ".", "get_data_type", "(", "inst_typ", ".", "get_data_type", "(", ")", ")", "alloc_size", "=", "context", ".", "get_abi_sizeof", "(", "alloc_type", ")", "meminfo", "=", "context", ".", "nrt", ".", "meminfo_alloc_dtor", "(", "builder", ",", "context", ".", "get_constant", "(", "types", ".", "uintp", ",", "alloc_size", ")", ",", "imp_dtor", "(", "context", ",", "builder", ".", "module", ",", "inst_typ", ")", ",", ")", "data_pointer", "=", "context", ".", "nrt", ".", "meminfo_data", "(", "builder", ",", "meminfo", ")", "data_pointer", "=", "builder", ".", "bitcast", "(", "data_pointer", ",", "alloc_type", ".", "as_pointer", "(", ")", ")", "# Nullify all data", "builder", ".", "store", "(", "cgutils", ".", "get_null_value", "(", "alloc_type", ")", ",", "data_pointer", ")", "inst_struct", "=", "context", ".", "make_helper", "(", "builder", ",", "inst_typ", ")", "inst_struct", ".", "meminfo", "=", "meminfo", "inst_struct", ".", "data", "=", "data_pointer", "# Call the jitted __init__", "# TODO: extract the following into a common util", "init_sig", "=", "(", "sig", ".", "return_type", ",", ")", "+", "sig", ".", "args", "init", "=", "inst_typ", ".", "jitmethods", "[", "'__init__'", "]", "disp_type", "=", "types", ".", "Dispatcher", "(", "init", ")", "call", "=", "context", ".", "get_function", "(", "disp_type", ",", "types", ".", "void", "(", "*", "init_sig", ")", ")", "_add_linking_libs", "(", "context", ",", "call", ")", "realargs", "=", "[", "inst_struct", ".", "_getvalue", "(", ")", "]", "+", "list", "(", "args", ")", "call", "(", "builder", ",", "realargs", ")", "# Prepare return value", "ret", "=", "inst_struct", ".", "_getvalue", "(", ")", "return", "imputils", ".", "impl_ret_new_ref", "(", "context", ",", "builder", ",", "inst_typ", ",", "ret", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/jitclass/base.py#L488-L528
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/training/input.py
python
_enqueue
(queue, tensor_list, threads, enqueue_many, keep_input)
Enqueue `tensor_list` in `queue`.
Enqueue `tensor_list` in `queue`.
[ "Enqueue", "tensor_list", "in", "queue", "." ]
def _enqueue(queue, tensor_list, threads, enqueue_many, keep_input): """Enqueue `tensor_list` in `queue`.""" if enqueue_many: enqueue_fn = queue.enqueue_many else: enqueue_fn = queue.enqueue if keep_input.shape.ndims == 1: enqueue_ops = [ enqueue_fn(_select_which_to_enqueue(tensor_list, keep_input))] * threads else: enqueue_ops = [utils.smart_cond( keep_input, lambda: enqueue_fn(tensor_list), control_flow_ops.no_op)] * threads queue_runner.add_queue_runner(queue_runner.QueueRunner(queue, enqueue_ops))
[ "def", "_enqueue", "(", "queue", ",", "tensor_list", ",", "threads", ",", "enqueue_many", ",", "keep_input", ")", ":", "if", "enqueue_many", ":", "enqueue_fn", "=", "queue", ".", "enqueue_many", "else", ":", "enqueue_fn", "=", "queue", ".", "enqueue", "if", "keep_input", ".", "shape", ".", "ndims", "==", "1", ":", "enqueue_ops", "=", "[", "enqueue_fn", "(", "_select_which_to_enqueue", "(", "tensor_list", ",", "keep_input", ")", ")", "]", "*", "threads", "else", ":", "enqueue_ops", "=", "[", "utils", ".", "smart_cond", "(", "keep_input", ",", "lambda", ":", "enqueue_fn", "(", "tensor_list", ")", ",", "control_flow_ops", ".", "no_op", ")", "]", "*", "threads", "queue_runner", ".", "add_queue_runner", "(", "queue_runner", ".", "QueueRunner", "(", "queue", ",", "enqueue_ops", ")", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/training/input.py#L666-L680
openvinotoolkit/openvino
dedcbeafa8b84cccdc55ca64b8da516682b381c7
tools/mo/openvino/tools/mo/utils/cli_parser.py
python
check_available_transforms
(transforms: list)
return True
This function check that transformations specified by user are available. :param transforms: list of user specified transformations :return: raises an Error if transformation is not available
This function check that transformations specified by user are available. :param transforms: list of user specified transformations :return: raises an Error if transformation is not available
[ "This", "function", "check", "that", "transformations", "specified", "by", "user", "are", "available", ".", ":", "param", "transforms", ":", "list", "of", "user", "specified", "transformations", ":", "return", ":", "raises", "an", "Error", "if", "transformation", "is", "not", "available" ]
def check_available_transforms(transforms: list): """ This function check that transformations specified by user are available. :param transforms: list of user specified transformations :return: raises an Error if transformation is not available """ from openvino.tools.mo.back.offline_transformations import get_available_transformations available_transforms = get_available_transformations() missing_transformations = [] for name, _ in transforms: if name not in available_transforms.keys(): missing_transformations.append(name) if len(missing_transformations) != 0: raise Error('Following transformations ({}) are not available. ' 'List with available transformations ({})'.format(','.join(missing_transformations), ','.join(available_transforms.keys()))) return True
[ "def", "check_available_transforms", "(", "transforms", ":", "list", ")", ":", "from", "openvino", ".", "tools", ".", "mo", ".", "back", ".", "offline_transformations", "import", "get_available_transformations", "available_transforms", "=", "get_available_transformations", "(", ")", "missing_transformations", "=", "[", "]", "for", "name", ",", "_", "in", "transforms", ":", "if", "name", "not", "in", "available_transforms", ".", "keys", "(", ")", ":", "missing_transformations", ".", "append", "(", "name", ")", "if", "len", "(", "missing_transformations", ")", "!=", "0", ":", "raise", "Error", "(", "'Following transformations ({}) are not available. '", "'List with available transformations ({})'", ".", "format", "(", "','", ".", "join", "(", "missing_transformations", ")", ",", "','", ".", "join", "(", "available_transforms", ".", "keys", "(", ")", ")", ")", ")", "return", "True" ]
https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/mo/openvino/tools/mo/utils/cli_parser.py#L1535-L1553
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/aui/tabart.py
python
FF2TabArt.DrawTab
(self, dc, wnd, page, in_rect, close_button_state, paint_control=False)
return out_tab_rect, out_button_rect, x_extent
Draws a single tab. :param `dc`: a :class:`DC` device context; :param `wnd`: a :class:`Window` instance object; :param `page`: the tab control page associated with the tab; :param Rect `in_rect`: rectangle the tab should be confined to; :param integer `close_button_state`: the state of the close button on the tab; :param bool `paint_control`: whether to draw the control inside a tab (if any) on a :class:`MemoryDC`.
Draws a single tab.
[ "Draws", "a", "single", "tab", "." ]
def DrawTab(self, dc, wnd, page, in_rect, close_button_state, paint_control=False): """ Draws a single tab. :param `dc`: a :class:`DC` device context; :param `wnd`: a :class:`Window` instance object; :param `page`: the tab control page associated with the tab; :param Rect `in_rect`: rectangle the tab should be confined to; :param integer `close_button_state`: the state of the close button on the tab; :param bool `paint_control`: whether to draw the control inside a tab (if any) on a :class:`MemoryDC`. """ # Firefox 2 style control = page.control # figure out the size of the tab tab_size, x_extent = self.GetTabSize(dc, wnd, page.caption, page.bitmap, page.active, close_button_state, control) tab_height = self._tab_ctrl_height - 2 tab_width = tab_size[0] tab_x = in_rect.x tab_y = in_rect.y + in_rect.height - tab_height clip_width = tab_width if tab_x + clip_width > in_rect.x + in_rect.width - 4: clip_width = (in_rect.x + in_rect.width) - tab_x - 4 dc.SetClippingRegion(tab_x, tab_y, clip_width + 1, tab_height - 3) tabPoints = [wx.Point() for i in xrange(7)] adjust = 0 if not page.active: adjust = 1 agwFlags = self.GetAGWFlags() tabPoints[0].x = tab_x + 3 tabPoints[0].y = (agwFlags & AUI_NB_BOTTOM and [3] or [tab_height - 2])[0] tabPoints[1].x = tabPoints[0].x tabPoints[1].y = (agwFlags & AUI_NB_BOTTOM and [tab_height - (vertical_border_padding + 2) - adjust] or \ [(vertical_border_padding + 2) + adjust])[0] tabPoints[2].x = tabPoints[1].x+2 tabPoints[2].y = (agwFlags & AUI_NB_BOTTOM and [tab_height - vertical_border_padding - adjust] or \ [vertical_border_padding + adjust])[0] tabPoints[3].x = tab_x + tab_width - 2 tabPoints[3].y = tabPoints[2].y tabPoints[4].x = tabPoints[3].x + 2 tabPoints[4].y = tabPoints[1].y tabPoints[5].x = tabPoints[4].x tabPoints[5].y = tabPoints[0].y tabPoints[6].x = tabPoints[0].x tabPoints[6].y = tabPoints[0].y rr = wx.RectPP(tabPoints[2], tabPoints[5]) self.DrawTabBackground(dc, rr, page.active, (agwFlags & AUI_NB_BOTTOM) == 0) dc.SetBrush(wx.TRANSPARENT_BRUSH) dc.SetPen(wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW))) # Draw the tab as rounded rectangle dc.DrawPolygon(tabPoints) if page.active: dc.DrawLine(tabPoints[0].x + 1, tabPoints[0].y, tabPoints[5].x , tabPoints[0].y) drawn_tab_yoff = tabPoints[1].y drawn_tab_height = tabPoints[0].y - tabPoints[2].y text_offset = tab_x + 8 close_button_width = 0 if close_button_state != AUI_BUTTON_STATE_HIDDEN: close_button_width = self._active_close_bmp.GetWidth() if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT: text_offset += close_button_width - 4 if not page.enabled: dc.SetTextForeground(wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT)) pagebitmap = page.dis_bitmap else: dc.SetTextForeground(page.text_colour) pagebitmap = page.bitmap shift = -1 if agwFlags & AUI_NB_BOTTOM: shift = 2 bitmap_offset = 0 if pagebitmap.IsOk(): bitmap_offset = tab_x + 8 if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT and close_button_width: bitmap_offset += close_button_width - 4 # draw bitmap dc.DrawBitmap(pagebitmap, bitmap_offset, drawn_tab_yoff + (drawn_tab_height/2) - (pagebitmap.GetHeight()/2) + shift, True) text_offset = bitmap_offset + pagebitmap.GetWidth() text_offset += 3 # bitmap padding else: if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT == 0 or not close_button_width: text_offset = tab_x + 8 # if the caption is empty, measure some temporary text caption = page.caption if caption == "": caption = "Xj" if page.active: dc.SetFont(self._selected_font) textx, texty, dummy = dc.GetMultiLineTextExtent(caption) else: dc.SetFont(self._normal_font) textx, texty, dummy = dc.GetMultiLineTextExtent(caption) if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT: draw_text = ChopText(dc, caption, tab_width - (text_offset-tab_x) - close_button_width + 1) else: draw_text = ChopText(dc, caption, tab_width - (text_offset-tab_x) - close_button_width) ypos = drawn_tab_yoff + drawn_tab_height/2 - texty/2 - 1 + shift offset_focus = text_offset if control is not None: try: if control.GetPosition() != wx.Point(text_offset+1, ypos): control.SetPosition(wx.Point(text_offset+1, ypos)) if not control.IsShown(): control.Show() if paint_control: bmp = TakeScreenShot(control.GetScreenRect()) dc.DrawBitmap(bmp, text_offset+1, ypos, True) controlW, controlH = control.GetSize() text_offset += controlW + 4 textx += controlW + 4 except wx.PyDeadObjectError: pass # draw tab text rectx, recty, dummy = dc.GetMultiLineTextExtent(draw_text) dc.DrawLabel(draw_text, wx.Rect(text_offset, ypos, rectx, recty)) # draw focus rectangle if (agwFlags & AUI_NB_NO_TAB_FOCUS) == 0: self.DrawFocusRectangle(dc, page, wnd, draw_text, offset_focus, bitmap_offset, drawn_tab_yoff+shift, drawn_tab_height, rectx, recty) out_button_rect = wx.Rect() # draw 'x' on tab (if enabled) if close_button_state != AUI_BUTTON_STATE_HIDDEN: close_button_width = self._active_close_bmp.GetWidth() bmp = self._disabled_close_bmp if close_button_state == AUI_BUTTON_STATE_HOVER: bmp = self._hover_close_bmp elif close_button_state == AUI_BUTTON_STATE_PRESSED: bmp = self._pressed_close_bmp if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT: rect = wx.Rect(tab_x + 5, drawn_tab_yoff + (drawn_tab_height / 2) - (bmp.GetHeight() / 2) + shift, close_button_width, tab_height) else: rect = wx.Rect(tab_x + tab_width - close_button_width - 3, drawn_tab_yoff + (drawn_tab_height / 2) - (bmp.GetHeight() / 2) + shift, close_button_width, tab_height) # Indent the button if it is pressed down: rect = IndentPressedBitmap(rect, close_button_state) dc.DrawBitmap(bmp, rect.x, rect.y, True) out_button_rect = rect out_tab_rect = wx.Rect(tab_x, tab_y, tab_width, tab_height) dc.DestroyClippingRegion() return out_tab_rect, out_button_rect, x_extent
[ "def", "DrawTab", "(", "self", ",", "dc", ",", "wnd", ",", "page", ",", "in_rect", ",", "close_button_state", ",", "paint_control", "=", "False", ")", ":", "# Firefox 2 style", "control", "=", "page", ".", "control", "# figure out the size of the tab", "tab_size", ",", "x_extent", "=", "self", ".", "GetTabSize", "(", "dc", ",", "wnd", ",", "page", ".", "caption", ",", "page", ".", "bitmap", ",", "page", ".", "active", ",", "close_button_state", ",", "control", ")", "tab_height", "=", "self", ".", "_tab_ctrl_height", "-", "2", "tab_width", "=", "tab_size", "[", "0", "]", "tab_x", "=", "in_rect", ".", "x", "tab_y", "=", "in_rect", ".", "y", "+", "in_rect", ".", "height", "-", "tab_height", "clip_width", "=", "tab_width", "if", "tab_x", "+", "clip_width", ">", "in_rect", ".", "x", "+", "in_rect", ".", "width", "-", "4", ":", "clip_width", "=", "(", "in_rect", ".", "x", "+", "in_rect", ".", "width", ")", "-", "tab_x", "-", "4", "dc", ".", "SetClippingRegion", "(", "tab_x", ",", "tab_y", ",", "clip_width", "+", "1", ",", "tab_height", "-", "3", ")", "tabPoints", "=", "[", "wx", ".", "Point", "(", ")", "for", "i", "in", "xrange", "(", "7", ")", "]", "adjust", "=", "0", "if", "not", "page", ".", "active", ":", "adjust", "=", "1", "agwFlags", "=", "self", ".", "GetAGWFlags", "(", ")", "tabPoints", "[", "0", "]", ".", "x", "=", "tab_x", "+", "3", "tabPoints", "[", "0", "]", ".", "y", "=", "(", "agwFlags", "&", "AUI_NB_BOTTOM", "and", "[", "3", "]", "or", "[", "tab_height", "-", "2", "]", ")", "[", "0", "]", "tabPoints", "[", "1", "]", ".", "x", "=", "tabPoints", "[", "0", "]", ".", "x", "tabPoints", "[", "1", "]", ".", "y", "=", "(", "agwFlags", "&", "AUI_NB_BOTTOM", "and", "[", "tab_height", "-", "(", "vertical_border_padding", "+", "2", ")", "-", "adjust", "]", "or", "[", "(", "vertical_border_padding", "+", "2", ")", "+", "adjust", "]", ")", "[", "0", "]", "tabPoints", "[", "2", "]", ".", "x", "=", "tabPoints", "[", "1", "]", ".", "x", "+", "2", "tabPoints", "[", "2", "]", ".", "y", "=", "(", "agwFlags", "&", "AUI_NB_BOTTOM", "and", "[", "tab_height", "-", "vertical_border_padding", "-", "adjust", "]", "or", "[", "vertical_border_padding", "+", "adjust", "]", ")", "[", "0", "]", "tabPoints", "[", "3", "]", ".", "x", "=", "tab_x", "+", "tab_width", "-", "2", "tabPoints", "[", "3", "]", ".", "y", "=", "tabPoints", "[", "2", "]", ".", "y", "tabPoints", "[", "4", "]", ".", "x", "=", "tabPoints", "[", "3", "]", ".", "x", "+", "2", "tabPoints", "[", "4", "]", ".", "y", "=", "tabPoints", "[", "1", "]", ".", "y", "tabPoints", "[", "5", "]", ".", "x", "=", "tabPoints", "[", "4", "]", ".", "x", "tabPoints", "[", "5", "]", ".", "y", "=", "tabPoints", "[", "0", "]", ".", "y", "tabPoints", "[", "6", "]", ".", "x", "=", "tabPoints", "[", "0", "]", ".", "x", "tabPoints", "[", "6", "]", ".", "y", "=", "tabPoints", "[", "0", "]", ".", "y", "rr", "=", "wx", ".", "RectPP", "(", "tabPoints", "[", "2", "]", ",", "tabPoints", "[", "5", "]", ")", "self", ".", "DrawTabBackground", "(", "dc", ",", "rr", ",", "page", ".", "active", ",", "(", "agwFlags", "&", "AUI_NB_BOTTOM", ")", "==", "0", ")", "dc", ".", "SetBrush", "(", "wx", ".", "TRANSPARENT_BRUSH", ")", "dc", ".", "SetPen", "(", "wx", ".", "Pen", "(", "wx", ".", "SystemSettings_GetColour", "(", "wx", ".", "SYS_COLOUR_BTNSHADOW", ")", ")", ")", "# Draw the tab as rounded rectangle", "dc", ".", "DrawPolygon", "(", "tabPoints", ")", "if", "page", ".", "active", ":", "dc", ".", "DrawLine", "(", "tabPoints", "[", "0", "]", ".", "x", "+", "1", ",", "tabPoints", "[", "0", "]", ".", "y", ",", "tabPoints", "[", "5", "]", ".", "x", ",", "tabPoints", "[", "0", "]", ".", "y", ")", "drawn_tab_yoff", "=", "tabPoints", "[", "1", "]", ".", "y", "drawn_tab_height", "=", "tabPoints", "[", "0", "]", ".", "y", "-", "tabPoints", "[", "2", "]", ".", "y", "text_offset", "=", "tab_x", "+", "8", "close_button_width", "=", "0", "if", "close_button_state", "!=", "AUI_BUTTON_STATE_HIDDEN", ":", "close_button_width", "=", "self", ".", "_active_close_bmp", ".", "GetWidth", "(", ")", "if", "agwFlags", "&", "AUI_NB_CLOSE_ON_TAB_LEFT", ":", "text_offset", "+=", "close_button_width", "-", "4", "if", "not", "page", ".", "enabled", ":", "dc", ".", "SetTextForeground", "(", "wx", ".", "SystemSettings", ".", "GetColour", "(", "wx", ".", "SYS_COLOUR_GRAYTEXT", ")", ")", "pagebitmap", "=", "page", ".", "dis_bitmap", "else", ":", "dc", ".", "SetTextForeground", "(", "page", ".", "text_colour", ")", "pagebitmap", "=", "page", ".", "bitmap", "shift", "=", "-", "1", "if", "agwFlags", "&", "AUI_NB_BOTTOM", ":", "shift", "=", "2", "bitmap_offset", "=", "0", "if", "pagebitmap", ".", "IsOk", "(", ")", ":", "bitmap_offset", "=", "tab_x", "+", "8", "if", "agwFlags", "&", "AUI_NB_CLOSE_ON_TAB_LEFT", "and", "close_button_width", ":", "bitmap_offset", "+=", "close_button_width", "-", "4", "# draw bitmap", "dc", ".", "DrawBitmap", "(", "pagebitmap", ",", "bitmap_offset", ",", "drawn_tab_yoff", "+", "(", "drawn_tab_height", "/", "2", ")", "-", "(", "pagebitmap", ".", "GetHeight", "(", ")", "/", "2", ")", "+", "shift", ",", "True", ")", "text_offset", "=", "bitmap_offset", "+", "pagebitmap", ".", "GetWidth", "(", ")", "text_offset", "+=", "3", "# bitmap padding", "else", ":", "if", "agwFlags", "&", "AUI_NB_CLOSE_ON_TAB_LEFT", "==", "0", "or", "not", "close_button_width", ":", "text_offset", "=", "tab_x", "+", "8", "# if the caption is empty, measure some temporary text", "caption", "=", "page", ".", "caption", "if", "caption", "==", "\"\"", ":", "caption", "=", "\"Xj\"", "if", "page", ".", "active", ":", "dc", ".", "SetFont", "(", "self", ".", "_selected_font", ")", "textx", ",", "texty", ",", "dummy", "=", "dc", ".", "GetMultiLineTextExtent", "(", "caption", ")", "else", ":", "dc", ".", "SetFont", "(", "self", ".", "_normal_font", ")", "textx", ",", "texty", ",", "dummy", "=", "dc", ".", "GetMultiLineTextExtent", "(", "caption", ")", "if", "agwFlags", "&", "AUI_NB_CLOSE_ON_TAB_LEFT", ":", "draw_text", "=", "ChopText", "(", "dc", ",", "caption", ",", "tab_width", "-", "(", "text_offset", "-", "tab_x", ")", "-", "close_button_width", "+", "1", ")", "else", ":", "draw_text", "=", "ChopText", "(", "dc", ",", "caption", ",", "tab_width", "-", "(", "text_offset", "-", "tab_x", ")", "-", "close_button_width", ")", "ypos", "=", "drawn_tab_yoff", "+", "drawn_tab_height", "/", "2", "-", "texty", "/", "2", "-", "1", "+", "shift", "offset_focus", "=", "text_offset", "if", "control", "is", "not", "None", ":", "try", ":", "if", "control", ".", "GetPosition", "(", ")", "!=", "wx", ".", "Point", "(", "text_offset", "+", "1", ",", "ypos", ")", ":", "control", ".", "SetPosition", "(", "wx", ".", "Point", "(", "text_offset", "+", "1", ",", "ypos", ")", ")", "if", "not", "control", ".", "IsShown", "(", ")", ":", "control", ".", "Show", "(", ")", "if", "paint_control", ":", "bmp", "=", "TakeScreenShot", "(", "control", ".", "GetScreenRect", "(", ")", ")", "dc", ".", "DrawBitmap", "(", "bmp", ",", "text_offset", "+", "1", ",", "ypos", ",", "True", ")", "controlW", ",", "controlH", "=", "control", ".", "GetSize", "(", ")", "text_offset", "+=", "controlW", "+", "4", "textx", "+=", "controlW", "+", "4", "except", "wx", ".", "PyDeadObjectError", ":", "pass", "# draw tab text", "rectx", ",", "recty", ",", "dummy", "=", "dc", ".", "GetMultiLineTextExtent", "(", "draw_text", ")", "dc", ".", "DrawLabel", "(", "draw_text", ",", "wx", ".", "Rect", "(", "text_offset", ",", "ypos", ",", "rectx", ",", "recty", ")", ")", "# draw focus rectangle", "if", "(", "agwFlags", "&", "AUI_NB_NO_TAB_FOCUS", ")", "==", "0", ":", "self", ".", "DrawFocusRectangle", "(", "dc", ",", "page", ",", "wnd", ",", "draw_text", ",", "offset_focus", ",", "bitmap_offset", ",", "drawn_tab_yoff", "+", "shift", ",", "drawn_tab_height", ",", "rectx", ",", "recty", ")", "out_button_rect", "=", "wx", ".", "Rect", "(", ")", "# draw 'x' on tab (if enabled)", "if", "close_button_state", "!=", "AUI_BUTTON_STATE_HIDDEN", ":", "close_button_width", "=", "self", ".", "_active_close_bmp", ".", "GetWidth", "(", ")", "bmp", "=", "self", ".", "_disabled_close_bmp", "if", "close_button_state", "==", "AUI_BUTTON_STATE_HOVER", ":", "bmp", "=", "self", ".", "_hover_close_bmp", "elif", "close_button_state", "==", "AUI_BUTTON_STATE_PRESSED", ":", "bmp", "=", "self", ".", "_pressed_close_bmp", "if", "agwFlags", "&", "AUI_NB_CLOSE_ON_TAB_LEFT", ":", "rect", "=", "wx", ".", "Rect", "(", "tab_x", "+", "5", ",", "drawn_tab_yoff", "+", "(", "drawn_tab_height", "/", "2", ")", "-", "(", "bmp", ".", "GetHeight", "(", ")", "/", "2", ")", "+", "shift", ",", "close_button_width", ",", "tab_height", ")", "else", ":", "rect", "=", "wx", ".", "Rect", "(", "tab_x", "+", "tab_width", "-", "close_button_width", "-", "3", ",", "drawn_tab_yoff", "+", "(", "drawn_tab_height", "/", "2", ")", "-", "(", "bmp", ".", "GetHeight", "(", ")", "/", "2", ")", "+", "shift", ",", "close_button_width", ",", "tab_height", ")", "# Indent the button if it is pressed down:", "rect", "=", "IndentPressedBitmap", "(", "rect", ",", "close_button_state", ")", "dc", ".", "DrawBitmap", "(", "bmp", ",", "rect", ".", "x", ",", "rect", ".", "y", ",", "True", ")", "out_button_rect", "=", "rect", "out_tab_rect", "=", "wx", ".", "Rect", "(", "tab_x", ",", "tab_y", ",", "tab_width", ",", "tab_height", ")", "dc", ".", "DestroyClippingRegion", "(", ")", "return", "out_tab_rect", ",", "out_button_rect", ",", "x_extent" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/tabart.py#L1917-L2108
cornell-zhang/heterocl
6d9e4b4acc2ee2707b2d25b27298c0335bccedfd
python/heterocl/report_config.py
python
RptSetup.__init__
(self, profile, prod_name)
Parameters ---------- profile: dict Dictionary representation of the report file. prod_name: str Name of the target device.
Parameters ---------- profile: dict Dictionary representation of the report file.
[ "Parameters", "----------", "profile", ":", "dict", "Dictionary", "representation", "of", "the", "report", "file", "." ]
def __init__(self, profile, prod_name): """ Parameters ---------- profile: dict Dictionary representation of the report file. prod_name: str Name of the target device. """ self.profile = profile self.prod_name = prod_name self.version = ["ReportVersion", "Version"] # Units self.assignment_unit = ["UserAssignments", "unit"] self._perf_est = ["PerformanceEstimates"] self._overall_latency = self._perf_est + ["SummaryOfOverallLatency"] self.performance_unit = self._overall_latency + ["unit"] # User assignments self._user_assignments = ["UserAssignments"] self.prod_family = self._user_assignments + ["ProductFamily"] self.target_device = self._user_assignments + ["Part"] self.top_model_name = self._user_assignments + ["TopModelName"] self.target_cp = self._user_assignments + ["TargetClockPeriod"] # Area estimates self._area_est = ["AreaEstimates"] self.est_resources = self._area_est + ["Resources"] self.avail_resources = self._area_est + ["AvailableResources"] # Performance estimates self.estimated_cp = self._perf_est + ["SummaryOfTimingAnalysis", "EstimatedClockPeriod"] self.min_latency = self._overall_latency + ["Best-caseLatency"] self.max_latency = self._overall_latency + ["Worst-caseLatency"] self.min_interval = self._overall_latency + ["Interval-min"] self.max_interval = self._overall_latency + ["Interval-max"] # Loop latency self.loop_latency = self._perf_est + ["SummaryOfLoopLatency"]
[ "def", "__init__", "(", "self", ",", "profile", ",", "prod_name", ")", ":", "self", ".", "profile", "=", "profile", "self", ".", "prod_name", "=", "prod_name", "self", ".", "version", "=", "[", "\"ReportVersion\"", ",", "\"Version\"", "]", "# Units", "self", ".", "assignment_unit", "=", "[", "\"UserAssignments\"", ",", "\"unit\"", "]", "self", ".", "_perf_est", "=", "[", "\"PerformanceEstimates\"", "]", "self", ".", "_overall_latency", "=", "self", ".", "_perf_est", "+", "[", "\"SummaryOfOverallLatency\"", "]", "self", ".", "performance_unit", "=", "self", ".", "_overall_latency", "+", "[", "\"unit\"", "]", "# User assignments", "self", ".", "_user_assignments", "=", "[", "\"UserAssignments\"", "]", "self", ".", "prod_family", "=", "self", ".", "_user_assignments", "+", "[", "\"ProductFamily\"", "]", "self", ".", "target_device", "=", "self", ".", "_user_assignments", "+", "[", "\"Part\"", "]", "self", ".", "top_model_name", "=", "self", ".", "_user_assignments", "+", "[", "\"TopModelName\"", "]", "self", ".", "target_cp", "=", "self", ".", "_user_assignments", "+", "[", "\"TargetClockPeriod\"", "]", "# Area estimates", "self", ".", "_area_est", "=", "[", "\"AreaEstimates\"", "]", "self", ".", "est_resources", "=", "self", ".", "_area_est", "+", "[", "\"Resources\"", "]", "self", ".", "avail_resources", "=", "self", ".", "_area_est", "+", "[", "\"AvailableResources\"", "]", "# Performance estimates", "self", ".", "estimated_cp", "=", "self", ".", "_perf_est", "+", "[", "\"SummaryOfTimingAnalysis\"", ",", "\"EstimatedClockPeriod\"", "]", "self", ".", "min_latency", "=", "self", ".", "_overall_latency", "+", "[", "\"Best-caseLatency\"", "]", "self", ".", "max_latency", "=", "self", ".", "_overall_latency", "+", "[", "\"Worst-caseLatency\"", "]", "self", ".", "min_interval", "=", "self", ".", "_overall_latency", "+", "[", "\"Interval-min\"", "]", "self", ".", "max_interval", "=", "self", ".", "_overall_latency", "+", "[", "\"Interval-max\"", "]", "# Loop latency", "self", ".", "loop_latency", "=", "self", ".", "_perf_est", "+", "[", "\"SummaryOfLoopLatency\"", "]" ]
https://github.com/cornell-zhang/heterocl/blob/6d9e4b4acc2ee2707b2d25b27298c0335bccedfd/python/heterocl/report_config.py#L22-L62
physercoe/starquant
c00cad64d1de2da05081b3dc320ef264c6295e08
cppsrc/log4cplus-2.0.4/catch/scripts/updateDocumentToC.py
python
buildMarkdown
(toc_headlines, body, spacer=0, placeholder=None)
return markdown
Returns a string with the Markdown output contents incl. the table of contents. Keyword arguments: toc_headlines: lines for the table of contents as created by the createToc function. body: contents of the Markdown file including ID-anchor tags as returned by the tagAndCollect function. spacer: Adds vertical space after the table of contents. Height in pixels. placeholder: If a placeholder string is provided, the placeholder will be replaced by the TOC instead of inserting the TOC at the top of the document
Returns a string with the Markdown output contents incl. the table of contents.
[ "Returns", "a", "string", "with", "the", "Markdown", "output", "contents", "incl", ".", "the", "table", "of", "contents", "." ]
def buildMarkdown(toc_headlines, body, spacer=0, placeholder=None): """ Returns a string with the Markdown output contents incl. the table of contents. Keyword arguments: toc_headlines: lines for the table of contents as created by the createToc function. body: contents of the Markdown file including ID-anchor tags as returned by the tagAndCollect function. spacer: Adds vertical space after the table of contents. Height in pixels. placeholder: If a placeholder string is provided, the placeholder will be replaced by the TOC instead of inserting the TOC at the top of the document """ if spacer: spacer_line = ['\n<div style="height:%spx;"></div>\n' % (spacer)] toc_markdown = "\n".join(toc_headlines + spacer_line) else: toc_markdown = "\n".join(toc_headlines) if placeholder: body_markdown = "\n".join(body) markdown = body_markdown.replace(placeholder, toc_markdown) else: body_markdown_p1 = "\n".join(body[:contentLineNdx ]) + '\n' body_markdown_p2 = "\n".join(body[ contentLineNdx:]) markdown = body_markdown_p1 + toc_markdown + body_markdown_p2 return markdown
[ "def", "buildMarkdown", "(", "toc_headlines", ",", "body", ",", "spacer", "=", "0", ",", "placeholder", "=", "None", ")", ":", "if", "spacer", ":", "spacer_line", "=", "[", "'\\n<div style=\"height:%spx;\"></div>\\n'", "%", "(", "spacer", ")", "]", "toc_markdown", "=", "\"\\n\"", ".", "join", "(", "toc_headlines", "+", "spacer_line", ")", "else", ":", "toc_markdown", "=", "\"\\n\"", ".", "join", "(", "toc_headlines", ")", "if", "placeholder", ":", "body_markdown", "=", "\"\\n\"", ".", "join", "(", "body", ")", "markdown", "=", "body_markdown", ".", "replace", "(", "placeholder", ",", "toc_markdown", ")", "else", ":", "body_markdown_p1", "=", "\"\\n\"", ".", "join", "(", "body", "[", ":", "contentLineNdx", "]", ")", "+", "'\\n'", "body_markdown_p2", "=", "\"\\n\"", ".", "join", "(", "body", "[", "contentLineNdx", ":", "]", ")", "markdown", "=", "body_markdown_p1", "+", "toc_markdown", "+", "body_markdown_p2", "return", "markdown" ]
https://github.com/physercoe/starquant/blob/c00cad64d1de2da05081b3dc320ef264c6295e08/cppsrc/log4cplus-2.0.4/catch/scripts/updateDocumentToC.py#L227-L259
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/glcanvas.py
python
GLContext.SetCurrent
(*args, **kwargs)
return _glcanvas.GLContext_SetCurrent(*args, **kwargs)
SetCurrent(self, GLCanvas win) -> bool
SetCurrent(self, GLCanvas win) -> bool
[ "SetCurrent", "(", "self", "GLCanvas", "win", ")", "-", ">", "bool" ]
def SetCurrent(*args, **kwargs): """SetCurrent(self, GLCanvas win) -> bool""" return _glcanvas.GLContext_SetCurrent(*args, **kwargs)
[ "def", "SetCurrent", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_glcanvas", ".", "GLContext_SetCurrent", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/glcanvas.py#L70-L72
cksystemsgroup/scal
fa2208a97a77d65f4e90f85fef3404c27c1f2ac2
tools/cpplint.py
python
CheckForNewlineAtEOF
(filename, lines, error)
Logs an error if there is no newline char at the end of the file. Args: filename: The name of the current file. lines: An array of strings, each representing a line of the file. error: The function to call with any errors found.
Logs an error if there is no newline char at the end of the file.
[ "Logs", "an", "error", "if", "there", "is", "no", "newline", "char", "at", "the", "end", "of", "the", "file", "." ]
def CheckForNewlineAtEOF(filename, lines, error): """Logs an error if there is no newline char at the end of the file. Args: filename: The name of the current file. lines: An array of strings, each representing a line of the file. error: The function to call with any errors found. """ # The array lines() was created by adding two newlines to the # original file (go figure), then splitting on \n. # To verify that the file ends in \n, we just have to make sure the # last-but-two element of lines() exists and is empty. if len(lines) < 3 or lines[-2]: error(filename, len(lines) - 2, 'whitespace/ending_newline', 5, 'Could not find a newline character at the end of the file.')
[ "def", "CheckForNewlineAtEOF", "(", "filename", ",", "lines", ",", "error", ")", ":", "# The array lines() was created by adding two newlines to the", "# original file (go figure), then splitting on \\n.", "# To verify that the file ends in \\n, we just have to make sure the", "# last-but-two element of lines() exists and is empty.", "if", "len", "(", "lines", ")", "<", "3", "or", "lines", "[", "-", "2", "]", ":", "error", "(", "filename", ",", "len", "(", "lines", ")", "-", "2", ",", "'whitespace/ending_newline'", ",", "5", ",", "'Could not find a newline character at the end of the file.'", ")" ]
https://github.com/cksystemsgroup/scal/blob/fa2208a97a77d65f4e90f85fef3404c27c1f2ac2/tools/cpplint.py#L1825-L1840
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/indexes/multi.py
python
MultiIndex.copy
( self, names=None, dtype=None, levels=None, codes=None, deep=False, name=None, )
return new_index
Make a copy of this object. Names, dtype, levels and codes can be passed and will be set on new copy. Parameters ---------- names : sequence, optional dtype : numpy dtype or pandas type, optional .. deprecated:: 1.2.0 levels : sequence, optional .. deprecated:: 1.2.0 codes : sequence, optional .. deprecated:: 1.2.0 deep : bool, default False name : Label Kept for compatibility with 1-dimensional Index. Should not be used. Returns ------- MultiIndex Notes ----- In most cases, there should be no functional difference from using ``deep``, but if ``deep`` is passed it will attempt to deepcopy. This could be potentially expensive on large MultiIndex objects.
Make a copy of this object. Names, dtype, levels and codes can be passed and will be set on new copy.
[ "Make", "a", "copy", "of", "this", "object", ".", "Names", "dtype", "levels", "and", "codes", "can", "be", "passed", "and", "will", "be", "set", "on", "new", "copy", "." ]
def copy( self, names=None, dtype=None, levels=None, codes=None, deep=False, name=None, ): """ Make a copy of this object. Names, dtype, levels and codes can be passed and will be set on new copy. Parameters ---------- names : sequence, optional dtype : numpy dtype or pandas type, optional .. deprecated:: 1.2.0 levels : sequence, optional .. deprecated:: 1.2.0 codes : sequence, optional .. deprecated:: 1.2.0 deep : bool, default False name : Label Kept for compatibility with 1-dimensional Index. Should not be used. Returns ------- MultiIndex Notes ----- In most cases, there should be no functional difference from using ``deep``, but if ``deep`` is passed it will attempt to deepcopy. This could be potentially expensive on large MultiIndex objects. """ names = self._validate_names(name=name, names=names, deep=deep) if levels is not None: warnings.warn( "parameter levels is deprecated and will be removed in a future " "version. Use the set_levels method instead.", FutureWarning, stacklevel=2, ) if codes is not None: warnings.warn( "parameter codes is deprecated and will be removed in a future " "version. Use the set_codes method instead.", FutureWarning, stacklevel=2, ) if deep: from copy import deepcopy if levels is None: levels = deepcopy(self.levels) if codes is None: codes = deepcopy(self.codes) levels = levels if levels is not None else self.levels codes = codes if codes is not None else self.codes new_index = type(self)( levels=levels, codes=codes, sortorder=self.sortorder, names=names, verify_integrity=False, ) new_index._cache = self._cache.copy() new_index._cache.pop("levels", None) # GH32669 if dtype: warnings.warn( "parameter dtype is deprecated and will be removed in a future " "version. Use the astype method instead.", FutureWarning, stacklevel=2, ) new_index = new_index.astype(dtype) return new_index
[ "def", "copy", "(", "self", ",", "names", "=", "None", ",", "dtype", "=", "None", ",", "levels", "=", "None", ",", "codes", "=", "None", ",", "deep", "=", "False", ",", "name", "=", "None", ",", ")", ":", "names", "=", "self", ".", "_validate_names", "(", "name", "=", "name", ",", "names", "=", "names", ",", "deep", "=", "deep", ")", "if", "levels", "is", "not", "None", ":", "warnings", ".", "warn", "(", "\"parameter levels is deprecated and will be removed in a future \"", "\"version. Use the set_levels method instead.\"", ",", "FutureWarning", ",", "stacklevel", "=", "2", ",", ")", "if", "codes", "is", "not", "None", ":", "warnings", ".", "warn", "(", "\"parameter codes is deprecated and will be removed in a future \"", "\"version. Use the set_codes method instead.\"", ",", "FutureWarning", ",", "stacklevel", "=", "2", ",", ")", "if", "deep", ":", "from", "copy", "import", "deepcopy", "if", "levels", "is", "None", ":", "levels", "=", "deepcopy", "(", "self", ".", "levels", ")", "if", "codes", "is", "None", ":", "codes", "=", "deepcopy", "(", "self", ".", "codes", ")", "levels", "=", "levels", "if", "levels", "is", "not", "None", "else", "self", ".", "levels", "codes", "=", "codes", "if", "codes", "is", "not", "None", "else", "self", ".", "codes", "new_index", "=", "type", "(", "self", ")", "(", "levels", "=", "levels", ",", "codes", "=", "codes", ",", "sortorder", "=", "self", ".", "sortorder", ",", "names", "=", "names", ",", "verify_integrity", "=", "False", ",", ")", "new_index", ".", "_cache", "=", "self", ".", "_cache", ".", "copy", "(", ")", "new_index", ".", "_cache", ".", "pop", "(", "\"levels\"", ",", "None", ")", "# GH32669", "if", "dtype", ":", "warnings", ".", "warn", "(", "\"parameter dtype is deprecated and will be removed in a future \"", "\"version. Use the astype method instead.\"", ",", "FutureWarning", ",", "stacklevel", "=", "2", ",", ")", "new_index", "=", "new_index", ".", "astype", "(", "dtype", ")", "return", "new_index" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/indexes/multi.py#L1119-L1203
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/numpy/multiarray.py
python
stack
(arrays, axis=0, out=None)
return _mx_nd_np.stack(arrays, axis=axis, out=out)
Join a sequence of arrays along a new axis. The axis parameter specifies the index of the new axis in the dimensions of the result. For example, if `axis=0` it will be the first dimension and if `axis=-1` it will be the last dimension. Parameters ---------- arrays : sequence of array_like Each array must have the same shape. axis : int, optional The axis in the result array along which the input arrays are stacked. out : ndarray, optional If provided, the destination to place the result. The shape must be correct, matching that of what stack would have returned if no out argument were specified. Returns ------- stacked : ndarray The stacked array has one more dimension than the input arrays. See Also -------- concatenate : Join a sequence of arrays along an existing axis. split : Split array into a list of multiple sub-arrays of equal size. Examples -------- >>> arrays = [np.random.rand(3, 4) for _ in range(10)] >>> np.stack(arrays, axis=0).shape (10, 3, 4) >>> np.stack(arrays, axis=1).shape (3, 10, 4) >>> np.stack(arrays, axis=2).shape (3, 4, 10) >>> a = np.array([1, 2, 3]) >>> b = np.array([2, 3, 4]) >>> np.stack((a, b)) array([[1., 2., 3.], [2., 3., 4.]]) >>> np.stack((a, b), axis=-1) array([[1., 2.], [2., 3.], [3., 4.]])
Join a sequence of arrays along a new axis. The axis parameter specifies the index of the new axis in the dimensions of the result. For example, if `axis=0` it will be the first dimension and if `axis=-1` it will be the last dimension.
[ "Join", "a", "sequence", "of", "arrays", "along", "a", "new", "axis", ".", "The", "axis", "parameter", "specifies", "the", "index", "of", "the", "new", "axis", "in", "the", "dimensions", "of", "the", "result", ".", "For", "example", "if", "axis", "=", "0", "it", "will", "be", "the", "first", "dimension", "and", "if", "axis", "=", "-", "1", "it", "will", "be", "the", "last", "dimension", "." ]
def stack(arrays, axis=0, out=None): """Join a sequence of arrays along a new axis. The axis parameter specifies the index of the new axis in the dimensions of the result. For example, if `axis=0` it will be the first dimension and if `axis=-1` it will be the last dimension. Parameters ---------- arrays : sequence of array_like Each array must have the same shape. axis : int, optional The axis in the result array along which the input arrays are stacked. out : ndarray, optional If provided, the destination to place the result. The shape must be correct, matching that of what stack would have returned if no out argument were specified. Returns ------- stacked : ndarray The stacked array has one more dimension than the input arrays. See Also -------- concatenate : Join a sequence of arrays along an existing axis. split : Split array into a list of multiple sub-arrays of equal size. Examples -------- >>> arrays = [np.random.rand(3, 4) for _ in range(10)] >>> np.stack(arrays, axis=0).shape (10, 3, 4) >>> np.stack(arrays, axis=1).shape (3, 10, 4) >>> np.stack(arrays, axis=2).shape (3, 4, 10) >>> a = np.array([1, 2, 3]) >>> b = np.array([2, 3, 4]) >>> np.stack((a, b)) array([[1., 2., 3.], [2., 3., 4.]]) >>> np.stack((a, b), axis=-1) array([[1., 2.], [2., 3.], [3., 4.]]) """ return _mx_nd_np.stack(arrays, axis=axis, out=out)
[ "def", "stack", "(", "arrays", ",", "axis", "=", "0", ",", "out", "=", "None", ")", ":", "return", "_mx_nd_np", ".", "stack", "(", "arrays", ",", "axis", "=", "axis", ",", "out", "=", "out", ")" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/numpy/multiarray.py#L7453-L7501
aimerykong/Low-Rank-Bilinear-Pooling
487eb2c857fd9c95357a5166b0c15ad0fe135b28
demo3_modelVisualization/vlfeat/docsrc/formatter.py
python
Formatter.parse_DIV
(self, indent)
return xs
Parse a DIV(N) symbol. A DIV(N) a sequence of blank
Parse a DIV(N) symbol. A DIV(N) a sequence of blank
[ "Parse", "a", "DIV", "(", "N", ")", "symbol", ".", "A", "DIV", "(", "N", ")", "a", "sequence", "of", "blank" ]
def parse_DIV(self, indent): "Parse a DIV(N) symbol. A DIV(N) a sequence of blank" "lines (B or other blocks at indentation level N, such as" "pharagraphs P(N), bullet lists BL(N), description lists DN(N)" pos = self.tokens.getpos() xs = [] while True: x = self.parse_Terminal(B) if x: continue x = self.parse_P(indent) if x: xs.append(x) continue x = self.parse_V(indent) if x: xs.append(x) continue x = self.parse_UL(indent) if x: xs.append(x) continue x = self.parse_DL(indent) if x: xs.append(x) continue break if len(xs) == 0: return None return xs
[ "def", "parse_DIV", "(", "self", ",", "indent", ")", ":", "\"lines (B or other blocks at indentation level N, such as\"", "\"pharagraphs P(N), bullet lists BL(N), description lists DN(N)\"", "pos", "=", "self", ".", "tokens", ".", "getpos", "(", ")", "xs", "=", "[", "]", "while", "True", ":", "x", "=", "self", ".", "parse_Terminal", "(", "B", ")", "if", "x", ":", "continue", "x", "=", "self", ".", "parse_P", "(", "indent", ")", "if", "x", ":", "xs", ".", "append", "(", "x", ")", "continue", "x", "=", "self", ".", "parse_V", "(", "indent", ")", "if", "x", ":", "xs", ".", "append", "(", "x", ")", "continue", "x", "=", "self", ".", "parse_UL", "(", "indent", ")", "if", "x", ":", "xs", ".", "append", "(", "x", ")", "continue", "x", "=", "self", ".", "parse_DL", "(", "indent", ")", "if", "x", ":", "xs", ".", "append", "(", "x", ")", "continue", "break", "if", "len", "(", "xs", ")", "==", "0", ":", "return", "None", "return", "xs" ]
https://github.com/aimerykong/Low-Rank-Bilinear-Pooling/blob/487eb2c857fd9c95357a5166b0c15ad0fe135b28/demo3_modelVisualization/vlfeat/docsrc/formatter.py#L293-L325
apache/qpid-proton
6bcdfebb55ea3554bc29b1901422532db331a591
python/proton/_delivery.py
python
Delivery.transport
(self)
return self.connection.transport
The :class:`Transport` bound to the :class:`Connection` over which the delivery was sent or received.
The :class:`Transport` bound to the :class:`Connection` over which the delivery was sent or received.
[ "The", ":", "class", ":", "Transport", "bound", "to", "the", ":", "class", ":", "Connection", "over", "which", "the", "delivery", "was", "sent", "or", "received", "." ]
def transport(self) -> 'Transport': """ The :class:`Transport` bound to the :class:`Connection` over which the delivery was sent or received. """ return self.connection.transport
[ "def", "transport", "(", "self", ")", "->", "'Transport'", ":", "return", "self", ".", "connection", ".", "transport" ]
https://github.com/apache/qpid-proton/blob/6bcdfebb55ea3554bc29b1901422532db331a591/python/proton/_delivery.py#L453-L458
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py
python
UTF8Charcmp
(utf1, utf2)
return ret
compares the two UCS4 values
compares the two UCS4 values
[ "compares", "the", "two", "UCS4", "values" ]
def UTF8Charcmp(utf1, utf2): """compares the two UCS4 values """ ret = libxml2mod.xmlUTF8Charcmp(utf1, utf2) return ret
[ "def", "UTF8Charcmp", "(", "utf1", ",", "utf2", ")", ":", "ret", "=", "libxml2mod", ".", "xmlUTF8Charcmp", "(", "utf1", ",", "utf2", ")", "return", "ret" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L1248-L1251
swift/swift
12d031cf8177fdec0137f9aa7e2912fa23c4416b
3rdParty/SCons/scons-3.0.1/engine/SCons/Tool/docbook/__init__.py
python
__build_libxml2
(target, source, env)
return None
General XSLT builder (HTML/FO), using the libxml2 module.
General XSLT builder (HTML/FO), using the libxml2 module.
[ "General", "XSLT", "builder", "(", "HTML", "/", "FO", ")", "using", "the", "libxml2", "module", "." ]
def __build_libxml2(target, source, env): """ General XSLT builder (HTML/FO), using the libxml2 module. """ xsl_style = env.subst('$DOCBOOK_XSL') styledoc = libxml2.parseFile(xsl_style) style = libxslt.parseStylesheetDoc(styledoc) doc = libxml2.readFile(str(source[0]),None,libxml2.XML_PARSE_NOENT) # Support for additional parameters parampass = {} if parampass: result = style.applyStylesheet(doc, parampass) else: result = style.applyStylesheet(doc, None) style.saveResultToFilename(str(target[0]), result, 0) style.freeStylesheet() doc.freeDoc() result.freeDoc() return None
[ "def", "__build_libxml2", "(", "target", ",", "source", ",", "env", ")", ":", "xsl_style", "=", "env", ".", "subst", "(", "'$DOCBOOK_XSL'", ")", "styledoc", "=", "libxml2", ".", "parseFile", "(", "xsl_style", ")", "style", "=", "libxslt", ".", "parseStylesheetDoc", "(", "styledoc", ")", "doc", "=", "libxml2", ".", "readFile", "(", "str", "(", "source", "[", "0", "]", ")", ",", "None", ",", "libxml2", ".", "XML_PARSE_NOENT", ")", "# Support for additional parameters", "parampass", "=", "{", "}", "if", "parampass", ":", "result", "=", "style", ".", "applyStylesheet", "(", "doc", ",", "parampass", ")", "else", ":", "result", "=", "style", ".", "applyStylesheet", "(", "doc", ",", "None", ")", "style", ".", "saveResultToFilename", "(", "str", "(", "target", "[", "0", "]", ")", ",", "result", ",", "0", ")", "style", ".", "freeStylesheet", "(", ")", "doc", ".", "freeDoc", "(", ")", "result", ".", "freeDoc", "(", ")", "return", "None" ]
https://github.com/swift/swift/blob/12d031cf8177fdec0137f9aa7e2912fa23c4416b/3rdParty/SCons/scons-3.0.1/engine/SCons/Tool/docbook/__init__.py#L309-L328
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Path/PathScripts/PathToolController.py
python
ToolController.getTool
(self, obj)
return obj.Tool
returns the tool associated with this tool controller
returns the tool associated with this tool controller
[ "returns", "the", "tool", "associated", "with", "this", "tool", "controller" ]
def getTool(self, obj): """returns the tool associated with this tool controller""" PathLog.track() return obj.Tool
[ "def", "getTool", "(", "self", ",", "obj", ")", ":", "PathLog", ".", "track", "(", ")", "return", "obj", ".", "Tool" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Path/PathScripts/PathToolController.py#L295-L298
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/extern/aui/auibook.py
python
TabFrame.DoGetSize
(self)
return self._rect.width, self._rect.height
Returns the window size. :note: Overridden from :class:`PyControl`.
Returns the window size.
[ "Returns", "the", "window", "size", "." ]
def DoGetSize(self): """ Returns the window size. :note: Overridden from :class:`PyControl`. """ return self._rect.width, self._rect.height
[ "def", "DoGetSize", "(", "self", ")", ":", "return", "self", ".", "_rect", ".", "width", ",", "self", ".", "_rect", ".", "height" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/auibook.py#L2578-L2585
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
Window.GetAutoLayout
(*args, **kwargs)
return _core_.Window_GetAutoLayout(*args, **kwargs)
GetAutoLayout(self) -> bool Returns the current autoLayout setting
GetAutoLayout(self) -> bool
[ "GetAutoLayout", "(", "self", ")", "-", ">", "bool" ]
def GetAutoLayout(*args, **kwargs): """ GetAutoLayout(self) -> bool Returns the current autoLayout setting """ return _core_.Window_GetAutoLayout(*args, **kwargs)
[ "def", "GetAutoLayout", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Window_GetAutoLayout", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L11483-L11489
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/ultimatelistctrl.py
python
UltimateListHeaderWindow.HitTestColumn
(self, x, y)
return -1
HitTest method for column headers. :param `x`: the mouse `x` position; :param `y`: the mouse `y` position. :return: The column index if any column client rectangle contains the mouse position, ``wx.NOT_FOUND`` otherwise.
HitTest method for column headers.
[ "HitTest", "method", "for", "column", "headers", "." ]
def HitTestColumn(self, x, y): """ HitTest method for column headers. :param `x`: the mouse `x` position; :param `y`: the mouse `y` position. :return: The column index if any column client rectangle contains the mouse position, ``wx.NOT_FOUND`` otherwise. """ xOld = 0 for i in xrange(self._owner.GetColumnCount()): if not self.IsColumnShown(i): continue xOld += self._owner.GetColumnWidth(i) if x <= xOld: return i return -1
[ "def", "HitTestColumn", "(", "self", ",", "x", ",", "y", ")", ":", "xOld", "=", "0", "for", "i", "in", "xrange", "(", "self", ".", "_owner", ".", "GetColumnCount", "(", ")", ")", ":", "if", "not", "self", ".", "IsColumnShown", "(", "i", ")", ":", "continue", "xOld", "+=", "self", ".", "_owner", ".", "GetColumnWidth", "(", "i", ")", "if", "x", "<=", "xOld", ":", "return", "i", "return", "-", "1" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L5673-L5694
albertz/openlierox
d316c14a8eb57848ef56e9bfa7b23a56f694a51b
tools/DedicatedServerVideo/gdata/blogger/data.py
python
BloggerEntry.get_blog_name
(self)
return None
Finds the name of this blog as used in the 'alternate' URL. An alternate URL is in the form 'http://blogName.blogspot.com/'. For an entry representing the above example, this method would return 'blogName'. Returns: The blog's URL name component as a string.
Finds the name of this blog as used in the 'alternate' URL.
[ "Finds", "the", "name", "of", "this", "blog", "as", "used", "in", "the", "alternate", "URL", "." ]
def get_blog_name(self): """Finds the name of this blog as used in the 'alternate' URL. An alternate URL is in the form 'http://blogName.blogspot.com/'. For an entry representing the above example, this method would return 'blogName'. Returns: The blog's URL name component as a string. """ for link in self.link: if link.rel == 'alternate': return BLOG_NAME_PATTERN.match(link.href).group(2) return None
[ "def", "get_blog_name", "(", "self", ")", ":", "for", "link", "in", "self", ".", "link", ":", "if", "link", ".", "rel", "==", "'alternate'", ":", "return", "BLOG_NAME_PATTERN", ".", "match", "(", "link", ".", "href", ")", ".", "group", "(", "2", ")", "return", "None" ]
https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/blogger/data.py#L64-L76
google/llvm-propeller
45c226984fe8377ebfb2ad7713c680d652ba678d
compiler-rt/lib/sanitizer_common/scripts/cpplint.py
python
_IncludeState.ResetSection
(self, directive)
Reset section checking for preprocessor directive. Args: directive: preprocessor directive (e.g. "if", "else").
Reset section checking for preprocessor directive.
[ "Reset", "section", "checking", "for", "preprocessor", "directive", "." ]
def ResetSection(self, directive): """Reset section checking for preprocessor directive. Args: directive: preprocessor directive (e.g. "if", "else"). """ # The name of the current section. self._section = self._INITIAL_SECTION # The path of last found header. self._last_header = '' # Update list of includes. Note that we never pop from the # include list. if directive in ('if', 'ifdef', 'ifndef'): self.include_list.append([]) elif directive in ('else', 'elif'): self.include_list[-1] = []
[ "def", "ResetSection", "(", "self", ",", "directive", ")", ":", "# The name of the current section.", "self", ".", "_section", "=", "self", ".", "_INITIAL_SECTION", "# The path of last found header.", "self", ".", "_last_header", "=", "''", "# Update list of includes. Note that we never pop from the", "# include list.", "if", "directive", "in", "(", "'if'", ",", "'ifdef'", ",", "'ifndef'", ")", ":", "self", ".", "include_list", ".", "append", "(", "[", "]", ")", "elif", "directive", "in", "(", "'else'", ",", "'elif'", ")", ":", "self", ".", "include_list", "[", "-", "1", "]", "=", "[", "]" ]
https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L751-L767
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/pubsub/py2and3.py
python
with_metaclass
(meta, *bases)
return meta("NewBase", bases, {})
Create a base class with a metaclass.
Create a base class with a metaclass.
[ "Create", "a", "base", "class", "with", "a", "metaclass", "." ]
def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" return meta("NewBase", bases, {})
[ "def", "with_metaclass", "(", "meta", ",", "*", "bases", ")", ":", "return", "meta", "(", "\"NewBase\"", ",", "bases", ",", "{", "}", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/pubsub/py2and3.py#L564-L566
google/shaka-player-embedded
dabbeb5b47cc257b37b9a254661546352aaf0afe
shaka/tools/gen_eme_plugins.py
python
_ParsePlugin
(file_path)
Reads the given file and parses it into an object.
Reads the given file and parses it into an object.
[ "Reads", "the", "given", "file", "and", "parses", "it", "into", "an", "object", "." ]
def _ParsePlugin(file_path): """Reads the given file and parses it into an object.""" with open(file_path, 'r') as f: return json.load(f)
[ "def", "_ParsePlugin", "(", "file_path", ")", ":", "with", "open", "(", "file_path", ",", "'r'", ")", "as", "f", ":", "return", "json", ".", "load", "(", "f", ")" ]
https://github.com/google/shaka-player-embedded/blob/dabbeb5b47cc257b37b9a254661546352aaf0afe/shaka/tools/gen_eme_plugins.py#L42-L45
cyberbotics/webots
af7fa7d68dcf7b4550f1f2e132092b41e83698fc
projects/default/controllers/sumo_supervisor/SumoSupervisor.py
python
SumoSupervisor.run
(self, port, disableTrafficLight, directory, step, rotateWheels, maxVehicles, radius, enableHeight, useDisplay, displayRefreshRate, displayZoom, displayFitSize, maximumLateralSpeed, maximumAngularSpeed, laneChangeDelay, traci, sumolib)
Main loop function.
Main loop function.
[ "Main", "loop", "function", "." ]
def run(self, port, disableTrafficLight, directory, step, rotateWheels, maxVehicles, radius, enableHeight, useDisplay, displayRefreshRate, displayZoom, displayFitSize, maximumLateralSpeed, maximumAngularSpeed, laneChangeDelay, traci, sumolib): """Main loop function.""" try: print('Connect to SUMO... This operation may take a few seconds.') self.step(step) traci.init(port, numRetries=20) except: sys.exit('Unable to connect to SUMO, please make sure any previous instance of SUMO is closed.\n You can try' ' changing SUMO port using the "--port" argument.') self.traci = traci self.sumolib = sumolib self.radius = radius self.enableHeight = enableHeight self.sumoClosed = False self.temporaryDirectory = directory self.rootChildren = self.getRoot().getField("children") self.viewpointPosition = self.get_viewpoint_position_field() self.maxWebotsVehicleDistanceToLane = 15 self.webotsVehicleNumber = 0 self.webotsVehicles = {} self.vehicleNumber = 0 self.vehicles = {} self.vehiclesLimit = maxVehicles self.vehiclesClass = {} # for backward compatibility if self.traci.constants.TRACI_VERSION <= 15: self.traci.trafficlight = self.traci.trafficlights # get sumo vehicles already present in the world self.get_initial_vehicles() # parse the net and get the offsets self.net = sumolib.net.readNet((directory + "/sumo.net.xml").replace('/', os.sep)) xOffset = -self.net.getLocationOffset()[0] yOffset = -self.net.getLocationOffset()[1] # Load plugin to the generic SUMO Supervisor (if any) self.usePlugin = False if os.path.exists((directory + "/plugin.py").replace('/', os.sep)): self.usePlugin = True sys.path.append(directory) import plugin sumoSupervisorPlugin = plugin.SumoSupervisorPlugin(self, self.traci, self.net) # Get all the LEDs of the traffic lights if not disableTrafficLight: trafficLightsList = self.traci.trafficlight.getIDList() self.get_traffic_light(trafficLightsList) for id in trafficLightsList: # subscribe to traffic lights state self.traci.trafficlight.subscribe(id, [self.traci.constants.TL_RED_YELLOW_GREEN_STATE]) # Subscribe to new vehicles entering the simulation self.traci.simulation.subscribe([ self.traci.constants.VAR_DEPARTED_VEHICLES_IDS, self.traci.constants.VAR_MIN_EXPECTED_VEHICLES ]) # Create the vehicle variable subscription list self.vehicleVariableList = [ self.traci.constants.VAR_POSITION, self.traci.constants.VAR_ANGLE, self.traci.constants.VAR_LENGTH, self.traci.constants.VAR_ROAD_ID, self.traci.constants.VAR_LANE_INDEX ] if rotateWheels: self.vehicleVariableList.append(self.traci.constants.VAR_SPEED) if enableHeight: self.vehicleVariableList.extend([ self.traci.constants.VAR_ROAD_ID, self.traci.constants.VAR_LANEPOSITION, self.traci.constants.VAR_LANE_ID ]) # create the SUMO display self.sumoDisplay = None if useDisplay: view = self.traci.gui.getIDList()[0] display = self.getDevice('sumo') if display is not None: from SumoDisplay import SumoDisplay self.sumoDisplay = SumoDisplay(display, displayZoom, view, directory, displayRefreshRate, displayFitSize, self.traci) # Main simulation loop while self.step(step) >= 0: if self.usePlugin: sumoSupervisorPlugin.run(step) if self.sumoDisplay is not None: self.sumoDisplay.step(step) # try to perform a SUMO step, if it fails it means SUMO has been closed by the user try: self.traci.simulationStep() except self.traci.exceptions.FatalTraCIError: print("Sumo closed") self.sumoClosed = True break result = self.traci.simulation.getSubscriptionResults() # SUMO simulation over (no more vehicle are expected) if result[self.traci.constants.VAR_MIN_EXPECTED_VEHICLES] == 0: break # subscribe to new vehicle for id in result[self.traci.constants.VAR_DEPARTED_VEHICLES_IDS]: if not id.startswith("webotsVehicle"): self.traci.vehicle.subscribe(id, self.vehicleVariableList) elif self.sumoDisplay is not None and len(self.webotsVehicles) == 1: # Only one vehicle controlled by Webots => center the view on it self.traci.gui.trackVehicle(view, 'webotsVehicle0') # get result from the vehicle subscription and apply it idList = self.traci.vehicle.getIDList() for id in idList: self.get_vehicles_position(id, self.traci.vehicle.getSubscriptionResults(id), step, xOffset, yOffset, maximumLateralSpeed, maximumAngularSpeed, laneChangeDelay) self.disable_unused_vehicles(idList) # hide unused vehicles self.hide_unused_vehicles() if not disableTrafficLight: for id in self.trafficLights: self.update_traffic_light_state(id, self.traci.trafficlight.getSubscriptionResults(id)) self.update_vehicles_position_and_velocity(step, rotateWheels) self.update_webots_vehicles(xOffset, yOffset) if not self.sumoClosed: self.traci.close() else: self.stop_all_vehicles() sys.stdout.flush()
[ "def", "run", "(", "self", ",", "port", ",", "disableTrafficLight", ",", "directory", ",", "step", ",", "rotateWheels", ",", "maxVehicles", ",", "radius", ",", "enableHeight", ",", "useDisplay", ",", "displayRefreshRate", ",", "displayZoom", ",", "displayFitSize", ",", "maximumLateralSpeed", ",", "maximumAngularSpeed", ",", "laneChangeDelay", ",", "traci", ",", "sumolib", ")", ":", "try", ":", "print", "(", "'Connect to SUMO... This operation may take a few seconds.'", ")", "self", ".", "step", "(", "step", ")", "traci", ".", "init", "(", "port", ",", "numRetries", "=", "20", ")", "except", ":", "sys", ".", "exit", "(", "'Unable to connect to SUMO, please make sure any previous instance of SUMO is closed.\\n You can try'", "' changing SUMO port using the \"--port\" argument.'", ")", "self", ".", "traci", "=", "traci", "self", ".", "sumolib", "=", "sumolib", "self", ".", "radius", "=", "radius", "self", ".", "enableHeight", "=", "enableHeight", "self", ".", "sumoClosed", "=", "False", "self", ".", "temporaryDirectory", "=", "directory", "self", ".", "rootChildren", "=", "self", ".", "getRoot", "(", ")", ".", "getField", "(", "\"children\"", ")", "self", ".", "viewpointPosition", "=", "self", ".", "get_viewpoint_position_field", "(", ")", "self", ".", "maxWebotsVehicleDistanceToLane", "=", "15", "self", ".", "webotsVehicleNumber", "=", "0", "self", ".", "webotsVehicles", "=", "{", "}", "self", ".", "vehicleNumber", "=", "0", "self", ".", "vehicles", "=", "{", "}", "self", ".", "vehiclesLimit", "=", "maxVehicles", "self", ".", "vehiclesClass", "=", "{", "}", "# for backward compatibility", "if", "self", ".", "traci", ".", "constants", ".", "TRACI_VERSION", "<=", "15", ":", "self", ".", "traci", ".", "trafficlight", "=", "self", ".", "traci", ".", "trafficlights", "# get sumo vehicles already present in the world", "self", ".", "get_initial_vehicles", "(", ")", "# parse the net and get the offsets", "self", ".", "net", "=", "sumolib", ".", "net", ".", "readNet", "(", "(", "directory", "+", "\"/sumo.net.xml\"", ")", ".", "replace", "(", "'/'", ",", "os", ".", "sep", ")", ")", "xOffset", "=", "-", "self", ".", "net", ".", "getLocationOffset", "(", ")", "[", "0", "]", "yOffset", "=", "-", "self", ".", "net", ".", "getLocationOffset", "(", ")", "[", "1", "]", "# Load plugin to the generic SUMO Supervisor (if any)", "self", ".", "usePlugin", "=", "False", "if", "os", ".", "path", ".", "exists", "(", "(", "directory", "+", "\"/plugin.py\"", ")", ".", "replace", "(", "'/'", ",", "os", ".", "sep", ")", ")", ":", "self", ".", "usePlugin", "=", "True", "sys", ".", "path", ".", "append", "(", "directory", ")", "import", "plugin", "sumoSupervisorPlugin", "=", "plugin", ".", "SumoSupervisorPlugin", "(", "self", ",", "self", ".", "traci", ",", "self", ".", "net", ")", "# Get all the LEDs of the traffic lights", "if", "not", "disableTrafficLight", ":", "trafficLightsList", "=", "self", ".", "traci", ".", "trafficlight", ".", "getIDList", "(", ")", "self", ".", "get_traffic_light", "(", "trafficLightsList", ")", "for", "id", "in", "trafficLightsList", ":", "# subscribe to traffic lights state", "self", ".", "traci", ".", "trafficlight", ".", "subscribe", "(", "id", ",", "[", "self", ".", "traci", ".", "constants", ".", "TL_RED_YELLOW_GREEN_STATE", "]", ")", "# Subscribe to new vehicles entering the simulation", "self", ".", "traci", ".", "simulation", ".", "subscribe", "(", "[", "self", ".", "traci", ".", "constants", ".", "VAR_DEPARTED_VEHICLES_IDS", ",", "self", ".", "traci", ".", "constants", ".", "VAR_MIN_EXPECTED_VEHICLES", "]", ")", "# Create the vehicle variable subscription list", "self", ".", "vehicleVariableList", "=", "[", "self", ".", "traci", ".", "constants", ".", "VAR_POSITION", ",", "self", ".", "traci", ".", "constants", ".", "VAR_ANGLE", ",", "self", ".", "traci", ".", "constants", ".", "VAR_LENGTH", ",", "self", ".", "traci", ".", "constants", ".", "VAR_ROAD_ID", ",", "self", ".", "traci", ".", "constants", ".", "VAR_LANE_INDEX", "]", "if", "rotateWheels", ":", "self", ".", "vehicleVariableList", ".", "append", "(", "self", ".", "traci", ".", "constants", ".", "VAR_SPEED", ")", "if", "enableHeight", ":", "self", ".", "vehicleVariableList", ".", "extend", "(", "[", "self", ".", "traci", ".", "constants", ".", "VAR_ROAD_ID", ",", "self", ".", "traci", ".", "constants", ".", "VAR_LANEPOSITION", ",", "self", ".", "traci", ".", "constants", ".", "VAR_LANE_ID", "]", ")", "# create the SUMO display", "self", ".", "sumoDisplay", "=", "None", "if", "useDisplay", ":", "view", "=", "self", ".", "traci", ".", "gui", ".", "getIDList", "(", ")", "[", "0", "]", "display", "=", "self", ".", "getDevice", "(", "'sumo'", ")", "if", "display", "is", "not", "None", ":", "from", "SumoDisplay", "import", "SumoDisplay", "self", ".", "sumoDisplay", "=", "SumoDisplay", "(", "display", ",", "displayZoom", ",", "view", ",", "directory", ",", "displayRefreshRate", ",", "displayFitSize", ",", "self", ".", "traci", ")", "# Main simulation loop", "while", "self", ".", "step", "(", "step", ")", ">=", "0", ":", "if", "self", ".", "usePlugin", ":", "sumoSupervisorPlugin", ".", "run", "(", "step", ")", "if", "self", ".", "sumoDisplay", "is", "not", "None", ":", "self", ".", "sumoDisplay", ".", "step", "(", "step", ")", "# try to perform a SUMO step, if it fails it means SUMO has been closed by the user", "try", ":", "self", ".", "traci", ".", "simulationStep", "(", ")", "except", "self", ".", "traci", ".", "exceptions", ".", "FatalTraCIError", ":", "print", "(", "\"Sumo closed\"", ")", "self", ".", "sumoClosed", "=", "True", "break", "result", "=", "self", ".", "traci", ".", "simulation", ".", "getSubscriptionResults", "(", ")", "# SUMO simulation over (no more vehicle are expected)", "if", "result", "[", "self", ".", "traci", ".", "constants", ".", "VAR_MIN_EXPECTED_VEHICLES", "]", "==", "0", ":", "break", "# subscribe to new vehicle", "for", "id", "in", "result", "[", "self", ".", "traci", ".", "constants", ".", "VAR_DEPARTED_VEHICLES_IDS", "]", ":", "if", "not", "id", ".", "startswith", "(", "\"webotsVehicle\"", ")", ":", "self", ".", "traci", ".", "vehicle", ".", "subscribe", "(", "id", ",", "self", ".", "vehicleVariableList", ")", "elif", "self", ".", "sumoDisplay", "is", "not", "None", "and", "len", "(", "self", ".", "webotsVehicles", ")", "==", "1", ":", "# Only one vehicle controlled by Webots => center the view on it", "self", ".", "traci", ".", "gui", ".", "trackVehicle", "(", "view", ",", "'webotsVehicle0'", ")", "# get result from the vehicle subscription and apply it", "idList", "=", "self", ".", "traci", ".", "vehicle", ".", "getIDList", "(", ")", "for", "id", "in", "idList", ":", "self", ".", "get_vehicles_position", "(", "id", ",", "self", ".", "traci", ".", "vehicle", ".", "getSubscriptionResults", "(", "id", ")", ",", "step", ",", "xOffset", ",", "yOffset", ",", "maximumLateralSpeed", ",", "maximumAngularSpeed", ",", "laneChangeDelay", ")", "self", ".", "disable_unused_vehicles", "(", "idList", ")", "# hide unused vehicles", "self", ".", "hide_unused_vehicles", "(", ")", "if", "not", "disableTrafficLight", ":", "for", "id", "in", "self", ".", "trafficLights", ":", "self", ".", "update_traffic_light_state", "(", "id", ",", "self", ".", "traci", ".", "trafficlight", ".", "getSubscriptionResults", "(", "id", ")", ")", "self", ".", "update_vehicles_position_and_velocity", "(", "step", ",", "rotateWheels", ")", "self", ".", "update_webots_vehicles", "(", "xOffset", ",", "yOffset", ")", "if", "not", "self", ".", "sumoClosed", ":", "self", ".", "traci", ".", "close", "(", ")", "else", ":", "self", ".", "stop_all_vehicles", "(", ")", "sys", ".", "stdout", ".", "flush", "(", ")" ]
https://github.com/cyberbotics/webots/blob/af7fa7d68dcf7b4550f1f2e132092b41e83698fc/projects/default/controllers/sumo_supervisor/SumoSupervisor.py#L424-L566
AXErunners/axe
53f14e8112ab6370b96e1e78d2858dabc886bba4
contrib/devtools/update-translations.py
python
find_format_specifiers
(s)
return specifiers
Find all format specifiers in a string.
Find all format specifiers in a string.
[ "Find", "all", "format", "specifiers", "in", "a", "string", "." ]
def find_format_specifiers(s): '''Find all format specifiers in a string.''' pos = 0 specifiers = [] while True: percent = s.find('%', pos) if percent < 0: break try: specifiers.append(s[percent+1]) except: print('Failed to get specifier') pos = percent+2 return specifiers
[ "def", "find_format_specifiers", "(", "s", ")", ":", "pos", "=", "0", "specifiers", "=", "[", "]", "while", "True", ":", "percent", "=", "s", ".", "find", "(", "'%'", ",", "pos", ")", "if", "percent", "<", "0", ":", "break", "try", ":", "specifiers", ".", "append", "(", "s", "[", "percent", "+", "1", "]", ")", "except", ":", "print", "(", "'Failed to get specifier'", ")", "pos", "=", "percent", "+", "2", "return", "specifiers" ]
https://github.com/AXErunners/axe/blob/53f14e8112ab6370b96e1e78d2858dabc886bba4/contrib/devtools/update-translations.py#L45-L58
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/Jinja2/py2/jinja2/loaders.py
python
BaseLoader.list_templates
(self)
Iterates over all templates. If the loader does not support that it should raise a :exc:`TypeError` which is the default behavior.
Iterates over all templates. If the loader does not support that it should raise a :exc:`TypeError` which is the default behavior.
[ "Iterates", "over", "all", "templates", ".", "If", "the", "loader", "does", "not", "support", "that", "it", "should", "raise", "a", ":", "exc", ":", "TypeError", "which", "is", "the", "default", "behavior", "." ]
def list_templates(self): """Iterates over all templates. If the loader does not support that it should raise a :exc:`TypeError` which is the default behavior. """ raise TypeError("this loader cannot iterate over all templates")
[ "def", "list_templates", "(", "self", ")", ":", "raise", "TypeError", "(", "\"this loader cannot iterate over all templates\"", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Jinja2/py2/jinja2/loaders.py#L95-L99
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/install.py
python
add_targets_to_INSTALLED_FILES
(target, source, env)
return (target, source)
An emitter that adds all target files to the list stored in the _INSTALLED_FILES global variable. This way all installed files of one scons call will be collected.
An emitter that adds all target files to the list stored in the _INSTALLED_FILES global variable. This way all installed files of one scons call will be collected.
[ "An", "emitter", "that", "adds", "all", "target", "files", "to", "the", "list", "stored", "in", "the", "_INSTALLED_FILES", "global", "variable", ".", "This", "way", "all", "installed", "files", "of", "one", "scons", "call", "will", "be", "collected", "." ]
def add_targets_to_INSTALLED_FILES(target, source, env): """ An emitter that adds all target files to the list stored in the _INSTALLED_FILES global variable. This way all installed files of one scons call will be collected. """ global _INSTALLED_FILES, _UNIQUE_INSTALLED_FILES _INSTALLED_FILES.extend(target) _UNIQUE_INSTALLED_FILES = None return (target, source)
[ "def", "add_targets_to_INSTALLED_FILES", "(", "target", ",", "source", ",", "env", ")", ":", "global", "_INSTALLED_FILES", ",", "_UNIQUE_INSTALLED_FILES", "_INSTALLED_FILES", ".", "extend", "(", "target", ")", "_UNIQUE_INSTALLED_FILES", "=", "None", "return", "(", "target", ",", "source", ")" ]
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/install.py#L227-L236
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/ops/control_flow_ops.py
python
GradLoopState.forward_index
(self)
return self._forward_index
The loop index of forward loop.
The loop index of forward loop.
[ "The", "loop", "index", "of", "forward", "loop", "." ]
def forward_index(self): """The loop index of forward loop.""" return self._forward_index
[ "def", "forward_index", "(", "self", ")", ":", "return", "self", ".", "_forward_index" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/ops/control_flow_ops.py#L571-L573
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py3/IPython/core/interactiveshell.py
python
InteractiveShell.mktempfile
(self, data=None, prefix='ipython_edit_')
return filename
Make a new tempfile and return its filename. This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp), but it registers the created filename internally so ipython cleans it up at exit time. Optional inputs: - data(None): if data is given, it gets written out to the temp file immediately, and the file is closed again.
Make a new tempfile and return its filename.
[ "Make", "a", "new", "tempfile", "and", "return", "its", "filename", "." ]
def mktempfile(self, data=None, prefix='ipython_edit_'): """Make a new tempfile and return its filename. This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp), but it registers the created filename internally so ipython cleans it up at exit time. Optional inputs: - data(None): if data is given, it gets written out to the temp file immediately, and the file is closed again.""" dirname = tempfile.mkdtemp(prefix=prefix) self.tempdirs.append(dirname) handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname) os.close(handle) # On Windows, there can only be one open handle on a file self.tempfiles.append(filename) if data: with open(filename, 'w') as tmp_file: tmp_file.write(data) return filename
[ "def", "mktempfile", "(", "self", ",", "data", "=", "None", ",", "prefix", "=", "'ipython_edit_'", ")", ":", "dirname", "=", "tempfile", ".", "mkdtemp", "(", "prefix", "=", "prefix", ")", "self", ".", "tempdirs", ".", "append", "(", "dirname", ")", "handle", ",", "filename", "=", "tempfile", ".", "mkstemp", "(", "'.py'", ",", "prefix", ",", "dir", "=", "dirname", ")", "os", ".", "close", "(", "handle", ")", "# On Windows, there can only be one open handle on a file", "self", ".", "tempfiles", ".", "append", "(", "filename", ")", "if", "data", ":", "with", "open", "(", "filename", ",", "'w'", ")", "as", "tmp_file", ":", "tmp_file", ".", "write", "(", "data", ")", "return", "filename" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/core/interactiveshell.py#L3634-L3656
gnuradio/gnuradio
09c3c4fa4bfb1a02caac74cb5334dfe065391e3b
gr-digital/python/digital/qa_header_payload_demux.py
python
qa_header_payload_demux.connect_all_blocks
(self, data_src, trigger_src, hpd, mock_header_demod, payload_sink, header_sink)
Connect the standard HPD test flowgraph
Connect the standard HPD test flowgraph
[ "Connect", "the", "standard", "HPD", "test", "flowgraph" ]
def connect_all_blocks(self, data_src, trigger_src, hpd, mock_header_demod, payload_sink, header_sink): """ Connect the standard HPD test flowgraph """ self.tb.connect(data_src, (hpd, 0)) if trigger_src is not None: self.tb.connect(trigger_src, (hpd, 1)) self.tb.connect((hpd, 0), mock_header_demod) self.tb.connect(mock_header_demod, header_sink) self.tb.msg_connect( mock_header_demod, 'header_data', hpd, 'header_data' ) self.tb.connect((hpd, 1), payload_sink)
[ "def", "connect_all_blocks", "(", "self", ",", "data_src", ",", "trigger_src", ",", "hpd", ",", "mock_header_demod", ",", "payload_sink", ",", "header_sink", ")", ":", "self", ".", "tb", ".", "connect", "(", "data_src", ",", "(", "hpd", ",", "0", ")", ")", "if", "trigger_src", "is", "not", "None", ":", "self", ".", "tb", ".", "connect", "(", "trigger_src", ",", "(", "hpd", ",", "1", ")", ")", "self", ".", "tb", ".", "connect", "(", "(", "hpd", ",", "0", ")", ",", "mock_header_demod", ")", "self", ".", "tb", ".", "connect", "(", "mock_header_demod", ",", "header_sink", ")", "self", ".", "tb", ".", "msg_connect", "(", "mock_header_demod", ",", "'header_data'", ",", "hpd", ",", "'header_data'", ")", "self", ".", "tb", ".", "connect", "(", "(", "hpd", ",", "1", ")", ",", "payload_sink", ")" ]
https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/gr-digital/python/digital/qa_header_payload_demux.py#L74-L91
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/contributed/sumopy/coremodules/demand/turnflows_wxgui.py
python
TurnflowWxGuiMixin.on_turnflows_to_routes
(self, event=None)
Generates routes, based on flow information and turnflow probabilities. This function will apply the JTROUTER for each transport mode separately.
Generates routes, based on flow information and turnflow probabilities. This function will apply the JTROUTER for each transport mode separately.
[ "Generates", "routes", "based", "on", "flow", "information", "and", "turnflow", "probabilities", ".", "This", "function", "will", "apply", "the", "JTROUTER", "for", "each", "transport", "mode", "separately", "." ]
def on_turnflows_to_routes(self, event=None): """Generates routes, based on flow information and turnflow probabilities. This function will apply the JTROUTER for each transport mode separately. """ # TODO: maka proper control-panel #self._demand.turnflows.turnflows_to_routes(is_clear_trips = False, is_make_probabilities = True) # self._mainframe.browse_obj(self._demand.trips) tfrouter = turnflows.TurnflowRouter(self._demand.turnflows, logger=self._mainframe.get_logger() ) dlg = ProcessDialog(self._mainframe, tfrouter) dlg.CenterOnScreen() # this does not return until the dialog is closed. val = dlg.ShowModal() # print ' val,val == wx.ID_OK',val,wx.ID_OK,wx.ID_CANCEL,val == wx.ID_CANCEL # print ' status =',dlg.get_status() if dlg.get_status() != 'success': # val == wx.ID_CANCEL: # print ">>>>>>>>>Unsuccessful\n" dlg.Destroy() if dlg.get_status() == 'success': # print ">>>>>>>>>successful\n" # apply current widget values to scenario instance dlg.apply() dlg.Destroy() self._mainframe.browse_obj(self._demand.trips)
[ "def", "on_turnflows_to_routes", "(", "self", ",", "event", "=", "None", ")", ":", "# TODO: maka proper control-panel", "#self._demand.turnflows.turnflows_to_routes(is_clear_trips = False, is_make_probabilities = True)", "# self._mainframe.browse_obj(self._demand.trips)", "tfrouter", "=", "turnflows", ".", "TurnflowRouter", "(", "self", ".", "_demand", ".", "turnflows", ",", "logger", "=", "self", ".", "_mainframe", ".", "get_logger", "(", ")", ")", "dlg", "=", "ProcessDialog", "(", "self", ".", "_mainframe", ",", "tfrouter", ")", "dlg", ".", "CenterOnScreen", "(", ")", "# this does not return until the dialog is closed.", "val", "=", "dlg", ".", "ShowModal", "(", ")", "# print ' val,val == wx.ID_OK',val,wx.ID_OK,wx.ID_CANCEL,val == wx.ID_CANCEL", "# print ' status =',dlg.get_status()", "if", "dlg", ".", "get_status", "(", ")", "!=", "'success'", ":", "# val == wx.ID_CANCEL:", "# print \">>>>>>>>>Unsuccessful\\n\"", "dlg", ".", "Destroy", "(", ")", "if", "dlg", ".", "get_status", "(", ")", "==", "'success'", ":", "# print \">>>>>>>>>successful\\n\"", "# apply current widget values to scenario instance", "dlg", ".", "apply", "(", ")", "dlg", ".", "Destroy", "(", ")", "self", ".", "_mainframe", ".", "browse_obj", "(", "self", ".", "_demand", ".", "trips", ")" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/coremodules/demand/turnflows_wxgui.py#L114-L142
metashell/metashell
f4177e4854ea00c8dbc722cadab26ef413d798ea
3rd/templight/clang/bindings/python/clang/cindex.py
python
TranslationUnit.diagnostics
(self)
return DiagIterator(self)
Return an iterable (and indexable) object containing the diagnostics.
Return an iterable (and indexable) object containing the diagnostics.
[ "Return", "an", "iterable", "(", "and", "indexable", ")", "object", "containing", "the", "diagnostics", "." ]
def diagnostics(self): """ Return an iterable (and indexable) object containing the diagnostics. """ class DiagIterator(object): def __init__(self, tu): self.tu = tu def __len__(self): return int(conf.lib.clang_getNumDiagnostics(self.tu)) def __getitem__(self, key): diag = conf.lib.clang_getDiagnostic(self.tu, key) if not diag: raise IndexError return Diagnostic(diag) return DiagIterator(self)
[ "def", "diagnostics", "(", "self", ")", ":", "class", "DiagIterator", "(", "object", ")", ":", "def", "__init__", "(", "self", ",", "tu", ")", ":", "self", ".", "tu", "=", "tu", "def", "__len__", "(", "self", ")", ":", "return", "int", "(", "conf", ".", "lib", ".", "clang_getNumDiagnostics", "(", "self", ".", "tu", ")", ")", "def", "__getitem__", "(", "self", ",", "key", ")", ":", "diag", "=", "conf", ".", "lib", ".", "clang_getDiagnostic", "(", "self", ".", "tu", ",", "key", ")", "if", "not", "diag", ":", "raise", "IndexError", "return", "Diagnostic", "(", "diag", ")", "return", "DiagIterator", "(", "self", ")" ]
https://github.com/metashell/metashell/blob/f4177e4854ea00c8dbc722cadab26ef413d798ea/3rd/templight/clang/bindings/python/clang/cindex.py#L2969-L2986
google/iree
1224bbdbe65b0d1fdf40e7324f60f68beeaf7c76
integrations/tensorflow/python_projects/iree_tf/iree/tf/support/module_utils.py
python
IreeCompiledModule.reinitialize
(self)
Reinitializes all stateful variables.
Reinitializes all stateful variables.
[ "Reinitializes", "all", "stateful", "variables", "." ]
def reinitialize(self): """Reinitializes all stateful variables.""" # set_random_seed is not needed here because the model_class.__init__ is not # called. self._context = iree.runtime.SystemContext(vm_modules=[self._vm_module], config=self._config)
[ "def", "reinitialize", "(", "self", ")", ":", "# set_random_seed is not needed here because the model_class.__init__ is not", "# called.", "self", ".", "_context", "=", "iree", ".", "runtime", ".", "SystemContext", "(", "vm_modules", "=", "[", "self", ".", "_vm_module", "]", ",", "config", "=", "self", ".", "_config", ")" ]
https://github.com/google/iree/blob/1224bbdbe65b0d1fdf40e7324f60f68beeaf7c76/integrations/tensorflow/python_projects/iree_tf/iree/tf/support/module_utils.py#L432-L437
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/stc.py
python
StyledTextCtrl.CmdKeyAssign
(*args, **kwargs)
return _stc.StyledTextCtrl_CmdKeyAssign(*args, **kwargs)
CmdKeyAssign(self, int key, int modifiers, int cmd) When key+modifier combination km is pressed perform msg.
CmdKeyAssign(self, int key, int modifiers, int cmd)
[ "CmdKeyAssign", "(", "self", "int", "key", "int", "modifiers", "int", "cmd", ")" ]
def CmdKeyAssign(*args, **kwargs): """ CmdKeyAssign(self, int key, int modifiers, int cmd) When key+modifier combination km is pressed perform msg. """ return _stc.StyledTextCtrl_CmdKeyAssign(*args, **kwargs)
[ "def", "CmdKeyAssign", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_CmdKeyAssign", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/stc.py#L2779-L2785
etternagame/etterna
8775f74ac9c353320128609d4b4150672e9a6d04
extern/SQLiteCpp/cpplint.py
python
CheckSpacingForFunctionCall
(filename, line, linenum, error)
Checks for the correctness of various spacing around function calls. Args: filename: The name of the current file. line: The text of the line to check. linenum: The number of the line to check. error: The function to call with any errors found.
Checks for the correctness of various spacing around function calls.
[ "Checks", "for", "the", "correctness", "of", "various", "spacing", "around", "function", "calls", "." ]
def CheckSpacingForFunctionCall(filename, line, linenum, error): """Checks for the correctness of various spacing around function calls. Args: filename: The name of the current file. line: The text of the line to check. linenum: The number of the line to check. error: The function to call with any errors found. """ # Since function calls often occur inside if/for/while/switch # expressions - which have their own, more liberal conventions - we # first see if we should be looking inside such an expression for a # function call, to which we can apply more strict standards. fncall = line # if there's no control flow construct, look at whole line for pattern in (r'\bif\s*\((.*)\)\s*{', r'\bfor\s*\((.*)\)\s*{', r'\bwhile\s*\((.*)\)\s*[{;]', r'\bswitch\s*\((.*)\)\s*{'): match = Search(pattern, line) if match: fncall = match.group(1) # look inside the parens for function calls break # Except in if/for/while/switch, there should never be space # immediately inside parens (eg "f( 3, 4 )"). We make an exception # for nested parens ( (a+b) + c ). Likewise, there should never be # a space before a ( when it's a function argument. I assume it's a # function argument when the char before the whitespace is legal in # a function name (alnum + _) and we're not starting a macro. Also ignore # pointers and references to arrays and functions coz they're too tricky: # we use a very simple way to recognize these: # " (something)(maybe-something)" or # " (something)(maybe-something," or # " (something)[something]" # Note that we assume the contents of [] to be short enough that # they'll never need to wrap. if ( # Ignore control structures. not Search(r'\b(if|for|while|switch|return|new|delete|catch|sizeof)\b', fncall) and # Ignore pointers/references to functions. not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and # Ignore pointers/references to arrays. not Search(r' \([^)]+\)\[[^\]]+\]', fncall)): if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call error(filename, linenum, 'whitespace/parens', 4, 'Extra space after ( in function call') elif Search(r'\(\s+(?!(\s*\\)|\()', fncall): error(filename, linenum, 'whitespace/parens', 2, 'Extra space after (') if (Search(r'\w\s+\(', fncall) and not Search(r'#\s*define|typedef', fncall) and not Search(r'\w\s+\((\w+::)*\*\w+\)\(', fncall)): error(filename, linenum, 'whitespace/parens', 4, 'Extra space before ( in function call') # If the ) is followed only by a newline or a { + newline, assume it's # part of a control statement (if/while/etc), and don't complain if Search(r'[^)]\s+\)\s*[^{\s]', fncall): # If the closing parenthesis is preceded by only whitespaces, # try to give a more descriptive error message. if Search(r'^\s+\)', fncall): error(filename, linenum, 'whitespace/parens', 2, 'Closing ) should be moved to the previous line') else: error(filename, linenum, 'whitespace/parens', 2, 'Extra space before )')
[ "def", "CheckSpacingForFunctionCall", "(", "filename", ",", "line", ",", "linenum", ",", "error", ")", ":", "# Since function calls often occur inside if/for/while/switch", "# expressions - which have their own, more liberal conventions - we", "# first see if we should be looking inside such an expression for a", "# function call, to which we can apply more strict standards.", "fncall", "=", "line", "# if there's no control flow construct, look at whole line", "for", "pattern", "in", "(", "r'\\bif\\s*\\((.*)\\)\\s*{'", ",", "r'\\bfor\\s*\\((.*)\\)\\s*{'", ",", "r'\\bwhile\\s*\\((.*)\\)\\s*[{;]'", ",", "r'\\bswitch\\s*\\((.*)\\)\\s*{'", ")", ":", "match", "=", "Search", "(", "pattern", ",", "line", ")", "if", "match", ":", "fncall", "=", "match", ".", "group", "(", "1", ")", "# look inside the parens for function calls", "break", "# Except in if/for/while/switch, there should never be space", "# immediately inside parens (eg \"f( 3, 4 )\"). We make an exception", "# for nested parens ( (a+b) + c ). Likewise, there should never be", "# a space before a ( when it's a function argument. I assume it's a", "# function argument when the char before the whitespace is legal in", "# a function name (alnum + _) and we're not starting a macro. Also ignore", "# pointers and references to arrays and functions coz they're too tricky:", "# we use a very simple way to recognize these:", "# \" (something)(maybe-something)\" or", "# \" (something)(maybe-something,\" or", "# \" (something)[something]\"", "# Note that we assume the contents of [] to be short enough that", "# they'll never need to wrap.", "if", "(", "# Ignore control structures.", "not", "Search", "(", "r'\\b(if|for|while|switch|return|new|delete|catch|sizeof)\\b'", ",", "fncall", ")", "and", "# Ignore pointers/references to functions.", "not", "Search", "(", "r' \\([^)]+\\)\\([^)]*(\\)|,$)'", ",", "fncall", ")", "and", "# Ignore pointers/references to arrays.", "not", "Search", "(", "r' \\([^)]+\\)\\[[^\\]]+\\]'", ",", "fncall", ")", ")", ":", "if", "Search", "(", "r'\\w\\s*\\(\\s(?!\\s*\\\\$)'", ",", "fncall", ")", ":", "# a ( used for a fn call", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "4", ",", "'Extra space after ( in function call'", ")", "elif", "Search", "(", "r'\\(\\s+(?!(\\s*\\\\)|\\()'", ",", "fncall", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "2", ",", "'Extra space after ('", ")", "if", "(", "Search", "(", "r'\\w\\s+\\('", ",", "fncall", ")", "and", "not", "Search", "(", "r'#\\s*define|typedef'", ",", "fncall", ")", "and", "not", "Search", "(", "r'\\w\\s+\\((\\w+::)*\\*\\w+\\)\\('", ",", "fncall", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "4", ",", "'Extra space before ( in function call'", ")", "# If the ) is followed only by a newline or a { + newline, assume it's", "# part of a control statement (if/while/etc), and don't complain", "if", "Search", "(", "r'[^)]\\s+\\)\\s*[^{\\s]'", ",", "fncall", ")", ":", "# If the closing parenthesis is preceded by only whitespaces,", "# try to give a more descriptive error message.", "if", "Search", "(", "r'^\\s+\\)'", ",", "fncall", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "2", ",", "'Closing ) should be moved to the previous line'", ")", "else", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "2", ",", "'Extra space before )'", ")" ]
https://github.com/etternagame/etterna/blob/8775f74ac9c353320128609d4b4150672e9a6d04/extern/SQLiteCpp/cpplint.py#L2230-L2295
zhaoweicai/hwgq
ebc706bee3e2d145de1da4be446ce8de8740738f
scripts/cpp_lint.py
python
CheckSpacing
(filename, clean_lines, linenum, nesting_state, error)
Checks for the correctness of various spacing issues in the code. Things we check for: spaces around operators, spaces after if/for/while/switch, no spaces around parens in function calls, two spaces between code and comment, don't start a block with a blank line, don't end a function with a blank line, don't add a blank line after public/protected/private, don't have too many blank lines in a row. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found.
Checks for the correctness of various spacing issues in the code.
[ "Checks", "for", "the", "correctness", "of", "various", "spacing", "issues", "in", "the", "code", "." ]
def CheckSpacing(filename, clean_lines, linenum, nesting_state, error): """Checks for the correctness of various spacing issues in the code. Things we check for: spaces around operators, spaces after if/for/while/switch, no spaces around parens in function calls, two spaces between code and comment, don't start a block with a blank line, don't end a function with a blank line, don't add a blank line after public/protected/private, don't have too many blank lines in a row. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ # Don't use "elided" lines here, otherwise we can't check commented lines. # Don't want to use "raw" either, because we don't want to check inside C++11 # raw strings, raw = clean_lines.lines_without_raw_strings line = raw[linenum] # Before nixing comments, check if the line is blank for no good # reason. This includes the first line after a block is opened, and # blank lines at the end of a function (ie, right before a line like '}' # # Skip all the blank line checks if we are immediately inside a # namespace body. In other words, don't issue blank line warnings # for this block: # namespace { # # } # # A warning about missing end of namespace comments will be issued instead. if IsBlankLine(line) and not nesting_state.InNamespaceBody(): elided = clean_lines.elided prev_line = elided[linenum - 1] prevbrace = prev_line.rfind('{') # TODO(unknown): Don't complain if line before blank line, and line after, # both start with alnums and are indented the same amount. # This ignores whitespace at the start of a namespace block # because those are not usually indented. if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1: # OK, we have a blank line at the start of a code block. Before we # complain, we check if it is an exception to the rule: The previous # non-empty line has the parameters of a function header that are indented # 4 spaces (because they did not fit in a 80 column line when placed on # the same line as the function name). We also check for the case where # the previous line is indented 6 spaces, which may happen when the # initializers of a constructor do not fit into a 80 column line. exception = False if Match(r' {6}\w', prev_line): # Initializer list? # We are looking for the opening column of initializer list, which # should be indented 4 spaces to cause 6 space indentation afterwards. search_position = linenum-2 while (search_position >= 0 and Match(r' {6}\w', elided[search_position])): search_position -= 1 exception = (search_position >= 0 and elided[search_position][:5] == ' :') else: # Search for the function arguments or an initializer list. We use a # simple heuristic here: If the line is indented 4 spaces; and we have a # closing paren, without the opening paren, followed by an opening brace # or colon (for initializer lists) we assume that it is the last line of # a function header. If we have a colon indented 4 spaces, it is an # initializer list. exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)', prev_line) or Match(r' {4}:', prev_line)) if not exception: error(filename, linenum, 'whitespace/blank_line', 2, 'Redundant blank line at the start of a code block ' 'should be deleted.') # Ignore blank lines at the end of a block in a long if-else # chain, like this: # if (condition1) { # // Something followed by a blank line # # } else if (condition2) { # // Something else # } if linenum + 1 < clean_lines.NumLines(): next_line = raw[linenum + 1] if (next_line and Match(r'\s*}', next_line) and next_line.find('} else ') == -1): error(filename, linenum, 'whitespace/blank_line', 3, 'Redundant blank line at the end of a code block ' 'should be deleted.') matched = Match(r'\s*(public|protected|private):', prev_line) if matched: error(filename, linenum, 'whitespace/blank_line', 3, 'Do not leave a blank line after "%s:"' % matched.group(1)) # Next, we complain if there's a comment too near the text commentpos = line.find('//') if commentpos != -1: # Check if the // may be in quotes. If so, ignore it # Comparisons made explicit for clarity -- pylint: disable=g-explicit-bool-comparison if (line.count('"', 0, commentpos) - line.count('\\"', 0, commentpos)) % 2 == 0: # not in quotes # Allow one space for new scopes, two spaces otherwise: if (not Match(r'^\s*{ //', line) and ((commentpos >= 1 and line[commentpos-1] not in string.whitespace) or (commentpos >= 2 and line[commentpos-2] not in string.whitespace))): error(filename, linenum, 'whitespace/comments', 2, 'At least two spaces is best between code and comments') # There should always be a space between the // and the comment commentend = commentpos + 2 if commentend < len(line) and not line[commentend] == ' ': # but some lines are exceptions -- e.g. if they're big # comment delimiters like: # //---------------------------------------------------------- # or are an empty C++ style Doxygen comment, like: # /// # or C++ style Doxygen comments placed after the variable: # ///< Header comment # //!< Header comment # or they begin with multiple slashes followed by a space: # //////// Header comment match = (Search(r'[=/-]{4,}\s*$', line[commentend:]) or Search(r'^/$', line[commentend:]) or Search(r'^!< ', line[commentend:]) or Search(r'^/< ', line[commentend:]) or Search(r'^/+ ', line[commentend:])) if not match: error(filename, linenum, 'whitespace/comments', 4, 'Should have a space between // and comment') CheckComment(line[commentpos:], filename, linenum, error) line = clean_lines.elided[linenum] # get rid of comments and strings # Don't try to do spacing checks for operator methods line = re.sub(r'operator(==|!=|<|<<|<=|>=|>>|>)\(', 'operator\(', line) # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )". # Otherwise not. Note we only check for non-spaces on *both* sides; # sometimes people put non-spaces on one side when aligning ='s among # many lines (not that this is behavior that I approve of...) if Search(r'[\w.]=[\w.]', line) and not Search(r'\b(if|while) ', line): error(filename, linenum, 'whitespace/operators', 4, 'Missing spaces around =') # It's ok not to have spaces around binary operators like + - * /, but if # there's too little whitespace, we get concerned. It's hard to tell, # though, so we punt on this one for now. TODO. # You should always have whitespace around binary operators. # # Check <= and >= first to avoid false positives with < and >, then # check non-include lines for spacing around < and >. match = Search(r'[^<>=!\s](==|!=|<=|>=)[^<>=!\s]', line) if match: error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around %s' % match.group(1)) # We allow no-spaces around << when used like this: 10<<20, but # not otherwise (particularly, not when used as streams) # Also ignore using ns::operator<<; match = Search(r'(operator|\S)(?:L|UL|ULL|l|ul|ull)?<<(\S)', line) if (match and not (match.group(1).isdigit() and match.group(2).isdigit()) and not (match.group(1) == 'operator' and match.group(2) == ';')): error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around <<') elif not Match(r'#.*include', line): # Avoid false positives on -> reduced_line = line.replace('->', '') # Look for < that is not surrounded by spaces. This is only # triggered if both sides are missing spaces, even though # technically should should flag if at least one side is missing a # space. This is done to avoid some false positives with shifts. match = Search(r'[^\s<]<([^\s=<].*)', reduced_line) if (match and not FindNextMatchingAngleBracket(clean_lines, linenum, match.group(1))): error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around <') # Look for > that is not surrounded by spaces. Similar to the # above, we only trigger if both sides are missing spaces to avoid # false positives with shifts. match = Search(r'^(.*[^\s>])>[^\s=>]', reduced_line) if (match and not FindPreviousMatchingAngleBracket(clean_lines, linenum, match.group(1))): error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around >') # We allow no-spaces around >> for almost anything. This is because # C++11 allows ">>" to close nested templates, which accounts for # most cases when ">>" is not followed by a space. # # We still warn on ">>" followed by alpha character, because that is # likely due to ">>" being used for right shifts, e.g.: # value >> alpha # # When ">>" is used to close templates, the alphanumeric letter that # follows would be part of an identifier, and there should still be # a space separating the template type and the identifier. # type<type<type>> alpha match = Search(r'>>[a-zA-Z_]', line) if match: error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around >>') # There shouldn't be space around unary operators match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line) if match: error(filename, linenum, 'whitespace/operators', 4, 'Extra space for operator %s' % match.group(1)) # A pet peeve of mine: no spaces after an if, while, switch, or for match = Search(r' (if\(|for\(|while\(|switch\()', line) if match: error(filename, linenum, 'whitespace/parens', 5, 'Missing space before ( in %s' % match.group(1)) # For if/for/while/switch, the left and right parens should be # consistent about how many spaces are inside the parens, and # there should either be zero or one spaces inside the parens. # We don't want: "if ( foo)" or "if ( foo )". # Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed. match = Search(r'\b(if|for|while|switch)\s*' r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$', line) if match: if len(match.group(2)) != len(match.group(4)): if not (match.group(3) == ';' and len(match.group(2)) == 1 + len(match.group(4)) or not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)): error(filename, linenum, 'whitespace/parens', 5, 'Mismatching spaces inside () in %s' % match.group(1)) if len(match.group(2)) not in [0, 1]: error(filename, linenum, 'whitespace/parens', 5, 'Should have zero or one spaces inside ( and ) in %s' % match.group(1)) # You should always have a space after a comma (either as fn arg or operator) # # This does not apply when the non-space character following the # comma is another comma, since the only time when that happens is # for empty macro arguments. # # We run this check in two passes: first pass on elided lines to # verify that lines contain missing whitespaces, second pass on raw # lines to confirm that those missing whitespaces are not due to # elided comments. if Search(r',[^,\s]', line) and Search(r',[^,\s]', raw[linenum]): error(filename, linenum, 'whitespace/comma', 3, 'Missing space after ,') # You should always have a space after a semicolon # except for few corner cases # TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more # space after ; if Search(r';[^\s};\\)/]', line): error(filename, linenum, 'whitespace/semicolon', 3, 'Missing space after ;') # Next we will look for issues with function calls. CheckSpacingForFunctionCall(filename, line, linenum, error) # Except after an opening paren, or after another opening brace (in case of # an initializer list, for instance), you should have spaces before your # braces. And since you should never have braces at the beginning of a line, # this is an easy test. match = Match(r'^(.*[^ ({]){', line) if match: # Try a bit harder to check for brace initialization. This # happens in one of the following forms: # Constructor() : initializer_list_{} { ... } # Constructor{}.MemberFunction() # Type variable{}; # FunctionCall(type{}, ...); # LastArgument(..., type{}); # LOG(INFO) << type{} << " ..."; # map_of_type[{...}] = ...; # # We check for the character following the closing brace, and # silence the warning if it's one of those listed above, i.e. # "{.;,)<]". # # To account for nested initializer list, we allow any number of # closing braces up to "{;,)<". We can't simply silence the # warning on first sight of closing brace, because that would # cause false negatives for things that are not initializer lists. # Silence this: But not this: # Outer{ if (...) { # Inner{...} if (...){ // Missing space before { # }; } # # There is a false negative with this approach if people inserted # spurious semicolons, e.g. "if (cond){};", but we will catch the # spurious semicolon with a separate check. (endline, endlinenum, endpos) = CloseExpression( clean_lines, linenum, len(match.group(1))) trailing_text = '' if endpos > -1: trailing_text = endline[endpos:] for offset in xrange(endlinenum + 1, min(endlinenum + 3, clean_lines.NumLines() - 1)): trailing_text += clean_lines.elided[offset] if not Match(r'^[\s}]*[{.;,)<\]]', trailing_text): error(filename, linenum, 'whitespace/braces', 5, 'Missing space before {') # Make sure '} else {' has spaces. if Search(r'}else', line): error(filename, linenum, 'whitespace/braces', 5, 'Missing space before else') # You shouldn't have spaces before your brackets, except maybe after # 'delete []' or 'new char * []'. if Search(r'\w\s+\[', line) and not Search(r'delete\s+\[', line): error(filename, linenum, 'whitespace/braces', 5, 'Extra space before [') # You shouldn't have a space before a semicolon at the end of the line. # There's a special case for "for" since the style guide allows space before # the semicolon there. if Search(r':\s*;\s*$', line): error(filename, linenum, 'whitespace/semicolon', 5, 'Semicolon defining empty statement. Use {} instead.') elif Search(r'^\s*;\s*$', line): error(filename, linenum, 'whitespace/semicolon', 5, 'Line contains only semicolon. If this should be an empty statement, ' 'use {} instead.') elif (Search(r'\s+;\s*$', line) and not Search(r'\bfor\b', line)): error(filename, linenum, 'whitespace/semicolon', 5, 'Extra space before last semicolon. If this should be an empty ' 'statement, use {} instead.') # In range-based for, we wanted spaces before and after the colon, but # not around "::" tokens that might appear. if (Search('for *\(.*[^:]:[^: ]', line) or Search('for *\(.*[^: ]:[^:]', line)): error(filename, linenum, 'whitespace/forcolon', 2, 'Missing space around colon in range-based for loop')
[ "def", "CheckSpacing", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "nesting_state", ",", "error", ")", ":", "# Don't use \"elided\" lines here, otherwise we can't check commented lines.", "# Don't want to use \"raw\" either, because we don't want to check inside C++11", "# raw strings,", "raw", "=", "clean_lines", ".", "lines_without_raw_strings", "line", "=", "raw", "[", "linenum", "]", "# Before nixing comments, check if the line is blank for no good", "# reason. This includes the first line after a block is opened, and", "# blank lines at the end of a function (ie, right before a line like '}'", "#", "# Skip all the blank line checks if we are immediately inside a", "# namespace body. In other words, don't issue blank line warnings", "# for this block:", "# namespace {", "#", "# }", "#", "# A warning about missing end of namespace comments will be issued instead.", "if", "IsBlankLine", "(", "line", ")", "and", "not", "nesting_state", ".", "InNamespaceBody", "(", ")", ":", "elided", "=", "clean_lines", ".", "elided", "prev_line", "=", "elided", "[", "linenum", "-", "1", "]", "prevbrace", "=", "prev_line", ".", "rfind", "(", "'{'", ")", "# TODO(unknown): Don't complain if line before blank line, and line after,", "# both start with alnums and are indented the same amount.", "# This ignores whitespace at the start of a namespace block", "# because those are not usually indented.", "if", "prevbrace", "!=", "-", "1", "and", "prev_line", "[", "prevbrace", ":", "]", ".", "find", "(", "'}'", ")", "==", "-", "1", ":", "# OK, we have a blank line at the start of a code block. Before we", "# complain, we check if it is an exception to the rule: The previous", "# non-empty line has the parameters of a function header that are indented", "# 4 spaces (because they did not fit in a 80 column line when placed on", "# the same line as the function name). We also check for the case where", "# the previous line is indented 6 spaces, which may happen when the", "# initializers of a constructor do not fit into a 80 column line.", "exception", "=", "False", "if", "Match", "(", "r' {6}\\w'", ",", "prev_line", ")", ":", "# Initializer list?", "# We are looking for the opening column of initializer list, which", "# should be indented 4 spaces to cause 6 space indentation afterwards.", "search_position", "=", "linenum", "-", "2", "while", "(", "search_position", ">=", "0", "and", "Match", "(", "r' {6}\\w'", ",", "elided", "[", "search_position", "]", ")", ")", ":", "search_position", "-=", "1", "exception", "=", "(", "search_position", ">=", "0", "and", "elided", "[", "search_position", "]", "[", ":", "5", "]", "==", "' :'", ")", "else", ":", "# Search for the function arguments or an initializer list. We use a", "# simple heuristic here: If the line is indented 4 spaces; and we have a", "# closing paren, without the opening paren, followed by an opening brace", "# or colon (for initializer lists) we assume that it is the last line of", "# a function header. If we have a colon indented 4 spaces, it is an", "# initializer list.", "exception", "=", "(", "Match", "(", "r' {4}\\w[^\\(]*\\)\\s*(const\\s*)?(\\{\\s*$|:)'", ",", "prev_line", ")", "or", "Match", "(", "r' {4}:'", ",", "prev_line", ")", ")", "if", "not", "exception", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/blank_line'", ",", "2", ",", "'Redundant blank line at the start of a code block '", "'should be deleted.'", ")", "# Ignore blank lines at the end of a block in a long if-else", "# chain, like this:", "# if (condition1) {", "# // Something followed by a blank line", "#", "# } else if (condition2) {", "# // Something else", "# }", "if", "linenum", "+", "1", "<", "clean_lines", ".", "NumLines", "(", ")", ":", "next_line", "=", "raw", "[", "linenum", "+", "1", "]", "if", "(", "next_line", "and", "Match", "(", "r'\\s*}'", ",", "next_line", ")", "and", "next_line", ".", "find", "(", "'} else '", ")", "==", "-", "1", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/blank_line'", ",", "3", ",", "'Redundant blank line at the end of a code block '", "'should be deleted.'", ")", "matched", "=", "Match", "(", "r'\\s*(public|protected|private):'", ",", "prev_line", ")", "if", "matched", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/blank_line'", ",", "3", ",", "'Do not leave a blank line after \"%s:\"'", "%", "matched", ".", "group", "(", "1", ")", ")", "# Next, we complain if there's a comment too near the text", "commentpos", "=", "line", ".", "find", "(", "'//'", ")", "if", "commentpos", "!=", "-", "1", ":", "# Check if the // may be in quotes. If so, ignore it", "# Comparisons made explicit for clarity -- pylint: disable=g-explicit-bool-comparison", "if", "(", "line", ".", "count", "(", "'\"'", ",", "0", ",", "commentpos", ")", "-", "line", ".", "count", "(", "'\\\\\"'", ",", "0", ",", "commentpos", ")", ")", "%", "2", "==", "0", ":", "# not in quotes", "# Allow one space for new scopes, two spaces otherwise:", "if", "(", "not", "Match", "(", "r'^\\s*{ //'", ",", "line", ")", "and", "(", "(", "commentpos", ">=", "1", "and", "line", "[", "commentpos", "-", "1", "]", "not", "in", "string", ".", "whitespace", ")", "or", "(", "commentpos", ">=", "2", "and", "line", "[", "commentpos", "-", "2", "]", "not", "in", "string", ".", "whitespace", ")", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/comments'", ",", "2", ",", "'At least two spaces is best between code and comments'", ")", "# There should always be a space between the // and the comment", "commentend", "=", "commentpos", "+", "2", "if", "commentend", "<", "len", "(", "line", ")", "and", "not", "line", "[", "commentend", "]", "==", "' '", ":", "# but some lines are exceptions -- e.g. if they're big", "# comment delimiters like:", "# //----------------------------------------------------------", "# or are an empty C++ style Doxygen comment, like:", "# ///", "# or C++ style Doxygen comments placed after the variable:", "# ///< Header comment", "# //!< Header comment", "# or they begin with multiple slashes followed by a space:", "# //////// Header comment", "match", "=", "(", "Search", "(", "r'[=/-]{4,}\\s*$'", ",", "line", "[", "commentend", ":", "]", ")", "or", "Search", "(", "r'^/$'", ",", "line", "[", "commentend", ":", "]", ")", "or", "Search", "(", "r'^!< '", ",", "line", "[", "commentend", ":", "]", ")", "or", "Search", "(", "r'^/< '", ",", "line", "[", "commentend", ":", "]", ")", "or", "Search", "(", "r'^/+ '", ",", "line", "[", "commentend", ":", "]", ")", ")", "if", "not", "match", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/comments'", ",", "4", ",", "'Should have a space between // and comment'", ")", "CheckComment", "(", "line", "[", "commentpos", ":", "]", ",", "filename", ",", "linenum", ",", "error", ")", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# get rid of comments and strings", "# Don't try to do spacing checks for operator methods", "line", "=", "re", ".", "sub", "(", "r'operator(==|!=|<|<<|<=|>=|>>|>)\\('", ",", "'operator\\('", ",", "line", ")", "# We allow no-spaces around = within an if: \"if ( (a=Foo()) == 0 )\".", "# Otherwise not. Note we only check for non-spaces on *both* sides;", "# sometimes people put non-spaces on one side when aligning ='s among", "# many lines (not that this is behavior that I approve of...)", "if", "Search", "(", "r'[\\w.]=[\\w.]'", ",", "line", ")", "and", "not", "Search", "(", "r'\\b(if|while) '", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/operators'", ",", "4", ",", "'Missing spaces around ='", ")", "# It's ok not to have spaces around binary operators like + - * /, but if", "# there's too little whitespace, we get concerned. It's hard to tell,", "# though, so we punt on this one for now. TODO.", "# You should always have whitespace around binary operators.", "#", "# Check <= and >= first to avoid false positives with < and >, then", "# check non-include lines for spacing around < and >.", "match", "=", "Search", "(", "r'[^<>=!\\s](==|!=|<=|>=)[^<>=!\\s]'", ",", "line", ")", "if", "match", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/operators'", ",", "3", ",", "'Missing spaces around %s'", "%", "match", ".", "group", "(", "1", ")", ")", "# We allow no-spaces around << when used like this: 10<<20, but", "# not otherwise (particularly, not when used as streams)", "# Also ignore using ns::operator<<;", "match", "=", "Search", "(", "r'(operator|\\S)(?:L|UL|ULL|l|ul|ull)?<<(\\S)'", ",", "line", ")", "if", "(", "match", "and", "not", "(", "match", ".", "group", "(", "1", ")", ".", "isdigit", "(", ")", "and", "match", ".", "group", "(", "2", ")", ".", "isdigit", "(", ")", ")", "and", "not", "(", "match", ".", "group", "(", "1", ")", "==", "'operator'", "and", "match", ".", "group", "(", "2", ")", "==", "';'", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/operators'", ",", "3", ",", "'Missing spaces around <<'", ")", "elif", "not", "Match", "(", "r'#.*include'", ",", "line", ")", ":", "# Avoid false positives on ->", "reduced_line", "=", "line", ".", "replace", "(", "'->'", ",", "''", ")", "# Look for < that is not surrounded by spaces. This is only", "# triggered if both sides are missing spaces, even though", "# technically should should flag if at least one side is missing a", "# space. This is done to avoid some false positives with shifts.", "match", "=", "Search", "(", "r'[^\\s<]<([^\\s=<].*)'", ",", "reduced_line", ")", "if", "(", "match", "and", "not", "FindNextMatchingAngleBracket", "(", "clean_lines", ",", "linenum", ",", "match", ".", "group", "(", "1", ")", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/operators'", ",", "3", ",", "'Missing spaces around <'", ")", "# Look for > that is not surrounded by spaces. Similar to the", "# above, we only trigger if both sides are missing spaces to avoid", "# false positives with shifts.", "match", "=", "Search", "(", "r'^(.*[^\\s>])>[^\\s=>]'", ",", "reduced_line", ")", "if", "(", "match", "and", "not", "FindPreviousMatchingAngleBracket", "(", "clean_lines", ",", "linenum", ",", "match", ".", "group", "(", "1", ")", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/operators'", ",", "3", ",", "'Missing spaces around >'", ")", "# We allow no-spaces around >> for almost anything. This is because", "# C++11 allows \">>\" to close nested templates, which accounts for", "# most cases when \">>\" is not followed by a space.", "#", "# We still warn on \">>\" followed by alpha character, because that is", "# likely due to \">>\" being used for right shifts, e.g.:", "# value >> alpha", "#", "# When \">>\" is used to close templates, the alphanumeric letter that", "# follows would be part of an identifier, and there should still be", "# a space separating the template type and the identifier.", "# type<type<type>> alpha", "match", "=", "Search", "(", "r'>>[a-zA-Z_]'", ",", "line", ")", "if", "match", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/operators'", ",", "3", ",", "'Missing spaces around >>'", ")", "# There shouldn't be space around unary operators", "match", "=", "Search", "(", "r'(!\\s|~\\s|[\\s]--[\\s;]|[\\s]\\+\\+[\\s;])'", ",", "line", ")", "if", "match", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/operators'", ",", "4", ",", "'Extra space for operator %s'", "%", "match", ".", "group", "(", "1", ")", ")", "# A pet peeve of mine: no spaces after an if, while, switch, or for", "match", "=", "Search", "(", "r' (if\\(|for\\(|while\\(|switch\\()'", ",", "line", ")", "if", "match", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "5", ",", "'Missing space before ( in %s'", "%", "match", ".", "group", "(", "1", ")", ")", "# For if/for/while/switch, the left and right parens should be", "# consistent about how many spaces are inside the parens, and", "# there should either be zero or one spaces inside the parens.", "# We don't want: \"if ( foo)\" or \"if ( foo )\".", "# Exception: \"for ( ; foo; bar)\" and \"for (foo; bar; )\" are allowed.", "match", "=", "Search", "(", "r'\\b(if|for|while|switch)\\s*'", "r'\\(([ ]*)(.).*[^ ]+([ ]*)\\)\\s*{\\s*$'", ",", "line", ")", "if", "match", ":", "if", "len", "(", "match", ".", "group", "(", "2", ")", ")", "!=", "len", "(", "match", ".", "group", "(", "4", ")", ")", ":", "if", "not", "(", "match", ".", "group", "(", "3", ")", "==", "';'", "and", "len", "(", "match", ".", "group", "(", "2", ")", ")", "==", "1", "+", "len", "(", "match", ".", "group", "(", "4", ")", ")", "or", "not", "match", ".", "group", "(", "2", ")", "and", "Search", "(", "r'\\bfor\\s*\\(.*; \\)'", ",", "line", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "5", ",", "'Mismatching spaces inside () in %s'", "%", "match", ".", "group", "(", "1", ")", ")", "if", "len", "(", "match", ".", "group", "(", "2", ")", ")", "not", "in", "[", "0", ",", "1", "]", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "5", ",", "'Should have zero or one spaces inside ( and ) in %s'", "%", "match", ".", "group", "(", "1", ")", ")", "# You should always have a space after a comma (either as fn arg or operator)", "#", "# This does not apply when the non-space character following the", "# comma is another comma, since the only time when that happens is", "# for empty macro arguments.", "#", "# We run this check in two passes: first pass on elided lines to", "# verify that lines contain missing whitespaces, second pass on raw", "# lines to confirm that those missing whitespaces are not due to", "# elided comments.", "if", "Search", "(", "r',[^,\\s]'", ",", "line", ")", "and", "Search", "(", "r',[^,\\s]'", ",", "raw", "[", "linenum", "]", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/comma'", ",", "3", ",", "'Missing space after ,'", ")", "# You should always have a space after a semicolon", "# except for few corner cases", "# TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more", "# space after ;", "if", "Search", "(", "r';[^\\s};\\\\)/]'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/semicolon'", ",", "3", ",", "'Missing space after ;'", ")", "# Next we will look for issues with function calls.", "CheckSpacingForFunctionCall", "(", "filename", ",", "line", ",", "linenum", ",", "error", ")", "# Except after an opening paren, or after another opening brace (in case of", "# an initializer list, for instance), you should have spaces before your", "# braces. And since you should never have braces at the beginning of a line,", "# this is an easy test.", "match", "=", "Match", "(", "r'^(.*[^ ({]){'", ",", "line", ")", "if", "match", ":", "# Try a bit harder to check for brace initialization. This", "# happens in one of the following forms:", "# Constructor() : initializer_list_{} { ... }", "# Constructor{}.MemberFunction()", "# Type variable{};", "# FunctionCall(type{}, ...);", "# LastArgument(..., type{});", "# LOG(INFO) << type{} << \" ...\";", "# map_of_type[{...}] = ...;", "#", "# We check for the character following the closing brace, and", "# silence the warning if it's one of those listed above, i.e.", "# \"{.;,)<]\".", "#", "# To account for nested initializer list, we allow any number of", "# closing braces up to \"{;,)<\". We can't simply silence the", "# warning on first sight of closing brace, because that would", "# cause false negatives for things that are not initializer lists.", "# Silence this: But not this:", "# Outer{ if (...) {", "# Inner{...} if (...){ // Missing space before {", "# }; }", "#", "# There is a false negative with this approach if people inserted", "# spurious semicolons, e.g. \"if (cond){};\", but we will catch the", "# spurious semicolon with a separate check.", "(", "endline", ",", "endlinenum", ",", "endpos", ")", "=", "CloseExpression", "(", "clean_lines", ",", "linenum", ",", "len", "(", "match", ".", "group", "(", "1", ")", ")", ")", "trailing_text", "=", "''", "if", "endpos", ">", "-", "1", ":", "trailing_text", "=", "endline", "[", "endpos", ":", "]", "for", "offset", "in", "xrange", "(", "endlinenum", "+", "1", ",", "min", "(", "endlinenum", "+", "3", ",", "clean_lines", ".", "NumLines", "(", ")", "-", "1", ")", ")", ":", "trailing_text", "+=", "clean_lines", ".", "elided", "[", "offset", "]", "if", "not", "Match", "(", "r'^[\\s}]*[{.;,)<\\]]'", ",", "trailing_text", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/braces'", ",", "5", ",", "'Missing space before {'", ")", "# Make sure '} else {' has spaces.", "if", "Search", "(", "r'}else'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/braces'", ",", "5", ",", "'Missing space before else'", ")", "# You shouldn't have spaces before your brackets, except maybe after", "# 'delete []' or 'new char * []'.", "if", "Search", "(", "r'\\w\\s+\\['", ",", "line", ")", "and", "not", "Search", "(", "r'delete\\s+\\['", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/braces'", ",", "5", ",", "'Extra space before ['", ")", "# You shouldn't have a space before a semicolon at the end of the line.", "# There's a special case for \"for\" since the style guide allows space before", "# the semicolon there.", "if", "Search", "(", "r':\\s*;\\s*$'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/semicolon'", ",", "5", ",", "'Semicolon defining empty statement. Use {} instead.'", ")", "elif", "Search", "(", "r'^\\s*;\\s*$'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/semicolon'", ",", "5", ",", "'Line contains only semicolon. If this should be an empty statement, '", "'use {} instead.'", ")", "elif", "(", "Search", "(", "r'\\s+;\\s*$'", ",", "line", ")", "and", "not", "Search", "(", "r'\\bfor\\b'", ",", "line", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/semicolon'", ",", "5", ",", "'Extra space before last semicolon. If this should be an empty '", "'statement, use {} instead.'", ")", "# In range-based for, we wanted spaces before and after the colon, but", "# not around \"::\" tokens that might appear.", "if", "(", "Search", "(", "'for *\\(.*[^:]:[^: ]'", ",", "line", ")", "or", "Search", "(", "'for *\\(.*[^: ]:[^:]'", ",", "line", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/forcolon'", ",", "2", ",", "'Missing space around colon in range-based for loop'", ")" ]
https://github.com/zhaoweicai/hwgq/blob/ebc706bee3e2d145de1da4be446ce8de8740738f/scripts/cpp_lint.py#L2643-L2988
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/mplgraphicsview.py
python
MplGraphicsView.draw
(self)
return self._myCanvas.draw()
Draw to commit the change
Draw to commit the change
[ "Draw", "to", "commit", "the", "change" ]
def draw(self): """ Draw to commit the change """ return self._myCanvas.draw()
[ "def", "draw", "(", "self", ")", ":", "return", "self", ".", "_myCanvas", ".", "draw", "(", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/mplgraphicsview.py#L656-L659
google/syzygy
8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5
third_party/numpy/files/numpy/lib/twodim_base.py
python
vander
(x, N=None)
return X
Generate a Van der Monde matrix. The columns of the output matrix are decreasing powers of the input vector. Specifically, the `i`-th output column is the input vector raised element-wise to the power of ``N - i - 1``. Such a matrix with a geometric progression in each row is named for Alexandre-Theophile Vandermonde. Parameters ---------- x : array_like 1-D input array. N : int, optional Order of (number of columns in) the output. If `N` is not specified, a square array is returned (``N = len(x)``). Returns ------- out : ndarray Van der Monde matrix of order `N`. The first column is ``x^(N-1)``, the second ``x^(N-2)`` and so forth. Examples -------- >>> x = np.array([1, 2, 3, 5]) >>> N = 3 >>> np.vander(x, N) array([[ 1, 1, 1], [ 4, 2, 1], [ 9, 3, 1], [25, 5, 1]]) >>> np.column_stack([x**(N-1-i) for i in range(N)]) array([[ 1, 1, 1], [ 4, 2, 1], [ 9, 3, 1], [25, 5, 1]]) >>> x = np.array([1, 2, 3, 5]) >>> np.vander(x) array([[ 1, 1, 1, 1], [ 8, 4, 2, 1], [ 27, 9, 3, 1], [125, 25, 5, 1]]) The determinant of a square Vandermonde matrix is the product of the differences between the values of the input vector: >>> np.linalg.det(np.vander(x)) 48.000000000000043 >>> (5-3)*(5-2)*(5-1)*(3-2)*(3-1)*(2-1) 48
Generate a Van der Monde matrix.
[ "Generate", "a", "Van", "der", "Monde", "matrix", "." ]
def vander(x, N=None): """ Generate a Van der Monde matrix. The columns of the output matrix are decreasing powers of the input vector. Specifically, the `i`-th output column is the input vector raised element-wise to the power of ``N - i - 1``. Such a matrix with a geometric progression in each row is named for Alexandre-Theophile Vandermonde. Parameters ---------- x : array_like 1-D input array. N : int, optional Order of (number of columns in) the output. If `N` is not specified, a square array is returned (``N = len(x)``). Returns ------- out : ndarray Van der Monde matrix of order `N`. The first column is ``x^(N-1)``, the second ``x^(N-2)`` and so forth. Examples -------- >>> x = np.array([1, 2, 3, 5]) >>> N = 3 >>> np.vander(x, N) array([[ 1, 1, 1], [ 4, 2, 1], [ 9, 3, 1], [25, 5, 1]]) >>> np.column_stack([x**(N-1-i) for i in range(N)]) array([[ 1, 1, 1], [ 4, 2, 1], [ 9, 3, 1], [25, 5, 1]]) >>> x = np.array([1, 2, 3, 5]) >>> np.vander(x) array([[ 1, 1, 1, 1], [ 8, 4, 2, 1], [ 27, 9, 3, 1], [125, 25, 5, 1]]) The determinant of a square Vandermonde matrix is the product of the differences between the values of the input vector: >>> np.linalg.det(np.vander(x)) 48.000000000000043 >>> (5-3)*(5-2)*(5-1)*(3-2)*(3-1)*(2-1) 48 """ x = asarray(x) if N is None: N=len(x) X = ones( (len(x),N), x.dtype) for i in range(N - 1): X[:,i] = x**(N - i - 1) return X
[ "def", "vander", "(", "x", ",", "N", "=", "None", ")", ":", "x", "=", "asarray", "(", "x", ")", "if", "N", "is", "None", ":", "N", "=", "len", "(", "x", ")", "X", "=", "ones", "(", "(", "len", "(", "x", ")", ",", "N", ")", ",", "x", ".", "dtype", ")", "for", "i", "in", "range", "(", "N", "-", "1", ")", ":", "X", "[", ":", ",", "i", "]", "=", "x", "**", "(", "N", "-", "i", "-", "1", ")", "return", "X" ]
https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/lib/twodim_base.py#L457-L519
generalized-intelligence/GAAS
29ab17d3e8a4ba18edef3a57c36d8db6329fac73
deprecated/algorithms/sfm/OpenSfM/opensfm/geo.py
python
lla_from_topocentric
(x, y, z, reflat, reflon, refalt)
return lla_from_ecef(ex, ey, ez)
Transform from topocentric XYZ to lat, lon, alt.
Transform from topocentric XYZ to lat, lon, alt.
[ "Transform", "from", "topocentric", "XYZ", "to", "lat", "lon", "alt", "." ]
def lla_from_topocentric(x, y, z, reflat, reflon, refalt): ''' Transform from topocentric XYZ to lat, lon, alt. ''' T = ecef_from_topocentric_transform(reflat, reflon, refalt) ex = T[0, 0] * x + T[0, 1] * y + T[0, 2] * z + T[0, 3] ey = T[1, 0] * x + T[1, 1] * y + T[1, 2] * z + T[1, 3] ez = T[2, 0] * x + T[2, 1] * y + T[2, 2] * z + T[2, 3] return lla_from_ecef(ex, ey, ez)
[ "def", "lla_from_topocentric", "(", "x", ",", "y", ",", "z", ",", "reflat", ",", "reflon", ",", "refalt", ")", ":", "T", "=", "ecef_from_topocentric_transform", "(", "reflat", ",", "reflon", ",", "refalt", ")", "ex", "=", "T", "[", "0", ",", "0", "]", "*", "x", "+", "T", "[", "0", ",", "1", "]", "*", "y", "+", "T", "[", "0", ",", "2", "]", "*", "z", "+", "T", "[", "0", ",", "3", "]", "ey", "=", "T", "[", "1", ",", "0", "]", "*", "x", "+", "T", "[", "1", ",", "1", "]", "*", "y", "+", "T", "[", "1", ",", "2", "]", "*", "z", "+", "T", "[", "1", ",", "3", "]", "ez", "=", "T", "[", "2", ",", "0", "]", "*", "x", "+", "T", "[", "2", ",", "1", "]", "*", "y", "+", "T", "[", "2", ",", "2", "]", "*", "z", "+", "T", "[", "2", ",", "3", "]", "return", "lla_from_ecef", "(", "ex", ",", "ey", ",", "ez", ")" ]
https://github.com/generalized-intelligence/GAAS/blob/29ab17d3e8a4ba18edef3a57c36d8db6329fac73/deprecated/algorithms/sfm/OpenSfM/opensfm/geo.py#L123-L131
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/protorpc/protorpc/wsgi/service.py
python
service_mapping
(service_factory, service_path=r'.*', protocols=None)
return protorpc_service_app
WSGI application that handles a single ProtoRPC service mapping. Args: service_factory: Service factory for creating instances of service request handlers. Either callable that takes no parameters and returns a service instance or a service class whose constructor requires no parameters. service_path: Regular expression for matching requests against. Requests that do not have matching paths will cause a 404 (Not Found) response. protocols: remote.Protocols instance that configures supported protocols on server.
WSGI application that handles a single ProtoRPC service mapping.
[ "WSGI", "application", "that", "handles", "a", "single", "ProtoRPC", "service", "mapping", "." ]
def service_mapping(service_factory, service_path=r'.*', protocols=None): """WSGI application that handles a single ProtoRPC service mapping. Args: service_factory: Service factory for creating instances of service request handlers. Either callable that takes no parameters and returns a service instance or a service class whose constructor requires no parameters. service_path: Regular expression for matching requests against. Requests that do not have matching paths will cause a 404 (Not Found) response. protocols: remote.Protocols instance that configures supported protocols on server. """ service_class = getattr(service_factory, 'service_class', service_factory) remote_methods = service_class.all_remote_methods() path_matcher = re.compile(_REQUEST_PATH_PATTERN % service_path) def protorpc_service_app(environ, start_response): """Actual WSGI application function.""" path_match = path_matcher.match(environ['PATH_INFO']) if not path_match: return _HTTP_NOT_FOUND(environ, start_response) service_path = path_match.group(1) method_name = path_match.group(2) content_type = environ.get('CONTENT_TYPE') if not content_type: content_type = environ.get('HTTP_CONTENT_TYPE') if not content_type: return _HTTP_BAD_REQUEST(environ, start_response) # TODO(rafek): Handle alternate encodings. content_type = cgi.parse_header(content_type)[0] request_method = environ['REQUEST_METHOD'] if request_method != 'POST': content = ('%s.%s is a ProtoRPC method.\n\n' 'Service %s\n\n' 'More about ProtoRPC: ' '%s\n' % (service_path, method_name, service_class.definition_name().encode('utf-8'), util.PROTORPC_PROJECT_URL)) error_handler = wsgi_util.error( six.moves.http_client.METHOD_NOT_ALLOWED, six.moves.http_client.responses[six.moves.http_client.METHOD_NOT_ALLOWED], content=content, content_type='text/plain; charset=utf-8') return error_handler(environ, start_response) local_protocols = protocols or remote.Protocols.get_default() try: protocol = local_protocols.lookup_by_content_type(content_type) except KeyError: return _HTTP_UNSUPPORTED_MEDIA_TYPE(environ,start_response) def send_rpc_error(status_code, state, message, error_name=None): """Helper function to send an RpcStatus message as response. Will create static error handler and begin response. Args: status_code: HTTP integer status code. state: remote.RpcState enum value to send as response. message: Helpful message to send in response. error_name: Error name if applicable. Returns: List containing encoded content response using the same content-type as the request. """ status = remote.RpcStatus(state=state, error_message=message, error_name=error_name) encoded_status = protocol.encode_message(status) error_handler = wsgi_util.error( status_code, content_type=protocol.default_content_type, content=encoded_status) return error_handler(environ, start_response) method = remote_methods.get(method_name) if not method: return send_rpc_error(six.moves.http_client.BAD_REQUEST, remote.RpcState.METHOD_NOT_FOUND_ERROR, 'Unrecognized RPC method: %s' % method_name) content_length = int(environ.get('CONTENT_LENGTH') or '0') remote_info = method.remote try: request = protocol.decode_message( remote_info.request_type, environ['wsgi.input'].read(content_length)) except (messages.ValidationError, messages.DecodeError) as err: return send_rpc_error(six.moves.http_client.BAD_REQUEST, remote.RpcState.REQUEST_ERROR, 'Error parsing ProtoRPC request ' '(Unable to parse request content: %s)' % err) instance = service_factory() initialize_request_state = getattr( instance, 'initialize_request_state', None) if initialize_request_state: # TODO(rafek): This is not currently covered by tests. server_port = environ.get('SERVER_PORT', None) if server_port: server_port = int(server_port) headers = [] for name, value in six.iteritems(environ): if name.startswith('HTTP_'): headers.append((name[len('HTTP_'):].lower().replace('_', '-'), value)) request_state = remote.HttpRequestState( remote_host=environ.get('REMOTE_HOST', None), remote_address=environ.get('REMOTE_ADDR', None), server_host=environ.get('SERVER_HOST', None), server_port=server_port, http_method=request_method, service_path=service_path, headers=headers) initialize_request_state(request_state) try: response = method(instance, request) encoded_response = protocol.encode_message(response) except remote.ApplicationError as err: return send_rpc_error(six.moves.http_client.BAD_REQUEST, remote.RpcState.APPLICATION_ERROR, err.message, err.error_name) except Exception as err: logging.exception('Encountered unexpected error from ProtoRPC ' 'method implementation: %s (%s)' % (err.__class__.__name__, err)) return send_rpc_error(six.moves.http_client.INTERNAL_SERVER_ERROR, remote.RpcState.SERVER_ERROR, 'Internal Server Error') response_headers = [('content-type', content_type)] start_response('%d %s' % (six.moves.http_client.OK, six.moves.http_client.responses[six.moves.http_client.OK],), response_headers) return [encoded_response] # Return WSGI application. return protorpc_service_app
[ "def", "service_mapping", "(", "service_factory", ",", "service_path", "=", "r'.*'", ",", "protocols", "=", "None", ")", ":", "service_class", "=", "getattr", "(", "service_factory", ",", "'service_class'", ",", "service_factory", ")", "remote_methods", "=", "service_class", ".", "all_remote_methods", "(", ")", "path_matcher", "=", "re", ".", "compile", "(", "_REQUEST_PATH_PATTERN", "%", "service_path", ")", "def", "protorpc_service_app", "(", "environ", ",", "start_response", ")", ":", "\"\"\"Actual WSGI application function.\"\"\"", "path_match", "=", "path_matcher", ".", "match", "(", "environ", "[", "'PATH_INFO'", "]", ")", "if", "not", "path_match", ":", "return", "_HTTP_NOT_FOUND", "(", "environ", ",", "start_response", ")", "service_path", "=", "path_match", ".", "group", "(", "1", ")", "method_name", "=", "path_match", ".", "group", "(", "2", ")", "content_type", "=", "environ", ".", "get", "(", "'CONTENT_TYPE'", ")", "if", "not", "content_type", ":", "content_type", "=", "environ", ".", "get", "(", "'HTTP_CONTENT_TYPE'", ")", "if", "not", "content_type", ":", "return", "_HTTP_BAD_REQUEST", "(", "environ", ",", "start_response", ")", "# TODO(rafek): Handle alternate encodings.", "content_type", "=", "cgi", ".", "parse_header", "(", "content_type", ")", "[", "0", "]", "request_method", "=", "environ", "[", "'REQUEST_METHOD'", "]", "if", "request_method", "!=", "'POST'", ":", "content", "=", "(", "'%s.%s is a ProtoRPC method.\\n\\n'", "'Service %s\\n\\n'", "'More about ProtoRPC: '", "'%s\\n'", "%", "(", "service_path", ",", "method_name", ",", "service_class", ".", "definition_name", "(", ")", ".", "encode", "(", "'utf-8'", ")", ",", "util", ".", "PROTORPC_PROJECT_URL", ")", ")", "error_handler", "=", "wsgi_util", ".", "error", "(", "six", ".", "moves", ".", "http_client", ".", "METHOD_NOT_ALLOWED", ",", "six", ".", "moves", ".", "http_client", ".", "responses", "[", "six", ".", "moves", ".", "http_client", ".", "METHOD_NOT_ALLOWED", "]", ",", "content", "=", "content", ",", "content_type", "=", "'text/plain; charset=utf-8'", ")", "return", "error_handler", "(", "environ", ",", "start_response", ")", "local_protocols", "=", "protocols", "or", "remote", ".", "Protocols", ".", "get_default", "(", ")", "try", ":", "protocol", "=", "local_protocols", ".", "lookup_by_content_type", "(", "content_type", ")", "except", "KeyError", ":", "return", "_HTTP_UNSUPPORTED_MEDIA_TYPE", "(", "environ", ",", "start_response", ")", "def", "send_rpc_error", "(", "status_code", ",", "state", ",", "message", ",", "error_name", "=", "None", ")", ":", "\"\"\"Helper function to send an RpcStatus message as response.\n\n Will create static error handler and begin response.\n\n Args:\n status_code: HTTP integer status code.\n state: remote.RpcState enum value to send as response.\n message: Helpful message to send in response.\n error_name: Error name if applicable.\n\n Returns:\n List containing encoded content response using the same content-type as\n the request.\n \"\"\"", "status", "=", "remote", ".", "RpcStatus", "(", "state", "=", "state", ",", "error_message", "=", "message", ",", "error_name", "=", "error_name", ")", "encoded_status", "=", "protocol", ".", "encode_message", "(", "status", ")", "error_handler", "=", "wsgi_util", ".", "error", "(", "status_code", ",", "content_type", "=", "protocol", ".", "default_content_type", ",", "content", "=", "encoded_status", ")", "return", "error_handler", "(", "environ", ",", "start_response", ")", "method", "=", "remote_methods", ".", "get", "(", "method_name", ")", "if", "not", "method", ":", "return", "send_rpc_error", "(", "six", ".", "moves", ".", "http_client", ".", "BAD_REQUEST", ",", "remote", ".", "RpcState", ".", "METHOD_NOT_FOUND_ERROR", ",", "'Unrecognized RPC method: %s'", "%", "method_name", ")", "content_length", "=", "int", "(", "environ", ".", "get", "(", "'CONTENT_LENGTH'", ")", "or", "'0'", ")", "remote_info", "=", "method", ".", "remote", "try", ":", "request", "=", "protocol", ".", "decode_message", "(", "remote_info", ".", "request_type", ",", "environ", "[", "'wsgi.input'", "]", ".", "read", "(", "content_length", ")", ")", "except", "(", "messages", ".", "ValidationError", ",", "messages", ".", "DecodeError", ")", "as", "err", ":", "return", "send_rpc_error", "(", "six", ".", "moves", ".", "http_client", ".", "BAD_REQUEST", ",", "remote", ".", "RpcState", ".", "REQUEST_ERROR", ",", "'Error parsing ProtoRPC request '", "'(Unable to parse request content: %s)'", "%", "err", ")", "instance", "=", "service_factory", "(", ")", "initialize_request_state", "=", "getattr", "(", "instance", ",", "'initialize_request_state'", ",", "None", ")", "if", "initialize_request_state", ":", "# TODO(rafek): This is not currently covered by tests.", "server_port", "=", "environ", ".", "get", "(", "'SERVER_PORT'", ",", "None", ")", "if", "server_port", ":", "server_port", "=", "int", "(", "server_port", ")", "headers", "=", "[", "]", "for", "name", ",", "value", "in", "six", ".", "iteritems", "(", "environ", ")", ":", "if", "name", ".", "startswith", "(", "'HTTP_'", ")", ":", "headers", ".", "append", "(", "(", "name", "[", "len", "(", "'HTTP_'", ")", ":", "]", ".", "lower", "(", ")", ".", "replace", "(", "'_'", ",", "'-'", ")", ",", "value", ")", ")", "request_state", "=", "remote", ".", "HttpRequestState", "(", "remote_host", "=", "environ", ".", "get", "(", "'REMOTE_HOST'", ",", "None", ")", ",", "remote_address", "=", "environ", ".", "get", "(", "'REMOTE_ADDR'", ",", "None", ")", ",", "server_host", "=", "environ", ".", "get", "(", "'SERVER_HOST'", ",", "None", ")", ",", "server_port", "=", "server_port", ",", "http_method", "=", "request_method", ",", "service_path", "=", "service_path", ",", "headers", "=", "headers", ")", "initialize_request_state", "(", "request_state", ")", "try", ":", "response", "=", "method", "(", "instance", ",", "request", ")", "encoded_response", "=", "protocol", ".", "encode_message", "(", "response", ")", "except", "remote", ".", "ApplicationError", "as", "err", ":", "return", "send_rpc_error", "(", "six", ".", "moves", ".", "http_client", ".", "BAD_REQUEST", ",", "remote", ".", "RpcState", ".", "APPLICATION_ERROR", ",", "err", ".", "message", ",", "err", ".", "error_name", ")", "except", "Exception", "as", "err", ":", "logging", ".", "exception", "(", "'Encountered unexpected error from ProtoRPC '", "'method implementation: %s (%s)'", "%", "(", "err", ".", "__class__", ".", "__name__", ",", "err", ")", ")", "return", "send_rpc_error", "(", "six", ".", "moves", ".", "http_client", ".", "INTERNAL_SERVER_ERROR", ",", "remote", ".", "RpcState", ".", "SERVER_ERROR", ",", "'Internal Server Error'", ")", "response_headers", "=", "[", "(", "'content-type'", ",", "content_type", ")", "]", "start_response", "(", "'%d %s'", "%", "(", "six", ".", "moves", ".", "http_client", ".", "OK", ",", "six", ".", "moves", ".", "http_client", ".", "responses", "[", "six", ".", "moves", ".", "http_client", ".", "OK", "]", ",", ")", ",", "response_headers", ")", "return", "[", "encoded_response", "]", "# Return WSGI application.", "return", "protorpc_service_app" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/protorpc/protorpc/wsgi/service.py#L57-L203
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/training/tensorboard_logging.py
python
log
(level, message, *args)
Conditionally logs `message % args` at the level `level`. Note that tensorboard_logging verbosity and logging verbosity are separate; the message will always be passed through to the logging module regardless of whether it passes the tensorboard_logging verbosity check. Args: level: The verbosity level to use. Must be one of tensorboard_logging.{DEBUG, INFO, WARN, ERROR, FATAL}. message: The message template to use. *args: Arguments to interpolate to the message template, if any. Raises: ValueError: If `level` is not a valid logging level. RuntimeError: If the `SummaryWriter` to use has not been set.
Conditionally logs `message % args` at the level `level`.
[ "Conditionally", "logs", "message", "%", "args", "at", "the", "level", "level", "." ]
def log(level, message, *args): """Conditionally logs `message % args` at the level `level`. Note that tensorboard_logging verbosity and logging verbosity are separate; the message will always be passed through to the logging module regardless of whether it passes the tensorboard_logging verbosity check. Args: level: The verbosity level to use. Must be one of tensorboard_logging.{DEBUG, INFO, WARN, ERROR, FATAL}. message: The message template to use. *args: Arguments to interpolate to the message template, if any. Raises: ValueError: If `level` is not a valid logging level. RuntimeError: If the `SummaryWriter` to use has not been set. """ if _summary_writer is _sentinel_summary_writer: raise RuntimeError('Must call set_summary_writer before doing any ' 'logging from tensorboard_logging') _check_verbosity(level) proto_level = _LEVEL_PROTO_MAP[level] if proto_level >= _LEVEL_PROTO_MAP[_verbosity]: log_message = event_pb2.LogMessage(level=proto_level, message=message % args) event = event_pb2.Event(wall_time=time.time(), log_message=log_message) if _summary_writer: _summary_writer.add_event(event) logging.log(_PLATFORM_LOGGING_LEVEL_MAP[level], message, *args)
[ "def", "log", "(", "level", ",", "message", ",", "*", "args", ")", ":", "if", "_summary_writer", "is", "_sentinel_summary_writer", ":", "raise", "RuntimeError", "(", "'Must call set_summary_writer before doing any '", "'logging from tensorboard_logging'", ")", "_check_verbosity", "(", "level", ")", "proto_level", "=", "_LEVEL_PROTO_MAP", "[", "level", "]", "if", "proto_level", ">=", "_LEVEL_PROTO_MAP", "[", "_verbosity", "]", ":", "log_message", "=", "event_pb2", ".", "LogMessage", "(", "level", "=", "proto_level", ",", "message", "=", "message", "%", "args", ")", "event", "=", "event_pb2", ".", "Event", "(", "wall_time", "=", "time", ".", "time", "(", ")", ",", "log_message", "=", "log_message", ")", "if", "_summary_writer", ":", "_summary_writer", ".", "add_event", "(", "event", ")", "logging", ".", "log", "(", "_PLATFORM_LOGGING_LEVEL_MAP", "[", "level", "]", ",", "message", ",", "*", "args", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/training/tensorboard_logging.py#L117-L147
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/operations/build/wheel.py
python
build_wheel_pep517
( name, # type: str backend, # type: Pep517HookCaller metadata_directory, # type: str build_options, # type: List[str] tempd, # type: str )
return os.path.join(tempd, wheel_name)
Build one InstallRequirement using the PEP 517 build process. Returns path to wheel if successfully built. Otherwise, returns None.
Build one InstallRequirement using the PEP 517 build process.
[ "Build", "one", "InstallRequirement", "using", "the", "PEP", "517", "build", "process", "." ]
def build_wheel_pep517( name, # type: str backend, # type: Pep517HookCaller metadata_directory, # type: str build_options, # type: List[str] tempd, # type: str ): # type: (...) -> Optional[str] """Build one InstallRequirement using the PEP 517 build process. Returns path to wheel if successfully built. Otherwise, returns None. """ assert metadata_directory is not None if build_options: # PEP 517 does not support --build-options logger.error('Cannot build wheel for %s using PEP 517 when ' '--build-option is present', name) return None try: logger.debug('Destination directory: %s', tempd) runner = runner_with_spinner_message( f'Building wheel for {name} (PEP 517)' ) with backend.subprocess_runner(runner): wheel_name = backend.build_wheel( tempd, metadata_directory=metadata_directory, ) except Exception: logger.error('Failed building wheel for %s', name) return None return os.path.join(tempd, wheel_name)
[ "def", "build_wheel_pep517", "(", "name", ",", "# type: str", "backend", ",", "# type: Pep517HookCaller", "metadata_directory", ",", "# type: str", "build_options", ",", "# type: List[str]", "tempd", ",", "# type: str", ")", ":", "# type: (...) -> Optional[str]", "assert", "metadata_directory", "is", "not", "None", "if", "build_options", ":", "# PEP 517 does not support --build-options", "logger", ".", "error", "(", "'Cannot build wheel for %s using PEP 517 when '", "'--build-option is present'", ",", "name", ")", "return", "None", "try", ":", "logger", ".", "debug", "(", "'Destination directory: %s'", ",", "tempd", ")", "runner", "=", "runner_with_spinner_message", "(", "f'Building wheel for {name} (PEP 517)'", ")", "with", "backend", ".", "subprocess_runner", "(", "runner", ")", ":", "wheel_name", "=", "backend", ".", "build_wheel", "(", "tempd", ",", "metadata_directory", "=", "metadata_directory", ",", ")", "except", "Exception", ":", "logger", ".", "error", "(", "'Failed building wheel for %s'", ",", "name", ")", "return", "None", "return", "os", ".", "path", ".", "join", "(", "tempd", ",", "wheel_name", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/operations/build/wheel.py#L29-L93
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/distributed/fleet/meta_optimizers/sharding/fp16_helper.py
python
FP16Utils.prune_fp16
(block, shard, reduced_grads_to_param, ring_ids)
1. prune all cast_fp16_to_fp32 ops if the param not belongs to this shard 2. revise amp inifine grad checking for sharding
1. prune all cast_fp16_to_fp32 ops if the param not belongs to this shard 2. revise amp inifine grad checking for sharding
[ "1", ".", "prune", "all", "cast_fp16_to_fp32", "ops", "if", "the", "param", "not", "belongs", "to", "this", "shard", "2", ".", "revise", "amp", "inifine", "grad", "checking", "for", "sharding" ]
def prune_fp16(block, shard, reduced_grads_to_param, ring_ids): """ 1. prune all cast_fp16_to_fp32 ops if the param not belongs to this shard 2. revise amp inifine grad checking for sharding """ # remove cast for idx, op in reversed(list(enumerate(block.ops))): if not FP16Utils.is_fp32_cast_op(block, op): continue output_name = op.desc.output_arg_names()[0] # TODO (JZ-LIANG) revise this for uniform mixed parallelism param_name = output_name.strip( "@GRAD@MERGED" ) if "@MERGED" in output_name else output_name.strip("@GRAD") if param_name not in shard.global_params: raise ValueError("Output 'X' of cast_op must be a grad of" "model param, but {} is not a grad".format( output_name)) if output_name in reduced_grads_to_param: continue if shard.has_param(param_name): continue block._remove_op(idx, sync=False) block._remove_var(output_name, sync=False) block._sync_with_cpp() update_loss_scaling_op_idx = -1 inf_var_name = '' for idx, op in reversed(list(enumerate(block.ops))): if op.type == "update_loss_scaling": update_loss_scaling_op_idx = idx inf_var_name = op.desc.input('FoundInfinite')[0] if op.type in ["check_finite_and_unscale", "update_loss_scaling"]: reversed_x = [] reversed_x_paramname = [] for input_name in op.desc.input('X'): # TODO (JZ-LIANG) revise this for uniform mixed parallelism if "@MERGED" in input_name: param_name = input_name.strip("@GRAD@MERGED") else: param_name = input_name.strip("@GRAD") if param_name not in shard.global_params: raise ValueError( "Input 'X' of check_finite_and_unscale must" "be grads, but {} is not a grad".format(input_name)) if shard.has_param(param_name): reversed_x.append(input_name) reversed_x_paramname.append(param_name) op.desc.set_input('X', reversed_x) op.desc.set_output('Out', reversed_x) # the grad checking should take the all and only param in the current shard to_check_param = set(reversed_x_paramname) should_check_param = set(shard.global_params).intersection( set([param for param, worker_idx in shard.global_param2device.items() \ if worker_idx == shard.worker_idx])) assert to_check_param == should_check_param, "amp \ check_finite_and_unscale checking miss [{}] and got unexpected [{}]".format( should_check_param - to_check_param, to_check_param - should_check_param) if update_loss_scaling_op_idx == -1: return inf_var = block.var(inf_var_name) inf_var_int32 = block.create_var( name=inf_var_name + "@cast_int32", shape=inf_var.shape, dtype=core.VarDesc.VarType.INT32) block._insert_op_without_sync( update_loss_scaling_op_idx, type='cast', inputs={'X': inf_var}, outputs={'Out': inf_var_int32}, attrs={ "in_dtype": inf_var.dtype, "out_dtype": inf_var_int32.dtype, OP_ROLE_KEY: OpRole.Optimize }) update_loss_scaling_op_idx += 1 # allreduce(mp)->allreduce(sharding)->allreduce(pp) for ring_id in ring_ids: if ring_id == -1: continue # this allreduce communication should not overlap with calc block._insert_op_without_sync( update_loss_scaling_op_idx, type='c_allreduce_max', inputs={'X': inf_var_int32}, outputs={'Out': inf_var_int32}, attrs={ 'ring_id': ring_id, 'use_calc_stream': True, OP_ROLE_KEY: OpRole.Optimize }) update_loss_scaling_op_idx += 1 block._insert_op_without_sync( update_loss_scaling_op_idx, type='cast', inputs={'X': inf_var_int32}, outputs={'Out': inf_var}, attrs={ "in_dtype": inf_var_int32.dtype, "out_dtype": inf_var.dtype, OP_ROLE_KEY: OpRole.Optimize }) update_loss_scaling_op_idx += 1 block._sync_with_cpp()
[ "def", "prune_fp16", "(", "block", ",", "shard", ",", "reduced_grads_to_param", ",", "ring_ids", ")", ":", "# remove cast", "for", "idx", ",", "op", "in", "reversed", "(", "list", "(", "enumerate", "(", "block", ".", "ops", ")", ")", ")", ":", "if", "not", "FP16Utils", ".", "is_fp32_cast_op", "(", "block", ",", "op", ")", ":", "continue", "output_name", "=", "op", ".", "desc", ".", "output_arg_names", "(", ")", "[", "0", "]", "# TODO (JZ-LIANG) revise this for uniform mixed parallelism", "param_name", "=", "output_name", ".", "strip", "(", "\"@GRAD@MERGED\"", ")", "if", "\"@MERGED\"", "in", "output_name", "else", "output_name", ".", "strip", "(", "\"@GRAD\"", ")", "if", "param_name", "not", "in", "shard", ".", "global_params", ":", "raise", "ValueError", "(", "\"Output 'X' of cast_op must be a grad of\"", "\"model param, but {} is not a grad\"", ".", "format", "(", "output_name", ")", ")", "if", "output_name", "in", "reduced_grads_to_param", ":", "continue", "if", "shard", ".", "has_param", "(", "param_name", ")", ":", "continue", "block", ".", "_remove_op", "(", "idx", ",", "sync", "=", "False", ")", "block", ".", "_remove_var", "(", "output_name", ",", "sync", "=", "False", ")", "block", ".", "_sync_with_cpp", "(", ")", "update_loss_scaling_op_idx", "=", "-", "1", "inf_var_name", "=", "''", "for", "idx", ",", "op", "in", "reversed", "(", "list", "(", "enumerate", "(", "block", ".", "ops", ")", ")", ")", ":", "if", "op", ".", "type", "==", "\"update_loss_scaling\"", ":", "update_loss_scaling_op_idx", "=", "idx", "inf_var_name", "=", "op", ".", "desc", ".", "input", "(", "'FoundInfinite'", ")", "[", "0", "]", "if", "op", ".", "type", "in", "[", "\"check_finite_and_unscale\"", ",", "\"update_loss_scaling\"", "]", ":", "reversed_x", "=", "[", "]", "reversed_x_paramname", "=", "[", "]", "for", "input_name", "in", "op", ".", "desc", ".", "input", "(", "'X'", ")", ":", "# TODO (JZ-LIANG) revise this for uniform mixed parallelism", "if", "\"@MERGED\"", "in", "input_name", ":", "param_name", "=", "input_name", ".", "strip", "(", "\"@GRAD@MERGED\"", ")", "else", ":", "param_name", "=", "input_name", ".", "strip", "(", "\"@GRAD\"", ")", "if", "param_name", "not", "in", "shard", ".", "global_params", ":", "raise", "ValueError", "(", "\"Input 'X' of check_finite_and_unscale must\"", "\"be grads, but {} is not a grad\"", ".", "format", "(", "input_name", ")", ")", "if", "shard", ".", "has_param", "(", "param_name", ")", ":", "reversed_x", ".", "append", "(", "input_name", ")", "reversed_x_paramname", ".", "append", "(", "param_name", ")", "op", ".", "desc", ".", "set_input", "(", "'X'", ",", "reversed_x", ")", "op", ".", "desc", ".", "set_output", "(", "'Out'", ",", "reversed_x", ")", "# the grad checking should take the all and only param in the current shard", "to_check_param", "=", "set", "(", "reversed_x_paramname", ")", "should_check_param", "=", "set", "(", "shard", ".", "global_params", ")", ".", "intersection", "(", "set", "(", "[", "param", "for", "param", ",", "worker_idx", "in", "shard", ".", "global_param2device", ".", "items", "(", ")", "if", "worker_idx", "==", "shard", ".", "worker_idx", "]", ")", ")", "assert", "to_check_param", "==", "should_check_param", ",", "\"amp \\\n check_finite_and_unscale checking miss [{}] and got unexpected [{}]\"", ".", "format", "(", "should_check_param", "-", "to_check_param", ",", "to_check_param", "-", "should_check_param", ")", "if", "update_loss_scaling_op_idx", "==", "-", "1", ":", "return", "inf_var", "=", "block", ".", "var", "(", "inf_var_name", ")", "inf_var_int32", "=", "block", ".", "create_var", "(", "name", "=", "inf_var_name", "+", "\"@cast_int32\"", ",", "shape", "=", "inf_var", ".", "shape", ",", "dtype", "=", "core", ".", "VarDesc", ".", "VarType", ".", "INT32", ")", "block", ".", "_insert_op_without_sync", "(", "update_loss_scaling_op_idx", ",", "type", "=", "'cast'", ",", "inputs", "=", "{", "'X'", ":", "inf_var", "}", ",", "outputs", "=", "{", "'Out'", ":", "inf_var_int32", "}", ",", "attrs", "=", "{", "\"in_dtype\"", ":", "inf_var", ".", "dtype", ",", "\"out_dtype\"", ":", "inf_var_int32", ".", "dtype", ",", "OP_ROLE_KEY", ":", "OpRole", ".", "Optimize", "}", ")", "update_loss_scaling_op_idx", "+=", "1", "# allreduce(mp)->allreduce(sharding)->allreduce(pp)", "for", "ring_id", "in", "ring_ids", ":", "if", "ring_id", "==", "-", "1", ":", "continue", "# this allreduce communication should not overlap with calc", "block", ".", "_insert_op_without_sync", "(", "update_loss_scaling_op_idx", ",", "type", "=", "'c_allreduce_max'", ",", "inputs", "=", "{", "'X'", ":", "inf_var_int32", "}", ",", "outputs", "=", "{", "'Out'", ":", "inf_var_int32", "}", ",", "attrs", "=", "{", "'ring_id'", ":", "ring_id", ",", "'use_calc_stream'", ":", "True", ",", "OP_ROLE_KEY", ":", "OpRole", ".", "Optimize", "}", ")", "update_loss_scaling_op_idx", "+=", "1", "block", ".", "_insert_op_without_sync", "(", "update_loss_scaling_op_idx", ",", "type", "=", "'cast'", ",", "inputs", "=", "{", "'X'", ":", "inf_var_int32", "}", ",", "outputs", "=", "{", "'Out'", ":", "inf_var", "}", ",", "attrs", "=", "{", "\"in_dtype\"", ":", "inf_var_int32", ".", "dtype", ",", "\"out_dtype\"", ":", "inf_var", ".", "dtype", ",", "OP_ROLE_KEY", ":", "OpRole", ".", "Optimize", "}", ")", "update_loss_scaling_op_idx", "+=", "1", "block", ".", "_sync_with_cpp", "(", ")" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/distributed/fleet/meta_optimizers/sharding/fp16_helper.py#L76-L184
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/deps/v8/third_party/jinja2/utils.py
python
LRUCache.items
(self)
return result
Return a list of items.
Return a list of items.
[ "Return", "a", "list", "of", "items", "." ]
def items(self): """Return a list of items.""" result = [(key, self._mapping[key]) for key in list(self._queue)] result.reverse() return result
[ "def", "items", "(", "self", ")", ":", "result", "=", "[", "(", "key", ",", "self", ".", "_mapping", "[", "key", "]", ")", "for", "key", "in", "list", "(", "self", ".", "_queue", ")", "]", "result", ".", "reverse", "(", ")", "return", "result" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/v8/third_party/jinja2/utils.py#L444-L448
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/Pygments/py3/pygments/formatters/rtf.py
python
RtfFormatter.__init__
(self, **options)
r""" Additional options accepted: ``fontface`` Name of the font used. Could for example be ``'Courier New'`` to further specify the default which is ``'\fmodern'``. The RTF specification claims that ``\fmodern`` are "Fixed-pitch serif and sans serif fonts". Hope every RTF implementation thinks the same about modern...
r""" Additional options accepted:
[ "r", "Additional", "options", "accepted", ":" ]
def __init__(self, **options): r""" Additional options accepted: ``fontface`` Name of the font used. Could for example be ``'Courier New'`` to further specify the default which is ``'\fmodern'``. The RTF specification claims that ``\fmodern`` are "Fixed-pitch serif and sans serif fonts". Hope every RTF implementation thinks the same about modern... """ Formatter.__init__(self, **options) self.fontface = options.get('fontface') or '' self.fontsize = get_int_opt(options, 'fontsize', 0)
[ "def", "__init__", "(", "self", ",", "*", "*", "options", ")", ":", "Formatter", ".", "__init__", "(", "self", ",", "*", "*", "options", ")", "self", ".", "fontface", "=", "options", ".", "get", "(", "'fontface'", ")", "or", "''", "self", ".", "fontsize", "=", "get_int_opt", "(", "options", ",", "'fontsize'", ",", "0", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Pygments/py3/pygments/formatters/rtf.py#L50-L64
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/_op_impl/tbe/rsqrt_ds.py
python
_rsqrt_ds_tbe
()
return
Rsqrt TBE register
Rsqrt TBE register
[ "Rsqrt", "TBE", "register" ]
def _rsqrt_ds_tbe(): """Rsqrt TBE register""" return
[ "def", "_rsqrt_ds_tbe", "(", ")", ":", "return" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/tbe/rsqrt_ds.py#L36-L38
johmathe/shotdetect
1ecf93a695c96fd7601a41ab5834f1117b9d7d50
tools/cpplint.py
python
ResetNolintSuppressions
()
Resets the set of NOLINT suppressions to empty.
Resets the set of NOLINT suppressions to empty.
[ "Resets", "the", "set", "of", "NOLINT", "suppressions", "to", "empty", "." ]
def ResetNolintSuppressions(): "Resets the set of NOLINT suppressions to empty." _error_suppressions.clear()
[ "def", "ResetNolintSuppressions", "(", ")", ":", "_error_suppressions", ".", "clear", "(", ")" ]
https://github.com/johmathe/shotdetect/blob/1ecf93a695c96fd7601a41ab5834f1117b9d7d50/tools/cpplint.py#L329-L331
bigartm/bigartm
47e37f982de87aa67bfd475ff1f39da696b181b3
3rdparty/protobuf-3.0.0/python/google/protobuf/message.py
python
Message.__setstate__
(self, state)
Support the pickle protocol.
Support the pickle protocol.
[ "Support", "the", "pickle", "protocol", "." ]
def __setstate__(self, state): """Support the pickle protocol.""" self.__init__() self.ParseFromString(state['serialized'])
[ "def", "__setstate__", "(", "self", ",", "state", ")", ":", "self", ".", "__init__", "(", ")", "self", ".", "ParseFromString", "(", "state", "[", "'serialized'", "]", ")" ]
https://github.com/bigartm/bigartm/blob/47e37f982de87aa67bfd475ff1f39da696b181b3/3rdparty/protobuf-3.0.0/python/google/protobuf/message.py#L292-L295
panda3d/panda3d
833ad89ebad58395d0af0b7ec08538e5e4308265
direct/src/actor/Actor.py
python
Actor.verifySubpartsComplete
(self, partName = None, lodName = None)
Ensures that each joint is defined by at least one subPart. Prints a warning if this is not the case.
Ensures that each joint is defined by at least one subPart. Prints a warning if this is not the case.
[ "Ensures", "that", "each", "joint", "is", "defined", "by", "at", "least", "one", "subPart", ".", "Prints", "a", "warning", "if", "this", "is", "not", "the", "case", "." ]
def verifySubpartsComplete(self, partName = None, lodName = None): """ Ensures that each joint is defined by at least one subPart. Prints a warning if this is not the case. """ if partName: assert partName not in self.__subpartDict partNames = [partName] else: if lodName: partNames = self.__partBundleDict[lodName].keys() else: partNames = next(iter(self.__partBundleDict.values())).keys() for partName in partNames: subJoints = set() for subPartName, subPartDef in self.__subpartDict.items(): if subPartName != partName and subPartDef.truePartName == partName: subJoints |= set(self.getJoints(partName = subPartName, lodName = lodName)) allJoints = set(self.getJoints(partName = partName, lodName = lodName)) diff = allJoints.difference(subJoints) if diff: self.notify.warning('Uncovered joints: %s' % (list(diff)))
[ "def", "verifySubpartsComplete", "(", "self", ",", "partName", "=", "None", ",", "lodName", "=", "None", ")", ":", "if", "partName", ":", "assert", "partName", "not", "in", "self", ".", "__subpartDict", "partNames", "=", "[", "partName", "]", "else", ":", "if", "lodName", ":", "partNames", "=", "self", ".", "__partBundleDict", "[", "lodName", "]", ".", "keys", "(", ")", "else", ":", "partNames", "=", "next", "(", "iter", "(", "self", ".", "__partBundleDict", ".", "values", "(", ")", ")", ")", ".", "keys", "(", ")", "for", "partName", "in", "partNames", ":", "subJoints", "=", "set", "(", ")", "for", "subPartName", ",", "subPartDef", "in", "self", ".", "__subpartDict", ".", "items", "(", ")", ":", "if", "subPartName", "!=", "partName", "and", "subPartDef", ".", "truePartName", "==", "partName", ":", "subJoints", "|=", "set", "(", "self", ".", "getJoints", "(", "partName", "=", "subPartName", ",", "lodName", "=", "lodName", ")", ")", "allJoints", "=", "set", "(", "self", ".", "getJoints", "(", "partName", "=", "partName", ",", "lodName", "=", "lodName", ")", ")", "diff", "=", "allJoints", ".", "difference", "(", "subJoints", ")", "if", "diff", ":", "self", ".", "notify", ".", "warning", "(", "'Uncovered joints: %s'", "%", "(", "list", "(", "diff", ")", ")", ")" ]
https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/actor/Actor.py#L2098-L2120
idaholab/moose
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
python/peacock/Input/InputFileEditorPlugin.py
python
InputFileEditorPlugin._saveInputFileAs
(self)
Ask the user what file to save the input tree to.
Ask the user what file to save the input tree to.
[ "Ask", "the", "user", "what", "file", "to", "save", "the", "input", "tree", "to", "." ]
def _saveInputFileAs(self): """ Ask the user what file to save the input tree to. """ input_name, other = QFileDialog.getSaveFileName(self, "Choose input file", os.getcwd(), "Input File (*.i)") if input_name: input_name = os.path.abspath(input_name) self.writeInputFile(input_name) self.setInputFile(input_name) self._recently_used_menu.update(input_name) self.has_changed = False
[ "def", "_saveInputFileAs", "(", "self", ")", ":", "input_name", ",", "other", "=", "QFileDialog", ".", "getSaveFileName", "(", "self", ",", "\"Choose input file\"", ",", "os", ".", "getcwd", "(", ")", ",", "\"Input File (*.i)\"", ")", "if", "input_name", ":", "input_name", "=", "os", ".", "path", ".", "abspath", "(", "input_name", ")", "self", ".", "writeInputFile", "(", "input_name", ")", "self", ".", "setInputFile", "(", "input_name", ")", "self", ".", "_recently_used_menu", ".", "update", "(", "input_name", ")", "self", ".", "has_changed", "=", "False" ]
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/peacock/Input/InputFileEditorPlugin.py#L108-L118
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/pyfakefs/pyfakefs/fake_filesystem.py
python
FakeDirectory.GetEntry
(self, pathname_name)
return self.contents[pathname_name]
Retrieves the specified child file or directory. Args: pathname_name: basename of the child object to retrieve Returns: string, file contents Raises: KeyError: if no child exists by the specified name
Retrieves the specified child file or directory.
[ "Retrieves", "the", "specified", "child", "file", "or", "directory", "." ]
def GetEntry(self, pathname_name): """Retrieves the specified child file or directory. Args: pathname_name: basename of the child object to retrieve Returns: string, file contents Raises: KeyError: if no child exists by the specified name """ return self.contents[pathname_name]
[ "def", "GetEntry", "(", "self", ",", "pathname_name", ")", ":", "return", "self", ".", "contents", "[", "pathname_name", "]" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/pyfakefs/pyfakefs/fake_filesystem.py#L324-L334
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/FortranCommon.py
python
ComputeFortranSuffixes
(suffixes, ppsuffixes)
suffixes are fortran source files, and ppsuffixes the ones to be pre-processed. Both should be sequences, not strings.
suffixes are fortran source files, and ppsuffixes the ones to be pre-processed. Both should be sequences, not strings.
[ "suffixes", "are", "fortran", "source", "files", "and", "ppsuffixes", "the", "ones", "to", "be", "pre", "-", "processed", ".", "Both", "should", "be", "sequences", "not", "strings", "." ]
def ComputeFortranSuffixes(suffixes, ppsuffixes): """suffixes are fortran source files, and ppsuffixes the ones to be pre-processed. Both should be sequences, not strings.""" assert len(suffixes) > 0 s = suffixes[0] sup = s.upper() upper_suffixes = [_.upper() for _ in suffixes] if SCons.Util.case_sensitive_suffixes(s, sup): ppsuffixes.extend(upper_suffixes) else: suffixes.extend(upper_suffixes)
[ "def", "ComputeFortranSuffixes", "(", "suffixes", ",", "ppsuffixes", ")", ":", "assert", "len", "(", "suffixes", ")", ">", "0", "s", "=", "suffixes", "[", "0", "]", "sup", "=", "s", ".", "upper", "(", ")", "upper_suffixes", "=", "[", "_", ".", "upper", "(", ")", "for", "_", "in", "suffixes", "]", "if", "SCons", ".", "Util", ".", "case_sensitive_suffixes", "(", "s", ",", "sup", ")", ":", "ppsuffixes", ".", "extend", "(", "upper_suffixes", ")", "else", ":", "suffixes", ".", "extend", "(", "upper_suffixes", ")" ]
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/FortranCommon.py#L88-L98
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/html.py
python
HtmlWidgetCell.__init__
(self, *args, **kwargs)
__init__(self, Window wnd, int w=0) -> HtmlWidgetCell
__init__(self, Window wnd, int w=0) -> HtmlWidgetCell
[ "__init__", "(", "self", "Window", "wnd", "int", "w", "=", "0", ")", "-", ">", "HtmlWidgetCell" ]
def __init__(self, *args, **kwargs): """__init__(self, Window wnd, int w=0) -> HtmlWidgetCell""" _html.HtmlWidgetCell_swiginit(self,_html.new_HtmlWidgetCell(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_html", ".", "HtmlWidgetCell_swiginit", "(", "self", ",", "_html", ".", "new_HtmlWidgetCell", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/html.py#L895-L897
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/extern/aui/aui_utilities.py
python
LightColour
(colour, percent)
return wx.Colour(r, g, b)
Brighten input `colour` by `percent`. :param Colour `colour`: the colour to be brightened; :param integer `percent`: brightening percentage.
Brighten input `colour` by `percent`.
[ "Brighten", "input", "colour", "by", "percent", "." ]
def LightColour(colour, percent): """ Brighten input `colour` by `percent`. :param Colour `colour`: the colour to be brightened; :param integer `percent`: brightening percentage. """ end_colour = wx.WHITE rd = end_colour.Red() - colour.Red() gd = end_colour.Green() - colour.Green() bd = end_colour.Blue() - colour.Blue() high = 100 # We take the percent way of the colour from colour -. white i = percent r = colour.Red() + ((i*rd*100)/high)/100 g = colour.Green() + ((i*gd*100)/high)/100 b = colour.Blue() + ((i*bd*100)/high)/100 return wx.Colour(r, g, b)
[ "def", "LightColour", "(", "colour", ",", "percent", ")", ":", "end_colour", "=", "wx", ".", "WHITE", "rd", "=", "end_colour", ".", "Red", "(", ")", "-", "colour", ".", "Red", "(", ")", "gd", "=", "end_colour", ".", "Green", "(", ")", "-", "colour", ".", "Green", "(", ")", "bd", "=", "end_colour", ".", "Blue", "(", ")", "-", "colour", ".", "Blue", "(", ")", "high", "=", "100", "# We take the percent way of the colour from colour -. white", "i", "=", "percent", "r", "=", "colour", ".", "Red", "(", ")", "+", "(", "(", "i", "*", "rd", "*", "100", ")", "/", "high", ")", "/", "100", "g", "=", "colour", ".", "Green", "(", ")", "+", "(", "(", "i", "*", "gd", "*", "100", ")", "/", "high", ")", "/", "100", "b", "=", "colour", ".", "Blue", "(", ")", "+", "(", "(", "i", "*", "bd", "*", "100", ")", "/", "high", ")", "/", "100", "return", "wx", ".", "Colour", "(", "r", ",", "g", ",", "b", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/aui_utilities.py#L252-L273