nwo
stringlengths
5
86
sha
stringlengths
40
40
path
stringlengths
4
189
language
stringclasses
1 value
identifier
stringlengths
1
94
parameters
stringlengths
2
4.03k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
11.5k
docstring
stringlengths
1
33.2k
docstring_summary
stringlengths
0
5.15k
docstring_tokens
list
function
stringlengths
34
151k
function_tokens
list
url
stringlengths
90
278
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/perspective.py
python
PerspectiveManager.RemovePerspective
(self, name)
Removes a named perspective from the managed set @param name: name of perspective to remove/delete
Removes a named perspective from the managed set @param name: name of perspective to remove/delete
[ "Removes", "a", "named", "perspective", "from", "the", "managed", "set", "@param", "name", ":", "name", "of", "perspective", "to", "remove", "/", "delete" ]
def RemovePerspective(self, name): """Removes a named perspective from the managed set @param name: name of perspective to remove/delete """ if name in self._viewset: del self._viewset[name] rem_id = self._menu.RemoveItemByName(name) if rem_id: self._ids.remove(rem_id)
[ "def", "RemovePerspective", "(", "self", ",", "name", ")", ":", "if", "name", "in", "self", ".", "_viewset", ":", "del", "self", ".", "_viewset", "[", "name", "]", "rem_id", "=", "self", ".", "_menu", ".", "RemoveItemByName", "(", "name", ")", "if", "rem_id", ":", "self", ".", "_ids", ".", "remove", "(", "rem_id", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/perspective.py#L328-L337
deepmind/open_spiel
4ca53bea32bb2875c7385d215424048ae92f78c8
open_spiel/python/algorithms/fictitious_play.py
python
JointPolicy.__init__
(self, game, policies)
Initializes a joint policy from a table of callables. Args: game: The game being played. policies: A dictionary mapping player number to a function `state` -> list of (action, prob).
Initializes a joint policy from a table of callables.
[ "Initializes", "a", "joint", "policy", "from", "a", "table", "of", "callables", "." ]
def __init__(self, game, policies): """Initializes a joint policy from a table of callables. Args: game: The game being played. policies: A dictionary mapping player number to a function `state` -> list of (action, prob). """ super().__init__(game, list(range(game.num_players()))) self.policies = policies
[ "def", "__init__", "(", "self", ",", "game", ",", "policies", ")", ":", "super", "(", ")", ".", "__init__", "(", "game", ",", "list", "(", "range", "(", "game", ".", "num_players", "(", ")", ")", ")", ")", "self", ".", "policies", "=", "policies" ]
https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/algorithms/fictitious_play.py#L64-L73
etotheipi/BitcoinArmory
2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98
urllib3/packages/ordered_dict.py
python
OrderedDict.pop
(self, key, default=__marker)
return default
od.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised.
od.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised.
[ "od", ".", "pop", "(", "k", "[", "d", "]", ")", "-", ">", "v", "remove", "specified", "key", "and", "return", "the", "corresponding", "value", ".", "If", "key", "is", "not", "found", "d", "is", "returned", "if", "given", "otherwise", "KeyError", "is", "raised", "." ]
def pop(self, key, default=__marker): '''od.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised. ''' if key in self: result = self[key] del self[key] return result if default is self.__marker: raise KeyError(key) return default
[ "def", "pop", "(", "self", ",", "key", ",", "default", "=", "__marker", ")", ":", "if", "key", "in", "self", ":", "result", "=", "self", "[", "key", "]", "del", "self", "[", "key", "]", "return", "result", "if", "default", "is", "self", ".", "__marker", ":", "raise", "KeyError", "(", "key", ")", "return", "default" ]
https://github.com/etotheipi/BitcoinArmory/blob/2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98/urllib3/packages/ordered_dict.py#L178-L189
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/ops/array_ops.py
python
_ExpandDimsShape
(op)
return [tensor_shape.TensorShape(result_shape)]
Determine shape for expand op's output tensor. Args: op: Operation for which to determine shape. op.inputs[0] is the input tensor. op.inputs[1] is the dimension in which to expand. Returns: Shape of op's output tensor. Raises: ValueError: If dim is outside of [-rank - 1, rank], where rank is the number of dimensions in the input tensor.
Determine shape for expand op's output tensor.
[ "Determine", "shape", "for", "expand", "op", "s", "output", "tensor", "." ]
def _ExpandDimsShape(op): """Determine shape for expand op's output tensor. Args: op: Operation for which to determine shape. op.inputs[0] is the input tensor. op.inputs[1] is the dimension in which to expand. Returns: Shape of op's output tensor. Raises: ValueError: If dim is outside of [-rank - 1, rank], where rank is the number of dimensions in the input tensor. """ input_shape = op.inputs[0].get_shape() if input_shape.dims is None: return [tensor_shape.unknown_shape()] dim = tensor_util.constant_value(op.inputs[1]) input_ndims = input_shape.ndims if dim < -input_ndims - 1 or dim > input_ndims: raise ValueError( "dim %d not in [%d, %d]." % (dim, -input_ndims, input_ndims)) if dim < 0: dim += (input_ndims + 1) result_shape = list(input_shape.dims) result_shape.insert(dim, 1) return [tensor_shape.TensorShape(result_shape)]
[ "def", "_ExpandDimsShape", "(", "op", ")", ":", "input_shape", "=", "op", ".", "inputs", "[", "0", "]", ".", "get_shape", "(", ")", "if", "input_shape", ".", "dims", "is", "None", ":", "return", "[", "tensor_shape", ".", "unknown_shape", "(", ")", "]", "dim", "=", "tensor_util", ".", "constant_value", "(", "op", ".", "inputs", "[", "1", "]", ")", "input_ndims", "=", "input_shape", ".", "ndims", "if", "dim", "<", "-", "input_ndims", "-", "1", "or", "dim", ">", "input_ndims", ":", "raise", "ValueError", "(", "\"dim %d not in [%d, %d].\"", "%", "(", "dim", ",", "-", "input_ndims", ",", "input_ndims", ")", ")", "if", "dim", "<", "0", ":", "dim", "+=", "(", "input_ndims", "+", "1", ")", "result_shape", "=", "list", "(", "input_shape", ".", "dims", ")", "result_shape", ".", "insert", "(", "dim", ",", "1", ")", "return", "[", "tensor_shape", ".", "TensorShape", "(", "result_shape", ")", "]" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/array_ops.py#L1726-L1751
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/keras/utils/tf_utils.py
python
dataset_is_infinite
(dataset)
True if the passed dataset is infinite.
True if the passed dataset is infinite.
[ "True", "if", "the", "passed", "dataset", "is", "infinite", "." ]
def dataset_is_infinite(dataset): """True if the passed dataset is infinite.""" if ops.executing_eagerly_outside_functions(): return math_ops.equal( cardinality.cardinality(dataset), cardinality.INFINITE) else: dataset_size = K.get_session().run(cardinality.cardinality(dataset)) return dataset_size == cardinality.INFINITE
[ "def", "dataset_is_infinite", "(", "dataset", ")", ":", "if", "ops", ".", "executing_eagerly_outside_functions", "(", ")", ":", "return", "math_ops", ".", "equal", "(", "cardinality", ".", "cardinality", "(", "dataset", ")", ",", "cardinality", ".", "INFINITE", ")", "else", ":", "dataset_size", "=", "K", ".", "get_session", "(", ")", ".", "run", "(", "cardinality", ".", "cardinality", "(", "dataset", ")", ")", "return", "dataset_size", "==", "cardinality", ".", "INFINITE" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/utils/tf_utils.py#L458-L465
idaholab/moose
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
python/moosetree/search.py
python
find
(node, func=None, method=None, **kwargs)
return nodes[0] if nodes else None
Operates in the same fashion as "findall"; however, if a match is found the search is terminated and the node is returned.
Operates in the same fashion as "findall"; however, if a match is found the search is terminated and the node is returned.
[ "Operates", "in", "the", "same", "fashion", "as", "findall", ";", "however", "if", "a", "match", "is", "found", "the", "search", "is", "terminated", "and", "the", "node", "is", "returned", "." ]
def find(node, func=None, method=None, **kwargs): """ Operates in the same fashion as "findall"; however, if a match is found the search is terminated and the node is returned. """ if (func is None) and (kwargs): func = lambda n: any(n.attributes.get(key, None)==value for key, value in kwargs.items()) nodes = list(iterate(node, func, True, method)) return nodes[0] if nodes else None
[ "def", "find", "(", "node", ",", "func", "=", "None", ",", "method", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "(", "func", "is", "None", ")", "and", "(", "kwargs", ")", ":", "func", "=", "lambda", "n", ":", "any", "(", "n", ".", "attributes", ".", "get", "(", "key", ",", "None", ")", "==", "value", "for", "key", ",", "value", "in", "kwargs", ".", "items", "(", ")", ")", "nodes", "=", "list", "(", "iterate", "(", "node", ",", "func", ",", "True", ",", "method", ")", ")", "return", "nodes", "[", "0", "]", "if", "nodes", "else", "None" ]
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/moosetree/search.py#L30-L38
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py3/_distutils_hack/__init__.py
python
do_override
()
Ensure that the local copy of distutils is preferred over stdlib. See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401 for more motivation.
Ensure that the local copy of distutils is preferred over stdlib.
[ "Ensure", "that", "the", "local", "copy", "of", "distutils", "is", "preferred", "over", "stdlib", "." ]
def do_override(): """ Ensure that the local copy of distutils is preferred over stdlib. See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401 for more motivation. """ if enabled(): warn_distutils_present() ensure_local_distutils()
[ "def", "do_override", "(", ")", ":", "if", "enabled", "(", ")", ":", "warn_distutils_present", "(", ")", "ensure_local_distutils", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/_distutils_hack/__init__.py#L64-L73
gnuradio/gnuradio
09c3c4fa4bfb1a02caac74cb5334dfe065391e3b
gr-utils/blocktool/core/parseheader.py
python
BlockHeaderParser.get_header_info
(self)
return self.parsed_data
PyGCCXML header code parser magic happens here! : returns the parsed header data in python dict : return dict keys: namespace, class, io_signature, make, properties, methods : Can be used as an CLI command or an external API
PyGCCXML header code parser magic happens here! : returns the parsed header data in python dict : return dict keys: namespace, class, io_signature, make, properties, methods : Can be used as an CLI command or an external API
[ "PyGCCXML", "header", "code", "parser", "magic", "happens", "here!", ":", "returns", "the", "parsed", "header", "data", "in", "python", "dict", ":", "return", "dict", "keys", ":", "namespace", "class", "io_signature", "make", "properties", "methods", ":", "Can", "be", "used", "as", "an", "CLI", "command", "or", "an", "external", "API" ]
def get_header_info(self): """ PyGCCXML header code parser magic happens here! : returns the parsed header data in python dict : return dict keys: namespace, class, io_signature, make, properties, methods : Can be used as an CLI command or an external API """ gr = self.modname.split('-')[0] module = self.modname.split('-')[-1] self.parsed_data['module_name'] = module generator_path, generator_name = utils.find_xml_generator() xml_generator_config = parser.xml_generator_configuration_t( xml_generator_path=generator_path, xml_generator=generator_name, include_paths=self.include_paths, compiler='gcc', define_symbols=['BOOST_ATOMIC_DETAIL_EXTRA_BACKEND_GENERIC'], cflags='-std=c++11') decls = parser.parse( [self.target_file], xml_generator_config) global_namespace = declarations.get_global_namespace(decls) # namespace try: self.parsed_data['namespace'] = [] ns = global_namespace.namespace(gr) if ns is None: raise BlockToolException main_namespace = ns.namespace(module) if main_namespace is None: raise BlockToolException('namespace cannot be none') self.parsed_data['namespace'] = [gr, module] if main_namespace.declarations: for _namespace in main_namespace.declarations: if isinstance(_namespace, declarations.namespace_t): if Constants.KERNEL not in str(_namespace): main_namespace = _namespace self.parsed_data['namespace'].append( str(_namespace).split('::')[-1].split(' ')[0]) except RuntimeError: raise BlockToolException( 'Invalid namespace format in the block header file') # class try: self.parsed_data['class'] = '' for _class in main_namespace.declarations: if isinstance(_class, declarations.class_t): expected_class_name = self.filename.split('.')[0] if expected_class_name in str(_class): main_class = _class self.parsed_data['class'] = str(_class).split('::')[ 2].split(' ')[0] # in more complicated blocks, there are many classes included in this declaration # Break after the first class - safe to assume this is the "main class"? if len(main_class.bases) > 0: self.parsed_data['block_type'] = main_class.bases[0].declaration_path[-1] break except RuntimeError: raise BlockToolException( 'Block header namespace {} must consist of a valid class instance'.format(module)) # io_signature, message_ports self.parsed_data['io_signature'] = {} self.parsed_data['message_port'] = {} if os.path.isfile(self.impl_file) and exist_comments(self): self.parsed_data['io_signature'] = io_signature( self.impl_file) self.parsed_data['message_port'] = message_port( self.impl_file) read_comments(self) elif os.path.isfile(self.impl_file) and not exist_comments(self): self.parsed_data['io_signature'] = io_signature( self.impl_file) self.parsed_data['message_port'] = message_port( self.impl_file) if self.addcomments: add_comments(self) elif not os.path.isfile(self.impl_file) and exist_comments(self): read_comments(self) else: self.parsed_data['io_signature'] = { "input": [], "output": [] } self.parsed_data['message_port'] = self.parsed_data['io_signature'] # make try: self.parsed_data['make'] = {} self.parsed_data['make']['arguments'] = [] query_m = declarations.custom_matcher_t( lambda mem_fun: mem_fun.name.startswith('make')) query_make = query_m & declarations.access_type_matcher_t('public') make_func = main_class.member_functions(function=query_make, allow_empty=True, header_file=self.target_file) criteria = declarations.calldef_matcher(name='make') _make_fun = declarations.matcher.get_single(criteria, main_class) _make_fun = str(_make_fun).split( 'make')[-1].split(')')[0].split('(')[1].lstrip().rstrip().split(',') if make_func: for arg in make_func[0].arguments: make_arguments = None ''' for _arg in _make_fun: if str(arg.name) in _arg: make_arguments = { "name": str(arg.name), "dtype": str(arg.decl_type), "default": "" } if re.findall(r'[-+]?\d*\.\d+|\d+', _arg): make_arguments['default'] = re.findall( r'[-+]?\d*\.\d+|\d+', _arg)[0] elif re.findall(r'\"(.+?)\"', _arg): make_arguments['default'] = re.findall( r'\"(.+?)\"', _arg)[0] elif "true" in _arg: make_arguments['default'] = "True" elif "false" in _arg: make_arguments['default'] = "False" ''' # In case the search did not find an argument in the inner loop # This happens while parsing digital/symbol_sync_cc.h if make_arguments: self.parsed_data['make']['arguments'].append( make_arguments.copy()) else: self.parsed_data['make']['arguments'].append( { "name": str(arg.name), "dtype": str(arg.decl_type), "default": arg.default_value # can we get default argument directly from arg }) except RuntimeError: self.parsed_data['make'] = {} self.parsed_data['make']['arguments'] = [] # setters try: self.parsed_data['methods'] = [] query_methods = declarations.access_type_matcher_t('public') setters = main_class.member_functions(function=query_methods, allow_empty=True, header_file=self.target_file) getter_arguments = [] if setters: for setter in setters: if str(setter.name).startswith('set_') and setter.arguments: setter_args = { "name": str(setter.name), "arguments_type": [] } for argument in setter.arguments: args = { "name": str(argument.name), "dtype": str(argument.decl_type) } getter_arguments.append(args['name']) setter_args['arguments_type'].append(args.copy()) self.parsed_data['methods'].append(setter_args.copy()) except RuntimeError: self.parsed_data['methods'] = [] # getters try: self.parsed_data['properties'] = [] query_properties = declarations.access_type_matcher_t('public') getters = main_class.member_functions(function=query_properties, allow_empty=True, header_file=self.target_file) if getters: for getter in getters: if not getter.arguments or getter.has_const: getter_args = { "name": str(getter.name), "dtype": str(getter.return_type), "read_only": True } if getter_args['name'] in getter_arguments: getter_args["read_only"] = False self.parsed_data['properties'].append( getter_args.copy()) except RuntimeError: self.parsed_data['properties'] = [] # all member functions # setters and getters do not return all member functions for a block try: self.parsed_data['member_functions'] = [] query_methods = declarations.access_type_matcher_t('public') functions = main_class.member_functions(function=query_methods, allow_empty=True, header_file=self.target_file) if functions: for fcn in functions: if str(fcn.name) not in [main_class.name, '~' + main_class.name, 'make']: fcn_args = { "name": str(fcn.name), "arguments": [] } for argument in fcn.arguments: args = { "name": str(argument.name), "dtype": str(argument.decl_type), "default": argument.default_value } fcn_args['arguments'].append(args.copy()) self.parsed_data['member_functions'].append( fcn_args.copy()) except RuntimeError: self.parsed_data['member_functions'] = [] # documentation try: _index = None header_file = codecs.open(self.target_file, 'r', 'cp932') self.parsed_data['docstring'] = re.compile( r'//.*?$|/\*.*?\*/', re.DOTALL | re.MULTILINE).findall( header_file.read())[2:] header_file.close() for doc in self.parsed_data['docstring']: if Constants.BLOCKTOOL in doc: _index = self.parsed_data['docstring'].index(doc) if _index is not None: self.parsed_data['docstring'] = self.parsed_data['docstring'][: _index] except: self.parsed_data['docstring'] = [] return self.parsed_data
[ "def", "get_header_info", "(", "self", ")", ":", "gr", "=", "self", ".", "modname", ".", "split", "(", "'-'", ")", "[", "0", "]", "module", "=", "self", ".", "modname", ".", "split", "(", "'-'", ")", "[", "-", "1", "]", "self", ".", "parsed_data", "[", "'module_name'", "]", "=", "module", "generator_path", ",", "generator_name", "=", "utils", ".", "find_xml_generator", "(", ")", "xml_generator_config", "=", "parser", ".", "xml_generator_configuration_t", "(", "xml_generator_path", "=", "generator_path", ",", "xml_generator", "=", "generator_name", ",", "include_paths", "=", "self", ".", "include_paths", ",", "compiler", "=", "'gcc'", ",", "define_symbols", "=", "[", "'BOOST_ATOMIC_DETAIL_EXTRA_BACKEND_GENERIC'", "]", ",", "cflags", "=", "'-std=c++11'", ")", "decls", "=", "parser", ".", "parse", "(", "[", "self", ".", "target_file", "]", ",", "xml_generator_config", ")", "global_namespace", "=", "declarations", ".", "get_global_namespace", "(", "decls", ")", "# namespace", "try", ":", "self", ".", "parsed_data", "[", "'namespace'", "]", "=", "[", "]", "ns", "=", "global_namespace", ".", "namespace", "(", "gr", ")", "if", "ns", "is", "None", ":", "raise", "BlockToolException", "main_namespace", "=", "ns", ".", "namespace", "(", "module", ")", "if", "main_namespace", "is", "None", ":", "raise", "BlockToolException", "(", "'namespace cannot be none'", ")", "self", ".", "parsed_data", "[", "'namespace'", "]", "=", "[", "gr", ",", "module", "]", "if", "main_namespace", ".", "declarations", ":", "for", "_namespace", "in", "main_namespace", ".", "declarations", ":", "if", "isinstance", "(", "_namespace", ",", "declarations", ".", "namespace_t", ")", ":", "if", "Constants", ".", "KERNEL", "not", "in", "str", "(", "_namespace", ")", ":", "main_namespace", "=", "_namespace", "self", ".", "parsed_data", "[", "'namespace'", "]", ".", "append", "(", "str", "(", "_namespace", ")", ".", "split", "(", "'::'", ")", "[", "-", "1", "]", ".", "split", "(", "' '", ")", "[", "0", "]", ")", "except", "RuntimeError", ":", "raise", "BlockToolException", "(", "'Invalid namespace format in the block header file'", ")", "# class", "try", ":", "self", ".", "parsed_data", "[", "'class'", "]", "=", "''", "for", "_class", "in", "main_namespace", ".", "declarations", ":", "if", "isinstance", "(", "_class", ",", "declarations", ".", "class_t", ")", ":", "expected_class_name", "=", "self", ".", "filename", ".", "split", "(", "'.'", ")", "[", "0", "]", "if", "expected_class_name", "in", "str", "(", "_class", ")", ":", "main_class", "=", "_class", "self", ".", "parsed_data", "[", "'class'", "]", "=", "str", "(", "_class", ")", ".", "split", "(", "'::'", ")", "[", "2", "]", ".", "split", "(", "' '", ")", "[", "0", "]", "# in more complicated blocks, there are many classes included in this declaration", "# Break after the first class - safe to assume this is the \"main class\"?", "if", "len", "(", "main_class", ".", "bases", ")", ">", "0", ":", "self", ".", "parsed_data", "[", "'block_type'", "]", "=", "main_class", ".", "bases", "[", "0", "]", ".", "declaration_path", "[", "-", "1", "]", "break", "except", "RuntimeError", ":", "raise", "BlockToolException", "(", "'Block header namespace {} must consist of a valid class instance'", ".", "format", "(", "module", ")", ")", "# io_signature, message_ports", "self", ".", "parsed_data", "[", "'io_signature'", "]", "=", "{", "}", "self", ".", "parsed_data", "[", "'message_port'", "]", "=", "{", "}", "if", "os", ".", "path", ".", "isfile", "(", "self", ".", "impl_file", ")", "and", "exist_comments", "(", "self", ")", ":", "self", ".", "parsed_data", "[", "'io_signature'", "]", "=", "io_signature", "(", "self", ".", "impl_file", ")", "self", ".", "parsed_data", "[", "'message_port'", "]", "=", "message_port", "(", "self", ".", "impl_file", ")", "read_comments", "(", "self", ")", "elif", "os", ".", "path", ".", "isfile", "(", "self", ".", "impl_file", ")", "and", "not", "exist_comments", "(", "self", ")", ":", "self", ".", "parsed_data", "[", "'io_signature'", "]", "=", "io_signature", "(", "self", ".", "impl_file", ")", "self", ".", "parsed_data", "[", "'message_port'", "]", "=", "message_port", "(", "self", ".", "impl_file", ")", "if", "self", ".", "addcomments", ":", "add_comments", "(", "self", ")", "elif", "not", "os", ".", "path", ".", "isfile", "(", "self", ".", "impl_file", ")", "and", "exist_comments", "(", "self", ")", ":", "read_comments", "(", "self", ")", "else", ":", "self", ".", "parsed_data", "[", "'io_signature'", "]", "=", "{", "\"input\"", ":", "[", "]", ",", "\"output\"", ":", "[", "]", "}", "self", ".", "parsed_data", "[", "'message_port'", "]", "=", "self", ".", "parsed_data", "[", "'io_signature'", "]", "# make", "try", ":", "self", ".", "parsed_data", "[", "'make'", "]", "=", "{", "}", "self", ".", "parsed_data", "[", "'make'", "]", "[", "'arguments'", "]", "=", "[", "]", "query_m", "=", "declarations", ".", "custom_matcher_t", "(", "lambda", "mem_fun", ":", "mem_fun", ".", "name", ".", "startswith", "(", "'make'", ")", ")", "query_make", "=", "query_m", "&", "declarations", ".", "access_type_matcher_t", "(", "'public'", ")", "make_func", "=", "main_class", ".", "member_functions", "(", "function", "=", "query_make", ",", "allow_empty", "=", "True", ",", "header_file", "=", "self", ".", "target_file", ")", "criteria", "=", "declarations", ".", "calldef_matcher", "(", "name", "=", "'make'", ")", "_make_fun", "=", "declarations", ".", "matcher", ".", "get_single", "(", "criteria", ",", "main_class", ")", "_make_fun", "=", "str", "(", "_make_fun", ")", ".", "split", "(", "'make'", ")", "[", "-", "1", "]", ".", "split", "(", "')'", ")", "[", "0", "]", ".", "split", "(", "'('", ")", "[", "1", "]", ".", "lstrip", "(", ")", ".", "rstrip", "(", ")", ".", "split", "(", "','", ")", "if", "make_func", ":", "for", "arg", "in", "make_func", "[", "0", "]", ".", "arguments", ":", "make_arguments", "=", "None", "'''\n for _arg in _make_fun:\n if str(arg.name) in _arg:\n make_arguments = {\n \"name\": str(arg.name),\n \"dtype\": str(arg.decl_type),\n \"default\": \"\"\n }\n if re.findall(r'[-+]?\\d*\\.\\d+|\\d+', _arg):\n make_arguments['default'] = re.findall(\n r'[-+]?\\d*\\.\\d+|\\d+', _arg)[0]\n elif re.findall(r'\\\"(.+?)\\\"', _arg):\n make_arguments['default'] = re.findall(\n r'\\\"(.+?)\\\"', _arg)[0]\n elif \"true\" in _arg:\n make_arguments['default'] = \"True\"\n elif \"false\" in _arg:\n make_arguments['default'] = \"False\"\n '''", "# In case the search did not find an argument in the inner loop", "# This happens while parsing digital/symbol_sync_cc.h", "if", "make_arguments", ":", "self", ".", "parsed_data", "[", "'make'", "]", "[", "'arguments'", "]", ".", "append", "(", "make_arguments", ".", "copy", "(", ")", ")", "else", ":", "self", ".", "parsed_data", "[", "'make'", "]", "[", "'arguments'", "]", ".", "append", "(", "{", "\"name\"", ":", "str", "(", "arg", ".", "name", ")", ",", "\"dtype\"", ":", "str", "(", "arg", ".", "decl_type", ")", ",", "\"default\"", ":", "arg", ".", "default_value", "# can we get default argument directly from arg", "}", ")", "except", "RuntimeError", ":", "self", ".", "parsed_data", "[", "'make'", "]", "=", "{", "}", "self", ".", "parsed_data", "[", "'make'", "]", "[", "'arguments'", "]", "=", "[", "]", "# setters", "try", ":", "self", ".", "parsed_data", "[", "'methods'", "]", "=", "[", "]", "query_methods", "=", "declarations", ".", "access_type_matcher_t", "(", "'public'", ")", "setters", "=", "main_class", ".", "member_functions", "(", "function", "=", "query_methods", ",", "allow_empty", "=", "True", ",", "header_file", "=", "self", ".", "target_file", ")", "getter_arguments", "=", "[", "]", "if", "setters", ":", "for", "setter", "in", "setters", ":", "if", "str", "(", "setter", ".", "name", ")", ".", "startswith", "(", "'set_'", ")", "and", "setter", ".", "arguments", ":", "setter_args", "=", "{", "\"name\"", ":", "str", "(", "setter", ".", "name", ")", ",", "\"arguments_type\"", ":", "[", "]", "}", "for", "argument", "in", "setter", ".", "arguments", ":", "args", "=", "{", "\"name\"", ":", "str", "(", "argument", ".", "name", ")", ",", "\"dtype\"", ":", "str", "(", "argument", ".", "decl_type", ")", "}", "getter_arguments", ".", "append", "(", "args", "[", "'name'", "]", ")", "setter_args", "[", "'arguments_type'", "]", ".", "append", "(", "args", ".", "copy", "(", ")", ")", "self", ".", "parsed_data", "[", "'methods'", "]", ".", "append", "(", "setter_args", ".", "copy", "(", ")", ")", "except", "RuntimeError", ":", "self", ".", "parsed_data", "[", "'methods'", "]", "=", "[", "]", "# getters", "try", ":", "self", ".", "parsed_data", "[", "'properties'", "]", "=", "[", "]", "query_properties", "=", "declarations", ".", "access_type_matcher_t", "(", "'public'", ")", "getters", "=", "main_class", ".", "member_functions", "(", "function", "=", "query_properties", ",", "allow_empty", "=", "True", ",", "header_file", "=", "self", ".", "target_file", ")", "if", "getters", ":", "for", "getter", "in", "getters", ":", "if", "not", "getter", ".", "arguments", "or", "getter", ".", "has_const", ":", "getter_args", "=", "{", "\"name\"", ":", "str", "(", "getter", ".", "name", ")", ",", "\"dtype\"", ":", "str", "(", "getter", ".", "return_type", ")", ",", "\"read_only\"", ":", "True", "}", "if", "getter_args", "[", "'name'", "]", "in", "getter_arguments", ":", "getter_args", "[", "\"read_only\"", "]", "=", "False", "self", ".", "parsed_data", "[", "'properties'", "]", ".", "append", "(", "getter_args", ".", "copy", "(", ")", ")", "except", "RuntimeError", ":", "self", ".", "parsed_data", "[", "'properties'", "]", "=", "[", "]", "# all member functions", "# setters and getters do not return all member functions for a block", "try", ":", "self", ".", "parsed_data", "[", "'member_functions'", "]", "=", "[", "]", "query_methods", "=", "declarations", ".", "access_type_matcher_t", "(", "'public'", ")", "functions", "=", "main_class", ".", "member_functions", "(", "function", "=", "query_methods", ",", "allow_empty", "=", "True", ",", "header_file", "=", "self", ".", "target_file", ")", "if", "functions", ":", "for", "fcn", "in", "functions", ":", "if", "str", "(", "fcn", ".", "name", ")", "not", "in", "[", "main_class", ".", "name", ",", "'~'", "+", "main_class", ".", "name", ",", "'make'", "]", ":", "fcn_args", "=", "{", "\"name\"", ":", "str", "(", "fcn", ".", "name", ")", ",", "\"arguments\"", ":", "[", "]", "}", "for", "argument", "in", "fcn", ".", "arguments", ":", "args", "=", "{", "\"name\"", ":", "str", "(", "argument", ".", "name", ")", ",", "\"dtype\"", ":", "str", "(", "argument", ".", "decl_type", ")", ",", "\"default\"", ":", "argument", ".", "default_value", "}", "fcn_args", "[", "'arguments'", "]", ".", "append", "(", "args", ".", "copy", "(", ")", ")", "self", ".", "parsed_data", "[", "'member_functions'", "]", ".", "append", "(", "fcn_args", ".", "copy", "(", ")", ")", "except", "RuntimeError", ":", "self", ".", "parsed_data", "[", "'member_functions'", "]", "=", "[", "]", "# documentation", "try", ":", "_index", "=", "None", "header_file", "=", "codecs", ".", "open", "(", "self", ".", "target_file", ",", "'r'", ",", "'cp932'", ")", "self", ".", "parsed_data", "[", "'docstring'", "]", "=", "re", ".", "compile", "(", "r'//.*?$|/\\*.*?\\*/'", ",", "re", ".", "DOTALL", "|", "re", ".", "MULTILINE", ")", ".", "findall", "(", "header_file", ".", "read", "(", ")", ")", "[", "2", ":", "]", "header_file", ".", "close", "(", ")", "for", "doc", "in", "self", ".", "parsed_data", "[", "'docstring'", "]", ":", "if", "Constants", ".", "BLOCKTOOL", "in", "doc", ":", "_index", "=", "self", ".", "parsed_data", "[", "'docstring'", "]", ".", "index", "(", "doc", ")", "if", "_index", "is", "not", "None", ":", "self", ".", "parsed_data", "[", "'docstring'", "]", "=", "self", ".", "parsed_data", "[", "'docstring'", "]", "[", ":", "_index", "]", "except", ":", "self", ".", "parsed_data", "[", "'docstring'", "]", "=", "[", "]", "return", "self", ".", "parsed_data" ]
https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/gr-utils/blocktool/core/parseheader.py#L85-L317
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/external/coremltools_wrap/coremltools/coremltools/models/_infer_shapes_nn_mlmodel.py
python
infer_shapes
(nn_spec, input_spec, input_shape_dict=None)
return shape_dict
Input: spec : mlmodel spec input_shape_dict: dictionary of string --> tuple string: input name tuple: input shape as a 5 length tuple in order (Seq, Batch, C, H, W) If input_shape_dict is not provided, input shapes are inferred from the input description in the mlmodel. Since the description in the specification only contains values of C,H,W; Seq and Batch dimensions are set to 1. Output: shape_dict: dictionary containing all the blobs in the neural network and their shapes, expressed as length 5 tuples, to be interpreted in order (Seq, Batch, C, H, W).
Input:
[ "Input", ":" ]
def infer_shapes(nn_spec, input_spec, input_shape_dict=None): """ Input: spec : mlmodel spec input_shape_dict: dictionary of string --> tuple string: input name tuple: input shape as a 5 length tuple in order (Seq, Batch, C, H, W) If input_shape_dict is not provided, input shapes are inferred from the input description in the mlmodel. Since the description in the specification only contains values of C,H,W; Seq and Batch dimensions are set to 1. Output: shape_dict: dictionary containing all the blobs in the neural network and their shapes, expressed as length 5 tuples, to be interpreted in order (Seq, Batch, C, H, W). """ shape_dict = {} if input_shape_dict: for key, value in input_shape_dict.items(): assert len(value) == 5, "Shape of the input must be of length 5" shape_dict[key] = value # construct input_shape_dict from the model description else: for inp in input_spec: input_name = inp.name C = H = W = 1 if inp.type.WhichOneof("Type") == "imageType": W = int(inp.type.imageType.width) H = int(inp.type.imageType.height) colorspace = _FeatureTypes_pb2.ImageFeatureType.ColorSpace.Name( inp.type.imageType.colorSpace ) if colorspace == "GRAYSCALE": C = 1 elif colorspace == "RGB" or colorspace == "BGR": C = 3 else: raise ValueError("Input %s : Invalid Colorspace" % (input_name)) elif inp.type.WhichOneof("Type") == "multiArrayType": array_shape = inp.type.multiArrayType.shape if len(array_shape) == 1: C = array_shape[0] elif len(array_shape) == 3: C, H, W = map(int, array_shape) else: raise ValueError( "Input %s : Multi array must be of length 1 or 3" % (input_name) ) else: raise ValueError( "Input %s : Input type must be image or multi-array" % (input_name) ) shape_dict[input_name] = (1, 1, C, H, W) layers = nn_spec.layers for i, layer in enumerate(layers): for inp in layer.input: assert inp in shape_dict, "Input %s shape not cannot be determined" % (inp) layer_type = layer.WhichOneof("layer") if layer_type == "custom": break layer_translator = _get_translator_function(layer_type) layer_translator(layer, shape_dict) return shape_dict
[ "def", "infer_shapes", "(", "nn_spec", ",", "input_spec", ",", "input_shape_dict", "=", "None", ")", ":", "shape_dict", "=", "{", "}", "if", "input_shape_dict", ":", "for", "key", ",", "value", "in", "input_shape_dict", ".", "items", "(", ")", ":", "assert", "len", "(", "value", ")", "==", "5", ",", "\"Shape of the input must be of length 5\"", "shape_dict", "[", "key", "]", "=", "value", "# construct input_shape_dict from the model description", "else", ":", "for", "inp", "in", "input_spec", ":", "input_name", "=", "inp", ".", "name", "C", "=", "H", "=", "W", "=", "1", "if", "inp", ".", "type", ".", "WhichOneof", "(", "\"Type\"", ")", "==", "\"imageType\"", ":", "W", "=", "int", "(", "inp", ".", "type", ".", "imageType", ".", "width", ")", "H", "=", "int", "(", "inp", ".", "type", ".", "imageType", ".", "height", ")", "colorspace", "=", "_FeatureTypes_pb2", ".", "ImageFeatureType", ".", "ColorSpace", ".", "Name", "(", "inp", ".", "type", ".", "imageType", ".", "colorSpace", ")", "if", "colorspace", "==", "\"GRAYSCALE\"", ":", "C", "=", "1", "elif", "colorspace", "==", "\"RGB\"", "or", "colorspace", "==", "\"BGR\"", ":", "C", "=", "3", "else", ":", "raise", "ValueError", "(", "\"Input %s : Invalid Colorspace\"", "%", "(", "input_name", ")", ")", "elif", "inp", ".", "type", ".", "WhichOneof", "(", "\"Type\"", ")", "==", "\"multiArrayType\"", ":", "array_shape", "=", "inp", ".", "type", ".", "multiArrayType", ".", "shape", "if", "len", "(", "array_shape", ")", "==", "1", ":", "C", "=", "array_shape", "[", "0", "]", "elif", "len", "(", "array_shape", ")", "==", "3", ":", "C", ",", "H", ",", "W", "=", "map", "(", "int", ",", "array_shape", ")", "else", ":", "raise", "ValueError", "(", "\"Input %s : Multi array must be of length 1 or 3\"", "%", "(", "input_name", ")", ")", "else", ":", "raise", "ValueError", "(", "\"Input %s : Input type must be image or multi-array\"", "%", "(", "input_name", ")", ")", "shape_dict", "[", "input_name", "]", "=", "(", "1", ",", "1", ",", "C", ",", "H", ",", "W", ")", "layers", "=", "nn_spec", ".", "layers", "for", "i", ",", "layer", "in", "enumerate", "(", "layers", ")", ":", "for", "inp", "in", "layer", ".", "input", ":", "assert", "inp", "in", "shape_dict", ",", "\"Input %s shape not cannot be determined\"", "%", "(", "inp", ")", "layer_type", "=", "layer", ".", "WhichOneof", "(", "\"layer\"", ")", "if", "layer_type", "==", "\"custom\"", ":", "break", "layer_translator", "=", "_get_translator_function", "(", "layer_type", ")", "layer_translator", "(", "layer", ",", "shape_dict", ")", "return", "shape_dict" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/coremltools/models/_infer_shapes_nn_mlmodel.py#L416-L484
mandiant/flare-wmi
b0a5a094ff9ca7d7a1c4fc711dc00c74dec4b6b1
python-cim/samples/auto_carve_class_definitions.py
python
filetime2datetime
(ft)
return datetime.datetime.utcfromtimestamp(float(ft) * 1e-7 - 11644473600)
convert a FILETIME 64-bit integer to a timestamp. Args: ft (int): the FILETIME number. Returns: datetime.datetime: the python timestamp.
convert a FILETIME 64-bit integer to a timestamp. Args: ft (int): the FILETIME number.
[ "convert", "a", "FILETIME", "64", "-", "bit", "integer", "to", "a", "timestamp", ".", "Args", ":", "ft", "(", "int", ")", ":", "the", "FILETIME", "number", "." ]
def filetime2datetime(ft): ''' convert a FILETIME 64-bit integer to a timestamp. Args: ft (int): the FILETIME number. Returns: datetime.datetime: the python timestamp. ''' return datetime.datetime.utcfromtimestamp(float(ft) * 1e-7 - 11644473600)
[ "def", "filetime2datetime", "(", "ft", ")", ":", "return", "datetime", ".", "datetime", ".", "utcfromtimestamp", "(", "float", "(", "ft", ")", "*", "1e-7", "-", "11644473600", ")" ]
https://github.com/mandiant/flare-wmi/blob/b0a5a094ff9ca7d7a1c4fc711dc00c74dec4b6b1/python-cim/samples/auto_carve_class_definitions.py#L22-L32
apache/singa
93fd9da72694e68bfe3fb29d0183a65263d238a1
python/singa/autograd.py
python
Max._max
(self, a, b)
return res, (mask0, mask1)
Args: a (CTensor): First operand b (CTensor): Second operand Returns: CTensor, the output tuple of CTensor, mask tensor
Args: a (CTensor): First operand b (CTensor): Second operand Returns: CTensor, the output tuple of CTensor, mask tensor
[ "Args", ":", "a", "(", "CTensor", ")", ":", "First", "operand", "b", "(", "CTensor", ")", ":", "Second", "operand", "Returns", ":", "CTensor", "the", "output", "tuple", "of", "CTensor", "mask", "tensor" ]
def _max(self, a, b): """ Args: a (CTensor): First operand b (CTensor): Second operand Returns: CTensor, the output tuple of CTensor, mask tensor """ m = singa.__sub__(a, b) mask0 = singa.GEFloat(m, 0) mask1 = singa.LTFloat(m, 0) res = singa.__add__(singa.__mul__(mask0, a), singa.__mul__(mask1, b)) return res, (mask0, mask1)
[ "def", "_max", "(", "self", ",", "a", ",", "b", ")", ":", "m", "=", "singa", ".", "__sub__", "(", "a", ",", "b", ")", "mask0", "=", "singa", ".", "GEFloat", "(", "m", ",", "0", ")", "mask1", "=", "singa", ".", "LTFloat", "(", "m", ",", "0", ")", "res", "=", "singa", ".", "__add__", "(", "singa", ".", "__mul__", "(", "mask0", ",", "a", ")", ",", "singa", ".", "__mul__", "(", "mask1", ",", "b", ")", ")", "return", "res", ",", "(", "mask0", ",", "mask1", ")" ]
https://github.com/apache/singa/blob/93fd9da72694e68bfe3fb29d0183a65263d238a1/python/singa/autograd.py#L3409-L3422
deepmind/streetlearn
ccf1d60b9c45154894d45a897748aee85d7eb69b
streetlearn/python/environment/batched_streetlearn.py
python
BatchedStreetLearn.action_set
(self)
return self._envs[0].action_set()
Returns the set of actions, mapping integer actions to 1D arrays.
Returns the set of actions, mapping integer actions to 1D arrays.
[ "Returns", "the", "set", "of", "actions", "mapping", "integer", "actions", "to", "1D", "arrays", "." ]
def action_set(self): """Returns the set of actions, mapping integer actions to 1D arrays.""" return self._envs[0].action_set()
[ "def", "action_set", "(", "self", ")", ":", "return", "self", ".", "_envs", "[", "0", "]", ".", "action_set", "(", ")" ]
https://github.com/deepmind/streetlearn/blob/ccf1d60b9c45154894d45a897748aee85d7eb69b/streetlearn/python/environment/batched_streetlearn.py#L166-L168
wesnoth/wesnoth
6ccac5a5e8ff75303c9190c0da60580925cb32c0
data/tools/wesnoth/wmltools3.py
python
pop_to_top
(whoami)
Pop upward to the top-level directory.
Pop upward to the top-level directory.
[ "Pop", "upward", "to", "the", "top", "-", "level", "directory", "." ]
def pop_to_top(whoami): "Pop upward to the top-level directory." upwards = os.getcwd().split(os.sep) upwards.reverse() for pathpart in upwards: # Loose match because people have things like git trees. if os.path.basename(pathpart).find("wesnoth") > -1: break else: os.chdir("..") else: print(whoami + ": must be run from within a Battle " "for Wesnoth source tree.", file=sys.stderr) sys.exit(1)
[ "def", "pop_to_top", "(", "whoami", ")", ":", "upwards", "=", "os", ".", "getcwd", "(", ")", ".", "split", "(", "os", ".", "sep", ")", "upwards", ".", "reverse", "(", ")", "for", "pathpart", "in", "upwards", ":", "# Loose match because people have things like git trees.", "if", "os", ".", "path", ".", "basename", "(", "pathpart", ")", ".", "find", "(", "\"wesnoth\"", ")", ">", "-", "1", ":", "break", "else", ":", "os", ".", "chdir", "(", "\"..\"", ")", "else", ":", "print", "(", "whoami", "+", "\": must be run from within a Battle \"", "\"for Wesnoth source tree.\"", ",", "file", "=", "sys", ".", "stderr", ")", "sys", ".", "exit", "(", "1", ")" ]
https://github.com/wesnoth/wesnoth/blob/6ccac5a5e8ff75303c9190c0da60580925cb32c0/data/tools/wesnoth/wmltools3.py#L100-L113
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/resources/ico_tools.py
python
RebuildANDMask
(iconimage)
return iconimage[:40 + xor_palette_size + xor_size] + and_data
Rebuild the AND mask in an icon image. GIMP (<=2.8.14) creates a bad AND mask on 32-bit icon images (pixels with <50% opacity are marked as transparent, which end up looking black on Windows). So, if this is a 32-bit image, throw the mask away and recompute it from the alpha data. (See: https://bugzilla.gnome.org/show_bug.cgi?id=755200) Args: iconimage: Bytes of an icon image (the BMP data for an entry in an ICO file). Must be in BMP format, not PNG. Does not need to be 32-bit (if it is not 32-bit, this is a no-op). Returns: An updated |iconimage|, with the AND mask re-computed using ComputeANDMaskFromAlpha.
Rebuild the AND mask in an icon image.
[ "Rebuild", "the", "AND", "mask", "in", "an", "icon", "image", "." ]
def RebuildANDMask(iconimage): """Rebuild the AND mask in an icon image. GIMP (<=2.8.14) creates a bad AND mask on 32-bit icon images (pixels with <50% opacity are marked as transparent, which end up looking black on Windows). So, if this is a 32-bit image, throw the mask away and recompute it from the alpha data. (See: https://bugzilla.gnome.org/show_bug.cgi?id=755200) Args: iconimage: Bytes of an icon image (the BMP data for an entry in an ICO file). Must be in BMP format, not PNG. Does not need to be 32-bit (if it is not 32-bit, this is a no-op). Returns: An updated |iconimage|, with the AND mask re-computed using ComputeANDMaskFromAlpha. """ # Parse BITMAPINFOHEADER. (_, width, height, _, bpp, _, _, _, _, num_colors, _) = struct.unpack( '<LLLHHLLLLLL', iconimage[:40]) if bpp != 32: # No alpha channel, so the mask cannot be "wrong" (it is the only source of # transparency information). return iconimage height /= 2 xor_size = int(math.ceil(width * bpp / 32.0)) * 4 * height # num_colors can be 0, implying 2^bpp colors. xor_palette_size = (num_colors or (1 << bpp if bpp < 24 else 0)) * 4 xor_data = iconimage[40 + xor_palette_size : 40 + xor_palette_size + xor_size] and_data = ComputeANDMaskFromAlpha(xor_data, width, height) # Replace the AND mask in the original icon data. return iconimage[:40 + xor_palette_size + xor_size] + and_data
[ "def", "RebuildANDMask", "(", "iconimage", ")", ":", "# Parse BITMAPINFOHEADER.", "(", "_", ",", "width", ",", "height", ",", "_", ",", "bpp", ",", "_", ",", "_", ",", "_", ",", "_", ",", "num_colors", ",", "_", ")", "=", "struct", ".", "unpack", "(", "'<LLLHHLLLLLL'", ",", "iconimage", "[", ":", "40", "]", ")", "if", "bpp", "!=", "32", ":", "# No alpha channel, so the mask cannot be \"wrong\" (it is the only source of", "# transparency information).", "return", "iconimage", "height", "/=", "2", "xor_size", "=", "int", "(", "math", ".", "ceil", "(", "width", "*", "bpp", "/", "32.0", ")", ")", "*", "4", "*", "height", "# num_colors can be 0, implying 2^bpp colors.", "xor_palette_size", "=", "(", "num_colors", "or", "(", "1", "<<", "bpp", "if", "bpp", "<", "24", "else", "0", ")", ")", "*", "4", "xor_data", "=", "iconimage", "[", "40", "+", "xor_palette_size", ":", "40", "+", "xor_palette_size", "+", "xor_size", "]", "and_data", "=", "ComputeANDMaskFromAlpha", "(", "xor_data", ",", "width", ",", "height", ")", "# Replace the AND mask in the original icon data.", "return", "iconimage", "[", ":", "40", "+", "xor_palette_size", "+", "xor_size", "]", "+", "and_data" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/resources/ico_tools.py#L100-L137
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/importlib_metadata/_compat.py
python
install
(cls)
return cls
Class decorator for installation on sys.meta_path. Adds the backport DistributionFinder to sys.meta_path and attempts to disable the finder functionality of the stdlib DistributionFinder.
Class decorator for installation on sys.meta_path.
[ "Class", "decorator", "for", "installation", "on", "sys", ".", "meta_path", "." ]
def install(cls): """ Class decorator for installation on sys.meta_path. Adds the backport DistributionFinder to sys.meta_path and attempts to disable the finder functionality of the stdlib DistributionFinder. """ sys.meta_path.append(cls()) disable_stdlib_finder() return cls
[ "def", "install", "(", "cls", ")", ":", "sys", ".", "meta_path", ".", "append", "(", "cls", "(", ")", ")", "disable_stdlib_finder", "(", ")", "return", "cls" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/importlib_metadata/_compat.py#L57-L67
microsoft/checkedc-clang
a173fefde5d7877b7750e7ce96dd08cf18baebf2
llvm/examples/Kaleidoscope/MCJIT/complete/genk-timing.py
python
KScriptGenerator.updateFunctionCallMap
(self, caller, callee)
Maintains a map of functions that are called from other functions
Maintains a map of functions that are called from other functions
[ "Maintains", "a", "map", "of", "functions", "that", "are", "called", "from", "other", "functions" ]
def updateFunctionCallMap(self, caller, callee): """Maintains a map of functions that are called from other functions""" if not caller in self.calledFunctionTable: self.calledFunctionTable[caller] = [] if not callee in self.calledFunctionTable[caller]: self.calledFunctionTable[caller].append(callee) if not caller in self.comprehensiveCalledFunctionTable: self.comprehensiveCalledFunctionTable[caller] = [] self.comprehensiveCalledFunctionTable[caller].append(callee)
[ "def", "updateFunctionCallMap", "(", "self", ",", "caller", ",", "callee", ")", ":", "if", "not", "caller", "in", "self", ".", "calledFunctionTable", ":", "self", ".", "calledFunctionTable", "[", "caller", "]", "=", "[", "]", "if", "not", "callee", "in", "self", ".", "calledFunctionTable", "[", "caller", "]", ":", "self", ".", "calledFunctionTable", "[", "caller", "]", ".", "append", "(", "callee", ")", "if", "not", "caller", "in", "self", ".", "comprehensiveCalledFunctionTable", ":", "self", ".", "comprehensiveCalledFunctionTable", "[", "caller", "]", "=", "[", "]", "self", ".", "comprehensiveCalledFunctionTable", "[", "caller", "]", ".", "append", "(", "callee", ")" ]
https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/llvm/examples/Kaleidoscope/MCJIT/complete/genk-timing.py#L63-L71
intel/llvm
e6d0547e9d99b5a56430c4749f6c7e328bf221ab
clang/bindings/python/clang/cindex.py
python
Type.get_declaration
(self)
return conf.lib.clang_getTypeDeclaration(self)
Return the cursor for the declaration of the given type.
Return the cursor for the declaration of the given type.
[ "Return", "the", "cursor", "for", "the", "declaration", "of", "the", "given", "type", "." ]
def get_declaration(self): """ Return the cursor for the declaration of the given type. """ return conf.lib.clang_getTypeDeclaration(self)
[ "def", "get_declaration", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_getTypeDeclaration", "(", "self", ")" ]
https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/clang/bindings/python/clang/cindex.py#L2343-L2347
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/factorization/python/ops/factorization_ops.py
python
WALSModel.row_weights
(self)
return self._row_weights
Returns a list of tensors corresponding to row weight shards.
Returns a list of tensors corresponding to row weight shards.
[ "Returns", "a", "list", "of", "tensors", "corresponding", "to", "row", "weight", "shards", "." ]
def row_weights(self): """Returns a list of tensors corresponding to row weight shards.""" return self._row_weights
[ "def", "row_weights", "(", "self", ")", ":", "return", "self", ".", "_row_weights" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/factorization/python/ops/factorization_ops.py#L284-L286
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_pyio.py
python
IOBase.flush
(self)
Flush write buffers, if applicable. This is not implemented for read-only and non-blocking streams.
Flush write buffers, if applicable.
[ "Flush", "write", "buffers", "if", "applicable", "." ]
def flush(self): """Flush write buffers, if applicable. This is not implemented for read-only and non-blocking streams. """ self._checkClosed()
[ "def", "flush", "(", "self", ")", ":", "self", ".", "_checkClosed", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_pyio.py#L353-L358
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/lib2to3/fixer_base.py
python
BaseFix.start_tree
(self, tree, filename)
Some fixers need to maintain tree-wide state. This method is called once, at the start of tree fix-up. tree - the root node of the tree to be processed. filename - the name of the file the tree came from.
Some fixers need to maintain tree-wide state. This method is called once, at the start of tree fix-up.
[ "Some", "fixers", "need", "to", "maintain", "tree", "-", "wide", "state", ".", "This", "method", "is", "called", "once", "at", "the", "start", "of", "tree", "fix", "-", "up", "." ]
def start_tree(self, tree, filename): """Some fixers need to maintain tree-wide state. This method is called once, at the start of tree fix-up. tree - the root node of the tree to be processed. filename - the name of the file the tree came from. """ self.used_names = tree.used_names self.set_filename(filename) self.numbers = itertools.count(1) self.first_log = True
[ "def", "start_tree", "(", "self", ",", "tree", ",", "filename", ")", ":", "self", ".", "used_names", "=", "tree", ".", "used_names", "self", ".", "set_filename", "(", "filename", ")", "self", ".", "numbers", "=", "itertools", ".", "count", "(", "1", ")", "self", ".", "first_log", "=", "True" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/lib2to3/fixer_base.py#L141-L151
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/idlelib/format.py
python
FormatRegion.dedent_region_event
(self, event=None)
return "break"
Dedent region by indentwidth spaces.
Dedent region by indentwidth spaces.
[ "Dedent", "region", "by", "indentwidth", "spaces", "." ]
def dedent_region_event(self, event=None): "Dedent region by indentwidth spaces." head, tail, chars, lines = self.get_region() for pos in range(len(lines)): line = lines[pos] if line: raw, effective = get_line_indent(line, self.editwin.tabwidth) effective = max(effective - self.editwin.indentwidth, 0) lines[pos] = self.editwin._make_blanks(effective) + line[raw:] self.set_region(head, tail, chars, lines) return "break"
[ "def", "dedent_region_event", "(", "self", ",", "event", "=", "None", ")", ":", "head", ",", "tail", ",", "chars", ",", "lines", "=", "self", ".", "get_region", "(", ")", "for", "pos", "in", "range", "(", "len", "(", "lines", ")", ")", ":", "line", "=", "lines", "[", "pos", "]", "if", "line", ":", "raw", ",", "effective", "=", "get_line_indent", "(", "line", ",", "self", ".", "editwin", ".", "tabwidth", ")", "effective", "=", "max", "(", "effective", "-", "self", ".", "editwin", ".", "indentwidth", ",", "0", ")", "lines", "[", "pos", "]", "=", "self", ".", "editwin", ".", "_make_blanks", "(", "effective", ")", "+", "line", "[", "raw", ":", "]", "self", ".", "set_region", "(", "head", ",", "tail", ",", "chars", ",", "lines", ")", "return", "\"break\"" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/idlelib/format.py#L276-L286
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/telnetlib.py
python
Telnet.read_eager
(self)
return self.read_very_lazy()
Read readily available data. Raise EOFError if connection closed and no cooked data available. Return '' if no cooked data available otherwise. Don't block unless in the midst of an IAC sequence.
Read readily available data.
[ "Read", "readily", "available", "data", "." ]
def read_eager(self): """Read readily available data. Raise EOFError if connection closed and no cooked data available. Return '' if no cooked data available otherwise. Don't block unless in the midst of an IAC sequence. """ self.process_rawq() while not self.cookedq and not self.eof and self.sock_avail(): self.fill_rawq() self.process_rawq() return self.read_very_lazy()
[ "def", "read_eager", "(", "self", ")", ":", "self", ".", "process_rawq", "(", ")", "while", "not", "self", ".", "cookedq", "and", "not", "self", ".", "eof", "and", "self", ".", "sock_avail", "(", ")", ":", "self", ".", "fill_rawq", "(", ")", "self", ".", "process_rawq", "(", ")", "return", "self", ".", "read_very_lazy", "(", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/telnetlib.py#L417-L429
google/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
earth_enterprise/src/server/wsgi/common/utils.py
python
GetApacheSchemePortFromListen
()
return None
Gets scheme, port number that Apache is running on. Gets scheme and port number from Listen directive of httpd config file: Format of Listen directive: Listen [IP-address:]portnumber [protocol] Note: IPv6 addresses must be surrounded in square brackets: Listen [2001:db8::a00:20ff:fea7:ccea]:80 Returns: tuple (scheme, port number) that Apache is listening on or None.
Gets scheme, port number that Apache is running on.
[ "Gets", "scheme", "port", "number", "that", "Apache", "is", "running", "on", "." ]
def GetApacheSchemePortFromListen(): """Gets scheme, port number that Apache is running on. Gets scheme and port number from Listen directive of httpd config file: Format of Listen directive: Listen [IP-address:]portnumber [protocol] Note: IPv6 addresses must be surrounded in square brackets: Listen [2001:db8::a00:20ff:fea7:ccea]:80 Returns: tuple (scheme, port number) that Apache is listening on or None. """ match = MatchPattern( GEHTTPD_CONF_PATH, r"^Listen\s+(?:\[?([a-fA-F\d\.\:]+)\]?:)?(\d+)(?:\s+(https?))?") if match: (scheme, port) = (match[2], match[1]) assert port if not scheme: scheme = "https" if port == "443" else "http" return (scheme, port) logging.error("Listen directive is not specified in gehttpd config.") return None
[ "def", "GetApacheSchemePortFromListen", "(", ")", ":", "match", "=", "MatchPattern", "(", "GEHTTPD_CONF_PATH", ",", "r\"^Listen\\s+(?:\\[?([a-fA-F\\d\\.\\:]+)\\]?:)?(\\d+)(?:\\s+(https?))?\"", ")", "if", "match", ":", "(", "scheme", ",", "port", ")", "=", "(", "match", "[", "2", "]", ",", "match", "[", "1", "]", ")", "assert", "port", "if", "not", "scheme", ":", "scheme", "=", "\"https\"", "if", "port", "==", "\"443\"", "else", "\"http\"", "return", "(", "scheme", ",", "port", ")", "logging", ".", "error", "(", "\"Listen directive is not specified in gehttpd config.\"", ")", "return", "None" ]
https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/server/wsgi/common/utils.py#L199-L221
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/pip/_vendor/requests/packages/urllib3/filepost.py
python
encode_multipart_formdata
(fields, boundary=None)
return body.getvalue(), content_type
Encode a dictionary of ``fields`` using the multipart/form-data MIME format. :param fields: Dictionary of fields or list of (key, :class:`~urllib3.fields.RequestField`). :param boundary: If not specified, then a random boundary will be generated using :func:`mimetools.choose_boundary`.
Encode a dictionary of ``fields`` using the multipart/form-data MIME format.
[ "Encode", "a", "dictionary", "of", "fields", "using", "the", "multipart", "/", "form", "-", "data", "MIME", "format", "." ]
def encode_multipart_formdata(fields, boundary=None): """ Encode a dictionary of ``fields`` using the multipart/form-data MIME format. :param fields: Dictionary of fields or list of (key, :class:`~urllib3.fields.RequestField`). :param boundary: If not specified, then a random boundary will be generated using :func:`mimetools.choose_boundary`. """ body = BytesIO() if boundary is None: boundary = choose_boundary() for field in iter_field_objects(fields): body.write(b('--%s\r\n' % (boundary))) writer(body).write(field.render_headers()) data = field.data if isinstance(data, int): data = str(data) # Backwards compatibility if isinstance(data, six.text_type): writer(body).write(data) else: body.write(data) body.write(b'\r\n') body.write(b('--%s--\r\n' % (boundary))) content_type = str('multipart/form-data; boundary=%s' % boundary) return body.getvalue(), content_type
[ "def", "encode_multipart_formdata", "(", "fields", ",", "boundary", "=", "None", ")", ":", "body", "=", "BytesIO", "(", ")", "if", "boundary", "is", "None", ":", "boundary", "=", "choose_boundary", "(", ")", "for", "field", "in", "iter_field_objects", "(", "fields", ")", ":", "body", ".", "write", "(", "b", "(", "'--%s\\r\\n'", "%", "(", "boundary", ")", ")", ")", "writer", "(", "body", ")", ".", "write", "(", "field", ".", "render_headers", "(", ")", ")", "data", "=", "field", ".", "data", "if", "isinstance", "(", "data", ",", "int", ")", ":", "data", "=", "str", "(", "data", ")", "# Backwards compatibility", "if", "isinstance", "(", "data", ",", "six", ".", "text_type", ")", ":", "writer", "(", "body", ")", ".", "write", "(", "data", ")", "else", ":", "body", ".", "write", "(", "data", ")", "body", ".", "write", "(", "b'\\r\\n'", ")", "body", ".", "write", "(", "b", "(", "'--%s--\\r\\n'", "%", "(", "boundary", ")", ")", ")", "content_type", "=", "str", "(", "'multipart/form-data; boundary=%s'", "%", "boundary", ")", "return", "body", ".", "getvalue", "(", ")", ",", "content_type" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/requests/packages/urllib3/filepost.py#L58-L93
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/contrib/learn/python/learn/utils/checkpoints.py
python
init_from_checkpoint
(checkpoint_dir, assignment_map)
See `tf.contrib.framework.init_from_checkpoint`.
See `tf.contrib.framework.init_from_checkpoint`.
[ "See", "tf", ".", "contrib", ".", "framework", ".", "init_from_checkpoint", "." ]
def init_from_checkpoint(checkpoint_dir, assignment_map): """See `tf.contrib.framework.init_from_checkpoint`.""" checkpoint_utils.init_from_checkpoint(checkpoint_dir, assignment_map)
[ "def", "init_from_checkpoint", "(", "checkpoint_dir", ",", "assignment_map", ")", ":", "checkpoint_utils", ".", "init_from_checkpoint", "(", "checkpoint_dir", ",", "assignment_map", ")" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/learn/python/learn/utils/checkpoints.py#L49-L51
rrwick/Unicycler
96ffea71e3a78d63ade19d6124946773e65cf129
unicycler/assembly_graph.py
python
AssemblyGraph.get_copy_number
(self, segment)
return len(self.copy_depths[segment.number])
Returns the segment's copy number (0 if copy number determination did not occur for this segment).
Returns the segment's copy number (0 if copy number determination did not occur for this segment).
[ "Returns", "the", "segment", "s", "copy", "number", "(", "0", "if", "copy", "number", "determination", "did", "not", "occur", "for", "this", "segment", ")", "." ]
def get_copy_number(self, segment): """ Returns the segment's copy number (0 if copy number determination did not occur for this segment). """ if segment.number not in self.copy_depths: return 0 return len(self.copy_depths[segment.number])
[ "def", "get_copy_number", "(", "self", ",", "segment", ")", ":", "if", "segment", ".", "number", "not", "in", "self", ".", "copy_depths", ":", "return", "0", "return", "len", "(", "self", ".", "copy_depths", "[", "segment", ".", "number", "]", ")" ]
https://github.com/rrwick/Unicycler/blob/96ffea71e3a78d63ade19d6124946773e65cf129/unicycler/assembly_graph.py#L1041-L1048
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/tarfile.py
python
_Stream.__read
(self, size)
return t[:size]
Return size bytes from stream. If internal buffer is empty, read another block from the stream.
Return size bytes from stream. If internal buffer is empty, read another block from the stream.
[ "Return", "size", "bytes", "from", "stream", ".", "If", "internal", "buffer", "is", "empty", "read", "another", "block", "from", "the", "stream", "." ]
def __read(self, size): """Return size bytes from stream. If internal buffer is empty, read another block from the stream. """ c = len(self.buf) t = [self.buf] while c < size: buf = self.fileobj.read(self.bufsize) if not buf: break t.append(buf) c += len(buf) t = b"".join(t) self.buf = t[size:] return t[:size]
[ "def", "__read", "(", "self", ",", "size", ")", ":", "c", "=", "len", "(", "self", ".", "buf", ")", "t", "=", "[", "self", ".", "buf", "]", "while", "c", "<", "size", ":", "buf", "=", "self", ".", "fileobj", ".", "read", "(", "self", ".", "bufsize", ")", "if", "not", "buf", ":", "break", "t", ".", "append", "(", "buf", ")", "c", "+=", "len", "(", "buf", ")", "t", "=", "b\"\"", ".", "join", "(", "t", ")", "self", ".", "buf", "=", "t", "[", "size", ":", "]", "return", "t", "[", ":", "size", "]" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tarfile.py#L563-L577
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/mailbox.py
python
_create_temporary
(path)
return _create_carefully('%s.%s.%s.%s' % (path, int(time.time()), socket.gethostname(), os.getpid()))
Create a temp file based on path and open for reading and writing.
Create a temp file based on path and open for reading and writing.
[ "Create", "a", "temp", "file", "based", "on", "path", "and", "open", "for", "reading", "and", "writing", "." ]
def _create_temporary(path): """Create a temp file based on path and open for reading and writing.""" return _create_carefully('%s.%s.%s.%s' % (path, int(time.time()), socket.gethostname(), os.getpid()))
[ "def", "_create_temporary", "(", "path", ")", ":", "return", "_create_carefully", "(", "'%s.%s.%s.%s'", "%", "(", "path", ",", "int", "(", "time", ".", "time", "(", ")", ")", ",", "socket", ".", "gethostname", "(", ")", ",", "os", ".", "getpid", "(", ")", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/mailbox.py#L2115-L2119
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/ops/control_flow_ops.py
python
GradLoopState.switch_map
(self)
return self._switch_map
The map that records all the Switch ops for the While loop.
The map that records all the Switch ops for the While loop.
[ "The", "map", "that", "records", "all", "the", "Switch", "ops", "for", "the", "While", "loop", "." ]
def switch_map(self): """The map that records all the Switch ops for the While loop.""" return self._switch_map
[ "def", "switch_map", "(", "self", ")", ":", "return", "self", ".", "_switch_map" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/ops/control_flow_ops.py#L619-L621
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site.py
python
execsitecustomize
()
Run custom site specific code, if available.
Run custom site specific code, if available.
[ "Run", "custom", "site", "specific", "code", "if", "available", "." ]
def execsitecustomize(): """Run custom site specific code, if available.""" try: import sitecustomize except ImportError: pass except Exception: if sys.flags.verbose: sys.excepthook(*sys.exc_info()) else: print >>sys.stderr, \ "'import sitecustomize' failed; use -v for traceback"
[ "def", "execsitecustomize", "(", ")", ":", "try", ":", "import", "sitecustomize", "except", "ImportError", ":", "pass", "except", "Exception", ":", "if", "sys", ".", "flags", ".", "verbose", ":", "sys", ".", "excepthook", "(", "*", "sys", ".", "exc_info", "(", ")", ")", "else", ":", "print", ">>", "sys", ".", "stderr", ",", "\"'import sitecustomize' failed; use -v for traceback\"" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site.py#L495-L506
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/distutils/fancy_getopt.py
python
FancyGetopt._grok_option_table
(self)
Populate the various data structures that keep tabs on the option table. Called by 'getopt()' before it can do anything worthwhile.
Populate the various data structures that keep tabs on the option table. Called by 'getopt()' before it can do anything worthwhile.
[ "Populate", "the", "various", "data", "structures", "that", "keep", "tabs", "on", "the", "option", "table", ".", "Called", "by", "getopt", "()", "before", "it", "can", "do", "anything", "worthwhile", "." ]
def _grok_option_table(self): """Populate the various data structures that keep tabs on the option table. Called by 'getopt()' before it can do anything worthwhile. """ self.long_opts = [] self.short_opts = [] self.short2long.clear() self.repeat = {} for option in self.option_table: if len(option) == 3: long, short, help = option repeat = 0 elif len(option) == 4: long, short, help, repeat = option else: # the option table is part of the code, so simply # assert that it is correct raise ValueError("invalid option tuple: %r" % (option,)) # Type- and value-check the option names if not isinstance(long, str) or len(long) < 2: raise DistutilsGetoptError(("invalid long option '%s': " "must be a string of length >= 2") % long) if (not ((short is None) or (isinstance(short, str) and len(short) == 1))): raise DistutilsGetoptError("invalid short option '%s': " "must a single character or None" % short) self.repeat[long] = repeat self.long_opts.append(long) if long[-1] == '=': # option takes an argument? if short: short = short + ':' long = long[0:-1] self.takes_arg[long] = 1 else: # Is option is a "negative alias" for some other option (eg. # "quiet" == "!verbose")? alias_to = self.negative_alias.get(long) if alias_to is not None: if self.takes_arg[alias_to]: raise DistutilsGetoptError( "invalid negative alias '%s': " "aliased option '%s' takes a value" % (long, alias_to)) self.long_opts[-1] = long # XXX redundant?! self.takes_arg[long] = 0 # If this is an alias option, make sure its "takes arg" flag is # the same as the option it's aliased to. alias_to = self.alias.get(long) if alias_to is not None: if self.takes_arg[long] != self.takes_arg[alias_to]: raise DistutilsGetoptError( "invalid alias '%s': inconsistent with " "aliased option '%s' (one of them takes a value, " "the other doesn't" % (long, alias_to)) # Now enforce some bondage on the long option name, so we can # later translate it to an attribute name on some object. Have # to do this a bit late to make sure we've removed any trailing # '='. if not longopt_re.match(long): raise DistutilsGetoptError( "invalid long option name '%s' " "(must be letters, numbers, hyphens only" % long) self.attr_name[long] = self.get_attr_name(long) if short: self.short_opts.append(short) self.short2long[short[0]] = long
[ "def", "_grok_option_table", "(", "self", ")", ":", "self", ".", "long_opts", "=", "[", "]", "self", ".", "short_opts", "=", "[", "]", "self", ".", "short2long", ".", "clear", "(", ")", "self", ".", "repeat", "=", "{", "}", "for", "option", "in", "self", ".", "option_table", ":", "if", "len", "(", "option", ")", "==", "3", ":", "long", ",", "short", ",", "help", "=", "option", "repeat", "=", "0", "elif", "len", "(", "option", ")", "==", "4", ":", "long", ",", "short", ",", "help", ",", "repeat", "=", "option", "else", ":", "# the option table is part of the code, so simply", "# assert that it is correct", "raise", "ValueError", "(", "\"invalid option tuple: %r\"", "%", "(", "option", ",", ")", ")", "# Type- and value-check the option names", "if", "not", "isinstance", "(", "long", ",", "str", ")", "or", "len", "(", "long", ")", "<", "2", ":", "raise", "DistutilsGetoptError", "(", "(", "\"invalid long option '%s': \"", "\"must be a string of length >= 2\"", ")", "%", "long", ")", "if", "(", "not", "(", "(", "short", "is", "None", ")", "or", "(", "isinstance", "(", "short", ",", "str", ")", "and", "len", "(", "short", ")", "==", "1", ")", ")", ")", ":", "raise", "DistutilsGetoptError", "(", "\"invalid short option '%s': \"", "\"must a single character or None\"", "%", "short", ")", "self", ".", "repeat", "[", "long", "]", "=", "repeat", "self", ".", "long_opts", ".", "append", "(", "long", ")", "if", "long", "[", "-", "1", "]", "==", "'='", ":", "# option takes an argument?", "if", "short", ":", "short", "=", "short", "+", "':'", "long", "=", "long", "[", "0", ":", "-", "1", "]", "self", ".", "takes_arg", "[", "long", "]", "=", "1", "else", ":", "# Is option is a \"negative alias\" for some other option (eg.", "# \"quiet\" == \"!verbose\")?", "alias_to", "=", "self", ".", "negative_alias", ".", "get", "(", "long", ")", "if", "alias_to", "is", "not", "None", ":", "if", "self", ".", "takes_arg", "[", "alias_to", "]", ":", "raise", "DistutilsGetoptError", "(", "\"invalid negative alias '%s': \"", "\"aliased option '%s' takes a value\"", "%", "(", "long", ",", "alias_to", ")", ")", "self", ".", "long_opts", "[", "-", "1", "]", "=", "long", "# XXX redundant?!", "self", ".", "takes_arg", "[", "long", "]", "=", "0", "# If this is an alias option, make sure its \"takes arg\" flag is", "# the same as the option it's aliased to.", "alias_to", "=", "self", ".", "alias", ".", "get", "(", "long", ")", "if", "alias_to", "is", "not", "None", ":", "if", "self", ".", "takes_arg", "[", "long", "]", "!=", "self", ".", "takes_arg", "[", "alias_to", "]", ":", "raise", "DistutilsGetoptError", "(", "\"invalid alias '%s': inconsistent with \"", "\"aliased option '%s' (one of them takes a value, \"", "\"the other doesn't\"", "%", "(", "long", ",", "alias_to", ")", ")", "# Now enforce some bondage on the long option name, so we can", "# later translate it to an attribute name on some object. Have", "# to do this a bit late to make sure we've removed any trailing", "# '='.", "if", "not", "longopt_re", ".", "match", "(", "long", ")", ":", "raise", "DistutilsGetoptError", "(", "\"invalid long option name '%s' \"", "\"(must be letters, numbers, hyphens only\"", "%", "long", ")", "self", ".", "attr_name", "[", "long", "]", "=", "self", ".", "get_attr_name", "(", "long", ")", "if", "short", ":", "self", ".", "short_opts", ".", "append", "(", "short", ")", "self", ".", "short2long", "[", "short", "[", "0", "]", "]", "=", "long" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/distutils/fancy_getopt.py#L133-L208
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/polynomial/laguerre.py
python
laggrid3d
(x, y, z, c)
return c
Evaluate a 3-D Laguerre series on the Cartesian product of x, y, and z. This function returns the values: .. math:: p(a,b,c) = \\sum_{i,j,k} c_{i,j,k} * L_i(a) * L_j(b) * L_k(c) where the points `(a, b, c)` consist of all triples formed by taking `a` from `x`, `b` from `y`, and `c` from `z`. The resulting points form a grid with `x` in the first dimension, `y` in the second, and `z` in the third. The parameters `x`, `y`, and `z` are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars. In either case, either `x`, `y`, and `z` or their elements must support multiplication and addition both with themselves and with the elements of `c`. If `c` has fewer than three dimensions, ones are implicitly appended to its shape to make it 3-D. The shape of the result will be c.shape[3:] + x.shape + y.shape + z.shape. Parameters ---------- x, y, z : array_like, compatible objects The three dimensional series is evaluated at the points in the Cartesian product of `x`, `y`, and `z`. If `x`,`y`, or `z` is a list or tuple, it is first converted to an ndarray, otherwise it is left unchanged and, if it isn't an ndarray, it is treated as a scalar. c : array_like Array of coefficients ordered so that the coefficients for terms of degree i,j are contained in ``c[i,j]``. If `c` has dimension greater than two the remaining indices enumerate multiple sets of coefficients. Returns ------- values : ndarray, compatible object The values of the two dimensional polynomial at points in the Cartesian product of `x` and `y`. See Also -------- lagval, lagval2d, laggrid2d, lagval3d Notes ----- .. versionadded::1.7.0
Evaluate a 3-D Laguerre series on the Cartesian product of x, y, and z.
[ "Evaluate", "a", "3", "-", "D", "Laguerre", "series", "on", "the", "Cartesian", "product", "of", "x", "y", "and", "z", "." ]
def laggrid3d(x, y, z, c): """ Evaluate a 3-D Laguerre series on the Cartesian product of x, y, and z. This function returns the values: .. math:: p(a,b,c) = \\sum_{i,j,k} c_{i,j,k} * L_i(a) * L_j(b) * L_k(c) where the points `(a, b, c)` consist of all triples formed by taking `a` from `x`, `b` from `y`, and `c` from `z`. The resulting points form a grid with `x` in the first dimension, `y` in the second, and `z` in the third. The parameters `x`, `y`, and `z` are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars. In either case, either `x`, `y`, and `z` or their elements must support multiplication and addition both with themselves and with the elements of `c`. If `c` has fewer than three dimensions, ones are implicitly appended to its shape to make it 3-D. The shape of the result will be c.shape[3:] + x.shape + y.shape + z.shape. Parameters ---------- x, y, z : array_like, compatible objects The three dimensional series is evaluated at the points in the Cartesian product of `x`, `y`, and `z`. If `x`,`y`, or `z` is a list or tuple, it is first converted to an ndarray, otherwise it is left unchanged and, if it isn't an ndarray, it is treated as a scalar. c : array_like Array of coefficients ordered so that the coefficients for terms of degree i,j are contained in ``c[i,j]``. If `c` has dimension greater than two the remaining indices enumerate multiple sets of coefficients. Returns ------- values : ndarray, compatible object The values of the two dimensional polynomial at points in the Cartesian product of `x` and `y`. See Also -------- lagval, lagval2d, laggrid2d, lagval3d Notes ----- .. versionadded::1.7.0 """ c = lagval(x, c) c = lagval(y, c) c = lagval(z, c) return c
[ "def", "laggrid3d", "(", "x", ",", "y", ",", "z", ",", "c", ")", ":", "c", "=", "lagval", "(", "x", ",", "c", ")", "c", "=", "lagval", "(", "y", ",", "c", ")", "c", "=", "lagval", "(", "z", ",", "c", ")", "return", "c" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/polynomial/laguerre.py#L1117-L1173
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/mod_pywebsocket/mux.py
python
_LogicalStream._send_pong
(self, body)
Overrides Stream._send_pong
Overrides Stream._send_pong
[ "Overrides", "Stream", ".", "_send_pong" ]
def _send_pong(self, body): """Overrides Stream._send_pong""" self._logger.debug('Sending pong on logical channel %d: %r' % (self._request.channel_id, body)) self._write_inner_frame(common.OPCODE_PONG, body, end=True)
[ "def", "_send_pong", "(", "self", ",", "body", ")", ":", "self", ".", "_logger", ".", "debug", "(", "'Sending pong on logical channel %d: %r'", "%", "(", "self", ".", "_request", ".", "channel_id", ",", "body", ")", ")", "self", ".", "_write_inner_frame", "(", "common", ".", "OPCODE_PONG", ",", "body", ",", "end", "=", "True", ")" ]
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/mod_pywebsocket/mux.py#L1055-L1060
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/mapreduce/mapreduce/datastore_range_iterators.py
python
RangeIterator.from_json
(cls, json)
Reverse of to_json.
Reverse of to_json.
[ "Reverse", "of", "to_json", "." ]
def from_json(cls, json): """Reverse of to_json.""" raise NotImplementedError()
[ "def", "from_json", "(", "cls", ",", "json", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/mapreduce/mapreduce/datastore_range_iterators.py#L127-L129
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/LargeScaleStructures/geometry_writer.py
python
MantidGeom.addDetectorIds
(self, idname, idlist)
Add the detector IDs. A list is provided that must be divisible by 3. The list should be specified as [start1, end1, step1, start2, end2, step2, ...]. If no step is required, use None.
Add the detector IDs. A list is provided that must be divisible by 3. The list should be specified as [start1, end1, step1, start2, end2, step2, ...]. If no step is required, use None.
[ "Add", "the", "detector", "IDs", ".", "A", "list", "is", "provided", "that", "must", "be", "divisible", "by", "3", ".", "The", "list", "should", "be", "specified", "as", "[", "start1", "end1", "step1", "start2", "end2", "step2", "...", "]", ".", "If", "no", "step", "is", "required", "use", "None", "." ]
def addDetectorIds(self, idname, idlist): """ Add the detector IDs. A list is provided that must be divisible by 3. The list should be specified as [start1, end1, step1, start2, end2, step2, ...]. If no step is required, use None. """ if len(idlist) % 3 != 0: raise IndexError("Please specify list as [start1, end1, step1, " + "start2, end2, step2, ...]. If no step is" + "required, use None.") num_ids = len(idlist) / 3 id_element = self._append_child("idlist", self._root, idname=idname) for i in range(num_ids): if idlist[(i * 3) + 2] is None: self._append_child("id", id_element, start=str(idlist[(i * 3)]), end=str(idlist[(i * 3) + 1])) else: self._append_child("id", id_element, start=str(idlist[(i * 3)]), step=str(idlist[(i * 3) + 2]), end=str(idlist[(i * 3) + 1]))
[ "def", "addDetectorIds", "(", "self", ",", "idname", ",", "idlist", ")", ":", "if", "len", "(", "idlist", ")", "%", "3", "!=", "0", ":", "raise", "IndexError", "(", "\"Please specify list as [start1, end1, step1, \"", "+", "\"start2, end2, step2, ...]. If no step is\"", "+", "\"required, use None.\"", ")", "num_ids", "=", "len", "(", "idlist", ")", "/", "3", "id_element", "=", "self", ".", "_append_child", "(", "\"idlist\"", ",", "self", ".", "_root", ",", "idname", "=", "idname", ")", "for", "i", "in", "range", "(", "num_ids", ")", ":", "if", "idlist", "[", "(", "i", "*", "3", ")", "+", "2", "]", "is", "None", ":", "self", ".", "_append_child", "(", "\"id\"", ",", "id_element", ",", "start", "=", "str", "(", "idlist", "[", "(", "i", "*", "3", ")", "]", ")", ",", "end", "=", "str", "(", "idlist", "[", "(", "i", "*", "3", ")", "+", "1", "]", ")", ")", "else", ":", "self", ".", "_append_child", "(", "\"id\"", ",", "id_element", ",", "start", "=", "str", "(", "idlist", "[", "(", "i", "*", "3", ")", "]", ")", ",", "step", "=", "str", "(", "idlist", "[", "(", "i", "*", "3", ")", "+", "2", "]", ")", ",", "end", "=", "str", "(", "idlist", "[", "(", "i", "*", "3", ")", "+", "1", "]", ")", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/LargeScaleStructures/geometry_writer.py#L391-L410
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
deps/src/libxml2-2.9.1/python/libxml2class.py
python
uCSIsThaana
(code)
return ret
Check whether the character is part of Thaana UCS Block
Check whether the character is part of Thaana UCS Block
[ "Check", "whether", "the", "character", "is", "part", "of", "Thaana", "UCS", "Block" ]
def uCSIsThaana(code): """Check whether the character is part of Thaana UCS Block """ ret = libxml2mod.xmlUCSIsThaana(code) return ret
[ "def", "uCSIsThaana", "(", "code", ")", ":", "ret", "=", "libxml2mod", ".", "xmlUCSIsThaana", "(", "code", ")", "return", "ret" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2class.py#L2155-L2158
sslab-gatech/qsym
78702ba8928519ffb9beb7859ec2f7ddce2b2fe4
third_party/pin-2.14-71313-gcc.4.4.7-linux/source/tools/Utils/and-launch.py
python
RunCommand
(cmd)
return out
Execute a shell command and wait for it to complete. If the command fails, an error is printed and E{ReturnCode} is set to non-zero. @param cmd: The shell command to run. @type cmd: string. @return: Shell command output. @rtype string.
Execute a shell command and wait for it to complete. If the command fails, an error is printed and E{ReturnCode} is set to non-zero.
[ "Execute", "a", "shell", "command", "and", "wait", "for", "it", "to", "complete", ".", "If", "the", "command", "fails", "an", "error", "is", "printed", "and", "E", "{", "ReturnCode", "}", "is", "set", "to", "non", "-", "zero", "." ]
def RunCommand(cmd): """ Execute a shell command and wait for it to complete. If the command fails, an error is printed and E{ReturnCode} is set to non-zero. @param cmd: The shell command to run. @type cmd: string. @return: Shell command output. @rtype string. """ global ReturnCode if ReturnCode != 0: logging.error(">>> command was not executed due to previous failures") logging.error(">>> " + cmd) return "" logging.info(">>> " + cmd) # Flush ensures that any I/O printed by this script appears before any I/O from the command # we're about to execute. sys.stdout.flush() try: sub = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, err = sub.communicate() ret = sub.wait() except OSError, e: logging.error("Execution failed:" + str(e)) logging.error("\tcommand: " + cmd) ReturnCode = 1 if ret != 0: logging.error("Execution failed with return code " + str(ret)) logging.error("\tcommand: " + cmd) ReturnCode = ret return out
[ "def", "RunCommand", "(", "cmd", ")", ":", "global", "ReturnCode", "if", "ReturnCode", "!=", "0", ":", "logging", ".", "error", "(", "\">>> command was not executed due to previous failures\"", ")", "logging", ".", "error", "(", "\">>> \"", "+", "cmd", ")", "return", "\"\"", "logging", ".", "info", "(", "\">>> \"", "+", "cmd", ")", "# Flush ensures that any I/O printed by this script appears before any I/O from the command", "# we're about to execute.", "sys", ".", "stdout", ".", "flush", "(", ")", "try", ":", "sub", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "shell", "=", "True", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")", "out", ",", "err", "=", "sub", ".", "communicate", "(", ")", "ret", "=", "sub", ".", "wait", "(", ")", "except", "OSError", ",", "e", ":", "logging", ".", "error", "(", "\"Execution failed:\"", "+", "str", "(", "e", ")", ")", "logging", ".", "error", "(", "\"\\tcommand: \"", "+", "cmd", ")", "ReturnCode", "=", "1", "if", "ret", "!=", "0", ":", "logging", ".", "error", "(", "\"Execution failed with return code \"", "+", "str", "(", "ret", ")", ")", "logging", ".", "error", "(", "\"\\tcommand: \"", "+", "cmd", ")", "ReturnCode", "=", "ret", "return", "out" ]
https://github.com/sslab-gatech/qsym/blob/78702ba8928519ffb9beb7859ec2f7ddce2b2fe4/third_party/pin-2.14-71313-gcc.4.4.7-linux/source/tools/Utils/and-launch.py#L66-L104
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/tempfile.py
python
_mkstemp_inner
(dir, pre, suf, flags)
Code common to mkstemp, TemporaryFile, and NamedTemporaryFile.
Code common to mkstemp, TemporaryFile, and NamedTemporaryFile.
[ "Code", "common", "to", "mkstemp", "TemporaryFile", "and", "NamedTemporaryFile", "." ]
def _mkstemp_inner(dir, pre, suf, flags): """Code common to mkstemp, TemporaryFile, and NamedTemporaryFile.""" names = _get_candidate_names() for seq in xrange(TMP_MAX): name = names.next() file = _os.path.join(dir, pre + name + suf) try: fd = _os.open(file, flags, 0600) _set_cloexec(fd) return (fd, _os.path.abspath(file)) except OSError, e: if e.errno == _errno.EEXIST: continue # try again raise raise IOError, (_errno.EEXIST, "No usable temporary file name found")
[ "def", "_mkstemp_inner", "(", "dir", ",", "pre", ",", "suf", ",", "flags", ")", ":", "names", "=", "_get_candidate_names", "(", ")", "for", "seq", "in", "xrange", "(", "TMP_MAX", ")", ":", "name", "=", "names", ".", "next", "(", ")", "file", "=", "_os", ".", "path", ".", "join", "(", "dir", ",", "pre", "+", "name", "+", "suf", ")", "try", ":", "fd", "=", "_os", ".", "open", "(", "file", ",", "flags", ",", "0600", ")", "_set_cloexec", "(", "fd", ")", "return", "(", "fd", ",", "_os", ".", "path", ".", "abspath", "(", "file", ")", ")", "except", "OSError", ",", "e", ":", "if", "e", ".", "errno", "==", "_errno", ".", "EEXIST", ":", "continue", "# try again", "raise", "raise", "IOError", ",", "(", "_errno", ".", "EEXIST", ",", "\"No usable temporary file name found\"", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/tempfile.py#L230-L247
GoSSIP-SJTU/Armariris
ad5d868482956b2194a77b39c8d543c7c2318200
tools/clang/bindings/python/clang/cindex.py
python
Type.kind
(self)
return TypeKind.from_id(self._kind_id)
Return the kind of this type.
Return the kind of this type.
[ "Return", "the", "kind", "of", "this", "type", "." ]
def kind(self): """Return the kind of this type.""" return TypeKind.from_id(self._kind_id)
[ "def", "kind", "(", "self", ")", ":", "return", "TypeKind", ".", "from_id", "(", "self", ".", "_kind_id", ")" ]
https://github.com/GoSSIP-SJTU/Armariris/blob/ad5d868482956b2194a77b39c8d543c7c2318200/tools/clang/bindings/python/clang/cindex.py#L1780-L1782
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/propgrid.py
python
PGTextCtrlEditor_OnTextCtrlEvent
(*args, **kwargs)
return _propgrid.PGTextCtrlEditor_OnTextCtrlEvent(*args, **kwargs)
PGTextCtrlEditor_OnTextCtrlEvent(PropertyGrid propgrid, PGProperty property, Window ctrl, Event event) -> bool
PGTextCtrlEditor_OnTextCtrlEvent(PropertyGrid propgrid, PGProperty property, Window ctrl, Event event) -> bool
[ "PGTextCtrlEditor_OnTextCtrlEvent", "(", "PropertyGrid", "propgrid", "PGProperty", "property", "Window", "ctrl", "Event", "event", ")", "-", ">", "bool" ]
def PGTextCtrlEditor_OnTextCtrlEvent(*args, **kwargs): """ PGTextCtrlEditor_OnTextCtrlEvent(PropertyGrid propgrid, PGProperty property, Window ctrl, Event event) -> bool """ return _propgrid.PGTextCtrlEditor_OnTextCtrlEvent(*args, **kwargs)
[ "def", "PGTextCtrlEditor_OnTextCtrlEvent", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PGTextCtrlEditor_OnTextCtrlEvent", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/propgrid.py#L2745-L2750
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/metrics/cluster/_supervised.py
python
homogeneity_completeness_v_measure
(labels_true, labels_pred, beta=1.0)
return homogeneity, completeness, v_measure_score
Compute the homogeneity and completeness and V-Measure scores at once. Those metrics are based on normalized conditional entropy measures of the clustering labeling to evaluate given the knowledge of a Ground Truth class labels of the same samples. A clustering result satisfies homogeneity if all of its clusters contain only data points which are members of a single class. A clustering result satisfies completeness if all the data points that are members of a given class are elements of the same cluster. Both scores have positive values between 0.0 and 1.0, larger values being desirable. Those 3 metrics are independent of the absolute values of the labels: a permutation of the class or cluster label values won't change the score values in any way. V-Measure is furthermore symmetric: swapping ``labels_true`` and ``label_pred`` will give the same score. This does not hold for homogeneity and completeness. V-Measure is identical to :func:`normalized_mutual_info_score` with the arithmetic averaging method. Read more in the :ref:`User Guide <homogeneity_completeness>`. Parameters ---------- labels_true : int array, shape = [n_samples] ground truth class labels to be used as a reference labels_pred : array-like of shape (n_samples,) cluster labels to evaluate beta : float Ratio of weight attributed to ``homogeneity`` vs ``completeness``. If ``beta`` is greater than 1, ``completeness`` is weighted more strongly in the calculation. If ``beta`` is less than 1, ``homogeneity`` is weighted more strongly. Returns ------- homogeneity : float score between 0.0 and 1.0. 1.0 stands for perfectly homogeneous labeling completeness : float score between 0.0 and 1.0. 1.0 stands for perfectly complete labeling v_measure : float harmonic mean of the first two See also -------- homogeneity_score completeness_score v_measure_score
Compute the homogeneity and completeness and V-Measure scores at once.
[ "Compute", "the", "homogeneity", "and", "completeness", "and", "V", "-", "Measure", "scores", "at", "once", "." ]
def homogeneity_completeness_v_measure(labels_true, labels_pred, beta=1.0): """Compute the homogeneity and completeness and V-Measure scores at once. Those metrics are based on normalized conditional entropy measures of the clustering labeling to evaluate given the knowledge of a Ground Truth class labels of the same samples. A clustering result satisfies homogeneity if all of its clusters contain only data points which are members of a single class. A clustering result satisfies completeness if all the data points that are members of a given class are elements of the same cluster. Both scores have positive values between 0.0 and 1.0, larger values being desirable. Those 3 metrics are independent of the absolute values of the labels: a permutation of the class or cluster label values won't change the score values in any way. V-Measure is furthermore symmetric: swapping ``labels_true`` and ``label_pred`` will give the same score. This does not hold for homogeneity and completeness. V-Measure is identical to :func:`normalized_mutual_info_score` with the arithmetic averaging method. Read more in the :ref:`User Guide <homogeneity_completeness>`. Parameters ---------- labels_true : int array, shape = [n_samples] ground truth class labels to be used as a reference labels_pred : array-like of shape (n_samples,) cluster labels to evaluate beta : float Ratio of weight attributed to ``homogeneity`` vs ``completeness``. If ``beta`` is greater than 1, ``completeness`` is weighted more strongly in the calculation. If ``beta`` is less than 1, ``homogeneity`` is weighted more strongly. Returns ------- homogeneity : float score between 0.0 and 1.0. 1.0 stands for perfectly homogeneous labeling completeness : float score between 0.0 and 1.0. 1.0 stands for perfectly complete labeling v_measure : float harmonic mean of the first two See also -------- homogeneity_score completeness_score v_measure_score """ labels_true, labels_pred = check_clusterings(labels_true, labels_pred) if len(labels_true) == 0: return 1.0, 1.0, 1.0 entropy_C = entropy(labels_true) entropy_K = entropy(labels_pred) contingency = contingency_matrix(labels_true, labels_pred, sparse=True) MI = mutual_info_score(None, None, contingency=contingency) homogeneity = MI / (entropy_C) if entropy_C else 1.0 completeness = MI / (entropy_K) if entropy_K else 1.0 if homogeneity + completeness == 0.0: v_measure_score = 0.0 else: v_measure_score = ((1 + beta) * homogeneity * completeness / (beta * homogeneity + completeness)) return homogeneity, completeness, v_measure_score
[ "def", "homogeneity_completeness_v_measure", "(", "labels_true", ",", "labels_pred", ",", "beta", "=", "1.0", ")", ":", "labels_true", ",", "labels_pred", "=", "check_clusterings", "(", "labels_true", ",", "labels_pred", ")", "if", "len", "(", "labels_true", ")", "==", "0", ":", "return", "1.0", ",", "1.0", ",", "1.0", "entropy_C", "=", "entropy", "(", "labels_true", ")", "entropy_K", "=", "entropy", "(", "labels_pred", ")", "contingency", "=", "contingency_matrix", "(", "labels_true", ",", "labels_pred", ",", "sparse", "=", "True", ")", "MI", "=", "mutual_info_score", "(", "None", ",", "None", ",", "contingency", "=", "contingency", ")", "homogeneity", "=", "MI", "/", "(", "entropy_C", ")", "if", "entropy_C", "else", "1.0", "completeness", "=", "MI", "/", "(", "entropy_K", ")", "if", "entropy_K", "else", "1.0", "if", "homogeneity", "+", "completeness", "==", "0.0", ":", "v_measure_score", "=", "0.0", "else", ":", "v_measure_score", "=", "(", "(", "1", "+", "beta", ")", "*", "homogeneity", "*", "completeness", "/", "(", "beta", "*", "homogeneity", "+", "completeness", ")", ")", "return", "homogeneity", ",", "completeness", ",", "v_measure_score" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/metrics/cluster/_supervised.py#L243-L322
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/supertooltip.py
python
SuperToolTip.GetHeader
(self)
return self._header
Returns the header text.
Returns the header text.
[ "Returns", "the", "header", "text", "." ]
def GetHeader(self): """ Returns the header text. """ return self._header
[ "def", "GetHeader", "(", "self", ")", ":", "return", "self", ".", "_header" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/supertooltip.py#L1061-L1064
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/examples/speech_commands/models.py
python
create_model
(fingerprint_input, model_settings, model_architecture, is_training, runtime_settings=None)
Builds a model of the requested architecture compatible with the settings. There are many possible ways of deriving predictions from a spectrogram input, so this function provides an abstract interface for creating different kinds of models in a black-box way. You need to pass in a TensorFlow node as the 'fingerprint' input, and this should output a batch of 1D features that describe the audio. Typically this will be derived from a spectrogram that's been run through an MFCC, but in theory it can be any feature vector of the size specified in model_settings['fingerprint_size']. The function will build the graph it needs in the current TensorFlow graph, and return the tensorflow output that will contain the 'logits' input to the softmax prediction process. If training flag is on, it will also return a placeholder node that can be used to control the dropout amount. See the implementations below for the possible model architectures that can be requested. Args: fingerprint_input: TensorFlow node that will output audio feature vectors. model_settings: Dictionary of information about the model. model_architecture: String specifying which kind of model to create. is_training: Whether the model is going to be used for training. runtime_settings: Dictionary of information about the runtime. Returns: TensorFlow node outputting logits results, and optionally a dropout placeholder. Raises: Exception: If the architecture type isn't recognized.
Builds a model of the requested architecture compatible with the settings.
[ "Builds", "a", "model", "of", "the", "requested", "architecture", "compatible", "with", "the", "settings", "." ]
def create_model(fingerprint_input, model_settings, model_architecture, is_training, runtime_settings=None): """Builds a model of the requested architecture compatible with the settings. There are many possible ways of deriving predictions from a spectrogram input, so this function provides an abstract interface for creating different kinds of models in a black-box way. You need to pass in a TensorFlow node as the 'fingerprint' input, and this should output a batch of 1D features that describe the audio. Typically this will be derived from a spectrogram that's been run through an MFCC, but in theory it can be any feature vector of the size specified in model_settings['fingerprint_size']. The function will build the graph it needs in the current TensorFlow graph, and return the tensorflow output that will contain the 'logits' input to the softmax prediction process. If training flag is on, it will also return a placeholder node that can be used to control the dropout amount. See the implementations below for the possible model architectures that can be requested. Args: fingerprint_input: TensorFlow node that will output audio feature vectors. model_settings: Dictionary of information about the model. model_architecture: String specifying which kind of model to create. is_training: Whether the model is going to be used for training. runtime_settings: Dictionary of information about the runtime. Returns: TensorFlow node outputting logits results, and optionally a dropout placeholder. Raises: Exception: If the architecture type isn't recognized. """ if model_architecture == 'single_fc': return create_single_fc_model(fingerprint_input, model_settings, is_training) elif model_architecture == 'conv': return create_conv_model(fingerprint_input, model_settings, is_training) elif model_architecture == 'low_latency_conv': return create_low_latency_conv_model(fingerprint_input, model_settings, is_training) elif model_architecture == 'low_latency_svdf': return create_low_latency_svdf_model(fingerprint_input, model_settings, is_training, runtime_settings) else: raise Exception('model_architecture argument "' + model_architecture + '" not recognized, should be one of "single_fc", "conv",' + ' "low_latency_conv, or "low_latency_svdf"')
[ "def", "create_model", "(", "fingerprint_input", ",", "model_settings", ",", "model_architecture", ",", "is_training", ",", "runtime_settings", "=", "None", ")", ":", "if", "model_architecture", "==", "'single_fc'", ":", "return", "create_single_fc_model", "(", "fingerprint_input", ",", "model_settings", ",", "is_training", ")", "elif", "model_architecture", "==", "'conv'", ":", "return", "create_conv_model", "(", "fingerprint_input", ",", "model_settings", ",", "is_training", ")", "elif", "model_architecture", "==", "'low_latency_conv'", ":", "return", "create_low_latency_conv_model", "(", "fingerprint_input", ",", "model_settings", ",", "is_training", ")", "elif", "model_architecture", "==", "'low_latency_svdf'", ":", "return", "create_low_latency_svdf_model", "(", "fingerprint_input", ",", "model_settings", ",", "is_training", ",", "runtime_settings", ")", "else", ":", "raise", "Exception", "(", "'model_architecture argument \"'", "+", "model_architecture", "+", "'\" not recognized, should be one of \"single_fc\", \"conv\",'", "+", "' \"low_latency_conv, or \"low_latency_svdf\"'", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/examples/speech_commands/models.py#L64-L112
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/indexes/base.py
python
_trim_front
(strings)
return trimmed
Trims zeros and decimal points.
Trims zeros and decimal points.
[ "Trims", "zeros", "and", "decimal", "points", "." ]
def _trim_front(strings): """ Trims zeros and decimal points. """ trimmed = strings while len(strings) > 0 and all(x[0] == " " for x in trimmed): trimmed = [x[1:] for x in trimmed] return trimmed
[ "def", "_trim_front", "(", "strings", ")", ":", "trimmed", "=", "strings", "while", "len", "(", "strings", ")", ">", "0", "and", "all", "(", "x", "[", "0", "]", "==", "\" \"", "for", "x", "in", "trimmed", ")", ":", "trimmed", "=", "[", "x", "[", "1", ":", "]", "for", "x", "in", "trimmed", "]", "return", "trimmed" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/indexes/base.py#L5372-L5379
intel/caffe
3f494b442ee3f9d17a07b09ecbd5fa2bbda00836
scripts/cpp_lint.py
python
PrintUsage
(message)
Prints a brief usage string and exits, optionally with an error message. Args: message: The optional error message.
Prints a brief usage string and exits, optionally with an error message.
[ "Prints", "a", "brief", "usage", "string", "and", "exits", "optionally", "with", "an", "error", "message", "." ]
def PrintUsage(message): """Prints a brief usage string and exits, optionally with an error message. Args: message: The optional error message. """ sys.stderr.write(_USAGE) if message: sys.exit('\nFATAL ERROR: ' + message) else: sys.exit(1)
[ "def", "PrintUsage", "(", "message", ")", ":", "sys", ".", "stderr", ".", "write", "(", "_USAGE", ")", "if", "message", ":", "sys", ".", "exit", "(", "'\\nFATAL ERROR: '", "+", "message", ")", "else", ":", "sys", ".", "exit", "(", "1", ")" ]
https://github.com/intel/caffe/blob/3f494b442ee3f9d17a07b09ecbd5fa2bbda00836/scripts/cpp_lint.py#L4761-L4771
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/aui.py
python
AuiManager.SavePerspective
(*args, **kwargs)
return _aui.AuiManager_SavePerspective(*args, **kwargs)
SavePerspective(self) -> String
SavePerspective(self) -> String
[ "SavePerspective", "(", "self", ")", "-", ">", "String" ]
def SavePerspective(*args, **kwargs): """SavePerspective(self) -> String""" return _aui.AuiManager_SavePerspective(*args, **kwargs)
[ "def", "SavePerspective", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_aui", ".", "AuiManager_SavePerspective", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/aui.py#L671-L673
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/scipy/io/matlab/mio5.py
python
VarWriter5.write
(self, arr)
Write `arr` to stream at top and sub levels Parameters ---------- arr : array_like array-like object to create writer for
Write `arr` to stream at top and sub levels
[ "Write", "arr", "to", "stream", "at", "top", "and", "sub", "levels" ]
def write(self, arr): ''' Write `arr` to stream at top and sub levels Parameters ---------- arr : array_like array-like object to create writer for ''' # store position, so we can update the matrix tag mat_tag_pos = self.file_stream.tell() # First check if these are sparse if scipy.sparse.issparse(arr): self.write_sparse(arr) self.update_matrix_tag(mat_tag_pos) return # Try to convert things that aren't arrays narr = to_writeable(arr) if narr is None: raise TypeError('Could not convert %s (type %s) to array' % (arr, type(arr))) if isinstance(narr, MatlabObject): self.write_object(narr) elif isinstance(narr, MatlabFunction): raise MatWriteError('Cannot write matlab functions') elif narr is EmptyStructMarker: # empty struct array self.write_empty_struct() elif narr.dtype.fields: # struct array self.write_struct(narr) elif narr.dtype.hasobject: # cell array self.write_cells(narr) elif narr.dtype.kind in ('U', 'S'): if self.unicode_strings: codec = 'UTF8' else: codec = 'ascii' self.write_char(narr, codec) else: self.write_numeric(narr) self.update_matrix_tag(mat_tag_pos)
[ "def", "write", "(", "self", ",", "arr", ")", ":", "# store position, so we can update the matrix tag", "mat_tag_pos", "=", "self", ".", "file_stream", ".", "tell", "(", ")", "# First check if these are sparse", "if", "scipy", ".", "sparse", ".", "issparse", "(", "arr", ")", ":", "self", ".", "write_sparse", "(", "arr", ")", "self", ".", "update_matrix_tag", "(", "mat_tag_pos", ")", "return", "# Try to convert things that aren't arrays", "narr", "=", "to_writeable", "(", "arr", ")", "if", "narr", "is", "None", ":", "raise", "TypeError", "(", "'Could not convert %s (type %s) to array'", "%", "(", "arr", ",", "type", "(", "arr", ")", ")", ")", "if", "isinstance", "(", "narr", ",", "MatlabObject", ")", ":", "self", ".", "write_object", "(", "narr", ")", "elif", "isinstance", "(", "narr", ",", "MatlabFunction", ")", ":", "raise", "MatWriteError", "(", "'Cannot write matlab functions'", ")", "elif", "narr", "is", "EmptyStructMarker", ":", "# empty struct array", "self", ".", "write_empty_struct", "(", ")", "elif", "narr", ".", "dtype", ".", "fields", ":", "# struct array", "self", ".", "write_struct", "(", "narr", ")", "elif", "narr", ".", "dtype", ".", "hasobject", ":", "# cell array", "self", ".", "write_cells", "(", "narr", ")", "elif", "narr", ".", "dtype", ".", "kind", "in", "(", "'U'", ",", "'S'", ")", ":", "if", "self", ".", "unicode_strings", ":", "codec", "=", "'UTF8'", "else", ":", "codec", "=", "'ascii'", "self", ".", "write_char", "(", "narr", ",", "codec", ")", "else", ":", "self", ".", "write_numeric", "(", "narr", ")", "self", ".", "update_matrix_tag", "(", "mat_tag_pos", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/io/matlab/mio5.py#L589-L627
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/common/dtype.py
python
dtype_to_pytype
(type_)
return { bool_: bool, int_: int, int8: int, int16: int, int32: int, int64: int, uint8: int, uint16: int, uint32: int, uint64: int, float_: float, float16: float, float32: float, float64: float, list_: list, tuple_: tuple, string: str, complex64: complex, complex128: complex, type_none: type(None) }[type_]
Convert MindSpore dtype to python data type. Args: type_ (:class:`mindspore.dtype`): MindSpore's dtype. Returns: Type of python.
Convert MindSpore dtype to python data type.
[ "Convert", "MindSpore", "dtype", "to", "python", "data", "type", "." ]
def dtype_to_pytype(type_): """ Convert MindSpore dtype to python data type. Args: type_ (:class:`mindspore.dtype`): MindSpore's dtype. Returns: Type of python. """ return { bool_: bool, int_: int, int8: int, int16: int, int32: int, int64: int, uint8: int, uint16: int, uint32: int, uint64: int, float_: float, float16: float, float32: float, float64: float, list_: list, tuple_: tuple, string: str, complex64: complex, complex128: complex, type_none: type(None) }[type_]
[ "def", "dtype_to_pytype", "(", "type_", ")", ":", "return", "{", "bool_", ":", "bool", ",", "int_", ":", "int", ",", "int8", ":", "int", ",", "int16", ":", "int", ",", "int32", ":", "int", ",", "int64", ":", "int", ",", "uint8", ":", "int", ",", "uint16", ":", "int", ",", "uint32", ":", "int", ",", "uint64", ":", "int", ",", "float_", ":", "float", ",", "float16", ":", "float", ",", "float32", ":", "float", ",", "float64", ":", "float", ",", "list_", ":", "list", ",", "tuple_", ":", "tuple", ",", "string", ":", "str", ",", "complex64", ":", "complex", ",", "complex128", ":", "complex", ",", "type_none", ":", "type", "(", "None", ")", "}", "[", "type_", "]" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/common/dtype.py#L248-L280
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/keras/distribute/distributed_training_utils_v1.py
python
set_weights
(distribution_strategy, dist_model, weights)
Sets the weights of the replicated models. The weights of the replicated models are set to the weights of the original model. The weights of the replicated model are Mirrored variables and hence we need to use the `update` call within a DistributionStrategy scope. Args: distribution_strategy: DistributionStrategy used to distribute training and validation. dist_model: The replicated models on the different devices. weights: The weights of the original model.
Sets the weights of the replicated models.
[ "Sets", "the", "weights", "of", "the", "replicated", "models", "." ]
def set_weights(distribution_strategy, dist_model, weights): """Sets the weights of the replicated models. The weights of the replicated models are set to the weights of the original model. The weights of the replicated model are Mirrored variables and hence we need to use the `update` call within a DistributionStrategy scope. Args: distribution_strategy: DistributionStrategy used to distribute training and validation. dist_model: The replicated models on the different devices. weights: The weights of the original model. """ assign_ops = [] for layer in dist_model.layers: num_param = len(layer.weights) layer_weights = weights[:num_param] for sw, w in zip(layer.weights, layer_weights): if ops.executing_eagerly_outside_functions(): sw.assign(w) else: assign_ops.append(distribution_strategy.unwrap(sw.assign(w))) weights = weights[num_param:] if not ops.executing_eagerly_outside_functions(): backend.get_session(assign_ops).run(assign_ops)
[ "def", "set_weights", "(", "distribution_strategy", ",", "dist_model", ",", "weights", ")", ":", "assign_ops", "=", "[", "]", "for", "layer", "in", "dist_model", ".", "layers", ":", "num_param", "=", "len", "(", "layer", ".", "weights", ")", "layer_weights", "=", "weights", "[", ":", "num_param", "]", "for", "sw", ",", "w", "in", "zip", "(", "layer", ".", "weights", ",", "layer_weights", ")", ":", "if", "ops", ".", "executing_eagerly_outside_functions", "(", ")", ":", "sw", ".", "assign", "(", "w", ")", "else", ":", "assign_ops", ".", "append", "(", "distribution_strategy", ".", "unwrap", "(", "sw", ".", "assign", "(", "w", ")", ")", ")", "weights", "=", "weights", "[", "num_param", ":", "]", "if", "not", "ops", ".", "executing_eagerly_outside_functions", "(", ")", ":", "backend", ".", "get_session", "(", "assign_ops", ")", ".", "run", "(", "assign_ops", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/distribute/distributed_training_utils_v1.py#L51-L76
facebook/fbthrift
fb9c8562aba04c4fd9b17716eb5d970cc88a75bb
build/fbcode_builder/getdeps/expr.py
python
parse_expr
(expr_text, valid_variables)
return p.parse()
parses the simple criteria expression syntax used in dependency specifications. Returns an ExprNode instance that can be evaluated like this: ``` expr = parse_expr("os=windows") ok = expr.eval({ "os": "windows" }) ``` Whitespace is allowed between tokens. The following terms are recognized: KEY = VALUE # Evaluates to True if ctx[KEY] == VALUE not(EXPR) # Evaluates to True if EXPR evaluates to False # and vice versa all(EXPR1, EXPR2, ...) # Evaluates True if all of the supplied # EXPR's also evaluate True any(EXPR1, EXPR2, ...) # Evaluates True if any of the supplied # EXPR's also evaluate True, False if # none of them evaluated true.
parses the simple criteria expression syntax used in dependency specifications. Returns an ExprNode instance that can be evaluated like this:
[ "parses", "the", "simple", "criteria", "expression", "syntax", "used", "in", "dependency", "specifications", ".", "Returns", "an", "ExprNode", "instance", "that", "can", "be", "evaluated", "like", "this", ":" ]
def parse_expr(expr_text, valid_variables): """parses the simple criteria expression syntax used in dependency specifications. Returns an ExprNode instance that can be evaluated like this: ``` expr = parse_expr("os=windows") ok = expr.eval({ "os": "windows" }) ``` Whitespace is allowed between tokens. The following terms are recognized: KEY = VALUE # Evaluates to True if ctx[KEY] == VALUE not(EXPR) # Evaluates to True if EXPR evaluates to False # and vice versa all(EXPR1, EXPR2, ...) # Evaluates True if all of the supplied # EXPR's also evaluate True any(EXPR1, EXPR2, ...) # Evaluates True if any of the supplied # EXPR's also evaluate True, False if # none of them evaluated true. """ p = Parser(expr_text, valid_variables) return p.parse()
[ "def", "parse_expr", "(", "expr_text", ",", "valid_variables", ")", ":", "p", "=", "Parser", "(", "expr_text", ",", "valid_variables", ")", "return", "p", ".", "parse", "(", ")" ]
https://github.com/facebook/fbthrift/blob/fb9c8562aba04c4fd9b17716eb5d970cc88a75bb/build/fbcode_builder/getdeps/expr.py#L10-L36
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/dateutil/tz/_common.py
python
tzname_in_python2
(namefunc)
Change unicode output into bytestrings in Python 2 tzname() API changed in Python 3. It used to return bytes, but was changed to unicode strings
Change unicode output into bytestrings in Python 2
[ "Change", "unicode", "output", "into", "bytestrings", "in", "Python", "2" ]
def tzname_in_python2(namefunc): """Change unicode output into bytestrings in Python 2 tzname() API changed in Python 3. It used to return bytes, but was changed to unicode strings """ if PY2: @wraps(namefunc) def adjust_encoding(*args, **kwargs): name = namefunc(*args, **kwargs) if name is not None: name = name.encode() return name return adjust_encoding else: return namefunc
[ "def", "tzname_in_python2", "(", "namefunc", ")", ":", "if", "PY2", ":", "@", "wraps", "(", "namefunc", ")", "def", "adjust_encoding", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "name", "=", "namefunc", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "name", "is", "not", "None", ":", "name", "=", "name", ".", "encode", "(", ")", "return", "name", "return", "adjust_encoding", "else", ":", "return", "namefunc" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/dateutil/tz/_common.py#L13-L30
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
xpcom/idl-parser/xpidl.py
python
IDLParser.p_paramtype
(self, p)
paramtype : IN | INOUT | OUT
paramtype : IN | INOUT | OUT
[ "paramtype", ":", "IN", "|", "INOUT", "|", "OUT" ]
def p_paramtype(self, p): """paramtype : IN | INOUT | OUT""" p[0] = p[1]
[ "def", "p_paramtype", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/xpcom/idl-parser/xpidl.py#L1344-L1348
zhaoweicai/hwgq
ebc706bee3e2d145de1da4be446ce8de8740738f
scripts/cpp_lint.py
python
CheckVlogArguments
(filename, clean_lines, linenum, error)
Checks that VLOG() is only used for defining a logging level. For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and VLOG(FATAL) are not. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Checks that VLOG() is only used for defining a logging level.
[ "Checks", "that", "VLOG", "()", "is", "only", "used", "for", "defining", "a", "logging", "level", "." ]
def CheckVlogArguments(filename, clean_lines, linenum, error): """Checks that VLOG() is only used for defining a logging level. For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and VLOG(FATAL) are not. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] if Search(r'\bVLOG\((INFO|ERROR|WARNING|DFATAL|FATAL)\)', line): error(filename, linenum, 'runtime/vlog', 5, 'VLOG() should be used with numeric verbosity level. ' 'Use LOG() if you want symbolic severity levels.')
[ "def", "CheckVlogArguments", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "if", "Search", "(", "r'\\bVLOG\\((INFO|ERROR|WARNING|DFATAL|FATAL)\\)'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/vlog'", ",", "5", ",", "'VLOG() should be used with numeric verbosity level. '", "'Use LOG() if you want symbolic severity levels.'", ")" ]
https://github.com/zhaoweicai/hwgq/blob/ebc706bee3e2d145de1da4be446ce8de8740738f/scripts/cpp_lint.py#L1708-L1724
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/training/moving_averages.py
python
ExponentialMovingAverage.apply
(self, var_list=None)
Maintains moving averages of variables. `var_list` must be a list of `Variable` or `Tensor` objects. This method creates shadow variables for all elements of `var_list`. Shadow variables for `Variable` objects are initialized to the variable's initial value. They will be added to the `GraphKeys.MOVING_AVERAGE_VARIABLES` collection. For `Tensor` objects, the shadow variables are initialized to 0. shadow variables are created with `trainable=False` and added to the `GraphKeys.ALL_VARIABLES` collection. They will be returned by calls to `tf.all_variables()`. Returns an op that updates all shadow variables as described above. Note that `apply()` can be called multiple times with different lists of variables. Args: var_list: A list of Variable or Tensor objects. The variables and Tensors must be of types float16, float32, or float64. Returns: An Operation that updates the moving averages. Raises: TypeError: If the arguments are not all float16, float32, or float64. ValueError: If the moving average of one of the variables is already being computed.
Maintains moving averages of variables.
[ "Maintains", "moving", "averages", "of", "variables", "." ]
def apply(self, var_list=None): """Maintains moving averages of variables. `var_list` must be a list of `Variable` or `Tensor` objects. This method creates shadow variables for all elements of `var_list`. Shadow variables for `Variable` objects are initialized to the variable's initial value. They will be added to the `GraphKeys.MOVING_AVERAGE_VARIABLES` collection. For `Tensor` objects, the shadow variables are initialized to 0. shadow variables are created with `trainable=False` and added to the `GraphKeys.ALL_VARIABLES` collection. They will be returned by calls to `tf.all_variables()`. Returns an op that updates all shadow variables as described above. Note that `apply()` can be called multiple times with different lists of variables. Args: var_list: A list of Variable or Tensor objects. The variables and Tensors must be of types float16, float32, or float64. Returns: An Operation that updates the moving averages. Raises: TypeError: If the arguments are not all float16, float32, or float64. ValueError: If the moving average of one of the variables is already being computed. """ # TODO(touts): op_scope if var_list is None: var_list = variables.trainable_variables() for var in var_list: if var.dtype.base_dtype not in [dtypes.float16, dtypes.float32, dtypes.float64]: raise TypeError("The variables must be half, float, or double: %s" % var.name) if var in self._averages: raise ValueError("Moving average already computed for: %s" % var.name) # For variables: to lower communication bandwidth across devices we keep # the moving averages on the same device as the variables. For other # tensors, we rely on the existing device allocation mechanism. with ops.control_dependencies(None): if isinstance(var, variables.Variable): avg = slot_creator.create_slot(var, var.initialized_value(), self._name, colocate_with_primary=True) # NOTE(mrry): We only add `tf.Variable` objects to the # `MOVING_AVERAGE_VARIABLES` collection. ops.add_to_collection(ops.GraphKeys.MOVING_AVERAGE_VARIABLES, var) else: avg = slot_creator.create_zeros_slot( var, self._name, colocate_with_primary=(var.op.type == "Variable")) self._averages[var] = avg with ops.name_scope(self._name) as scope: decay = ops.convert_to_tensor(self._decay, name="decay") if self._num_updates is not None: num_updates = math_ops.cast(self._num_updates, dtypes.float32, name="num_updates") decay = math_ops.minimum(decay, (1.0 + num_updates) / (10.0 + num_updates)) updates = [] for var in var_list: updates.append(assign_moving_average(self._averages[var], var, decay)) return control_flow_ops.group(*updates, name=scope)
[ "def", "apply", "(", "self", ",", "var_list", "=", "None", ")", ":", "# TODO(touts): op_scope", "if", "var_list", "is", "None", ":", "var_list", "=", "variables", ".", "trainable_variables", "(", ")", "for", "var", "in", "var_list", ":", "if", "var", ".", "dtype", ".", "base_dtype", "not", "in", "[", "dtypes", ".", "float16", ",", "dtypes", ".", "float32", ",", "dtypes", ".", "float64", "]", ":", "raise", "TypeError", "(", "\"The variables must be half, float, or double: %s\"", "%", "var", ".", "name", ")", "if", "var", "in", "self", ".", "_averages", ":", "raise", "ValueError", "(", "\"Moving average already computed for: %s\"", "%", "var", ".", "name", ")", "# For variables: to lower communication bandwidth across devices we keep", "# the moving averages on the same device as the variables. For other", "# tensors, we rely on the existing device allocation mechanism.", "with", "ops", ".", "control_dependencies", "(", "None", ")", ":", "if", "isinstance", "(", "var", ",", "variables", ".", "Variable", ")", ":", "avg", "=", "slot_creator", ".", "create_slot", "(", "var", ",", "var", ".", "initialized_value", "(", ")", ",", "self", ".", "_name", ",", "colocate_with_primary", "=", "True", ")", "# NOTE(mrry): We only add `tf.Variable` objects to the", "# `MOVING_AVERAGE_VARIABLES` collection.", "ops", ".", "add_to_collection", "(", "ops", ".", "GraphKeys", ".", "MOVING_AVERAGE_VARIABLES", ",", "var", ")", "else", ":", "avg", "=", "slot_creator", ".", "create_zeros_slot", "(", "var", ",", "self", ".", "_name", ",", "colocate_with_primary", "=", "(", "var", ".", "op", ".", "type", "==", "\"Variable\"", ")", ")", "self", ".", "_averages", "[", "var", "]", "=", "avg", "with", "ops", ".", "name_scope", "(", "self", ".", "_name", ")", "as", "scope", ":", "decay", "=", "ops", ".", "convert_to_tensor", "(", "self", ".", "_decay", ",", "name", "=", "\"decay\"", ")", "if", "self", ".", "_num_updates", "is", "not", "None", ":", "num_updates", "=", "math_ops", ".", "cast", "(", "self", ".", "_num_updates", ",", "dtypes", ".", "float32", ",", "name", "=", "\"num_updates\"", ")", "decay", "=", "math_ops", ".", "minimum", "(", "decay", ",", "(", "1.0", "+", "num_updates", ")", "/", "(", "10.0", "+", "num_updates", ")", ")", "updates", "=", "[", "]", "for", "var", "in", "var_list", ":", "updates", ".", "append", "(", "assign_moving_average", "(", "self", ".", "_averages", "[", "var", "]", ",", "var", ",", "decay", ")", ")", "return", "control_flow_ops", ".", "group", "(", "*", "updates", ",", "name", "=", "scope", ")" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/training/moving_averages.py#L235-L306
mickem/nscp
79f89fdbb6da63f91bc9dedb7aea202fe938f237
scripts/python/lib/google/protobuf/internal/python_message.py
python
_AddClearExtensionMethod
(cls)
Helper for _AddMessageMethods().
Helper for _AddMessageMethods().
[ "Helper", "for", "_AddMessageMethods", "()", "." ]
def _AddClearExtensionMethod(cls): """Helper for _AddMessageMethods().""" def ClearExtension(self, extension_handle): _VerifyExtensionHandle(self, extension_handle) # Similar to ClearField(), above. if extension_handle in self._fields: del self._fields[extension_handle] self._Modified() cls.ClearExtension = ClearExtension
[ "def", "_AddClearExtensionMethod", "(", "cls", ")", ":", "def", "ClearExtension", "(", "self", ",", "extension_handle", ")", ":", "_VerifyExtensionHandle", "(", "self", ",", "extension_handle", ")", "# Similar to ClearField(), above.", "if", "extension_handle", "in", "self", ".", "_fields", ":", "del", "self", ".", "_fields", "[", "extension_handle", "]", "self", ".", "_Modified", "(", ")", "cls", ".", "ClearExtension", "=", "ClearExtension" ]
https://github.com/mickem/nscp/blob/79f89fdbb6da63f91bc9dedb7aea202fe938f237/scripts/python/lib/google/protobuf/internal/python_message.py#L606-L615
francinexue/xuefu
b6ff79747a42e020588c0c0a921048e08fe4680c
api/ctpx/ctptd.py
python
CtpTd.onRtnCombAction
(self, CombActionField)
申请组合通知
申请组合通知
[ "申请组合通知" ]
def onRtnCombAction(self, CombActionField): """申请组合通知""" pass
[ "def", "onRtnCombAction", "(", "self", ",", "CombActionField", ")", ":", "pass" ]
https://github.com/francinexue/xuefu/blob/b6ff79747a42e020588c0c0a921048e08fe4680c/api/ctpx/ctptd.py#L423-L425
mapnik/mapnik
f3da900c355e1d15059c4a91b00203dcc9d9f0ef
scons/scons-local-4.1.0/SCons/Builder.py
python
BuilderBase.add_src_builder
(self, builder)
Add a new Builder to the list of src_builders. This requires wiping out cached values so that the computed lists of source suffixes get re-calculated.
Add a new Builder to the list of src_builders.
[ "Add", "a", "new", "Builder", "to", "the", "list", "of", "src_builders", "." ]
def add_src_builder(self, builder): """ Add a new Builder to the list of src_builders. This requires wiping out cached values so that the computed lists of source suffixes get re-calculated. """ self._memo = {} self.src_builder.append(builder)
[ "def", "add_src_builder", "(", "self", ",", "builder", ")", ":", "self", ".", "_memo", "=", "{", "}", "self", ".", "src_builder", ".", "append", "(", "builder", ")" ]
https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Builder.py#L698-L706
apache/singa
93fd9da72694e68bfe3fb29d0183a65263d238a1
python/singa/autograd.py
python
Sigmoid.forward
(self, x)
return out
Args: x (CTensor): Input tensor Returns: CTensor, the output
Args: x (CTensor): Input tensor Returns: CTensor, the output
[ "Args", ":", "x", "(", "CTensor", ")", ":", "Input", "tensor", "Returns", ":", "CTensor", "the", "output" ]
def forward(self, x): """ Args: x (CTensor): Input tensor Returns: CTensor, the output """ out = singa.Sigmoid(x) if training: self.cache = (out,) return out
[ "def", "forward", "(", "self", ",", "x", ")", ":", "out", "=", "singa", ".", "Sigmoid", "(", "x", ")", "if", "training", ":", "self", ".", "cache", "=", "(", "out", ",", ")", "return", "out" ]
https://github.com/apache/singa/blob/93fd9da72694e68bfe3fb29d0183a65263d238a1/python/singa/autograd.py#L2462-L2472
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
current/tools/gyp/pylib/gyp/common.py
python
GetFlavor
(params)
return 'linux'
Returns |params.flavor| if it's set, the system's default flavor else.
Returns |params.flavor| if it's set, the system's default flavor else.
[ "Returns", "|params", ".", "flavor|", "if", "it", "s", "set", "the", "system", "s", "default", "flavor", "else", "." ]
def GetFlavor(params): """Returns |params.flavor| if it's set, the system's default flavor else.""" flavors = { 'cygwin': 'win', 'win32': 'win', 'darwin': 'mac', } if 'flavor' in params: return params['flavor'] if sys.platform in flavors: return flavors[sys.platform] if sys.platform.startswith('sunos'): return 'solaris' if sys.platform.startswith(('dragonfly', 'freebsd')): return 'freebsd' if sys.platform.startswith('openbsd'): return 'openbsd' if sys.platform.startswith('netbsd'): return 'netbsd' if sys.platform.startswith('aix'): return 'aix' if sys.platform.startswith(('os390', 'zos')): return 'zos' return 'linux'
[ "def", "GetFlavor", "(", "params", ")", ":", "flavors", "=", "{", "'cygwin'", ":", "'win'", ",", "'win32'", ":", "'win'", ",", "'darwin'", ":", "'mac'", ",", "}", "if", "'flavor'", "in", "params", ":", "return", "params", "[", "'flavor'", "]", "if", "sys", ".", "platform", "in", "flavors", ":", "return", "flavors", "[", "sys", ".", "platform", "]", "if", "sys", ".", "platform", ".", "startswith", "(", "'sunos'", ")", ":", "return", "'solaris'", "if", "sys", ".", "platform", ".", "startswith", "(", "(", "'dragonfly'", ",", "'freebsd'", ")", ")", ":", "return", "'freebsd'", "if", "sys", ".", "platform", ".", "startswith", "(", "'openbsd'", ")", ":", "return", "'openbsd'", "if", "sys", ".", "platform", ".", "startswith", "(", "'netbsd'", ")", ":", "return", "'netbsd'", "if", "sys", ".", "platform", ".", "startswith", "(", "'aix'", ")", ":", "return", "'aix'", "if", "sys", ".", "platform", ".", "startswith", "(", "(", "'os390'", ",", "'zos'", ")", ")", ":", "return", "'zos'", "return", "'linux'" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/gyp/pylib/gyp/common.py#L423-L448
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/closure_linter/closure_linter/javascripttokens.py
python
JavaScriptToken.IsAssignment
(self)
return (self.type == JavaScriptTokenType.OPERATOR and self.string.endswith('=') and self.string not in ('==', '!=', '>=', '<=', '===', '!=='))
Tests if this token is an assignment operator. Returns: True if this token is an assignment operator.
Tests if this token is an assignment operator.
[ "Tests", "if", "this", "token", "is", "an", "assignment", "operator", "." ]
def IsAssignment(self): """Tests if this token is an assignment operator. Returns: True if this token is an assignment operator. """ return (self.type == JavaScriptTokenType.OPERATOR and self.string.endswith('=') and self.string not in ('==', '!=', '>=', '<=', '===', '!=='))
[ "def", "IsAssignment", "(", "self", ")", ":", "return", "(", "self", ".", "type", "==", "JavaScriptTokenType", ".", "OPERATOR", "and", "self", ".", "string", ".", "endswith", "(", "'='", ")", "and", "self", ".", "string", "not", "in", "(", "'=='", ",", "'!='", ",", "'>='", ",", "'<='", ",", "'==='", ",", "'!=='", ")", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/closure_linter/closure_linter/javascripttokens.py#L121-L129
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/importlib/util.py
python
resolve_name
(name, package)
return _resolve_name(name[level:], package, level)
Resolve a relative module name to an absolute one.
Resolve a relative module name to an absolute one.
[ "Resolve", "a", "relative", "module", "name", "to", "an", "absolute", "one", "." ]
def resolve_name(name, package): """Resolve a relative module name to an absolute one.""" if not name.startswith('.'): return name elif not package: raise ImportError(f'no package specified for {repr(name)} ' '(required for relative module names)') level = 0 for character in name: if character != '.': break level += 1 return _resolve_name(name[level:], package, level)
[ "def", "resolve_name", "(", "name", ",", "package", ")", ":", "if", "not", "name", ".", "startswith", "(", "'.'", ")", ":", "return", "name", "elif", "not", "package", ":", "raise", "ImportError", "(", "f'no package specified for {repr(name)} '", "'(required for relative module names)'", ")", "level", "=", "0", "for", "character", "in", "name", ":", "if", "character", "!=", "'.'", ":", "break", "level", "+=", "1", "return", "_resolve_name", "(", "name", "[", "level", ":", "]", ",", "package", ",", "level", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/importlib/util.py#L27-L39
facebookresearch/habitat-sim
63b6c71d9ca8adaefb140b198196f5d0ca1f1e34
src_python/habitat_sim/utils/viz_utils.py
python
observation_to_image
( observation_image: np.ndarray, observation_type: str, depth_clip: Optional[float] = 10.0, )
return rgb_image
Generate an rgb image from a sensor observation. Supported types are: "color", "depth", "semantic" :param observation_image: Raw observation image from sensor output. :param observation_type: Observation type ("color", "depth", "semantic" supported) :param depth_clip: Defines default depth clip normalization for all depth images. :return: PIL Image object or None if fails.
Generate an rgb image from a sensor observation. Supported types are: "color", "depth", "semantic"
[ "Generate", "an", "rgb", "image", "from", "a", "sensor", "observation", ".", "Supported", "types", "are", ":", "color", "depth", "semantic" ]
def observation_to_image( observation_image: np.ndarray, observation_type: str, depth_clip: Optional[float] = 10.0, ): """Generate an rgb image from a sensor observation. Supported types are: "color", "depth", "semantic" :param observation_image: Raw observation image from sensor output. :param observation_type: Observation type ("color", "depth", "semantic" supported) :param depth_clip: Defines default depth clip normalization for all depth images. :return: PIL Image object or None if fails. """ rgb_image = None if observation_type == "color": rgb_image = Image.fromarray(np.uint8(observation_image)) elif observation_type == "depth": rgb_image = Image.fromarray( depth_to_rgb(observation_image, clip_max=depth_clip) ) elif observation_type == "semantic": rgb_image = semantic_to_rgb(observation_image) else: print( "semantic_to_rgb : Failed, unsupported observation type: " + observation_type ) return rgb_image
[ "def", "observation_to_image", "(", "observation_image", ":", "np", ".", "ndarray", ",", "observation_type", ":", "str", ",", "depth_clip", ":", "Optional", "[", "float", "]", "=", "10.0", ",", ")", ":", "rgb_image", "=", "None", "if", "observation_type", "==", "\"color\"", ":", "rgb_image", "=", "Image", ".", "fromarray", "(", "np", ".", "uint8", "(", "observation_image", ")", ")", "elif", "observation_type", "==", "\"depth\"", ":", "rgb_image", "=", "Image", ".", "fromarray", "(", "depth_to_rgb", "(", "observation_image", ",", "clip_max", "=", "depth_clip", ")", ")", "elif", "observation_type", "==", "\"semantic\"", ":", "rgb_image", "=", "semantic_to_rgb", "(", "observation_image", ")", "else", ":", "print", "(", "\"semantic_to_rgb : Failed, unsupported observation type: \"", "+", "observation_type", ")", "return", "rgb_image" ]
https://github.com/facebookresearch/habitat-sim/blob/63b6c71d9ca8adaefb140b198196f5d0ca1f1e34/src_python/habitat_sim/utils/viz_utils.py#L109-L136
brndnmtthws/conky
8f5014b90f1bc9f999beff752a9b369e4885f0d6
cmake/scripts/clang-format-check-changed.py
python
run_clang_format
(clang_format_bin, changed_files)
return 0
Run clang format on a list of files @return 0 if formatted correctly.
Run clang format on a list of files
[ "Run", "clang", "format", "on", "a", "list", "of", "files" ]
def run_clang_format(clang_format_bin, changed_files): """ Run clang format on a list of files @return 0 if formatted correctly. """ if len(changed_files) == 0: return 0 cmd = [clang_format_bin, "-style=file", "-output-replacements-xml"] + changed_files print("clang-format cmd = {}".format(cmd)) try: cmd_output = subprocess.check_output(cmd) if "replacement offset" in cmd_output: print("ERROR: Changed files don't match format") return 1 except subprocess.CalledProcessError, e: print("Error calling clang-format [{}]".format(e)) return e.returncode return 0
[ "def", "run_clang_format", "(", "clang_format_bin", ",", "changed_files", ")", ":", "if", "len", "(", "changed_files", ")", "==", "0", ":", "return", "0", "cmd", "=", "[", "clang_format_bin", ",", "\"-style=file\"", ",", "\"-output-replacements-xml\"", "]", "+", "changed_files", "print", "(", "\"clang-format cmd = {}\"", ".", "format", "(", "cmd", ")", ")", "try", ":", "cmd_output", "=", "subprocess", ".", "check_output", "(", "cmd", ")", "if", "\"replacement offset\"", "in", "cmd_output", ":", "print", "(", "\"ERROR: Changed files don't match format\"", ")", "return", "1", "except", "subprocess", ".", "CalledProcessError", ",", "e", ":", "print", "(", "\"Error calling clang-format [{}]\"", ".", "format", "(", "e", ")", ")", "return", "e", ".", "returncode", "return", "0" ]
https://github.com/brndnmtthws/conky/blob/8f5014b90f1bc9f999beff752a9b369e4885f0d6/cmake/scripts/clang-format-check-changed.py#L117-L136
microsoft/checkedc-clang
a173fefde5d7877b7750e7ce96dd08cf18baebf2
lldb/examples/python/file_extract.py
python
FileExtract.get_c_string
(self)
return cstr
Extract a single NULL terminated C string from the binary file at the current file position, returns a single C string
Extract a single NULL terminated C string from the binary file at the current file position, returns a single C string
[ "Extract", "a", "single", "NULL", "terminated", "C", "string", "from", "the", "binary", "file", "at", "the", "current", "file", "position", "returns", "a", "single", "C", "string" ]
def get_c_string(self): '''Extract a single NULL terminated C string from the binary file at the current file position, returns a single C string''' cstr = '' byte = self.get_uint8() while byte != 0: cstr += "%c" % byte byte = self.get_uint8() return cstr
[ "def", "get_c_string", "(", "self", ")", ":", "cstr", "=", "''", "byte", "=", "self", ".", "get_uint8", "(", ")", "while", "byte", "!=", "0", ":", "cstr", "+=", "\"%c\"", "%", "byte", "byte", "=", "self", ".", "get_uint8", "(", ")", "return", "cstr" ]
https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/lldb/examples/python/file_extract.py#L155-L162
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/jinja2/environment.py
python
Template.generate
(self, *args, **kwargs)
For very large templates it can be useful to not render the whole template at once but evaluate each statement after another and yield piece for piece. This method basically does exactly that and returns a generator that yields one item after another as unicode strings. It accepts the same arguments as :meth:`render`.
For very large templates it can be useful to not render the whole template at once but evaluate each statement after another and yield piece for piece. This method basically does exactly that and returns a generator that yields one item after another as unicode strings.
[ "For", "very", "large", "templates", "it", "can", "be", "useful", "to", "not", "render", "the", "whole", "template", "at", "once", "but", "evaluate", "each", "statement", "after", "another", "and", "yield", "piece", "for", "piece", ".", "This", "method", "basically", "does", "exactly", "that", "and", "returns", "a", "generator", "that", "yields", "one", "item", "after", "another", "as", "unicode", "strings", "." ]
def generate(self, *args, **kwargs): """For very large templates it can be useful to not render the whole template at once but evaluate each statement after another and yield piece for piece. This method basically does exactly that and returns a generator that yields one item after another as unicode strings. It accepts the same arguments as :meth:`render`. """ vars = dict(*args, **kwargs) try: for event in self.root_render_func(self.new_context(vars)): yield event except Exception: exc_info = sys.exc_info() else: return yield self.environment.handle_exception(exc_info, True)
[ "def", "generate", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "vars", "=", "dict", "(", "*", "args", ",", "*", "*", "kwargs", ")", "try", ":", "for", "event", "in", "self", ".", "root_render_func", "(", "self", ".", "new_context", "(", "vars", ")", ")", ":", "yield", "event", "except", "Exception", ":", "exc_info", "=", "sys", ".", "exc_info", "(", ")", "else", ":", "return", "yield", "self", ".", "environment", ".", "handle_exception", "(", "exc_info", ",", "True", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/jinja2/environment.py#L977-L993
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/telemetry/internal/backends/chrome_inspector/inspector_runtime.py
python
InspectorRuntime.Evaluate
(self, expr, context_id, timeout)
return res['result']['result']['value']
Evaluates a javascript expression and returns the result. |context_id| can refer to an iframe. The main page has context_id=1, the first iframe context_id=2, etc. Raises: exceptions.EvaluateException exceptions.WebSocketDisconnected websocket.WebSocketException socket.error
Evaluates a javascript expression and returns the result.
[ "Evaluates", "a", "javascript", "expression", "and", "returns", "the", "result", "." ]
def Evaluate(self, expr, context_id, timeout): """Evaluates a javascript expression and returns the result. |context_id| can refer to an iframe. The main page has context_id=1, the first iframe context_id=2, etc. Raises: exceptions.EvaluateException exceptions.WebSocketDisconnected websocket.WebSocketException socket.error """ request = { 'method': 'Runtime.evaluate', 'params': { 'expression': expr, 'returnByValue': True } } if context_id is not None: self.EnableAllContexts() request['params']['contextId'] = context_id res = self._inspector_websocket.SyncRequest(request, timeout) if 'error' in res: raise exceptions.EvaluateException(res['error']['message']) if 'wasThrown' in res['result'] and res['result']['wasThrown']: # TODO(nduca): propagate stacks from javascript up to the python # exception. raise exceptions.EvaluateException(res['result']['result']['description']) if res['result']['result']['type'] == 'undefined': return None return res['result']['result']['value']
[ "def", "Evaluate", "(", "self", ",", "expr", ",", "context_id", ",", "timeout", ")", ":", "request", "=", "{", "'method'", ":", "'Runtime.evaluate'", ",", "'params'", ":", "{", "'expression'", ":", "expr", ",", "'returnByValue'", ":", "True", "}", "}", "if", "context_id", "is", "not", "None", ":", "self", ".", "EnableAllContexts", "(", ")", "request", "[", "'params'", "]", "[", "'contextId'", "]", "=", "context_id", "res", "=", "self", ".", "_inspector_websocket", ".", "SyncRequest", "(", "request", ",", "timeout", ")", "if", "'error'", "in", "res", ":", "raise", "exceptions", ".", "EvaluateException", "(", "res", "[", "'error'", "]", "[", "'message'", "]", ")", "if", "'wasThrown'", "in", "res", "[", "'result'", "]", "and", "res", "[", "'result'", "]", "[", "'wasThrown'", "]", ":", "# TODO(nduca): propagate stacks from javascript up to the python", "# exception.", "raise", "exceptions", ".", "EvaluateException", "(", "res", "[", "'result'", "]", "[", "'result'", "]", "[", "'description'", "]", ")", "if", "res", "[", "'result'", "]", "[", "'result'", "]", "[", "'type'", "]", "==", "'undefined'", ":", "return", "None", "return", "res", "[", "'result'", "]", "[", "'result'", "]", "[", "'value'", "]" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/internal/backends/chrome_inspector/inspector_runtime.py#L23-L55
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
caffe2/python/dataset.py
python
Dataset.reader
(self, init_net=None, cursor_name=None, batch_size=1, enforce_batch_size=False)
return reader
Create a Reader object that is used to iterate through the dataset. This will append operations to `init_net` that create a TreeCursor, used to iterate through the data. NOTE: Currently, it is not safe to append to a dataset while reading. Args: init_net: net that will be run once to create the cursor. cursor_name: optional name for the blob containing a pointer to the cursor. batch_size: how many samples to read per iteration. Returns: A _DatasetReader that can be used to create operators that will iterate through the dataset.
Create a Reader object that is used to iterate through the dataset.
[ "Create", "a", "Reader", "object", "that", "is", "used", "to", "iterate", "through", "the", "dataset", "." ]
def reader(self, init_net=None, cursor_name=None, batch_size=1, enforce_batch_size=False): """Create a Reader object that is used to iterate through the dataset. This will append operations to `init_net` that create a TreeCursor, used to iterate through the data. NOTE: Currently, it is not safe to append to a dataset while reading. Args: init_net: net that will be run once to create the cursor. cursor_name: optional name for the blob containing a pointer to the cursor. batch_size: how many samples to read per iteration. Returns: A _DatasetReader that can be used to create operators that will iterate through the dataset. """ assert self.field_blobs, 'Dataset not initialized.' reader = _DatasetReader(self, cursor_name, batch_size, enforce_batch_size) if init_net is not None: reader.setup_ex(init_net, None) return reader
[ "def", "reader", "(", "self", ",", "init_net", "=", "None", ",", "cursor_name", "=", "None", ",", "batch_size", "=", "1", ",", "enforce_batch_size", "=", "False", ")", ":", "assert", "self", ".", "field_blobs", ",", "'Dataset not initialized.'", "reader", "=", "_DatasetReader", "(", "self", ",", "cursor_name", ",", "batch_size", ",", "enforce_batch_size", ")", "if", "init_net", "is", "not", "None", ":", "reader", ".", "setup_ex", "(", "init_net", ",", "None", ")", "return", "reader" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/caffe2/python/dataset.py#L276-L300
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/internals/blocks.py
python
Block._slice
(self, slicer)
return self.values[slicer]
return a slice of my values
return a slice of my values
[ "return", "a", "slice", "of", "my", "values" ]
def _slice(self, slicer): """ return a slice of my values """ return self.values[slicer]
[ "def", "_slice", "(", "self", ",", "slicer", ")", ":", "return", "self", ".", "values", "[", "slicer", "]" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/internals/blocks.py#L311-L313
microsoft/ELL
a1d6bacc37a14879cc025d9be2ba40b1a0632315
tools/utilities/datasetFromImages/datasetFromImages.py
python
load_categories
(file_name)
return categories
Loads the category index from file. Each category label is the name of a class specified on a separate line. The entry order is the index of the class.
Loads the category index from file. Each category label is the name of a class specified on a separate line. The entry order is the index of the class.
[ "Loads", "the", "category", "index", "from", "file", ".", "Each", "category", "label", "is", "the", "name", "of", "a", "class", "specified", "on", "a", "separate", "line", ".", "The", "entry", "order", "is", "the", "index", "of", "the", "class", "." ]
def load_categories(file_name): """ Loads the category index from file. Each category label is the name of a class specified on a separate line. The entry order is the index of the class. """ labels = [] with open(file_name) as f: labels = f.read().splitlines() categories = {} for category in labels: categories[category] = len(categories) return categories
[ "def", "load_categories", "(", "file_name", ")", ":", "labels", "=", "[", "]", "with", "open", "(", "file_name", ")", "as", "f", ":", "labels", "=", "f", ".", "read", "(", ")", ".", "splitlines", "(", ")", "categories", "=", "{", "}", "for", "category", "in", "labels", ":", "categories", "[", "category", "]", "=", "len", "(", "categories", ")", "return", "categories" ]
https://github.com/microsoft/ELL/blob/a1d6bacc37a14879cc025d9be2ba40b1a0632315/tools/utilities/datasetFromImages/datasetFromImages.py#L198-L210
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
Rect.Set
(*args, **kwargs)
return _core_.Rect_Set(*args, **kwargs)
Set(self, int x=0, int y=0, int width=0, int height=0) Set all rectangle properties.
Set(self, int x=0, int y=0, int width=0, int height=0)
[ "Set", "(", "self", "int", "x", "=", "0", "int", "y", "=", "0", "int", "width", "=", "0", "int", "height", "=", "0", ")" ]
def Set(*args, **kwargs): """ Set(self, int x=0, int y=0, int width=0, int height=0) Set all rectangle properties. """ return _core_.Rect_Set(*args, **kwargs)
[ "def", "Set", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Rect_Set", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L1555-L1561
llvm/llvm-project
ffa6262cb4e2a335d26416fad39a581b4f98c5f4
lldb/utils/lui/lldbutil.py
python
run_break_set_by_source_regexp
( test, regexp, extra_options=None, num_expected_locations=-1)
return get_bpno_from_match(break_results)
Set a breakpoint by source regular expression. Common options are the same as run_break_set_by_file_and_line.
Set a breakpoint by source regular expression. Common options are the same as run_break_set_by_file_and_line.
[ "Set", "a", "breakpoint", "by", "source", "regular", "expression", ".", "Common", "options", "are", "the", "same", "as", "run_break_set_by_file_and_line", "." ]
def run_break_set_by_source_regexp( test, regexp, extra_options=None, num_expected_locations=-1): """Set a breakpoint by source regular expression. Common options are the same as run_break_set_by_file_and_line.""" command = 'breakpoint set -p "%s"' % (regexp) if extra_options: command += " " + extra_options break_results = run_break_set_command(test, command) check_breakpoint_result( test, break_results, num_locations=num_expected_locations) return get_bpno_from_match(break_results)
[ "def", "run_break_set_by_source_regexp", "(", "test", ",", "regexp", ",", "extra_options", "=", "None", ",", "num_expected_locations", "=", "-", "1", ")", ":", "command", "=", "'breakpoint set -p \"%s\"'", "%", "(", "regexp", ")", "if", "extra_options", ":", "command", "+=", "\" \"", "+", "extra_options", "break_results", "=", "run_break_set_command", "(", "test", ",", "command", ")", "check_breakpoint_result", "(", "test", ",", "break_results", ",", "num_locations", "=", "num_expected_locations", ")", "return", "get_bpno_from_match", "(", "break_results", ")" ]
https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/lldb/utils/lui/lldbutil.py#L459-L476
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/minimum-number-of-increments-on-subarrays-to-form-a-target-array.py
python
Solution2.minNumberOperations
(self, target)
return sum(max(b-a, 0) for b, a in itertools.izip(target, [0]+target))
:type target: List[int] :rtype: int
:type target: List[int] :rtype: int
[ ":", "type", "target", ":", "List", "[", "int", "]", ":", "rtype", ":", "int" ]
def minNumberOperations(self, target): """ :type target: List[int] :rtype: int """ return sum(max(b-a, 0) for b, a in itertools.izip(target, [0]+target))
[ "def", "minNumberOperations", "(", "self", ",", "target", ")", ":", "return", "sum", "(", "max", "(", "b", "-", "a", ",", "0", ")", "for", "b", ",", "a", "in", "itertools", ".", "izip", "(", "target", ",", "[", "0", "]", "+", "target", ")", ")" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/minimum-number-of-increments-on-subarrays-to-form-a-target-array.py#L19-L24
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/protobuf/py2/google/protobuf/internal/python_message.py
python
_AddEnumValues
(descriptor, cls)
Sets class-level attributes for all enum fields defined in this message. Also exporting a class-level object that can name enum values. Args: descriptor: Descriptor object for this message type. cls: Class we're constructing for this message type.
Sets class-level attributes for all enum fields defined in this message.
[ "Sets", "class", "-", "level", "attributes", "for", "all", "enum", "fields", "defined", "in", "this", "message", "." ]
def _AddEnumValues(descriptor, cls): """Sets class-level attributes for all enum fields defined in this message. Also exporting a class-level object that can name enum values. Args: descriptor: Descriptor object for this message type. cls: Class we're constructing for this message type. """ for enum_type in descriptor.enum_types: setattr(cls, enum_type.name, enum_type_wrapper.EnumTypeWrapper(enum_type)) for enum_value in enum_type.values: setattr(cls, enum_value.name, enum_value.number)
[ "def", "_AddEnumValues", "(", "descriptor", ",", "cls", ")", ":", "for", "enum_type", "in", "descriptor", ".", "enum_types", ":", "setattr", "(", "cls", ",", "enum_type", ".", "name", ",", "enum_type_wrapper", ".", "EnumTypeWrapper", "(", "enum_type", ")", ")", "for", "enum_value", "in", "enum_type", ".", "values", ":", "setattr", "(", "cls", ",", "enum_value", ".", "name", ",", "enum_value", ".", "number", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py2/google/protobuf/internal/python_message.py#L385-L397
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/_extends/graph_kernel/model/graph_split.py
python
GraphSplitByPattern.fuse
(self, selector)
return changed
Fuse areas
Fuse areas
[ "Fuse", "areas" ]
def fuse(self, selector): """Fuse areas""" def _fuse_area(): for dominant in self.areas: result = selector(dominant) if result is None or not result[0]: continue fuse_areas, is_forward = result fuse_areas = self.limit_area_size(dominant, fuse_areas) if not fuse_areas: continue if is_forward: for area in fuse_areas: dominant.fuse(area) self.set_area_map(area.ops, dominant) self.areas.remove(area) else: forward_area = dominant for area in fuse_areas: area.fuse(forward_area) self.set_area_map(forward_area.ops, area) self.areas.remove(forward_area) forward_area = area return True return False changed, do_again = False, True while do_again: do_again = _fuse_area() changed = changed or do_again return changed
[ "def", "fuse", "(", "self", ",", "selector", ")", ":", "def", "_fuse_area", "(", ")", ":", "for", "dominant", "in", "self", ".", "areas", ":", "result", "=", "selector", "(", "dominant", ")", "if", "result", "is", "None", "or", "not", "result", "[", "0", "]", ":", "continue", "fuse_areas", ",", "is_forward", "=", "result", "fuse_areas", "=", "self", ".", "limit_area_size", "(", "dominant", ",", "fuse_areas", ")", "if", "not", "fuse_areas", ":", "continue", "if", "is_forward", ":", "for", "area", "in", "fuse_areas", ":", "dominant", ".", "fuse", "(", "area", ")", "self", ".", "set_area_map", "(", "area", ".", "ops", ",", "dominant", ")", "self", ".", "areas", ".", "remove", "(", "area", ")", "else", ":", "forward_area", "=", "dominant", "for", "area", "in", "fuse_areas", ":", "area", ".", "fuse", "(", "forward_area", ")", "self", ".", "set_area_map", "(", "forward_area", ".", "ops", ",", "area", ")", "self", ".", "areas", ".", "remove", "(", "forward_area", ")", "forward_area", "=", "area", "return", "True", "return", "False", "changed", ",", "do_again", "=", "False", ",", "True", "while", "do_again", ":", "do_again", "=", "_fuse_area", "(", ")", "changed", "=", "changed", "or", "do_again", "return", "changed" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/_extends/graph_kernel/model/graph_split.py#L359-L390
zachriggle/ida-splode
a4aee3be415b318a0e051a523ebd0a8d6d5e0026
py/idasplode/analysis/reconstruct.py
python
EnsureHeapMetadataHomogeneity
(Metadata)
return (Sizes.pop(), Offsets.pop(), Frames)
Ensures that all of the metadata provded are homoenous on the size, offset-from-base, and backtrace for all heap interactions. Returns: Tuple containing (size,offset,backtrace) for the common allocation type.
Ensures that all of the metadata provded are homoenous on the size, offset-from-base, and backtrace for all heap interactions.
[ "Ensures", "that", "all", "of", "the", "metadata", "provded", "are", "homoenous", "on", "the", "size", "offset", "-", "from", "-", "base", "and", "backtrace", "for", "all", "heap", "interactions", "." ]
def EnsureHeapMetadataHomogeneity(Metadata): """Ensures that all of the metadata provded are homoenous on the size, offset-from-base, and backtrace for all heap interactions. Returns: Tuple containing (size,offset,backtrace) for the common allocation type. """ HeapMeta = tuple(M for M in Metadata if M.Heap) Sizes = set(M.Heap.Size for M in HeapMeta) Offsets = set(M.Heap.Offset for M in HeapMeta) Frames = set(M.Heap.Frames for M in HeapMeta) if not len(HeapMeta): raise Exception("No heap data found") if len(HeapMeta) != len(Metadata): print "Not all interactions are heap metadata, only looking at heap data!" if len(Sizes) != 1: raise Exception("Multiple sizes %r, cannot analyze" % Sizes) if len(Offsets) != 1: raise Exception("Multiple offsets %r, cannot analyze" % Offsets) #if len(Frames) != 1: # raise Exception("Multiple allocation stacks, cannot analyze") return (Sizes.pop(), Offsets.pop(), Frames)
[ "def", "EnsureHeapMetadataHomogeneity", "(", "Metadata", ")", ":", "HeapMeta", "=", "tuple", "(", "M", "for", "M", "in", "Metadata", "if", "M", ".", "Heap", ")", "Sizes", "=", "set", "(", "M", ".", "Heap", ".", "Size", "for", "M", "in", "HeapMeta", ")", "Offsets", "=", "set", "(", "M", ".", "Heap", ".", "Offset", "for", "M", "in", "HeapMeta", ")", "Frames", "=", "set", "(", "M", ".", "Heap", ".", "Frames", "for", "M", "in", "HeapMeta", ")", "if", "not", "len", "(", "HeapMeta", ")", ":", "raise", "Exception", "(", "\"No heap data found\"", ")", "if", "len", "(", "HeapMeta", ")", "!=", "len", "(", "Metadata", ")", ":", "print", "\"Not all interactions are heap metadata, only looking at heap data!\"", "if", "len", "(", "Sizes", ")", "!=", "1", ":", "raise", "Exception", "(", "\"Multiple sizes %r, cannot analyze\"", "%", "Sizes", ")", "if", "len", "(", "Offsets", ")", "!=", "1", ":", "raise", "Exception", "(", "\"Multiple offsets %r, cannot analyze\"", "%", "Offsets", ")", "#if len(Frames) != 1:", "# raise Exception(\"Multiple allocation stacks, cannot analyze\")", "return", "(", "Sizes", ".", "pop", "(", ")", ",", "Offsets", ".", "pop", "(", ")", ",", "Frames", ")" ]
https://github.com/zachriggle/ida-splode/blob/a4aee3be415b318a0e051a523ebd0a8d6d5e0026/py/idasplode/analysis/reconstruct.py#L53-L77
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/training/input.py
python
batch
(tensors, batch_size, num_threads=1, capacity=32, enqueue_many=False, shapes=None, dynamic_pad=False, allow_smaller_final_batch=False, shared_name=None, name=None)
return _batch( tensors, batch_size, keep_input=True, num_threads=num_threads, capacity=capacity, enqueue_many=enqueue_many, shapes=shapes, dynamic_pad=dynamic_pad, allow_smaller_final_batch=allow_smaller_final_batch, shared_name=shared_name, name=name)
Creates batches of tensors in `tensors`. The argument `tensors` can be a list or a dictionary of tensors. The value returned by the function will be of the same type as `tensors`. This function is implemented using a queue. A `QueueRunner` for the queue is added to the current `Graph`'s `QUEUE_RUNNER` collection. If `enqueue_many` is `False`, `tensors` is assumed to represent a single example. An input tensor with shape `[x, y, z]` will be output as a tensor with shape `[batch_size, x, y, z]`. If `enqueue_many` is `True`, `tensors` is assumed to represent a batch of examples, where the first dimension is indexed by example, and all members of `tensors` should have the same size in the first dimension. If an input tensor has shape `[*, x, y, z]`, the output will have shape `[batch_size, x, y, z]`. The `capacity` argument controls the how long the prefetching is allowed to grow the queues. The returned operation is a dequeue operation and will throw `tf.errors.OutOfRangeError` if the input queue is exhausted. If this operation is feeding another input queue, its queue runner will catch this exception, however, if this operation is used in your main thread you are responsible for catching this yourself. *N.B.:* If `dynamic_pad` is `False`, you must ensure that either (i) the `shapes` argument is passed, or (ii) all of the tensors in `tensors` must have fully-defined shapes. `ValueError` will be raised if neither of these conditions holds. If `dynamic_pad` is `True`, it is sufficient that the *rank* of the tensors is known, but individual dimensions may have shape `None`. In this case, for each enqueue the dimensions with value `None` may have a variable length; upon dequeue, the output tensors will be padded on the right to the maximum shape of the tensors in the current minibatch. For numbers, this padding takes value 0. For strings, this padding is the empty string. See `PaddingFIFOQueue` for more info. If `allow_smaller_final_batch` is `True`, a smaller batch value than `batch_size` is returned when the queue is closed and there are not enough elements to fill the batch, otherwise the pending elements are discarded. In addition, all output tensors' static shapes, as accessed via the `get_shape` method will have a first `Dimension` value of `None`, and operations that depend on fixed batch_size would fail. Args: tensors: The list or dictionary of tensors to enqueue. batch_size: The new batch size pulled from the queue. num_threads: The number of threads enqueuing `tensors`. The batching will be nondeterministic if `num_threads > 1`. capacity: An integer. The maximum number of elements in the queue. enqueue_many: Whether each tensor in `tensors` is a single example. shapes: (Optional) The shapes for each example. Defaults to the inferred shapes for `tensors`. dynamic_pad: Boolean. Allow variable dimensions in input shapes. The given dimensions are padded upon dequeue so that tensors within a batch have the same shapes. allow_smaller_final_batch: (Optional) Boolean. If `True`, allow the final batch to be smaller if there are insufficient items left in the queue. shared_name: (Optional). If set, this queue will be shared under the given name across multiple sessions. name: (Optional) A name for the operations. Returns: A list or dictionary of tensors with the same types as `tensors` (except if the input is a list of one element, then it returns a tensor, not a list). Raises: ValueError: If the `shapes` are not specified, and cannot be inferred from the elements of `tensors`.
Creates batches of tensors in `tensors`.
[ "Creates", "batches", "of", "tensors", "in", "tensors", "." ]
def batch(tensors, batch_size, num_threads=1, capacity=32, enqueue_many=False, shapes=None, dynamic_pad=False, allow_smaller_final_batch=False, shared_name=None, name=None): """Creates batches of tensors in `tensors`. The argument `tensors` can be a list or a dictionary of tensors. The value returned by the function will be of the same type as `tensors`. This function is implemented using a queue. A `QueueRunner` for the queue is added to the current `Graph`'s `QUEUE_RUNNER` collection. If `enqueue_many` is `False`, `tensors` is assumed to represent a single example. An input tensor with shape `[x, y, z]` will be output as a tensor with shape `[batch_size, x, y, z]`. If `enqueue_many` is `True`, `tensors` is assumed to represent a batch of examples, where the first dimension is indexed by example, and all members of `tensors` should have the same size in the first dimension. If an input tensor has shape `[*, x, y, z]`, the output will have shape `[batch_size, x, y, z]`. The `capacity` argument controls the how long the prefetching is allowed to grow the queues. The returned operation is a dequeue operation and will throw `tf.errors.OutOfRangeError` if the input queue is exhausted. If this operation is feeding another input queue, its queue runner will catch this exception, however, if this operation is used in your main thread you are responsible for catching this yourself. *N.B.:* If `dynamic_pad` is `False`, you must ensure that either (i) the `shapes` argument is passed, or (ii) all of the tensors in `tensors` must have fully-defined shapes. `ValueError` will be raised if neither of these conditions holds. If `dynamic_pad` is `True`, it is sufficient that the *rank* of the tensors is known, but individual dimensions may have shape `None`. In this case, for each enqueue the dimensions with value `None` may have a variable length; upon dequeue, the output tensors will be padded on the right to the maximum shape of the tensors in the current minibatch. For numbers, this padding takes value 0. For strings, this padding is the empty string. See `PaddingFIFOQueue` for more info. If `allow_smaller_final_batch` is `True`, a smaller batch value than `batch_size` is returned when the queue is closed and there are not enough elements to fill the batch, otherwise the pending elements are discarded. In addition, all output tensors' static shapes, as accessed via the `get_shape` method will have a first `Dimension` value of `None`, and operations that depend on fixed batch_size would fail. Args: tensors: The list or dictionary of tensors to enqueue. batch_size: The new batch size pulled from the queue. num_threads: The number of threads enqueuing `tensors`. The batching will be nondeterministic if `num_threads > 1`. capacity: An integer. The maximum number of elements in the queue. enqueue_many: Whether each tensor in `tensors` is a single example. shapes: (Optional) The shapes for each example. Defaults to the inferred shapes for `tensors`. dynamic_pad: Boolean. Allow variable dimensions in input shapes. The given dimensions are padded upon dequeue so that tensors within a batch have the same shapes. allow_smaller_final_batch: (Optional) Boolean. If `True`, allow the final batch to be smaller if there are insufficient items left in the queue. shared_name: (Optional). If set, this queue will be shared under the given name across multiple sessions. name: (Optional) A name for the operations. Returns: A list or dictionary of tensors with the same types as `tensors` (except if the input is a list of one element, then it returns a tensor, not a list). Raises: ValueError: If the `shapes` are not specified, and cannot be inferred from the elements of `tensors`. """ return _batch( tensors, batch_size, keep_input=True, num_threads=num_threads, capacity=capacity, enqueue_many=enqueue_many, shapes=shapes, dynamic_pad=dynamic_pad, allow_smaller_final_batch=allow_smaller_final_batch, shared_name=shared_name, name=name)
[ "def", "batch", "(", "tensors", ",", "batch_size", ",", "num_threads", "=", "1", ",", "capacity", "=", "32", ",", "enqueue_many", "=", "False", ",", "shapes", "=", "None", ",", "dynamic_pad", "=", "False", ",", "allow_smaller_final_batch", "=", "False", ",", "shared_name", "=", "None", ",", "name", "=", "None", ")", ":", "return", "_batch", "(", "tensors", ",", "batch_size", ",", "keep_input", "=", "True", ",", "num_threads", "=", "num_threads", ",", "capacity", "=", "capacity", ",", "enqueue_many", "=", "enqueue_many", ",", "shapes", "=", "shapes", ",", "dynamic_pad", "=", "dynamic_pad", ",", "allow_smaller_final_batch", "=", "allow_smaller_final_batch", ",", "shared_name", "=", "shared_name", ",", "name", "=", "name", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/training/input.py#L836-L922
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py
python
Wm.wm_geometry
(self, newGeometry=None)
return self.tk.call('wm', 'geometry', self._w, newGeometry)
Set geometry to NEWGEOMETRY of the form =widthxheight+x+y. Return current value if None is given.
Set geometry to NEWGEOMETRY of the form =widthxheight+x+y. Return current value if None is given.
[ "Set", "geometry", "to", "NEWGEOMETRY", "of", "the", "form", "=", "widthxheight", "+", "x", "+", "y", ".", "Return", "current", "value", "if", "None", "is", "given", "." ]
def wm_geometry(self, newGeometry=None): """Set geometry to NEWGEOMETRY of the form =widthxheight+x+y. Return current value if None is given.""" return self.tk.call('wm', 'geometry', self._w, newGeometry)
[ "def", "wm_geometry", "(", "self", ",", "newGeometry", "=", "None", ")", ":", "return", "self", ".", "tk", ".", "call", "(", "'wm'", ",", "'geometry'", ",", "self", ".", "_w", ",", "newGeometry", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py#L1838-L1841
mickem/nscp
79f89fdbb6da63f91bc9dedb7aea202fe938f237
scripts/python/lib/google/protobuf/service_reflection.py
python
GeneratedServiceStubType.__init__
(cls, name, bases, dictionary)
Creates a message service stub class. Args: name: Name of the class (ignored, here). bases: Base classes of the class being constructed. dictionary: The class dictionary of the class being constructed. dictionary[_DESCRIPTOR_KEY] must contain a ServiceDescriptor object describing this protocol service type.
Creates a message service stub class.
[ "Creates", "a", "message", "service", "stub", "class", "." ]
def __init__(cls, name, bases, dictionary): """Creates a message service stub class. Args: name: Name of the class (ignored, here). bases: Base classes of the class being constructed. dictionary: The class dictionary of the class being constructed. dictionary[_DESCRIPTOR_KEY] must contain a ServiceDescriptor object describing this protocol service type. """ super(GeneratedServiceStubType, cls).__init__(name, bases, dictionary) # Don't do anything if this class doesn't have a descriptor. This happens # when a service stub is subclassed. if GeneratedServiceStubType._DESCRIPTOR_KEY not in dictionary: return descriptor = dictionary[GeneratedServiceStubType._DESCRIPTOR_KEY] service_stub_builder = _ServiceStubBuilder(descriptor) service_stub_builder.BuildServiceStub(cls)
[ "def", "__init__", "(", "cls", ",", "name", ",", "bases", ",", "dictionary", ")", ":", "super", "(", "GeneratedServiceStubType", ",", "cls", ")", ".", "__init__", "(", "name", ",", "bases", ",", "dictionary", ")", "# Don't do anything if this class doesn't have a descriptor. This happens", "# when a service stub is subclassed.", "if", "GeneratedServiceStubType", ".", "_DESCRIPTOR_KEY", "not", "in", "dictionary", ":", "return", "descriptor", "=", "dictionary", "[", "GeneratedServiceStubType", ".", "_DESCRIPTOR_KEY", "]", "service_stub_builder", "=", "_ServiceStubBuilder", "(", "descriptor", ")", "service_stub_builder", ".", "BuildServiceStub", "(", "cls", ")" ]
https://github.com/mickem/nscp/blob/79f89fdbb6da63f91bc9dedb7aea202fe938f237/scripts/python/lib/google/protobuf/service_reflection.py#L94-L111
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/external/bazel_tools/third_party/py/gflags/__init__.py
python
FlagValues.UseGnuGetOpt
(self, use_gnu_getopt=True)
Use GNU-style scanning. Allows mixing of flag and non-flag arguments. See http://docs.python.org/library/getopt.html#getopt.gnu_getopt Args: use_gnu_getopt: wether or not to use GNU style scanning.
Use GNU-style scanning. Allows mixing of flag and non-flag arguments.
[ "Use", "GNU", "-", "style", "scanning", ".", "Allows", "mixing", "of", "flag", "and", "non", "-", "flag", "arguments", "." ]
def UseGnuGetOpt(self, use_gnu_getopt=True): """Use GNU-style scanning. Allows mixing of flag and non-flag arguments. See http://docs.python.org/library/getopt.html#getopt.gnu_getopt Args: use_gnu_getopt: wether or not to use GNU style scanning. """ self.__dict__['__use_gnu_getopt'] = use_gnu_getopt
[ "def", "UseGnuGetOpt", "(", "self", ",", "use_gnu_getopt", "=", "True", ")", ":", "self", ".", "__dict__", "[", "'__use_gnu_getopt'", "]", "=", "use_gnu_getopt" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/external/bazel_tools/third_party/py/gflags/__init__.py#L833-L841
SpenceKonde/megaTinyCore
1c4a70b18a149fe6bcb551dfa6db11ca50b8997b
megaavr/tools/libs/pymcuprog/nvmserialupdi.py
python
NvmAccessProviderSerial.stop
(self)
Stop the debugging session
Stop the debugging session
[ "Stop", "the", "debugging", "session" ]
def stop(self): """ Stop the debugging session """ if self.avr is not None: self.avr.leave_progmode()
[ "def", "stop", "(", "self", ")", ":", "if", "self", ".", "avr", "is", "not", "None", ":", "self", ".", "avr", ".", "leave_progmode", "(", ")" ]
https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/pymcuprog/nvmserialupdi.py#L245-L250
panda3d/panda3d
833ad89ebad58395d0af0b7ec08538e5e4308265
direct/src/directtools/DirectSelection.py
python
SelectedNodePaths.forEachSelectedNodePathDo
(self, func)
Perform given func on selected node paths. No node path connectivity verification performed
Perform given func on selected node paths. No node path connectivity verification performed
[ "Perform", "given", "func", "on", "selected", "node", "paths", ".", "No", "node", "path", "connectivity", "verification", "performed" ]
def forEachSelectedNodePathDo(self, func): """ Perform given func on selected node paths. No node path connectivity verification performed """ selectedNodePaths = self.getSelectedAsList() for nodePath in selectedNodePaths: func(nodePath)
[ "def", "forEachSelectedNodePathDo", "(", "self", ",", "func", ")", ":", "selectedNodePaths", "=", "self", ".", "getSelectedAsList", "(", ")", "for", "nodePath", "in", "selectedNodePaths", ":", "func", "(", "nodePath", ")" ]
https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/directtools/DirectSelection.py#L178-L185
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Path/PathScripts/PathAreaOp.py
python
ObjectOp.areaOpOnDocumentRestored
(self, obj)
areaOpOnDocumentRestored(obj) ... overwrite to fully restore receiver
areaOpOnDocumentRestored(obj) ... overwrite to fully restore receiver
[ "areaOpOnDocumentRestored", "(", "obj", ")", "...", "overwrite", "to", "fully", "restore", "receiver" ]
def areaOpOnDocumentRestored(self, obj): """areaOpOnDocumentRestored(obj) ... overwrite to fully restore receiver""" pass
[ "def", "areaOpOnDocumentRestored", "(", "self", ",", "obj", ")", ":", "pass" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Path/PathScripts/PathAreaOp.py#L172-L174
MythTV/mythtv
d282a209cb8be85d036f85a62a8ec971b67d45f4
mythplugins/mytharchive/mythburn/scripts/mythburn.py
python
createDVDAuthorXMLNoMainMenu
(screensize, numberofitems)
Creates the xml file for dvdauthor to use the MythBurn menus.
Creates the xml file for dvdauthor to use the MythBurn menus.
[ "Creates", "the", "xml", "file", "for", "dvdauthor", "to", "use", "the", "MythBurn", "menus", "." ]
def createDVDAuthorXMLNoMainMenu(screensize, numberofitems): """Creates the xml file for dvdauthor to use the MythBurn menus.""" # creates a simple DVD with only a chapter menus shown before each video # can contain an intro movie and each title can have a details page # displayed before each title write( "Creating DVD XML file for dvd author (No Main Menu)") #FIXME: assert False
[ "def", "createDVDAuthorXMLNoMainMenu", "(", "screensize", ",", "numberofitems", ")", ":", "# creates a simple DVD with only a chapter menus shown before each video", "# can contain an intro movie and each title can have a details page", "# displayed before each title", "write", "(", "\"Creating DVD XML file for dvd author (No Main Menu)\"", ")", "#FIXME:", "assert", "False" ]
https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythplugins/mytharchive/mythburn/scripts/mythburn.py#L3070-L3079
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/tseries/holiday.py
python
sunday_to_monday
(dt)
return dt
If holiday falls on Sunday, use day thereafter (Monday) instead.
If holiday falls on Sunday, use day thereafter (Monday) instead.
[ "If", "holiday", "falls", "on", "Sunday", "use", "day", "thereafter", "(", "Monday", ")", "instead", "." ]
def sunday_to_monday(dt): """ If holiday falls on Sunday, use day thereafter (Monday) instead. """ if dt.weekday() == 6: return dt + timedelta(1) return dt
[ "def", "sunday_to_monday", "(", "dt", ")", ":", "if", "dt", ".", "weekday", "(", ")", "==", "6", ":", "return", "dt", "+", "timedelta", "(", "1", ")", "return", "dt" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/tseries/holiday.py#L53-L59
microsoft/EdgeML
ef9f8a77f096acbdeb941014791f8eda1c1bc35b
examples/pytorch/vision/Face_Detection/models/RPool_Face_M4.py
python
S3FD.__init__
(self, phase, base, head, num_classes)
self.priorbox = PriorBox(size,cfg) self.priors = Variable(self.priorbox.forward(), volatile=True)
self.priorbox = PriorBox(size,cfg) self.priors = Variable(self.priorbox.forward(), volatile=True)
[ "self", ".", "priorbox", "=", "PriorBox", "(", "size", "cfg", ")", "self", ".", "priors", "=", "Variable", "(", "self", ".", "priorbox", ".", "forward", "()", "volatile", "=", "True", ")" ]
def __init__(self, phase, base, head, num_classes): super(S3FD, self).__init__() self.phase = phase self.num_classes = num_classes ''' self.priorbox = PriorBox(size,cfg) self.priors = Variable(self.priorbox.forward(), volatile=True) ''' # SSD network self.conv = ConvBNReLU(1, 4, stride=2) self.unfold = nn.Unfold(kernel_size=(8,8),stride=(4,4)) self.rnn_model = RNNPool(8, 8, 16, 16, 4, w1Sparsity=0.5, u1Sparsity=0.3, w2Sparsity=0.3, u2Sparsity=0.3) self.mob = nn.ModuleList(base) # Layer learns to scale the l2 normalized features from conv4_3 self.L2Norm3_3 = L2Norm(32, 10) self.L2Norm4_3 = L2Norm(32, 8) self.L2Norm5_3 = L2Norm(64, 5) self.loc = nn.ModuleList(head[0]) self.conf = nn.ModuleList(head[1]) if self.phase == 'test': self.softmax = nn.Softmax(dim=-1)
[ "def", "__init__", "(", "self", ",", "phase", ",", "base", ",", "head", ",", "num_classes", ")", ":", "super", "(", "S3FD", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "phase", "=", "phase", "self", ".", "num_classes", "=", "num_classes", "# SSD network", "self", ".", "conv", "=", "ConvBNReLU", "(", "1", ",", "4", ",", "stride", "=", "2", ")", "self", ".", "unfold", "=", "nn", ".", "Unfold", "(", "kernel_size", "=", "(", "8", ",", "8", ")", ",", "stride", "=", "(", "4", ",", "4", ")", ")", "self", ".", "rnn_model", "=", "RNNPool", "(", "8", ",", "8", ",", "16", ",", "16", ",", "4", ",", "w1Sparsity", "=", "0.5", ",", "u1Sparsity", "=", "0.3", ",", "w2Sparsity", "=", "0.3", ",", "u2Sparsity", "=", "0.3", ")", "self", ".", "mob", "=", "nn", ".", "ModuleList", "(", "base", ")", "# Layer learns to scale the l2 normalized features from conv4_3", "self", ".", "L2Norm3_3", "=", "L2Norm", "(", "32", ",", "10", ")", "self", ".", "L2Norm4_3", "=", "L2Norm", "(", "32", ",", "8", ")", "self", ".", "L2Norm5_3", "=", "L2Norm", "(", "64", ",", "5", ")", "self", ".", "loc", "=", "nn", ".", "ModuleList", "(", "head", "[", "0", "]", ")", "self", ".", "conf", "=", "nn", ".", "ModuleList", "(", "head", "[", "1", "]", ")", "if", "self", ".", "phase", "==", "'test'", ":", "self", ".", "softmax", "=", "nn", ".", "Softmax", "(", "dim", "=", "-", "1", ")" ]
https://github.com/microsoft/EdgeML/blob/ef9f8a77f096acbdeb941014791f8eda1c1bc35b/examples/pytorch/vision/Face_Detection/models/RPool_Face_M4.py#L38-L66
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/saved_model/builder_impl.py
python
copy_assets_to_destination_dir
(asset_filename_map, destination_dir)
Copy all assets from source path to destination path.
Copy all assets from source path to destination path.
[ "Copy", "all", "assets", "from", "source", "path", "to", "destination", "path", "." ]
def copy_assets_to_destination_dir(asset_filename_map, destination_dir): """Copy all assets from source path to destination path.""" assets_destination_dir = saved_model_utils.get_or_create_assets_dir( destination_dir) # Copy each asset from source path to destination path. for asset_basename, asset_source_filepath in asset_filename_map.items(): asset_destination_filepath = file_io.join( compat.as_bytes(assets_destination_dir), compat.as_bytes(asset_basename)) # Only copy the asset file to the destination if it does not already # exist. This is to ensure that an asset with the same name defined as # part of multiple graphs is only copied the first time. if not file_io.file_exists(asset_destination_filepath): file_io.copy(asset_source_filepath, asset_destination_filepath) tf_logging.info("Assets written to: %s", compat.as_text(assets_destination_dir))
[ "def", "copy_assets_to_destination_dir", "(", "asset_filename_map", ",", "destination_dir", ")", ":", "assets_destination_dir", "=", "saved_model_utils", ".", "get_or_create_assets_dir", "(", "destination_dir", ")", "# Copy each asset from source path to destination path.", "for", "asset_basename", ",", "asset_source_filepath", "in", "asset_filename_map", ".", "items", "(", ")", ":", "asset_destination_filepath", "=", "file_io", ".", "join", "(", "compat", ".", "as_bytes", "(", "assets_destination_dir", ")", ",", "compat", ".", "as_bytes", "(", "asset_basename", ")", ")", "# Only copy the asset file to the destination if it does not already", "# exist. This is to ensure that an asset with the same name defined as", "# part of multiple graphs is only copied the first time.", "if", "not", "file_io", ".", "file_exists", "(", "asset_destination_filepath", ")", ":", "file_io", ".", "copy", "(", "asset_source_filepath", ",", "asset_destination_filepath", ")", "tf_logging", ".", "info", "(", "\"Assets written to: %s\"", ",", "compat", ".", "as_text", "(", "assets_destination_dir", ")", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/saved_model/builder_impl.py#L762-L780
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/mapreduce/mapreduce/base_handler.py
python
TaskQueueHandler.task_retry_count
(self)
return int(self.request.headers.get("X-AppEngine-TaskExecutionCount", 0))
Number of times this task has been retried.
Number of times this task has been retried.
[ "Number", "of", "times", "this", "task", "has", "been", "retried", "." ]
def task_retry_count(self): """Number of times this task has been retried.""" return int(self.request.headers.get("X-AppEngine-TaskExecutionCount", 0))
[ "def", "task_retry_count", "(", "self", ")", ":", "return", "int", "(", "self", ".", "request", ".", "headers", ".", "get", "(", "\"X-AppEngine-TaskExecutionCount\"", ",", "0", ")", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/mapreduce/mapreduce/base_handler.py#L156-L158
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/generic.py
python
NDFrame.describe
( self: FrameOrSeries, percentiles=None, include=None, exclude=None )
return d
Generate descriptive statistics. Descriptive statistics include those that summarize the central tendency, dispersion and shape of a dataset's distribution, excluding ``NaN`` values. Analyzes both numeric and object series, as well as ``DataFrame`` column sets of mixed data types. The output will vary depending on what is provided. Refer to the notes below for more detail. Parameters ---------- percentiles : list-like of numbers, optional The percentiles to include in the output. All should fall between 0 and 1. The default is ``[.25, .5, .75]``, which returns the 25th, 50th, and 75th percentiles. include : 'all', list-like of dtypes or None (default), optional A white list of data types to include in the result. Ignored for ``Series``. Here are the options: - 'all' : All columns of the input will be included in the output. - A list-like of dtypes : Limits the results to the provided data types. To limit the result to numeric types submit ``numpy.number``. To limit it instead to object columns submit the ``numpy.object`` data type. Strings can also be used in the style of ``select_dtypes`` (e.g. ``df.describe(include=['O'])``). To select pandas categorical columns, use ``'category'`` - None (default) : The result will include all numeric columns. exclude : list-like of dtypes or None (default), optional, A black list of data types to omit from the result. Ignored for ``Series``. Here are the options: - A list-like of dtypes : Excludes the provided data types from the result. To exclude numeric types submit ``numpy.number``. To exclude object columns submit the data type ``numpy.object``. Strings can also be used in the style of ``select_dtypes`` (e.g. ``df.describe(include=['O'])``). To exclude pandas categorical columns, use ``'category'`` - None (default) : The result will exclude nothing. Returns ------- Series or DataFrame Summary statistics of the Series or Dataframe provided. See Also -------- DataFrame.count: Count number of non-NA/null observations. DataFrame.max: Maximum of the values in the object. DataFrame.min: Minimum of the values in the object. DataFrame.mean: Mean of the values. DataFrame.std: Standard deviation of the observations. DataFrame.select_dtypes: Subset of a DataFrame including/excluding columns based on their dtype. Notes ----- For numeric data, the result's index will include ``count``, ``mean``, ``std``, ``min``, ``max`` as well as lower, ``50`` and upper percentiles. By default the lower percentile is ``25`` and the upper percentile is ``75``. The ``50`` percentile is the same as the median. For object data (e.g. strings or timestamps), the result's index will include ``count``, ``unique``, ``top``, and ``freq``. The ``top`` is the most common value. The ``freq`` is the most common value's frequency. Timestamps also include the ``first`` and ``last`` items. If multiple object values have the highest count, then the ``count`` and ``top`` results will be arbitrarily chosen from among those with the highest count. For mixed data types provided via a ``DataFrame``, the default is to return only an analysis of numeric columns. If the dataframe consists only of object and categorical data without any numeric columns, the default is to return an analysis of both the object and categorical columns. If ``include='all'`` is provided as an option, the result will include a union of attributes of each type. The `include` and `exclude` parameters can be used to limit which columns in a ``DataFrame`` are analyzed for the output. The parameters are ignored when analyzing a ``Series``. Examples -------- Describing a numeric ``Series``. >>> s = pd.Series([1, 2, 3]) >>> s.describe() count 3.0 mean 2.0 std 1.0 min 1.0 25% 1.5 50% 2.0 75% 2.5 max 3.0 dtype: float64 Describing a categorical ``Series``. >>> s = pd.Series(['a', 'a', 'b', 'c']) >>> s.describe() count 4 unique 3 top a freq 2 dtype: object Describing a timestamp ``Series``. >>> s = pd.Series([ ... np.datetime64("2000-01-01"), ... np.datetime64("2010-01-01"), ... np.datetime64("2010-01-01") ... ]) >>> s.describe() count 3 unique 2 top 2010-01-01 00:00:00 freq 2 first 2000-01-01 00:00:00 last 2010-01-01 00:00:00 dtype: object Describing a ``DataFrame``. By default only numeric fields are returned. >>> df = pd.DataFrame({'categorical': pd.Categorical(['d','e','f']), ... 'numeric': [1, 2, 3], ... 'object': ['a', 'b', 'c'] ... }) >>> df.describe() numeric count 3.0 mean 2.0 std 1.0 min 1.0 25% 1.5 50% 2.0 75% 2.5 max 3.0 Describing all columns of a ``DataFrame`` regardless of data type. >>> df.describe(include='all') categorical numeric object count 3 3.0 3 unique 3 NaN 3 top f NaN c freq 1 NaN 1 mean NaN 2.0 NaN std NaN 1.0 NaN min NaN 1.0 NaN 25% NaN 1.5 NaN 50% NaN 2.0 NaN 75% NaN 2.5 NaN max NaN 3.0 NaN Describing a column from a ``DataFrame`` by accessing it as an attribute. >>> df.numeric.describe() count 3.0 mean 2.0 std 1.0 min 1.0 25% 1.5 50% 2.0 75% 2.5 max 3.0 Name: numeric, dtype: float64 Including only numeric columns in a ``DataFrame`` description. >>> df.describe(include=[np.number]) numeric count 3.0 mean 2.0 std 1.0 min 1.0 25% 1.5 50% 2.0 75% 2.5 max 3.0 Including only string columns in a ``DataFrame`` description. >>> df.describe(include=[np.object]) object count 3 unique 3 top c freq 1 Including only categorical columns from a ``DataFrame`` description. >>> df.describe(include=['category']) categorical count 3 unique 3 top f freq 1 Excluding numeric columns from a ``DataFrame`` description. >>> df.describe(exclude=[np.number]) categorical object count 3 3 unique 3 3 top f c freq 1 1 Excluding object columns from a ``DataFrame`` description. >>> df.describe(exclude=[np.object]) categorical numeric count 3 3.0 unique 3 NaN top f NaN freq 1 NaN mean NaN 2.0 std NaN 1.0 min NaN 1.0 25% NaN 1.5 50% NaN 2.0 75% NaN 2.5 max NaN 3.0
Generate descriptive statistics.
[ "Generate", "descriptive", "statistics", "." ]
def describe( self: FrameOrSeries, percentiles=None, include=None, exclude=None ) -> FrameOrSeries: """ Generate descriptive statistics. Descriptive statistics include those that summarize the central tendency, dispersion and shape of a dataset's distribution, excluding ``NaN`` values. Analyzes both numeric and object series, as well as ``DataFrame`` column sets of mixed data types. The output will vary depending on what is provided. Refer to the notes below for more detail. Parameters ---------- percentiles : list-like of numbers, optional The percentiles to include in the output. All should fall between 0 and 1. The default is ``[.25, .5, .75]``, which returns the 25th, 50th, and 75th percentiles. include : 'all', list-like of dtypes or None (default), optional A white list of data types to include in the result. Ignored for ``Series``. Here are the options: - 'all' : All columns of the input will be included in the output. - A list-like of dtypes : Limits the results to the provided data types. To limit the result to numeric types submit ``numpy.number``. To limit it instead to object columns submit the ``numpy.object`` data type. Strings can also be used in the style of ``select_dtypes`` (e.g. ``df.describe(include=['O'])``). To select pandas categorical columns, use ``'category'`` - None (default) : The result will include all numeric columns. exclude : list-like of dtypes or None (default), optional, A black list of data types to omit from the result. Ignored for ``Series``. Here are the options: - A list-like of dtypes : Excludes the provided data types from the result. To exclude numeric types submit ``numpy.number``. To exclude object columns submit the data type ``numpy.object``. Strings can also be used in the style of ``select_dtypes`` (e.g. ``df.describe(include=['O'])``). To exclude pandas categorical columns, use ``'category'`` - None (default) : The result will exclude nothing. Returns ------- Series or DataFrame Summary statistics of the Series or Dataframe provided. See Also -------- DataFrame.count: Count number of non-NA/null observations. DataFrame.max: Maximum of the values in the object. DataFrame.min: Minimum of the values in the object. DataFrame.mean: Mean of the values. DataFrame.std: Standard deviation of the observations. DataFrame.select_dtypes: Subset of a DataFrame including/excluding columns based on their dtype. Notes ----- For numeric data, the result's index will include ``count``, ``mean``, ``std``, ``min``, ``max`` as well as lower, ``50`` and upper percentiles. By default the lower percentile is ``25`` and the upper percentile is ``75``. The ``50`` percentile is the same as the median. For object data (e.g. strings or timestamps), the result's index will include ``count``, ``unique``, ``top``, and ``freq``. The ``top`` is the most common value. The ``freq`` is the most common value's frequency. Timestamps also include the ``first`` and ``last`` items. If multiple object values have the highest count, then the ``count`` and ``top`` results will be arbitrarily chosen from among those with the highest count. For mixed data types provided via a ``DataFrame``, the default is to return only an analysis of numeric columns. If the dataframe consists only of object and categorical data without any numeric columns, the default is to return an analysis of both the object and categorical columns. If ``include='all'`` is provided as an option, the result will include a union of attributes of each type. The `include` and `exclude` parameters can be used to limit which columns in a ``DataFrame`` are analyzed for the output. The parameters are ignored when analyzing a ``Series``. Examples -------- Describing a numeric ``Series``. >>> s = pd.Series([1, 2, 3]) >>> s.describe() count 3.0 mean 2.0 std 1.0 min 1.0 25% 1.5 50% 2.0 75% 2.5 max 3.0 dtype: float64 Describing a categorical ``Series``. >>> s = pd.Series(['a', 'a', 'b', 'c']) >>> s.describe() count 4 unique 3 top a freq 2 dtype: object Describing a timestamp ``Series``. >>> s = pd.Series([ ... np.datetime64("2000-01-01"), ... np.datetime64("2010-01-01"), ... np.datetime64("2010-01-01") ... ]) >>> s.describe() count 3 unique 2 top 2010-01-01 00:00:00 freq 2 first 2000-01-01 00:00:00 last 2010-01-01 00:00:00 dtype: object Describing a ``DataFrame``. By default only numeric fields are returned. >>> df = pd.DataFrame({'categorical': pd.Categorical(['d','e','f']), ... 'numeric': [1, 2, 3], ... 'object': ['a', 'b', 'c'] ... }) >>> df.describe() numeric count 3.0 mean 2.0 std 1.0 min 1.0 25% 1.5 50% 2.0 75% 2.5 max 3.0 Describing all columns of a ``DataFrame`` regardless of data type. >>> df.describe(include='all') categorical numeric object count 3 3.0 3 unique 3 NaN 3 top f NaN c freq 1 NaN 1 mean NaN 2.0 NaN std NaN 1.0 NaN min NaN 1.0 NaN 25% NaN 1.5 NaN 50% NaN 2.0 NaN 75% NaN 2.5 NaN max NaN 3.0 NaN Describing a column from a ``DataFrame`` by accessing it as an attribute. >>> df.numeric.describe() count 3.0 mean 2.0 std 1.0 min 1.0 25% 1.5 50% 2.0 75% 2.5 max 3.0 Name: numeric, dtype: float64 Including only numeric columns in a ``DataFrame`` description. >>> df.describe(include=[np.number]) numeric count 3.0 mean 2.0 std 1.0 min 1.0 25% 1.5 50% 2.0 75% 2.5 max 3.0 Including only string columns in a ``DataFrame`` description. >>> df.describe(include=[np.object]) object count 3 unique 3 top c freq 1 Including only categorical columns from a ``DataFrame`` description. >>> df.describe(include=['category']) categorical count 3 unique 3 top f freq 1 Excluding numeric columns from a ``DataFrame`` description. >>> df.describe(exclude=[np.number]) categorical object count 3 3 unique 3 3 top f c freq 1 1 Excluding object columns from a ``DataFrame`` description. >>> df.describe(exclude=[np.object]) categorical numeric count 3 3.0 unique 3 NaN top f NaN freq 1 NaN mean NaN 2.0 std NaN 1.0 min NaN 1.0 25% NaN 1.5 50% NaN 2.0 75% NaN 2.5 max NaN 3.0 """ if self.ndim == 2 and self.columns.size == 0: raise ValueError("Cannot describe a DataFrame without columns") if percentiles is not None: # explicit conversion of `percentiles` to list percentiles = list(percentiles) # get them all to be in [0, 1] validate_percentile(percentiles) # median should always be included if 0.5 not in percentiles: percentiles.append(0.5) percentiles = np.asarray(percentiles) else: percentiles = np.array([0.25, 0.5, 0.75]) # sort and check for duplicates unique_pcts = np.unique(percentiles) if len(unique_pcts) < len(percentiles): raise ValueError("percentiles cannot contain duplicates") percentiles = unique_pcts formatted_percentiles = format_percentiles(percentiles) def describe_numeric_1d(series): stat_index = ( ["count", "mean", "std", "min"] + formatted_percentiles + ["max"] ) d = ( [series.count(), series.mean(), series.std(), series.min()] + series.quantile(percentiles).tolist() + [series.max()] ) return pd.Series(d, index=stat_index, name=series.name) def describe_categorical_1d(data): names = ["count", "unique"] objcounts = data.value_counts() count_unique = len(objcounts[objcounts != 0]) result = [data.count(), count_unique] dtype = None if result[1] > 0: top, freq = objcounts.index[0], objcounts.iloc[0] if is_datetime64_any_dtype(data): tz = data.dt.tz asint = data.dropna().values.view("i8") top = Timestamp(top) if top.tzinfo is not None and tz is not None: # Don't tz_localize(None) if key is already tz-aware top = top.tz_convert(tz) else: top = top.tz_localize(tz) names += ["top", "freq", "first", "last"] result += [ top, freq, Timestamp(asint.min(), tz=tz), Timestamp(asint.max(), tz=tz), ] else: names += ["top", "freq"] result += [top, freq] # If the DataFrame is empty, set 'top' and 'freq' to None # to maintain output shape consistency else: names += ["top", "freq"] result += [np.nan, np.nan] dtype = "object" return pd.Series(result, index=names, name=data.name, dtype=dtype) def describe_1d(data): if is_bool_dtype(data): return describe_categorical_1d(data) elif is_numeric_dtype(data): return describe_numeric_1d(data) elif is_timedelta64_dtype(data): return describe_numeric_1d(data) else: return describe_categorical_1d(data) if self.ndim == 1: return describe_1d(self) elif (include is None) and (exclude is None): # when some numerics are found, keep only numerics data = self.select_dtypes(include=[np.number]) if len(data.columns) == 0: data = self elif include == "all": if exclude is not None: msg = "exclude must be None when include is 'all'" raise ValueError(msg) data = self else: data = self.select_dtypes(include=include, exclude=exclude) ldesc = [describe_1d(s) for _, s in data.items()] # set a convenient order for rows names: List[Optional[Hashable]] = [] ldesc_indexes = sorted((x.index for x in ldesc), key=len) for idxnames in ldesc_indexes: for name in idxnames: if name not in names: names.append(name) d = pd.concat([x.reindex(names, copy=False) for x in ldesc], axis=1, sort=False) d.columns = data.columns.copy() return d
[ "def", "describe", "(", "self", ":", "FrameOrSeries", ",", "percentiles", "=", "None", ",", "include", "=", "None", ",", "exclude", "=", "None", ")", "->", "FrameOrSeries", ":", "if", "self", ".", "ndim", "==", "2", "and", "self", ".", "columns", ".", "size", "==", "0", ":", "raise", "ValueError", "(", "\"Cannot describe a DataFrame without columns\"", ")", "if", "percentiles", "is", "not", "None", ":", "# explicit conversion of `percentiles` to list", "percentiles", "=", "list", "(", "percentiles", ")", "# get them all to be in [0, 1]", "validate_percentile", "(", "percentiles", ")", "# median should always be included", "if", "0.5", "not", "in", "percentiles", ":", "percentiles", ".", "append", "(", "0.5", ")", "percentiles", "=", "np", ".", "asarray", "(", "percentiles", ")", "else", ":", "percentiles", "=", "np", ".", "array", "(", "[", "0.25", ",", "0.5", ",", "0.75", "]", ")", "# sort and check for duplicates", "unique_pcts", "=", "np", ".", "unique", "(", "percentiles", ")", "if", "len", "(", "unique_pcts", ")", "<", "len", "(", "percentiles", ")", ":", "raise", "ValueError", "(", "\"percentiles cannot contain duplicates\"", ")", "percentiles", "=", "unique_pcts", "formatted_percentiles", "=", "format_percentiles", "(", "percentiles", ")", "def", "describe_numeric_1d", "(", "series", ")", ":", "stat_index", "=", "(", "[", "\"count\"", ",", "\"mean\"", ",", "\"std\"", ",", "\"min\"", "]", "+", "formatted_percentiles", "+", "[", "\"max\"", "]", ")", "d", "=", "(", "[", "series", ".", "count", "(", ")", ",", "series", ".", "mean", "(", ")", ",", "series", ".", "std", "(", ")", ",", "series", ".", "min", "(", ")", "]", "+", "series", ".", "quantile", "(", "percentiles", ")", ".", "tolist", "(", ")", "+", "[", "series", ".", "max", "(", ")", "]", ")", "return", "pd", ".", "Series", "(", "d", ",", "index", "=", "stat_index", ",", "name", "=", "series", ".", "name", ")", "def", "describe_categorical_1d", "(", "data", ")", ":", "names", "=", "[", "\"count\"", ",", "\"unique\"", "]", "objcounts", "=", "data", ".", "value_counts", "(", ")", "count_unique", "=", "len", "(", "objcounts", "[", "objcounts", "!=", "0", "]", ")", "result", "=", "[", "data", ".", "count", "(", ")", ",", "count_unique", "]", "dtype", "=", "None", "if", "result", "[", "1", "]", ">", "0", ":", "top", ",", "freq", "=", "objcounts", ".", "index", "[", "0", "]", ",", "objcounts", ".", "iloc", "[", "0", "]", "if", "is_datetime64_any_dtype", "(", "data", ")", ":", "tz", "=", "data", ".", "dt", ".", "tz", "asint", "=", "data", ".", "dropna", "(", ")", ".", "values", ".", "view", "(", "\"i8\"", ")", "top", "=", "Timestamp", "(", "top", ")", "if", "top", ".", "tzinfo", "is", "not", "None", "and", "tz", "is", "not", "None", ":", "# Don't tz_localize(None) if key is already tz-aware", "top", "=", "top", ".", "tz_convert", "(", "tz", ")", "else", ":", "top", "=", "top", ".", "tz_localize", "(", "tz", ")", "names", "+=", "[", "\"top\"", ",", "\"freq\"", ",", "\"first\"", ",", "\"last\"", "]", "result", "+=", "[", "top", ",", "freq", ",", "Timestamp", "(", "asint", ".", "min", "(", ")", ",", "tz", "=", "tz", ")", ",", "Timestamp", "(", "asint", ".", "max", "(", ")", ",", "tz", "=", "tz", ")", ",", "]", "else", ":", "names", "+=", "[", "\"top\"", ",", "\"freq\"", "]", "result", "+=", "[", "top", ",", "freq", "]", "# If the DataFrame is empty, set 'top' and 'freq' to None", "# to maintain output shape consistency", "else", ":", "names", "+=", "[", "\"top\"", ",", "\"freq\"", "]", "result", "+=", "[", "np", ".", "nan", ",", "np", ".", "nan", "]", "dtype", "=", "\"object\"", "return", "pd", ".", "Series", "(", "result", ",", "index", "=", "names", ",", "name", "=", "data", ".", "name", ",", "dtype", "=", "dtype", ")", "def", "describe_1d", "(", "data", ")", ":", "if", "is_bool_dtype", "(", "data", ")", ":", "return", "describe_categorical_1d", "(", "data", ")", "elif", "is_numeric_dtype", "(", "data", ")", ":", "return", "describe_numeric_1d", "(", "data", ")", "elif", "is_timedelta64_dtype", "(", "data", ")", ":", "return", "describe_numeric_1d", "(", "data", ")", "else", ":", "return", "describe_categorical_1d", "(", "data", ")", "if", "self", ".", "ndim", "==", "1", ":", "return", "describe_1d", "(", "self", ")", "elif", "(", "include", "is", "None", ")", "and", "(", "exclude", "is", "None", ")", ":", "# when some numerics are found, keep only numerics", "data", "=", "self", ".", "select_dtypes", "(", "include", "=", "[", "np", ".", "number", "]", ")", "if", "len", "(", "data", ".", "columns", ")", "==", "0", ":", "data", "=", "self", "elif", "include", "==", "\"all\"", ":", "if", "exclude", "is", "not", "None", ":", "msg", "=", "\"exclude must be None when include is 'all'\"", "raise", "ValueError", "(", "msg", ")", "data", "=", "self", "else", ":", "data", "=", "self", ".", "select_dtypes", "(", "include", "=", "include", ",", "exclude", "=", "exclude", ")", "ldesc", "=", "[", "describe_1d", "(", "s", ")", "for", "_", ",", "s", "in", "data", ".", "items", "(", ")", "]", "# set a convenient order for rows", "names", ":", "List", "[", "Optional", "[", "Hashable", "]", "]", "=", "[", "]", "ldesc_indexes", "=", "sorted", "(", "(", "x", ".", "index", "for", "x", "in", "ldesc", ")", ",", "key", "=", "len", ")", "for", "idxnames", "in", "ldesc_indexes", ":", "for", "name", "in", "idxnames", ":", "if", "name", "not", "in", "names", ":", "names", ".", "append", "(", "name", ")", "d", "=", "pd", ".", "concat", "(", "[", "x", ".", "reindex", "(", "names", ",", "copy", "=", "False", ")", "for", "x", "in", "ldesc", "]", ",", "axis", "=", "1", ",", "sort", "=", "False", ")", "d", ".", "columns", "=", "data", ".", "columns", ".", "copy", "(", ")", "return", "d" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/generic.py#L9602-L9949
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/multiclass.py
python
OutputCodeClassifier.predict
(self, X)
return self.classes_[pred]
Predict multi-class targets using underlying estimators. Parameters ---------- X : (sparse) array-like of shape (n_samples, n_features) Data. Returns ------- y : numpy array of shape [n_samples] Predicted multi-class targets.
Predict multi-class targets using underlying estimators.
[ "Predict", "multi", "-", "class", "targets", "using", "underlying", "estimators", "." ]
def predict(self, X): """Predict multi-class targets using underlying estimators. Parameters ---------- X : (sparse) array-like of shape (n_samples, n_features) Data. Returns ------- y : numpy array of shape [n_samples] Predicted multi-class targets. """ check_is_fitted(self) X = check_array(X) Y = np.array([_predict_binary(e, X) for e in self.estimators_]).T pred = euclidean_distances(Y, self.code_book_).argmin(axis=1) return self.classes_[pred]
[ "def", "predict", "(", "self", ",", "X", ")", ":", "check_is_fitted", "(", "self", ")", "X", "=", "check_array", "(", "X", ")", "Y", "=", "np", ".", "array", "(", "[", "_predict_binary", "(", "e", ",", "X", ")", "for", "e", "in", "self", ".", "estimators_", "]", ")", ".", "T", "pred", "=", "euclidean_distances", "(", "Y", ",", "self", ".", "code_book_", ")", ".", "argmin", "(", "axis", "=", "1", ")", "return", "self", ".", "classes_", "[", "pred", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/multiclass.py#L799-L816
openvinotoolkit/openvino
dedcbeafa8b84cccdc55ca64b8da516682b381c7
tools/pot/openvino/tools/pot/algorithms/quantization/fake_quantize_configuration.py
python
add_range_estimator_configs
(fq_to_hw_confs, config)
return fq_to_hw_confs
Expand fake quantize configuration with range_estimator config :param fq_to_hw_confs: dictionary with fake quantize names as keys and its configurations as values :param config: tool config used to create range_estimator config :return dictionary with fake quantize nodes names as keys and its configurations as values extended with range_estimator config
Expand fake quantize configuration with range_estimator config :param fq_to_hw_confs: dictionary with fake quantize names as keys and its configurations as values :param config: tool config used to create range_estimator config :return dictionary with fake quantize nodes names as keys and its configurations as values extended with range_estimator config
[ "Expand", "fake", "quantize", "configuration", "with", "range_estimator", "config", ":", "param", "fq_to_hw_confs", ":", "dictionary", "with", "fake", "quantize", "names", "as", "keys", "and", "its", "configurations", "as", "values", ":", "param", "config", ":", "tool", "config", "used", "to", "create", "range_estimator", "config", ":", "return", "dictionary", "with", "fake", "quantize", "nodes", "names", "as", "keys", "and", "its", "configurations", "as", "values", "extended", "with", "range_estimator", "config" ]
def add_range_estimator_configs(fq_to_hw_confs, config): """ Expand fake quantize configuration with range_estimator config :param fq_to_hw_confs: dictionary with fake quantize names as keys and its configurations as values :param config: tool config used to create range_estimator config :return dictionary with fake quantize nodes names as keys and its configurations as values extended with range_estimator config""" for confs in fq_to_hw_confs.values(): for i_type, conf in confs.items(): conf['range_estimator'] = get_range_estimator_config(config, i_type, conf['granularity'], conf['mode']) return fq_to_hw_confs
[ "def", "add_range_estimator_configs", "(", "fq_to_hw_confs", ",", "config", ")", ":", "for", "confs", "in", "fq_to_hw_confs", ".", "values", "(", ")", ":", "for", "i_type", ",", "conf", "in", "confs", ".", "items", "(", ")", ":", "conf", "[", "'range_estimator'", "]", "=", "get_range_estimator_config", "(", "config", ",", "i_type", ",", "conf", "[", "'granularity'", "]", ",", "conf", "[", "'mode'", "]", ")", "return", "fq_to_hw_confs" ]
https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/pot/openvino/tools/pot/algorithms/quantization/fake_quantize_configuration.py#L156-L165
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/data_flow_ops.py
python
MapStagingArea.clear
(self, name=None)
return self._clear_fn( shared_name=self._name, name=name, dtypes=self._dtypes, capacity=self._capacity, memory_limit=self._memory_limit)
Clears the staging area. Args: name: A name for the operation (optional) Returns: The created op
Clears the staging area.
[ "Clears", "the", "staging", "area", "." ]
def clear(self, name=None): """Clears the staging area. Args: name: A name for the operation (optional) Returns: The created op """ if name is None: name = "%s_clear" % self._name return self._clear_fn( shared_name=self._name, name=name, dtypes=self._dtypes, capacity=self._capacity, memory_limit=self._memory_limit)
[ "def", "clear", "(", "self", ",", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "\"%s_clear\"", "%", "self", ".", "_name", "return", "self", ".", "_clear_fn", "(", "shared_name", "=", "self", ".", "_name", ",", "name", "=", "name", ",", "dtypes", "=", "self", ".", "_dtypes", ",", "capacity", "=", "self", ".", "_capacity", ",", "memory_limit", "=", "self", ".", "_memory_limit", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/data_flow_ops.py#L2411-L2428
omnisci/omniscidb
b9c95f1bd602b4ffc8b0edf18bfad61031e08d86
QueryEngine/scripts/generate_TableFunctionsFactory_init.py
python
Parser.parse_template
(self)
return TemplateNode(key, tuple(types))
fmt: off template: IDENTIFIER "=" "[" IDENTIFIER ("," IDENTIFIER)* "]" fmt: on
fmt: off
[ "fmt", ":", "off" ]
def parse_template(self): """fmt: off template: IDENTIFIER "=" "[" IDENTIFIER ("," IDENTIFIER)* "]" fmt: on """ key = self.parse_identifier() types = [] self.consume(Token.EQUAL) self.consume(Token.LSQB) types.append(self.parse_identifier()) while self.match(Token.COMMA): self.consume(Token.COMMA) types.append(self.parse_identifier()) self.consume(Token.RSQB) return TemplateNode(key, tuple(types))
[ "def", "parse_template", "(", "self", ")", ":", "key", "=", "self", ".", "parse_identifier", "(", ")", "types", "=", "[", "]", "self", ".", "consume", "(", "Token", ".", "EQUAL", ")", "self", ".", "consume", "(", "Token", ".", "LSQB", ")", "types", ".", "append", "(", "self", ".", "parse_identifier", "(", ")", ")", "while", "self", ".", "match", "(", "Token", ".", "COMMA", ")", ":", "self", ".", "consume", "(", "Token", ".", "COMMA", ")", "types", ".", "append", "(", "self", ".", "parse_identifier", "(", ")", ")", "self", ".", "consume", "(", "Token", ".", "RSQB", ")", "return", "TemplateNode", "(", "key", ",", "tuple", "(", "types", ")", ")" ]
https://github.com/omnisci/omniscidb/blob/b9c95f1bd602b4ffc8b0edf18bfad61031e08d86/QueryEngine/scripts/generate_TableFunctionsFactory_init.py#L1459-L1475
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/plugins/algorithms/ExportExperimentLog.py
python
ExportExperimentLog._processInputs
(self)
return
Process input properties
Process input properties
[ "Process", "input", "properties" ]
def _processInputs(self): """ Process input properties """ self._wksp = self.getProperty("InputWorkspace").value self._logfilename = self.getProperty("OutputFilename").value # Field and keys self._headerTitles = self.getProperty("SampleLogTitles").value self._sampleLogNames = self.getProperty("SampleLogNames").value ops = self.getProperty("SampleLogOperation").value if len(self._sampleLogNames) != len(ops): raise RuntimeError("Size of sample log names and sample operations are unequal!") self._sampleLogOperations = [] for i in range(len(self._sampleLogNames)): value = ops[i] self._sampleLogOperations.append(value) # ENDFOR if len(self._headerTitles) > 0 and len(self._headerTitles) != len(self._sampleLogNames): raise RuntimeError("Input header titles have a different length to sample log names") # Output file format self._fileformat = self.getProperty("FileFormat").value if self._fileformat == "tab": self._valuesep = "\t" else: self._valuesep = "," # Output file's postfix if self._fileformat == "comma (csv)": fileName, fileExtension = os.path.splitext(self._logfilename) if fileExtension != ".csv": # Force the extension of the output file to be .csv self._logfilename = "%s.csv" % (fileName) # Determine file mode if os.path.exists(self._logfilename) is False: self._filemode = "new" if len(self._headerTitles) == 0: raise RuntimeError("Without specifying header title, unable to new a file.") self.log().debug("Log file %s does not exist. So file mode is NEW." % (self._logfilename)) else: self._filemode = self.getProperty("FileMode").value self.log().debug("FileMode is from user specified value.") # Examine the file mode if self._filemode == "new" or self._filemode == "append": if len(self._headerTitles) != len(self._sampleLogNames): raise RuntimeError("In mode new or append, there must be same number of sample titles and names") self.log().information("File mode is %s. " % (self._filemode)) # This is left for a feature that might be needed in future. self._reorderOld = False self._timezone = self.getProperty("TimeZone").value # Determine whether output log-record file should be ordered by value of some log self._orderRecord = False self._titleToOrder = None if self._filemode != "new": ordertitle = self.getProperty("OrderByTitle").value if ordertitle in self._headerTitles: self._orderRecord = True self._removeDupRecord = self.getProperty("RemoveDuplicateRecord").value self.titleToOrder = ordertitle else: self.log().warning("Specified title to order by (%s) is not in given log titles." % (ordertitle)) if self._orderRecord is False: self._removeDupRecord = False # Override log values: it will not work in fastappend mode to override overridelist = self.getProperty("OverrideLogValue").value if len(self._headerTitles) > 0: if len(overridelist) % 2 != 0: raise RuntimeError("Number of items in OverrideLogValue must be even.") self._ovrdTitleValueDict = {} for i in range(int(len(overridelist)/2)): title = overridelist[2*i] if title in self._headerTitles: self._ovrdTitleValueDict[title] = overridelist[2*i+1] else: self.log().warning("Override title %s is not recognized. " % (title)) return
[ "def", "_processInputs", "(", "self", ")", ":", "self", ".", "_wksp", "=", "self", ".", "getProperty", "(", "\"InputWorkspace\"", ")", ".", "value", "self", ".", "_logfilename", "=", "self", ".", "getProperty", "(", "\"OutputFilename\"", ")", ".", "value", "# Field and keys", "self", ".", "_headerTitles", "=", "self", ".", "getProperty", "(", "\"SampleLogTitles\"", ")", ".", "value", "self", ".", "_sampleLogNames", "=", "self", ".", "getProperty", "(", "\"SampleLogNames\"", ")", ".", "value", "ops", "=", "self", ".", "getProperty", "(", "\"SampleLogOperation\"", ")", ".", "value", "if", "len", "(", "self", ".", "_sampleLogNames", ")", "!=", "len", "(", "ops", ")", ":", "raise", "RuntimeError", "(", "\"Size of sample log names and sample operations are unequal!\"", ")", "self", ".", "_sampleLogOperations", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "self", ".", "_sampleLogNames", ")", ")", ":", "value", "=", "ops", "[", "i", "]", "self", ".", "_sampleLogOperations", ".", "append", "(", "value", ")", "# ENDFOR", "if", "len", "(", "self", ".", "_headerTitles", ")", ">", "0", "and", "len", "(", "self", ".", "_headerTitles", ")", "!=", "len", "(", "self", ".", "_sampleLogNames", ")", ":", "raise", "RuntimeError", "(", "\"Input header titles have a different length to sample log names\"", ")", "# Output file format", "self", ".", "_fileformat", "=", "self", ".", "getProperty", "(", "\"FileFormat\"", ")", ".", "value", "if", "self", ".", "_fileformat", "==", "\"tab\"", ":", "self", ".", "_valuesep", "=", "\"\\t\"", "else", ":", "self", ".", "_valuesep", "=", "\",\"", "# Output file's postfix", "if", "self", ".", "_fileformat", "==", "\"comma (csv)\"", ":", "fileName", ",", "fileExtension", "=", "os", ".", "path", ".", "splitext", "(", "self", ".", "_logfilename", ")", "if", "fileExtension", "!=", "\".csv\"", ":", "# Force the extension of the output file to be .csv", "self", ".", "_logfilename", "=", "\"%s.csv\"", "%", "(", "fileName", ")", "# Determine file mode", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "_logfilename", ")", "is", "False", ":", "self", ".", "_filemode", "=", "\"new\"", "if", "len", "(", "self", ".", "_headerTitles", ")", "==", "0", ":", "raise", "RuntimeError", "(", "\"Without specifying header title, unable to new a file.\"", ")", "self", ".", "log", "(", ")", ".", "debug", "(", "\"Log file %s does not exist. So file mode is NEW.\"", "%", "(", "self", ".", "_logfilename", ")", ")", "else", ":", "self", ".", "_filemode", "=", "self", ".", "getProperty", "(", "\"FileMode\"", ")", ".", "value", "self", ".", "log", "(", ")", ".", "debug", "(", "\"FileMode is from user specified value.\"", ")", "# Examine the file mode", "if", "self", ".", "_filemode", "==", "\"new\"", "or", "self", ".", "_filemode", "==", "\"append\"", ":", "if", "len", "(", "self", ".", "_headerTitles", ")", "!=", "len", "(", "self", ".", "_sampleLogNames", ")", ":", "raise", "RuntimeError", "(", "\"In mode new or append, there must be same number of sample titles and names\"", ")", "self", ".", "log", "(", ")", ".", "information", "(", "\"File mode is %s. \"", "%", "(", "self", ".", "_filemode", ")", ")", "# This is left for a feature that might be needed in future.", "self", ".", "_reorderOld", "=", "False", "self", ".", "_timezone", "=", "self", ".", "getProperty", "(", "\"TimeZone\"", ")", ".", "value", "# Determine whether output log-record file should be ordered by value of some log", "self", ".", "_orderRecord", "=", "False", "self", ".", "_titleToOrder", "=", "None", "if", "self", ".", "_filemode", "!=", "\"new\"", ":", "ordertitle", "=", "self", ".", "getProperty", "(", "\"OrderByTitle\"", ")", ".", "value", "if", "ordertitle", "in", "self", ".", "_headerTitles", ":", "self", ".", "_orderRecord", "=", "True", "self", ".", "_removeDupRecord", "=", "self", ".", "getProperty", "(", "\"RemoveDuplicateRecord\"", ")", ".", "value", "self", ".", "titleToOrder", "=", "ordertitle", "else", ":", "self", ".", "log", "(", ")", ".", "warning", "(", "\"Specified title to order by (%s) is not in given log titles.\"", "%", "(", "ordertitle", ")", ")", "if", "self", ".", "_orderRecord", "is", "False", ":", "self", ".", "_removeDupRecord", "=", "False", "# Override log values: it will not work in fastappend mode to override", "overridelist", "=", "self", ".", "getProperty", "(", "\"OverrideLogValue\"", ")", ".", "value", "if", "len", "(", "self", ".", "_headerTitles", ")", ">", "0", ":", "if", "len", "(", "overridelist", ")", "%", "2", "!=", "0", ":", "raise", "RuntimeError", "(", "\"Number of items in OverrideLogValue must be even.\"", ")", "self", ".", "_ovrdTitleValueDict", "=", "{", "}", "for", "i", "in", "range", "(", "int", "(", "len", "(", "overridelist", ")", "/", "2", ")", ")", ":", "title", "=", "overridelist", "[", "2", "*", "i", "]", "if", "title", "in", "self", ".", "_headerTitles", ":", "self", ".", "_ovrdTitleValueDict", "[", "title", "]", "=", "overridelist", "[", "2", "*", "i", "+", "1", "]", "else", ":", "self", ".", "log", "(", ")", ".", "warning", "(", "\"Override title %s is not recognized. \"", "%", "(", "title", ")", ")", "return" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/ExportExperimentLog.py#L128-L216
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Path/PathScripts/PathOpGui.py
python
ViewProvider.getSelectionFactory
(self)
return PathSelection.select(self.OpName)
getSelectionFactory() ... return a factory function that can be used to create the selection observer.
getSelectionFactory() ... return a factory function that can be used to create the selection observer.
[ "getSelectionFactory", "()", "...", "return", "a", "factory", "function", "that", "can", "be", "used", "to", "create", "the", "selection", "observer", "." ]
def getSelectionFactory(self): """getSelectionFactory() ... return a factory function that can be used to create the selection observer.""" return PathSelection.select(self.OpName)
[ "def", "getSelectionFactory", "(", "self", ")", ":", "return", "PathSelection", ".", "select", "(", "self", ".", "OpName", ")" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Path/PathScripts/PathOpGui.py#L173-L175
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/richtext.py
python
RichTextBox.__init__
(self, *args)
__init__(self, RichTextObject parent=None) -> RichTextBox __init__(self, RichTextBox obj) -> RichTextBox
__init__(self, RichTextObject parent=None) -> RichTextBox __init__(self, RichTextBox obj) -> RichTextBox
[ "__init__", "(", "self", "RichTextObject", "parent", "=", "None", ")", "-", ">", "RichTextBox", "__init__", "(", "self", "RichTextBox", "obj", ")", "-", ">", "RichTextBox" ]
def __init__(self, *args): """ __init__(self, RichTextObject parent=None) -> RichTextBox __init__(self, RichTextBox obj) -> RichTextBox """ _richtext.RichTextBox_swiginit(self,_richtext.new_RichTextBox(*args))
[ "def", "__init__", "(", "self", ",", "*", "args", ")", ":", "_richtext", ".", "RichTextBox_swiginit", "(", "self", ",", "_richtext", ".", "new_RichTextBox", "(", "*", "args", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/richtext.py#L1872-L1877
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/pyparsing.py
python
ungroup
(expr)
return TokenConverter(expr).addParseAction(lambda t: t[0])
Helper to undo pyparsing's default grouping of And expressions, even if all but one are non-empty.
Helper to undo pyparsing's default grouping of And expressions,
[ "Helper", "to", "undo", "pyparsing", "s", "default", "grouping", "of", "And", "expressions" ]
def ungroup(expr): """Helper to undo pyparsing's default grouping of And expressions, even if all but one are non-empty. """ return TokenConverter(expr).addParseAction(lambda t: t[0])
[ "def", "ungroup", "(", "expr", ")", ":", "return", "TokenConverter", "(", "expr", ")", ".", "addParseAction", "(", "lambda", "t", ":", "t", "[", "0", "]", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/pyparsing.py#L11259-L11267
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/buildscripts/git.py
python
Repository._run_cmd
(self, cmd, args)
return self._run_process(cmd, params, cwd=self.directory)
Run the git command and return a GitCommandResult instance.
Run the git command and return a GitCommandResult instance.
[ "Run", "the", "git", "command", "and", "return", "a", "GitCommandResult", "instance", "." ]
def _run_cmd(self, cmd, args): """Run the git command and return a GitCommandResult instance. """ params = ["git", cmd] + args return self._run_process(cmd, params, cwd=self.directory)
[ "def", "_run_cmd", "(", "self", ",", "cmd", ",", "args", ")", ":", "params", "=", "[", "\"git\"", ",", "cmd", "]", "+", "args", "return", "self", ".", "_run_process", "(", "cmd", ",", "params", ",", "cwd", "=", "self", ".", "directory", ")" ]
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/git.py#L226-L231
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/graph_editor/reroute.py
python
_check_ts_compatibility
(ts0, ts1)
Make sure the shape and dtype of the two tensor's lists are compatible. Args: ts0: an object convertible to a list of `tf.Tensor`. ts1: an object convertible to a list of `tf.Tensor`. Raises: ValueError: if any pair of tensors (same index in ts0 and ts1) have a dtype or a shape which is not compatible.
Make sure the shape and dtype of the two tensor's lists are compatible.
[ "Make", "sure", "the", "shape", "and", "dtype", "of", "the", "two", "tensor", "s", "lists", "are", "compatible", "." ]
def _check_ts_compatibility(ts0, ts1): """Make sure the shape and dtype of the two tensor's lists are compatible. Args: ts0: an object convertible to a list of `tf.Tensor`. ts1: an object convertible to a list of `tf.Tensor`. Raises: ValueError: if any pair of tensors (same index in ts0 and ts1) have a dtype or a shape which is not compatible. """ ts0 = _util.make_list_of_t(ts0) ts1 = _util.make_list_of_t(ts1) if len(ts0) != len(ts1): raise ValueError("ts0 and ts1 have different sizes: {} != {}".format( len(ts0), len(ts1))) for t0, t1 in zip(ts0, ts1): # check dtype dtype0, dtype1 = t0.dtype, t1.dtype if not dtype0.is_compatible_with(dtype1): raise ValueError("Dtypes {} and {} are not compatible.".format(dtype0, dtype1)) # check shape shape0, shape1 = t0.get_shape(), t1.get_shape() if not shape0.is_compatible_with(shape1): raise ValueError("Shapes {} and {} are not compatible.".format(shape0, shape1))
[ "def", "_check_ts_compatibility", "(", "ts0", ",", "ts1", ")", ":", "ts0", "=", "_util", ".", "make_list_of_t", "(", "ts0", ")", "ts1", "=", "_util", ".", "make_list_of_t", "(", "ts1", ")", "if", "len", "(", "ts0", ")", "!=", "len", "(", "ts1", ")", ":", "raise", "ValueError", "(", "\"ts0 and ts1 have different sizes: {} != {}\"", ".", "format", "(", "len", "(", "ts0", ")", ",", "len", "(", "ts1", ")", ")", ")", "for", "t0", ",", "t1", "in", "zip", "(", "ts0", ",", "ts1", ")", ":", "# check dtype", "dtype0", ",", "dtype1", "=", "t0", ".", "dtype", ",", "t1", ".", "dtype", "if", "not", "dtype0", ".", "is_compatible_with", "(", "dtype1", ")", ":", "raise", "ValueError", "(", "\"Dtypes {} and {} are not compatible.\"", ".", "format", "(", "dtype0", ",", "dtype1", ")", ")", "# check shape", "shape0", ",", "shape1", "=", "t0", ".", "get_shape", "(", ")", ",", "t1", ".", "get_shape", "(", ")", "if", "not", "shape0", ".", "is_compatible_with", "(", "shape1", ")", ":", "raise", "ValueError", "(", "\"Shapes {} and {} are not compatible.\"", ".", "format", "(", "shape0", ",", "shape1", ")", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/graph_editor/reroute.py#L41-L66
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/linalg/python/ops/linear_operator_util.py
python
assert_no_entries_with_modulus_zero
( x, message=None, name="assert_no_entries_with_modulus_zero")
Returns `Op` that asserts Tensor `x` has no entries with modulus zero. Args: x: Numeric `Tensor`, real, integer, or complex. message: A string message to prepend to failure message. name: A name to give this `Op`. Returns: An `Op` that asserts `x` has no entries with modulus zero.
Returns `Op` that asserts Tensor `x` has no entries with modulus zero.
[ "Returns", "Op", "that", "asserts", "Tensor", "x", "has", "no", "entries", "with", "modulus", "zero", "." ]
def assert_no_entries_with_modulus_zero( x, message=None, name="assert_no_entries_with_modulus_zero"): """Returns `Op` that asserts Tensor `x` has no entries with modulus zero. Args: x: Numeric `Tensor`, real, integer, or complex. message: A string message to prepend to failure message. name: A name to give this `Op`. Returns: An `Op` that asserts `x` has no entries with modulus zero. """ with ops.name_scope(name, values=[x]): x = ops.convert_to_tensor(x, name="x") dtype = x.dtype.base_dtype should_be_nonzero = math_ops.abs(x) zero = ops.convert_to_tensor(0, dtype=dtype.real_dtype) return check_ops.assert_less(zero, should_be_nonzero, message=message)
[ "def", "assert_no_entries_with_modulus_zero", "(", "x", ",", "message", "=", "None", ",", "name", "=", "\"assert_no_entries_with_modulus_zero\"", ")", ":", "with", "ops", ".", "name_scope", "(", "name", ",", "values", "=", "[", "x", "]", ")", ":", "x", "=", "ops", ".", "convert_to_tensor", "(", "x", ",", "name", "=", "\"x\"", ")", "dtype", "=", "x", ".", "dtype", ".", "base_dtype", "should_be_nonzero", "=", "math_ops", ".", "abs", "(", "x", ")", "zero", "=", "ops", ".", "convert_to_tensor", "(", "0", ",", "dtype", "=", "dtype", ".", "real_dtype", ")", "return", "check_ops", ".", "assert_less", "(", "zero", ",", "should_be_nonzero", ",", "message", "=", "message", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/linalg/python/ops/linear_operator_util.py#L29-L46
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/src/motionplanning.py
python
CSpaceInterface.setNeighborhoodSampler
(self, pySamp)
return _motionplanning.CSpaceInterface_setNeighborhoodSampler(self, pySamp)
setNeighborhoodSampler(CSpaceInterface self, PyObject * pySamp)
setNeighborhoodSampler(CSpaceInterface self, PyObject * pySamp)
[ "setNeighborhoodSampler", "(", "CSpaceInterface", "self", "PyObject", "*", "pySamp", ")" ]
def setNeighborhoodSampler(self, pySamp): """ setNeighborhoodSampler(CSpaceInterface self, PyObject * pySamp) """ return _motionplanning.CSpaceInterface_setNeighborhoodSampler(self, pySamp)
[ "def", "setNeighborhoodSampler", "(", "self", ",", "pySamp", ")", ":", "return", "_motionplanning", ".", "CSpaceInterface_setNeighborhoodSampler", "(", "self", ",", "pySamp", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/src/motionplanning.py#L396-L403