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
google/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
earth_enterprise/src/server/wsgi/wms/ogc/common/utils.py
python
GetValue
(dictionary, key_no_case)
return None
Gets a value from a case-insensitive key. Args: dictionary: dict of key -> value key_no_case: your case-insensitive key. Returns: Value of first case-insensitive match for key_no_case.
Gets a value from a case-insensitive key.
[ "Gets", "a", "value", "from", "a", "case", "-", "insensitive", "key", "." ]
def GetValue(dictionary, key_no_case): """Gets a value from a case-insensitive key. Args: dictionary: dict of key -> value key_no_case: your case-insensitive key. Returns: Value of first case-insensitive match for key_no_case. """ key = key_no_case.lower() if dictionary.has_key(key): return dictionary[key] return None
[ "def", "GetValue", "(", "dictionary", ",", "key_no_case", ")", ":", "key", "=", "key_no_case", ".", "lower", "(", ")", "if", "dictionary", ".", "has_key", "(", "key", ")", ":", "return", "dictionary", "[", "key", "]", "return", "None" ]
https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/server/wsgi/wms/ogc/common/utils.py#L35-L51
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_gdi.py
python
ImageList.RemoveAll
(*args, **kwargs)
return _gdi_.ImageList_RemoveAll(*args, **kwargs)
RemoveAll(self) -> bool
RemoveAll(self) -> bool
[ "RemoveAll", "(", "self", ")", "-", ">", "bool" ]
def RemoveAll(*args, **kwargs): """RemoveAll(self) -> bool""" return _gdi_.ImageList_RemoveAll(*args, **kwargs)
[ "def", "RemoveAll", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "ImageList_RemoveAll", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L6795-L6797
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/sparse/construct.py
python
bmat
(blocks, format=None, dtype=None)
return coo_matrix((data, (row, col)), shape=shape).asformat(format)
Build a sparse matrix from sparse sub-blocks Parameters ---------- blocks : array_like Grid of sparse matrices with compatible shapes. An entry of None implies an all-zero matrix. format : {'bsr', 'coo', 'csc', 'csr', 'dia', 'dok', 'lil'}, optional The sparse format of the result (e.g. "csr"). By default an appropriate sparse matrix format is returned. This choice is subject to change. dtype : dtype, optional The data-type of the output matrix. If not given, the dtype is determined from that of `blocks`. Returns ------- bmat : sparse matrix See Also -------- block_diag, diags Examples -------- >>> from scipy.sparse import coo_matrix, bmat >>> A = coo_matrix([[1, 2], [3, 4]]) >>> B = coo_matrix([[5], [6]]) >>> C = coo_matrix([[7]]) >>> bmat([[A, B], [None, C]]).toarray() array([[1, 2, 5], [3, 4, 6], [0, 0, 7]]) >>> bmat([[A, None], [None, C]]).toarray() array([[1, 2, 0], [3, 4, 0], [0, 0, 7]])
Build a sparse matrix from sparse sub-blocks
[ "Build", "a", "sparse", "matrix", "from", "sparse", "sub", "-", "blocks" ]
def bmat(blocks, format=None, dtype=None): """ Build a sparse matrix from sparse sub-blocks Parameters ---------- blocks : array_like Grid of sparse matrices with compatible shapes. An entry of None implies an all-zero matrix. format : {'bsr', 'coo', 'csc', 'csr', 'dia', 'dok', 'lil'}, optional The sparse format of the result (e.g. "csr"). By default an appropriate sparse matrix format is returned. This choice is subject to change. dtype : dtype, optional The data-type of the output matrix. If not given, the dtype is determined from that of `blocks`. Returns ------- bmat : sparse matrix See Also -------- block_diag, diags Examples -------- >>> from scipy.sparse import coo_matrix, bmat >>> A = coo_matrix([[1, 2], [3, 4]]) >>> B = coo_matrix([[5], [6]]) >>> C = coo_matrix([[7]]) >>> bmat([[A, B], [None, C]]).toarray() array([[1, 2, 5], [3, 4, 6], [0, 0, 7]]) >>> bmat([[A, None], [None, C]]).toarray() array([[1, 2, 0], [3, 4, 0], [0, 0, 7]]) """ blocks = np.asarray(blocks, dtype='object') if blocks.ndim != 2: raise ValueError('blocks must be 2-D') M,N = blocks.shape # check for fast path cases if (N == 1 and format in (None, 'csr') and all(isinstance(b, csr_matrix) for b in blocks.flat)): A = _compressed_sparse_stack(blocks[:,0], 0) if dtype is not None: A = A.astype(dtype) return A elif (M == 1 and format in (None, 'csc') and all(isinstance(b, csc_matrix) for b in blocks.flat)): A = _compressed_sparse_stack(blocks[0,:], 1) if dtype is not None: A = A.astype(dtype) return A block_mask = np.zeros(blocks.shape, dtype=bool) brow_lengths = np.zeros(M, dtype=np.int64) bcol_lengths = np.zeros(N, dtype=np.int64) # convert everything to COO format for i in range(M): for j in range(N): if blocks[i,j] is not None: A = coo_matrix(blocks[i,j]) blocks[i,j] = A block_mask[i,j] = True if brow_lengths[i] == 0: brow_lengths[i] = A.shape[0] elif brow_lengths[i] != A.shape[0]: msg = ('blocks[{i},:] has incompatible row dimensions. ' 'Got blocks[{i},{j}].shape[0] == {got}, ' 'expected {exp}.'.format(i=i, j=j, exp=brow_lengths[i], got=A.shape[0])) raise ValueError(msg) if bcol_lengths[j] == 0: bcol_lengths[j] = A.shape[1] elif bcol_lengths[j] != A.shape[1]: msg = ('blocks[:,{j}] has incompatible row dimensions. ' 'Got blocks[{i},{j}].shape[1] == {got}, ' 'expected {exp}.'.format(i=i, j=j, exp=bcol_lengths[j], got=A.shape[1])) raise ValueError(msg) nnz = sum(block.nnz for block in blocks[block_mask]) if dtype is None: all_dtypes = [blk.dtype for blk in blocks[block_mask]] dtype = upcast(*all_dtypes) if all_dtypes else None row_offsets = np.append(0, np.cumsum(brow_lengths)) col_offsets = np.append(0, np.cumsum(bcol_lengths)) shape = (row_offsets[-1], col_offsets[-1]) data = np.empty(nnz, dtype=dtype) idx_dtype = get_index_dtype(maxval=max(shape)) row = np.empty(nnz, dtype=idx_dtype) col = np.empty(nnz, dtype=idx_dtype) nnz = 0 ii, jj = np.nonzero(block_mask) for i, j in zip(ii, jj): B = blocks[i, j] idx = slice(nnz, nnz + B.nnz) data[idx] = B.data row[idx] = B.row + row_offsets[i] col[idx] = B.col + col_offsets[j] nnz += B.nnz return coo_matrix((data, (row, col)), shape=shape).asformat(format)
[ "def", "bmat", "(", "blocks", ",", "format", "=", "None", ",", "dtype", "=", "None", ")", ":", "blocks", "=", "np", ".", "asarray", "(", "blocks", ",", "dtype", "=", "'object'", ")", "if", "blocks", ".", "ndim", "!=", "2", ":", "raise", "ValueError...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/sparse/construct.py#L502-L623
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/netrc.py
python
netrc.authenticators
(self, host)
Return a (user, account, password) tuple for given host.
Return a (user, account, password) tuple for given host.
[ "Return", "a", "(", "user", "account", "password", ")", "tuple", "for", "given", "host", "." ]
def authenticators(self, host): """Return a (user, account, password) tuple for given host.""" if host in self.hosts: return self.hosts[host] elif 'default' in self.hosts: return self.hosts['default'] else: return None
[ "def", "authenticators", "(", "self", ",", "host", ")", ":", "if", "host", "in", "self", ".", "hosts", ":", "return", "self", ".", "hosts", "[", "host", "]", "elif", "'default'", "in", "self", ".", "hosts", ":", "return", "self", ".", "hosts", "[", ...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/netrc.py#L96-L103
funnyzhou/Adaptive_Feeding
9c78182331d8c0ea28de47226e805776c638d46f
tools/train_net.py
python
parse_args
()
return args
Parse input arguments
Parse input arguments
[ "Parse", "input", "arguments" ]
def parse_args(): """ Parse input arguments """ parser = argparse.ArgumentParser(description='Train a Fast R-CNN network') parser.add_argument('--gpu', dest='gpu_id', help='GPU device id to use [0]', default=0, type=int) parser.add_argument('--solver', dest='solver', help='solver prototxt', default=None, type=str) parser.add_argument('--iters', dest='max_iters', help='number of iterations to train', default=40000, type=int) parser.add_argument('--weights', dest='pretrained_model', help='initialize with pretrained model weights', default=None, type=str) parser.add_argument('--cfg', dest='cfg_file', help='optional config file', default=None, type=str) parser.add_argument('--imdb', dest='imdb_name', help='dataset to train on', default='voc_2007_trainval', type=str) parser.add_argument('--rand', dest='randomize', help='randomize (do not use a fixed seed)', action='store_true') parser.add_argument('--set', dest='set_cfgs', help='set config keys', default=None, nargs=argparse.REMAINDER) if len(sys.argv) == 1: parser.print_help() sys.exit(1) args = parser.parse_args() return args
[ "def", "parse_args", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Train a Fast R-CNN network'", ")", "parser", ".", "add_argument", "(", "'--gpu'", ",", "dest", "=", "'gpu_id'", ",", "help", "=", "'GPU device id to ...
https://github.com/funnyzhou/Adaptive_Feeding/blob/9c78182331d8c0ea28de47226e805776c638d46f/tools/train_net.py#L23-L58
SpenceKonde/megaTinyCore
1c4a70b18a149fe6bcb551dfa6db11ca50b8997b
megaavr/tools/libs/pymcuprog/serialupdi/link.py
python
UpdiDatalink.st_ptr_inc16
(self, data)
Store a 16-bit word value to the pointer location with pointer post-increment :param data: data to store
Store a 16-bit word value to the pointer location with pointer post-increment :param data: data to store
[ "Store", "a", "16", "-", "bit", "word", "value", "to", "the", "pointer", "location", "with", "pointer", "post", "-", "increment", ":", "param", "data", ":", "data", "to", "store" ]
def st_ptr_inc16(self, data): """ Store a 16-bit word value to the pointer location with pointer post-increment :param data: data to store """ self.logger.debug("ST16 to *ptr++") self.updi_phy.send([constants.UPDI_PHY_SYNC, constants.UPDI_ST | constants.UPDI_PTR_INC | constants.UPDI_DATA_16, data[0], data[1]]) response = self.updi_phy.receive(1) if len(response) != 1 or response[0] != constants.UPDI_PHY_ACK: if len(response) > 0: self.logger.error("Expecting ACK after ST16 *ptr++. Got {}}", response[0]) else: self.logger.error("Expecting ACK after ST16 *ptr++. Got nothing") raise PymcuprogError("Error with st_ptr_inc16") num = 2 while num < len(data): self.updi_phy.send([data[num], data[num + 1]]) response = self.updi_phy.receive(1) if len(response) != 1 or response[0] != constants.UPDI_PHY_ACK: if len(response) > 0: self.logger.error("Expecting ACK after ST16 *ptr++, after word %d. 0x%00X}", num, request[0]) else: self.logger.error("Expecting ACK after ST16 *ptr++, after word %d. Got nothing", num) raise PymcuprogError("Error with st_ptr_inc16") num += 2
[ "def", "st_ptr_inc16", "(", "self", ",", "data", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"ST16 to *ptr++\"", ")", "self", ".", "updi_phy", ".", "send", "(", "[", "constants", ".", "UPDI_PHY_SYNC", ",", "constants", ".", "UPDI_ST", "|", "con...
https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/pymcuprog/serialupdi/link.py#L155-L183
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/dist.py
python
Distribution._clean_req
(self, req)
return req
Given a Requirement, remove environment markers and return it.
Given a Requirement, remove environment markers and return it.
[ "Given", "a", "Requirement", "remove", "environment", "markers", "and", "return", "it", "." ]
def _clean_req(self, req): """ Given a Requirement, remove environment markers and return it. """ req.marker = None return req
[ "def", "_clean_req", "(", "self", ",", "req", ")", ":", "req", ".", "marker", "=", "None", "return", "req" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/dist.py#L546-L551
microsoft/checkedc-clang
a173fefde5d7877b7750e7ce96dd08cf18baebf2
lldb/third_party/Python/module/ptyprocess-0.6.0/ptyprocess/ptyprocess.py
python
PtyProcess.read
(self, size=1024)
return s
Read and return at most ``size`` bytes from the pty. Can block if there is nothing to read. Raises :exc:`EOFError` if the terminal was closed. Unlike Pexpect's ``read_nonblocking`` method, this doesn't try to deal with the vagaries of EOF on platforms that do strange things, like IRIX or older Solaris systems. It handles the errno=EIO pattern used on Linux, and the empty-string return used on BSD platforms and (seemingly) on recent Solaris.
Read and return at most ``size`` bytes from the pty.
[ "Read", "and", "return", "at", "most", "size", "bytes", "from", "the", "pty", "." ]
def read(self, size=1024): """Read and return at most ``size`` bytes from the pty. Can block if there is nothing to read. Raises :exc:`EOFError` if the terminal was closed. Unlike Pexpect's ``read_nonblocking`` method, this doesn't try to deal with the vagaries of EOF on platforms that do strange things, like IRIX or older Solaris systems. It handles the errno=EIO pattern used on Linux, and the empty-string return used on BSD platforms and (seemingly) on recent Solaris. """ try: s = self.fileobj.read1(size) except (OSError, IOError) as err: if err.args[0] == errno.EIO: # Linux-style EOF self.flag_eof = True raise EOFError('End Of File (EOF). Exception style platform.') raise if s == b'': # BSD-style EOF (also appears to work on recent Solaris (OpenIndiana)) self.flag_eof = True raise EOFError('End Of File (EOF). Empty string style platform.') return s
[ "def", "read", "(", "self", ",", "size", "=", "1024", ")", ":", "try", ":", "s", "=", "self", ".", "fileobj", ".", "read1", "(", "size", ")", "except", "(", "OSError", ",", "IOError", ")", "as", "err", ":", "if", "err", ".", "args", "[", "0", ...
https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/lldb/third_party/Python/module/ptyprocess-0.6.0/ptyprocess/ptyprocess.py#L503-L528
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/SimpleXMLRPCServer.py
python
SimpleXMLRPCDispatcher._marshaled_dispatch
(self, data, dispatch_method = None, path = None)
return response
Dispatches an XML-RPC method from marshalled (XML) data. XML-RPC methods are dispatched from the marshalled (XML) data using the _dispatch method and the result is returned as marshalled data. For backwards compatibility, a dispatch function can be provided as an argument (see comment in SimpleXMLRPCRequestHandler.do_POST) but overriding the existing method through subclassing is the preferred means of changing method dispatch behavior.
Dispatches an XML-RPC method from marshalled (XML) data.
[ "Dispatches", "an", "XML", "-", "RPC", "method", "from", "marshalled", "(", "XML", ")", "data", "." ]
def _marshaled_dispatch(self, data, dispatch_method = None, path = None): """Dispatches an XML-RPC method from marshalled (XML) data. XML-RPC methods are dispatched from the marshalled (XML) data using the _dispatch method and the result is returned as marshalled data. For backwards compatibility, a dispatch function can be provided as an argument (see comment in SimpleXMLRPCRequestHandler.do_POST) but overriding the existing method through subclassing is the preferred means of changing method dispatch behavior. """ try: params, method = xmlrpclib.loads(data) # generate response if dispatch_method is not None: response = dispatch_method(method, params) else: response = self._dispatch(method, params) # wrap response in a singleton tuple response = (response,) response = xmlrpclib.dumps(response, methodresponse=1, allow_none=self.allow_none, encoding=self.encoding) except Fault, fault: response = xmlrpclib.dumps(fault, allow_none=self.allow_none, encoding=self.encoding) except: # report exception back to server exc_type, exc_value, exc_tb = sys.exc_info() response = xmlrpclib.dumps( xmlrpclib.Fault(1, "%s:%s" % (exc_type, exc_value)), encoding=self.encoding, allow_none=self.allow_none, ) return response
[ "def", "_marshaled_dispatch", "(", "self", ",", "data", ",", "dispatch_method", "=", "None", ",", "path", "=", "None", ")", ":", "try", ":", "params", ",", "method", "=", "xmlrpclib", ".", "loads", "(", "data", ")", "# generate response", "if", "dispatch_m...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/SimpleXMLRPCServer.py#L241-L276
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/compiler-rt/lib/sanitizer_common/scripts/cpplint.py
python
_NestingState.CheckClassFinished
(self, filename, error)
Checks that all classes have been completely parsed. Call this when all lines in a file have been processed. Args: filename: The name of the current file. error: The function to call with any errors found.
Checks that all classes have been completely parsed.
[ "Checks", "that", "all", "classes", "have", "been", "completely", "parsed", "." ]
def CheckClassFinished(self, filename, error): """Checks that all classes have been completely parsed. Call this when all lines in a file have been processed. Args: filename: The name of the current file. error: The function to call with any errors found. """ # Note: This test can result in false positives if #ifdef constructs # get in the way of brace matching. See the testBuildClass test in # cpplint_unittest.py for an example of this. for obj in self.stack: if isinstance(obj, _ClassInfo): error(filename, obj.starting_linenum, 'build/class', 5, 'Failed to find complete declaration of class %s' % obj.name)
[ "def", "CheckClassFinished", "(", "self", ",", "filename", ",", "error", ")", ":", "# Note: This test can result in false positives if #ifdef constructs", "# get in the way of brace matching. See the testBuildClass test in", "# cpplint_unittest.py for an example of this.", "for", "obj", ...
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L1732-L1747
forkineye/ESPixelStick
22926f1c0d1131f1369fc7cad405689a095ae3cb
dist/bin/pyserial/serial/rfc2217.py
python
Serial._telnet_read_loop
(self)
Read loop for the socket.
Read loop for the socket.
[ "Read", "loop", "for", "the", "socket", "." ]
def _telnet_read_loop(self): """Read loop for the socket.""" mode = M_NORMAL suboption = None try: while self.is_open: try: data = self._socket.recv(1024) except socket.timeout: # just need to get out of recv form time to time to check if # still alive continue except socket.error as e: # connection fails -> terminate loop if self.logger: self.logger.debug("socket error in reader thread: {}".format(e)) break if not data: break # lost connection for byte in iterbytes(data): if mode == M_NORMAL: # interpret as command or as data if byte == IAC: mode = M_IAC_SEEN else: # store data in read buffer or sub option buffer # depending on state if suboption is not None: suboption += byte else: self._read_buffer.put(byte) elif mode == M_IAC_SEEN: if byte == IAC: # interpret as command doubled -> insert character # itself if suboption is not None: suboption += IAC else: self._read_buffer.put(IAC) mode = M_NORMAL elif byte == SB: # sub option start suboption = bytearray() mode = M_NORMAL elif byte == SE: # sub option end -> process it now self._telnet_process_subnegotiation(bytes(suboption)) suboption = None mode = M_NORMAL elif byte in (DO, DONT, WILL, WONT): # negotiation telnet_command = byte mode = M_NEGOTIATE else: # other telnet commands self._telnet_process_command(byte) mode = M_NORMAL elif mode == M_NEGOTIATE: # DO, DONT, WILL, WONT was received, option now following self._telnet_negotiate_option(telnet_command, byte) mode = M_NORMAL finally: self._thread = None if self.logger: self.logger.debug("read thread terminated")
[ "def", "_telnet_read_loop", "(", "self", ")", ":", "mode", "=", "M_NORMAL", "suboption", "=", "None", "try", ":", "while", "self", ".", "is_open", ":", "try", ":", "data", "=", "self", ".", "_socket", ".", "recv", "(", "1024", ")", "except", "socket", ...
https://github.com/forkineye/ESPixelStick/blob/22926f1c0d1131f1369fc7cad405689a095ae3cb/dist/bin/pyserial/serial/rfc2217.py#L725-L788
google/ml-metadata
b60196492d2ea2bcd8e4ddff0f3757e5fd710e4d
ml_metadata/metadata_store/metadata_store.py
python
MetadataStore.get_artifacts
(self, list_options: Optional[ListOptions] = None )
return result
Gets artifacts. Args: list_options: A set of options to specify the conditions, limit the size and adjust order of the returned artifacts. Returns: A list of artifacts. Raises: errors.InternalError: if query execution fails. errors.InvalidArgument: if list_options is invalid.
Gets artifacts.
[ "Gets", "artifacts", "." ]
def get_artifacts(self, list_options: Optional[ListOptions] = None ) -> List[proto.Artifact]: """Gets artifacts. Args: list_options: A set of options to specify the conditions, limit the size and adjust order of the returned artifacts. Returns: A list of artifacts. Raises: errors.InternalError: if query execution fails. errors.InvalidArgument: if list_options is invalid. """ if list_options: if list_options.limit and list_options.limit < 1: raise _make_exception( 'Invalid list_options.limit value passed. list_options.limit is ' 'expected to be greater than 1', errors.INVALID_ARGUMENT) request = metadata_store_service_pb2.GetArtifactsRequest() return_size = None if list_options: request.options.max_result_size = 100 request.options.order_by_field.is_asc = list_options.is_asc if list_options.limit: return_size = list_options.limit if list_options.order_by: request.options.order_by_field.field = list_options.order_by.value if list_options.filter_query: request.options.filter_query = list_options.filter_query # windows # windows 1 # windows 2 # windows 3 # windows 4 # windows 5 # windows 6 result = [] while True: response = metadata_store_service_pb2.GetArtifactsResponse() # Updating request max_result_size option to optimize and avoid # discarding returned results. if return_size and return_size < 100: request.options.max_result_size = return_size self._call('GetArtifacts', request, response) for x in response.artifacts: result.append(x) if return_size: return_size = return_size - len(response.artifacts) if return_size <= 0: break if not response.HasField('next_page_token'): break request.options.next_page_token = response.next_page_token return result
[ "def", "get_artifacts", "(", "self", ",", "list_options", ":", "Optional", "[", "ListOptions", "]", "=", "None", ")", "->", "List", "[", "proto", ".", "Artifact", "]", ":", "if", "list_options", ":", "if", "list_options", ".", "limit", "and", "list_options...
https://github.com/google/ml-metadata/blob/b60196492d2ea2bcd8e4ddff0f3757e5fd710e4d/ml_metadata/metadata_store/metadata_store.py#L971-L1034
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemWebCommunicator/AWS/common-code/lib/AWSIoTPythonSDK/MQTTLib.py
python
AWSIoTMQTTClient.subscribeAsync
(self, topic, QoS, ackCallback=None, messageCallback=None)
return self._mqtt_core.subscribe_async(topic, QoS, ackCallback, messageCallback)
**Description** Subscribe to the desired topic and register a message callback with SUBACK callback. **Syntax** .. code:: python # Subscribe to "myTopic" with QoS0, custom SUBACK callback and a message callback myAWSIoTMQTTClient.subscribe("myTopic", 0, ackCallback=mySubackCallback, messageCallback=customMessageCallback) # Subscribe to "myTopic/#" with QoS1, custom SUBACK callback and a message callback myAWSIoTMQTTClient.subscribe("myTopic/#", 1, ackCallback=mySubackCallback, messageCallback=customMessageCallback) **Parameters** *topic* - Topic name or filter to subscribe to. *QoS* - Quality of Service. Could be 0 or 1. *ackCallback* - Callback to be invoked when the client receives a SUBACK. Should be in form :code:`customCallback(mid, data)`, where :code:`mid` is the packet id for the disconnect request and :code:`data` is the granted QoS for this subscription. *messageCallback* - Function to be called when a new message for the subscribed topic comes in. Should be in form :code:`customCallback(client, userdata, message)`, where :code:`message` contains :code:`topic` and :code:`payload`. Note that :code:`client` and :code:`userdata` are here just to be aligned with the underneath Paho callback function signature. These fields are pending to be deprecated and should not be depended on. **Returns** Subscribe request packet id, for tracking purpose in the corresponding callback.
**Description**
[ "**", "Description", "**" ]
def subscribeAsync(self, topic, QoS, ackCallback=None, messageCallback=None): """ **Description** Subscribe to the desired topic and register a message callback with SUBACK callback. **Syntax** .. code:: python # Subscribe to "myTopic" with QoS0, custom SUBACK callback and a message callback myAWSIoTMQTTClient.subscribe("myTopic", 0, ackCallback=mySubackCallback, messageCallback=customMessageCallback) # Subscribe to "myTopic/#" with QoS1, custom SUBACK callback and a message callback myAWSIoTMQTTClient.subscribe("myTopic/#", 1, ackCallback=mySubackCallback, messageCallback=customMessageCallback) **Parameters** *topic* - Topic name or filter to subscribe to. *QoS* - Quality of Service. Could be 0 or 1. *ackCallback* - Callback to be invoked when the client receives a SUBACK. Should be in form :code:`customCallback(mid, data)`, where :code:`mid` is the packet id for the disconnect request and :code:`data` is the granted QoS for this subscription. *messageCallback* - Function to be called when a new message for the subscribed topic comes in. Should be in form :code:`customCallback(client, userdata, message)`, where :code:`message` contains :code:`topic` and :code:`payload`. Note that :code:`client` and :code:`userdata` are here just to be aligned with the underneath Paho callback function signature. These fields are pending to be deprecated and should not be depended on. **Returns** Subscribe request packet id, for tracking purpose in the corresponding callback. """ return self._mqtt_core.subscribe_async(topic, QoS, ackCallback, messageCallback)
[ "def", "subscribeAsync", "(", "self", ",", "topic", ",", "QoS", ",", "ackCallback", "=", "None", ",", "messageCallback", "=", "None", ")", ":", "return", "self", ".", "_mqtt_core", ".", "subscribe_async", "(", "topic", ",", "QoS", ",", "ackCallback", ",", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemWebCommunicator/AWS/common-code/lib/AWSIoTPythonSDK/MQTTLib.py#L698-L734
qt/qtbase
81b9ee66b8e40ed145185fe46b7c91929688cafd
util/locale_database/ldml.py
python
LocaleScanner.__numberGrouping
(self, system)
return size, size, top
Sizes of groups of digits within a number. Returns a triple (least, higher, top) for which: * least is the number of digits after the last grouping separator; * higher is the number of digits between grouping separators; * top is the fewest digits that can appear before the first grouping separator. Thus (4, 3, 2) would want 1e7 as 1000,0000 but 1e8 as 10,000,0000. Note: CLDR does countenance the possibility of grouping also in the fractional part. This is not presently attempted. Nor is placement of the sign character anywhere but at the start of the number (some formats may place it at the end, possibly elsewhere).
Sizes of groups of digits within a number.
[ "Sizes", "of", "groups", "of", "digits", "within", "a", "number", "." ]
def __numberGrouping(self, system): """Sizes of groups of digits within a number. Returns a triple (least, higher, top) for which: * least is the number of digits after the last grouping separator; * higher is the number of digits between grouping separators; * top is the fewest digits that can appear before the first grouping separator. Thus (4, 3, 2) would want 1e7 as 1000,0000 but 1e8 as 10,000,0000. Note: CLDR does countenance the possibility of grouping also in the fractional part. This is not presently attempted. Nor is placement of the sign character anywhere but at the start of the number (some formats may place it at the end, possibly elsewhere).""" top = int(self.find('numbers/minimumGroupingDigits')) assert top < 4, top # We store it in a 2-bit field grouping = self.find(f'numbers/decimalFormats[numberSystem={system}]/' 'decimalFormatLength/decimalFormat/pattern') groups = grouping.split('.')[0].split(',')[-3:] assert all(len(x) < 8 for x in groups[-2:]), grouping # we store them in 3-bit fields if len(groups) > 2: return len(groups[-1]), len(groups[-2]), top size = len(groups[-1]) if len(groups) == 2 else 3 return size, size, top
[ "def", "__numberGrouping", "(", "self", ",", "system", ")", ":", "top", "=", "int", "(", "self", ".", "find", "(", "'numbers/minimumGroupingDigits'", ")", ")", "assert", "top", "<", "4", ",", "top", "# We store it in a 2-bit field", "grouping", "=", "self", ...
https://github.com/qt/qtbase/blob/81b9ee66b8e40ed145185fe46b7c91929688cafd/util/locale_database/ldml.py#L535-L563
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/prompt-toolkit/py3/prompt_toolkit/shortcuts/utils.py
python
print_container
( container: "AnyContainer", file: Optional[TextIO] = None, style: Optional[BaseStyle] = None, include_default_pygments_style: bool = True, )
Print any layout to the output in a non-interactive way. Example usage:: from prompt_toolkit.widgets import Frame, TextArea print_container( Frame(TextArea(text='Hello world!')))
Print any layout to the output in a non-interactive way.
[ "Print", "any", "layout", "to", "the", "output", "in", "a", "non", "-", "interactive", "way", "." ]
def print_container( container: "AnyContainer", file: Optional[TextIO] = None, style: Optional[BaseStyle] = None, include_default_pygments_style: bool = True, ) -> None: """ Print any layout to the output in a non-interactive way. Example usage:: from prompt_toolkit.widgets import Frame, TextArea print_container( Frame(TextArea(text='Hello world!'))) """ if file: output = create_output(stdout=file) else: output = get_app_session().output def exit_immediately() -> None: # Use `call_from_executor` to exit "soon", so that we still render one # initial time, before exiting the application. get_event_loop().call_soon(lambda: app.exit()) app: Application[None] = Application( layout=Layout(container=container), output=output, input=DummyInput(), style=_create_merged_style( style, include_default_pygments_style=include_default_pygments_style ), ) app.run(pre_run=exit_immediately, in_thread=True)
[ "def", "print_container", "(", "container", ":", "\"AnyContainer\"", ",", "file", ":", "Optional", "[", "TextIO", "]", "=", "None", ",", "style", ":", "Optional", "[", "BaseStyle", "]", "=", "None", ",", "include_default_pygments_style", ":", "bool", "=", "T...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py3/prompt_toolkit/shortcuts/utils.py#L166-L199
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/webapp2/webapp2.py
python
WSGIApplication._internal_error
(self, exception)
return exc.HTTPInternalServerError()
Last resource error for :meth:`__call__`.
Last resource error for :meth:`__call__`.
[ "Last", "resource", "error", "for", ":", "meth", ":", "__call__", "." ]
def _internal_error(self, exception): """Last resource error for :meth:`__call__`.""" logging.exception(exception) if self.debug: lines = ''.join(traceback.format_exception(*sys.exc_info())) html = _debug_template % (cgi.escape(lines, quote=True)) return Response(body=html, status=500) return exc.HTTPInternalServerError()
[ "def", "_internal_error", "(", "self", ",", "exception", ")", ":", "logging", ".", "exception", "(", "exception", ")", "if", "self", ".", "debug", ":", "lines", "=", "''", ".", "join", "(", "traceback", ".", "format_exception", "(", "*", "sys", ".", "e...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/webapp2/webapp2.py#L1551-L1559
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/rnn_cell_impl.py
python
ResidualWrapper.__call__
(self, inputs, state, scope=None)
return (res_outputs, new_state)
Run the cell and then apply the residual_fn on its inputs to its outputs. Args: inputs: cell inputs. state: cell state. scope: optional cell scope. Returns: Tuple of cell outputs and new state. Raises: TypeError: If cell inputs and outputs have different structure (type). ValueError: If cell inputs and outputs have different structure (value).
Run the cell and then apply the residual_fn on its inputs to its outputs.
[ "Run", "the", "cell", "and", "then", "apply", "the", "residual_fn", "on", "its", "inputs", "to", "its", "outputs", "." ]
def __call__(self, inputs, state, scope=None): """Run the cell and then apply the residual_fn on its inputs to its outputs. Args: inputs: cell inputs. state: cell state. scope: optional cell scope. Returns: Tuple of cell outputs and new state. Raises: TypeError: If cell inputs and outputs have different structure (type). ValueError: If cell inputs and outputs have different structure (value). """ outputs, new_state = self._cell(inputs, state, scope=scope) # Ensure shapes match def assert_shape_match(inp, out): inp.get_shape().assert_is_compatible_with(out.get_shape()) def default_residual_fn(inputs, outputs): nest.assert_same_structure(inputs, outputs) nest.map_structure(assert_shape_match, inputs, outputs) return nest.map_structure(lambda inp, out: inp + out, inputs, outputs) res_outputs = (self._residual_fn or default_residual_fn)(inputs, outputs) return (res_outputs, new_state)
[ "def", "__call__", "(", "self", ",", "inputs", ",", "state", ",", "scope", "=", "None", ")", ":", "outputs", ",", "new_state", "=", "self", ".", "_cell", "(", "inputs", ",", "state", ",", "scope", "=", "scope", ")", "# Ensure shapes match", "def", "ass...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/rnn_cell_impl.py#L1022-L1046
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/mapreduce/mapreduce/hooks.py
python
Hooks.__init__
(self, mapreduce_spec)
Initializes a Hooks class. Args: mapreduce_spec: The mapreduce.model.MapreduceSpec for the current mapreduce.
Initializes a Hooks class.
[ "Initializes", "a", "Hooks", "class", "." ]
def __init__(self, mapreduce_spec): """Initializes a Hooks class. Args: mapreduce_spec: The mapreduce.model.MapreduceSpec for the current mapreduce. """ self.mapreduce_spec = mapreduce_spec
[ "def", "__init__", "(", "self", ",", "mapreduce_spec", ")", ":", "self", ".", "mapreduce_spec", "=", "mapreduce_spec" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/mapreduce/mapreduce/hooks.py#L31-L38
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/keras/backend.py
python
reverse
(x, axes)
return array_ops.reverse(x, axes)
Reverse a tensor along the specified axes. Args: x: Tensor to reverse. axes: Integer or iterable of integers. Axes to reverse. Returns: A tensor.
Reverse a tensor along the specified axes.
[ "Reverse", "a", "tensor", "along", "the", "specified", "axes", "." ]
def reverse(x, axes): """Reverse a tensor along the specified axes. Args: x: Tensor to reverse. axes: Integer or iterable of integers. Axes to reverse. Returns: A tensor. """ if isinstance(axes, int): axes = [axes] return array_ops.reverse(x, axes)
[ "def", "reverse", "(", "x", ",", "axes", ")", ":", "if", "isinstance", "(", "axes", ",", "int", ")", ":", "axes", "=", "[", "axes", "]", "return", "array_ops", ".", "reverse", "(", "x", ",", "axes", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/backend.py#L3654-L3667
bundy-dns/bundy
3d41934996b82b0cd2fe22dd74d2abc1daba835d
src/lib/python/bundy/memmgr/datasrc_info.py
python
SegmentInfo.remove
(self)
Remove persistent system resource of the segment. This method is called for a final cleanup of a single generation of memory segment, which a new generation is active and the segment's generation will never be used, even after a restart. A specific operation for the remove depends on the type of segment, and is delegated to the '_remove()' protected method. The caller must ensure that there is no process that uses the segment, either for reading or writing. As a check for this condition, this method must not be called until both get_readers() and get_old_readers() return an empty set; otherwise SegmentInfoError exception will be raised.
Remove persistent system resource of the segment.
[ "Remove", "persistent", "system", "resource", "of", "the", "segment", "." ]
def remove(self): """Remove persistent system resource of the segment. This method is called for a final cleanup of a single generation of memory segment, which a new generation is active and the segment's generation will never be used, even after a restart. A specific operation for the remove depends on the type of segment, and is delegated to the '_remove()' protected method. The caller must ensure that there is no process that uses the segment, either for reading or writing. As a check for this condition, this method must not be called until both get_readers() and get_old_readers() return an empty set; otherwise SegmentInfoError exception will be raised. """ if self.__readers or self.__old_readers: raise SegmentInfoError('cannot remove SegmentInfo with readers') self._remove()
[ "def", "remove", "(", "self", ")", ":", "if", "self", ".", "__readers", "or", "self", ".", "__old_readers", ":", "raise", "SegmentInfoError", "(", "'cannot remove SegmentInfo with readers'", ")", "self", ".", "_remove", "(", ")" ]
https://github.com/bundy-dns/bundy/blob/3d41934996b82b0cd2fe22dd74d2abc1daba835d/src/lib/python/bundy/memmgr/datasrc_info.py#L483-L501
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/html.py
python
HtmlDCRenderer.SetSize
(*args, **kwargs)
return _html.HtmlDCRenderer_SetSize(*args, **kwargs)
SetSize(self, int width, int height)
SetSize(self, int width, int height)
[ "SetSize", "(", "self", "int", "width", "int", "height", ")" ]
def SetSize(*args, **kwargs): """SetSize(self, int width, int height)""" return _html.HtmlDCRenderer_SetSize(*args, **kwargs)
[ "def", "SetSize", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_html", ".", "HtmlDCRenderer_SetSize", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/html.py#L1236-L1238
ros-perception/vision_opencv
c791220cefd0abf02c6719e2ce0fea465857a88e
image_geometry/src/image_geometry/cameramodels.py
python
PinholeCameraModel.getDeltaV
(self, deltaY, Z)
:param deltaY: delta Y, in cartesian space :type deltaY: float :param Z: Z, in cartesian space :type Z: float :rtype: float Compute delta v, given Z and delta Y in Cartesian space. For given Z, this is the inverse of :meth:`getDeltaY`.
:param deltaY: delta Y, in cartesian space :type deltaY: float :param Z: Z, in cartesian space :type Z: float :rtype: float
[ ":", "param", "deltaY", ":", "delta", "Y", "in", "cartesian", "space", ":", "type", "deltaY", ":", "float", ":", "param", "Z", ":", "Z", "in", "cartesian", "space", ":", "type", "Z", ":", "float", ":", "rtype", ":", "float" ]
def getDeltaV(self, deltaY, Z): """ :param deltaY: delta Y, in cartesian space :type deltaY: float :param Z: Z, in cartesian space :type Z: float :rtype: float Compute delta v, given Z and delta Y in Cartesian space. For given Z, this is the inverse of :meth:`getDeltaY`. """ fy = self.P[1, 1] if Z == 0: return float('inf') else: return fy * deltaY / Z
[ "def", "getDeltaV", "(", "self", ",", "deltaY", ",", "Z", ")", ":", "fy", "=", "self", ".", "P", "[", "1", ",", "1", "]", "if", "Z", "==", "0", ":", "return", "float", "(", "'inf'", ")", "else", ":", "return", "fy", "*", "deltaY", "/", "Z" ]
https://github.com/ros-perception/vision_opencv/blob/c791220cefd0abf02c6719e2ce0fea465857a88e/image_geometry/src/image_geometry/cameramodels.py#L162-L177
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/imaplib.py
python
IMAP4_stream.shutdown
(self)
Close I/O established in "open".
Close I/O established in "open".
[ "Close", "I", "/", "O", "established", "in", "open", "." ]
def shutdown(self): """Close I/O established in "open".""" self.readfile.close() self.writefile.close() self.process.wait()
[ "def", "shutdown", "(", "self", ")", ":", "self", ".", "readfile", ".", "close", "(", ")", "self", ".", "writefile", ".", "close", "(", ")", "self", ".", "process", ".", "wait", "(", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/imaplib.py#L1258-L1262
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/roc/hlc/common.py
python
alloca_addrspace_correction
(llvmir)
return '\n'.join(new_ir)
rewrites llvmir such that alloca's go into addrspace(5) and are then addrspacecast back to to addrspace(0). Alloca into 5 is a requirement of the datalayout specification.
rewrites llvmir such that alloca's go into addrspace(5) and are then addrspacecast back to to addrspace(0). Alloca into 5 is a requirement of the datalayout specification.
[ "rewrites", "llvmir", "such", "that", "alloca", "s", "go", "into", "addrspace", "(", "5", ")", "and", "are", "then", "addrspacecast", "back", "to", "to", "addrspace", "(", "0", ")", ".", "Alloca", "into", "5", "is", "a", "requirement", "of", "the", "da...
def alloca_addrspace_correction(llvmir): """ rewrites llvmir such that alloca's go into addrspace(5) and are then addrspacecast back to to addrspace(0). Alloca into 5 is a requirement of the datalayout specification. """ lines = llvmir.splitlines() mangle = '__tmp' new_ir = [] for l in lines: # pluck lines containing alloca if 'alloca' in l: assignee, alloca_match, ptrty = _re_alloca_parts.match(l).groups() q_match = _re_alloca_quoted.match(assignee) if q_match: start, var = q_match.groups() var = var.strip() name_fmt = '%s"%s"' old_name = name_fmt % (start, var) new_name = name_fmt % (start, var + mangle) else: old_name = assignee.strip() new_name = old_name + mangle allocaline = "%s = %s, addrspace(5)" % (new_name, alloca_match) castline_fmt = ("%s = addrspacecast %s addrspace(5)* " "%s to %s addrspace(0)*") castline = castline_fmt % (old_name, ptrty, new_name, ptrty) new_ir.append(allocaline) new_ir.append(castline) else: new_ir.append(l) return '\n'.join(new_ir)
[ "def", "alloca_addrspace_correction", "(", "llvmir", ")", ":", "lines", "=", "llvmir", ".", "splitlines", "(", ")", "mangle", "=", "'__tmp'", "new_ir", "=", "[", "]", "for", "l", "in", "lines", ":", "# pluck lines containing alloca", "if", "'alloca'", "in", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/roc/hlc/common.py#L75-L106
microsoft/ivy
9f3c7ecc0b2383129fdd0953e10890d98d09a82d
ivy/tactics_api.py
python
Abstractors.propagate
(node)
Propagate clauses from predecessor
Propagate clauses from predecessor
[ "Propagate", "clauses", "from", "predecessor" ]
def propagate(node): """ Propagate clauses from predecessor """ preds, action = arg_get_preds_action(node) assert action != 'join' assert len(preds) == 1 pred = preds[0] implied = implied_facts( forward_image(arg_get_fact(pred), action), list(arg_get_conjuncts(pred)), ) node.clauses = true_clauses() for fact in implied: arg_add_facts(node, fact)
[ "def", "propagate", "(", "node", ")", ":", "preds", ",", "action", "=", "arg_get_preds_action", "(", "node", ")", "assert", "action", "!=", "'join'", "assert", "len", "(", "preds", ")", "==", "1", "pred", "=", "preds", "[", "0", "]", "implied", "=", ...
https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/tactics_api.py#L148-L162
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/maximum-non-negative-product-in-a-matrix.py
python
Solution.maxProductPath
(self, grid)
return max_dp[(len(grid)-1)%2][-1]%MOD if max_dp[(len(grid)-1)%2][-1] >= 0 else -1
:type grid: List[List[int]] :rtype: int
:type grid: List[List[int]] :rtype: int
[ ":", "type", "grid", ":", "List", "[", "List", "[", "int", "]]", ":", "rtype", ":", "int" ]
def maxProductPath(self, grid): """ :type grid: List[List[int]] :rtype: int """ MOD = 10**9+7 max_dp = [[0]*len(grid[0]) for _ in xrange(2)] min_dp = [[0]*len(grid[0]) for _ in xrange(2)] for i in xrange(len(grid)): for j in xrange(len(grid[i])): if i == 0 and j == 0: max_dp[i%2][j] = min_dp[i%2][j] = grid[i][j] continue curr_max = max(max_dp[(i-1)%2][j] if i > 0 else max_dp[i%2][j-1], max_dp[i%2][j-1] if j > 0 else max_dp[(i-1)%2][j]) curr_min = min(min_dp[(i-1)%2][j] if i > 0 else min_dp[i%2][j-1], min_dp[i%2][j-1] if j > 0 else min_dp[(i-1)%2][j]) if grid[i][j] < 0: curr_max, curr_min = curr_min, curr_max max_dp[i%2][j] = curr_max*grid[i][j] min_dp[i%2][j] = curr_min*grid[i][j] return max_dp[(len(grid)-1)%2][-1]%MOD if max_dp[(len(grid)-1)%2][-1] >= 0 else -1
[ "def", "maxProductPath", "(", "self", ",", "grid", ")", ":", "MOD", "=", "10", "**", "9", "+", "7", "max_dp", "=", "[", "[", "0", "]", "*", "len", "(", "grid", "[", "0", "]", ")", "for", "_", "in", "xrange", "(", "2", ")", "]", "min_dp", "=...
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/maximum-non-negative-product-in-a-matrix.py#L6-L27
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_controls.py
python
ToolBarBase.DoAddTool
(*args, **kwargs)
return _controls_.ToolBarBase_DoAddTool(*args, **kwargs)
DoAddTool(self, int id, String label, Bitmap bitmap, Bitmap bmpDisabled=wxNullBitmap, int kind=ITEM_NORMAL, String shortHelp=EmptyString, String longHelp=EmptyString, PyObject clientData=None) -> ToolBarToolBase
DoAddTool(self, int id, String label, Bitmap bitmap, Bitmap bmpDisabled=wxNullBitmap, int kind=ITEM_NORMAL, String shortHelp=EmptyString, String longHelp=EmptyString, PyObject clientData=None) -> ToolBarToolBase
[ "DoAddTool", "(", "self", "int", "id", "String", "label", "Bitmap", "bitmap", "Bitmap", "bmpDisabled", "=", "wxNullBitmap", "int", "kind", "=", "ITEM_NORMAL", "String", "shortHelp", "=", "EmptyString", "String", "longHelp", "=", "EmptyString", "PyObject", "clientD...
def DoAddTool(*args, **kwargs): """ DoAddTool(self, int id, String label, Bitmap bitmap, Bitmap bmpDisabled=wxNullBitmap, int kind=ITEM_NORMAL, String shortHelp=EmptyString, String longHelp=EmptyString, PyObject clientData=None) -> ToolBarToolBase """ return _controls_.ToolBarBase_DoAddTool(*args, **kwargs)
[ "def", "DoAddTool", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "ToolBarBase_DoAddTool", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L3593-L3600
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py2/IPython/extensions/autoreload.py
python
update_class
(old, new)
Replace stuff in the __dict__ of a class, and upgrade method code objects
Replace stuff in the __dict__ of a class, and upgrade method code objects
[ "Replace", "stuff", "in", "the", "__dict__", "of", "a", "class", "and", "upgrade", "method", "code", "objects" ]
def update_class(old, new): """Replace stuff in the __dict__ of a class, and upgrade method code objects""" for key in list(old.__dict__.keys()): old_obj = getattr(old, key) try: new_obj = getattr(new, key) except AttributeError: # obsolete attribute: remove it try: delattr(old, key) except (AttributeError, TypeError): pass continue if update_generic(old_obj, new_obj): continue try: setattr(old, key, getattr(new, key)) except (AttributeError, TypeError): pass
[ "def", "update_class", "(", "old", ",", "new", ")", ":", "for", "key", "in", "list", "(", "old", ".", "__dict__", ".", "keys", "(", ")", ")", ":", "old_obj", "=", "getattr", "(", "old", ",", "key", ")", "try", ":", "new_obj", "=", "getattr", "(",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py2/IPython/extensions/autoreload.py#L276-L297
epam/Indigo
30e40b4b1eb9bae0207435a26cfcb81ddcc42be1
api/python/indigo/renderer.py
python
IndigoRenderer.renderToBuffer
(self, obj)
Renders object to buffer Args: obj (IndigoObject): object to render Returns: buffer with byte array
Renders object to buffer
[ "Renders", "object", "to", "buffer" ]
def renderToBuffer(self, obj): """Renders object to buffer Args: obj (IndigoObject): object to render Returns: buffer with byte array """ self.indigo._setSessionId() wb = self.indigo.writeBuffer() try: self.indigo._checkResult(self._lib.indigoRender(obj.id, wb.id)) return wb.toBuffer() finally: wb.dispose()
[ "def", "renderToBuffer", "(", "self", ",", "obj", ")", ":", "self", ".", "indigo", ".", "_setSessionId", "(", ")", "wb", "=", "self", ".", "indigo", ".", "writeBuffer", "(", ")", "try", ":", "self", ".", "indigo", ".", "_checkResult", "(", "self", "....
https://github.com/epam/Indigo/blob/30e40b4b1eb9bae0207435a26cfcb81ddcc42be1/api/python/indigo/renderer.py#L76-L91
microsoft/ivy
9f3c7ecc0b2383129fdd0953e10890d98d09a82d
ivy/ivy_parser.py
python
p_funs_fun
(p)
funs : fun
funs : fun
[ "funs", ":", "fun" ]
def p_funs_fun(p): 'funs : fun' p[0] = [p[1]]
[ "def", "p_funs_fun", "(", "p", ")", ":", "p", "[", "0", "]", "=", "[", "p", "[", "1", "]", "]" ]
https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/ivy_parser.py#L855-L857
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/dtypes/common.py
python
is_complex_dtype
(arr_or_dtype)
return _is_dtype_type(arr_or_dtype, classes(np.complexfloating))
Check whether the provided array or dtype is of a complex dtype. Parameters ---------- arr_or_dtype : array-like The array or dtype to check. Returns ------- boolean : Whether or not the array or dtype is of a compex dtype. Examples -------- >>> is_complex_dtype(str) False >>> is_complex_dtype(int) False >>> is_complex_dtype(np.complex) True >>> is_complex_dtype(np.array(['a', 'b'])) False >>> is_complex_dtype(pd.Series([1, 2])) False >>> is_complex_dtype(np.array([1 + 1j, 5])) True
Check whether the provided array or dtype is of a complex dtype.
[ "Check", "whether", "the", "provided", "array", "or", "dtype", "is", "of", "a", "complex", "dtype", "." ]
def is_complex_dtype(arr_or_dtype): """ Check whether the provided array or dtype is of a complex dtype. Parameters ---------- arr_or_dtype : array-like The array or dtype to check. Returns ------- boolean : Whether or not the array or dtype is of a compex dtype. Examples -------- >>> is_complex_dtype(str) False >>> is_complex_dtype(int) False >>> is_complex_dtype(np.complex) True >>> is_complex_dtype(np.array(['a', 'b'])) False >>> is_complex_dtype(pd.Series([1, 2])) False >>> is_complex_dtype(np.array([1 + 1j, 5])) True """ return _is_dtype_type(arr_or_dtype, classes(np.complexfloating))
[ "def", "is_complex_dtype", "(", "arr_or_dtype", ")", ":", "return", "_is_dtype_type", "(", "arr_or_dtype", ",", "classes", "(", "np", ".", "complexfloating", ")", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/dtypes/common.py#L1752-L1781
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/hypertreelist.py
python
TreeListItem.GetWindowEnabled
(self, column=None)
return self._wnd[column].IsEnabled()
Returns whether the window associated with an item is enabled or not. :param `column`: if not ``None``, an integer specifying the column index. If it is ``None``, the main column index is used.
Returns whether the window associated with an item is enabled or not.
[ "Returns", "whether", "the", "window", "associated", "with", "an", "item", "is", "enabled", "or", "not", "." ]
def GetWindowEnabled(self, column=None): """ Returns whether the window associated with an item is enabled or not. :param `column`: if not ``None``, an integer specifying the column index. If it is ``None``, the main column index is used. """ column = (column is not None and [column] or [self._owner.GetMainColumn()])[0] if not self._wnd[column]: raise Exception("\nERROR: This Item Has No Window Associated At Column %s"%column) return self._wnd[column].IsEnabled()
[ "def", "GetWindowEnabled", "(", "self", ",", "column", "=", "None", ")", ":", "column", "=", "(", "column", "is", "not", "None", "and", "[", "column", "]", "or", "[", "self", ".", "_owner", ".", "GetMainColumn", "(", ")", "]", ")", "[", "0", "]", ...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/hypertreelist.py#L1713-L1726
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/win/toolchain/toolchain.py
python
GenerateTopLevelEnv
(target_dir, vsversion)
Generate a batch file that sets up various environment variables that let the Chromium build files and gyp find SDKs and tools.
Generate a batch file that sets up various environment variables that let the Chromium build files and gyp find SDKs and tools.
[ "Generate", "a", "batch", "file", "that", "sets", "up", "various", "environment", "variables", "that", "let", "the", "Chromium", "build", "files", "and", "gyp", "find", "SDKs", "and", "tools", "." ]
def GenerateTopLevelEnv(target_dir, vsversion): """Generate a batch file that sets up various environment variables that let the Chromium build files and gyp find SDKs and tools.""" with open(os.path.join(target_dir, r'env.bat'), 'w') as file: file.write('@echo off\n') file.write(':: Generated by tools\\win\\toolchain\\toolchain.py.\n') file.write(':: Targeting VS%s.\n' % vsversion) file.write('set GYP_DEFINES=windows_sdk_path="%s" ' 'component=shared_library\n' % ( os.path.join(target_dir, 'win8sdk'))) file.write('set GYP_MSVS_VERSION=%se\n' % vsversion) file.write('set GYP_MSVS_OVERRIDE_PATH=%s\n' % target_dir) file.write('set GYP_GENERATORS=ninja\n') file.write('set GYP_PARALLEL=1\n') file.write('set WDK_DIR=%s\n' % os.path.join(target_dir, r'WDK')) if vsversion == '2010': file.write('set DXSDK_DIR=%s\n' % os.path.join(target_dir, r'DXSDK')) file.write('set WindowsSDKDir=%s\n' % os.path.join(target_dir, r'win8sdk')) if vsversion == '2012': # TODO: For 2010 too. base = os.path.join(target_dir, r'VC\redist') paths = [ r'Debug_NonRedist\x64\Microsoft.VC110.DebugCRT', r'Debug_NonRedist\x86\Microsoft.VC110.DebugCRT', r'x64\Microsoft.VC110.CRT', r'x86\Microsoft.VC110.CRT', ] additions = ';'.join(os.path.join(base, x) for x in paths) file.write('set PATH=%s;%%PATH%%\n' % additions) file.write('echo Environment set for toolchain in %s.\n' % target_dir) file.write('cd /d %s\\..\n' % target_dir)
[ "def", "GenerateTopLevelEnv", "(", "target_dir", ",", "vsversion", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "target_dir", ",", "r'env.bat'", ")", ",", "'w'", ")", "as", "file", ":", "file", ".", "write", "(", "'@echo off\\n'", ...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/win/toolchain/toolchain.py#L626-L657
COVESA/ramses
86cac72b86dab4082c4d404d884db7e4ba0ed7b8
scripts/code_style_checker/common_modules/common.py
python
get_all_files_with_filter
(sdk_root, root, positive, negative)
return filenames
Iterates over targets and gets names of all files that do not match positive and negative filter
Iterates over targets and gets names of all files that do not match positive and negative filter
[ "Iterates", "over", "targets", "and", "gets", "names", "of", "all", "files", "that", "do", "not", "match", "positive", "and", "negative", "filter" ]
def get_all_files_with_filter(sdk_root, root, positive, negative): """ Iterates over targets and gets names of all files that do not match positive and negative filter """ positive_re = re.compile("|".join(["({})".format(p) for p in positive])) negative_re = negative and re.compile("|".join(["({})".format(n) for n in negative])) filenames = [] for f in subprocess.check_output(['git', 'ls-files', '--full-name', root], cwd=root, shell=False).decode('utf-8').split('\n'): if os.path.isfile(os.path.join(sdk_root, f)): pos_match = False neg_match = False relative_path = f.replace('\\', '/') pos_match = positive_re.search(relative_path) neg_match = negative_re and negative_re.search(relative_path) if pos_match and not neg_match: filenames.append(os.path.join(sdk_root, relative_path)) return filenames
[ "def", "get_all_files_with_filter", "(", "sdk_root", ",", "root", ",", "positive", ",", "negative", ")", ":", "positive_re", "=", "re", ".", "compile", "(", "\"|\"", ".", "join", "(", "[", "\"({})\"", ".", "format", "(", "p", ")", "for", "p", "in", "po...
https://github.com/COVESA/ramses/blob/86cac72b86dab4082c4d404d884db7e4ba0ed7b8/scripts/code_style_checker/common_modules/common.py#L103-L122
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Node/FS.py
python
Entry.must_be_same
(self, klass)
Called to make sure a Node is a Dir. Since we're an Entry, we can morph into one.
Called to make sure a Node is a Dir. Since we're an Entry, we can morph into one.
[ "Called", "to", "make", "sure", "a", "Node", "is", "a", "Dir", ".", "Since", "we", "re", "an", "Entry", "we", "can", "morph", "into", "one", "." ]
def must_be_same(self, klass): """Called to make sure a Node is a Dir. Since we're an Entry, we can morph into one.""" if self.__class__ is not klass: self.__class__ = klass self._morph() self.clear()
[ "def", "must_be_same", "(", "self", ",", "klass", ")", ":", "if", "self", ".", "__class__", "is", "not", "klass", ":", "self", ".", "__class__", "=", "klass", "self", ".", "_morph", "(", ")", "self", ".", "clear", "(", ")" ]
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Node/FS.py#L1065-L1071
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/conv2d_benchmark.py
python
Conv2DBenchmark._run_graph
(self, device, dtype, data_format, input_shape, filter_shape, strides, padding, num_iters, warmup_iters)
return duration
runs the graph and print its execution time. Args: device: String, the device to run on. dtype: Data type for the convolution. data_format: A string from: "NHWC" or "NCHW". Data format for input and output data. input_shape: Shape of the input tensor. filter_shape: Shape of the filter tensor. strides: A list of ints. 1-D of length 4. The stride of sliding window for each dimension of input. padding: A string from: "SAME", "VALID". The type of padding algorithm to use. num_iters: Number of iterations to run the benchmark. num_iters: number of iterations to run conv2d. warmup_iters: number of iterations for warmup runs. Returns: The duration of the run in seconds.
runs the graph and print its execution time.
[ "runs", "the", "graph", "and", "print", "its", "execution", "time", "." ]
def _run_graph(self, device, dtype, data_format, input_shape, filter_shape, strides, padding, num_iters, warmup_iters): """runs the graph and print its execution time. Args: device: String, the device to run on. dtype: Data type for the convolution. data_format: A string from: "NHWC" or "NCHW". Data format for input and output data. input_shape: Shape of the input tensor. filter_shape: Shape of the filter tensor. strides: A list of ints. 1-D of length 4. The stride of sliding window for each dimension of input. padding: A string from: "SAME", "VALID". The type of padding algorithm to use. num_iters: Number of iterations to run the benchmark. num_iters: number of iterations to run conv2d. warmup_iters: number of iterations for warmup runs. Returns: The duration of the run in seconds. """ graph = ops.Graph() with graph.as_default(): warmup_outputs, outputs = build_graph(device, dtype, data_format, input_shape, filter_shape, strides, padding, num_iters, warmup_iters) config = config_pb2.ConfigProto() config.graph_options.optimizer_options.opt_level = -1 rewrite_options = config.graph_options.rewrite_options # Disable layout optimizer to not change input data_format. rewrite_options.layout_optimizer = ( rewriter_config_pb2.RewriterConfig.ON if FLAGS.enable_layout_optimizer else rewriter_config_pb2.RewriterConfig.OFF) # Convolution ops are effectively noop in the test graph as we are not # fetching the convolution outputs. Disable dependency optimizer to not # remove the conv ops. rewrite_options.dependency_optimization = ( rewriter_config_pb2.RewriterConfig.OFF) with session_lib.Session(graph=graph, config=config) as session: # TODO(hinsu): Use run_op_benchmark method from test.Benchmark to run # benchmark along with warmup. variables.global_variables_initializer().run() # warmup runs session.run(warmup_outputs) start_time = time.time() session.run(outputs) duration = (time.time() - start_time) / num_iters print("%s %s %s inputshape:%s filtershape:%s strides:%s padding:%s " "%d iters: %.8f sec" % (device, str(dtype), data_format, str(input_shape).replace( " ", ""), str(filter_shape).replace(" ", ""), str(strides).replace(" ", ""), padding, num_iters, duration)) name_template = ( "conv2d_{device}_{datatype}_{data_format}_input_shape_{inputshape}_" "filter_shape_{filtershape}_strides_{strides}_padding_{padding}") self.report_benchmark( name=name_template.format( device=device, datatype=str(dtype), data_format=str(data_format), inputshape=str(input_shape).replace(" ", ""), filtershape=str(filter_shape).replace(" ", ""), strides=str(strides).replace(" ", ""), padding=padding).replace(" ", ""), iters=num_iters, wall_time=duration) return duration
[ "def", "_run_graph", "(", "self", ",", "device", ",", "dtype", ",", "data_format", ",", "input_shape", ",", "filter_shape", ",", "strides", ",", "padding", ",", "num_iters", ",", "warmup_iters", ")", ":", "graph", "=", "ops", ".", "Graph", "(", ")", "wit...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/conv2d_benchmark.py#L97-L171
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/richtext.py
python
RichTextObject.DeleteRange
(*args, **kwargs)
return _richtext.RichTextObject_DeleteRange(*args, **kwargs)
DeleteRange(self, RichTextRange range) -> bool
DeleteRange(self, RichTextRange range) -> bool
[ "DeleteRange", "(", "self", "RichTextRange", "range", ")", "-", ">", "bool" ]
def DeleteRange(*args, **kwargs): """DeleteRange(self, RichTextRange range) -> bool""" return _richtext.RichTextObject_DeleteRange(*args, **kwargs)
[ "def", "DeleteRange", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextObject_DeleteRange", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L1214-L1216
verilog-to-routing/vtr-verilog-to-routing
d9719cf7374821156c3cee31d66991cb85578562
vtr_flow/scripts/python_libs/vtr/log_parse.py
python
load_script_param
(script_param)
return script_param
Create script parameter string to be used in task names and output.
Create script parameter string to be used in task names and output.
[ "Create", "script", "parameter", "string", "to", "be", "used", "in", "task", "names", "and", "output", "." ]
def load_script_param(script_param): """ Create script parameter string to be used in task names and output. """ if script_param and "common" not in script_param: script_param = "common_" + script_param if script_param: script_param = script_param.replace(" ", "_") else: script_param = "common" for spec_char in [":", "<", ">", "|", "*", "?"]: # replaced to create valid URL path script_param = script_param.replace(spec_char, "_") return script_param
[ "def", "load_script_param", "(", "script_param", ")", ":", "if", "script_param", "and", "\"common\"", "not", "in", "script_param", ":", "script_param", "=", "\"common_\"", "+", "script_param", "if", "script_param", ":", "script_param", "=", "script_param", ".", "r...
https://github.com/verilog-to-routing/vtr-verilog-to-routing/blob/d9719cf7374821156c3cee31d66991cb85578562/vtr_flow/scripts/python_libs/vtr/log_parse.py#L294-L307
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/Pygments/py2/pygments/lexers/dsls.py
python
RslLexer.analyse_text
(text)
Check for the most common text in the beginning of a RSL file.
Check for the most common text in the beginning of a RSL file.
[ "Check", "for", "the", "most", "common", "text", "in", "the", "beginning", "of", "a", "RSL", "file", "." ]
def analyse_text(text): """ Check for the most common text in the beginning of a RSL file. """ if re.search(r'scheme\s*.*?=\s*class\s*type', text, re.I) is not None: return 1.0
[ "def", "analyse_text", "(", "text", ")", ":", "if", "re", ".", "search", "(", "r'scheme\\s*.*?=\\s*class\\s*type'", ",", "text", ",", "re", ".", "I", ")", "is", "not", "None", ":", "return", "1.0" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Pygments/py2/pygments/lexers/dsls.py#L490-L495
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
example/rcnn/rcnn/symbol/symbol_vgg.py
python
get_vgg_rcnn
(num_classes=config.NUM_CLASSES)
return group
Fast R-CNN with VGG 16 conv layers :param num_classes: used to determine output size :return: Symbol
Fast R-CNN with VGG 16 conv layers :param num_classes: used to determine output size :return: Symbol
[ "Fast", "R", "-", "CNN", "with", "VGG", "16", "conv", "layers", ":", "param", "num_classes", ":", "used", "to", "determine", "output", "size", ":", "return", ":", "Symbol" ]
def get_vgg_rcnn(num_classes=config.NUM_CLASSES): """ Fast R-CNN with VGG 16 conv layers :param num_classes: used to determine output size :return: Symbol """ data = mx.symbol.Variable(name="data") rois = mx.symbol.Variable(name='rois') label = mx.symbol.Variable(name='label') bbox_target = mx.symbol.Variable(name='bbox_target') bbox_weight = mx.symbol.Variable(name='bbox_weight') # reshape input rois = mx.symbol.Reshape(data=rois, shape=(-1, 5), name='rois_reshape') label = mx.symbol.Reshape(data=label, shape=(-1, ), name='label_reshape') bbox_target = mx.symbol.Reshape(data=bbox_target, shape=(-1, 4 * num_classes), name='bbox_target_reshape') bbox_weight = mx.symbol.Reshape(data=bbox_weight, shape=(-1, 4 * num_classes), name='bbox_weight_reshape') # shared convolutional layers relu5_3 = get_vgg_conv(data) # Fast R-CNN pool5 = mx.symbol.ROIPooling( name='roi_pool5', data=relu5_3, rois=rois, pooled_size=(7, 7), spatial_scale=1.0 / config.RCNN_FEAT_STRIDE) # group 6 flatten = mx.symbol.Flatten(data=pool5, name="flatten") fc6 = mx.symbol.FullyConnected(data=flatten, num_hidden=4096, name="fc6") relu6 = mx.symbol.Activation(data=fc6, act_type="relu", name="relu6") drop6 = mx.symbol.Dropout(data=relu6, p=0.5, name="drop6") # group 7 fc7 = mx.symbol.FullyConnected(data=drop6, num_hidden=4096, name="fc7") relu7 = mx.symbol.Activation(data=fc7, act_type="relu", name="relu7") drop7 = mx.symbol.Dropout(data=relu7, p=0.5, name="drop7") # classification cls_score = mx.symbol.FullyConnected(name='cls_score', data=drop7, num_hidden=num_classes) cls_prob = mx.symbol.SoftmaxOutput(name='cls_prob', data=cls_score, label=label, normalization='batch') # bounding box regression bbox_pred = mx.symbol.FullyConnected(name='bbox_pred', data=drop7, num_hidden=num_classes * 4) bbox_loss_ = bbox_weight * mx.symbol.smooth_l1(name='bbox_loss_', scalar=1.0, data=(bbox_pred - bbox_target)) bbox_loss = mx.sym.MakeLoss(name='bbox_loss', data=bbox_loss_, grad_scale=1.0 / config.TRAIN.BATCH_ROIS) # reshape output cls_prob = mx.symbol.Reshape(data=cls_prob, shape=(config.TRAIN.BATCH_IMAGES, -1, num_classes), name='cls_prob_reshape') bbox_loss = mx.symbol.Reshape(data=bbox_loss, shape=(config.TRAIN.BATCH_IMAGES, -1, 4 * num_classes), name='bbox_loss_reshape') # group output group = mx.symbol.Group([cls_prob, bbox_loss]) return group
[ "def", "get_vgg_rcnn", "(", "num_classes", "=", "config", ".", "NUM_CLASSES", ")", ":", "data", "=", "mx", ".", "symbol", ".", "Variable", "(", "name", "=", "\"data\"", ")", "rois", "=", "mx", ".", "symbol", ".", "Variable", "(", "name", "=", "'rois'",...
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/example/rcnn/rcnn/symbol/symbol_vgg.py#L86-L133
llvm/llvm-project
ffa6262cb4e2a335d26416fad39a581b4f98c5f4
llvm/bindings/python/llvm/object.py
python
Section.__init__
(self, ptr)
Construct a new section instance. Section instances can currently only be created from an ObjectFile instance. Therefore, this constructor should not be used outside of this module.
Construct a new section instance.
[ "Construct", "a", "new", "section", "instance", "." ]
def __init__(self, ptr): """Construct a new section instance. Section instances can currently only be created from an ObjectFile instance. Therefore, this constructor should not be used outside of this module. """ LLVMObject.__init__(self, ptr) self.expired = False
[ "def", "__init__", "(", "self", ",", "ptr", ")", ":", "LLVMObject", ".", "__init__", "(", "self", ",", "ptr", ")", "self", ".", "expired", "=", "False" ]
https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/llvm/bindings/python/llvm/object.py#L181-L190
pyne/pyne
0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3
pyne/mcnp.py
python
Wwinp.write_wwinp
(self, filename)
This method writes a complete WWINP file to <filename>.
This method writes a complete WWINP file to <filename>.
[ "This", "method", "writes", "a", "complete", "WWINP", "file", "to", "<filename", ">", "." ]
def write_wwinp(self, filename): """This method writes a complete WWINP file to <filename>.""" with open(filename, 'w') as f: self._write_block1(f) self._write_block2(f) self._write_block3(f)
[ "def", "write_wwinp", "(", "self", ",", "filename", ")", ":", "with", "open", "(", "filename", ",", "'w'", ")", "as", "f", ":", "self", ".", "_write_block1", "(", "f", ")", "self", ".", "_write_block2", "(", "f", ")", "self", ".", "_write_block3", "(...
https://github.com/pyne/pyne/blob/0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3/pyne/mcnp.py#L1732-L1737
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
KeyEvent.SetUnicodeKey
(*args, **kwargs)
return _core_.KeyEvent_SetUnicodeKey(*args, **kwargs)
SetUnicodeKey(self, int uniChar) Set the Unicode value of the key event, but only if this is a Unicode build of wxPython.
SetUnicodeKey(self, int uniChar)
[ "SetUnicodeKey", "(", "self", "int", "uniChar", ")" ]
def SetUnicodeKey(*args, **kwargs): """ SetUnicodeKey(self, int uniChar) Set the Unicode value of the key event, but only if this is a Unicode build of wxPython. """ return _core_.KeyEvent_SetUnicodeKey(*args, **kwargs)
[ "def", "SetUnicodeKey", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "KeyEvent_SetUnicodeKey", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L6031-L6038
vslavik/poedit
f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a
deps/boost/tools/build/src/build/build_request.py
python
__x_product_aux
(property_sets, seen_features)
Returns non-conflicting combinations of property sets. property_sets is a list of PropertySet instances. seen_features is a set of Property instances. Returns a tuple of: - list of lists of Property instances, such that within each list, no two Property instance have the same feature, and no Property is for feature in seen_features. - set of features we saw in property_sets
Returns non-conflicting combinations of property sets.
[ "Returns", "non", "-", "conflicting", "combinations", "of", "property", "sets", "." ]
def __x_product_aux (property_sets, seen_features): """Returns non-conflicting combinations of property sets. property_sets is a list of PropertySet instances. seen_features is a set of Property instances. Returns a tuple of: - list of lists of Property instances, such that within each list, no two Property instance have the same feature, and no Property is for feature in seen_features. - set of features we saw in property_sets """ assert is_iterable_typed(property_sets, property_set.PropertySet) assert isinstance(seen_features, set) if not property_sets: return ([], set()) properties = property_sets[0].all() these_features = set() for p in property_sets[0].non_free(): these_features.add(p.feature) # Note: the algorithm as implemented here, as in original Jam code, appears to # detect conflicts based on features, not properties. For example, if command # line build request say: # # <a>1/<b>1 c<1>/<b>1 # # It will decide that those two property sets conflict, because they both specify # a value for 'b' and will not try building "<a>1 <c1> <b1>", but rather two # different property sets. This is a topic for future fixing, maybe. if these_features & seen_features: (inner_result, inner_seen) = __x_product_aux(property_sets[1:], seen_features) return (inner_result, inner_seen | these_features) else: result = [] (inner_result, inner_seen) = __x_product_aux(property_sets[1:], seen_features | these_features) if inner_result: for inner in inner_result: result.append(properties + inner) else: result.append(properties) if inner_seen & these_features: # Some of elements in property_sets[1:] conflict with elements of property_sets[0], # Try again, this time omitting elements of property_sets[0] (inner_result2, inner_seen2) = __x_product_aux(property_sets[1:], seen_features) result.extend(inner_result2) return (result, inner_seen | these_features)
[ "def", "__x_product_aux", "(", "property_sets", ",", "seen_features", ")", ":", "assert", "is_iterable_typed", "(", "property_sets", ",", "property_set", ".", "PropertySet", ")", "assert", "isinstance", "(", "seen_features", ",", "set", ")", "if", "not", "property...
https://github.com/vslavik/poedit/blob/f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a/deps/boost/tools/build/src/build/build_request.py#L39-L91
apiaryio/drafter
4634ebd07f6c6f257cc656598ccd535492fdfb55
tools/gyp/pylib/gyp/generator/make.py
python
EscapeCppDefine
(s)
return s.replace('#', r'\#')
Escapes a CPP define so that it will reach the compiler unaltered.
Escapes a CPP define so that it will reach the compiler unaltered.
[ "Escapes", "a", "CPP", "define", "so", "that", "it", "will", "reach", "the", "compiler", "unaltered", "." ]
def EscapeCppDefine(s): """Escapes a CPP define so that it will reach the compiler unaltered.""" s = EscapeShellArgument(s) s = EscapeMakeVariableExpansion(s) # '#' characters must be escaped even embedded in a string, else Make will # treat it as the start of a comment. return s.replace('#', r'\#')
[ "def", "EscapeCppDefine", "(", "s", ")", ":", "s", "=", "EscapeShellArgument", "(", "s", ")", "s", "=", "EscapeMakeVariableExpansion", "(", "s", ")", "# '#' characters must be escaped even embedded in a string, else Make will", "# treat it as the start of a comment.", "return...
https://github.com/apiaryio/drafter/blob/4634ebd07f6c6f257cc656598ccd535492fdfb55/tools/gyp/pylib/gyp/generator/make.py#L591-L597
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/email/_parseaddr.py
python
AddrlistClass.__init__
(self, field)
Initialize a new instance. `field' is an unparsed address header field, containing one or more addresses.
Initialize a new instance.
[ "Initialize", "a", "new", "instance", "." ]
def __init__(self, field): """Initialize a new instance. `field' is an unparsed address header field, containing one or more addresses. """ self.specials = '()<>@,:;.\"[]' self.pos = 0 self.LWS = ' \t' self.CR = '\r\n' self.FWS = self.LWS + self.CR self.atomends = self.specials + self.LWS + self.CR # Note that RFC 2822 now specifies `.' as obs-phrase, meaning that it # is obsolete syntax. RFC 2822 requires that we recognize obsolete # syntax, so allow dots in phrases. self.phraseends = self.atomends.replace('.', '') self.field = field self.commentlist = []
[ "def", "__init__", "(", "self", ",", "field", ")", ":", "self", ".", "specials", "=", "'()<>@,:;.\\\"[]'", "self", ".", "pos", "=", "0", "self", ".", "LWS", "=", "' \\t'", "self", ".", "CR", "=", "'\\r\\n'", "self", ".", "FWS", "=", "self", ".", "L...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/email/_parseaddr.py#L182-L199
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/irc/irclib.py
python
ip_quad_to_numstr
(quad)
return s
Convert an IP address string (e.g. '192.168.0.1') to an IP number as an integer given in ASCII representation (e.g. '3232235521').
Convert an IP address string (e.g. '192.168.0.1') to an IP number as an integer given in ASCII representation (e.g. '3232235521').
[ "Convert", "an", "IP", "address", "string", "(", "e", ".", "g", ".", "192", ".", "168", ".", "0", ".", "1", ")", "to", "an", "IP", "number", "as", "an", "integer", "given", "in", "ASCII", "representation", "(", "e", ".", "g", ".", "3232235521", "...
def ip_quad_to_numstr(quad): """Convert an IP address string (e.g. '192.168.0.1') to an IP number as an integer given in ASCII representation (e.g. '3232235521').""" p = map(long, quad.split(".")) s = str((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]) if s[-1] == "L": s = s[:-1] return s
[ "def", "ip_quad_to_numstr", "(", "quad", ")", ":", "p", "=", "map", "(", "long", ",", "quad", ".", "split", "(", "\".\"", ")", ")", "s", "=", "str", "(", "(", "p", "[", "0", "]", "<<", "24", ")", "|", "(", "p", "[", "1", "]", "<<", "16", ...
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/irc/irclib.py#L1267-L1275
godlikepanos/anki-3d-engine
e2f65e5045624492571ea8527a4dbf3fad8d2c0a
Tools/Image/CreateAtlas.py
python
parse_commandline
()
return ctx
Parse the command line arguments
Parse the command line arguments
[ "Parse", "the", "command", "line", "arguments" ]
def parse_commandline(): """ Parse the command line arguments """ parser = argparse.ArgumentParser(description="This program creates a texture atlas", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("-i", "--input", nargs="+", required=True, help="specify the image(s) to convert. Seperate with space") parser.add_argument("-o", "--output", default="atlas.png", help="specify output PNG image.") parser.add_argument("-m", "--margin", type=int, default=0, help="specify the margin.") parser.add_argument("-b", "--background-color", help="specify background of empty areas", default="ff00ff00") parser.add_argument("-r", "--rpath", help="Path to append to the .ankiatex", default="") args = parser.parse_args() ctx = Context() ctx.in_files = args.input ctx.out_file = args.output ctx.margin = args.margin ctx.bg_color = int(args.background_color, 16) ctx.rpath = args.rpath if len(ctx.in_files) < 2: parser.error("Not enough images") return ctx
[ "def", "parse_commandline", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"This program creates a texture atlas\"", ",", "formatter_class", "=", "argparse", ".", "ArgumentDefaultsHelpFormatter", ")", "parser", ".", "add_argu...
https://github.com/godlikepanos/anki-3d-engine/blob/e2f65e5045624492571ea8527a4dbf3fad8d2c0a/Tools/Image/CreateAtlas.py#L64-L96
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Tool/link.py
python
_setup_versioned_lib_variables
(env, **kw)
Setup all variables required by the versioning machinery
Setup all variables required by the versioning machinery
[ "Setup", "all", "variables", "required", "by", "the", "versioning", "machinery" ]
def _setup_versioned_lib_variables(env, **kw): """ Setup all variables required by the versioning machinery """ tool = None try: tool = kw['tool'] except KeyError: pass use_soname = False try: use_soname = kw['use_soname'] except KeyError: pass # The $_SHLIBVERSIONFLAGS define extra commandline flags used when # building VERSIONED shared libraries. It's always set, but used only # when VERSIONED library is built (see __SHLIBVERSIONFLAGS in SCons/Defaults.py). if use_soname: # If the linker uses SONAME, then we need this little automata if tool == 'sunlink': env['_SHLIBVERSIONFLAGS'] = '$SHLIBVERSIONFLAGS -h $_SHLIBSONAME' env['_LDMODULEVERSIONFLAGS'] = '$LDMODULEVERSIONFLAGS -h $_LDMODULESONAME' else: env['_SHLIBVERSIONFLAGS'] = '$SHLIBVERSIONFLAGS -Wl,-soname=$_SHLIBSONAME' env['_LDMODULEVERSIONFLAGS'] = '$LDMODULEVERSIONFLAGS -Wl,-soname=$_LDMODULESONAME' env['_SHLIBSONAME'] = '${ShLibSonameGenerator(__env__,TARGET)}' env['_LDMODULESONAME'] = '${LdModSonameGenerator(__env__,TARGET)}' env['ShLibSonameGenerator'] = SCons.Tool.ShLibSonameGenerator env['LdModSonameGenerator'] = SCons.Tool.LdModSonameGenerator else: env['_SHLIBVERSIONFLAGS'] = '$SHLIBVERSIONFLAGS' env['_LDMODULEVERSIONFLAGS'] = '$LDMODULEVERSIONFLAGS' # LDOMDULVERSIONFLAGS should always default to $SHLIBVERSIONFLAGS env['LDMODULEVERSIONFLAGS'] = '$SHLIBVERSIONFLAGS'
[ "def", "_setup_versioned_lib_variables", "(", "env", ",", "*", "*", "kw", ")", ":", "tool", "=", "None", "try", ":", "tool", "=", "kw", "[", "'tool'", "]", "except", "KeyError", ":", "pass", "use_soname", "=", "False", "try", ":", "use_soname", "=", "k...
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Tool/link.py#L268-L305
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/integratedpeakview.py
python
IntegratedPeakView.remove_model
(self)
return
remove the plot for model :return:
remove the plot for model :return:
[ "remove", "the", "plot", "for", "model", ":", "return", ":" ]
def remove_model(self): """ remove the plot for model :return: """ if self._modelDataID is None: raise RuntimeError('There is no model plot on canvas') # reset title self.set_title('') self.remove_line(self._modelDataID) self._modelDataID = None return
[ "def", "remove_model", "(", "self", ")", ":", "if", "self", ".", "_modelDataID", "is", "None", ":", "raise", "RuntimeError", "(", "'There is no model plot on canvas'", ")", "# reset title", "self", ".", "set_title", "(", "''", ")", "self", ".", "remove_line", ...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/integratedpeakview.py#L133-L147
emscripten-core/emscripten
0d413d3c5af8b28349682496edc14656f5700c2f
third_party/ply/example/calc/calc.py
python
p_expression_name
(p)
expression : NAME
expression : NAME
[ "expression", ":", "NAME" ]
def p_expression_name(p): "expression : NAME" try: p[0] = names[p[1]] except LookupError: print("Undefined name '%s'" % p[1]) p[0] = 0
[ "def", "p_expression_name", "(", "p", ")", ":", "try", ":", "p", "[", "0", "]", "=", "names", "[", "p", "[", "1", "]", "]", "except", "LookupError", ":", "print", "(", "\"Undefined name '%s'\"", "%", "p", "[", "1", "]", ")", "p", "[", "0", "]", ...
https://github.com/emscripten-core/emscripten/blob/0d413d3c5af8b28349682496edc14656f5700c2f/third_party/ply/example/calc/calc.py#L84-L90
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/traceback.py
python
print_exc
(limit=None, file=None)
Shorthand for 'print_exception(sys.exc_type, sys.exc_value, sys.exc_traceback, limit, file)'. (In fact, it uses sys.exc_info() to retrieve the same information in a thread-safe way.)
Shorthand for 'print_exception(sys.exc_type, sys.exc_value, sys.exc_traceback, limit, file)'. (In fact, it uses sys.exc_info() to retrieve the same information in a thread-safe way.)
[ "Shorthand", "for", "print_exception", "(", "sys", ".", "exc_type", "sys", ".", "exc_value", "sys", ".", "exc_traceback", "limit", "file", ")", ".", "(", "In", "fact", "it", "uses", "sys", ".", "exc_info", "()", "to", "retrieve", "the", "same", "informatio...
def print_exc(limit=None, file=None): """Shorthand for 'print_exception(sys.exc_type, sys.exc_value, sys.exc_traceback, limit, file)'. (In fact, it uses sys.exc_info() to retrieve the same information in a thread-safe way.)""" if file is None: file = sys.stderr try: etype, value, tb = sys.exc_info() print_exception(etype, value, tb, limit, file) finally: etype = value = tb = None
[ "def", "print_exc", "(", "limit", "=", "None", ",", "file", "=", "None", ")", ":", "if", "file", "is", "None", ":", "file", "=", "sys", ".", "stderr", "try", ":", "etype", ",", "value", ",", "tb", "=", "sys", ".", "exc_info", "(", ")", "print_exc...
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/traceback.py#L219-L229
bulletphysics/bullet3
f0f2a952e146f016096db6f85cf0c44ed75b0b9a
examples/pybullet/gym/pybullet_envs/minitaur/envs/minitaur.py
python
Minitaur.GetBasePosition
(self)
return position
Get the position of minitaur's base. Returns: The position of minitaur's base.
Get the position of minitaur's base.
[ "Get", "the", "position", "of", "minitaur", "s", "base", "." ]
def GetBasePosition(self): """Get the position of minitaur's base. Returns: The position of minitaur's base. """ position, _ = (self._pybullet_client.getBasePositionAndOrientation(self.quadruped)) return position
[ "def", "GetBasePosition", "(", "self", ")", ":", "position", ",", "_", "=", "(", "self", ".", "_pybullet_client", ".", "getBasePositionAndOrientation", "(", "self", ".", "quadruped", ")", ")", "return", "position" ]
https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/minitaur/envs/minitaur.py#L419-L426
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/httplib2/upload-diffs.py
python
GitVCS.GetFileContent
(self, file_hash, is_binary)
return data
Returns the content of a file identified by its git hash.
Returns the content of a file identified by its git hash.
[ "Returns", "the", "content", "of", "a", "file", "identified", "by", "its", "git", "hash", "." ]
def GetFileContent(self, file_hash, is_binary): """Returns the content of a file identified by its git hash.""" data, retcode = RunShellWithReturnCode(["git", "show", file_hash], universal_newlines=not is_binary) if retcode: ErrorExit("Got error status from 'git show %s'" % file_hash) return data
[ "def", "GetFileContent", "(", "self", ",", "file_hash", ",", "is_binary", ")", ":", "data", ",", "retcode", "=", "RunShellWithReturnCode", "(", "[", "\"git\"", ",", "\"show\"", ",", "file_hash", "]", ",", "universal_newlines", "=", "not", "is_binary", ")", "...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/httplib2/upload-diffs.py#L1361-L1367
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/docview.py
python
DocParentFrame.OnMRUFile
(self, event)
Opens the appropriate file when it is selected from the file history menu.
Opens the appropriate file when it is selected from the file history menu.
[ "Opens", "the", "appropriate", "file", "when", "it", "is", "selected", "from", "the", "file", "history", "menu", "." ]
def OnMRUFile(self, event): """ Opens the appropriate file when it is selected from the file history menu. """ n = event.GetId() - wx.ID_FILE1 filename = self._docManager.GetHistoryFile(n) if filename: self._docManager.CreateDocument(filename, DOC_SILENT) else: self._docManager.RemoveFileFromHistory(n) msgTitle = wx.GetApp().GetAppName() if not msgTitle: msgTitle = _("File Error") wx.MessageBox("The file '%s' doesn't exist and couldn't be opened.\nIt has been removed from the most recently used files list" % FileNameFromPath(file), msgTitle, wx.OK | wx.ICON_EXCLAMATION, self)
[ "def", "OnMRUFile", "(", "self", ",", "event", ")", ":", "n", "=", "event", ".", "GetId", "(", ")", "-", "wx", ".", "ID_FILE1", "filename", "=", "self", ".", "_docManager", ".", "GetHistoryFile", "(", "n", ")", "if", "filename", ":", "self", ".", "...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/docview.py#L2432-L2449
msracver/Deep-Image-Analogy
632b9287b42552e32dad64922967c8c9ec7fc4d3
python/caffe/io.py
python
arraylist_to_blobprotovector_str
(arraylist)
return vec.SerializeToString()
Converts a list of arrays to a serialized blobprotovec, which could be then passed to a network for processing.
Converts a list of arrays to a serialized blobprotovec, which could be then passed to a network for processing.
[ "Converts", "a", "list", "of", "arrays", "to", "a", "serialized", "blobprotovec", "which", "could", "be", "then", "passed", "to", "a", "network", "for", "processing", "." ]
def arraylist_to_blobprotovector_str(arraylist): """Converts a list of arrays to a serialized blobprotovec, which could be then passed to a network for processing. """ vec = caffe_pb2.BlobProtoVector() vec.blobs.extend([array_to_blobproto(arr) for arr in arraylist]) return vec.SerializeToString()
[ "def", "arraylist_to_blobprotovector_str", "(", "arraylist", ")", ":", "vec", "=", "caffe_pb2", ".", "BlobProtoVector", "(", ")", "vec", ".", "blobs", ".", "extend", "(", "[", "array_to_blobproto", "(", "arr", ")", "for", "arr", "in", "arraylist", "]", ")", ...
https://github.com/msracver/Deep-Image-Analogy/blob/632b9287b42552e32dad64922967c8c9ec7fc4d3/python/caffe/io.py#L49-L55
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
Sizer.RemoveSizer
(self, *args, **kw)
return self.Remove(*args, **kw)
Compatibility alias for `Remove`.
Compatibility alias for `Remove`.
[ "Compatibility", "alias", "for", "Remove", "." ]
def RemoveSizer(self, *args, **kw): """Compatibility alias for `Remove`.""" return self.Remove(*args, **kw)
[ "def", "RemoveSizer", "(", "self", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "return", "self", ".", "Remove", "(", "*", "args", ",", "*", "*", "kw", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L14737-L14739
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/model/trajectory.py
python
SE3Trajectory.preTransform
(self,T)
Premultiplies every transform in self by the se3 element T. In other words, if T transforms a local frame F to frame F', this method converts this SE3Trajectory from coordinates in F to coordinates in F
Premultiplies every transform in self by the se3 element T. In other words, if T transforms a local frame F to frame F', this method converts this SE3Trajectory from coordinates in F to coordinates in F
[ "Premultiplies", "every", "transform", "in", "self", "by", "the", "se3", "element", "T", ".", "In", "other", "words", "if", "T", "transforms", "a", "local", "frame", "F", "to", "frame", "F", "this", "method", "converts", "this", "SE3Trajectory", "from", "c...
def preTransform(self,T): """Premultiplies every transform in self by the se3 element T. In other words, if T transforms a local frame F to frame F', this method converts this SE3Trajectory from coordinates in F to coordinates in F'""" for i,m in enumerate(self.milestones): Tm = self.to_se3(m) self.milestones[i] = self.from_se3(se3.mul(T,Tm))
[ "def", "preTransform", "(", "self", ",", "T", ")", ":", "for", "i", ",", "m", "in", "enumerate", "(", "self", ".", "milestones", ")", ":", "Tm", "=", "self", ".", "to_se3", "(", "m", ")", "self", ".", "milestones", "[", "i", "]", "=", "self", "...
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/model/trajectory.py#L704-L711
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/math/symbolic.py
python
Expression.find
(self,val)
return None
Returns self if self contains the given expression as a sub-expression, or None otherwise.
Returns self if self contains the given expression as a sub-expression, or None otherwise.
[ "Returns", "self", "if", "self", "contains", "the", "given", "expression", "as", "a", "sub", "-", "expression", "or", "None", "otherwise", "." ]
def find(self,val): """Returns self if self contains the given expression as a sub-expression, or None otherwise.""" if self.match(val): return self return None
[ "def", "find", "(", "self", ",", "val", ")", ":", "if", "self", ".", "match", "(", "val", ")", ":", "return", "self", "return", "None" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/math/symbolic.py#L2619-L2622
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/command/easy_install.py
python
easy_install.select_scheme
(self, name)
Sets the install directories by applying the install schemes.
Sets the install directories by applying the install schemes.
[ "Sets", "the", "install", "directories", "by", "applying", "the", "install", "schemes", "." ]
def select_scheme(self, name): """Sets the install directories by applying the install schemes.""" # it's the caller's problem if they supply a bad name! scheme = INSTALL_SCHEMES[name] for key in SCHEME_KEYS: attrname = 'install_' + key if getattr(self, attrname) is None: setattr(self, attrname, scheme[key])
[ "def", "select_scheme", "(", "self", ",", "name", ")", ":", "# it's the caller's problem if they supply a bad name!", "scheme", "=", "INSTALL_SCHEMES", "[", "name", "]", "for", "key", "in", "SCHEME_KEYS", ":", "attrname", "=", "'install_'", "+", "key", "if", "geta...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/command/easy_install.py#L711-L718
v8mips/v8mips
f0c9cc0bbfd461c7f516799d9a58e9a7395f737e
tools/jsmin.py
python
JavaScriptMinifier.Declaration
(self, m)
return matched_text
Rewrites bits of the program selected by a regexp. These can be curly braces, literal strings, function declarations and var declarations. (These last two must be on one line including the opening curly brace of the function for their variables to be renamed). Args: m: The match object returned by re.search. Returns: The string that should replace the match in the rewritten program.
Rewrites bits of the program selected by a regexp.
[ "Rewrites", "bits", "of", "the", "program", "selected", "by", "a", "regexp", "." ]
def Declaration(self, m): """Rewrites bits of the program selected by a regexp. These can be curly braces, literal strings, function declarations and var declarations. (These last two must be on one line including the opening curly brace of the function for their variables to be renamed). Args: m: The match object returned by re.search. Returns: The string that should replace the match in the rewritten program. """ matched_text = m.group(0) if matched_text == "{": self.Push() return matched_text if matched_text == "}": self.Pop() return matched_text if re.match("[\"'/]", matched_text): return matched_text m = re.match(r"var ", matched_text) if m: var_names = matched_text[m.end():] var_names = re.split(r",", var_names) return "var " + ",".join(map(self.FindNewName, var_names)) m = re.match(r"(function\b[^(]*)\((.*)\)\{$", matched_text) if m: up_to_args = m.group(1) args = m.group(2) args = re.split(r",", args) self.Push() return up_to_args + "(" + ",".join(map(self.FindNewName, args)) + "){" if matched_text in self.map: return self.map[matched_text] return matched_text
[ "def", "Declaration", "(", "self", ",", "m", ")", ":", "matched_text", "=", "m", ".", "group", "(", "0", ")", "if", "matched_text", "==", "\"{\"", ":", "self", ".", "Push", "(", ")", "return", "matched_text", "if", "matched_text", "==", "\"}\"", ":", ...
https://github.com/v8mips/v8mips/blob/f0c9cc0bbfd461c7f516799d9a58e9a7395f737e/tools/jsmin.py#L89-L127
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Show/TVStack.py
python
TVStack.purge_dead
(self)
return n
removes dead TV instances from the stack
removes dead TV instances from the stack
[ "removes", "dead", "TV", "instances", "from", "the", "stack" ]
def purge_dead(self): """removes dead TV instances from the stack""" n = 0 for i in reversed(range(len(self.stack))): if self.stack[i]() is None: self.stack.pop(i) n += 1 if n > 0: self.rebuild_index() return n
[ "def", "purge_dead", "(", "self", ")", ":", "n", "=", "0", "for", "i", "in", "reversed", "(", "range", "(", "len", "(", "self", ".", "stack", ")", ")", ")", ":", "if", "self", ".", "stack", "[", "i", "]", "(", ")", "is", "None", ":", "self", ...
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Show/TVStack.py#L101-L110
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/src/robotsim.py
python
IKSolver.add
(self, objective: "IKObjective")
return _robotsim.IKSolver_add(self, objective)
r""" add(IKSolver self, IKObjective objective) Adds a new simultaneous objective.
r""" add(IKSolver self, IKObjective objective)
[ "r", "add", "(", "IKSolver", "self", "IKObjective", "objective", ")" ]
def add(self, objective: "IKObjective") -> "void": r""" add(IKSolver self, IKObjective objective) Adds a new simultaneous objective. """ return _robotsim.IKSolver_add(self, objective)
[ "def", "add", "(", "self", ",", "objective", ":", "\"IKObjective\"", ")", "->", "\"void\"", ":", "return", "_robotsim", ".", "IKSolver_add", "(", "self", ",", "objective", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/src/robotsim.py#L6679-L6687
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/io/formats/info.py
python
BaseInfo.non_null_counts
(self)
Sequence of non-null counts for all columns or column (if series).
Sequence of non-null counts for all columns or column (if series).
[ "Sequence", "of", "non", "-", "null", "counts", "for", "all", "columns", "or", "column", "(", "if", "series", ")", "." ]
def non_null_counts(self) -> Sequence[int]: """Sequence of non-null counts for all columns or column (if series)."""
[ "def", "non_null_counts", "(", "self", ")", "->", "Sequence", "[", "int", "]", ":" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/io/formats/info.py#L135-L136
rdkit/rdkit
ede860ae316d12d8568daf5ee800921c3389c84e
rdkit/sping/PDF/pdfgen.py
python
Canvas.setLineCap
(self, mode)
0=butt,1=round,2=square
0=butt,1=round,2=square
[ "0", "=", "butt", "1", "=", "round", "2", "=", "square" ]
def setLineCap(self, mode): """0=butt,1=round,2=square""" assert mode in (0, 1, 2), "Line caps allowed: 0=butt,1=round,2=square" self._lineCap = mode self._code.append('%d J' % mode)
[ "def", "setLineCap", "(", "self", ",", "mode", ")", ":", "assert", "mode", "in", "(", "0", ",", "1", ",", "2", ")", ",", "\"Line caps allowed: 0=butt,1=round,2=square\"", "self", ".", "_lineCap", "=", "mode", "self", ".", "_code", ".", "append", "(", "'%...
https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/sping/PDF/pdfgen.py#L499-L503
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/client/timeline.py
python
Timeline._analyze_tensors
(self, show_memory)
Analyze tensor references to track dataflow.
Analyze tensor references to track dataflow.
[ "Analyze", "tensor", "references", "to", "track", "dataflow", "." ]
def _analyze_tensors(self, show_memory): """Analyze tensor references to track dataflow.""" for dev_stats in self._step_stats.dev_stats: device_pid = self._device_pids[dev_stats.device] tensors_pid = self._tensor_pids[dev_stats.device] for node_stats in dev_stats.node_stats: tid = node_stats.thread_id node_name = node_stats.node_name start_time = node_stats.all_start_micros end_time = node_stats.all_start_micros + node_stats.all_end_rel_micros for index, output in enumerate(node_stats.output): if index: output_name = '%s:%d' % (node_name, index) else: output_name = node_name allocation = output.tensor_description.allocation_description num_bytes = allocation.requested_bytes allocator_name = allocation.allocator_name tensor = self._produce_tensor(output_name, start_time, tensors_pid, allocator_name, num_bytes) tensor.add_ref(start_time) tensor.add_unref(end_time) self._flow_starts[output_name] = (end_time, device_pid, tid) if show_memory: self._chrome_trace.emit_obj_create('Tensor', output_name, start_time, tensors_pid, tid, tensor.object_id) self._emit_tensor_snapshot(tensor, end_time - 1, tensors_pid, tid, output)
[ "def", "_analyze_tensors", "(", "self", ",", "show_memory", ")", ":", "for", "dev_stats", "in", "self", ".", "_step_stats", ".", "dev_stats", ":", "device_pid", "=", "self", ".", "_device_pids", "[", "dev_stats", ".", "device", "]", "tensors_pid", "=", "self...
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/client/timeline.py#L476-L506
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/mailbox.py
python
_mboxMMDFMessage._explain_to
(self, message)
Copy mbox- or MMDF-specific state to message insofar as possible.
Copy mbox- or MMDF-specific state to message insofar as possible.
[ "Copy", "mbox", "-", "or", "MMDF", "-", "specific", "state", "to", "message", "insofar", "as", "possible", "." ]
def _explain_to(self, message): """Copy mbox- or MMDF-specific state to message insofar as possible.""" if isinstance(message, MaildirMessage): flags = set(self.get_flags()) if 'O' in flags: message.set_subdir('cur') if 'F' in flags: message.add_flag('F') if 'A' in flags: message.add_flag('R') if 'R' in flags: message.add_flag('S') if 'D' in flags: message.add_flag('T') del message['status'] del message['x-status'] maybe_date = ' '.join(self.get_from().split()[-5:]) try: message.set_date(calendar.timegm(time.strptime(maybe_date, '%a %b %d %H:%M:%S %Y'))) except (ValueError, OverflowError): pass elif isinstance(message, _mboxMMDFMessage): message.set_flags(self.get_flags()) message.set_from(self.get_from()) elif isinstance(message, MHMessage): flags = set(self.get_flags()) if 'R' not in flags: message.add_sequence('unseen') if 'A' in flags: message.add_sequence('replied') if 'F' in flags: message.add_sequence('flagged') del message['status'] del message['x-status'] elif isinstance(message, BabylMessage): flags = set(self.get_flags()) if 'R' not in flags: message.add_label('unseen') if 'D' in flags: message.add_label('deleted') if 'A' in flags: message.add_label('answered') del message['status'] del message['x-status'] elif isinstance(message, Message): pass else: raise TypeError('Cannot convert to specified type: %s' % type(message))
[ "def", "_explain_to", "(", "self", ",", "message", ")", ":", "if", "isinstance", "(", "message", ",", "MaildirMessage", ")", ":", "flags", "=", "set", "(", "self", ".", "get_flags", "(", ")", ")", "if", "'O'", "in", "flags", ":", "message", ".", "set...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/mailbox.py#L1637-L1686
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDynamicContent/AWS/resource-manager-code/path_utils.py
python
ensure_posix_path
(file_path)
return file_path
On Windows convert to standard pathing for DynamicContent which is posix style '/' path separators. This is because Windows operations can handle both pathing styles
On Windows convert to standard pathing for DynamicContent which is posix style '/' path separators.
[ "On", "Windows", "convert", "to", "standard", "pathing", "for", "DynamicContent", "which", "is", "posix", "style", "/", "path", "separators", "." ]
def ensure_posix_path(file_path): """ On Windows convert to standard pathing for DynamicContent which is posix style '/' path separators. This is because Windows operations can handle both pathing styles """ if file_path is not None and platform.system() == 'Windows': return file_path.replace('\\', posixpath.sep) return file_path
[ "def", "ensure_posix_path", "(", "file_path", ")", ":", "if", "file_path", "is", "not", "None", "and", "platform", ".", "system", "(", ")", "==", "'Windows'", ":", "return", "file_path", ".", "replace", "(", "'\\\\'", ",", "posixpath", ".", "sep", ")", "...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDynamicContent/AWS/resource-manager-code/path_utils.py#L16-L24
gimli-org/gimli
17aa2160de9b15ababd9ef99e89b1bc3277bbb23
versioneer.py
python
get_cmdclass
()
return cmds
Get the custom setuptools/distutils subclasses used by Versioneer.
Get the custom setuptools/distutils subclasses used by Versioneer.
[ "Get", "the", "custom", "setuptools", "/", "distutils", "subclasses", "used", "by", "Versioneer", "." ]
def get_cmdclass(): """Get the custom setuptools/distutils subclasses used by Versioneer.""" if "versioneer" in sys.modules: del sys.modules["versioneer"] # this fixes the "python setup.py develop" case (also 'install' and # 'easy_install .'), in which subdependencies of the main project are # built (using setup.py bdist_egg) in the same python process. Assume # a main project A and a dependency B, which use different versions # of Versioneer. A's setup.py imports A's Versioneer, leaving it in # sys.modules by the time B's setup.py is executed, causing B to run # with the wrong versioneer. Setuptools wraps the sub-dep builds in a # sandbox that restores sys.modules to it's pre-build state, so the # parent is protected against the child's "import versioneer". By # removing ourselves from sys.modules here, before the child build # happens, we protect the child from the parent's versioneer too. # Also see https://github.com/warner/python-versioneer/issues/52 cmds = {} # we add "version" to both distutils and setuptools from distutils.core import Command class cmd_version(Command): description = "report generated version string" user_options = [] boolean_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): vers = get_versions(verbose=True) print("Version: %s" % vers["version"]) print(" full-revisionid: %s" % vers.get("full-revisionid")) print(" dirty: %s" % vers.get("dirty")) print(" date: %s" % vers.get("date")) if vers["error"]: print(" error: %s" % vers["error"]) cmds["version"] = cmd_version # we override "build_py" in both distutils and setuptools # # most invocation pathways end up running build_py: # distutils/build -> build_py # distutils/install -> distutils/build ->.. # setuptools/bdist_wheel -> distutils/install ->.. # setuptools/bdist_egg -> distutils/install_lib -> build_py # setuptools/install -> bdist_egg ->.. # setuptools/develop -> ? # pip install: # copies source tree to a tempdir before running egg_info/etc # if .git isn't copied too, 'git describe' will fail # then does setup.py bdist_wheel, or sometimes setup.py install # setup.py egg_info -> ? # we override different "build_py" commands for both environments if "setuptools" in sys.modules: from setuptools.command.build_py import build_py as _build_py else: from distutils.command.build_py import build_py as _build_py class cmd_build_py(_build_py): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() _build_py.run(self) # now locate _version.py in the new build/ directory and replace # it with an updated value if cfg.versionfile_build: target_versionfile = os.path.join(self.build_lib, cfg.versionfile_build) print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) cmds["build_py"] = cmd_build_py if "cx_Freeze" in sys.modules: # cx_freeze enabled? from cx_Freeze.dist import build_exe as _build_exe # nczeczulin reports that py2exe won't like the pep440-style string # as FILEVERSION, but it can be used for PRODUCTVERSION, e.g. # setup(console=[{ # "version": versioneer.get_version().split("+", 1)[0], # FILEVERSION # "product_version": versioneer.get_version(), # ... class cmd_build_exe(_build_exe): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() target_versionfile = cfg.versionfile_source print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) _build_exe.run(self) os.unlink(target_versionfile) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write(LONG % {"DOLLAR": "$", "STYLE": cfg.style, "TAG_PREFIX": cfg.tag_prefix, "PARENTDIR_PREFIX": cfg.parentdir_prefix, "VERSIONFILE_SOURCE": cfg.versionfile_source, }) cmds["build_exe"] = cmd_build_exe del cmds["build_py"] if 'py2exe' in sys.modules: # py2exe enabled? try: from py2exe.distutils_buildexe import py2exe as _py2exe # py3 except ImportError: from py2exe.build_exe import py2exe as _py2exe # py2 class cmd_py2exe(_py2exe): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() target_versionfile = cfg.versionfile_source print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) _py2exe.run(self) os.unlink(target_versionfile) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write(LONG % {"DOLLAR": "$", "STYLE": cfg.style, "TAG_PREFIX": cfg.tag_prefix, "PARENTDIR_PREFIX": cfg.parentdir_prefix, "VERSIONFILE_SOURCE": cfg.versionfile_source, }) cmds["py2exe"] = cmd_py2exe # we override different "sdist" commands for both environments if "setuptools" in sys.modules: from setuptools.command.sdist import sdist as _sdist else: from distutils.command.sdist import sdist as _sdist class cmd_sdist(_sdist): def run(self): versions = get_versions() self._versioneer_generated_versions = versions # unless we update this, the command will keep using the old # version self.distribution.metadata.version = versions["version"] return _sdist.run(self) def make_release_tree(self, base_dir, files): root = get_root() cfg = get_config_from_root(root) _sdist.make_release_tree(self, base_dir, files) # now locate _version.py in the new base_dir directory # (remembering that it may be a hardlink) and replace it with an # updated value target_versionfile = os.path.join(base_dir, cfg.versionfile_source) print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, self._versioneer_generated_versions) cmds["sdist"] = cmd_sdist return cmds
[ "def", "get_cmdclass", "(", ")", ":", "if", "\"versioneer\"", "in", "sys", ".", "modules", ":", "del", "sys", ".", "modules", "[", "\"versioneer\"", "]", "# this fixes the \"python setup.py develop\" case (also 'install' and", "# 'easy_install .'), in which subdependencies of...
https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/versioneer.py#L1483-L1650
OSGeo/gdal
3748fc4ba4fba727492774b2b908a2130c864a83
swig/python/osgeo/gdal.py
python
Band.GetNoDataValue
(self, *args)
return _gdal.Band_GetNoDataValue(self, *args)
r"""GetNoDataValue(Band self)
r"""GetNoDataValue(Band self)
[ "r", "GetNoDataValue", "(", "Band", "self", ")" ]
def GetNoDataValue(self, *args): r"""GetNoDataValue(Band self)""" return _gdal.Band_GetNoDataValue(self, *args)
[ "def", "GetNoDataValue", "(", "self", ",", "*", "args", ")", ":", "return", "_gdal", ".", "Band_GetNoDataValue", "(", "self", ",", "*", "args", ")" ]
https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/gdal.py#L3412-L3414
tfwu/FaceDetection-ConvNet-3D
f9251c48eb40c5aec8fba7455115c355466555be
python/mxnet/model.py
python
FeedForward._init_iter
(self, X, y, is_train)
return X
Initialize the iterator given input.
Initialize the iterator given input.
[ "Initialize", "the", "iterator", "given", "input", "." ]
def _init_iter(self, X, y, is_train): """Initialize the iterator given input.""" if isinstance(X, (np.ndarray, nd.NDArray)): if y is None: if is_train: raise ValueError('y must be specified when X is numpy.ndarray') else: y = np.zeros(X.shape[0]) if not isinstance(y, (np.ndarray, nd.NDArray)): raise TypeError('y must be ndarray when X is numpy.ndarray') if X.shape[0] != y.shape[0]: raise ValueError("The numbers of data points and labels not equal") if y.ndim == 2 and y.shape[1] == 1: y = y.flatten() if y.ndim != 1: raise ValueError("Label must be 1D or 2D (with 2nd dimension being 1)") if is_train: return io.NDArrayIter(X, y, min(X.shape[0], self.numpy_batch_size), shuffle=is_train, last_batch_handle='roll_over') else: return io.NDArrayIter(X, y, min(X.shape[0], self.numpy_batch_size), shuffle=False) if not isinstance(X, io.DataIter): raise TypeError('X must be DataIter, NDArray or numpy.ndarray') return X
[ "def", "_init_iter", "(", "self", ",", "X", ",", "y", ",", "is_train", ")", ":", "if", "isinstance", "(", "X", ",", "(", "np", ".", "ndarray", ",", "nd", ".", "NDArray", ")", ")", ":", "if", "y", "is", "None", ":", "if", "is_train", ":", "raise...
https://github.com/tfwu/FaceDetection-ConvNet-3D/blob/f9251c48eb40c5aec8fba7455115c355466555be/python/mxnet/model.py#L535-L558
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/propgrid.py
python
PGProperty.InsertChoice
(*args, **kwargs)
return _propgrid.PGProperty_InsertChoice(*args, **kwargs)
InsertChoice(self, String label, int index, int value=INT_MAX) -> int
InsertChoice(self, String label, int index, int value=INT_MAX) -> int
[ "InsertChoice", "(", "self", "String", "label", "int", "index", "int", "value", "=", "INT_MAX", ")", "-", ">", "int" ]
def InsertChoice(*args, **kwargs): """InsertChoice(self, String label, int index, int value=INT_MAX) -> int""" return _propgrid.PGProperty_InsertChoice(*args, **kwargs)
[ "def", "InsertChoice", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PGProperty_InsertChoice", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/propgrid.py#L579-L581
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_controls.py
python
TreeCtrl.GetFocusedItem
(*args, **kwargs)
return _controls_.TreeCtrl_GetFocusedItem(*args, **kwargs)
GetFocusedItem(self) -> TreeItemId
GetFocusedItem(self) -> TreeItemId
[ "GetFocusedItem", "(", "self", ")", "-", ">", "TreeItemId" ]
def GetFocusedItem(*args, **kwargs): """GetFocusedItem(self) -> TreeItemId""" return _controls_.TreeCtrl_GetFocusedItem(*args, **kwargs)
[ "def", "GetFocusedItem", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "TreeCtrl_GetFocusedItem", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L5371-L5373
google/syzygy
8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5
third_party/numpy/files/numpy/distutils/misc_util.py
python
Configuration.todict
(self)
return d
Return a dictionary compatible with the keyword arguments of distutils setup function. Examples -------- >>> setup(**config.todict()) #doctest: +SKIP
Return a dictionary compatible with the keyword arguments of distutils setup function.
[ "Return", "a", "dictionary", "compatible", "with", "the", "keyword", "arguments", "of", "distutils", "setup", "function", "." ]
def todict(self): """ Return a dictionary compatible with the keyword arguments of distutils setup function. Examples -------- >>> setup(**config.todict()) #doctest: +SKIP """ self._optimize_data_files() d = {} known_keys = self.list_keys + self.dict_keys + self.extra_keys for n in known_keys: a = getattr(self,n) if a: d[n] = a return d
[ "def", "todict", "(", "self", ")", ":", "self", ".", "_optimize_data_files", "(", ")", "d", "=", "{", "}", "known_keys", "=", "self", ".", "list_keys", "+", "self", ".", "dict_keys", "+", "self", ".", "extra_keys", "for", "n", "in", "known_keys", ":", ...
https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/distutils/misc_util.py#L772-L789
WeitaoVan/L-GM-loss
598582f0631bac876b3eeb8d6c4cd1d780269e03
scripts/cpp_lint.py
python
_ShouldPrintError
(category, confidence, linenum)
return True
If confidence >= verbose, category passes filter and is not suppressed.
If confidence >= verbose, category passes filter and is not suppressed.
[ "If", "confidence", ">", "=", "verbose", "category", "passes", "filter", "and", "is", "not", "suppressed", "." ]
def _ShouldPrintError(category, confidence, linenum): """If confidence >= verbose, category passes filter and is not suppressed.""" # There are three ways we might decide not to print an error message: # a "NOLINT(category)" comment appears in the source, # the verbosity level isn't high enough, or the filters filter it out. if IsErrorSuppressedByNolint(category, linenum): return False if confidence < _cpplint_state.verbose_level: return False is_filtered = False for one_filter in _Filters(): if one_filter.startswith('-'): if category.startswith(one_filter[1:]): is_filtered = True elif one_filter.startswith('+'): if category.startswith(one_filter[1:]): is_filtered = False else: assert False # should have been checked for in SetFilter. if is_filtered: return False return True
[ "def", "_ShouldPrintError", "(", "category", ",", "confidence", ",", "linenum", ")", ":", "# There are three ways we might decide not to print an error message:", "# a \"NOLINT(category)\" comment appears in the source,", "# the verbosity level isn't high enough, or the filters filter it out...
https://github.com/WeitaoVan/L-GM-loss/blob/598582f0631bac876b3eeb8d6c4cd1d780269e03/scripts/cpp_lint.py#L961-L985
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/syntax/synxml.py
python
FeatureList.GetFeature
(self, fet)
return feature
Get the callable feature by name @param fet: string (module name)
Get the callable feature by name @param fet: string (module name)
[ "Get", "the", "callable", "feature", "by", "name", "@param", "fet", ":", "string", "(", "module", "name", ")" ]
def GetFeature(self, fet): """Get the callable feature by name @param fet: string (module name) """ feature = None src = self._features.get(fet, None) if src is not None: feature = src return feature
[ "def", "GetFeature", "(", "self", ",", "fet", ")", ":", "feature", "=", "None", "src", "=", "self", ".", "_features", ".", "get", "(", "fet", ",", "None", ")", "if", "src", "is", "not", "None", ":", "feature", "=", "src", "return", "feature" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/syntax/synxml.py#L802-L811
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/util.py
python
is_installable_dir
(path)
return False
Return True if `path` is a directory containing a setup.py file.
Return True if `path` is a directory containing a setup.py file.
[ "Return", "True", "if", "path", "is", "a", "directory", "containing", "a", "setup", ".", "py", "file", "." ]
def is_installable_dir(path): """Return True if `path` is a directory containing a setup.py file.""" if not os.path.isdir(path): return False setup_py = os.path.join(path, 'setup.py') if os.path.isfile(setup_py): return True return False
[ "def", "is_installable_dir", "(", "path", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "return", "False", "setup_py", "=", "os", ".", "path", ".", "join", "(", "path", ",", "'setup.py'", ")", "if", "os", ".", "path...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/util.py#L190-L197
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/urllib3/fields.py
python
RequestField.make_multipart
( self, content_disposition=None, content_type=None, content_location=None )
Makes this request field into a multipart request field. This method overrides "Content-Disposition", "Content-Type" and "Content-Location" headers to the request parameter. :param content_type: The 'Content-Type' of the request body. :param content_location: The 'Content-Location' of the request body.
[]
def make_multipart( self, content_disposition=None, content_type=None, content_location=None ): """ Makes this request field into a multipart request field. This method overrides "Content-Disposition", "Content-Type" and "Content-Location" headers to the request parameter. :param content_type: The 'Content-Type' of the request body. :param content_location: The 'Content-Location' of the request body. """ self.headers["Content-Disposition"] = content_disposition or u"form-data" self.headers["Content-Disposition"] += u"; ".join( [ u"", self._render_parts( ((u"name", self._name), (u"filename", self._filename)) ), ] ) self.headers["Content-Type"] = content_type self.headers["Content-Location"] = content_location
[ "def", "make_multipart", "(", "self", ",", "content_disposition", "=", "None", ",", "content_type", "=", "None", ",", "content_location", "=", "None", ")", ":", "self", ".", "headers", "[", "\"Content-Disposition\"", "]", "=", "content_disposition", "or", "u\"fo...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/urllib3/fields.py#L497-L547
openthread/openthread
9fcdbed9c526c70f1556d1ed84099c1535c7cd32
tools/harness-thci/OpenThread.py
python
OpenThreadTHCI._deviceEscapeEscapable
(self, string)
return string
Escape CLI escapable characters in the given string. Args: string (str): UTF-8 input string. Returns: [str]: The modified string with escaped characters.
Escape CLI escapable characters in the given string.
[ "Escape", "CLI", "escapable", "characters", "in", "the", "given", "string", "." ]
def _deviceEscapeEscapable(self, string): """Escape CLI escapable characters in the given string. Args: string (str): UTF-8 input string. Returns: [str]: The modified string with escaped characters. """ escapable_chars = '\\ \t\r\n' for char in escapable_chars: string = string.replace(char, '\\%s' % char) return string
[ "def", "_deviceEscapeEscapable", "(", "self", ",", "string", ")", ":", "escapable_chars", "=", "'\\\\ \\t\\r\\n'", "for", "char", "in", "escapable_chars", ":", "string", "=", "string", ".", "replace", "(", "char", ",", "'\\\\%s'", "%", "char", ")", "return", ...
https://github.com/openthread/openthread/blob/9fcdbed9c526c70f1556d1ed84099c1535c7cd32/tools/harness-thci/OpenThread.py#L834-L846
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/src/robotsim.py
python
RigidObjectModel.saveFile
(self, fn: "char const *", geometryName: "char const *"=None)
return _robotsim.RigidObjectModel_saveFile(self, fn, geometryName)
r""" saveFile(RigidObjectModel self, char const * fn, char const * geometryName=None) -> bool Saves the object to the file fn. If geometryName is given, the geometry is saved to that file.
r""" saveFile(RigidObjectModel self, char const * fn, char const * geometryName=None) -> bool
[ "r", "saveFile", "(", "RigidObjectModel", "self", "char", "const", "*", "fn", "char", "const", "*", "geometryName", "=", "None", ")", "-", ">", "bool" ]
def saveFile(self, fn: "char const *", geometryName: "char const *"=None) -> "bool": r""" saveFile(RigidObjectModel self, char const * fn, char const * geometryName=None) -> bool Saves the object to the file fn. If geometryName is given, the geometry is saved to that file. """ return _robotsim.RigidObjectModel_saveFile(self, fn, geometryName)
[ "def", "saveFile", "(", "self", ",", "fn", ":", "\"char const *\"", ",", "geometryName", ":", "\"char const *\"", "=", "None", ")", "->", "\"bool\"", ":", "return", "_robotsim", ".", "RigidObjectModel_saveFile", "(", "self", ",", "fn", ",", "geometryName", ")"...
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/src/robotsim.py#L5566-L5575
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/math_grad.py
python
_MaximumGrad
(op, grad)
return _MaximumMinimumGrad(op, grad, math_ops.greater_equal)
Returns grad*(x >= y, x < y) with type of grad.
Returns grad*(x >= y, x < y) with type of grad.
[ "Returns", "grad", "*", "(", "x", ">", "=", "y", "x", "<", "y", ")", "with", "type", "of", "grad", "." ]
def _MaximumGrad(op, grad): """Returns grad*(x >= y, x < y) with type of grad.""" return _MaximumMinimumGrad(op, grad, math_ops.greater_equal)
[ "def", "_MaximumGrad", "(", "op", ",", "grad", ")", ":", "return", "_MaximumMinimumGrad", "(", "op", ",", "grad", ",", "math_ops", ".", "greater_equal", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/math_grad.py#L1592-L1594
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
deps/src/libxml2-2.9.1/python/libxml2class.py
python
xmlNode.setTreeDoc
(self, doc)
update all nodes under the tree to point to the right document
update all nodes under the tree to point to the right document
[ "update", "all", "nodes", "under", "the", "tree", "to", "point", "to", "the", "right", "document" ]
def setTreeDoc(self, doc): """update all nodes under the tree to point to the right document """ if doc is None: doc__o = None else: doc__o = doc._o libxml2mod.xmlSetTreeDoc(self._o, doc__o)
[ "def", "setTreeDoc", "(", "self", ",", "doc", ")", ":", "if", "doc", "is", "None", ":", "doc__o", "=", "None", "else", ":", "doc__o", "=", "doc", ".", "_o", "libxml2mod", ".", "xmlSetTreeDoc", "(", "self", ".", "_o", ",", "doc__o", ")" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2class.py#L2807-L2812
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/opt/python/training/moving_average_optimizer.py
python
MovingAverageOptimizer.swapping_saver
(self, var_list=None, name='swapping_saver', **kwargs)
return saver.Saver(swapped_var_list, name=name, **kwargs)
Create a saver swapping moving averages and variables. You should use this saver during training. It will save the moving averages of the trained parameters under the original parameter names. For evaluations or inference you should use a regular saver and it will automatically use the moving averages for the trained variable. You must call this function after all variables have been created and after you have called Optimizer.minimize(). Args: var_list: List of variables to save, as per `Saver()`. If set to None, will save all the variables that have been created before this call. name: The name of the saver. **kwargs: Keyword arguments of `Saver()`. Returns: A `tf.compat.v1.train.Saver` object. Raises: RuntimeError: If apply_gradients or minimize has not been called before. ValueError: If var_list is provided and contains some variables but not their moving average counterpart.
Create a saver swapping moving averages and variables.
[ "Create", "a", "saver", "swapping", "moving", "averages", "and", "variables", "." ]
def swapping_saver(self, var_list=None, name='swapping_saver', **kwargs): """Create a saver swapping moving averages and variables. You should use this saver during training. It will save the moving averages of the trained parameters under the original parameter names. For evaluations or inference you should use a regular saver and it will automatically use the moving averages for the trained variable. You must call this function after all variables have been created and after you have called Optimizer.minimize(). Args: var_list: List of variables to save, as per `Saver()`. If set to None, will save all the variables that have been created before this call. name: The name of the saver. **kwargs: Keyword arguments of `Saver()`. Returns: A `tf.compat.v1.train.Saver` object. Raises: RuntimeError: If apply_gradients or minimize has not been called before. ValueError: If var_list is provided and contains some variables but not their moving average counterpart. """ if self._swapped_variable_name_map is None: raise RuntimeError('Must call apply_gradients or minimize before ' 'creating the swapping_saver') if var_list is None: var_list = variables.global_variables() if not isinstance(var_list, dict): var_list = saveable_object_util.op_list_to_dict(var_list) v_name_to_tensor = {} for k, tensor_or_list in six.iteritems(var_list): # For each partitioned variable OpListToDict returns list of constituent # parts instead of single tensor. if (isinstance(tensor_or_list, list) or isinstance(tensor_or_list, variables.PartitionedVariable)): for tensor in tensor_or_list: v_name = tensor.op.name v_name_to_tensor[v_name] = tensor else: v_name_to_tensor[k] = tensor_or_list # Now swap variables and moving averages swapped_var_list = {} for k, tensor_or_list in six.iteritems(var_list): if isinstance(tensor_or_list, list): tensor_list_to_save = [] for tensor in tensor_or_list: v_name = tensor.op.name swapped_variable = self._find_swapped_variable(v_name_to_tensor, v_name, tensor) tensor_list_to_save.append(swapped_variable) swapped_var_list[k] = tensor_list_to_save else: swapped_var_list[k] = self._find_swapped_variable( v_name_to_tensor, k, tensor_or_list) # Build the swapping saver. return saver.Saver(swapped_var_list, name=name, **kwargs)
[ "def", "swapping_saver", "(", "self", ",", "var_list", "=", "None", ",", "name", "=", "'swapping_saver'", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_swapped_variable_name_map", "is", "None", ":", "raise", "RuntimeError", "(", "'Must call apply_gra...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/opt/python/training/moving_average_optimizer.py#L136-L200
bumptop/BumpTop
466d23597a07ae738f4265262fa01087fc6e257c
trunk/mac/Build/cpplint.py
python
_CppLintState.SetVerboseLevel
(self, level)
return last_verbose_level
Sets the module's verbosity, and returns the previous setting.
Sets the module's verbosity, and returns the previous setting.
[ "Sets", "the", "module", "s", "verbosity", "and", "returns", "the", "previous", "setting", "." ]
def SetVerboseLevel(self, level): """Sets the module's verbosity, and returns the previous setting.""" last_verbose_level = self.verbose_level self.verbose_level = level return last_verbose_level
[ "def", "SetVerboseLevel", "(", "self", ",", "level", ")", ":", "last_verbose_level", "=", "self", ".", "verbose_level", "self", ".", "verbose_level", "=", "level", "return", "last_verbose_level" ]
https://github.com/bumptop/BumpTop/blob/466d23597a07ae738f4265262fa01087fc6e257c/trunk/mac/Build/cpplint.py#L374-L378
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/model/create/moving_base_robot.py
python
set_xform
(robot,R,t)
For a moving base robot model, set the current base rotation matrix R and translation t. (Note: if you are controlling a robot during simulation, use send_moving_base_xform_command)
For a moving base robot model, set the current base rotation matrix R and translation t. (Note: if you are controlling a robot during simulation, use send_moving_base_xform_command)
[ "For", "a", "moving", "base", "robot", "model", "set", "the", "current", "base", "rotation", "matrix", "R", "and", "translation", "t", ".", "(", "Note", ":", "if", "you", "are", "controlling", "a", "robot", "during", "simulation", "use", "send_moving_base_xf...
def set_xform(robot,R,t): """For a moving base robot model, set the current base rotation matrix R and translation t. (Note: if you are controlling a robot during simulation, use send_moving_base_xform_command) """ q = robot.getConfig() for i in range(3): q[i] = t[i] roll,pitch,yaw = so3.rpy(R) q[3]=yaw q[4]=pitch q[5]=roll robot.setConfig(q)
[ "def", "set_xform", "(", "robot", ",", "R", ",", "t", ")", ":", "q", "=", "robot", ".", "getConfig", "(", ")", "for", "i", "in", "range", "(", "3", ")", ":", "q", "[", "i", "]", "=", "t", "[", "i", "]", "roll", ",", "pitch", ",", "yaw", "...
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/model/create/moving_base_robot.py#L108-L120
nest/nest-simulator
f2623eb78518cdbd55e77e0ed486bf1111bcb62f
pynest/nest/ll_api.py
python
init
(argv)
Initializes NEST. If the environment variable PYNEST_QUIET is set, NEST will not print welcome text containing the version and other information. Likewise, if the environment variable PYNEST_DEBUG is set, NEST starts in debug mode. Note that the same effect can be achieved by using the commandline arguments --quiet and --debug respectively. Parameters ---------- argv : list Command line arguments, passed to the NEST kernel Raises ------ kernel.NESTError.PyNESTError
Initializes NEST.
[ "Initializes", "NEST", "." ]
def init(argv): """Initializes NEST. If the environment variable PYNEST_QUIET is set, NEST will not print welcome text containing the version and other information. Likewise, if the environment variable PYNEST_DEBUG is set, NEST starts in debug mode. Note that the same effect can be achieved by using the commandline arguments --quiet and --debug respectively. Parameters ---------- argv : list Command line arguments, passed to the NEST kernel Raises ------ kernel.NESTError.PyNESTError """ global initialized if initialized: raise kernel.NESTErrors.PyNESTError("NEST already initialized.") # Some commandline arguments of NEST and Python have the same # name, but different meaning. To avoid unintended behavior, we # handle NEST's arguments here and pass it a modified copy, while # we leave the original list unchanged for further use by the user # or other modules. nest_argv = argv[:] quiet = "--quiet" in nest_argv or 'PYNEST_QUIET' in os.environ if "--quiet" in nest_argv: nest_argv.remove("--quiet") if "--debug" in nest_argv: nest_argv.remove("--debug") if "--sli-debug" in nest_argv: nest_argv.remove("--sli-debug") nest_argv.append("--debug") if 'PYNEST_DEBUG' in os.environ and '--debug' not in nest_argv: nest_argv.append("--debug") path = os.path.dirname(__file__) initialized = engine.init(nest_argv, path) if initialized: if not quiet: engine.run("pywelcome") # Dirty hack to get tab-completion for models in IPython. try: __IPYTHON__ except NameError: pass else: try: import keyword from .lib.hl_api_models import Models # noqa keyword.kwlist += Models() except ImportError: pass else: raise kernel.NESTErrors.PyNESTError("Initialization of NEST failed.")
[ "def", "init", "(", "argv", ")", ":", "global", "initialized", "if", "initialized", ":", "raise", "kernel", ".", "NESTErrors", ".", "PyNESTError", "(", "\"NEST already initialized.\"", ")", "# Some commandline arguments of NEST and Python have the same", "# name, but differ...
https://github.com/nest/nest-simulator/blob/f2623eb78518cdbd55e77e0ed486bf1111bcb62f/pynest/nest/ll_api.py#L343-L407
vnpy/vnpy
f50f2535ed39dd33272e0985ed40c7078e4c19f6
vnpy/trader/utility.py
python
ArrayManager.plus_dm
(self, n: int, array: bool = False)
return result[-1]
PLUS_DM.
PLUS_DM.
[ "PLUS_DM", "." ]
def plus_dm(self, n: int, array: bool = False) -> Union[float, np.ndarray]: """ PLUS_DM. """ result = talib.PLUS_DM(self.high, self.low, n) if array: return result return result[-1]
[ "def", "plus_dm", "(", "self", ",", "n", ":", "int", ",", "array", ":", "bool", "=", "False", ")", "->", "Union", "[", "float", ",", "np", ".", "ndarray", "]", ":", "result", "=", "talib", ".", "PLUS_DM", "(", "self", ".", "high", ",", "self", ...
https://github.com/vnpy/vnpy/blob/f50f2535ed39dd33272e0985ed40c7078e4c19f6/vnpy/trader/utility.py#L903-L911
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
src/pybind/mgr/orchestrator/_interface.py
python
Orchestrator.upgrade_status
(self)
If an upgrade is currently underway, report on where we are in the process, or if some error has occurred. :return: UpgradeStatusSpec instance
If an upgrade is currently underway, report on where we are in the process, or if some error has occurred.
[ "If", "an", "upgrade", "is", "currently", "underway", "report", "on", "where", "we", "are", "in", "the", "process", "or", "if", "some", "error", "has", "occurred", "." ]
def upgrade_status(self) -> OrchResult['UpgradeStatusSpec']: """ If an upgrade is currently underway, report on where we are in the process, or if some error has occurred. :return: UpgradeStatusSpec instance """ raise NotImplementedError()
[ "def", "upgrade_status", "(", "self", ")", "->", "OrchResult", "[", "'UpgradeStatusSpec'", "]", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/pybind/mgr/orchestrator/_interface.py#L677-L684
deepmind/open_spiel
4ca53bea32bb2875c7385d215424048ae92f78c8
open_spiel/python/mfg/distribution.py
python
Distribution.value
(self, state)
Returns the probability of the distribution on the state. Args: state: A `pyspiel.State` object. Returns: A `float`.
Returns the probability of the distribution on the state.
[ "Returns", "the", "probability", "of", "the", "distribution", "on", "the", "state", "." ]
def value(self, state): """Returns the probability of the distribution on the state. Args: state: A `pyspiel.State` object. Returns: A `float`. """ raise NotImplementedError()
[ "def", "value", "(", "self", ",", "state", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/mfg/distribution.py#L42-L51
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/contrib/framework/python/ops/variables.py
python
get_global_step
(graph=None)
return global_step_tensor
Get the global step tensor. The global step tensor must be an integer variable. We first try to find it in the collection `GLOBAL_STEP`, or by name `global_step:0`. Args: graph: The graph to find the global step in. If missing, use default graph. Returns: The global step variable, or `None` if none was found. Raises: TypeError: If the global step tensor has a non-integer type, or if it is not a `Variable`.
Get the global step tensor.
[ "Get", "the", "global", "step", "tensor", "." ]
def get_global_step(graph=None): """Get the global step tensor. The global step tensor must be an integer variable. We first try to find it in the collection `GLOBAL_STEP`, or by name `global_step:0`. Args: graph: The graph to find the global step in. If missing, use default graph. Returns: The global step variable, or `None` if none was found. Raises: TypeError: If the global step tensor has a non-integer type, or if it is not a `Variable`. """ graph = ops.get_default_graph() if graph is None else graph global_step_tensor = None global_step_tensors = graph.get_collection(ops.GraphKeys.GLOBAL_STEP) if len(global_step_tensors) == 1: global_step_tensor = global_step_tensors[0] elif not global_step_tensors: try: global_step_tensor = graph.get_tensor_by_name('global_step:0') except KeyError: return None else: logging.error('Multiple tensors in global_step collection.') return None assert_global_step(global_step_tensor) return global_step_tensor
[ "def", "get_global_step", "(", "graph", "=", "None", ")", ":", "graph", "=", "ops", ".", "get_default_graph", "(", ")", "if", "graph", "is", "None", "else", "graph", "global_step_tensor", "=", "None", "global_step_tensors", "=", "graph", ".", "get_collection",...
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/framework/python/ops/variables.py#L102-L133
eric612/Caffe-YOLOv3-Windows
6736ca6e16781789b828cc64218ff77cc3454e5d
python/caffe/io.py
python
Transformer.set_raw_scale
(self, in_, scale)
Set the scale of raw features s.t. the input blob = input * scale. While Python represents images in [0, 1], certain Caffe models like CaffeNet and AlexNet represent images in [0, 255] so the raw_scale of these models must be 255. Parameters ---------- in_ : which input to assign this scale factor scale : scale coefficient
Set the scale of raw features s.t. the input blob = input * scale. While Python represents images in [0, 1], certain Caffe models like CaffeNet and AlexNet represent images in [0, 255] so the raw_scale of these models must be 255.
[ "Set", "the", "scale", "of", "raw", "features", "s", ".", "t", ".", "the", "input", "blob", "=", "input", "*", "scale", ".", "While", "Python", "represents", "images", "in", "[", "0", "1", "]", "certain", "Caffe", "models", "like", "CaffeNet", "and", ...
def set_raw_scale(self, in_, scale): """ Set the scale of raw features s.t. the input blob = input * scale. While Python represents images in [0, 1], certain Caffe models like CaffeNet and AlexNet represent images in [0, 255] so the raw_scale of these models must be 255. Parameters ---------- in_ : which input to assign this scale factor scale : scale coefficient """ self.__check_input(in_) self.raw_scale[in_] = scale
[ "def", "set_raw_scale", "(", "self", ",", "in_", ",", "scale", ")", ":", "self", ".", "__check_input", "(", "in_", ")", "self", ".", "raw_scale", "[", "in_", "]", "=", "scale" ]
https://github.com/eric612/Caffe-YOLOv3-Windows/blob/6736ca6e16781789b828cc64218ff77cc3454e5d/python/caffe/io.py#L221-L234
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/decimal.py
python
Decimal.is_nan
(self)
return self._exp in ('n', 'N')
Return True if self is a qNaN or sNaN; otherwise return False.
Return True if self is a qNaN or sNaN; otherwise return False.
[ "Return", "True", "if", "self", "is", "a", "qNaN", "or", "sNaN", ";", "otherwise", "return", "False", "." ]
def is_nan(self): """Return True if self is a qNaN or sNaN; otherwise return False.""" return self._exp in ('n', 'N')
[ "def", "is_nan", "(", "self", ")", ":", "return", "self", ".", "_exp", "in", "(", "'n'", ",", "'N'", ")" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/decimal.py#L2871-L2873
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/debug/framework.py
python
BaseDebugWrapperSession.on_session_init
(self, request)
Callback invoked during construction of the debug-wrapper session. This is a blocking callback. The invocation happens right before the constructor ends. Args: request: (OnSessionInitRequest) callback request carrying information such as the session being wrapped. Returns: An instance of OnSessionInitResponse.
Callback invoked during construction of the debug-wrapper session.
[ "Callback", "invoked", "during", "construction", "of", "the", "debug", "-", "wrapper", "session", "." ]
def on_session_init(self, request): """Callback invoked during construction of the debug-wrapper session. This is a blocking callback. The invocation happens right before the constructor ends. Args: request: (OnSessionInitRequest) callback request carrying information such as the session being wrapped. Returns: An instance of OnSessionInitResponse. """ pass
[ "def", "on_session_init", "(", "self", ",", "request", ")", ":", "pass" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/debug/framework.py#L418-L431
turi-code/SFrame
796b9bdfb2fa1b881d82080754643c7e68629cd2
oss_src/unity/python/sframe/data_structures/sarray.py
python
SArray.argmax
(self)
return sf_out['maximum_x1'][0]
Get the index of the maximum numeric value in SArray. Returns None on an empty SArray. Raises an exception if called on an SArray with non-numeric type. Returns ------- out : int Index of the maximum value of SArray See Also -------- argmin Examples -------- >>> graphlab.SArray([14, 62, 83, 72, 77, 96, 5, 25, 69, 66]).argmax()
Get the index of the maximum numeric value in SArray.
[ "Get", "the", "index", "of", "the", "maximum", "numeric", "value", "in", "SArray", "." ]
def argmax(self): """ Get the index of the maximum numeric value in SArray. Returns None on an empty SArray. Raises an exception if called on an SArray with non-numeric type. Returns ------- out : int Index of the maximum value of SArray See Also -------- argmin Examples -------- >>> graphlab.SArray([14, 62, 83, 72, 77, 96, 5, 25, 69, 66]).argmax() """ from .sframe import SFrame as _SFrame if len(self) == 0: return None if not any([isinstance(self[0], i) for i in [int,float,long]]): raise TypeError("SArray must be of type 'int', 'long', or 'float'.") sf = _SFrame(self).add_row_number() sf_out = sf.groupby(key_columns=[],operations={'maximum_x1': _aggregate.ARGMAX('X1','id')}) return sf_out['maximum_x1'][0]
[ "def", "argmax", "(", "self", ")", ":", "from", ".", "sframe", "import", "SFrame", "as", "_SFrame", "if", "len", "(", "self", ")", "==", "0", ":", "return", "None", "if", "not", "any", "(", "[", "isinstance", "(", "self", "[", "0", "]", ",", "i",...
https://github.com/turi-code/SFrame/blob/796b9bdfb2fa1b881d82080754643c7e68629cd2/oss_src/unity/python/sframe/data_structures/sarray.py#L2137-L2167
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/ensemble/gradient_boosting.py
python
BaseGradientBoosting._fit_stages
(self, X, y, y_pred, sample_weight, random_state, begin_at_stage=0, monitor=None, X_idx_sorted=None)
return i + 1
Iteratively fits the stages. For each stage it computes the progress (OOB, train score) and delegates to ``_fit_stage``. Returns the number of stages fit; might differ from ``n_estimators`` due to early stopping.
Iteratively fits the stages.
[ "Iteratively", "fits", "the", "stages", "." ]
def _fit_stages(self, X, y, y_pred, sample_weight, random_state, begin_at_stage=0, monitor=None, X_idx_sorted=None): """Iteratively fits the stages. For each stage it computes the progress (OOB, train score) and delegates to ``_fit_stage``. Returns the number of stages fit; might differ from ``n_estimators`` due to early stopping. """ n_samples = X.shape[0] do_oob = self.subsample < 1.0 sample_mask = np.ones((n_samples, ), dtype=np.bool) n_inbag = max(1, int(self.subsample * n_samples)) loss_ = self.loss_ # Set min_weight_leaf from min_weight_fraction_leaf if self.min_weight_fraction_leaf != 0. and sample_weight is not None: min_weight_leaf = (self.min_weight_fraction_leaf * np.sum(sample_weight)) else: min_weight_leaf = 0. if self.verbose: verbose_reporter = VerboseReporter(self.verbose) verbose_reporter.init(self, begin_at_stage) X_csc = csc_matrix(X) if issparse(X) else None X_csr = csr_matrix(X) if issparse(X) else None # perform boosting iterations i = begin_at_stage for i in range(begin_at_stage, self.n_estimators): # subsampling if do_oob: sample_mask = _random_sample_mask(n_samples, n_inbag, random_state) # OOB score before adding this stage old_oob_score = loss_(y[~sample_mask], y_pred[~sample_mask], sample_weight[~sample_mask]) # fit next stage of trees y_pred = self._fit_stage(i, X, y, y_pred, sample_weight, sample_mask, random_state, X_idx_sorted, X_csc, X_csr) # track deviance (= loss) if do_oob: self.train_score_[i] = loss_(y[sample_mask], y_pred[sample_mask], sample_weight[sample_mask]) self.oob_improvement_[i] = ( old_oob_score - loss_(y[~sample_mask], y_pred[~sample_mask], sample_weight[~sample_mask])) else: # no need to fancy index w/ no subsampling self.train_score_[i] = loss_(y, y_pred, sample_weight) if self.verbose > 0: verbose_reporter.update(i, self) if monitor is not None: early_stopping = monitor(i, self, locals()) if early_stopping: break return i + 1
[ "def", "_fit_stages", "(", "self", ",", "X", ",", "y", ",", "y_pred", ",", "sample_weight", ",", "random_state", ",", "begin_at_stage", "=", "0", ",", "monitor", "=", "None", ",", "X_idx_sorted", "=", "None", ")", ":", "n_samples", "=", "X", ".", "shap...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/ensemble/gradient_boosting.py#L1038-L1105
yuxng/DA-RNN
77fbb50b4272514588a10a9f90b7d5f8d46974fb
lib/networks/fcn8_vgg.py
python
_activation_summary
(x)
Helper to create summaries for activations. Creates a summary that provides a histogram of activations. Creates a summary that measure the sparsity of activations. Args: x: Tensor Returns: nothing
Helper to create summaries for activations.
[ "Helper", "to", "create", "summaries", "for", "activations", "." ]
def _activation_summary(x): """Helper to create summaries for activations. Creates a summary that provides a histogram of activations. Creates a summary that measure the sparsity of activations. Args: x: Tensor Returns: nothing """ # Remove 'tower_[0-9]/' from the name in case this is a multi-GPU training # session. This helps the clarity of presentation on tensorboard. tensor_name = x.op.name # tensor_name = re.sub('%s_[0-9]*/' % TOWER_NAME, '', x.op.name) tf.histogram_summary(tensor_name + '/activations', x) tf.scalar_summary(tensor_name + '/sparsity', tf.nn.zero_fraction(x))
[ "def", "_activation_summary", "(", "x", ")", ":", "# Remove 'tower_[0-9]/' from the name in case this is a multi-GPU training", "# session. This helps the clarity of presentation on tensorboard.", "tensor_name", "=", "x", ".", "op", ".", "name", "# tensor_name = re.sub('%s_[0-9]*/' % T...
https://github.com/yuxng/DA-RNN/blob/77fbb50b4272514588a10a9f90b7d5f8d46974fb/lib/networks/fcn8_vgg.py#L435-L451
NREL/EnergyPlus
fadc5973b85c70e8cc923efb69c144e808a26078
doc/tools/parse_latex_log.py
python
parse_warning_start
(line)
return None
- line: str, line RETURN: None OR (Tuple str, str, str) - the warning type - warning type continued (usually for package) - the message
- line: str, line RETURN: None OR (Tuple str, str, str) - the warning type - warning type continued (usually for package) - the message
[ "-", "line", ":", "str", "line", "RETURN", ":", "None", "OR", "(", "Tuple", "str", "str", "str", ")", "-", "the", "warning", "type", "-", "warning", "type", "continued", "(", "usually", "for", "package", ")", "-", "the", "message" ]
def parse_warning_start(line): """ - line: str, line RETURN: None OR (Tuple str, str, str) - the warning type - warning type continued (usually for package) - the message """ m = GENERAL_WARNING.match(line) if m is not None: return (m.group(2), m.group(4), m.group(5)) return None
[ "def", "parse_warning_start", "(", "line", ")", ":", "m", "=", "GENERAL_WARNING", ".", "match", "(", "line", ")", "if", "m", "is", "not", "None", ":", "return", "(", "m", ".", "group", "(", "2", ")", ",", "m", ".", "group", "(", "4", ")", ",", ...
https://github.com/NREL/EnergyPlus/blob/fadc5973b85c70e8cc923efb69c144e808a26078/doc/tools/parse_latex_log.py#L129-L141
yun-liu/RCF
91bfb054ad04187dbbe21e539e165ad9bd3ff00b
scripts/cpp_lint.py
python
CheckForNewlineAtEOF
(filename, lines, error)
Logs an error if there is no newline char at the end of the file. Args: filename: The name of the current file. lines: An array of strings, each representing a line of the file. error: The function to call with any errors found.
Logs an error if there is no newline char at the end of the file.
[ "Logs", "an", "error", "if", "there", "is", "no", "newline", "char", "at", "the", "end", "of", "the", "file", "." ]
def CheckForNewlineAtEOF(filename, lines, error): """Logs an error if there is no newline char at the end of the file. Args: filename: The name of the current file. lines: An array of strings, each representing a line of the file. error: The function to call with any errors found. """ # The array lines() was created by adding two newlines to the # original file (go figure), then splitting on \n. # To verify that the file ends in \n, we just have to make sure the # last-but-two element of lines() exists and is empty. if len(lines) < 3 or lines[-2]: error(filename, len(lines) - 2, 'whitespace/ending_newline', 5, 'Could not find a newline character at the end of the file.')
[ "def", "CheckForNewlineAtEOF", "(", "filename", ",", "lines", ",", "error", ")", ":", "# The array lines() was created by adding two newlines to the", "# original file (go figure), then splitting on \\n.", "# To verify that the file ends in \\n, we just have to make sure the", "# last-but-...
https://github.com/yun-liu/RCF/blob/91bfb054ad04187dbbe21e539e165ad9bd3ff00b/scripts/cpp_lint.py#L1508-L1523
Slicer/SlicerGitSVNArchive
65e92bb16c2b32ea47a1a66bee71f238891ee1ca
Modules/Scripted/EditorLib/Effect.py
python
EffectLogic.layerXYToIJK
(self,layerLogic,xyPoint)
return (i,j,k)
return i j k in image space of the layer for a given x y
return i j k in image space of the layer for a given x y
[ "return", "i", "j", "k", "in", "image", "space", "of", "the", "layer", "for", "a", "given", "x", "y" ]
def layerXYToIJK(self,layerLogic,xyPoint): """return i j k in image space of the layer for a given x y""" xyToIJK = layerLogic.GetXYToIJKTransform() ijk = xyToIJK.TransformDoublePoint(xyPoint + (0,)) i = int(round(ijk[0])) j = int(round(ijk[1])) k = int(round(ijk[2])) return (i,j,k)
[ "def", "layerXYToIJK", "(", "self", ",", "layerLogic", ",", "xyPoint", ")", ":", "xyToIJK", "=", "layerLogic", ".", "GetXYToIJKTransform", "(", ")", "ijk", "=", "xyToIJK", ".", "TransformDoublePoint", "(", "xyPoint", "+", "(", "0", ",", ")", ")", "i", "=...
https://github.com/Slicer/SlicerGitSVNArchive/blob/65e92bb16c2b32ea47a1a66bee71f238891ee1ca/Modules/Scripted/EditorLib/Effect.py#L307-L314
neoml-lib/neoml
a0d370fba05269a1b2258cef126f77bbd2054a3e
NeoML/Python/neoml/Dnn/Dnn.py
python
Dnn.store_checkpoint
(self, path)
Serializes the network with the data required to resume training. :param path: The full path to the location where the network should be stored. :type path: str
Serializes the network with the data required to resume training. :param path: The full path to the location where the network should be stored. :type path: str
[ "Serializes", "the", "network", "with", "the", "data", "required", "to", "resume", "training", ".", ":", "param", "path", ":", "The", "full", "path", "to", "the", "location", "where", "the", "network", "should", "be", "stored", ".", ":", "type", "path", ...
def store_checkpoint(self, path): """Serializes the network with the data required to resume training. :param path: The full path to the location where the network should be stored. :type path: str """ self._store_checkpoint(str(path))
[ "def", "store_checkpoint", "(", "self", ",", "path", ")", ":", "self", ".", "_store_checkpoint", "(", "str", "(", "path", ")", ")" ]
https://github.com/neoml-lib/neoml/blob/a0d370fba05269a1b2258cef126f77bbd2054a3e/NeoML/Python/neoml/Dnn/Dnn.py#L62-L68