repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
genepattern/genepattern-python
gp/core.py
https://github.com/genepattern/genepattern-python/blob/9478ea65362b91c72a94f7300c3de8d710bebb71/gp/core.py#L305-L323
def load_info(self): """ Parses the JSON object stored at GPJob.info and assigns its metadata to properties of this GPJob object. Primarily intended to be called from GPJob.get_info(). """ self.task_name = self.info['taskName'] self.task_lsid = self.info['taskLsi...
[ "def", "load_info", "(", "self", ")", ":", "self", ".", "task_name", "=", "self", ".", "info", "[", "'taskName'", "]", "self", ".", "task_lsid", "=", "self", ".", "info", "[", "'taskLsid'", "]", "self", ".", "user_id", "=", "self", ".", "info", "[", ...
Parses the JSON object stored at GPJob.info and assigns its metadata to properties of this GPJob object. Primarily intended to be called from GPJob.get_info().
[ "Parses", "the", "JSON", "object", "stored", "at", "GPJob", ".", "info", "and", "assigns", "its", "metadata", "to", "properties", "of", "this", "GPJob", "object", "." ]
python
train
20c/xbahn
xbahn/api.py
https://github.com/20c/xbahn/blob/afb27b0576841338a366d7cac0200a782bd84be6/xbahn/api.py#L304-L350
def on_receive(self, message=None, wire=None, event_origin=None): """ event handler bound to the receive event of the link the server is wired too. Arguments: - message (message.Message): incoming message Keyword arguments: - event_origin (connection.Li...
[ "def", "on_receive", "(", "self", ",", "message", "=", "None", ",", "wire", "=", "None", ",", "event_origin", "=", "None", ")", ":", "self", ".", "trigger", "(", "\"before_call\"", ",", "message", ")", "fn_name", "=", "message", ".", "data", "pmsg", "=...
event handler bound to the receive event of the link the server is wired too. Arguments: - message (message.Message): incoming message Keyword arguments: - event_origin (connection.Link)
[ "event", "handler", "bound", "to", "the", "receive", "event", "of", "the", "link", "the", "server", "is", "wired", "too", "." ]
python
train
mongodb/mongo-python-driver
pymongo/change_stream.py
https://github.com/mongodb/mongo-python-driver/blob/c29c21449e3aae74154207058cf85fd94018d4cd/pymongo/change_stream.py#L226-L283
def try_next(self): """Advance the cursor without blocking indefinitely. This method returns the next change document without waiting indefinitely for the next change. For example:: with db.collection.watch() as stream: while stream.alive: change...
[ "def", "try_next", "(", "self", ")", ":", "# Attempt to get the next change with at most one getMore and at most", "# one resume attempt.", "try", ":", "change", "=", "self", ".", "_cursor", ".", "_try_next", "(", "True", ")", "except", "ConnectionFailure", ":", "self",...
Advance the cursor without blocking indefinitely. This method returns the next change document without waiting indefinitely for the next change. For example:: with db.collection.watch() as stream: while stream.alive: change = stream.try_next() ...
[ "Advance", "the", "cursor", "without", "blocking", "indefinitely", "." ]
python
train
Mxit/python-mxit
mxit/services.py
https://github.com/Mxit/python-mxit/blob/6b18a54ef6fbfe1f9d94755ba3d4ad77743c8b0c/mxit/services.py#L274-L287
def get_friend_suggestions(self, scope='graph/read'): """ Retrieve the Mxit user's full profile User authentication required with the following scope: 'graph/read' """ suggestions = _get( token=self.oauth.get_user_token(scope), uri='/user/socialgraph/sugge...
[ "def", "get_friend_suggestions", "(", "self", ",", "scope", "=", "'graph/read'", ")", ":", "suggestions", "=", "_get", "(", "token", "=", "self", ".", "oauth", ".", "get_user_token", "(", "scope", ")", ",", "uri", "=", "'/user/socialgraph/suggestions'", ")", ...
Retrieve the Mxit user's full profile User authentication required with the following scope: 'graph/read'
[ "Retrieve", "the", "Mxit", "user", "s", "full", "profile", "User", "authentication", "required", "with", "the", "following", "scope", ":", "graph", "/", "read" ]
python
train
wummel/linkchecker
linkcheck/lock.py
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/lock.py#L59-L74
def get_semaphore(name, value=None, debug=False): """Get a new semaphore. @param value: if not None, a BoundedSemaphore will be used @ptype debug: int or None @param debug: if True, acquire() and release() will have debug messages @ptype debug: boolean, default is False @return: a semaphore obje...
[ "def", "get_semaphore", "(", "name", ",", "value", "=", "None", ",", "debug", "=", "False", ")", ":", "if", "value", "is", "None", ":", "lock", "=", "threading", ".", "Semaphore", "(", ")", "else", ":", "lock", "=", "threading", ".", "BoundedSemaphore"...
Get a new semaphore. @param value: if not None, a BoundedSemaphore will be used @ptype debug: int or None @param debug: if True, acquire() and release() will have debug messages @ptype debug: boolean, default is False @return: a semaphore object @rtype: threading.Semaphore or threading.BoundedSe...
[ "Get", "a", "new", "semaphore", "." ]
python
train
tbielawa/bitmath
bitmath/__init__.py
https://github.com/tbielawa/bitmath/blob/58ad3ac5f076cc6e53f36a91af055c6028c850a5/bitmath/__init__.py#L439-L528
def best_prefix(self, system=None): """Optional parameter, `system`, allows you to prefer NIST or SI in the results. By default, the current system is used (Bit/Byte default to NIST). Logic discussion/notes: Base-case, does it need converting? If the instance is less than one Byte, return the instance as a B...
[ "def", "best_prefix", "(", "self", ",", "system", "=", "None", ")", ":", "# Use absolute value so we don't return Bit's for *everything*", "# less than Byte(1). From github issue #55", "if", "abs", "(", "self", ")", "<", "Byte", "(", "1", ")", ":", "return", "Bit", ...
Optional parameter, `system`, allows you to prefer NIST or SI in the results. By default, the current system is used (Bit/Byte default to NIST). Logic discussion/notes: Base-case, does it need converting? If the instance is less than one Byte, return the instance as a Bit instance. Else, begin by recording the unit...
[ "Optional", "parameter", "system", "allows", "you", "to", "prefer", "NIST", "or", "SI", "in", "the", "results", ".", "By", "default", "the", "current", "system", "is", "used", "(", "Bit", "/", "Byte", "default", "to", "NIST", ")", "." ]
python
train
agile-geoscience/welly
welly/utils.py
https://github.com/agile-geoscience/welly/blob/ed4c991011d6290938fef365553041026ba29f42/welly/utils.py#L307-L323
def normalize(a, new_min=0.0, new_max=1.0): """ From ``bruges`` Normalize an array to [0,1] or to arbitrary new min and max. Args: a (ndarray) new_min (float): the new min, default 0. new_max (float): the new max, default 1. Returns: ndarray. The normalized array. ...
[ "def", "normalize", "(", "a", ",", "new_min", "=", "0.0", ",", "new_max", "=", "1.0", ")", ":", "n", "=", "(", "a", "-", "np", ".", "amin", "(", "a", ")", ")", "/", "np", ".", "amax", "(", "a", "-", "np", ".", "amin", "(", "a", ")", ")", ...
From ``bruges`` Normalize an array to [0,1] or to arbitrary new min and max. Args: a (ndarray) new_min (float): the new min, default 0. new_max (float): the new max, default 1. Returns: ndarray. The normalized array.
[ "From", "bruges" ]
python
train
isislovecruft/python-gnupg
pretty_bad_protocol/_meta.py
https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_meta.py#L795-L814
def _recv_keys(self, keyids, keyserver=None): """Import keys from a keyserver. :param str keyids: A space-delimited string containing the keyids to request. :param str keyserver: The keyserver to request the ``keyids`` from; defaults to `...
[ "def", "_recv_keys", "(", "self", ",", "keyids", ",", "keyserver", "=", "None", ")", ":", "if", "not", "keyserver", ":", "keyserver", "=", "self", ".", "keyserver", "args", "=", "[", "'--keyserver {0}'", ".", "format", "(", "keyserver", ")", ",", "'--rec...
Import keys from a keyserver. :param str keyids: A space-delimited string containing the keyids to request. :param str keyserver: The keyserver to request the ``keyids`` from; defaults to `gnupg.GPG.keyserver`.
[ "Import", "keys", "from", "a", "keyserver", "." ]
python
train
tanghaibao/jcvi
jcvi/formats/blast.py
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/blast.py#L367-L380
def collect_gaps(blast, use_subject=False): """ Collect the gaps between adjacent HSPs in the BLAST file. """ key = lambda x: x.sstart if use_subject else x.qstart blast.sort(key=key) for a, b in zip(blast, blast[1:]): if use_subject: if a.sstop < b.sstart: y...
[ "def", "collect_gaps", "(", "blast", ",", "use_subject", "=", "False", ")", ":", "key", "=", "lambda", "x", ":", "x", ".", "sstart", "if", "use_subject", "else", "x", ".", "qstart", "blast", ".", "sort", "(", "key", "=", "key", ")", "for", "a", ","...
Collect the gaps between adjacent HSPs in the BLAST file.
[ "Collect", "the", "gaps", "between", "adjacent", "HSPs", "in", "the", "BLAST", "file", "." ]
python
train
Atomistica/atomistica
src/python/atomistica/io.py
https://github.com/Atomistica/atomistica/blob/5ed79d776c92b91a566be22615bfb304ecc75db7/src/python/atomistica/io.py#L76-L89
def write(fn, a, **kwargs): """ Convenience function: Detect file extension and write via Atomistica or ASE. Has support for writing LAMMPS data files. """ ext = fn[fn.rfind('.'):].split('@') if ext[0] == '.out' or ext[0] == '.dat': return write_atoms(fn, a) elif ext[0] == '.lammps':...
[ "def", "write", "(", "fn", ",", "a", ",", "*", "*", "kwargs", ")", ":", "ext", "=", "fn", "[", "fn", ".", "rfind", "(", "'.'", ")", ":", "]", ".", "split", "(", "'@'", ")", "if", "ext", "[", "0", "]", "==", "'.out'", "or", "ext", "[", "0"...
Convenience function: Detect file extension and write via Atomistica or ASE. Has support for writing LAMMPS data files.
[ "Convenience", "function", ":", "Detect", "file", "extension", "and", "write", "via", "Atomistica", "or", "ASE", ".", "Has", "support", "for", "writing", "LAMMPS", "data", "files", "." ]
python
train
hit9/rux
rux/utils.py
https://github.com/hit9/rux/blob/d7f60722658a3b83ac6d7bb3ca2790ac9c926b59/rux/utils.py#L75-L92
def update_nested_dict(a, b): """ update nested dict `a` with another dict b. usage:: >>> a = {'x' : { 'y': 1}} >>> b = {'x' : {'z':2, 'y':3}, 'w': 4} >>> update_nested_dict(a,b) {'x': {'y': 3, 'z': 2}, 'w': 4} """ for k, v in b.iteritems(): if isinstance(v,...
[ "def", "update_nested_dict", "(", "a", ",", "b", ")", ":", "for", "k", ",", "v", "in", "b", ".", "iteritems", "(", ")", ":", "if", "isinstance", "(", "v", ",", "dict", ")", ":", "d", "=", "a", ".", "setdefault", "(", "k", ",", "{", "}", ")", ...
update nested dict `a` with another dict b. usage:: >>> a = {'x' : { 'y': 1}} >>> b = {'x' : {'z':2, 'y':3}, 'w': 4} >>> update_nested_dict(a,b) {'x': {'y': 3, 'z': 2}, 'w': 4}
[ "update", "nested", "dict", "a", "with", "another", "dict", "b", ".", "usage", "::" ]
python
valid
DataDog/integrations-core
openldap/datadog_checks/openldap/openldap.py
https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/openldap/datadog_checks/openldap/openldap.py#L58-L94
def _get_tls_object(self, ssl_params): """ Return a TLS object to establish a secure connection to a server """ if ssl_params is None: return None if not ssl_params["verify"] and ssl_params["ca_certs"]: self.warning( "Incorrect configurati...
[ "def", "_get_tls_object", "(", "self", ",", "ssl_params", ")", ":", "if", "ssl_params", "is", "None", ":", "return", "None", "if", "not", "ssl_params", "[", "\"verify\"", "]", "and", "ssl_params", "[", "\"ca_certs\"", "]", ":", "self", ".", "warning", "(",...
Return a TLS object to establish a secure connection to a server
[ "Return", "a", "TLS", "object", "to", "establish", "a", "secure", "connection", "to", "a", "server" ]
python
train
marrow/mongo
marrow/mongo/core/trait/expires.py
https://github.com/marrow/mongo/blob/2066dc73e281b8a46cb5fc965267d6b8e1b18467/marrow/mongo/core/trait/expires.py#L36-L44
def from_mongo(cls, data, expired=False, **kw): """In the event a value that has technically already expired is loaded, swap it for None.""" value = super(Expires, cls).from_mongo(data, **kw) if not expired and value.is_expired: return None return value
[ "def", "from_mongo", "(", "cls", ",", "data", ",", "expired", "=", "False", ",", "*", "*", "kw", ")", ":", "value", "=", "super", "(", "Expires", ",", "cls", ")", ".", "from_mongo", "(", "data", ",", "*", "*", "kw", ")", "if", "not", "expired", ...
In the event a value that has technically already expired is loaded, swap it for None.
[ "In", "the", "event", "a", "value", "that", "has", "technically", "already", "expired", "is", "loaded", "swap", "it", "for", "None", "." ]
python
train
kennethreitz/maya
maya/core.py
https://github.com/kennethreitz/maya/blob/774b141d91a83a5d77cb5351db3d02bf50564b21/maya/core.py#L158-L165
def snap(self, instruction): """ Returns a new MayaDT object modified by the given instruction. Powered by snaptime. See https://github.com/zartstrom/snaptime for a complete documentation about the snaptime instructions. """ return self.from_datetime(snaptime.snap(self....
[ "def", "snap", "(", "self", ",", "instruction", ")", ":", "return", "self", ".", "from_datetime", "(", "snaptime", ".", "snap", "(", "self", ".", "datetime", "(", ")", ",", "instruction", ")", ")" ]
Returns a new MayaDT object modified by the given instruction. Powered by snaptime. See https://github.com/zartstrom/snaptime for a complete documentation about the snaptime instructions.
[ "Returns", "a", "new", "MayaDT", "object", "modified", "by", "the", "given", "instruction", "." ]
python
train
PyFilesystem/pyfilesystem2
fs/multifs.py
https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/multifs.py#L165-L171
def _writable_required(self, path): # type: (Text) -> FS """Check that ``path`` is writeable. """ if self.write_fs is None: raise errors.ResourceReadOnly(path) return self.write_fs
[ "def", "_writable_required", "(", "self", ",", "path", ")", ":", "# type: (Text) -> FS", "if", "self", ".", "write_fs", "is", "None", ":", "raise", "errors", ".", "ResourceReadOnly", "(", "path", ")", "return", "self", ".", "write_fs" ]
Check that ``path`` is writeable.
[ "Check", "that", "path", "is", "writeable", "." ]
python
train
ricmoo/pyscrypt
pyscrypt/hash.py
https://github.com/ricmoo/pyscrypt/blob/131ca39acee4963afd704b4c4631497e4fe34c97/pyscrypt/hash.py#L217-L258
def hash(password, salt, N, r, p, dkLen): """Returns the result of the scrypt password-based key derivation function. Constraints: r * p < (2 ** 30) dkLen <= (((2 ** 32) - 1) * 32 N must be a power of 2 greater than 1 (eg. 2, 4, 8, 16, 32...) N, r, p must be positive ...
[ "def", "hash", "(", "password", ",", "salt", ",", "N", ",", "r", ",", "p", ",", "dkLen", ")", ":", "# This only matters to Python 3", "if", "not", "check_bytes", "(", "password", ")", ":", "raise", "ValueError", "(", "'password must be a byte array'", ")", "...
Returns the result of the scrypt password-based key derivation function. Constraints: r * p < (2 ** 30) dkLen <= (((2 ** 32) - 1) * 32 N must be a power of 2 greater than 1 (eg. 2, 4, 8, 16, 32...) N, r, p must be positive
[ "Returns", "the", "result", "of", "the", "scrypt", "password", "-", "based", "key", "derivation", "function", "." ]
python
train
fake-name/ChromeController
ChromeController/Generator/Generated.py
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L2271-L2329
def Network_setCookie(self, name, value, **kwargs): """ Function path: Network.setCookie Domain: Network Method name: setCookie WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'name' (type: string) -> Cookie name. 'value' (type: string) -> Cookie valu...
[ "def", "Network_setCookie", "(", "self", ",", "name", ",", "value", ",", "*", "*", "kwargs", ")", ":", "assert", "isinstance", "(", "name", ",", "(", "str", ",", ")", ")", ",", "\"Argument 'name' must be of type '['str']'. Received type: '%s'\"", "%", "type", ...
Function path: Network.setCookie Domain: Network Method name: setCookie WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'name' (type: string) -> Cookie name. 'value' (type: string) -> Cookie value. Optional arguments: 'url' (type: string) -> The ...
[ "Function", "path", ":", "Network", ".", "setCookie", "Domain", ":", "Network", "Method", "name", ":", "setCookie", "WARNING", ":", "This", "function", "is", "marked", "Experimental", "!", "Parameters", ":", "Required", "arguments", ":", "name", "(", "type", ...
python
train
happyleavesaoc/python-motorparts
motorparts/__init__.py
https://github.com/happyleavesaoc/python-motorparts/blob/4a6b4dc72dd45524dd64a7a079478bd98c55215c/motorparts/__init__.py#L140-L154
def _traverse_report(data): """Recursively traverse vehicle health report.""" if 'items' not in data: return {} out = {} for item in data['items']: skip = (item['severity'] == 'NonDisplay' or item['itemKey'] == 'categoryDesc' or item['value'] in [None, 'Nu...
[ "def", "_traverse_report", "(", "data", ")", ":", "if", "'items'", "not", "in", "data", ":", "return", "{", "}", "out", "=", "{", "}", "for", "item", "in", "data", "[", "'items'", "]", ":", "skip", "=", "(", "item", "[", "'severity'", "]", "==", ...
Recursively traverse vehicle health report.
[ "Recursively", "traverse", "vehicle", "health", "report", "." ]
python
train
santoshphilip/eppy
eppy/EPlusInterfaceFunctions/iddindex.py
https://github.com/santoshphilip/eppy/blob/55410ff7c11722f35bc4331ff5e00a0b86f787e1/eppy/EPlusInterfaceFunctions/iddindex.py#L65-L71
def makeref2namesdct(name2refdct): """make the ref2namesdct in the idd_index""" ref2namesdct = {} for key, values in name2refdct.items(): for value in values: ref2namesdct.setdefault(value, set()).add(key) return ref2namesdct
[ "def", "makeref2namesdct", "(", "name2refdct", ")", ":", "ref2namesdct", "=", "{", "}", "for", "key", ",", "values", "in", "name2refdct", ".", "items", "(", ")", ":", "for", "value", "in", "values", ":", "ref2namesdct", ".", "setdefault", "(", "value", "...
make the ref2namesdct in the idd_index
[ "make", "the", "ref2namesdct", "in", "the", "idd_index" ]
python
train
QUANTAXIS/QUANTAXIS
QUANTAXIS/QAARP/QAUser.py
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QAUser.py#L408-L424
def register_account(self, account, portfolio_cookie=None): ''' 注册一个account到portfolio组合中 account 也可以是一个策略类,实现其 on_bar 方法 :param account: 被注册的account :return: ''' # 查找 portfolio if len(self.portfolio_list.keys()) < 1: po = self.new_portfolio() ...
[ "def", "register_account", "(", "self", ",", "account", ",", "portfolio_cookie", "=", "None", ")", ":", "# 查找 portfolio", "if", "len", "(", "self", ".", "portfolio_list", ".", "keys", "(", ")", ")", "<", "1", ":", "po", "=", "self", ".", "new_portfolio",...
注册一个account到portfolio组合中 account 也可以是一个策略类,实现其 on_bar 方法 :param account: 被注册的account :return:
[ "注册一个account到portfolio组合中", "account", "也可以是一个策略类,实现其", "on_bar", "方法", ":", "param", "account", ":", "被注册的account", ":", "return", ":" ]
python
train
revelc/pyaccumulo
pyaccumulo/proxy/AccumuloProxy.py
https://github.com/revelc/pyaccumulo/blob/8adcf535bb82ba69c749efce785c9efc487e85de/pyaccumulo/proxy/AccumuloProxy.py#L3021-L3029
def updateAndFlush(self, login, tableName, cells): """ Parameters: - login - tableName - cells """ self.send_updateAndFlush(login, tableName, cells) self.recv_updateAndFlush()
[ "def", "updateAndFlush", "(", "self", ",", "login", ",", "tableName", ",", "cells", ")", ":", "self", ".", "send_updateAndFlush", "(", "login", ",", "tableName", ",", "cells", ")", "self", ".", "recv_updateAndFlush", "(", ")" ]
Parameters: - login - tableName - cells
[ "Parameters", ":", "-", "login", "-", "tableName", "-", "cells" ]
python
train
log2timeline/dfvfs
dfvfs/helpers/file_system_searcher.py
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/file_system_searcher.py#L364-L384
def PrepareMatches(self, file_system): """Prepare find specification for matching. Args: file_system (FileSystem): file system. """ if self._location is not None: self._location_segments = self._SplitPath( self._location, file_system.PATH_SEPARATOR) elif self._location_regex ...
[ "def", "PrepareMatches", "(", "self", ",", "file_system", ")", ":", "if", "self", ".", "_location", "is", "not", "None", ":", "self", ".", "_location_segments", "=", "self", ".", "_SplitPath", "(", "self", ".", "_location", ",", "file_system", ".", "PATH_S...
Prepare find specification for matching. Args: file_system (FileSystem): file system.
[ "Prepare", "find", "specification", "for", "matching", "." ]
python
train
quasipedia/swaggery
swaggery/utils.py
https://github.com/quasipedia/swaggery/blob/89a2e1b2bebbc511c781c9e63972f65aef73cc2f/swaggery/utils.py#L98-L101
def map_exception_codes(): '''Helper function to intialise CODES_TO_EXCEPTIONS.''' werkex = inspect.getmembers(exceptions, lambda x: getattr(x, 'code', None)) return {e.code: e for _, e in werkex}
[ "def", "map_exception_codes", "(", ")", ":", "werkex", "=", "inspect", ".", "getmembers", "(", "exceptions", ",", "lambda", "x", ":", "getattr", "(", "x", ",", "'code'", ",", "None", ")", ")", "return", "{", "e", ".", "code", ":", "e", "for", "_", ...
Helper function to intialise CODES_TO_EXCEPTIONS.
[ "Helper", "function", "to", "intialise", "CODES_TO_EXCEPTIONS", "." ]
python
train
prthkms/alex
alex/web.py
https://github.com/prthkms/alex/blob/79d3167c877e94cc07db0aab55a35857fac67ef7/alex/web.py#L4-L47
def weather(query): """weather(query) -- use Name Entity Recogniser (nltk-stanford-ner), to determine location entity in query and fetch weather info for that location (using yahoo apis). """ print 'Identifying the location . . .' try: response = unirest.post("https://textanalysis.p.mashape.com/nltk-stanford-...
[ "def", "weather", "(", "query", ")", ":", "print", "'Identifying the location . . .'", "try", ":", "response", "=", "unirest", ".", "post", "(", "\"https://textanalysis.p.mashape.com/nltk-stanford-ner\"", ",", "headers", "=", "{", "\"X-Mashape-Key\"", ":", "\"E7WffsNDbN...
weather(query) -- use Name Entity Recogniser (nltk-stanford-ner), to determine location entity in query and fetch weather info for that location (using yahoo apis).
[ "weather", "(", "query", ")", "--", "use", "Name", "Entity", "Recogniser", "(", "nltk", "-", "stanford", "-", "ner", ")", "to", "determine", "location", "entity", "in", "query", "and", "fetch", "weather", "info", "for", "that", "location", "(", "using", ...
python
train
pycontribs/pyrax
pyrax/autoscale.py
https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/autoscale.py#L1030-L1038
def replace(self, scaling_group, name, cooldown, min_entities, max_entities, metadata=None): """ Replace an existing ScalingGroup configuration. All of the attributes must be specified. If you wish to delete any of the optional attributes, pass them in as None. """ ...
[ "def", "replace", "(", "self", ",", "scaling_group", ",", "name", ",", "cooldown", ",", "min_entities", ",", "max_entities", ",", "metadata", "=", "None", ")", ":", "return", "self", ".", "_manager", ".", "replace", "(", "scaling_group", ",", "name", ",", ...
Replace an existing ScalingGroup configuration. All of the attributes must be specified. If you wish to delete any of the optional attributes, pass them in as None.
[ "Replace", "an", "existing", "ScalingGroup", "configuration", ".", "All", "of", "the", "attributes", "must", "be", "specified", ".", "If", "you", "wish", "to", "delete", "any", "of", "the", "optional", "attributes", "pass", "them", "in", "as", "None", "." ]
python
train
ashmastaflash/kal-wrapper
kalibrate/fn.py
https://github.com/ashmastaflash/kal-wrapper/blob/80ee03ab7bd3172ac26b769d6b442960f3424b0e/kalibrate/fn.py#L157-L189
def parse_kal_scan(kal_out): """Parse kal band scan output.""" kal_data = [] scan_band = determine_scan_band(kal_out) scan_gain = determine_scan_gain(kal_out) scan_device = determine_device(kal_out) sample_rate = determine_sample_rate(kal_out) chan_detect_threshold = determine_chan_detect_th...
[ "def", "parse_kal_scan", "(", "kal_out", ")", ":", "kal_data", "=", "[", "]", "scan_band", "=", "determine_scan_band", "(", "kal_out", ")", "scan_gain", "=", "determine_scan_gain", "(", "kal_out", ")", "scan_device", "=", "determine_device", "(", "kal_out", ")",...
Parse kal band scan output.
[ "Parse", "kal", "band", "scan", "output", "." ]
python
train
Azure/msrest-for-python
msrest/pipeline/requests.py
https://github.com/Azure/msrest-for-python/blob/0732bc90bdb290e5f58c675ffdd7dbfa9acefc93/msrest/pipeline/requests.py#L105-L147
def send(self, request, **kwargs): """Patch the current session with Request level operation config. This is deprecated, we shouldn't patch the session with arguments at the Request, and "config" should be used. """ session = request.context.session old_max_redirects = ...
[ "def", "send", "(", "self", ",", "request", ",", "*", "*", "kwargs", ")", ":", "session", "=", "request", ".", "context", ".", "session", "old_max_redirects", "=", "None", "if", "'max_redirects'", "in", "kwargs", ":", "warnings", ".", "warn", "(", "\"max...
Patch the current session with Request level operation config. This is deprecated, we shouldn't patch the session with arguments at the Request, and "config" should be used.
[ "Patch", "the", "current", "session", "with", "Request", "level", "operation", "config", "." ]
python
train
pyopenapi/pyswagger
pyswagger/primitives/render.py
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/primitives/render.py#L231-L264
def default(): """ return default options, available options: - max_name_length: maximum length of name for additionalProperties - max_prop_count: maximum count of properties (count of fixed properties + additional properties) - max_str_length: maximum length of string type - max...
[ "def", "default", "(", ")", ":", "return", "dict", "(", "max_name_length", "=", "64", ",", "max_prop_count", "=", "32", ",", "max_str_length", "=", "100", ",", "max_byte_length", "=", "100", ",", "max_array_length", "=", "100", ",", "max_file_length", "=", ...
return default options, available options: - max_name_length: maximum length of name for additionalProperties - max_prop_count: maximum count of properties (count of fixed properties + additional properties) - max_str_length: maximum length of string type - max_byte_length: maximum lengt...
[ "return", "default", "options", "available", "options", ":", "-", "max_name_length", ":", "maximum", "length", "of", "name", "for", "additionalProperties", "-", "max_prop_count", ":", "maximum", "count", "of", "properties", "(", "count", "of", "fixed", "properties...
python
train
geophysics-ubonn/reda
lib/reda/plotters/plots2d.py
https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/plotters/plots2d.py#L13-L31
def _pseudodepths_wenner(configs, spacing=1, grid=None): """Given distances between electrodes, compute Wenner pseudo depths for the provided configuration The pseudodepth is computed after Roy & Apparao, 1971, as 0.11 times the distance between the two outermost electrodes. It's not really clear w...
[ "def", "_pseudodepths_wenner", "(", "configs", ",", "spacing", "=", "1", ",", "grid", "=", "None", ")", ":", "if", "grid", "is", "None", ":", "xpositions", "=", "(", "configs", "-", "1", ")", "*", "spacing", "else", ":", "xpositions", "=", "grid", "....
Given distances between electrodes, compute Wenner pseudo depths for the provided configuration The pseudodepth is computed after Roy & Apparao, 1971, as 0.11 times the distance between the two outermost electrodes. It's not really clear why the Wenner depths are different from the Dipole-Dipole de...
[ "Given", "distances", "between", "electrodes", "compute", "Wenner", "pseudo", "depths", "for", "the", "provided", "configuration" ]
python
train
djordon/queueing-tool
queueing_tool/queues/queue_servers.py
https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/queues/queue_servers.py#L418-L465
def _current_color(self, which=0): """Returns a color for the queue. Parameters ---------- which : int (optional, default: ``0``) Specifies the type of color to return. Returns ------- color : list Returns a RGBA color that is represented...
[ "def", "_current_color", "(", "self", ",", "which", "=", "0", ")", ":", "if", "which", "==", "1", ":", "color", "=", "self", ".", "colors", "[", "'edge_loop_color'", "]", "elif", "which", "==", "2", ":", "color", "=", "self", ".", "colors", "[", "'...
Returns a color for the queue. Parameters ---------- which : int (optional, default: ``0``) Specifies the type of color to return. Returns ------- color : list Returns a RGBA color that is represented as a list with 4 entries where ea...
[ "Returns", "a", "color", "for", "the", "queue", "." ]
python
valid
optimizely/python-sdk
optimizely/logger.py
https://github.com/optimizely/python-sdk/blob/ec028d9efcf22498c3820f2650fa10f5c30bec90/optimizely/logger.py#L95-L117
def adapt_logger(logger): """ Adapt our custom logger.BaseLogger object into a standard logging.Logger object. Adaptations are: - NoOpLogger turns into a logger with a single NullHandler. - SimpleLogger turns into a logger with a StreamHandler and level. Args: logger: Possibly a logger.BaseLogger,...
[ "def", "adapt_logger", "(", "logger", ")", ":", "if", "isinstance", "(", "logger", ",", "logging", ".", "Logger", ")", ":", "return", "logger", "# Use the standard python logger created by these classes.", "if", "isinstance", "(", "logger", ",", "(", "SimpleLogger",...
Adapt our custom logger.BaseLogger object into a standard logging.Logger object. Adaptations are: - NoOpLogger turns into a logger with a single NullHandler. - SimpleLogger turns into a logger with a StreamHandler and level. Args: logger: Possibly a logger.BaseLogger, or a standard python logging.Logg...
[ "Adapt", "our", "custom", "logger", ".", "BaseLogger", "object", "into", "a", "standard", "logging", ".", "Logger", "object", "." ]
python
train
tensorlayer/tensorlayer
tensorlayer/prepro.py
https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L587-L628
def affine_transform_keypoints(coords_list, transform_matrix): """Transform keypoint coordinates according to a given affine transform matrix. OpenCV format, x is width. Note that, for pose estimation task, flipping requires maintaining the left and right body information. We should not flip the left a...
[ "def", "affine_transform_keypoints", "(", "coords_list", ",", "transform_matrix", ")", ":", "coords_result_list", "=", "[", "]", "for", "coords", "in", "coords_list", ":", "coords", "=", "np", ".", "asarray", "(", "coords", ")", "coords", "=", "coords", ".", ...
Transform keypoint coordinates according to a given affine transform matrix. OpenCV format, x is width. Note that, for pose estimation task, flipping requires maintaining the left and right body information. We should not flip the left and right body, so please use ``tl.prepro.keypoint_random_flip``. ...
[ "Transform", "keypoint", "coordinates", "according", "to", "a", "given", "affine", "transform", "matrix", ".", "OpenCV", "format", "x", "is", "width", "." ]
python
valid
ska-sa/montblanc
montblanc/impl/rime/tensorflow/sources/fits_beam_source_provider.py
https://github.com/ska-sa/montblanc/blob/8a2e742e7500bcc6196489b735f87b233075dd2d/montblanc/impl/rime/tensorflow/sources/fits_beam_source_provider.py#L213-L226
def _open_fits_files(filenames): """ Given a {correlation: filename} mapping for filenames returns a {correlation: file handle} mapping """ kw = { 'mode' : 'update', 'memmap' : False } def _fh(fn): """ Returns a filehandle or None if file does not exist """ return fits.open(fn, ...
[ "def", "_open_fits_files", "(", "filenames", ")", ":", "kw", "=", "{", "'mode'", ":", "'update'", ",", "'memmap'", ":", "False", "}", "def", "_fh", "(", "fn", ")", ":", "\"\"\" Returns a filehandle or None if file does not exist \"\"\"", "return", "fits", ".", "...
Given a {correlation: filename} mapping for filenames returns a {correlation: file handle} mapping
[ "Given", "a", "{", "correlation", ":", "filename", "}", "mapping", "for", "filenames", "returns", "a", "{", "correlation", ":", "file", "handle", "}", "mapping" ]
python
train
SHDShim/pytheos
pytheos/eqn_electronic.py
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_electronic.py#L6-L30
def zharkov_pel(v, temp, v0, e0, g, n, z, t_ref=300., three_r=3. * constants.R): """ calculate electronic contributions in pressure for the Zharkov equation the equation can be found in Sokolova and Dorogokupets 2013 :param v: unit-cell volume in A^3 :param temp: temperature in K ...
[ "def", "zharkov_pel", "(", "v", ",", "temp", ",", "v0", ",", "e0", ",", "g", ",", "n", ",", "z", ",", "t_ref", "=", "300.", ",", "three_r", "=", "3.", "*", "constants", ".", "R", ")", ":", "v_mol", "=", "vol_uc2mol", "(", "v", ",", "z", ")", ...
calculate electronic contributions in pressure for the Zharkov equation the equation can be found in Sokolova and Dorogokupets 2013 :param v: unit-cell volume in A^3 :param temp: temperature in K :param v0: unit-cell volume in A^3 at 1 bar :param e0: parameter in K-1 for the Zharkov equation :p...
[ "calculate", "electronic", "contributions", "in", "pressure", "for", "the", "Zharkov", "equation", "the", "equation", "can", "be", "found", "in", "Sokolova", "and", "Dorogokupets", "2013" ]
python
train
worldcompany/djangoembed
oembed/consumer.py
https://github.com/worldcompany/djangoembed/blob/f3f2be283441d91d1f89db780444dc75f7b51902/oembed/consumer.py#L30-L37
def extract_oembeds(self, text, maxwidth=None, maxheight=None, resource_type=None): """ Scans a block of text and extracts oembed data on any urls, returning it in a list of dictionaries """ parser = text_parser() urls = parser.extract_urls(text) return self.handl...
[ "def", "extract_oembeds", "(", "self", ",", "text", ",", "maxwidth", "=", "None", ",", "maxheight", "=", "None", ",", "resource_type", "=", "None", ")", ":", "parser", "=", "text_parser", "(", ")", "urls", "=", "parser", ".", "extract_urls", "(", "text",...
Scans a block of text and extracts oembed data on any urls, returning it in a list of dictionaries
[ "Scans", "a", "block", "of", "text", "and", "extracts", "oembed", "data", "on", "any", "urls", "returning", "it", "in", "a", "list", "of", "dictionaries" ]
python
valid
ConsenSys/mythril-classic
mythril/laser/ethereum/state/world_state.py
https://github.com/ConsenSys/mythril-classic/blob/27af71c34b2ce94f4fae5613ec457f93df1a8f56/mythril/laser/ethereum/state/world_state.py#L119-L130
def _generate_new_address(self, creator=None) -> str: """Generates a new address for the global state. :return: """ if creator: # TODO: Use nounce return "0x" + str(mk_contract_address(creator, 0).hex()) while True: address = "0x" + "".join([s...
[ "def", "_generate_new_address", "(", "self", ",", "creator", "=", "None", ")", "->", "str", ":", "if", "creator", ":", "# TODO: Use nounce", "return", "\"0x\"", "+", "str", "(", "mk_contract_address", "(", "creator", ",", "0", ")", ".", "hex", "(", ")", ...
Generates a new address for the global state. :return:
[ "Generates", "a", "new", "address", "for", "the", "global", "state", "." ]
python
train
ssalentin/plip
plip/modules/pymolplip.py
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/pymolplip.py#L168-L191
def show_cationpi(self): """Visualize cation-pi interactions.""" for i, p in enumerate(self.plcomplex.pication): cmd.pseudoatom('ps-picat-1-%i' % i, pos=p.ring_center) cmd.pseudoatom('ps-picat-2-%i' % i, pos=p.charge_center) if p.protcharged: cmd.pseud...
[ "def", "show_cationpi", "(", "self", ")", ":", "for", "i", ",", "p", "in", "enumerate", "(", "self", ".", "plcomplex", ".", "pication", ")", ":", "cmd", ".", "pseudoatom", "(", "'ps-picat-1-%i'", "%", "i", ",", "pos", "=", "p", ".", "ring_center", ")...
Visualize cation-pi interactions.
[ "Visualize", "cation", "-", "pi", "interactions", "." ]
python
train
hydraplatform/hydra-base
hydra_base/util/hdb.py
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/util/hdb.py#L425-L433
def get_dimension_from_db_by_name(dimension_name): """ Gets a dimension from the DB table. """ try: dimension = db.DBSession.query(Dimension).filter(Dimension.name==dimension_name).one() return JSONObject(dimension) except NoResultFound: raise ResourceNotFoundError("Dimen...
[ "def", "get_dimension_from_db_by_name", "(", "dimension_name", ")", ":", "try", ":", "dimension", "=", "db", ".", "DBSession", ".", "query", "(", "Dimension", ")", ".", "filter", "(", "Dimension", ".", "name", "==", "dimension_name", ")", ".", "one", "(", ...
Gets a dimension from the DB table.
[ "Gets", "a", "dimension", "from", "the", "DB", "table", "." ]
python
train
jgillick/LendingClub
lendingclub/__init__.py
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/__init__.py#L1134-L1183
def __get_strut_token(self): """ Move the staged loan notes to the order stage and get the struts token from the place order HTML. The order will not be placed until calling _confirm_order() Returns ------- dict A dict with the token name and value ...
[ "def", "__get_strut_token", "(", "self", ")", ":", "try", ":", "# Move to the place order page and get the struts token", "response", "=", "self", ".", "lc", ".", "session", ".", "get", "(", "'/portfolio/placeOrder.action'", ")", "soup", "=", "BeautifulSoup", "(", "...
Move the staged loan notes to the order stage and get the struts token from the place order HTML. The order will not be placed until calling _confirm_order() Returns ------- dict A dict with the token name and value
[ "Move", "the", "staged", "loan", "notes", "to", "the", "order", "stage", "and", "get", "the", "struts", "token", "from", "the", "place", "order", "HTML", ".", "The", "order", "will", "not", "be", "placed", "until", "calling", "_confirm_order", "()" ]
python
train
deepmind/pysc2
pysc2/bin/agent_remote.py
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/bin/agent_remote.py#L124-L152
def agent(): """Run the agent, connecting to a (remote) host started independently.""" agent_module, agent_name = FLAGS.agent.rsplit(".", 1) agent_cls = getattr(importlib.import_module(agent_module), agent_name) logging.info("Starting agent:") with remote_sc2_env.RemoteSC2Env( map_name=FLAGS.map, ...
[ "def", "agent", "(", ")", ":", "agent_module", ",", "agent_name", "=", "FLAGS", ".", "agent", ".", "rsplit", "(", "\".\"", ",", "1", ")", "agent_cls", "=", "getattr", "(", "importlib", ".", "import_module", "(", "agent_module", ")", ",", "agent_name", ")...
Run the agent, connecting to a (remote) host started independently.
[ "Run", "the", "agent", "connecting", "to", "a", "(", "remote", ")", "host", "started", "independently", "." ]
python
train
laysakura/relshell
relshell/batch_command.py
https://github.com/laysakura/relshell/blob/9ca5c03a34c11cb763a4a75595f18bf4383aa8cc/relshell/batch_command.py#L86-L110
def _parse_out_batch(cmd_array): """Find patterns that match to `out_batch_pat` and replace them into `STDOUT` or `TMPFILE`. :param cmd_array: `shlex.split`-ed command :rtype: ([cmd_array], batch_from_file) :returns: Modified `cmd_array` and tuple to show how OUT_BATCH is instantiated...
[ "def", "_parse_out_batch", "(", "cmd_array", ")", ":", "res_cmd_array", "=", "cmd_array", "[", ":", "]", "res_batch_from_file", "=", "None", "out_batch_cmdidx", "=", "BatchCommand", ".", "_out_batch_cmdidx", "(", "cmd_array", ")", "if", "out_batch_cmdidx", "is", "...
Find patterns that match to `out_batch_pat` and replace them into `STDOUT` or `TMPFILE`. :param cmd_array: `shlex.split`-ed command :rtype: ([cmd_array], batch_from_file) :returns: Modified `cmd_array` and tuple to show how OUT_BATCH is instantiated (TMPFILE or STDOUT). Returned `...
[ "Find", "patterns", "that", "match", "to", "out_batch_pat", "and", "replace", "them", "into", "STDOUT", "or", "TMPFILE", "." ]
python
train
mlperf/training
rnn_translator/pytorch/seq2seq/data/dataset.py
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/data/dataset.py#L115-L123
def sort_by_length(self): """ Sorts dataset by the sequence length. """ self.lengths, indices = self.lengths.sort(descending=True) self.src = [self.src[idx] for idx in indices] self.indices = indices.tolist() self.sorted = True
[ "def", "sort_by_length", "(", "self", ")", ":", "self", ".", "lengths", ",", "indices", "=", "self", ".", "lengths", ".", "sort", "(", "descending", "=", "True", ")", "self", ".", "src", "=", "[", "self", ".", "src", "[", "idx", "]", "for", "idx", ...
Sorts dataset by the sequence length.
[ "Sorts", "dataset", "by", "the", "sequence", "length", "." ]
python
train
cloud9ers/gurumate
environment/lib/python2.7/site-packages/IPython/parallel/controller/mongodb.py
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/mongodb.py#L63-L67
def add_record(self, msg_id, rec): """Add a new Task Record, by msg_id.""" # print rec rec = self._binary_buffers(rec) self._records.insert(rec)
[ "def", "add_record", "(", "self", ",", "msg_id", ",", "rec", ")", ":", "# print rec", "rec", "=", "self", ".", "_binary_buffers", "(", "rec", ")", "self", ".", "_records", ".", "insert", "(", "rec", ")" ]
Add a new Task Record, by msg_id.
[ "Add", "a", "new", "Task", "Record", "by", "msg_id", "." ]
python
test
Kane610/axis
axis/param_cgi.py
https://github.com/Kane610/axis/blob/b2b44ce595c7b722b5e13eabcab7b91f048e1808/axis/param_cgi.py#L27-L29
def update_brand(self) -> None: """Update brand group of parameters.""" self.update(path=URL_GET + GROUP.format(group=BRAND))
[ "def", "update_brand", "(", "self", ")", "->", "None", ":", "self", ".", "update", "(", "path", "=", "URL_GET", "+", "GROUP", ".", "format", "(", "group", "=", "BRAND", ")", ")" ]
Update brand group of parameters.
[ "Update", "brand", "group", "of", "parameters", "." ]
python
train
pgjones/quart
quart/app.py
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L1722-L1753
async def postprocess_websocket( self, response: Optional[Response], websocket_context: Optional[WebsocketContext]=None, ) -> Response: """Postprocess the websocket acting on the response. Arguments: response: The response after the websocket is finalized. ...
[ "async", "def", "postprocess_websocket", "(", "self", ",", "response", ":", "Optional", "[", "Response", "]", ",", "websocket_context", ":", "Optional", "[", "WebsocketContext", "]", "=", "None", ",", ")", "->", "Response", ":", "websocket_", "=", "(", "webs...
Postprocess the websocket acting on the response. Arguments: response: The response after the websocket is finalized. webcoket_context: The websocket context, optional as Flask omits this argument.
[ "Postprocess", "the", "websocket", "acting", "on", "the", "response", "." ]
python
train
biolink/ontobio
ontobio/golr/golr_stats.py
https://github.com/biolink/ontobio/blob/4e512a7831cfe6bc1b32f2c3be2ba41bc5cf7345/ontobio/golr/golr_stats.py#L17-L52
def get_counts(entities=None, object_category=None, min_count=1, **kwargs): """ given a set of entities (genes, diseases, etc), finds the number of entities associated with each descriptor in a given category. The result is a tuple (cmap, results), where cmap is...
[ "def", "get_counts", "(", "entities", "=", "None", ",", "object_category", "=", "None", ",", "min_count", "=", "1", ",", "*", "*", "kwargs", ")", ":", "if", "entities", "is", "None", ":", "entities", "=", "[", "]", "results", "=", "search_associations", ...
given a set of entities (genes, diseases, etc), finds the number of entities associated with each descriptor in a given category. The result is a tuple (cmap, results), where cmap is a dict of TERM:COUNT
[ "given", "a", "set", "of", "entities", "(", "genes", "diseases", "etc", ")", "finds", "the", "number", "of", "entities", "associated", "with", "each", "descriptor", "in", "a", "given", "category", "." ]
python
train
rsmuc/health_monitoring_plugins
health_monitoring_plugins/idrac.py
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/idrac.py#L177-L188
def probe_check(name, status, device_type): """if the status is "ok" in the PROBE_STATE dict, return ok + string if the status is not "ok", return critical + string""" status_string = PROBE_STATE.get(int(status), "unknown") if status_string == "ok": return ok, "{} '{}': {}".format(device_type, ...
[ "def", "probe_check", "(", "name", ",", "status", ",", "device_type", ")", ":", "status_string", "=", "PROBE_STATE", ".", "get", "(", "int", "(", "status", ")", ",", "\"unknown\"", ")", "if", "status_string", "==", "\"ok\"", ":", "return", "ok", ",", "\"...
if the status is "ok" in the PROBE_STATE dict, return ok + string if the status is not "ok", return critical + string
[ "if", "the", "status", "is", "ok", "in", "the", "PROBE_STATE", "dict", "return", "ok", "+", "string", "if", "the", "status", "is", "not", "ok", "return", "critical", "+", "string" ]
python
train
denisenkom/pytds
src/pytds/tds.py
https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L247-L254
def read_whole_packet(self): """ Reads single packet and returns bytes payload of the packet Can only be called when transport's read pointer is at the beginning of the packet. """ self._read_packet() return readall(self, self._size - _header.size)
[ "def", "read_whole_packet", "(", "self", ")", ":", "self", ".", "_read_packet", "(", ")", "return", "readall", "(", "self", ",", "self", ".", "_size", "-", "_header", ".", "size", ")" ]
Reads single packet and returns bytes payload of the packet Can only be called when transport's read pointer is at the beginning of the packet.
[ "Reads", "single", "packet", "and", "returns", "bytes", "payload", "of", "the", "packet" ]
python
train
apache/incubator-mxnet
python/mxnet/profiler.py
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/profiler.py#L89-L106
def set_state(state='stop', profile_process='worker'): """Set up the profiler state to 'run' or 'stop'. Parameters ---------- state : string, optional Indicates whether to run the profiler, can be 'stop' or 'run'. Default is `stop`. profile_process : string whether to profil...
[ "def", "set_state", "(", "state", "=", "'stop'", ",", "profile_process", "=", "'worker'", ")", ":", "state2int", "=", "{", "'stop'", ":", "0", ",", "'run'", ":", "1", "}", "profile_process2int", "=", "{", "'worker'", ":", "0", ",", "'server'", ":", "1"...
Set up the profiler state to 'run' or 'stop'. Parameters ---------- state : string, optional Indicates whether to run the profiler, can be 'stop' or 'run'. Default is `stop`. profile_process : string whether to profile kvstore `server` or `worker`. server can only be pro...
[ "Set", "up", "the", "profiler", "state", "to", "run", "or", "stop", "." ]
python
train
MacHu-GWU/pymongo_mate-project
pymongo_mate/mongomock_mate.py
https://github.com/MacHu-GWU/pymongo_mate-project/blob/be53170c2db54cb705b9e548d32ef26c773ff7f3/pymongo_mate/mongomock_mate.py#L12-L26
def _dump(db): """ Dump :class:`mongomock.database.Database` to dict data. """ db_data = {"name": db.name, "_collections": dict()} for col_name, collection in iteritems(db._collections): if col_name != "system.indexes": col_data = { "_documents": collection._docu...
[ "def", "_dump", "(", "db", ")", ":", "db_data", "=", "{", "\"name\"", ":", "db", ".", "name", ",", "\"_collections\"", ":", "dict", "(", ")", "}", "for", "col_name", ",", "collection", "in", "iteritems", "(", "db", ".", "_collections", ")", ":", "if"...
Dump :class:`mongomock.database.Database` to dict data.
[ "Dump", ":", "class", ":", "mongomock", ".", "database", ".", "Database", "to", "dict", "data", "." ]
python
train
lowandrew/OLCTools
spadespipeline/typingclasses.py
https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/spadespipeline/typingclasses.py#L958-L982
def runner(self): """ Run the necessary methods in the correct order """ vir_report = os.path.join(self.reportpath, 'virulence.csv') if os.path.isfile(vir_report): self.report_parse(vir_report) else: logging.info('Starting {} analysis pipeline'.fo...
[ "def", "runner", "(", "self", ")", ":", "vir_report", "=", "os", ".", "path", ".", "join", "(", "self", ".", "reportpath", ",", "'virulence.csv'", ")", "if", "os", ".", "path", ".", "isfile", "(", "vir_report", ")", ":", "self", ".", "report_parse", ...
Run the necessary methods in the correct order
[ "Run", "the", "necessary", "methods", "in", "the", "correct", "order" ]
python
train
FNNDSC/pfmisc
pfmisc/C_snode.py
https://github.com/FNNDSC/pfmisc/blob/960b4d6135fcc50bed0a8e55db2ab1ddad9b99d8/pfmisc/C_snode.py#L1385-L1439
def treeExplore(self, **kwargs): """ Recursively walk through a C_stree, applying a passed function at each node. The actual "walk" uses individual nodes' internal child dictionaries. It is assumed that the start origin of exploration can in fact ...
[ "def", "treeExplore", "(", "self", ",", "*", "*", "kwargs", ")", ":", "str_recursePath", "=", "''", "str_startPath", "=", "'/'", "f", "=", "None", "ret", "=", "{", "}", "for", "key", ",", "val", "in", "kwargs", ".", "items", "(", ")", ":", "if", ...
Recursively walk through a C_stree, applying a passed function at each node. The actual "walk" uses individual nodes' internal child dictionaries. It is assumed that the start origin of exploration can in fact be reached by a 'cd()' call. Directories are added to the int...
[ "Recursively", "walk", "through", "a", "C_stree", "applying", "a", "passed", "function", "at", "each", "node", ".", "The", "actual", "walk", "uses", "individual", "nodes", "internal", "child", "dictionaries", "." ]
python
train
koszullab/metaTOR
metator/scripts/network.py
https://github.com/koszullab/metaTOR/blob/0c1203d1dffedfa5ea380c0335b4baa9cfb7e89a/metator/scripts/network.py#L438-L574
def alignment_to_reads( sam_merged, output_dir, parameters=DEFAULT_PARAMETERS, save_memory=True, *bin_fasta ): """Generate reads from ambiguous alignment file Extract reads found to be mapping an input FASTA bin. If one read maps, the whole pair is extracted and written to the outpu...
[ "def", "alignment_to_reads", "(", "sam_merged", ",", "output_dir", ",", "parameters", "=", "DEFAULT_PARAMETERS", ",", "save_memory", "=", "True", ",", "*", "bin_fasta", ")", ":", "# Just in case file objects are sent as input", "def", "get_file_string", "(", "file_thi...
Generate reads from ambiguous alignment file Extract reads found to be mapping an input FASTA bin. If one read maps, the whole pair is extracted and written to the output paired-end FASTQ files. Reads that mapped and weren't part of a pair are kept in a third 'single' file for people who need it (e...
[ "Generate", "reads", "from", "ambiguous", "alignment", "file" ]
python
train
cs01/gdbgui
gdbgui/SSLify.py
https://github.com/cs01/gdbgui/blob/5367f87554f8f7c671d1f4596c133bf1303154f0/gdbgui/SSLify.py#L90-L104
def get_ssl_context(private_key, certificate): """Get ssl context from private key and certificate paths. The return value is used when calling Flask. i.e. app.run(ssl_context=get_ssl_context(,,,)) """ if ( certificate and os.path.isfile(certificate) and private_key a...
[ "def", "get_ssl_context", "(", "private_key", ",", "certificate", ")", ":", "if", "(", "certificate", "and", "os", ".", "path", ".", "isfile", "(", "certificate", ")", "and", "private_key", "and", "os", ".", "path", ".", "isfile", "(", "private_key", ")", ...
Get ssl context from private key and certificate paths. The return value is used when calling Flask. i.e. app.run(ssl_context=get_ssl_context(,,,))
[ "Get", "ssl", "context", "from", "private", "key", "and", "certificate", "paths", ".", "The", "return", "value", "is", "used", "when", "calling", "Flask", ".", "i", ".", "e", ".", "app", ".", "run", "(", "ssl_context", "=", "get_ssl_context", "(", "))" ]
python
train
KrzyHonk/bpmn-python
bpmn_python/bpmn_diagram_import.py
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_import.py#L95-L111
def import_participant_element(diagram_graph, participants_dictionary, participant_element): """ Adds 'participant' element to the collaboration dictionary. :param diagram_graph: NetworkX graph representing a BPMN process diagram, :param participants_dictionary: dictionary with particip...
[ "def", "import_participant_element", "(", "diagram_graph", ",", "participants_dictionary", ",", "participant_element", ")", ":", "participant_id", "=", "participant_element", ".", "getAttribute", "(", "consts", ".", "Consts", ".", "id", ")", "name", "=", "participant_...
Adds 'participant' element to the collaboration dictionary. :param diagram_graph: NetworkX graph representing a BPMN process diagram, :param participants_dictionary: dictionary with participant element attributes. Key is participant ID, value is a dictionary of participant attributes, ...
[ "Adds", "participant", "element", "to", "the", "collaboration", "dictionary", "." ]
python
train
firstprayer/monsql
monsql/sql.py
https://github.com/firstprayer/monsql/blob/6285c15b574c8664046eae2edfeb548c7b173efd/monsql/sql.py#L70-L84
def build_insert(table_name, attributes): """ Given the table_name and the data, return the sql to insert the data """ sql = "INSERT INTO %s" %(table_name) column_str = u"" value_str = u"" for index, (key, value) in enumerate(attributes.items()): if index > 0: column_str ...
[ "def", "build_insert", "(", "table_name", ",", "attributes", ")", ":", "sql", "=", "\"INSERT INTO %s\"", "%", "(", "table_name", ")", "column_str", "=", "u\"\"", "value_str", "=", "u\"\"", "for", "index", ",", "(", "key", ",", "value", ")", "in", "enumerat...
Given the table_name and the data, return the sql to insert the data
[ "Given", "the", "table_name", "and", "the", "data", "return", "the", "sql", "to", "insert", "the", "data" ]
python
train
phoebe-project/phoebe2
phoebe/parameters/parameters.py
https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L407-L419
def tags(self): """Returns a dictionary that lists all available tags that can be used for further filtering """ ret = {} for typ in _meta_fields_twig: if typ in ['uniqueid', 'plugin', 'feedback', 'fitting', 'history', 'twig', 'uniquetwig']: continue ...
[ "def", "tags", "(", "self", ")", ":", "ret", "=", "{", "}", "for", "typ", "in", "_meta_fields_twig", ":", "if", "typ", "in", "[", "'uniqueid'", ",", "'plugin'", ",", "'feedback'", ",", "'fitting'", ",", "'history'", ",", "'twig'", ",", "'uniquetwig'", ...
Returns a dictionary that lists all available tags that can be used for further filtering
[ "Returns", "a", "dictionary", "that", "lists", "all", "available", "tags", "that", "can", "be", "used", "for", "further", "filtering" ]
python
train
thespacedoctor/tastic
tastic/workspace/workspace.py
https://github.com/thespacedoctor/tastic/blob/a0a16cf329a50057906ac3f696bb60b6fcee25e0/tastic/workspace/workspace.py#L158-L181
def _sort_tp_file( self, taskpaperPath): """*sort individual taskpaper documents* **Key Arguments:** - ``taskpaperPath`` -- path to a taskpaper file **Return:** - None """ self.log.info('starting the ``_sort_tp_file`` method') ...
[ "def", "_sort_tp_file", "(", "self", ",", "taskpaperPath", ")", ":", "self", ".", "log", ".", "info", "(", "'starting the ``_sort_tp_file`` method'", ")", "# OPEN TASKPAPER FILE", "self", ".", "log", ".", "info", "(", "\"sorting taskpaper file %(taskpaperPath)s\"", "%...
*sort individual taskpaper documents* **Key Arguments:** - ``taskpaperPath`` -- path to a taskpaper file **Return:** - None
[ "*", "sort", "individual", "taskpaper", "documents", "*" ]
python
train
RudolfCardinal/pythonlib
cardinal_pythonlib/rnc_text.py
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L59-L68
def output_csv(filehandle: TextIO, values: Iterable[str]) -> None: """ Write a line of CSV. POOR; does not escape things properly. DEPRECATED. Args: filehandle: file to write to values: values """ line = ",".join(values) filehandle.write(line + "\n")
[ "def", "output_csv", "(", "filehandle", ":", "TextIO", ",", "values", ":", "Iterable", "[", "str", "]", ")", "->", "None", ":", "line", "=", "\",\"", ".", "join", "(", "values", ")", "filehandle", ".", "write", "(", "line", "+", "\"\\n\"", ")" ]
Write a line of CSV. POOR; does not escape things properly. DEPRECATED. Args: filehandle: file to write to values: values
[ "Write", "a", "line", "of", "CSV", ".", "POOR", ";", "does", "not", "escape", "things", "properly", ".", "DEPRECATED", "." ]
python
train
unt-libraries/edtf-validate
edtf_validate/valid_edtf.py
https://github.com/unt-libraries/edtf-validate/blob/d6d63141919a66aea4ff1c31fa0cb8ff744ef9d9/edtf_validate/valid_edtf.py#L326-L351
def replace_u(matchobj): """Break the interval into parts, and replace 'u's. pieces - [pos/neg, start_year, start_month, start_day, pos/neg, end_year, end_month, end_day] """ pieces = list(matchobj.groups('')) # Replace "u"s in start and end years. if 'u' in pieces[1]: pie...
[ "def", "replace_u", "(", "matchobj", ")", ":", "pieces", "=", "list", "(", "matchobj", ".", "groups", "(", "''", ")", ")", "# Replace \"u\"s in start and end years.", "if", "'u'", "in", "pieces", "[", "1", "]", ":", "pieces", "[", "1", "]", "=", "pieces"...
Break the interval into parts, and replace 'u's. pieces - [pos/neg, start_year, start_month, start_day, pos/neg, end_year, end_month, end_day]
[ "Break", "the", "interval", "into", "parts", "and", "replace", "u", "s", "." ]
python
train
sernst/cauldron
cauldron/session/reloading.py
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/reloading.py#L146-L175
def refresh( *modules: typing.Union[str, types.ModuleType], recursive: bool = False, force: bool = False ) -> bool: """ Checks the specified module or modules for changes and reloads them if they have been changed since the module was first imported or last refreshed. :param...
[ "def", "refresh", "(", "*", "modules", ":", "typing", ".", "Union", "[", "str", ",", "types", ".", "ModuleType", "]", ",", "recursive", ":", "bool", "=", "False", ",", "force", ":", "bool", "=", "False", ")", "->", "bool", ":", "out", "=", "[", "...
Checks the specified module or modules for changes and reloads them if they have been changed since the module was first imported or last refreshed. :param modules: One or more module objects that should be refreshed if they the currently loaded versions are out of date. The package name fo...
[ "Checks", "the", "specified", "module", "or", "modules", "for", "changes", "and", "reloads", "them", "if", "they", "have", "been", "changed", "since", "the", "module", "was", "first", "imported", "or", "last", "refreshed", "." ]
python
train
starling-lab/rnlp
rnlp/__init__.py
https://github.com/starling-lab/rnlp/blob/72054cc2c0cbaea1d281bf3d56b271d4da29fc4a/rnlp/__init__.py#L82-L94
def converter(input_string, block_size=2): """ The cli tool as a built-in function. :param input_string: A string that should be converted to a set of facts. :type input_string: str. :param blocks_size: Optional block size of sentences (Default: 2). :type block_size: int. """ sentences...
[ "def", "converter", "(", "input_string", ",", "block_size", "=", "2", ")", ":", "sentences", "=", "textprocessing", ".", "getSentences", "(", "input_string", ")", "blocks", "=", "textprocessing", ".", "getBlocks", "(", "sentences", ",", "block_size", ")", "par...
The cli tool as a built-in function. :param input_string: A string that should be converted to a set of facts. :type input_string: str. :param blocks_size: Optional block size of sentences (Default: 2). :type block_size: int.
[ "The", "cli", "tool", "as", "a", "built", "-", "in", "function", "." ]
python
train
dswah/pyGAM
pygam/terms.py
https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/terms.py#L1340-L1368
def build_constraints(self, coef, constraint_lam, constraint_l2): """ builds the GAM block-diagonal constraint matrix in quadratic form out of constraint matrices specified for each feature. Parameters ---------- coefs : array-like containing the coefficients of a term ...
[ "def", "build_constraints", "(", "self", ",", "coef", ",", "constraint_lam", ",", "constraint_l2", ")", ":", "C", "=", "sp", ".", "sparse", ".", "csc_matrix", "(", "np", ".", "zeros", "(", "(", "self", ".", "n_coefs", ",", "self", ".", "n_coefs", ")", ...
builds the GAM block-diagonal constraint matrix in quadratic form out of constraint matrices specified for each feature. Parameters ---------- coefs : array-like containing the coefficients of a term constraint_lam : float, penalty to impose on the constraint. ...
[ "builds", "the", "GAM", "block", "-", "diagonal", "constraint", "matrix", "in", "quadratic", "form", "out", "of", "constraint", "matrices", "specified", "for", "each", "feature", "." ]
python
train
batiste/django-page-cms
pages/placeholders.py
https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/placeholders.py#L162-L171
def get_field(self, page, language, initial=None): """The field that will be shown within the admin.""" if self.parsed: help_text = _('Note: This field is evaluated as template code.') else: help_text = '' widget = self.get_widget(page, language) return se...
[ "def", "get_field", "(", "self", ",", "page", ",", "language", ",", "initial", "=", "None", ")", ":", "if", "self", ".", "parsed", ":", "help_text", "=", "_", "(", "'Note: This field is evaluated as template code.'", ")", "else", ":", "help_text", "=", "''",...
The field that will be shown within the admin.
[ "The", "field", "that", "will", "be", "shown", "within", "the", "admin", "." ]
python
train
PyCQA/pylint
pylint/checkers/utils.py
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/utils.py#L669-L681
def inherit_from_std_ex(node: astroid.node_classes.NodeNG) -> bool: """ Return true if the given class node is subclass of exceptions.Exception. """ ancestors = node.ancestors() if hasattr(node, "ancestors") else [] for ancestor in itertools.chain([node], ancestors): if ( anc...
[ "def", "inherit_from_std_ex", "(", "node", ":", "astroid", ".", "node_classes", ".", "NodeNG", ")", "->", "bool", ":", "ancestors", "=", "node", ".", "ancestors", "(", ")", "if", "hasattr", "(", "node", ",", "\"ancestors\"", ")", "else", "[", "]", "for",...
Return true if the given class node is subclass of exceptions.Exception.
[ "Return", "true", "if", "the", "given", "class", "node", "is", "subclass", "of", "exceptions", ".", "Exception", "." ]
python
test
elifesciences/elife-tools
elifetools/parseJATS.py
https://github.com/elifesciences/elife-tools/blob/4b9e38cbe485c61a4ed7cbd8970c6b318334fd86/elifetools/parseJATS.py#L990-L997
def contrib_phone(contrib_tag): """ Given a contrib tag, look for an phone tag """ phone = None if raw_parser.phone(contrib_tag): phone = first(raw_parser.phone(contrib_tag)).text return phone
[ "def", "contrib_phone", "(", "contrib_tag", ")", ":", "phone", "=", "None", "if", "raw_parser", ".", "phone", "(", "contrib_tag", ")", ":", "phone", "=", "first", "(", "raw_parser", ".", "phone", "(", "contrib_tag", ")", ")", ".", "text", "return", "phon...
Given a contrib tag, look for an phone tag
[ "Given", "a", "contrib", "tag", "look", "for", "an", "phone", "tag" ]
python
train
maciejkula/glove-python
glove/glove.py
https://github.com/maciejkula/glove-python/blob/749494290fdfd24379dcc2e244c583ee61808634/glove/glove.py#L190-L209
def add_dictionary(self, dictionary): """ Supply a word-id dictionary to allow similarity queries. """ if self.word_vectors is None: raise Exception('Model must be fit before adding a dictionary') if len(dictionary) > self.word_vectors.shape[0]: raise Ex...
[ "def", "add_dictionary", "(", "self", ",", "dictionary", ")", ":", "if", "self", ".", "word_vectors", "is", "None", ":", "raise", "Exception", "(", "'Model must be fit before adding a dictionary'", ")", "if", "len", "(", "dictionary", ")", ">", "self", ".", "w...
Supply a word-id dictionary to allow similarity queries.
[ "Supply", "a", "word", "-", "id", "dictionary", "to", "allow", "similarity", "queries", "." ]
python
train
MrYsLab/pymata-aio
pymata_aio/pymata_iot.py
https://github.com/MrYsLab/pymata-aio/blob/015081a4628b9d47dfe3f8d6c698ff903f107810/pymata_aio/pymata_iot.py#L320-L333
async def get_protocol_version(self): """ This method retrieves the Firmata protocol version. JSON command: {"method": "get_protocol_version", "params": ["null"]} :returns: {"method": "protocol_version_reply", "params": [PROTOCOL_VERSION]} """ value = await self.core.ge...
[ "async", "def", "get_protocol_version", "(", "self", ")", ":", "value", "=", "await", "self", ".", "core", ".", "get_protocol_version", "(", ")", "if", "value", ":", "reply", "=", "json", ".", "dumps", "(", "{", "\"method\"", ":", "\"protocol_version_reply\"...
This method retrieves the Firmata protocol version. JSON command: {"method": "get_protocol_version", "params": ["null"]} :returns: {"method": "protocol_version_reply", "params": [PROTOCOL_VERSION]}
[ "This", "method", "retrieves", "the", "Firmata", "protocol", "version", "." ]
python
train
nitmir/django-cas-server
cas_server/views.py
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/views.py#L543-L581
def process_post(self): """ Analyse the POST request: * check that the LoginTicket is valid * check that the user sumited credentials are valid :return: * :attr:`INVALID_LOGIN_TICKET` if the POSTed LoginTicket is not valid ...
[ "def", "process_post", "(", "self", ")", ":", "if", "not", "self", ".", "check_lt", "(", ")", ":", "self", ".", "init_form", "(", "self", ".", "request", ".", "POST", ")", "logger", ".", "warning", "(", "\"Received an invalid login ticket\"", ")", "return"...
Analyse the POST request: * check that the LoginTicket is valid * check that the user sumited credentials are valid :return: * :attr:`INVALID_LOGIN_TICKET` if the POSTed LoginTicket is not valid * :attr:`USER_ALREADY_LOGGED` if the user is al...
[ "Analyse", "the", "POST", "request", ":" ]
python
train
coleifer/walrus
walrus/containers.py
https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L984-L998
def pop(self, idx=None): """ Remove an item from the array. By default this will be the last item by index, but any index can be specified. """ if idx is not None: return self.database.run_script( 'array_remove', keys=[self.key], ...
[ "def", "pop", "(", "self", ",", "idx", "=", "None", ")", ":", "if", "idx", "is", "not", "None", ":", "return", "self", ".", "database", ".", "run_script", "(", "'array_remove'", ",", "keys", "=", "[", "self", ".", "key", "]", ",", "args", "=", "[...
Remove an item from the array. By default this will be the last item by index, but any index can be specified.
[ "Remove", "an", "item", "from", "the", "array", ".", "By", "default", "this", "will", "be", "the", "last", "item", "by", "index", "but", "any", "index", "can", "be", "specified", "." ]
python
train
sassoftware/saspy
saspy/sasbase.py
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasbase.py#L733-L753
def read_csv(self, file: str, table: str = '_csv', libref: str = '', results: str = '', opts: dict = None) -> 'SASdata': """ :param file: either the OS filesystem path of the file, or HTTP://... for a url accessible file :param table: the name of the SAS Data Set to create ...
[ "def", "read_csv", "(", "self", ",", "file", ":", "str", ",", "table", ":", "str", "=", "'_csv'", ",", "libref", ":", "str", "=", "''", ",", "results", ":", "str", "=", "''", ",", "opts", ":", "dict", "=", "None", ")", "->", "'SASdata'", ":", "...
:param file: either the OS filesystem path of the file, or HTTP://... for a url accessible file :param table: the name of the SAS Data Set to create :param libref: the libref for the SAS Data Set being created. Defaults to WORK, or USER if assigned :param results: format of results, SASsession.r...
[ ":", "param", "file", ":", "either", "the", "OS", "filesystem", "path", "of", "the", "file", "or", "HTTP", ":", "//", "...", "for", "a", "url", "accessible", "file", ":", "param", "table", ":", "the", "name", "of", "the", "SAS", "Data", "Set", "to", ...
python
train
habnabit/panglery
panglery/pangler.py
https://github.com/habnabit/panglery/blob/4d62e408c4bfaae126c93a6151ded1e8dc75bcc8/panglery/pangler.py#L113-L126
def combine(self, *others): """Combine other Panglers into this Pangler. Returns a copy of this Pangler with all of the hooks from the provided Panglers added to it as well. The new Pangler will be bound to the same instance and have the same `id`, but new hooks will not be shared with ...
[ "def", "combine", "(", "self", ",", "*", "others", ")", ":", "p", "=", "self", ".", "clone", "(", ")", "for", "other", "in", "others", ":", "p", ".", "hooks", ".", "extend", "(", "other", ".", "hooks", ")", "return", "p" ]
Combine other Panglers into this Pangler. Returns a copy of this Pangler with all of the hooks from the provided Panglers added to it as well. The new Pangler will be bound to the same instance and have the same `id`, but new hooks will not be shared with this Pangler or any provided Pa...
[ "Combine", "other", "Panglers", "into", "this", "Pangler", "." ]
python
train
mishbahr/django-connected
connected_accounts/views.py
https://github.com/mishbahr/django-connected/blob/7ec1f042786fef2eb6c00b1479ce47c90341ba81/connected_accounts/views.py#L119-L129
def get_login_redirect(self, provider, account): """Return url to redirect authenticated users.""" info = self.model._meta.app_label, self.model._meta.model_name # inline import to prevent circular imports. from .admin import PRESERVED_FILTERS_SESSION_KEY preserved_filters = self...
[ "def", "get_login_redirect", "(", "self", ",", "provider", ",", "account", ")", ":", "info", "=", "self", ".", "model", ".", "_meta", ".", "app_label", ",", "self", ".", "model", ".", "_meta", ".", "model_name", "# inline import to prevent circular imports.", ...
Return url to redirect authenticated users.
[ "Return", "url", "to", "redirect", "authenticated", "users", "." ]
python
train
pmichali/whodunit
whodunit/__init__.py
https://github.com/pmichali/whodunit/blob/eed9107533766d716469e35fbb647a39dfa07035/whodunit/__init__.py#L111-L118
def store_attribute(self, key, value): """Store blame info we are interested in.""" if key == 'summary' or key == 'filename' or key == 'previous': return attr = key.replace('-', '_') if key.endswith('-time'): value = int(value) setattr(self, attr, value)
[ "def", "store_attribute", "(", "self", ",", "key", ",", "value", ")", ":", "if", "key", "==", "'summary'", "or", "key", "==", "'filename'", "or", "key", "==", "'previous'", ":", "return", "attr", "=", "key", ".", "replace", "(", "'-'", ",", "'_'", ")...
Store blame info we are interested in.
[ "Store", "blame", "info", "we", "are", "interested", "in", "." ]
python
train
Nachtfeuer/pipeline
spline/tools/condition.py
https://github.com/Nachtfeuer/pipeline/blob/04ca18c4e95e4349532bb45b768206393e1f2c13/spline/tools/condition.py#L144-L167
def match_tokens(ast_tokens, ast_types): """ Verify that each token in order does match the expected types. The list provided by `get_tokens` does have three more elements at the beginning of the list which should be always the same for a condition (Module and Expr). Those are a...
[ "def", "match_tokens", "(", "ast_tokens", ",", "ast_types", ")", ":", "ast_final_types", "=", "[", "ast", ".", "Module", ",", "ast", ".", "Expr", "]", "+", "ast_types", "return", "all", "(", "isinstance", "(", "ast_token", ",", "ast_type", ")", "for", "a...
Verify that each token in order does match the expected types. The list provided by `get_tokens` does have three more elements at the beginning of the list which should be always the same for a condition (Module and Expr). Those are automatically added first to the final list of expecte...
[ "Verify", "that", "each", "token", "in", "order", "does", "match", "the", "expected", "types", "." ]
python
train
drdoctr/doctr
doctr/__main__.py
https://github.com/drdoctr/doctr/blob/0f19ff78c8239efcc98d417f36b0a31d9be01ba5/doctr/__main__.py#L372-L568
def configure(args, parser): """ Color guide - red: Error and warning messages - green: Welcome messages (use sparingly) - blue: Default values - bold_magenta: Action items - bold_black: Parts of code to be run or copied that should be modified """ if not args.force and on_travis():...
[ "def", "configure", "(", "args", ",", "parser", ")", ":", "if", "not", "args", ".", "force", "and", "on_travis", "(", ")", ":", "parser", ".", "error", "(", "red", "(", "\"doctr appears to be running on Travis. Use \"", "\"doctr configure --force to run anyway.\"", ...
Color guide - red: Error and warning messages - green: Welcome messages (use sparingly) - blue: Default values - bold_magenta: Action items - bold_black: Parts of code to be run or copied that should be modified
[ "Color", "guide" ]
python
train
JukeboxPipeline/jukedj
src/jukedj/models.py
https://github.com/JukeboxPipeline/jukedj/blob/d4159961c819c26792a278981ee68106ee15f3f3/src/jukedj/models.py#L490-L508
def create_all_tasks(element): """Create all tasks for the element :param element: The shot or asset that needs tasks :type element: :class:`muke.models.Shot` | :class:`muke.models.Asset` :returns: None :rtype: None :raises: None """ prj = element.project if isinstance(element, Asse...
[ "def", "create_all_tasks", "(", "element", ")", ":", "prj", "=", "element", ".", "project", "if", "isinstance", "(", "element", ",", "Asset", ")", ":", "flag", "=", "True", "else", ":", "flag", "=", "False", "deps", "=", "prj", ".", "department_set", "...
Create all tasks for the element :param element: The shot or asset that needs tasks :type element: :class:`muke.models.Shot` | :class:`muke.models.Asset` :returns: None :rtype: None :raises: None
[ "Create", "all", "tasks", "for", "the", "element" ]
python
test
taxpon/openpyscad
openpyscad/custom3dshapes.py
https://github.com/taxpon/openpyscad/blob/d487b409fcef429da7585dcc50180af3e9203236/openpyscad/custom3dshapes.py#L7-L36
def dice(edge=15, fn=32): """ dice """ edge = float(edge) # dice c = ops.Cube(edge, center=True) s = ops.Sphere(edge * 3 / 4, center=True) dice = c & s # points c = ops.Circle(edge / 12, _fn=fn) h = 0.7 point = c.linear_extrude(heig...
[ "def", "dice", "(", "edge", "=", "15", ",", "fn", "=", "32", ")", ":", "edge", "=", "float", "(", "edge", ")", "# dice", "c", "=", "ops", ".", "Cube", "(", "edge", ",", "center", "=", "True", ")", "s", "=", "ops", ".", "Sphere", "(", "edge", ...
dice
[ "dice" ]
python
train
mmp2/megaman
megaman/utils/k_means_clustering.py
https://github.com/mmp2/megaman/blob/faccaf267aad0a8b18ec8a705735fd9dd838ca1e/megaman/utils/k_means_clustering.py#L121-L145
def get_centroids(data,k,labels,centroids,data_norms): """ For each element in the dataset, choose the closest centroid Parameters ------------ data: array-like, shape= (m_samples,n_samples) K: integer, number of K clusters centroids: array-like, shape=(K, n_samples) labels: ...
[ "def", "get_centroids", "(", "data", ",", "k", ",", "labels", ",", "centroids", ",", "data_norms", ")", ":", "D", "=", "data", ".", "shape", "[", "1", "]", "for", "j", "in", "range", "(", "k", ")", ":", "cluster_points", "=", "np", ".", "where", ...
For each element in the dataset, choose the closest centroid Parameters ------------ data: array-like, shape= (m_samples,n_samples) K: integer, number of K clusters centroids: array-like, shape=(K, n_samples) labels: array-like, shape (1,n_samples) returns ------------- c...
[ "For", "each", "element", "in", "the", "dataset", "choose", "the", "closest", "centroid", "Parameters", "------------", "data", ":", "array", "-", "like", "shape", "=", "(", "m_samples", "n_samples", ")", "K", ":", "integer", "number", "of", "K", "clusters",...
python
train
saltstack/salt
salt/modules/mac_power.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_power.py#L360-L376
def get_restart_power_failure(): ''' Displays whether 'restart on power failure' is on or off if supported :return: A string value representing the "restart on power failure" settings :rtype: string CLI Example: .. code-block:: bash salt '*' power.get_restart_power_failure ''' ...
[ "def", "get_restart_power_failure", "(", ")", ":", "ret", "=", "salt", ".", "utils", ".", "mac_utils", ".", "execute_return_result", "(", "'systemsetup -getrestartpowerfailure'", ")", "return", "salt", ".", "utils", ".", "mac_utils", ".", "validate_enabled", "(", ...
Displays whether 'restart on power failure' is on or off if supported :return: A string value representing the "restart on power failure" settings :rtype: string CLI Example: .. code-block:: bash salt '*' power.get_restart_power_failure
[ "Displays", "whether", "restart", "on", "power", "failure", "is", "on", "or", "off", "if", "supported" ]
python
train
rytilahti/python-eq3bt
eq3bt/eq3cli.py
https://github.com/rytilahti/python-eq3bt/blob/595459d9885920cf13b7059a1edd2cf38cede1f0/eq3bt/eq3cli.py#L157-L168
def state(ctx): """ Prints out all available information. """ dev = ctx.obj click.echo(dev) ctx.forward(locked) ctx.forward(low_battery) ctx.forward(window_open) ctx.forward(boost) ctx.forward(temp) # ctx.forward(presets) ctx.forward(mode) ctx.forward(valve_state)
[ "def", "state", "(", "ctx", ")", ":", "dev", "=", "ctx", ".", "obj", "click", ".", "echo", "(", "dev", ")", "ctx", ".", "forward", "(", "locked", ")", "ctx", ".", "forward", "(", "low_battery", ")", "ctx", ".", "forward", "(", "window_open", ")", ...
Prints out all available information.
[ "Prints", "out", "all", "available", "information", "." ]
python
train
WhyNotHugo/django-afip
django_afip/models.py
https://github.com/WhyNotHugo/django-afip/blob/5fb73213f1fe86ca52b501ffd0737911ef26ddb3/django_afip/models.py#L1230-L1255
def save_pdf(self, save_model=True): """ Save the receipt as a PDF related to this model. The related :class:`~.Receipt` should be validated first, of course. :param bool save_model: If True, immediately save this model instance. """ from django_afip.views import Receip...
[ "def", "save_pdf", "(", "self", ",", "save_model", "=", "True", ")", ":", "from", "django_afip", ".", "views", "import", "ReceiptPDFView", "if", "not", "self", ".", "receipt", ".", "is_validated", ":", "raise", "exceptions", ".", "DjangoAfipException", "(", ...
Save the receipt as a PDF related to this model. The related :class:`~.Receipt` should be validated first, of course. :param bool save_model: If True, immediately save this model instance.
[ "Save", "the", "receipt", "as", "a", "PDF", "related", "to", "this", "model", "." ]
python
train
zeroSteiner/smoke-zephyr
smoke_zephyr/job.py
https://github.com/zeroSteiner/smoke-zephyr/blob/a6d2498aeacc72ee52e7806f783a4d83d537ffb2/smoke_zephyr/job.py#L219-L241
def stop(self): """ Stop the JobManager thread. """ self.logger.debug('stopping the job manager') self._thread_running.clear() self._thread_shutdown.wait() self._job_lock.acquire() self.logger.debug('waiting on ' + str(len(self._jobs)) + ' job threads') for job_desc in self._jobs.values(): if job_d...
[ "def", "stop", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "'stopping the job manager'", ")", "self", ".", "_thread_running", ".", "clear", "(", ")", "self", ".", "_thread_shutdown", ".", "wait", "(", ")", "self", ".", "_job_lock", "...
Stop the JobManager thread.
[ "Stop", "the", "JobManager", "thread", "." ]
python
train
log2timeline/plaso
plaso/parsers/mac_keychain.py
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/parsers/mac_keychain.py#L759-L798
def _ParseApplicationPasswordRecord(self, parser_mediator, record): """Extracts the information from an application password record. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. record (dict[str, object]): d...
[ "def", "_ParseApplicationPasswordRecord", "(", "self", ",", "parser_mediator", ",", "record", ")", ":", "key", "=", "record", ".", "get", "(", "'_key_'", ",", "None", ")", "if", "not", "key", "or", "not", "key", ".", "startswith", "(", "b'ssgp'", ")", ":...
Extracts the information from an application password record. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. record (dict[str, object]): database record. Raises: ParseError: if Internet password record ...
[ "Extracts", "the", "information", "from", "an", "application", "password", "record", "." ]
python
train
Jammy2211/PyAutoLens
autolens/model/galaxy/galaxy.py
https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/galaxy/galaxy.py#L259-L279
def mass_within_ellipse_in_units(self, major_axis, unit_mass='angular', kpc_per_arcsec=None, critical_surface_density=None): """Compute the total angular mass of the galaxy's mass profiles within an ellipse of specified major_axis. See *profiles.mass_profiles.angualr_mass_within_ellipse* for details of...
[ "def", "mass_within_ellipse_in_units", "(", "self", ",", "major_axis", ",", "unit_mass", "=", "'angular'", ",", "kpc_per_arcsec", "=", "None", ",", "critical_surface_density", "=", "None", ")", ":", "if", "self", ".", "has_mass_profile", ":", "return", "sum", "(...
Compute the total angular mass of the galaxy's mass profiles within an ellipse of specified major_axis. See *profiles.mass_profiles.angualr_mass_within_ellipse* for details of how this is performed. Parameters ---------- major_axis : float The major-axis radius of the ellip...
[ "Compute", "the", "total", "angular", "mass", "of", "the", "galaxy", "s", "mass", "profiles", "within", "an", "ellipse", "of", "specified", "major_axis", "." ]
python
valid
danielhrisca/asammdf
asammdf/blocks/mdf_v3.py
https://github.com/danielhrisca/asammdf/blob/3c7a1fd19c957ceebe4dcdbb2abf00806c2bdb66/asammdf/blocks/mdf_v3.py#L2406-L2451
def get_channel_comment(self, name=None, group=None, index=None): """Gets channel comment. Channel can be specified in two ways: * using the first positional argument *name* * if there are multiple occurances for this channel then the *group* and *index* arguments can...
[ "def", "get_channel_comment", "(", "self", ",", "name", "=", "None", ",", "group", "=", "None", ",", "index", "=", "None", ")", ":", "gp_nr", ",", "ch_nr", "=", "self", ".", "_validate_channel_selection", "(", "name", ",", "group", ",", "index", ")", "...
Gets channel comment. Channel can be specified in two ways: * using the first positional argument *name* * if there are multiple occurances for this channel then the *group* and *index* arguments can be used to select a specific group. * if there are...
[ "Gets", "channel", "comment", ".", "Channel", "can", "be", "specified", "in", "two", "ways", ":" ]
python
train
python-rope/rope
rope/base/pycore.py
https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/pycore.py#L326-L334
def is_changed(self, start, end): """Tell whether any of start till end lines have changed The end points are inclusive and indices start from 1. """ left, right = self._get_changed(start, end) if left < right: return True return False
[ "def", "is_changed", "(", "self", ",", "start", ",", "end", ")", ":", "left", ",", "right", "=", "self", ".", "_get_changed", "(", "start", ",", "end", ")", "if", "left", "<", "right", ":", "return", "True", "return", "False" ]
Tell whether any of start till end lines have changed The end points are inclusive and indices start from 1.
[ "Tell", "whether", "any", "of", "start", "till", "end", "lines", "have", "changed" ]
python
train
bitesofcode/projexui
projexui/widgets/xtreewidget/xtreewidget.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtreewidget/xtreewidget.py#L1875-L1885
def setVisibleColumns(self, visible): """ Sets the list of visible columns for this widget. This method will take any column in this tree's list NOT found within the inputed column list and hide them. :param columns | [<str>, ..] """ colname...
[ "def", "setVisibleColumns", "(", "self", ",", "visible", ")", ":", "colnames", "=", "self", ".", "columns", "(", ")", "for", "c", ",", "column", "in", "enumerate", "(", "colnames", ")", ":", "self", ".", "setColumnHidden", "(", "c", ",", "column", "not...
Sets the list of visible columns for this widget. This method will take any column in this tree's list NOT found within the inputed column list and hide them. :param columns | [<str>, ..]
[ "Sets", "the", "list", "of", "visible", "columns", "for", "this", "widget", ".", "This", "method", "will", "take", "any", "column", "in", "this", "tree", "s", "list", "NOT", "found", "within", "the", "inputed", "column", "list", "and", "hide", "them", "....
python
train
HydrelioxGitHub/pybbox
pybbox/__init__.py
https://github.com/HydrelioxGitHub/pybbox/blob/bedcdccab5d18d36890ef8bf414845f2dec18b5c/pybbox/__init__.py#L115-L127
def is_device_connected(self, ip): """ Check if a device identified by it IP is connected to the box :param ip: IP of the device you want to test :type ip: str :return: True is the device is connected, False if it's not :rtype: bool """ all_devices = self....
[ "def", "is_device_connected", "(", "self", ",", "ip", ")", ":", "all_devices", "=", "self", ".", "get_all_connected_devices", "(", ")", "for", "device", "in", "all_devices", ":", "if", "ip", "==", "device", "[", "'ipaddress'", "]", ":", "return", "device", ...
Check if a device identified by it IP is connected to the box :param ip: IP of the device you want to test :type ip: str :return: True is the device is connected, False if it's not :rtype: bool
[ "Check", "if", "a", "device", "identified", "by", "it", "IP", "is", "connected", "to", "the", "box", ":", "param", "ip", ":", "IP", "of", "the", "device", "you", "want", "to", "test", ":", "type", "ip", ":", "str", ":", "return", ":", "True", "is",...
python
train
tchellomello/python-arlo
pyarlo/base_station.py
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L362-L369
def is_in_schedule_mode(self): """Returns True if base_station is currently on a scheduled mode.""" resource = "schedule" mode_event = self.publish_and_get_event(resource) if mode_event and mode_event.get("resource", None) == "schedule": properties = mode_event.get('propertie...
[ "def", "is_in_schedule_mode", "(", "self", ")", ":", "resource", "=", "\"schedule\"", "mode_event", "=", "self", ".", "publish_and_get_event", "(", "resource", ")", "if", "mode_event", "and", "mode_event", ".", "get", "(", "\"resource\"", ",", "None", ")", "==...
Returns True if base_station is currently on a scheduled mode.
[ "Returns", "True", "if", "base_station", "is", "currently", "on", "a", "scheduled", "mode", "." ]
python
train
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/brocade_mac_access_list.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_mac_access_list.py#L446-L460
def get_mac_acl_for_intf_output_interface_interface_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_mac_acl_for_intf = ET.Element("get_mac_acl_for_intf") config = get_mac_acl_for_intf output = ET.SubElement(get_mac_acl_for_intf, "output"...
[ "def", "get_mac_acl_for_intf_output_interface_interface_name", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "get_mac_acl_for_intf", "=", "ET", ".", "Element", "(", "\"get_mac_acl_for_intf\"", ")", "co...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
materialsproject/pymatgen
pymatgen/analysis/structure_analyzer.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/structure_analyzer.py#L350-L363
def get_sitej(self, site_index, image_index): """ Assuming there is some value in the connectivity array at indices (1, 3, 12). sitei can be obtained directly from the input structure (structure[1]). sitej can be obtained by passing 3, 12 to this function Args: site_...
[ "def", "get_sitej", "(", "self", ",", "site_index", ",", "image_index", ")", ":", "atoms_n_occu", "=", "self", ".", "s", "[", "site_index", "]", ".", "species", "lattice", "=", "self", ".", "s", ".", "lattice", "coords", "=", "self", ".", "s", "[", "...
Assuming there is some value in the connectivity array at indices (1, 3, 12). sitei can be obtained directly from the input structure (structure[1]). sitej can be obtained by passing 3, 12 to this function Args: site_index (int): index of the site (3 in the example) imag...
[ "Assuming", "there", "is", "some", "value", "in", "the", "connectivity", "array", "at", "indices", "(", "1", "3", "12", ")", ".", "sitei", "can", "be", "obtained", "directly", "from", "the", "input", "structure", "(", "structure", "[", "1", "]", ")", "...
python
train
cltl/KafNafParserPy
KafNafParserPy/KafNafParserMod.py
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/KafNafParserMod.py#L734-L744
def remove_dependency_layer(self): """ Removes the dependency layer (if exists) of the object (in memory) """ if self.dependency_layer is not None: this_node = self.dependency_layer.get_node() self.root.remove(this_node) self.dependency_layer = self.my...
[ "def", "remove_dependency_layer", "(", "self", ")", ":", "if", "self", ".", "dependency_layer", "is", "not", "None", ":", "this_node", "=", "self", ".", "dependency_layer", ".", "get_node", "(", ")", "self", ".", "root", ".", "remove", "(", "this_node", ")...
Removes the dependency layer (if exists) of the object (in memory)
[ "Removes", "the", "dependency", "layer", "(", "if", "exists", ")", "of", "the", "object", "(", "in", "memory", ")" ]
python
train
cons3rt/pycons3rt
pycons3rt/deployment.py
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/deployment.py#L638-L665
def get_scenario_host_ip_on_network(self, scenario_role_name, network_name): """Given a network name, returns the IP address :param network_name: (str) Name of the network to search for :param scenario_role_name: (str) role name to return the IP address for :return: (str) IP address on ...
[ "def", "get_scenario_host_ip_on_network", "(", "self", ",", "scenario_role_name", ",", "network_name", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "self", ".", "cls_logger", "+", "'.get_scenario_host_ip_on_network'", ")", "# Determine the network info for this...
Given a network name, returns the IP address :param network_name: (str) Name of the network to search for :param scenario_role_name: (str) role name to return the IP address for :return: (str) IP address on the specified network or None
[ "Given", "a", "network", "name", "returns", "the", "IP", "address" ]
python
train
hyperledger/sawtooth-core
validator/sawtooth_validator/execution/scheduler_parallel.py
https://github.com/hyperledger/sawtooth-core/blob/8cf473bc2207e51f02bd182d825158a57d72b098/validator/sawtooth_validator/execution/scheduler_parallel.py#L812-L848
def _set_least_batch_id(self, txn_signature): """Set the first batch id that doesn't have all results. Args: txn_signature (str): The txn identifier of the transaction with results being set. """ batch = self._batches_by_txn_id[txn_signature] least...
[ "def", "_set_least_batch_id", "(", "self", ",", "txn_signature", ")", ":", "batch", "=", "self", ".", "_batches_by_txn_id", "[", "txn_signature", "]", "least_index", "=", "self", ".", "_index_of_batch", "(", "self", ".", "_batches_by_id", "[", "self", ".", "_l...
Set the first batch id that doesn't have all results. Args: txn_signature (str): The txn identifier of the transaction with results being set.
[ "Set", "the", "first", "batch", "id", "that", "doesn", "t", "have", "all", "results", "." ]
python
train
senaite/senaite.core.supermodel
src/senaite/core/supermodel/model.py
https://github.com/senaite/senaite.core.supermodel/blob/1819154332b8776f187aa98a2e299701983a0119/src/senaite/core/supermodel/model.py#L77-L83
def init_with_brain(self, brain): """Initialize with a catalog brain """ self._uid = api.get_uid(brain) self._brain = brain self._catalog = self.get_catalog_for(brain) self._instance = None
[ "def", "init_with_brain", "(", "self", ",", "brain", ")", ":", "self", ".", "_uid", "=", "api", ".", "get_uid", "(", "brain", ")", "self", ".", "_brain", "=", "brain", "self", ".", "_catalog", "=", "self", ".", "get_catalog_for", "(", "brain", ")", "...
Initialize with a catalog brain
[ "Initialize", "with", "a", "catalog", "brain" ]
python
train
tensorflow/tensor2tensor
tensor2tensor/trax/trax.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L307-L333
def _jit_update_fun(predict_fun, loss_fun, optimizer, lr_fun, num_devices): """Get jit-ed update function for loss, optimizer, learning rate function.""" if num_devices == 1: # TODO(lukaszkaiser): remove branch when not needed. def single_update(i, opt_state, batch, rng): rng, subrng = jax_random.split(r...
[ "def", "_jit_update_fun", "(", "predict_fun", ",", "loss_fun", ",", "optimizer", ",", "lr_fun", ",", "num_devices", ")", ":", "if", "num_devices", "==", "1", ":", "# TODO(lukaszkaiser): remove branch when not needed.", "def", "single_update", "(", "i", ",", "opt_sta...
Get jit-ed update function for loss, optimizer, learning rate function.
[ "Get", "jit", "-", "ed", "update", "function", "for", "loss", "optimizer", "learning", "rate", "function", "." ]
python
train
doraemonext/wechat-python-sdk
wechat_sdk/core/conf.py
https://github.com/doraemonext/wechat-python-sdk/blob/bf6f6f3d4a5440feb73a51937059d7feddc335a0/wechat_sdk/core/conf.py#L286-L295
def _update_crypto(self): """ 根据当前配置内容更新 Crypto 类 """ if self.__encrypt_mode in ['compatible', 'safe'] and self.__encoding_aes_key is not None: if self.__token is None or self.__appid is None: raise NeedParamError('Please provide token and appid parameters in ...
[ "def", "_update_crypto", "(", "self", ")", ":", "if", "self", ".", "__encrypt_mode", "in", "[", "'compatible'", ",", "'safe'", "]", "and", "self", ".", "__encoding_aes_key", "is", "not", "None", ":", "if", "self", ".", "__token", "is", "None", "or", "sel...
根据当前配置内容更新 Crypto 类
[ "根据当前配置内容更新", "Crypto", "类" ]
python
valid
saltstack/salt
salt/modules/btrfs.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/btrfs.py#L514-L580
def _restripe(mountpoint, direction, *devices, **kwargs): ''' Restripe BTRFS: add or remove devices from the particular mounted filesystem. ''' fs_log = [] if salt.utils.fsutils._is_device(mountpoint): raise CommandExecutionError( "Mountpount expected, while device \"{0}\" speci...
[ "def", "_restripe", "(", "mountpoint", ",", "direction", ",", "*", "devices", ",", "*", "*", "kwargs", ")", ":", "fs_log", "=", "[", "]", "if", "salt", ".", "utils", ".", "fsutils", ".", "_is_device", "(", "mountpoint", ")", ":", "raise", "CommandExecu...
Restripe BTRFS: add or remove devices from the particular mounted filesystem.
[ "Restripe", "BTRFS", ":", "add", "or", "remove", "devices", "from", "the", "particular", "mounted", "filesystem", "." ]
python
train
tmontaigu/pylas
pylas/point/dims.py
https://github.com/tmontaigu/pylas/blob/8335a1a7d7677f0e4bc391bb6fa3c75b42ed5b06/pylas/point/dims.py#L29-L37
def _build_point_formats_dtypes(point_format_dimensions, dimensions_dict): """ Builds the dict mapping point format id to numpy.dtype In the dtypes, bit fields are still packed, and need to be unpacked each time you want to access them """ return { fmt_id: _point_format_to_dtype(point_fmt, d...
[ "def", "_build_point_formats_dtypes", "(", "point_format_dimensions", ",", "dimensions_dict", ")", ":", "return", "{", "fmt_id", ":", "_point_format_to_dtype", "(", "point_fmt", ",", "dimensions_dict", ")", "for", "fmt_id", ",", "point_fmt", "in", "point_format_dimensio...
Builds the dict mapping point format id to numpy.dtype In the dtypes, bit fields are still packed, and need to be unpacked each time you want to access them
[ "Builds", "the", "dict", "mapping", "point", "format", "id", "to", "numpy", ".", "dtype", "In", "the", "dtypes", "bit", "fields", "are", "still", "packed", "and", "need", "to", "be", "unpacked", "each", "time", "you", "want", "to", "access", "them" ]
python
test