repo
stringlengths
7
55
path
stringlengths
4
223
url
stringlengths
87
315
code
stringlengths
75
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
avg_line_len
float64
7.91
980
apache/airflow
airflow/contrib/hooks/azure_fileshare_hook.py
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/azure_fileshare_hook.py#L174-L191
def load_string(self, string_data, share_name, directory_name, file_name, **kwargs): """ Upload a string to Azure File Share. :param string_data: String to load. :type string_data: str :param share_name: Name of the share. :type share_name: str :param directory_n...
[ "def", "load_string", "(", "self", ",", "string_data", ",", "share_name", ",", "directory_name", ",", "file_name", ",", "*", "*", "kwargs", ")", ":", "self", ".", "connection", ".", "create_file_from_text", "(", "share_name", ",", "directory_name", ",", "file_...
Upload a string to Azure File Share. :param string_data: String to load. :type string_data: str :param share_name: Name of the share. :type share_name: str :param directory_name: Name of the directory. :type directory_name: str :param file_name: Name of the file....
[ "Upload", "a", "string", "to", "Azure", "File", "Share", "." ]
python
test
41.333333
ehansis/ozelot
ozelot/orm/base.py
https://github.com/ehansis/ozelot/blob/948675e02eb6fca940450f5cb814f53e97159e5b/ozelot/orm/base.py#L112-L146
def get_max_id(cls, session): """Get the current max value of the ``id`` column. When creating and storing ORM objects in bulk, :mod:`sqlalchemy` does not automatically generate an incrementing primary key ``id``. To do this manually, one needs to know the current max ``id``. For ORM ob...
[ "def", "get_max_id", "(", "cls", ",", "session", ")", ":", "# sqlalchemy allows only one level of inheritance, so just check this class and all its bases", "id_base", "=", "None", "for", "c", "in", "[", "cls", "]", "+", "list", "(", "cls", ".", "__bases__", ")", ":"...
Get the current max value of the ``id`` column. When creating and storing ORM objects in bulk, :mod:`sqlalchemy` does not automatically generate an incrementing primary key ``id``. To do this manually, one needs to know the current max ``id``. For ORM object classes that are derived from other ...
[ "Get", "the", "current", "max", "value", "of", "the", "id", "column", "." ]
python
train
43.514286
hcchengithub/peforth
__init__.py
https://github.com/hcchengithub/peforth/blob/51f5e5255d647f3bdab5649fdc49ec984be579d0/__init__.py#L72-L112
def ok(prompt='OK ', loc={}, glo={}, cmd=""): ''' Invoke the peforth interpreter. An statement: peforth.ok(prompt='OK ', loc=locals(), glo=globals(), cmd="") is like a breakpoint. The prompt indicates which breakpoint it is if there are many. Arguments loc (locals) and glo (globals) along with the...
[ "def", "ok", "(", "prompt", "=", "'OK '", ",", "loc", "=", "{", "}", ",", "glo", "=", "{", "}", ",", "cmd", "=", "\"\"", ")", ":", "if", "loc", "or", "glo", ":", "vm", ".", "push", "(", "(", "loc", ",", "glo", ",", "prompt", ")", ")", "# ...
Invoke the peforth interpreter. An statement: peforth.ok(prompt='OK ', loc=locals(), glo=globals(), cmd="") is like a breakpoint. The prompt indicates which breakpoint it is if there are many. Arguments loc (locals) and glo (globals) along with the prompt are the debuggee's informations that is packe...
[ "Invoke", "the", "peforth", "interpreter", ".", "An", "statement", ":", "peforth", ".", "ok", "(", "prompt", "=", "OK", "loc", "=", "locals", "()", "glo", "=", "globals", "()", "cmd", "=", ")", "is", "like", "a", "breakpoint", ".", "The", "prompt", "...
python
train
51.341463
projectatomic/osbs-client
osbs/api.py
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/api.py#L765-L793
def create_prod_build(self, *args, **kwargs): """ Create a production build :param git_uri: str, URI of git repository :param git_ref: str, reference to commit :param git_branch: str, branch name :param user: str, user name :param component: str, not used anymore...
[ "def", "create_prod_build", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "warning", "(", "\"prod (all-in-one) builds are deprecated, \"", "\"please use create_orchestrator_build \"", "\"(support will be removed in version 0.54)\"", ")", "...
Create a production build :param git_uri: str, URI of git repository :param git_ref: str, reference to commit :param git_branch: str, branch name :param user: str, user name :param component: str, not used anymore :param target: str, koji target :param architectu...
[ "Create", "a", "production", "build" ]
python
train
51.551724
tanghaibao/goatools
goatools/anno/genetogo_reader.py
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/anno/genetogo_reader.py#L64-L68
def fill_taxid2asscs(taxid2asscs_usr, taxid2asscs_ret): """Fill user taxid2asscs for backward compatibility.""" for taxid, ab_ret in taxid2asscs_ret.items(): taxid2asscs_usr[taxid]['ID2GOs'] = ab_ret['ID2GOs'] taxid2asscs_usr[taxid]['GO2IDs'] = ab_ret['GO2IDs']
[ "def", "fill_taxid2asscs", "(", "taxid2asscs_usr", ",", "taxid2asscs_ret", ")", ":", "for", "taxid", ",", "ab_ret", "in", "taxid2asscs_ret", ".", "items", "(", ")", ":", "taxid2asscs_usr", "[", "taxid", "]", "[", "'ID2GOs'", "]", "=", "ab_ret", "[", "'ID2GOs...
Fill user taxid2asscs for backward compatibility.
[ "Fill", "user", "taxid2asscs", "for", "backward", "compatibility", "." ]
python
train
59.4
idlesign/django-sitetree
sitetree/sitetreeapp.py
https://github.com/idlesign/django-sitetree/blob/61de4608e6e415247c75fe8691027d7c4ed0d1e7/sitetree/sitetreeapp.py#L341-L348
def get_entry(self, entry_name, key): """Returns cache entry parameter value by its name. :param str|unicode entry_name: :param key: :return: """ return self.cache[entry_name].get(key, False)
[ "def", "get_entry", "(", "self", ",", "entry_name", ",", "key", ")", ":", "return", "self", ".", "cache", "[", "entry_name", "]", ".", "get", "(", "key", ",", "False", ")" ]
Returns cache entry parameter value by its name. :param str|unicode entry_name: :param key: :return:
[ "Returns", "cache", "entry", "parameter", "value", "by", "its", "name", "." ]
python
test
29.125
bitesofcode/projex
projex/envmanager.py
https://github.com/bitesofcode/projex/blob/d31743ec456a41428709968ab11a2cf6c6c76247/projex/envmanager.py#L68-L84
def appendPath(self, path): """ Appends the inputted path to the end of the sys.path variable, provided the path does not already exist in it. :param path :type str :return bool: success """ # normalize the path pat...
[ "def", "appendPath", "(", "self", ",", "path", ")", ":", "# normalize the path", "path", "=", "os", ".", "path", ".", "normcase", "(", "nstr", "(", "path", ")", ")", ".", "strip", "(", ")", "if", "path", "and", "path", "!=", "'.'", "and", "path", "...
Appends the inputted path to the end of the sys.path variable, provided the path does not already exist in it. :param path :type str :return bool: success
[ "Appends", "the", "inputted", "path", "to", "the", "end", "of", "the", "sys", ".", "path", "variable", "provided", "the", "path", "does", "not", "already", "exist", "in", "it", ".", ":", "param", "path", ":", "type", "str", ":", "return", "bool", ":", ...
python
train
30.764706
kivy/python-for-android
pythonforandroid/bootstraps/pygame/build/buildlib/argparse.py
https://github.com/kivy/python-for-android/blob/8e0e8056bc22e4d5bd3398a6b0301f38ff167933/pythonforandroid/bootstraps/pygame/build/buildlib/argparse.py#L2348-L2358
def error(self, message): """error(message: string) Prints a usage message incorporating the message to stderr and exits. If you override this in a subclass, it should not return -- it should either exit or raise an exception. """ self.print_usage(_sys....
[ "def", "error", "(", "self", ",", "message", ")", ":", "self", ".", "print_usage", "(", "_sys", ".", "stderr", ")", "self", ".", "exit", "(", "2", ",", "_", "(", "'%s: error: %s\\n'", ")", "%", "(", "self", ".", "prog", ",", "message", ")", ")" ]
error(message: string) Prints a usage message incorporating the message to stderr and exits. If you override this in a subclass, it should not return -- it should either exit or raise an exception.
[ "error", "(", "message", ":", "string", ")", "Prints", "a", "usage", "message", "incorporating", "the", "message", "to", "stderr", "and", "exits", ".", "If", "you", "override", "this", "in", "a", "subclass", "it", "should", "not", "return", "--", "it", "...
python
train
34.909091
pydata/numexpr
numexpr/necompiler.py
https://github.com/pydata/numexpr/blob/364bac13d84524e0e01db892301b2959d822dcff/numexpr/necompiler.py#L158-L166
def expressionToAST(ex): """Take an expression tree made out of expressions.ExpressionNode, and convert to an AST tree. This is necessary as ExpressionNode overrides many methods to act like a number. """ return ASTNode(ex.astType, ex.astKind, ex.value, [expressionToAST(c) fo...
[ "def", "expressionToAST", "(", "ex", ")", ":", "return", "ASTNode", "(", "ex", ".", "astType", ",", "ex", ".", "astKind", ",", "ex", ".", "value", ",", "[", "expressionToAST", "(", "c", ")", "for", "c", "in", "ex", ".", "children", "]", ")" ]
Take an expression tree made out of expressions.ExpressionNode, and convert to an AST tree. This is necessary as ExpressionNode overrides many methods to act like a number.
[ "Take", "an", "expression", "tree", "made", "out", "of", "expressions", ".", "ExpressionNode", "and", "convert", "to", "an", "AST", "tree", "." ]
python
train
36.888889
raphaelvallat/pingouin
pingouin/multicomp.py
https://github.com/raphaelvallat/pingouin/blob/58b19fa4fffbfe09d58b456e3926a148249e4d9b/pingouin/multicomp.py#L193-L279
def holm(pvals, alpha=.05): """P-values correction with Holm method. Parameters ---------- pvals : array_like Array of p-values of the individual tests. alpha : float Error rate (= alpha level). Returns ------- reject : array, bool True if a hypothesis is reject...
[ "def", "holm", "(", "pvals", ",", "alpha", "=", ".05", ")", ":", "# Convert to array and save original shape", "pvals", "=", "np", ".", "asarray", "(", "pvals", ")", "shape_init", "=", "pvals", ".", "shape", "pvals", "=", "pvals", ".", "ravel", "(", ")", ...
P-values correction with Holm method. Parameters ---------- pvals : array_like Array of p-values of the individual tests. alpha : float Error rate (= alpha level). Returns ------- reject : array, bool True if a hypothesis is rejected, False if not pvals_correcte...
[ "P", "-", "values", "correction", "with", "Holm", "method", "." ]
python
train
31.034483
aleju/imgaug
imgaug/imgaug.py
https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/imgaug.py#L185-L200
def is_integer_array(val): """ Checks whether a variable is a numpy integer array. Parameters ---------- val The variable to check. Returns ------- bool True if the variable is a numpy integer array. Otherwise False. """ return is_np_array(val) and issubclass(v...
[ "def", "is_integer_array", "(", "val", ")", ":", "return", "is_np_array", "(", "val", ")", "and", "issubclass", "(", "val", ".", "dtype", ".", "type", ",", "np", ".", "integer", ")" ]
Checks whether a variable is a numpy integer array. Parameters ---------- val The variable to check. Returns ------- bool True if the variable is a numpy integer array. Otherwise False.
[ "Checks", "whether", "a", "variable", "is", "a", "numpy", "integer", "array", "." ]
python
valid
20.6875
gboeing/osmnx
osmnx/pois.py
https://github.com/gboeing/osmnx/blob/be59fd313bcb68af8fc79242c56194f1247e26e2/osmnx/pois.py#L24-L65
def parse_poi_query(north, south, east, west, amenities=None, timeout=180, maxsize=''): """ Parse the Overpass QL query based on the list of amenities. Parameters ---------- north : float Northernmost coordinate from bounding box of the search area. south : float Southernmo...
[ "def", "parse_poi_query", "(", "north", ",", "south", ",", "east", ",", "west", ",", "amenities", "=", "None", ",", "timeout", "=", "180", ",", "maxsize", "=", "''", ")", ":", "if", "amenities", ":", "# Overpass QL template", "query_template", "=", "(", ...
Parse the Overpass QL query based on the list of amenities. Parameters ---------- north : float Northernmost coordinate from bounding box of the search area. south : float Southernmost coordinate from bounding box of the search area. east : float Easternmost coordinate ...
[ "Parse", "the", "Overpass", "QL", "query", "based", "on", "the", "list", "of", "amenities", "." ]
python
train
48.166667
iotile/coretools
iotilesensorgraph/iotile/sg/parser/parser_v1.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/parser/parser_v1.py#L85-L115
def compile(self, model): """Compile this file into a SensorGraph. You must have preivously called parse_file to parse a sensor graph file into statements that are then executed by this command to build a sensor graph. The results are stored in self.sensor_graph and can be ...
[ "def", "compile", "(", "self", ",", "model", ")", ":", "log", "=", "SensorLog", "(", "InMemoryStorageEngine", "(", "model", ")", ",", "model", ")", "self", ".", "sensor_graph", "=", "SensorGraph", "(", "log", ",", "model", ")", "allocator", "=", "StreamA...
Compile this file into a SensorGraph. You must have preivously called parse_file to parse a sensor graph file into statements that are then executed by this command to build a sensor graph. The results are stored in self.sensor_graph and can be inspected before running optimiza...
[ "Compile", "this", "file", "into", "a", "SensorGraph", "." ]
python
train
32.967742
bcbio/bcbio-nextgen
bcbio/distributed/objectstore.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/objectstore.py#L362-L369
def connect(cls, resource): """Connect to this Region's endpoint. Returns a connection object pointing to the endpoint associated to the received resource. """ import boto return boto.s3.connect_to_region(cls.get_region(resource))
[ "def", "connect", "(", "cls", ",", "resource", ")", ":", "import", "boto", "return", "boto", ".", "s3", ".", "connect_to_region", "(", "cls", ".", "get_region", "(", "resource", ")", ")" ]
Connect to this Region's endpoint. Returns a connection object pointing to the endpoint associated to the received resource.
[ "Connect", "to", "this", "Region", "s", "endpoint", "." ]
python
train
34
ValvePython/steam
steam/util/web.py
https://github.com/ValvePython/steam/blob/2de1364c47598410b572114e6129eab8fff71d5b/steam/util/web.py#L5-L17
def make_requests_session(): """ :returns: requests session :rtype: :class:`requests.Session` """ session = requests.Session() version = __import__('steam').__version__ ua = "python-steam/{0} {1}".format(version, session.headers['User-Agent']) session.hea...
[ "def", "make_requests_session", "(", ")", ":", "session", "=", "requests", ".", "Session", "(", ")", "version", "=", "__import__", "(", "'steam'", ")", ".", "__version__", "ua", "=", "\"python-steam/{0} {1}\"", ".", "format", "(", "version", ",", "session", ...
:returns: requests session :rtype: :class:`requests.Session`
[ ":", "returns", ":", "requests", "session", ":", "rtype", ":", ":", "class", ":", "requests", ".", "Session" ]
python
train
27
PSU-OIT-ARC/django-cloak
cloak/__init__.py
https://github.com/PSU-OIT-ARC/django-cloak/blob/3f09711837f4fe7b1813692daa064e536135ffa3/cloak/__init__.py#L5-L19
def can_cloak_as(user, other_user): """ Returns true if `user` can cloak as `other_user` """ # check to see if the user is allowed to do this can_cloak = False try: can_cloak = user.can_cloak_as(other_user) except AttributeError as e: try: can_cloak = user.is_staf...
[ "def", "can_cloak_as", "(", "user", ",", "other_user", ")", ":", "# check to see if the user is allowed to do this", "can_cloak", "=", "False", "try", ":", "can_cloak", "=", "user", ".", "can_cloak_as", "(", "other_user", ")", "except", "AttributeError", "as", "e", ...
Returns true if `user` can cloak as `other_user`
[ "Returns", "true", "if", "user", "can", "cloak", "as", "other_user" ]
python
train
25.466667
apache/airflow
airflow/bin/cli.py
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/bin/cli.py#L221-L236
def trigger_dag(args): """ Creates a dag run for the specified dag :param args: :return: """ log = LoggingMixin().log try: message = api_client.trigger_dag(dag_id=args.dag_id, run_id=args.run_id, conf=a...
[ "def", "trigger_dag", "(", "args", ")", ":", "log", "=", "LoggingMixin", "(", ")", ".", "log", "try", ":", "message", "=", "api_client", ".", "trigger_dag", "(", "dag_id", "=", "args", ".", "dag_id", ",", "run_id", "=", "args", ".", "run_id", ",", "c...
Creates a dag run for the specified dag :param args: :return:
[ "Creates", "a", "dag", "run", "for", "the", "specified", "dag", ":", "param", "args", ":", ":", "return", ":" ]
python
test
30.875
openatx/facebook-wda
wda/__init__.py
https://github.com/openatx/facebook-wda/blob/aa644204620c6d5c7705a9c7452d8c0cc39330d5/wda/__init__.py#L707-L721
def _add_escape_character_for_quote_prime_character(self, text): """ Fix for https://github.com/openatx/facebook-wda/issues/33 Returns: string with properly formated quotes, or non changed text """ if text is not None: if "'" in text: return text...
[ "def", "_add_escape_character_for_quote_prime_character", "(", "self", ",", "text", ")", ":", "if", "text", "is", "not", "None", ":", "if", "\"'\"", "in", "text", ":", "return", "text", ".", "replace", "(", "\"'\"", ",", "\"\\\\'\"", ")", "elif", "'\"'", "...
Fix for https://github.com/openatx/facebook-wda/issues/33 Returns: string with properly formated quotes, or non changed text
[ "Fix", "for", "https", ":", "//", "github", ".", "com", "/", "openatx", "/", "facebook", "-", "wda", "/", "issues", "/", "33", "Returns", ":", "string", "with", "properly", "formated", "quotes", "or", "non", "changed", "text" ]
python
train
31.6
dolph/pasteraw-client
pasteraw.py
https://github.com/dolph/pasteraw-client/blob/f1d5ec0bc0fb02584ad12f50266ac8f1fd2a3297/pasteraw.py#L63-L86
def create_paste(self, content): """Create a raw paste of the given content. Returns a URL to the paste, or raises a ``pasteraw.Error`` if something tragic happens instead. """ r = requests.post( self.endpoint + '/pastes', data={'content': content}, ...
[ "def", "create_paste", "(", "self", ",", "content", ")", ":", "r", "=", "requests", ".", "post", "(", "self", ".", "endpoint", "+", "'/pastes'", ",", "data", "=", "{", "'content'", ":", "content", "}", ",", "allow_redirects", "=", "False", ")", "if", ...
Create a raw paste of the given content. Returns a URL to the paste, or raises a ``pasteraw.Error`` if something tragic happens instead.
[ "Create", "a", "raw", "paste", "of", "the", "given", "content", "." ]
python
train
27.75
srevenant/dictlib
dictlib/__init__.py
https://github.com/srevenant/dictlib/blob/88d743aa897d9c2c6de3c405522f9de3ba2aa869/dictlib/__init__.py#L29-L51
def _splice_index(*key): """ Utility for key management in dig/dug If first elem of key list contains an index[], spread it out as a second numeric index. >>> _splice_index('abc[0]', 'def') ('abc', 0, 'def') >>> _splice_index('abc[a]', 'def') ('abc[a]', 'def') >>> _splice_index('ab...
[ "def", "_splice_index", "(", "*", "key", ")", ":", "if", "isinstance", "(", "key", "[", "0", "]", ",", "str", ")", ":", "result", "=", "rx_index", ".", "search", "(", "key", "[", "0", "]", ")", "if", "result", ":", "return", "tuple", "(", "[", ...
Utility for key management in dig/dug If first elem of key list contains an index[], spread it out as a second numeric index. >>> _splice_index('abc[0]', 'def') ('abc', 0, 'def') >>> _splice_index('abc[a]', 'def') ('abc[a]', 'def') >>> _splice_index('abc[200]', 'def') ('abc', 200, 'def...
[ "Utility", "for", "key", "management", "in", "dig", "/", "dug" ]
python
train
28.26087
DataBiosphere/toil
src/toil/utils/toilStatus.py
https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/utils/toilStatus.py#L159-L186
def getPIDStatus(jobStoreName): """ Determine the status of a process with a particular pid. Checks to see if a process exists or not. :return: A string indicating the status of the PID of the workflow as stored in the jobstore. :rtype: str """ try: ...
[ "def", "getPIDStatus", "(", "jobStoreName", ")", ":", "try", ":", "jobstore", "=", "Toil", ".", "resumeJobStore", "(", "jobStoreName", ")", "except", "NoSuchJobStoreException", ":", "return", "'QUEUED'", "except", "NoSuchFileException", ":", "return", "'QUEUED'", ...
Determine the status of a process with a particular pid. Checks to see if a process exists or not. :return: A string indicating the status of the PID of the workflow as stored in the jobstore. :rtype: str
[ "Determine", "the", "status", "of", "a", "process", "with", "a", "particular", "pid", "." ]
python
train
33.5
brocade/pynos
pynos/device.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/device.py#L369-L394
def find_interface_by_mac(self, **kwargs): """Find the interface through which a MAC can be reached. Args: mac_address (str): A MAC address in 'xx:xx:xx:xx:xx:xx' format. Returns: list[dict]: a list of mac table data. Raises: KeyError: if `mac_addre...
[ "def", "find_interface_by_mac", "(", "self", ",", "*", "*", "kwargs", ")", ":", "mac", "=", "kwargs", ".", "pop", "(", "'mac_address'", ")", "results", "=", "[", "x", "for", "x", "in", "self", ".", "mac_table", "if", "x", "[", "'mac_address'", "]", "...
Find the interface through which a MAC can be reached. Args: mac_address (str): A MAC address in 'xx:xx:xx:xx:xx:xx' format. Returns: list[dict]: a list of mac table data. Raises: KeyError: if `mac_address` is not specified. Examples: >...
[ "Find", "the", "interface", "through", "which", "a", "MAC", "can", "be", "reached", "." ]
python
train
36.653846
Scoppio/RagnarokEngine3
RagnarokEngine3/RE3.py
https://github.com/Scoppio/RagnarokEngine3/blob/4395d419ccd64fe9327c41f200b72ee0176ad896/RagnarokEngine3/RE3.py#L919-L925
def transpose(self): """Create a transpose of this matrix.""" ma4 = Matrix4(self.get_col(0), self.get_col(1), self.get_col(2), self.get_col(3)) return ma4
[ "def", "transpose", "(", "self", ")", ":", "ma4", "=", "Matrix4", "(", "self", ".", "get_col", "(", "0", ")", ",", "self", ".", "get_col", "(", "1", ")", ",", "self", ".", "get_col", "(", "2", ")", ",", "self", ".", "get_col", "(", "3", ")", ...
Create a transpose of this matrix.
[ "Create", "a", "transpose", "of", "this", "matrix", "." ]
python
train
34
bitprophet/ssh
ssh/transport.py
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/transport.py#L1094-L1119
def auth_none(self, username): """ Try to authenticate to the server using no authentication at all. This will almost always fail. It may be useful for determining the list of authentication types supported by the server, by catching the L{BadAuthenticationType} exception raised...
[ "def", "auth_none", "(", "self", ",", "username", ")", ":", "if", "(", "not", "self", ".", "active", ")", "or", "(", "not", "self", ".", "initial_kex_done", ")", ":", "raise", "SSHException", "(", "'No existing session'", ")", "my_event", "=", "threading",...
Try to authenticate to the server using no authentication at all. This will almost always fail. It may be useful for determining the list of authentication types supported by the server, by catching the L{BadAuthenticationType} exception raised. @param username: the username to authent...
[ "Try", "to", "authenticate", "to", "the", "server", "using", "no", "authentication", "at", "all", ".", "This", "will", "almost", "always", "fail", ".", "It", "may", "be", "useful", "for", "determining", "the", "list", "of", "authentication", "types", "suppor...
python
train
41.5
serge-sans-paille/pythran
pythran/analyses/range_values.py
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/range_values.py#L233-L269
def visit_UnaryOp(self, node): """ Update range with given unary operation. >>> import gast as ast >>> from pythran import passmanager, backend >>> node = ast.parse(''' ... def foo(): ... a = 2 ... c = -a ... d = ~a ... f = +a ...
[ "def", "visit_UnaryOp", "(", "self", ",", "node", ")", ":", "res", "=", "self", ".", "visit", "(", "node", ".", "operand", ")", "if", "isinstance", "(", "node", ".", "op", ",", "ast", ".", "Not", ")", ":", "res", "=", "Interval", "(", "0", ",", ...
Update range with given unary operation. >>> import gast as ast >>> from pythran import passmanager, backend >>> node = ast.parse(''' ... def foo(): ... a = 2 ... c = -a ... d = ~a ... f = +a ... e = not a''') >>> pm = ...
[ "Update", "range", "with", "given", "unary", "operation", "." ]
python
train
31.351351
chrisjsewell/jsonextended
jsonextended/units/core.py
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/units/core.py#L126-L173
def split_quantities(data, units='units', magnitude='magnitude', list_of_dicts=False): """ split pint.Quantity objects into <unit,magnitude> pairs Parameters ---------- data : dict units : str name for units key magnitude : str name for magnitude key lis...
[ "def", "split_quantities", "(", "data", ",", "units", "=", "'units'", ",", "magnitude", "=", "'magnitude'", ",", "list_of_dicts", "=", "False", ")", ":", "try", ":", "from", "pint", ".", "quantity", "import", "_Quantity", "except", "ImportError", ":", "raise...
split pint.Quantity objects into <unit,magnitude> pairs Parameters ---------- data : dict units : str name for units key magnitude : str name for magnitude key list_of_dicts: bool treat list of dicts as additional branches Examples -------- >>> from pprint i...
[ "split", "pint", ".", "Quantity", "objects", "into", "<unit", "magnitude", ">", "pairs" ]
python
train
34
sripathikrishnan/redis-rdb-tools
rdbtools/parser.py
https://github.com/sripathikrishnan/redis-rdb-tools/blob/543a73e84702e911ddcd31325ecfde77d7fd230b/rdbtools/parser.py#L941-L953
def _decode_module_id(self, module_id): """ decode module id to string based on @antirez moduleTypeNameByID function from redis/src/module.c :param module_id: 64bit integer :return: string """ name = [''] * 9 module_id >>= 10 for i in reversed(rang...
[ "def", "_decode_module_id", "(", "self", ",", "module_id", ")", ":", "name", "=", "[", "''", "]", "*", "9", "module_id", ">>=", "10", "for", "i", "in", "reversed", "(", "range", "(", "9", ")", ")", ":", "name", "[", "i", "]", "=", "self", ".", ...
decode module id to string based on @antirez moduleTypeNameByID function from redis/src/module.c :param module_id: 64bit integer :return: string
[ "decode", "module", "id", "to", "string", "based", "on" ]
python
train
32.461538
pyqt/python-qt5
PyQt5/uic/uiparser.py
https://github.com/pyqt/python-qt5/blob/c9ed180c56f6fd3521ffe5fb70904bc5d3f50e5f/PyQt5/uic/uiparser.py#L626-L633
def any_i18n(*args): """ Return True if any argument appears to be an i18n string. """ for a in args: if a is not None and not isinstance(a, str): return True return False
[ "def", "any_i18n", "(", "*", "args", ")", ":", "for", "a", "in", "args", ":", "if", "a", "is", "not", "None", "and", "not", "isinstance", "(", "a", ",", "str", ")", ":", "return", "True", "return", "False" ]
Return True if any argument appears to be an i18n string.
[ "Return", "True", "if", "any", "argument", "appears", "to", "be", "an", "i18n", "string", "." ]
python
train
27.25
openstack/networking-cisco
networking_cisco/plugins/cisco/l3/rpc/l3_router_rpc_cfg_agent_api.py
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/l3/rpc/l3_router_rpc_cfg_agent_api.py#L110-L119
def routers_updated(self, context, routers, operation=None, data=None, shuffle_agents=False): """Notify cfg agents about configuration changes to routers. This includes operations performed on the router like when a router interface is added or removed. """ ...
[ "def", "routers_updated", "(", "self", ",", "context", ",", "routers", ",", "operation", "=", "None", ",", "data", "=", "None", ",", "shuffle_agents", "=", "False", ")", ":", "if", "routers", ":", "self", ".", "_notification", "(", "context", ",", "'rout...
Notify cfg agents about configuration changes to routers. This includes operations performed on the router like when a router interface is added or removed.
[ "Notify", "cfg", "agents", "about", "configuration", "changes", "to", "routers", "." ]
python
train
45.1
holgern/pyedflib
pyedflib/edfreader.py
https://github.com/holgern/pyedflib/blob/0f787fc1202b84a6f30d098296acf72666eaeeb4/pyedflib/edfreader.py#L536-L564
def getDigitalMaximum(self, chn=None): """ Returns the maximum digital value of signal edfsignal. Parameters ---------- chn : int channel number Examples -------- >>> import pyedflib >>> f = pyedflib.data.test_generator() >>> ...
[ "def", "getDigitalMaximum", "(", "self", ",", "chn", "=", "None", ")", ":", "if", "chn", "is", "not", "None", ":", "if", "0", "<=", "chn", "<", "self", ".", "signals_in_file", ":", "return", "self", ".", "digital_max", "(", "chn", ")", "else", ":", ...
Returns the maximum digital value of signal edfsignal. Parameters ---------- chn : int channel number Examples -------- >>> import pyedflib >>> f = pyedflib.data.test_generator() >>> f.getDigitalMaximum(0) 32767 >>> f._close()...
[ "Returns", "the", "maximum", "digital", "value", "of", "signal", "edfsignal", "." ]
python
train
25.517241
adamchainz/django-mysql
django_mysql/cache.py
https://github.com/adamchainz/django-mysql/blob/967daa4245cf55c9bc5dc018e560f417c528916a/django_mysql/cache.py#L414-L430
def encode(self, obj): """ Take a Python object and return it as a tuple (value, value_type), a blob and a one-char code for what type it is """ if self._is_valid_mysql_bigint(obj): return obj, 'i' value = pickle.dumps(obj, pickle.HIGHEST_PROTOCOL) va...
[ "def", "encode", "(", "self", ",", "obj", ")", ":", "if", "self", ".", "_is_valid_mysql_bigint", "(", "obj", ")", ":", "return", "obj", ",", "'i'", "value", "=", "pickle", ".", "dumps", "(", "obj", ",", "pickle", ".", "HIGHEST_PROTOCOL", ")", "value_ty...
Take a Python object and return it as a tuple (value, value_type), a blob and a one-char code for what type it is
[ "Take", "a", "Python", "object", "and", "return", "it", "as", "a", "tuple", "(", "value", "value_type", ")", "a", "blob", "and", "a", "one", "-", "char", "code", "for", "what", "type", "it", "is" ]
python
train
33
SmokinCaterpillar/pypet
pypet/storageservice.py
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/storageservice.py#L965-L1337
def store(self, msg, stuff_to_store, *args, **kwargs): """ Stores a particular item to disk. The storage service always accepts these parameters: :param trajectory_name: Name or current trajectory and name of top node in hdf5 file :param filename: Name of the hdf5 file :param...
[ "def", "store", "(", "self", ",", "msg", ",", "stuff_to_store", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "opened", "=", "True", "try", ":", "opened", "=", "self", ".", "_srvc_opening_routine", "(", "'a'", ",", "msg", ",", "kwargs", ")", ...
Stores a particular item to disk. The storage service always accepts these parameters: :param trajectory_name: Name or current trajectory and name of top node in hdf5 file :param filename: Name of the hdf5 file :param file_title: If file needs to be created, assigns a title to the fi...
[ "Stores", "a", "particular", "item", "to", "disk", "." ]
python
test
36.557641
Esri/ArcREST
src/arcrest/security/security.py
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/security/security.py#L790-L797
def token(self): """ obtains a token from the site """ if self._token is None or \ datetime.datetime.now() >= self._token_expires_on: self._generateForOAuthSecurity(self._client_id, self._secret_id, ...
[ "def", "token", "(", "self", ")", ":", "if", "self", ".", "_token", "is", "None", "or", "datetime", ".", "datetime", ".", "now", "(", ")", ">=", "self", ".", "_token_expires_on", ":", "self", ".", "_generateForOAuthSecurity", "(", "self", ".", "_client_i...
obtains a token from the site
[ "obtains", "a", "token", "from", "the", "site" ]
python
train
45
night-crawler/django-docker-helpers
django_docker_helpers/utils.py
https://github.com/night-crawler/django-docker-helpers/blob/b64f8009101a8eb61d3841124ba19e3ab881aa2f/django_docker_helpers/utils.py#L396-L404
def is_production(flag_name: str = 'PRODUCTION', strict: bool = False): """ Reads env ``PRODUCTION`` variable as a boolean. :param flag_name: environment variable name :param strict: raise a ``ValueError`` if variable does not look like a normal boolean :return: ``True`` if has truthy ``PRODUCTION`...
[ "def", "is_production", "(", "flag_name", ":", "str", "=", "'PRODUCTION'", ",", "strict", ":", "bool", "=", "False", ")", ":", "return", "env_bool_flag", "(", "flag_name", ",", "strict", "=", "strict", ")" ]
Reads env ``PRODUCTION`` variable as a boolean. :param flag_name: environment variable name :param strict: raise a ``ValueError`` if variable does not look like a normal boolean :return: ``True`` if has truthy ``PRODUCTION`` env, ``False`` otherwise
[ "Reads", "env", "PRODUCTION", "variable", "as", "a", "boolean", "." ]
python
train
44.111111
pymc-devs/pymc
pymc/distributions.py
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L2447-L2462
def rtruncated_normal(mu, tau, a=-np.inf, b=np.inf, size=None): """ Random truncated normal variates. """ sigma = 1. / np.sqrt(tau) na = utils.normcdf((a - mu) / sigma) nb = utils.normcdf((b - mu) / sigma) # Use the inverse CDF generation method. U = np.random.mtrand.uniform(size=size)...
[ "def", "rtruncated_normal", "(", "mu", ",", "tau", ",", "a", "=", "-", "np", ".", "inf", ",", "b", "=", "np", ".", "inf", ",", "size", "=", "None", ")", ":", "sigma", "=", "1.", "/", "np", ".", "sqrt", "(", "tau", ")", "na", "=", "utils", "...
Random truncated normal variates.
[ "Random", "truncated", "normal", "variates", "." ]
python
train
25.25
greenbone/ospd
ospd/misc.py
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L107-L113
def set_progress(self, scan_id, progress): """ Sets scan_id scan's progress. """ if progress > 0 and progress <= 100: self.scans_table[scan_id]['progress'] = progress if progress == 100: self.scans_table[scan_id]['end_time'] = int(time.time())
[ "def", "set_progress", "(", "self", ",", "scan_id", ",", "progress", ")", ":", "if", "progress", ">", "0", "and", "progress", "<=", "100", ":", "self", ".", "scans_table", "[", "scan_id", "]", "[", "'progress'", "]", "=", "progress", "if", "progress", ...
Sets scan_id scan's progress.
[ "Sets", "scan_id", "scan", "s", "progress", "." ]
python
train
40.857143
ev3dev/ev3dev-lang-python
ev3dev2/motor.py
https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/motor.py#L767-L776
def run_to_rel_pos(self, **kwargs): """ Run to a position relative to the current `position` value. The new position will be current `position` + `position_sp`. When the new position is reached, the motor will stop using the action specified by `stop_action`. """ ...
[ "def", "run_to_rel_pos", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for", "key", "in", "kwargs", ":", "setattr", "(", "self", ",", "key", ",", "kwargs", "[", "key", "]", ")", "self", ".", "command", "=", "self", ".", "COMMAND_RUN_TO_REL_POS" ]
Run to a position relative to the current `position` value. The new position will be current `position` + `position_sp`. When the new position is reached, the motor will stop using the action specified by `stop_action`.
[ "Run", "to", "a", "position", "relative", "to", "the", "current", "position", "value", ".", "The", "new", "position", "will", "be", "current", "position", "+", "position_sp", ".", "When", "the", "new", "position", "is", "reached", "the", "motor", "will", "...
python
train
42.4
cloudendpoints/endpoints-management-python
endpoints_management/control/report_request.py
https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/report_request.py#L344-L393
def as_report_request(self, rules, timer=datetime.utcnow): """Makes a `ServicecontrolServicesReportRequest` from this instance Args: rules (:class:`ReportingRules`): determines what labels, metrics and logs to include in the report request. timer: a function that determi...
[ "def", "as_report_request", "(", "self", ",", "rules", ",", "timer", "=", "datetime", ".", "utcnow", ")", ":", "if", "not", "self", ".", "service_name", ":", "raise", "ValueError", "(", "u'the service name must be set'", ")", "op", "=", "super", "(", "Info",...
Makes a `ServicecontrolServicesReportRequest` from this instance Args: rules (:class:`ReportingRules`): determines what labels, metrics and logs to include in the report request. timer: a function that determines the current time Return: a ``ServicecontrolServ...
[ "Makes", "a", "ServicecontrolServicesReportRequest", "from", "this", "instance" ]
python
train
40.38
chrisjsewell/jsonextended
jsonextended/edict.py
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L58-L63
def is_dict_like(obj, attr=('keys', 'items')): """test if object is dict like""" for a in attr: if not hasattr(obj, a): return False return True
[ "def", "is_dict_like", "(", "obj", ",", "attr", "=", "(", "'keys'", ",", "'items'", ")", ")", ":", "for", "a", "in", "attr", ":", "if", "not", "hasattr", "(", "obj", ",", "a", ")", ":", "return", "False", "return", "True" ]
test if object is dict like
[ "test", "if", "object", "is", "dict", "like" ]
python
train
28.5
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/brocade_cee_map.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_cee_map.py#L66-L80
def cee_map_priority_group_table_pfc(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") cee_map = ET.SubElement(config, "cee-map", xmlns="urn:brocade.com:mgmt:brocade-cee-map") name_key = ET.SubElement(cee_map, "name") name_key.text = kwargs.pop('na...
[ "def", "cee_map_priority_group_table_pfc", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "cee_map", "=", "ET", ".", "SubElement", "(", "config", ",", "\"cee-map\"", ",", "xmlns", "=", "\"urn:br...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
45.266667
marcolagi/quantulum
quantulum/parser.py
https://github.com/marcolagi/quantulum/blob/28b697dfa997116c1aa3ef63a3ceb8725bffd24f/quantulum/parser.py#L388-L400
def clean_text(text): """Clean text before parsing.""" # Replace a few nasty unicode characters with their ASCII equivalent maps = {u'×': u'x', u'–': u'-', u'−': '-'} for element in maps: text = text.replace(element, maps[element]) # Replace genitives text = re.sub(r'(?<=\w)\'s\b|(?<=\w...
[ "def", "clean_text", "(", "text", ")", ":", "# Replace a few nasty unicode characters with their ASCII equivalent", "maps", "=", "{", "u'×':", " ", "'x',", " ", "'–': u", "'", "', u", "'", "': '-'", "}", "", "", "for", "element", "in", "maps", ":", "text", "="...
Clean text before parsing.
[ "Clean", "text", "before", "parsing", "." ]
python
train
30.384615
push-things/django-th
th_evernote/my_evernote.py
https://github.com/push-things/django-th/blob/86c999d16bcf30b6224206e5b40824309834ac8c/th_evernote/my_evernote.py#L245-L254
def _content(note, content): """ content of the note :param note: note object :param content: content string to make the main body of the note :return: """ note.content = EvernoteMgr.set_header() note.content += sanitize(content) return note
[ "def", "_content", "(", "note", ",", "content", ")", ":", "note", ".", "content", "=", "EvernoteMgr", ".", "set_header", "(", ")", "note", ".", "content", "+=", "sanitize", "(", "content", ")", "return", "note" ]
content of the note :param note: note object :param content: content string to make the main body of the note :return:
[ "content", "of", "the", "note", ":", "param", "note", ":", "note", "object", ":", "param", "content", ":", "content", "string", "to", "make", "the", "main", "body", "of", "the", "note", ":", "return", ":" ]
python
train
30.4
CityOfZion/neo-python
neo/Core/BlockBase.py
https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/BlockBase.py#L130-L143
def DeserializeUnsigned(self, reader): """ Deserialize unsigned data only. Args: reader (neo.IO.BinaryReader): """ self.Version = reader.ReadUInt32() self.PrevHash = reader.ReadUInt256() self.MerkleRoot = reader.ReadUInt256() self.Timestamp = ...
[ "def", "DeserializeUnsigned", "(", "self", ",", "reader", ")", ":", "self", ".", "Version", "=", "reader", ".", "ReadUInt32", "(", ")", "self", ".", "PrevHash", "=", "reader", ".", "ReadUInt256", "(", ")", "self", ".", "MerkleRoot", "=", "reader", ".", ...
Deserialize unsigned data only. Args: reader (neo.IO.BinaryReader):
[ "Deserialize", "unsigned", "data", "only", "." ]
python
train
33.285714
getfleety/coralillo
coralillo/datamodel.py
https://github.com/getfleety/coralillo/blob/9cac101738a0fa7c1106f129604c00ef703370e1/coralillo/datamodel.py#L39-L60
def distance(self, loc): """ Calculate the great circle distance between two points on the earth (specified in decimal degrees) """ assert type(loc) == type(self) # convert decimal degrees to radians lon1, lat1, lon2, lat2 = map(radians, [ self.lon, ...
[ "def", "distance", "(", "self", ",", "loc", ")", ":", "assert", "type", "(", "loc", ")", "==", "type", "(", "self", ")", "# convert decimal degrees to radians", "lon1", ",", "lat1", ",", "lon2", ",", "lat2", "=", "map", "(", "radians", ",", "[", "self"...
Calculate the great circle distance between two points on the earth (specified in decimal degrees)
[ "Calculate", "the", "great", "circle", "distance", "between", "two", "points", "on", "the", "earth", "(", "specified", "in", "decimal", "degrees", ")" ]
python
train
28.318182
saltstack/salt
salt/modules/elasticsearch.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L1015-L1037
def repository_create(name, body, hosts=None, profile=None): ''' .. versionadded:: 2017.7.0 Create repository for storing snapshots. Note that shared repository paths have to be specified in path.repo Elasticsearch configuration option. name Repository name body Repository definiti...
[ "def", "repository_create", "(", "name", ",", "body", ",", "hosts", "=", "None", ",", "profile", "=", "None", ")", ":", "es", "=", "_get_instance", "(", "hosts", ",", "profile", ")", "try", ":", "result", "=", "es", ".", "snapshot", ".", "create_reposi...
.. versionadded:: 2017.7.0 Create repository for storing snapshots. Note that shared repository paths have to be specified in path.repo Elasticsearch configuration option. name Repository name body Repository definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/...
[ "..", "versionadded", "::", "2017", ".", "7", ".", "0" ]
python
train
40
EpistasisLab/scikit-mdr
mdr/utils/utils.py
https://github.com/EpistasisLab/scikit-mdr/blob/768565deb10467d04a960d27e000ab38b7aa8a62/mdr/utils/utils.py#L245-L268
def mdr_mutual_information(X, Y, labels, base=2): """Calculates the MDR mutual information, I(XY;labels), in the given base MDR mutual information is calculated by combining variables X and Y into a single MDR model then calculating the mutual information between the resulting model's predictions and the l...
[ "def", "mdr_mutual_information", "(", "X", ",", "Y", ",", "labels", ",", "base", "=", "2", ")", ":", "return", "mutual_information", "(", "_mdr_predict", "(", "X", ",", "Y", ",", "labels", ")", ",", "labels", ",", "base", "=", "base", ")" ]
Calculates the MDR mutual information, I(XY;labels), in the given base MDR mutual information is calculated by combining variables X and Y into a single MDR model then calculating the mutual information between the resulting model's predictions and the labels. Parameters ---------- X: array-like (...
[ "Calculates", "the", "MDR", "mutual", "information", "I", "(", "XY", ";", "labels", ")", "in", "the", "given", "base" ]
python
test
41.125
cqparts/cqparts
src/cqparts/utils/wrappers.py
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/utils/wrappers.py#L2-L42
def as_part(func): """ Converts a function to a :class:`Part <cqparts.Part>` instance. So the conventionally defined *part*:: import cadquery from cqparts import Part from cqparts.params import Float class Box(Part): x = Float(1) y = Float(2) ...
[ "def", "as_part", "(", "func", ")", ":", "from", ".", ".", "import", "Part", "def", "inner", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "part_class", "=", "type", "(", "func", ".", "__name__", ",", "(", "Part", ",", ")", ",", "{", "'m...
Converts a function to a :class:`Part <cqparts.Part>` instance. So the conventionally defined *part*:: import cadquery from cqparts import Part from cqparts.params import Float class Box(Part): x = Float(1) y = Float(2) z = Float(4) ...
[ "Converts", "a", "function", "to", "a", ":", "class", ":", "Part", "<cqparts", ".", "Part", ">", "instance", "." ]
python
train
25.146341
apache/incubator-mxnet
example/profiler/profiler_ndarray.py
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/profiler/profiler_ndarray.py#L51-L77
def check_with_uniform(uf, arg_shapes, dim=None, npuf=None, rmin=-10, type_list=[np.float32]): """check function consistency with uniform random numbers""" if isinstance(arg_shapes, int): assert dim shape = tuple(np.random.randint(1, int(1000**(1.0/dim)), size=dim)) arg_shapes = [shape] ...
[ "def", "check_with_uniform", "(", "uf", ",", "arg_shapes", ",", "dim", "=", "None", ",", "npuf", "=", "None", ",", "rmin", "=", "-", "10", ",", "type_list", "=", "[", "np", ".", "float32", "]", ")", ":", "if", "isinstance", "(", "arg_shapes", ",", ...
check function consistency with uniform random numbers
[ "check", "function", "consistency", "with", "uniform", "random", "numbers" ]
python
train
37.777778
bitesofcode/projexui
projexui/widgets/xserialedit.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xserialedit.py#L82-L90
def cut(self): """ Cuts the text from the serial to the clipboard. """ text = self.selectedText() for editor in self.editors(): editor.cut() QtGui.QApplication.clipboard().setText(text)
[ "def", "cut", "(", "self", ")", ":", "text", "=", "self", ".", "selectedText", "(", ")", "for", "editor", "in", "self", ".", "editors", "(", ")", ":", "editor", ".", "cut", "(", ")", "QtGui", ".", "QApplication", ".", "clipboard", "(", ")", ".", ...
Cuts the text from the serial to the clipboard.
[ "Cuts", "the", "text", "from", "the", "serial", "to", "the", "clipboard", "." ]
python
train
28.222222
vertexproject/synapse
synapse/lib/layer.py
https://github.com/vertexproject/synapse/blob/22e67c5a8f6d7caddbcf34b39ab1bd2d6c4a6e0b/synapse/lib/layer.py#L148-L162
async def getLiftRows(self, lops): ''' Returns: Iterable[Tuple[bytes, Dict[str, Any]]]: yield a stream of tuple (buid, propdict) ''' for oper in lops: func = self._lift_funcs.get(oper[0]) if func is None: raise s_exc.NoSuchLift(name=o...
[ "async", "def", "getLiftRows", "(", "self", ",", "lops", ")", ":", "for", "oper", "in", "lops", ":", "func", "=", "self", ".", "_lift_funcs", ".", "get", "(", "oper", "[", "0", "]", ")", "if", "func", "is", "None", ":", "raise", "s_exc", ".", "No...
Returns: Iterable[Tuple[bytes, Dict[str, Any]]]: yield a stream of tuple (buid, propdict)
[ "Returns", ":", "Iterable", "[", "Tuple", "[", "bytes", "Dict", "[", "str", "Any", "]]]", ":", "yield", "a", "stream", "of", "tuple", "(", "buid", "propdict", ")" ]
python
train
31.666667
davidmogar/cucco
cucco/batch.py
https://github.com/davidmogar/cucco/blob/e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4/cucco/batch.py#L11-L35
def files_generator(path, recursive): """Yield files found in a given path. Walk over a given path finding and yielding all files found on it. This can be done only on the root directory or recursively. Args: path: Path to the directory. recursive: Whether to find files recursively...
[ "def", "files_generator", "(", "path", ",", "recursive", ")", ":", "if", "recursive", ":", "for", "(", "path", ",", "_", ",", "files", ")", "in", "os", ".", "walk", "(", "path", ")", ":", "for", "file", "in", "files", ":", "if", "not", "file", "....
Yield files found in a given path. Walk over a given path finding and yielding all files found on it. This can be done only on the root directory or recursively. Args: path: Path to the directory. recursive: Whether to find files recursively or not. Yields: A tuple for eac...
[ "Yield", "files", "found", "in", "a", "given", "path", "." ]
python
train
32.72
cos-archives/modular-odm
modularodm/fields/field.py
https://github.com/cos-archives/modular-odm/blob/8a34891892b8af69b21fdc46701c91763a5c1cf9/modularodm/fields/field.py#L218-L223
def _get_underlying_data(self, instance): """Return data from raw data store, rather than overridden __get__ methods. Should NOT be overwritten. """ self._touch(instance) return self.data.get(instance, None)
[ "def", "_get_underlying_data", "(", "self", ",", "instance", ")", ":", "self", ".", "_touch", "(", "instance", ")", "return", "self", ".", "data", ".", "get", "(", "instance", ",", "None", ")" ]
Return data from raw data store, rather than overridden __get__ methods. Should NOT be overwritten.
[ "Return", "data", "from", "raw", "data", "store", "rather", "than", "overridden", "__get__", "methods", ".", "Should", "NOT", "be", "overwritten", "." ]
python
valid
40.333333
all-umass/graphs
graphs/mixins/embed.py
https://github.com/all-umass/graphs/blob/4fbeb025dfe33340335f34300f58dd3809228822/graphs/mixins/embed.py#L45-L55
def locally_linear_embedding(self, num_dims=None): '''Locally Linear Embedding (LLE). Note: may need to call barycenter_edge_weights() before this! ''' W = self.matrix() # compute M = (I-W)'(I-W) M = W.T.dot(W) - W.T - W if issparse(M): M = M.toarray() M.flat[::M.shape[0] + 1] += 1...
[ "def", "locally_linear_embedding", "(", "self", ",", "num_dims", "=", "None", ")", ":", "W", "=", "self", ".", "matrix", "(", ")", "# compute M = (I-W)'(I-W)", "M", "=", "W", ".", "T", ".", "dot", "(", "W", ")", "-", "W", ".", "T", "-", "W", "if", ...
Locally Linear Embedding (LLE). Note: may need to call barycenter_edge_weights() before this!
[ "Locally", "Linear", "Embedding", "(", "LLE", ")", ".", "Note", ":", "may", "need", "to", "call", "barycenter_edge_weights", "()", "before", "this!" ]
python
train
33.727273
softlayer/softlayer-python
SoftLayer/CLI/firewall/detail.py
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/firewall/detail.py#L16-L27
def cli(env, identifier): """Detail firewall.""" mgr = SoftLayer.FirewallManager(env.client) firewall_type, firewall_id = firewall.parse_id(identifier) if firewall_type == 'vlan': rules = mgr.get_dedicated_fwl_rules(firewall_id) else: rules = mgr.get_standard_fwl_rules(firewall_id)...
[ "def", "cli", "(", "env", ",", "identifier", ")", ":", "mgr", "=", "SoftLayer", ".", "FirewallManager", "(", "env", ".", "client", ")", "firewall_type", ",", "firewall_id", "=", "firewall", ".", "parse_id", "(", "identifier", ")", "if", "firewall_type", "=...
Detail firewall.
[ "Detail", "firewall", "." ]
python
train
28.916667
tslight/treepick
treepick/actions.py
https://github.com/tslight/treepick/blob/7adf838900f11e8845e17d8c79bb2b23617aec2c/treepick/actions.py#L92-L115
def prevparent(self, parent, depth): ''' Subtract lines from our curline if the name of a node is prefixed with the parent directory when traversing the grandparent object. ''' pdir = os.path.dirname(self.name) if depth > 1: # can't jump to parent of root node! ...
[ "def", "prevparent", "(", "self", ",", "parent", ",", "depth", ")", ":", "pdir", "=", "os", ".", "path", ".", "dirname", "(", "self", ".", "name", ")", "if", "depth", ">", "1", ":", "# can't jump to parent of root node!", "for", "c", ",", "d", "in", ...
Subtract lines from our curline if the name of a node is prefixed with the parent directory when traversing the grandparent object.
[ "Subtract", "lines", "from", "our", "curline", "if", "the", "name", "of", "a", "node", "is", "prefixed", "with", "the", "parent", "directory", "when", "traversing", "the", "grandparent", "object", "." ]
python
train
40.625
OpenGov/carpenter
carpenter/blocks/flagable.py
https://github.com/OpenGov/carpenter/blob/0ab3c54c05133b9b0468c63e834a7ce3a6fb575b/carpenter/blocks/flagable.py#L54-L74
def flag_change(self, flags, level, location=None, worksheet=None, message=''): ''' Wraps the pushing of a change flag into the flags dictionary to handle all edge cases/auto-filling. ''' if not isinstance(level, basestring): try: level = self.FLAG_LEV...
[ "def", "flag_change", "(", "self", ",", "flags", ",", "level", ",", "location", "=", "None", ",", "worksheet", "=", "None", ",", "message", "=", "''", ")", ":", "if", "not", "isinstance", "(", "level", ",", "basestring", ")", ":", "try", ":", "level"...
Wraps the pushing of a change flag into the flags dictionary to handle all edge cases/auto-filling.
[ "Wraps", "the", "pushing", "of", "a", "change", "flag", "into", "the", "flags", "dictionary", "to", "handle", "all", "edge", "cases", "/", "auto", "-", "filling", "." ]
python
train
32.190476
google/mobly
mobly/logger.py
https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/logger.py#L59-L76
def logline_timestamp_comparator(t1, t2): """Comparator for timestamps in logline format. Args: t1: Timestamp in logline format. t2: Timestamp in logline format. Returns: -1 if t1 < t2; 1 if t1 > t2; 0 if t1 == t2. """ dt1 = _parse_logline_timestamp(t1) dt2 = _parse_log...
[ "def", "logline_timestamp_comparator", "(", "t1", ",", "t2", ")", ":", "dt1", "=", "_parse_logline_timestamp", "(", "t1", ")", "dt2", "=", "_parse_logline_timestamp", "(", "t2", ")", "for", "u1", ",", "u2", "in", "zip", "(", "dt1", ",", "dt2", ")", ":", ...
Comparator for timestamps in logline format. Args: t1: Timestamp in logline format. t2: Timestamp in logline format. Returns: -1 if t1 < t2; 1 if t1 > t2; 0 if t1 == t2.
[ "Comparator", "for", "timestamps", "in", "logline", "format", "." ]
python
train
25.111111
orbingol/NURBS-Python
geomdl/visualization/vtk_helpers.py
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/visualization/vtk_helpers.py#L241-L286
def create_actor_tri(pts, tris, color, **kwargs): """ Creates a VTK actor for rendering triangulated surface plots. :param pts: points :type pts: vtkFloatArray :param tris: list of triangle indices :type tris: ndarray :param color: actor color :type color: list :return: a VTK actor ...
[ "def", "create_actor_tri", "(", "pts", ",", "tris", ",", "color", ",", "*", "*", "kwargs", ")", ":", "# Keyword arguments", "array_name", "=", "kwargs", ".", "get", "(", "'name'", ",", "\"\"", ")", "array_index", "=", "kwargs", ".", "get", "(", "'index'"...
Creates a VTK actor for rendering triangulated surface plots. :param pts: points :type pts: vtkFloatArray :param tris: list of triangle indices :type tris: ndarray :param color: actor color :type color: list :return: a VTK actor :rtype: vtkActor
[ "Creates", "a", "VTK", "actor", "for", "rendering", "triangulated", "surface", "plots", "." ]
python
train
26.978261
brookemosby/titanic
TitanicAttempt/TitanicAttempt.py
https://github.com/brookemosby/titanic/blob/e0eb3537a83c7b9d0b7a01db5f23785ffc6f8f70/TitanicAttempt/TitanicAttempt.py#L70-L89
def Produce_Predictions(FileName,train,test): """ Produces predictions for testing set, based off of training set. :param FileName: This is the csv file name we wish to have our predictions exported to. :param train: This is the file name of a csv file that will be the training set. :param test...
[ "def", "Produce_Predictions", "(", "FileName", ",", "train", ",", "test", ")", ":", "TestFileName", "=", "test", "TrainFileName", "=", "train", "trainDF", "=", "pd", ".", "read_csv", "(", "train", ")", "train", "=", "Feature_Engineering", "(", "train", ",", ...
Produces predictions for testing set, based off of training set. :param FileName: This is the csv file name we wish to have our predictions exported to. :param train: This is the file name of a csv file that will be the training set. :param test: This is the file name of the testing set that prediction...
[ "Produces", "predictions", "for", "testing", "set", "based", "off", "of", "training", "set", ".", ":", "param", "FileName", ":", "This", "is", "the", "csv", "file", "name", "we", "wish", "to", "have", "our", "predictions", "exported", "to", ".", ":", "pa...
python
train
47.45
push-things/django-th
th_pocket/my_pocket.py
https://github.com/push-things/django-th/blob/86c999d16bcf30b6224206e5b40824309834ac8c/th_pocket/my_pocket.py#L152-L167
def auth(self, request): """ let's auth the user to the Service :param request: request object :return: callback url :rtype: string that contains the url to redirect after auth """ callback_url = self.callback_url(request) request_token = ...
[ "def", "auth", "(", "self", ",", "request", ")", ":", "callback_url", "=", "self", ".", "callback_url", "(", "request", ")", "request_token", "=", "Pocket", ".", "get_request_token", "(", "consumer_key", "=", "self", ".", "consumer_key", ",", "redirect_uri", ...
let's auth the user to the Service :param request: request object :return: callback url :rtype: string that contains the url to redirect after auth
[ "let", "s", "auth", "the", "user", "to", "the", "Service", ":", "param", "request", ":", "request", "object", ":", "return", ":", "callback", "url", ":", "rtype", ":", "string", "that", "contains", "the", "url", "to", "redirect", "after", "auth" ]
python
train
41.75
Hrabal/TemPy
tempy/tempyrepr.py
https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/tempyrepr.py#L23-L42
def _evaluate_tempyREPR(self, child, repr_cls): """Assign a score ito a TempyRepr class. The scores depends on the current scope and position of the object in which the TempyREPR is found.""" score = 0 if repr_cls.__name__ == self.__class__.__name__: # One point if the REPR h...
[ "def", "_evaluate_tempyREPR", "(", "self", ",", "child", ",", "repr_cls", ")", ":", "score", "=", "0", "if", "repr_cls", ".", "__name__", "==", "self", ".", "__class__", ".", "__name__", ":", "# One point if the REPR have the same name of the container", "score", ...
Assign a score ito a TempyRepr class. The scores depends on the current scope and position of the object in which the TempyREPR is found.
[ "Assign", "a", "score", "ito", "a", "TempyRepr", "class", ".", "The", "scores", "depends", "on", "the", "current", "scope", "and", "position", "of", "the", "object", "in", "which", "the", "TempyREPR", "is", "found", "." ]
python
train
47.7
gabstopper/smc-python
smc/base/collection.py
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/base/collection.py#L524-L539
def batch(self, num): """ Iterator returning results in batches. When making more general queries that might have larger results, specify a batch result that should be returned with each iteration. :param int num: number of results per iteration :return: iterator...
[ "def", "batch", "(", "self", ",", "num", ")", ":", "self", ".", "_params", ".", "pop", "(", "'limit'", ",", "None", ")", "# Limit and batch are mutually exclusive", "it", "=", "iter", "(", "self", ")", "while", "True", ":", "chunk", "=", "list", "(", "...
Iterator returning results in batches. When making more general queries that might have larger results, specify a batch result that should be returned with each iteration. :param int num: number of results per iteration :return: iterator holding list of results
[ "Iterator", "returning", "results", "in", "batches", ".", "When", "making", "more", "general", "queries", "that", "might", "have", "larger", "results", "specify", "a", "batch", "result", "that", "should", "be", "returned", "with", "each", "iteration", ".", ":"...
python
train
36.3125
rshk/python-libxdo
xdo/__init__.py
https://github.com/rshk/python-libxdo/blob/84cafa5943b005bc423edd28203a5266b3579ac3/xdo/__init__.py#L43-L53
def _gen_input_mask(mask): """Generate input mask from bytemask""" return input_mask( shift=bool(mask & MOD_Shift), lock=bool(mask & MOD_Lock), control=bool(mask & MOD_Control), mod1=bool(mask & MOD_Mod1), mod2=bool(mask & MOD_Mod2), mod3=bool(mask & MOD_Mod3), ...
[ "def", "_gen_input_mask", "(", "mask", ")", ":", "return", "input_mask", "(", "shift", "=", "bool", "(", "mask", "&", "MOD_Shift", ")", ",", "lock", "=", "bool", "(", "mask", "&", "MOD_Lock", ")", ",", "control", "=", "bool", "(", "mask", "&", "MOD_C...
Generate input mask from bytemask
[ "Generate", "input", "mask", "from", "bytemask" ]
python
train
34.454545
alimanfoo/csvvalidator
csvvalidator.py
https://github.com/alimanfoo/csvvalidator/blob/50a86eefdc549c48f65a91a5c0a66099010ee65d/csvvalidator.py#L575-L588
def _apply_record_length_checks(self, i, r, summarize=False, context=None): """Apply record length checks on the given record `r`.""" for code, message, modulus in self._record_length_checks: if i % modulus == 0: # support sampling if len(r) != len(self._field_names): ...
[ "def", "_apply_record_length_checks", "(", "self", ",", "i", ",", "r", ",", "summarize", "=", "False", ",", "context", "=", "None", ")", ":", "for", "code", ",", "message", ",", "modulus", "in", "self", ".", "_record_length_checks", ":", "if", "i", "%", ...
Apply record length checks on the given record `r`.
[ "Apply", "record", "length", "checks", "on", "the", "given", "record", "r", "." ]
python
valid
46.357143
merll/docker-fabric
dockerfabric/utils/files.py
https://github.com/merll/docker-fabric/blob/785d84e40e17265b667d8b11a6e30d8e6b2bf8d4/dockerfabric/utils/files.py#L67-L94
def temp_dir(apply_chown=None, apply_chmod=None, remove_using_sudo=None, remove_force=False): """ Creates a temporary directory on the remote machine. The directory is removed when no longer needed. Failure to do so will be ignored. :param apply_chown: Optional; change the owner of the directory. :...
[ "def", "temp_dir", "(", "apply_chown", "=", "None", ",", "apply_chmod", "=", "None", ",", "remove_using_sudo", "=", "None", ",", "remove_force", "=", "False", ")", ":", "path", "=", "get_remote_temp", "(", ")", "try", ":", "if", "apply_chmod", ":", "run", ...
Creates a temporary directory on the remote machine. The directory is removed when no longer needed. Failure to do so will be ignored. :param apply_chown: Optional; change the owner of the directory. :type apply_chown: unicode :param apply_chmod: Optional; change the permissions of the directory. :...
[ "Creates", "a", "temporary", "directory", "on", "the", "remote", "machine", ".", "The", "directory", "is", "removed", "when", "no", "longer", "needed", ".", "Failure", "to", "do", "so", "will", "be", "ignored", "." ]
python
train
40.607143
xolox/python-coloredlogs
scripts/generate-screenshots.py
https://github.com/xolox/python-coloredlogs/blob/1cbf0c6bbee400c6ddbc43008143809934ec3e79/scripts/generate-screenshots.py#L146-L165
def interpret_script(shell_script): """Make it appear as if commands are typed into the terminal.""" with CaptureOutput() as capturer: shell = subprocess.Popen(['bash', '-'], stdin=subprocess.PIPE) with open(shell_script) as handle: for line in handle: sys.stdout.writ...
[ "def", "interpret_script", "(", "shell_script", ")", ":", "with", "CaptureOutput", "(", ")", "as", "capturer", ":", "shell", "=", "subprocess", ".", "Popen", "(", "[", "'bash'", ",", "'-'", "]", ",", "stdin", "=", "subprocess", ".", "PIPE", ")", "with", ...
Make it appear as if commands are typed into the terminal.
[ "Make", "it", "appear", "as", "if", "commands", "are", "typed", "into", "the", "terminal", "." ]
python
train
46.3
PyPSA/PyPSA
pypsa/opf.py
https://github.com/PyPSA/PyPSA/blob/46954b1b3c21460550f7104681517065279a53b7/pypsa/opf.py#L732-L764
def define_sub_network_cycle_constraints( subnetwork, snapshots, passive_branch_p, attribute): """ Constructs cycle_constraints for a particular subnetwork """ sub_network_cycle_constraints = {} sub_network_cycle_index = [] matrix = subnetwork.C.tocsc() branches = subnetwork.branches() fo...
[ "def", "define_sub_network_cycle_constraints", "(", "subnetwork", ",", "snapshots", ",", "passive_branch_p", ",", "attribute", ")", ":", "sub_network_cycle_constraints", "=", "{", "}", "sub_network_cycle_index", "=", "[", "]", "matrix", "=", "subnetwork", ".", "C", ...
Constructs cycle_constraints for a particular subnetwork
[ "Constructs", "cycle_constraints", "for", "a", "particular", "subnetwork" ]
python
train
37.787879
juju/charm-helpers
charmhelpers/contrib/peerstorage/__init__.py
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/peerstorage/__init__.py#L240-L267
def peer_store_and_set(relation_id=None, peer_relation_name='cluster', peer_store_fatal=False, relation_settings=None, delimiter='_', **kwargs): """Store passed-in arguments both in argument relation and in peer storage. It functions like doing relation_set() and p...
[ "def", "peer_store_and_set", "(", "relation_id", "=", "None", ",", "peer_relation_name", "=", "'cluster'", ",", "peer_store_fatal", "=", "False", ",", "relation_settings", "=", "None", ",", "delimiter", "=", "'_'", ",", "*", "*", "kwargs", ")", ":", "relation_...
Store passed-in arguments both in argument relation and in peer storage. It functions like doing relation_set() and peer_store() at the same time, with the same data. @param relation_id: the id of the relation to store the data on. Defaults to the current relation. @param peer_...
[ "Store", "passed", "-", "in", "arguments", "both", "in", "argument", "relation", "and", "in", "peer", "storage", "." ]
python
train
49.321429
zulily/pudl
pudl/ad_user.py
https://github.com/zulily/pudl/blob/761eec76841964780e759e6bf6d5f06a54844a80/pudl/ad_user.py#L133-L155
def group_samaccountnames(self, base_dn): """For the current ADUser instance, determine which groups the user is a member of and convert the group DistinguishedNames to sAMAccountNames. The resulting list of groups may not be complete if explicit_membership_only was set to ...
[ "def", "group_samaccountnames", "(", "self", ",", "base_dn", ")", ":", "#pylint: disable=no-member", "mappings", "=", "self", ".", "samaccountnames", "(", "base_dn", ",", "self", ".", "memberof", ")", "#pylint: enable=no-member", "groups", "=", "[", "samaccountname"...
For the current ADUser instance, determine which groups the user is a member of and convert the group DistinguishedNames to sAMAccountNames. The resulting list of groups may not be complete if explicit_membership_only was set to True when the object factory method (user() or user...
[ "For", "the", "current", "ADUser", "instance", "determine", "which", "groups", "the", "user", "is", "a", "member", "of", "and", "convert", "the", "group", "DistinguishedNames", "to", "sAMAccountNames", ".", "The", "resulting", "list", "of", "groups", "may", "n...
python
train
43.086957
rapidpro/expressions
python/temba_expressions/functions/__init__.py
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/__init__.py#L9-L24
def add_library(self, library): """ Adds functions from a library module :param library: the library module :return: """ for fn in library.__dict__.copy().values(): # ignore imported methods and anything beginning __ if inspect.isfunction(fn) and i...
[ "def", "add_library", "(", "self", ",", "library", ")", ":", "for", "fn", "in", "library", ".", "__dict__", ".", "copy", "(", ")", ".", "values", "(", ")", ":", "# ignore imported methods and anything beginning __", "if", "inspect", ".", "isfunction", "(", "...
Adds functions from a library module :param library: the library module :return:
[ "Adds", "functions", "from", "a", "library", "module", ":", "param", "library", ":", "the", "library", "module", ":", "return", ":" ]
python
train
39
taskcluster/taskcluster-client.py
taskcluster/github.py
https://github.com/taskcluster/taskcluster-client.py/blob/bcc95217f8bf80bed2ae5885a19fa0035da7ebc9/taskcluster/github.py#L70-L80
def badge(self, *args, **kwargs): """ Latest Build Status Badge Checks the status of the latest build of a given branch and returns corresponding badge svg. This method is ``experimental`` """ return self._makeApiCall(self.funcinfo["badge"], *args, **kwargs)
[ "def", "badge", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_makeApiCall", "(", "self", ".", "funcinfo", "[", "\"badge\"", "]", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Latest Build Status Badge Checks the status of the latest build of a given branch and returns corresponding badge svg. This method is ``experimental``
[ "Latest", "Build", "Status", "Badge" ]
python
train
27.909091
CalebBell/fluids
fluids/two_phase.py
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/two_phase.py#L2660-L2708
def two_phase_dP_dz_gravitational(angle, alpha, rhol, rhog, g=g): r'''This function handles calculation of two-phase liquid-gas pressure drop due to gravitation for flow inside channels. This is a differential calculation for a segment with an infinitesimal difference in elevation for use in performing...
[ "def", "two_phase_dP_dz_gravitational", "(", "angle", ",", "alpha", ",", "rhol", ",", "rhog", ",", "g", "=", "g", ")", ":", "angle", "=", "radians", "(", "angle", ")", "return", "g", "*", "sin", "(", "angle", ")", "*", "(", "alpha", "*", "rhog", "+...
r'''This function handles calculation of two-phase liquid-gas pressure drop due to gravitation for flow inside channels. This is a differential calculation for a segment with an infinitesimal difference in elevation for use in performing integration over a pipe as shown in [1]_ and [2]_. .. math::...
[ "r", "This", "function", "handles", "calculation", "of", "two", "-", "phase", "liquid", "-", "gas", "pressure", "drop", "due", "to", "gravitation", "for", "flow", "inside", "channels", ".", "This", "is", "a", "differential", "calculation", "for", "a", "segme...
python
train
34.836735
LogicalDash/LiSE
allegedb/allegedb/wrap.py
https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/wrap.py#L307-L309
def unwrap(self): """Return a deep copy of myself as a list, and unwrap any wrapper objects in me.""" return [v.unwrap() if hasattr(v, 'unwrap') and not hasattr(v, 'no_unwrap') else v for v in self]
[ "def", "unwrap", "(", "self", ")", ":", "return", "[", "v", ".", "unwrap", "(", ")", "if", "hasattr", "(", "v", ",", "'unwrap'", ")", "and", "not", "hasattr", "(", "v", ",", "'no_unwrap'", ")", "else", "v", "for", "v", "in", "self", "]" ]
Return a deep copy of myself as a list, and unwrap any wrapper objects in me.
[ "Return", "a", "deep", "copy", "of", "myself", "as", "a", "list", "and", "unwrap", "any", "wrapper", "objects", "in", "me", "." ]
python
train
70.666667
streamlink/streamlink
src/streamlink/logger.py
https://github.com/streamlink/streamlink/blob/c8ed1daff14ac03195870238b9b900c1109dd5c1/src/streamlink/logger.py#L36-L46
def getMessage(self): """ Return the message for this LogRecord. Return the message for this LogRecord after merging any user-supplied arguments with the message. """ msg = self.msg if self.args: msg = msg.format(*self.args) return maybe_encod...
[ "def", "getMessage", "(", "self", ")", ":", "msg", "=", "self", ".", "msg", "if", "self", ".", "args", ":", "msg", "=", "msg", ".", "format", "(", "*", "self", ".", "args", ")", "return", "maybe_encode", "(", "msg", ")" ]
Return the message for this LogRecord. Return the message for this LogRecord after merging any user-supplied arguments with the message.
[ "Return", "the", "message", "for", "this", "LogRecord", "." ]
python
test
28.727273
log2timeline/dfvfs
dfvfs/encryption/aes_decrypter.py
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/encryption/aes_decrypter.py#L57-L75
def Decrypt(self, encrypted_data): """Decrypts the encrypted data. Args: encrypted_data (bytes): encrypted data. Returns: tuple[bytes, bytes]: decrypted data and remaining encrypted data. """ index_split = -(len(encrypted_data) % AES.block_size) if index_split: remaining_encr...
[ "def", "Decrypt", "(", "self", ",", "encrypted_data", ")", ":", "index_split", "=", "-", "(", "len", "(", "encrypted_data", ")", "%", "AES", ".", "block_size", ")", "if", "index_split", ":", "remaining_encrypted_data", "=", "encrypted_data", "[", "index_split"...
Decrypts the encrypted data. Args: encrypted_data (bytes): encrypted data. Returns: tuple[bytes, bytes]: decrypted data and remaining encrypted data.
[ "Decrypts", "the", "encrypted", "data", "." ]
python
train
29.368421
Capitains/MyCapytain
MyCapytain/resolvers/cts/api.py
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resolvers/cts/api.py#L67-L81
def getSiblings(self, textId, subreference): """ Retrieve the siblings of a textual node :param textId: CtsTextMetadata Identifier :type textId: str :param subreference: CapitainsCtsPassage Reference :type subreference: str :return: Tuple of references :rtype: (s...
[ "def", "getSiblings", "(", "self", ",", "textId", ",", "subreference", ")", ":", "text", "=", "CtsText", "(", "urn", "=", "textId", ",", "retriever", "=", "self", ".", "endpoint", ")", "return", "text", ".", "getPrevNextUrn", "(", "subreference", ")" ]
Retrieve the siblings of a textual node :param textId: CtsTextMetadata Identifier :type textId: str :param subreference: CapitainsCtsPassage Reference :type subreference: str :return: Tuple of references :rtype: (str, str)
[ "Retrieve", "the", "siblings", "of", "a", "textual", "node" ]
python
train
31.266667
blockstack/blockstack-core
blockstack/lib/nameset/db.py
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L2081-L2112
def namedb_get_record_states_at(cur, history_id, block_number): """ Get the state(s) that the given history record was in at a given block height. Normally, this is one state (i.e. if a name was registered at block 8, then it is in a NAME_REGISTRATION state in block 10) However, if the record changed a...
[ "def", "namedb_get_record_states_at", "(", "cur", ",", "history_id", ",", "block_number", ")", ":", "query", "=", "'SELECT block_id,history_data FROM history WHERE history_id = ? AND block_id == ? ORDER BY block_id DESC,vtxindex DESC'", "args", "=", "(", "history_id", ",", "block...
Get the state(s) that the given history record was in at a given block height. Normally, this is one state (i.e. if a name was registered at block 8, then it is in a NAME_REGISTRATION state in block 10) However, if the record changed at this block, then this method returns all states the record passed through....
[ "Get", "the", "state", "(", "s", ")", "that", "the", "given", "history", "record", "was", "in", "at", "a", "given", "block", "height", ".", "Normally", "this", "is", "one", "state", "(", "i", ".", "e", ".", "if", "a", "name", "was", "registered", "...
python
train
41.625
Jajcus/pyxmpp2
pyxmpp2/cert.py
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cert.py#L413-L455
def from_der_data(cls, data): """Decode DER-encoded certificate. :Parameters: - `data`: the encoded certificate :Types: - `data`: `bytes` :Return: decoded certificate data :Returntype: ASN1CertificateData """ # pylint: disable=W0212 ...
[ "def", "from_der_data", "(", "cls", ",", "data", ")", ":", "# pylint: disable=W0212", "logger", ".", "debug", "(", "\"Decoding DER certificate: {0!r}\"", ".", "format", "(", "data", ")", ")", "if", "cls", ".", "_cert_asn1_type", "is", "None", ":", "cls", ".", ...
Decode DER-encoded certificate. :Parameters: - `data`: the encoded certificate :Types: - `data`: `bytes` :Return: decoded certificate data :Returntype: ASN1CertificateData
[ "Decode", "DER", "-", "encoded", "certificate", "." ]
python
valid
44.27907
sqreen/PyMiniRacer
py_mini_racer/extension/v8_build.py
https://github.com/sqreen/PyMiniRacer/blob/86747cddb13895ccaba990704ad68e5e059587f9/py_mini_racer/extension/v8_build.py#L57-L68
def ensure_v8_src(): """ Ensure that v8 src are presents and up-to-date """ path = local_path('v8') if not os.path.isdir(path): fetch_v8(path) else: update_v8(path) checkout_v8_version(local_path("v8/v8"), V8_VERSION) dependencies_sync(path)
[ "def", "ensure_v8_src", "(", ")", ":", "path", "=", "local_path", "(", "'v8'", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "fetch_v8", "(", "path", ")", "else", ":", "update_v8", "(", "path", ")", "checkout_v8_version", ...
Ensure that v8 src are presents and up-to-date
[ "Ensure", "that", "v8", "src", "are", "presents", "and", "up", "-", "to", "-", "date" ]
python
train
23
saltstack/salt
salt/modules/influxdbmod.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/influxdbmod.py#L495-L513
def list_privileges(name, **client_args): ''' List privileges from a user. name Name of the user from whom privileges will be listed. CLI Example: .. code-block:: bash salt '*' influxdb.list_privileges <name> ''' client = _client(**client_args) res = {} for item ...
[ "def", "list_privileges", "(", "name", ",", "*", "*", "client_args", ")", ":", "client", "=", "_client", "(", "*", "*", "client_args", ")", "res", "=", "{", "}", "for", "item", "in", "client", ".", "get_list_privileges", "(", "name", ")", ":", "res", ...
List privileges from a user. name Name of the user from whom privileges will be listed. CLI Example: .. code-block:: bash salt '*' influxdb.list_privileges <name>
[ "List", "privileges", "from", "a", "user", "." ]
python
train
22.210526
bigchaindb/bigchaindb
bigchaindb/elections/election.py
https://github.com/bigchaindb/bigchaindb/blob/835fdfcf598918f76139e3b88ee33dd157acaaa7/bigchaindb/elections/election.py#L194-L215
def has_concluded(self, bigchain, current_votes=[]): """Check if the election can be concluded or not. * Elections can only be concluded if the validator set has not changed since the election was initiated. * Elections can be concluded only if the current votes form a supermajority. ...
[ "def", "has_concluded", "(", "self", ",", "bigchain", ",", "current_votes", "=", "[", "]", ")", ":", "if", "self", ".", "has_validator_set_changed", "(", "bigchain", ")", ":", "return", "False", "election_pk", "=", "self", ".", "to_public_key", "(", "self", ...
Check if the election can be concluded or not. * Elections can only be concluded if the validator set has not changed since the election was initiated. * Elections can be concluded only if the current votes form a supermajority. Custom elections may override this function and introdu...
[ "Check", "if", "the", "election", "can", "be", "concluded", "or", "not", "." ]
python
train
41.409091
bwhite/hadoopy
hadoopy/thirdparty/pyinstaller/PyInstaller/bindepend.py
https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/bindepend.py#L283-L338
def selectAssemblies(pth, manifest=None): """ Return a binary's dependent assemblies files that should be included. Return a list of pairs (name, fullpath) """ rv = [] if not os.path.isfile(pth): pth = check_extract_from_egg(pth)[0][0] if manifest: _depNames = set([dep.name ...
[ "def", "selectAssemblies", "(", "pth", ",", "manifest", "=", "None", ")", ":", "rv", "=", "[", "]", "if", "not", "os", ".", "path", ".", "isfile", "(", "pth", ")", ":", "pth", "=", "check_extract_from_egg", "(", "pth", ")", "[", "0", "]", "[", "0...
Return a binary's dependent assemblies files that should be included. Return a list of pairs (name, fullpath)
[ "Return", "a", "binary", "s", "dependent", "assemblies", "files", "that", "should", "be", "included", "." ]
python
train
42.142857
Hackerfleet/hfos
modules/enrol/hfos/enrol/enrolmanager.py
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/modules/enrol/hfos/enrol/enrolmanager.py#L388-L396
def invite(self, event): """A new user has been invited to enrol by an admin user""" self.log('Inviting new user to enrol') name = event.data['name'] email = event.data['email'] method = event.data['method'] self._invite(name, method, email, event.client.uuid, event)
[ "def", "invite", "(", "self", ",", "event", ")", ":", "self", ".", "log", "(", "'Inviting new user to enrol'", ")", "name", "=", "event", ".", "data", "[", "'name'", "]", "email", "=", "event", ".", "data", "[", "'email'", "]", "method", "=", "event", ...
A new user has been invited to enrol by an admin user
[ "A", "new", "user", "has", "been", "invited", "to", "enrol", "by", "an", "admin", "user" ]
python
train
34.333333
MacHu-GWU/angora-project
angora/bot/macro.py
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/bot/macro.py#L238-L242
def Type_string(self, text, interval = 0, dl = 0): """键盘输入字符串,interval是字符间输入时间间隔,单位"秒" """ self.Delay(dl) self.keyboard.type_string(text, interval)
[ "def", "Type_string", "(", "self", ",", "text", ",", "interval", "=", "0", ",", "dl", "=", "0", ")", ":", "self", ".", "Delay", "(", "dl", ")", "self", ".", "keyboard", ".", "type_string", "(", "text", ",", "interval", ")" ]
键盘输入字符串,interval是字符间输入时间间隔,单位"秒"
[ "键盘输入字符串,interval是字符间输入时间间隔,单位", "秒" ]
python
train
35
dwavesystems/dwave_networkx
dwave_networkx/drawing/pegasus_layout.py
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/drawing/pegasus_layout.py#L107-L184
def pegasus_node_placer_2d(G, scale=1., center=None, dim=2, crosses=False): """Generates a function that converts Pegasus indices to x, y coordinates for a plot. Parameters ---------- G : NetworkX graph Should be a Pegasus graph or a subgraph of a Pegasus graph. This should be the p...
[ "def", "pegasus_node_placer_2d", "(", "G", ",", "scale", "=", "1.", ",", "center", "=", "None", ",", "dim", "=", "2", ",", "crosses", "=", "False", ")", ":", "import", "numpy", "as", "np", "m", "=", "G", ".", "graph", ".", "get", "(", "'rows'", "...
Generates a function that converts Pegasus indices to x, y coordinates for a plot. Parameters ---------- G : NetworkX graph Should be a Pegasus graph or a subgraph of a Pegasus graph. This should be the product of dwave_networkx.pegasus_graph scale : float (default 1.) Scal...
[ "Generates", "a", "function", "that", "converts", "Pegasus", "indices", "to", "x", "y", "coordinates", "for", "a", "plot", "." ]
python
train
29.679487
XuShaohua/bcloud
bcloud/RequestCookie.py
https://github.com/XuShaohua/bcloud/blob/4b54e0fdccf2b3013285fef05c97354cfa31697b/bcloud/RequestCookie.py#L17-L25
def header_output(self): '''只输出cookie的key-value字串. 比如: HISTORY=21341; PHPSESSION=3289012u39jsdijf28; token=233129 ''' result = [] for key in self.keys(): result.append(key + '=' + self.get(key).value) return '; '.join(result)
[ "def", "header_output", "(", "self", ")", ":", "result", "=", "[", "]", "for", "key", "in", "self", ".", "keys", "(", ")", ":", "result", ".", "append", "(", "key", "+", "'='", "+", "self", ".", "get", "(", "key", ")", ".", "value", ")", "retur...
只输出cookie的key-value字串. 比如: HISTORY=21341; PHPSESSION=3289012u39jsdijf28; token=233129
[ "只输出cookie的key", "-", "value字串", ".", "比如", ":", "HISTORY", "=", "21341", ";", "PHPSESSION", "=", "3289012u39jsdijf28", ";", "token", "=", "233129" ]
python
train
31.777778
mcs07/PubChemPy
pubchempy.py
https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L757-L767
def cid(self): """The PubChem Compound Identifier (CID). .. note:: When searching using a SMILES or InChI query that is not present in the PubChem Compound database, an automatically generated record may be returned that contains properties that have been calculated on the ...
[ "def", "cid", "(", "self", ")", ":", "if", "'id'", "in", "self", ".", "record", "and", "'id'", "in", "self", ".", "record", "[", "'id'", "]", "and", "'cid'", "in", "self", ".", "record", "[", "'id'", "]", "[", "'id'", "]", ":", "return", "self", ...
The PubChem Compound Identifier (CID). .. note:: When searching using a SMILES or InChI query that is not present in the PubChem Compound database, an automatically generated record may be returned that contains properties that have been calculated on the fly. These records...
[ "The", "PubChem", "Compound", "Identifier", "(", "CID", ")", "." ]
python
train
47.909091
wright-group/WrightTools
WrightTools/artists/_base.py
https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/artists/_base.py#L385-L422
def pcolormesh(self, *args, **kwargs): """Create a pseudocolor plot of a 2-D array. If a 3D or higher Data object is passed, a lower dimensional channel can be plotted, provided the ``squeeze`` of the channel has ``ndim==2`` and the first two axes do not span dimensions other th...
[ "def", "pcolormesh", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "args", ",", "kwargs", "=", "self", ".", "_parse_plot_args", "(", "*", "args", ",", "*", "*", "kwargs", ",", "plot_type", "=", "\"pcolormesh\"", ")", "return", "su...
Create a pseudocolor plot of a 2-D array. If a 3D or higher Data object is passed, a lower dimensional channel can be plotted, provided the ``squeeze`` of the channel has ``ndim==2`` and the first two axes do not span dimensions other than those spanned by that channel. Uses pc...
[ "Create", "a", "pseudocolor", "plot", "of", "a", "2", "-", "D", "array", "." ]
python
train
40.421053
chrislit/abydos
abydos/phonetic/_statistics_canada.py
https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/phonetic/_statistics_canada.py#L53-L95
def encode(self, word, max_length=4): """Return the Statistics Canada code for a word. Parameters ---------- word : str The word to transform max_length : int The maximum length (default 4) of the code to return Returns ------- st...
[ "def", "encode", "(", "self", ",", "word", ",", "max_length", "=", "4", ")", ":", "# uppercase, normalize, decompose, and filter non-A-Z out", "word", "=", "unicode_normalize", "(", "'NFKD'", ",", "text_type", "(", "word", ".", "upper", "(", ")", ")", ")", "wo...
Return the Statistics Canada code for a word. Parameters ---------- word : str The word to transform max_length : int The maximum length (default 4) of the code to return Returns ------- str The Statistics Canada name code val...
[ "Return", "the", "Statistics", "Canada", "code", "for", "a", "word", "." ]
python
valid
26.488372
JNRowe/jnrbase
jnrbase/context.py
https://github.com/JNRowe/jnrbase/blob/ae505ef69a9feb739b5f4e62c5a8e6533104d3ea/jnrbase/context.py#L27-L41
def chdir(__path: str) -> ContextManager: """Context handler to temporarily switch directories. Args: __path: Directory to change to Yields: Execution context in ``path`` """ old = os.getcwd() try: os.chdir(__path) yield finally: os.chdir(old)
[ "def", "chdir", "(", "__path", ":", "str", ")", "->", "ContextManager", ":", "old", "=", "os", ".", "getcwd", "(", ")", "try", ":", "os", ".", "chdir", "(", "__path", ")", "yield", "finally", ":", "os", ".", "chdir", "(", "old", ")" ]
Context handler to temporarily switch directories. Args: __path: Directory to change to Yields: Execution context in ``path``
[ "Context", "handler", "to", "temporarily", "switch", "directories", "." ]
python
train
19.933333
slackapi/python-slackclient
slack/rtm/client.py
https://github.com/slackapi/python-slackclient/blob/901341c0284fd81e6d2719d6a0502308760d83e4/slack/rtm/client.py#L256-L269
def typing(self, *, channel: str): """Sends a typing indicator to the specified channel. This indicates that this app is currently writing a message to send to a channel. Args: channel (str): The channel id. e.g. 'C024BE91L' Raises: SlackClientNotConnec...
[ "def", "typing", "(", "self", ",", "*", ",", "channel", ":", "str", ")", ":", "payload", "=", "{", "\"id\"", ":", "self", ".", "_next_msg_id", "(", ")", ",", "\"type\"", ":", "\"typing\"", ",", "\"channel\"", ":", "channel", "}", "self", ".", "send_o...
Sends a typing indicator to the specified channel. This indicates that this app is currently writing a message to send to a channel. Args: channel (str): The channel id. e.g. 'C024BE91L' Raises: SlackClientNotConnectedError: Websocket connection is closed.
[ "Sends", "a", "typing", "indicator", "to", "the", "specified", "channel", "." ]
python
train
35.285714
clinicedc/edc-model-fields
edc_model_fields/fields/hostname_modification_field.py
https://github.com/clinicedc/edc-model-fields/blob/fac30a71163760edd57329f26b48095eb0a0dd5b/edc_model_fields/fields/hostname_modification_field.py#L15-L19
def pre_save(self, model_instance, add): """Updates socket.gethostname() on each save.""" value = socket.gethostname() setattr(model_instance, self.attname, value) return value
[ "def", "pre_save", "(", "self", ",", "model_instance", ",", "add", ")", ":", "value", "=", "socket", ".", "gethostname", "(", ")", "setattr", "(", "model_instance", ",", "self", ".", "attname", ",", "value", ")", "return", "value" ]
Updates socket.gethostname() on each save.
[ "Updates", "socket", ".", "gethostname", "()", "on", "each", "save", "." ]
python
train
40.8
mwgielen/jackal
jackal/scripts/eternalblue.py
https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/eternalblue.py#L189-L200
def exploit_single(self, ip, operating_system): """ Exploits a single ip, exploit is based on the given operating system. """ result = None if "Windows Server 2008" in operating_system or "Windows 7" in operating_system: result = subprocess.run(['python2', os.path...
[ "def", "exploit_single", "(", "self", ",", "ip", ",", "operating_system", ")", ":", "result", "=", "None", "if", "\"Windows Server 2008\"", "in", "operating_system", "or", "\"Windows 7\"", "in", "operating_system", ":", "result", "=", "subprocess", ".", "run", "...
Exploits a single ip, exploit is based on the given operating system.
[ "Exploits", "a", "single", "ip", "exploit", "is", "based", "on", "the", "given", "operating", "system", "." ]
python
valid
82.166667
msmbuilder/msmbuilder
msmbuilder/cluster/base.py
https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/cluster/base.py#L116-L135
def partial_predict(self, X, y=None): """Predict the closest cluster each sample in X belongs to. In the vector quantization literature, `cluster_centers_` is called the code book and each value returned by `predict` is the index of the closest code in the code book. Parameters...
[ "def", "partial_predict", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "if", "isinstance", "(", "X", ",", "md", ".", "Trajectory", ")", ":", "X", ".", "center_coordinates", "(", ")", "return", "super", "(", "MultiSequenceClusterMixin", ",", ...
Predict the closest cluster each sample in X belongs to. In the vector quantization literature, `cluster_centers_` is called the code book and each value returned by `predict` is the index of the closest code in the code book. Parameters ---------- X : array-like shape=...
[ "Predict", "the", "closest", "cluster", "each", "sample", "in", "X", "belongs", "to", "." ]
python
train
34.55
qiniu/python-sdk
qiniu/services/compute/qcos_api.py
https://github.com/qiniu/python-sdk/blob/a69fbef4e3e6ea1ebe09f4610a5b18bb2c17de59/qiniu/services/compute/qcos_api.py#L210-L225
def get_service_inspect(self, stack, service): """查看服务 查看指定名称服务的属性。 Args: - stack: 服务所属的服务组名称 - service: 服务名 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回服务信息,失败返回{"error": "<errMsg string>"} ...
[ "def", "get_service_inspect", "(", "self", ",", "stack", ",", "service", ")", ":", "url", "=", "'{0}/v3/stacks/{1}/services/{2}/inspect'", ".", "format", "(", "self", ".", "host", ",", "stack", ",", "service", ")", "return", "self", ".", "__get", "(", "url",...
查看服务 查看指定名称服务的属性。 Args: - stack: 服务所属的服务组名称 - service: 服务名 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回服务信息,失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息
[ "查看服务" ]
python
train
29.25
troeger/opensubmit
web/opensubmit/models/submission.py
https://github.com/troeger/opensubmit/blob/384a95b7c6fa41e3f949a129d25dafd9a1c54859/web/opensubmit/models/submission.py#L332-L343
def grading_means_passed(self): ''' Information if the given grading means passed. Non-graded assignments are always passed. ''' if self.assignment.is_graded(): if self.grading and self.grading.means_passed: return True else: ...
[ "def", "grading_means_passed", "(", "self", ")", ":", "if", "self", ".", "assignment", ".", "is_graded", "(", ")", ":", "if", "self", ".", "grading", "and", "self", ".", "grading", ".", "means_passed", ":", "return", "True", "else", ":", "return", "False...
Information if the given grading means passed. Non-graded assignments are always passed.
[ "Information", "if", "the", "given", "grading", "means", "passed", ".", "Non", "-", "graded", "assignments", "are", "always", "passed", "." ]
python
train
30.083333
olsoneric/pedemath
pedemath/vec2.py
https://github.com/olsoneric/pedemath/blob/4bffcfe7089e421d603eb0a9708b84789c2d16be/pedemath/vec2.py#L431-L436
def rot_rads(self, rads): """ Rotate vector by angle in radians.""" new_x = self.x * math.cos(rads) - self.y * math.sin(rads) self.y = self.x * math.sin(rads) + self.y * math.cos(rads) self.x = new_x
[ "def", "rot_rads", "(", "self", ",", "rads", ")", ":", "new_x", "=", "self", ".", "x", "*", "math", ".", "cos", "(", "rads", ")", "-", "self", ".", "y", "*", "math", ".", "sin", "(", "rads", ")", "self", ".", "y", "=", "self", ".", "x", "*"...
Rotate vector by angle in radians.
[ "Rotate", "vector", "by", "angle", "in", "radians", "." ]
python
train
37.833333
mattloper/chumpy
chumpy/ch.py
https://github.com/mattloper/chumpy/blob/a3cfdb1be3c8265c369c507b22f6f3f89414c772/chumpy/ch.py#L1088-L1110
def tree_iterator(self, visited=None, path=None): ''' Generator function that traverse the dr tree start from this node (self). ''' if visited is None: visited = set() if self not in visited: if path and isinstance(path, list): path.append...
[ "def", "tree_iterator", "(", "self", ",", "visited", "=", "None", ",", "path", "=", "None", ")", ":", "if", "visited", "is", "None", ":", "visited", "=", "set", "(", ")", "if", "self", "not", "in", "visited", ":", "if", "path", "and", "isinstance", ...
Generator function that traverse the dr tree start from this node (self).
[ "Generator", "function", "that", "traverse", "the", "dr", "tree", "start", "from", "this", "node", "(", "self", ")", "." ]
python
train
31.956522
artizirk/python-axp209
axp209.py
https://github.com/artizirk/python-axp209/blob/dc48015b23ea3695bf1ee076355c96ea434b77e4/axp209.py#L189-L194
def battery_voltage(self): """ Returns voltage in mV """ msb = self.bus.read_byte_data(AXP209_ADDRESS, BATTERY_VOLTAGE_MSB_REG) lsb = self.bus.read_byte_data(AXP209_ADDRESS, BATTERY_VOLTAGE_LSB_REG) voltage_bin = msb << 4 | lsb & 0x0f return voltage_bin * 1.1
[ "def", "battery_voltage", "(", "self", ")", ":", "msb", "=", "self", ".", "bus", ".", "read_byte_data", "(", "AXP209_ADDRESS", ",", "BATTERY_VOLTAGE_MSB_REG", ")", "lsb", "=", "self", ".", "bus", ".", "read_byte_data", "(", "AXP209_ADDRESS", ",", "BATTERY_VOLT...
Returns voltage in mV
[ "Returns", "voltage", "in", "mV" ]
python
train
49
mfcloud/python-zvm-sdk
zvmsdk/utils.py
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/utils.py#L113-L125
def convert_to_mb(s): """Convert memory size from GB to MB.""" s = s.upper() try: if s.endswith('G'): return float(s[:-1].strip()) * 1024 elif s.endswith('T'): return float(s[:-1].strip()) * 1024 * 1024 else: return float(s[:-1].strip()) except...
[ "def", "convert_to_mb", "(", "s", ")", ":", "s", "=", "s", ".", "upper", "(", ")", "try", ":", "if", "s", ".", "endswith", "(", "'G'", ")", ":", "return", "float", "(", "s", "[", ":", "-", "1", "]", ".", "strip", "(", ")", ")", "*", "1024",...
Convert memory size from GB to MB.
[ "Convert", "memory", "size", "from", "GB", "to", "MB", "." ]
python
train
35.307692