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
janpipek/physt
physt/histogram1d.py
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/histogram1d.py#L222-L236
def std(self) -> Optional[float]: #, ddof=0): """Standard deviation of all values entered into histogram. This number is precise, because we keep the necessary data separate from bin contents. Returns ------- float """ # TODO: Add DOF if self._s...
[ "def", "std", "(", "self", ")", "->", "Optional", "[", "float", "]", ":", "#, ddof=0):", "# TODO: Add DOF", "if", "self", ".", "_stats", ":", "return", "np", ".", "sqrt", "(", "self", ".", "variance", "(", ")", ")", "else", ":", "return", "None" ]
Standard deviation of all values entered into histogram. This number is precise, because we keep the necessary data separate from bin contents. Returns ------- float
[ "Standard", "deviation", "of", "all", "values", "entered", "into", "histogram", "." ]
python
train
26.2
SatelliteQE/nailgun
nailgun/entities.py
https://github.com/SatelliteQE/nailgun/blob/c36d8c20862e87bf6975bd48ac1ca40a9e634eaa/nailgun/entities.py#L2524-L2553
def read(self, entity=None, attrs=None, ignore=None, params=None): """Fetch an attribute missing from the server's response. For more information, see `Bugzilla #1237257 <https://bugzilla.redhat.com/show_bug.cgi?id=1237257>`_. Add content_view_component to the response if needed, as ...
[ "def", "read", "(", "self", ",", "entity", "=", "None", ",", "attrs", "=", "None", ",", "ignore", "=", "None", ",", "params", "=", "None", ")", ":", "if", "attrs", "is", "None", ":", "attrs", "=", "self", ".", "read_json", "(", ")", "if", "_get_v...
Fetch an attribute missing from the server's response. For more information, see `Bugzilla #1237257 <https://bugzilla.redhat.com/show_bug.cgi?id=1237257>`_. Add content_view_component to the response if needed, as :meth:`nailgun.entity_mixins.EntityReadMixin.read` can't initialize ...
[ "Fetch", "an", "attribute", "missing", "from", "the", "server", "s", "response", "." ]
python
train
43.133333
Nachtfeuer/pipeline
spline/tools/event.py
https://github.com/Nachtfeuer/pipeline/blob/04ca18c4e95e4349532bb45b768206393e1f2c13/spline/tools/event.py#L46-L55
def configure(**kwargs): """Global configuration for event handling.""" for key in kwargs: if key == 'is_logging_enabled': Event.is_logging_enabled = kwargs[key] elif key == 'collector_queue': Event.collector_queue = kwargs[key] else: ...
[ "def", "configure", "(", "*", "*", "kwargs", ")", ":", "for", "key", "in", "kwargs", ":", "if", "key", "==", "'is_logging_enabled'", ":", "Event", ".", "is_logging_enabled", "=", "kwargs", "[", "key", "]", "elif", "key", "==", "'collector_queue'", ":", "...
Global configuration for event handling.
[ "Global", "configuration", "for", "event", "handling", "." ]
python
train
47.9
cltk/cltk
cltk/tag/treebanks.py
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/tag/treebanks.py#L5-L31
def set_path(dicts, keys, v): """ Helper function for modifying nested dictionaries :param dicts: dict: the given dictionary :param keys: list str: path to added value :param v: str: value to be added Example: >>> d = dict() >>> set_path(d, ['a', 'b', 'c'], 'd') >>> d ...
[ "def", "set_path", "(", "dicts", ",", "keys", ",", "v", ")", ":", "for", "key", "in", "keys", "[", ":", "-", "1", "]", ":", "dicts", "=", "dicts", ".", "setdefault", "(", "key", ",", "dict", "(", ")", ")", "dicts", "=", "dicts", ".", "setdefaul...
Helper function for modifying nested dictionaries :param dicts: dict: the given dictionary :param keys: list str: path to added value :param v: str: value to be added Example: >>> d = dict() >>> set_path(d, ['a', 'b', 'c'], 'd') >>> d {'a': {'b': {'c': ['d']}}} ...
[ "Helper", "function", "for", "modifying", "nested", "dictionaries" ]
python
train
26.37037
lrq3000/pyFileFixity
pyFileFixity/lib/profilers/visual/pympler/summary.py
https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/profilers/visual/pympler/summary.py#L112-L134
def summarize(objects): """Summarize an objects list. Return a list of lists, whereas each row consists of:: [str(type), number of objects of this type, total size of these objects]. No guarantee regarding the order is given. """ count = {} total_size = {} for o in objects: ...
[ "def", "summarize", "(", "objects", ")", ":", "count", "=", "{", "}", "total_size", "=", "{", "}", "for", "o", "in", "objects", ":", "otype", "=", "_repr", "(", "o", ")", "if", "otype", "in", "count", ":", "count", "[", "otype", "]", "+=", "1", ...
Summarize an objects list. Return a list of lists, whereas each row consists of:: [str(type), number of objects of this type, total size of these objects]. No guarantee regarding the order is given.
[ "Summarize", "an", "objects", "list", "." ]
python
train
27.086957
dcramer/django-ratings
djangoratings/managers.py
https://github.com/dcramer/django-ratings/blob/4d00dedc920a4e32d650dc12d5f480c51fc6216c/djangoratings/managers.py#L8-L29
def delete(self, *args, **kwargs): """Handles updating the related `votes` and `score` fields attached to the model.""" # XXX: circular import from fields import RatingField qs = self.distinct().values_list('content_type', 'object_id').order_by('content_type') to_update = [...
[ "def", "delete", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# XXX: circular import", "from", "fields", "import", "RatingField", "qs", "=", "self", ".", "distinct", "(", ")", ".", "values_list", "(", "'content_type'", ",", "'object_i...
Handles updating the related `votes` and `score` fields attached to the model.
[ "Handles", "updating", "the", "related", "votes", "and", "score", "fields", "attached", "to", "the", "model", "." ]
python
train
41.5
JNRowe/jnrbase
jnrbase/cmdline.py
https://github.com/JNRowe/jnrbase/blob/ae505ef69a9feb739b5f4e62c5a8e6533104d3ea/jnrbase/cmdline.py#L97-L108
def config_(name: str, local: bool, package: str, section: str, key: Optional[str]): """Extract or list values from config.""" cfg = config.read_configs(package, name, local=local) if key: with suppress(NoOptionError, NoSectionError): echo(cfg.get(section, key)) else: ...
[ "def", "config_", "(", "name", ":", "str", ",", "local", ":", "bool", ",", "package", ":", "str", ",", "section", ":", "str", ",", "key", ":", "Optional", "[", "str", "]", ")", ":", "cfg", "=", "config", ".", "read_configs", "(", "package", ",", ...
Extract or list values from config.
[ "Extract", "or", "list", "values", "from", "config", "." ]
python
train
40.583333
saltstack/salt
salt/cloud/clouds/azurearm.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/azurearm.py#L1772-L1792
def delete_blob(call=None, kwargs=None): # pylint: disable=unused-argument ''' Delete a blob from a container. ''' if kwargs is None: kwargs = {} if 'container' not in kwargs: raise SaltCloudSystemExit( 'A container must be specified' ) if 'blob' not in kwa...
[ "def", "delete_blob", "(", "call", "=", "None", ",", "kwargs", "=", "None", ")", ":", "# pylint: disable=unused-argument", "if", "kwargs", "is", "None", ":", "kwargs", "=", "{", "}", "if", "'container'", "not", "in", "kwargs", ":", "raise", "SaltCloudSystemE...
Delete a blob from a container.
[ "Delete", "a", "blob", "from", "a", "container", "." ]
python
train
25.095238
google/apitools
apitools/gen/util.py
https://github.com/google/apitools/blob/f3745a7ea535aa0e88b0650c16479b696d6fd446/apitools/gen/util.py#L257-L289
def ReplaceHomoglyphs(s): """Returns s with unicode homoglyphs replaced by ascii equivalents.""" homoglyphs = { '\xa0': ' ', # &nbsp; ? '\u00e3': '', # TODO(gsfowler) drop after .proto spurious char elided '\u00a0': ' ', # &nbsp; ? '\u00a9': '(C)', # COPYRIGHT SIGN (would you...
[ "def", "ReplaceHomoglyphs", "(", "s", ")", ":", "homoglyphs", "=", "{", "'\\xa0'", ":", "' '", ",", "# &nbsp; ?", "'\\u00e3'", ":", "''", ",", "# TODO(gsfowler) drop after .proto spurious char elided", "'\\u00a0'", ":", "' '", ",", "# &nbsp; ?", "'\\u00a9'", ":", ...
Returns s with unicode homoglyphs replaced by ascii equivalents.
[ "Returns", "s", "with", "unicode", "homoglyphs", "replaced", "by", "ascii", "equivalents", "." ]
python
train
36.212121
pallets/werkzeug
examples/simplewiki/utils.py
https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/examples/simplewiki/utils.py#L54-L57
def generate_template(template_name, **context): """Load and generate a template.""" context.update(href=href, format_datetime=format_datetime) return template_loader.load(template_name).generate(**context)
[ "def", "generate_template", "(", "template_name", ",", "*", "*", "context", ")", ":", "context", ".", "update", "(", "href", "=", "href", ",", "format_datetime", "=", "format_datetime", ")", "return", "template_loader", ".", "load", "(", "template_name", ")", ...
Load and generate a template.
[ "Load", "and", "generate", "a", "template", "." ]
python
train
53.75
pydot/pydot
pydot.py
https://github.com/pydot/pydot/blob/48ba231b36012c5e13611807c9aac7d8ae8c15c4/pydot.py#L285-L300
def graph_from_dot_file(path, encoding=None): """Load graphs from DOT file at `path`. @param path: to DOT file @param encoding: as passed to `io.open`. For example, `'utf-8'`. @return: Graphs that result from parsing. @rtype: `list` of `pydot.Dot` """ with io.open(path, 'rt', encod...
[ "def", "graph_from_dot_file", "(", "path", ",", "encoding", "=", "None", ")", ":", "with", "io", ".", "open", "(", "path", ",", "'rt'", ",", "encoding", "=", "encoding", ")", "as", "f", ":", "s", "=", "f", ".", "read", "(", ")", "if", "not", "PY3...
Load graphs from DOT file at `path`. @param path: to DOT file @param encoding: as passed to `io.open`. For example, `'utf-8'`. @return: Graphs that result from parsing. @rtype: `list` of `pydot.Dot`
[ "Load", "graphs", "from", "DOT", "file", "at", "path", "." ]
python
train
27.375
napalm-automation/napalm-logs
napalm_logs/server.py
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/server.py#L106-L146
def _compile_prefixes(self): ''' Create a dict of all OS prefixes and their compiled regexs ''' self.compiled_prefixes = {} for dev_os, os_config in self.config.items(): if not os_config: continue self.compiled_prefixes[dev_os] = [] ...
[ "def", "_compile_prefixes", "(", "self", ")", ":", "self", ".", "compiled_prefixes", "=", "{", "}", "for", "dev_os", ",", "os_config", "in", "self", ".", "config", ".", "items", "(", ")", ":", "if", "not", "os_config", ":", "continue", "self", ".", "co...
Create a dict of all OS prefixes and their compiled regexs
[ "Create", "a", "dict", "of", "all", "OS", "prefixes", "and", "their", "compiled", "regexs" ]
python
train
52.04878
twilio/twilio-python
twilio/base/version.py
https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/base/version.py#L128-L150
def read_limits(self, limit=None, page_size=None): """ Takes a limit on the max number of records to read and a max page_size and calculates the max number of pages to read. :param int limit: Max number of records to read. :param int page_size: Max page size. :return dic...
[ "def", "read_limits", "(", "self", ",", "limit", "=", "None", ",", "page_size", "=", "None", ")", ":", "page_limit", "=", "values", ".", "unset", "if", "limit", "is", "not", "None", ":", "if", "page_size", "is", "None", ":", "page_size", "=", "limit", ...
Takes a limit on the max number of records to read and a max page_size and calculates the max number of pages to read. :param int limit: Max number of records to read. :param int page_size: Max page size. :return dict: A dictionary of paging limits.
[ "Takes", "a", "limit", "on", "the", "max", "number", "of", "records", "to", "read", "and", "a", "max", "page_size", "and", "calculates", "the", "max", "number", "of", "pages", "to", "read", "." ]
python
train
30.478261
dnanexus/dx-toolkit
src/python/dxpy/api.py
https://github.com/dnanexus/dx-toolkit/blob/74befb53ad90fcf902d8983ae6d74580f402d619/src/python/dxpy/api.py#L395-L401
def container_rename_folder(object_id, input_params={}, always_retry=False, **kwargs): """ Invokes the /container-xxxx/renameFolder API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Folders-and-Deletion#API-method%3A-%2Fclass-xxxx%2FrenameFolder """ return DXHTTPReq...
[ "def", "container_rename_folder", "(", "object_id", ",", "input_params", "=", "{", "}", ",", "always_retry", "=", "False", ",", "*", "*", "kwargs", ")", ":", "return", "DXHTTPRequest", "(", "'/%s/renameFolder'", "%", "object_id", ",", "input_params", ",", "alw...
Invokes the /container-xxxx/renameFolder API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Folders-and-Deletion#API-method%3A-%2Fclass-xxxx%2FrenameFolder
[ "Invokes", "the", "/", "container", "-", "xxxx", "/", "renameFolder", "API", "method", "." ]
python
train
57.285714
marteinn/AtomicPress
atomicpress/ext/importer/__init__.py
https://github.com/marteinn/AtomicPress/blob/b8a0ca9c9c327f062833fc4a401a8ac0baccf6d1/atomicpress/ext/importer/__init__.py#L179-L189
def _clean_post_content(blog_url, content): """ Replace import path with something relative to blog. """ content = re.sub( "<img.src=\"%s(.*)\"" % blog_url, lambda s: "<img src=\"%s\"" % _get_relative_upload(s.groups(1)[0]), content) return content
[ "def", "_clean_post_content", "(", "blog_url", ",", "content", ")", ":", "content", "=", "re", ".", "sub", "(", "\"<img.src=\\\"%s(.*)\\\"\"", "%", "blog_url", ",", "lambda", "s", ":", "\"<img src=\\\"%s\\\"\"", "%", "_get_relative_upload", "(", "s", ".", "group...
Replace import path with something relative to blog.
[ "Replace", "import", "path", "with", "something", "relative", "to", "blog", "." ]
python
train
25.818182
gdub/python-simpleldap
simpleldap/__init__.py
https://github.com/gdub/python-simpleldap/blob/a833f444d90ad2f3fe779c3e2cb08350052fedc8/simpleldap/__init__.py#L188-L205
def clear_search_defaults(self, args=None): """ Clear all search defaults specified by the list of parameter names given as ``args``. If ``args`` is not given, then clear all existing search defaults. Examples:: conn.set_search_defaults(scope=ldap.SCOPE_BASE, attrs...
[ "def", "clear_search_defaults", "(", "self", ",", "args", "=", "None", ")", ":", "if", "args", "is", "None", ":", "self", ".", "_search_defaults", ".", "clear", "(", ")", "else", ":", "for", "arg", "in", "args", ":", "if", "arg", "in", "self", ".", ...
Clear all search defaults specified by the list of parameter names given as ``args``. If ``args`` is not given, then clear all existing search defaults. Examples:: conn.set_search_defaults(scope=ldap.SCOPE_BASE, attrs=['cn']) conn.clear_search_defaults(['scope']) ...
[ "Clear", "all", "search", "defaults", "specified", "by", "the", "list", "of", "parameter", "names", "given", "as", "args", ".", "If", "args", "is", "not", "given", "then", "clear", "all", "existing", "search", "defaults", "." ]
python
train
34.666667
soravux/scoop
scoop/futures.py
https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/futures.py#L72-L95
def _mapFuture(callable_, *iterables): """Similar to the built-in map function, but each of its iteration will spawn a separate independent parallel Future that will run either locally or remotely as `callable(*args)`. :param callable: Any callable object (function or class object with *__call__* ...
[ "def", "_mapFuture", "(", "callable_", ",", "*", "iterables", ")", ":", "childrenList", "=", "[", "]", "for", "args", "in", "zip", "(", "*", "iterables", ")", ":", "childrenList", ".", "append", "(", "submit", "(", "callable_", ",", "*", "args", ")", ...
Similar to the built-in map function, but each of its iteration will spawn a separate independent parallel Future that will run either locally or remotely as `callable(*args)`. :param callable: Any callable object (function or class object with *__call__* method); this object will be called to exec...
[ "Similar", "to", "the", "built", "-", "in", "map", "function", "but", "each", "of", "its", "iteration", "will", "spawn", "a", "separate", "independent", "parallel", "Future", "that", "will", "run", "either", "locally", "or", "remotely", "as", "callable", "("...
python
train
50.666667
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L516-L541
def disassemble_string(self, lpAddress, code): """ Disassemble instructions from a block of binary code. @type lpAddress: int @param lpAddress: Memory address where the code was read from. @type code: str @param code: Binary code to disassemble. @rtype: list...
[ "def", "disassemble_string", "(", "self", ",", "lpAddress", ",", "code", ")", ":", "try", ":", "disasm", "=", "self", ".", "__disasm", "except", "AttributeError", ":", "disasm", "=", "self", ".", "__disasm", "=", "Disassembler", "(", "self", ".", "get_arch...
Disassemble instructions from a block of binary code. @type lpAddress: int @param lpAddress: Memory address where the code was read from. @type code: str @param code: Binary code to disassemble. @rtype: list of tuple( long, int, str, str ) @return: List of tuples. E...
[ "Disassemble", "instructions", "from", "a", "block", "of", "binary", "code", "." ]
python
train
36.038462
portantier/habu
habu/cli/cmd_fernet_genkey.py
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_fernet_genkey.py#L20-L37
def cmd_fernet_genkey(writecfg): """Generate a new Fernet Key, optionally write it to ~/.habu.json Example: \b $ habu.fernet.genkey xgvWCIvjwe9Uq7NBvwO796iI4dsGD623QOT9GWqnuhg= """ key = Fernet.generate_key() print(key.decode()) if writecfg: habucfg = loadcfg(environment=...
[ "def", "cmd_fernet_genkey", "(", "writecfg", ")", ":", "key", "=", "Fernet", ".", "generate_key", "(", ")", "print", "(", "key", ".", "decode", "(", ")", ")", "if", "writecfg", ":", "habucfg", "=", "loadcfg", "(", "environment", "=", "False", ")", "hab...
Generate a new Fernet Key, optionally write it to ~/.habu.json Example: \b $ habu.fernet.genkey xgvWCIvjwe9Uq7NBvwO796iI4dsGD623QOT9GWqnuhg=
[ "Generate", "a", "new", "Fernet", "Key", "optionally", "write", "it", "to", "~", "/", ".", "habu", ".", "json" ]
python
train
26.888889
twilio/twilio-python
twilio/base/serialize.py
https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/base/serialize.py#L7-L19
def iso8601_date(d): """ Return a string representation of a date that the Twilio API understands Format is YYYY-MM-DD. Returns None if d is not a string, datetime, or date """ if d == values.unset: return d elif isinstance(d, datetime.datetime): return str(d.date()) elif isi...
[ "def", "iso8601_date", "(", "d", ")", ":", "if", "d", "==", "values", ".", "unset", ":", "return", "d", "elif", "isinstance", "(", "d", ",", "datetime", ".", "datetime", ")", ":", "return", "str", "(", "d", ".", "date", "(", ")", ")", "elif", "is...
Return a string representation of a date that the Twilio API understands Format is YYYY-MM-DD. Returns None if d is not a string, datetime, or date
[ "Return", "a", "string", "representation", "of", "a", "date", "that", "the", "Twilio", "API", "understands", "Format", "is", "YYYY", "-", "MM", "-", "DD", ".", "Returns", "None", "if", "d", "is", "not", "a", "string", "datetime", "or", "date" ]
python
train
30.923077
instaloader/instaloader
instaloader/structures.py
https://github.com/instaloader/instaloader/blob/87d877e650cd8020b04b8b51be120599a441fd5b/instaloader/structures.py#L923-L925
def get_items(self) -> Iterator[StoryItem]: """Retrieve all items from a story.""" yield from (StoryItem(self._context, item, self.owner_profile) for item in reversed(self._node['items']))
[ "def", "get_items", "(", "self", ")", "->", "Iterator", "[", "StoryItem", "]", ":", "yield", "from", "(", "StoryItem", "(", "self", ".", "_context", ",", "item", ",", "self", ".", "owner_profile", ")", "for", "item", "in", "reversed", "(", "self", ".",...
Retrieve all items from a story.
[ "Retrieve", "all", "items", "from", "a", "story", "." ]
python
train
67.333333
cloud-custodian/cloud-custodian
tools/c7n_org/scripts/gcpprojects.py
https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_org/scripts/gcpprojects.py#L27-L52
def main(output): """ Generate a c7n-org gcp projects config file """ client = Session().client('cloudresourcemanager', 'v1', 'projects') results = [] for page in client.execute_paged_query('list', {}): for project in page.get('projects', []): if project['lifecycleState'] ...
[ "def", "main", "(", "output", ")", ":", "client", "=", "Session", "(", ")", ".", "client", "(", "'cloudresourcemanager'", ",", "'v1'", ",", "'projects'", ")", "results", "=", "[", "]", "for", "page", "in", "client", ".", "execute_paged_query", "(", "'lis...
Generate a c7n-org gcp projects config file
[ "Generate", "a", "c7n", "-", "org", "gcp", "projects", "config", "file" ]
python
train
29.615385
LuqueDaniel/pybooru
pybooru/api_danbooru.py
https://github.com/LuqueDaniel/pybooru/blob/60cd5254684d293b308f0b11b8f4ac2dce101479/pybooru/api_danbooru.py#L340-L354
def comment_create(self, post_id, body, do_not_bump_post=None): """Action to lets you create a comment (Requires login). Parameters: post_id (int): body (str): do_not_bump_post (bool): Set to 1 if you do not want the post to be bu...
[ "def", "comment_create", "(", "self", ",", "post_id", ",", "body", ",", "do_not_bump_post", "=", "None", ")", ":", "params", "=", "{", "'comment[post_id]'", ":", "post_id", ",", "'comment[body]'", ":", "body", ",", "'comment[do_not_bump_post]'", ":", "do_not_bum...
Action to lets you create a comment (Requires login). Parameters: post_id (int): body (str): do_not_bump_post (bool): Set to 1 if you do not want the post to be bumped to the top of the comment listing.
[ "Action", "to", "lets", "you", "create", "a", "comment", "(", "Requires", "login", ")", "." ]
python
train
39.533333
BreakingBytes/simkit
simkit/core/__init__.py
https://github.com/BreakingBytes/simkit/blob/205163d879d3880b6c9ef609f1b723a58773026b/simkit/core/__init__.py#L267-L297
def set_meta(mcs, bases, attr): """ Get all of the ``Meta`` classes from bases and combine them with this class. Pops or creates ``Meta`` from attributes, combines all bases, adds ``_meta`` to attributes with all meta :param bases: bases of this class :param att...
[ "def", "set_meta", "(", "mcs", ",", "bases", ",", "attr", ")", ":", "# pop the meta class from the attributes", "meta", "=", "attr", ".", "pop", "(", "mcs", ".", "_meta_cls", ",", "types", ".", "ClassType", "(", "mcs", ".", "_meta_cls", ",", "(", ")", ",...
Get all of the ``Meta`` classes from bases and combine them with this class. Pops or creates ``Meta`` from attributes, combines all bases, adds ``_meta`` to attributes with all meta :param bases: bases of this class :param attr: class attributes :return: attributes with...
[ "Get", "all", "of", "the", "Meta", "classes", "from", "bases", "and", "combine", "them", "with", "this", "class", "." ]
python
train
40.483871
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L3191-L3199
def _match_national_number(number, number_desc, allow_prefix_match): """Returns whether the given national number (a string containing only decimal digits) matches the national number pattern defined in the given PhoneNumberDesc object. """ # We don't want to consider it a prefix match when matching non...
[ "def", "_match_national_number", "(", "number", ",", "number_desc", ",", "allow_prefix_match", ")", ":", "# We don't want to consider it a prefix match when matching non-empty input against an empty", "# pattern.", "if", "number_desc", "is", "None", "or", "number_desc", ".", "n...
Returns whether the given national number (a string containing only decimal digits) matches the national number pattern defined in the given PhoneNumberDesc object.
[ "Returns", "whether", "the", "given", "national", "number", "(", "a", "string", "containing", "only", "decimal", "digits", ")", "matches", "the", "national", "number", "pattern", "defined", "in", "the", "given", "PhoneNumberDesc", "object", "." ]
python
train
66.222222
korfuri/django-prometheus
django_prometheus/db/common.py
https://github.com/korfuri/django-prometheus/blob/c3a19ce46d812f76d9316e50a232878c27c9bdf5/django_prometheus/db/common.py#L51-L72
def ExportingCursorWrapper(cursor_class, alias, vendor): """Returns a CursorWrapper class that knows its database's alias and vendor name. """ class CursorWrapper(cursor_class): """Extends the base CursorWrapper to count events.""" def execute(self, *args, **kwargs): execut...
[ "def", "ExportingCursorWrapper", "(", "cursor_class", ",", "alias", ",", "vendor", ")", ":", "class", "CursorWrapper", "(", "cursor_class", ")", ":", "\"\"\"Extends the base CursorWrapper to count events.\"\"\"", "def", "execute", "(", "self", ",", "*", "args", ",", ...
Returns a CursorWrapper class that knows its database's alias and vendor name.
[ "Returns", "a", "CursorWrapper", "class", "that", "knows", "its", "database", "s", "alias", "and", "vendor", "name", "." ]
python
train
46.090909
pypa/pipenv
pipenv/patched/notpip/_vendor/pkg_resources/__init__.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L942-L954
def markers_pass(self, req, extras=None): """ Evaluate markers for req against each extra that demanded it. Return False if the req has a marker and fails evaluation. Otherwise, return True. """ extra_evals = ( req.marker.evaluate({'extra': extra}) ...
[ "def", "markers_pass", "(", "self", ",", "req", ",", "extras", "=", "None", ")", ":", "extra_evals", "=", "(", "req", ".", "marker", ".", "evaluate", "(", "{", "'extra'", ":", "extra", "}", ")", "for", "extra", "in", "self", ".", "get", "(", "req",...
Evaluate markers for req against each extra that demanded it. Return False if the req has a marker and fails evaluation. Otherwise, return True.
[ "Evaluate", "markers", "for", "req", "against", "each", "extra", "that", "demanded", "it", "." ]
python
train
33.076923
odlgroup/odl
odl/solvers/functional/default_functionals.py
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/solvers/functional/default_functionals.py#L1541-L1561
def gradient(self): """Gradient operator of the functional.""" functional = self class KLCrossEntCCGradient(Operator): """The gradient operator of this functional.""" def __init__(self): """Initialize a new instance.""" super(KLCrossEntC...
[ "def", "gradient", "(", "self", ")", ":", "functional", "=", "self", "class", "KLCrossEntCCGradient", "(", "Operator", ")", ":", "\"\"\"The gradient operator of this functional.\"\"\"", "def", "__init__", "(", "self", ")", ":", "\"\"\"Initialize a new instance.\"\"\"", ...
Gradient operator of the functional.
[ "Gradient", "operator", "of", "the", "functional", "." ]
python
train
34.333333
gnosis/gnosis-py
gnosis/safe/safe_service.py
https://github.com/gnosis/gnosis-py/blob/2a9a5d75a375fc9813ac04df133e6910c82f9d49/gnosis/safe/safe_service.py#L198-L211
def check_proxy_code(self, address) -> bool: """ Check if proxy is valid :param address: address of the proxy :return: True if proxy is valid, False otherwise """ deployed_proxy_code = self.w3.eth.getCode(address) proxy_code_fns = (get_paying_proxy_deployed_byteco...
[ "def", "check_proxy_code", "(", "self", ",", "address", ")", "->", "bool", ":", "deployed_proxy_code", "=", "self", ".", "w3", ".", "eth", ".", "getCode", "(", "address", ")", "proxy_code_fns", "=", "(", "get_paying_proxy_deployed_bytecode", ",", "get_proxy_fact...
Check if proxy is valid :param address: address of the proxy :return: True if proxy is valid, False otherwise
[ "Check", "if", "proxy", "is", "valid", ":", "param", "address", ":", "address", "of", "the", "proxy", ":", "return", ":", "True", "if", "proxy", "is", "valid", "False", "otherwise" ]
python
test
45.5
cltl/KafNafParserPy
KafNafParserPy/KafNafParserMod.py
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/KafNafParserMod.py#L816-L826
def remove_opinion_layer(self): """ Removes the opinion layer (if exists) of the object (in memory) """ if self.opinion_layer is not None: this_node = self.opinion_layer.get_node() self.root.remove(this_node) self.opinion_layer = None if self....
[ "def", "remove_opinion_layer", "(", "self", ")", ":", "if", "self", ".", "opinion_layer", "is", "not", "None", ":", "this_node", "=", "self", ".", "opinion_layer", ".", "get_node", "(", ")", "self", ".", "root", ".", "remove", "(", "this_node", ")", "sel...
Removes the opinion layer (if exists) of the object (in memory)
[ "Removes", "the", "opinion", "layer", "(", "if", "exists", ")", "of", "the", "object", "(", "in", "memory", ")" ]
python
train
34.090909
cltk/cltk
cltk/prosody/latin/metrical_validator.py
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/prosody/latin/metrical_validator.py#L36-L50
def is_valid_hendecasyllables(self, scanned_line: str) -> bool: """Determine if a scansion pattern is one of the valid Hendecasyllables metrical patterns :param scanned_line: a line containing a sequence of stressed and unstressed syllables :return bool >>> print(MetricalValidator().is...
[ "def", "is_valid_hendecasyllables", "(", "self", ",", "scanned_line", ":", "str", ")", "->", "bool", ":", "line", "=", "scanned_line", ".", "replace", "(", "self", ".", "constants", ".", "FOOT_SEPARATOR", ",", "\"\"", ")", "line", "=", "line", ".", "replac...
Determine if a scansion pattern is one of the valid Hendecasyllables metrical patterns :param scanned_line: a line containing a sequence of stressed and unstressed syllables :return bool >>> print(MetricalValidator().is_valid_hendecasyllables("-U-UU-U-U-U")) True
[ "Determine", "if", "a", "scansion", "pattern", "is", "one", "of", "the", "valid", "Hendecasyllables", "metrical", "patterns" ]
python
train
43.333333
trailofbits/manticore
manticore/platforms/decree.py
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/decree.py#L745-L765
def int80(self, cpu): """ 32 bit dispatcher. :param cpu: current CPU. _terminate, transmit, receive, fdwait, allocate, deallocate and random """ syscalls = {0x00000001: self.sys_terminate, 0x00000002: self.sys_transmit, 0x00000003: ...
[ "def", "int80", "(", "self", ",", "cpu", ")", ":", "syscalls", "=", "{", "0x00000001", ":", "self", ".", "sys_terminate", ",", "0x00000002", ":", "self", ".", "sys_transmit", ",", "0x00000003", ":", "self", ".", "sys_receive", ",", "0x00000004", ":", "se...
32 bit dispatcher. :param cpu: current CPU. _terminate, transmit, receive, fdwait, allocate, deallocate and random
[ "32", "bit", "dispatcher", ".", ":", "param", "cpu", ":", "current", "CPU", ".", "_terminate", "transmit", "receive", "fdwait", "allocate", "deallocate", "and", "random" ]
python
valid
45.904762
wbond/oscrypto
oscrypto/_win/symmetric.py
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_win/symmetric.py#L100-L140
def aes_cbc_no_padding_decrypt(key, data, iv): """ Decrypts AES ciphertext in CBC mode using a 128, 192 or 256 bit key and no padding. :param key: The encryption key - a byte string either 16, 24 or 32 bytes long :param data: The ciphertext - a byte string :param iv: T...
[ "def", "aes_cbc_no_padding_decrypt", "(", "key", ",", "data", ",", "iv", ")", ":", "if", "len", "(", "key", ")", "not", "in", "[", "16", ",", "24", ",", "32", "]", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n key must be either...
Decrypts AES ciphertext in CBC mode using a 128, 192 or 256 bit key and no padding. :param key: The encryption key - a byte string either 16, 24 or 32 bytes long :param data: The ciphertext - a byte string :param iv: The initialization vector - a byte string 16-bytes long ...
[ "Decrypts", "AES", "ciphertext", "in", "CBC", "mode", "using", "a", "128", "192", "or", "256", "bit", "key", "and", "no", "padding", "." ]
python
valid
26.463415
apache/incubator-heron
heron/tools/cli/src/python/execute.py
https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/cli/src/python/execute.py#L40-L84
def heron_class(class_name, lib_jars, extra_jars=None, args=None, java_defines=None): ''' Execute a heron class given the args and the jars needed for class path :param class_name: :param lib_jars: :param extra_jars: :param args: :param java_defines: :return: ''' # default optional params to empty l...
[ "def", "heron_class", "(", "class_name", ",", "lib_jars", ",", "extra_jars", "=", "None", ",", "args", "=", "None", ",", "java_defines", "=", "None", ")", ":", "# default optional params to empty list if not provided", "if", "extra_jars", "is", "None", ":", "extra...
Execute a heron class given the args and the jars needed for class path :param class_name: :param lib_jars: :param extra_jars: :param args: :param java_defines: :return:
[ "Execute", "a", "heron", "class", "given", "the", "args", "and", "the", "jars", "needed", "for", "class", "path", ":", "param", "class_name", ":", ":", "param", "lib_jars", ":", ":", "param", "extra_jars", ":", ":", "param", "args", ":", ":", "param", ...
python
valid
35.488889
wummel/patool
patoolib/util.py
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/util.py#L222-L228
def run_checked (cmd, ret_ok=(0,), **kwargs): """Run command and raise PatoolError on error.""" retcode = run(cmd, **kwargs) if retcode not in ret_ok: msg = "Command `%s' returned non-zero exit status %d" % (cmd, retcode) raise PatoolError(msg) return retcode
[ "def", "run_checked", "(", "cmd", ",", "ret_ok", "=", "(", "0", ",", ")", ",", "*", "*", "kwargs", ")", ":", "retcode", "=", "run", "(", "cmd", ",", "*", "*", "kwargs", ")", "if", "retcode", "not", "in", "ret_ok", ":", "msg", "=", "\"Command `%s'...
Run command and raise PatoolError on error.
[ "Run", "command", "and", "raise", "PatoolError", "on", "error", "." ]
python
train
40.714286
acristoffers/ahio
ahio/drivers/generic_tcp_io.py
https://github.com/acristoffers/ahio/blob/5d47f1697c173bd1cbdeac930546f97ad8570a38/ahio/drivers/generic_tcp_io.py#L46-L66
def setup(self, address, port): """Connects to server at `address`:`port`. Connects to a TCP server listening at `address`:`port` that implements the protocol described in the file "Generic TCP I:O Protocol.md" @arg address IP or address to connect to. @arg port port to connect...
[ "def", "setup", "(", "self", ",", "address", ",", "port", ")", ":", "address", "=", "str", "(", "address", ")", "port", "=", "int", "(", "port", ")", "self", ".", "_socket", "=", "socket", ".", "socket", "(", ")", "self", ".", "_socket", ".", "co...
Connects to server at `address`:`port`. Connects to a TCP server listening at `address`:`port` that implements the protocol described in the file "Generic TCP I:O Protocol.md" @arg address IP or address to connect to. @arg port port to connect to. @throw RuntimeError if connec...
[ "Connects", "to", "server", "at", "address", ":", "port", "." ]
python
valid
38.952381
bram85/topydo
topydo/commands/DepCommand.py
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/commands/DepCommand.py#L104-L131
def _handle_ls(self): """ Handles the ls subsubcommand. """ try: arg1 = self.argument(1) arg2 = self.argument(2) todos = [] if arg2 == 'to' or arg1 == 'before': # dep ls 1 to OR dep ls before 1 number = arg1 if arg2 == 'to'...
[ "def", "_handle_ls", "(", "self", ")", ":", "try", ":", "arg1", "=", "self", ".", "argument", "(", "1", ")", "arg2", "=", "self", ".", "argument", "(", "2", ")", "todos", "=", "[", "]", "if", "arg2", "==", "'to'", "or", "arg1", "==", "'before'", ...
Handles the ls subsubcommand.
[ "Handles", "the", "ls", "subsubcommand", "." ]
python
train
39.035714
kgori/treeCl
treeCl/tree.py
https://github.com/kgori/treeCl/blob/fed624b3db1c19cc07175ca04e3eda6905a8d305/treeCl/tree.py#L882-L887
def trifurcate_base(cls, newick): """ Rewrites a newick string so that the base is a trifurcation (usually means an unrooted tree) """ t = cls(newick) t._tree.deroot() return t.newick
[ "def", "trifurcate_base", "(", "cls", ",", "newick", ")", ":", "t", "=", "cls", "(", "newick", ")", "t", ".", "_tree", ".", "deroot", "(", ")", "return", "t", ".", "newick" ]
Rewrites a newick string so that the base is a trifurcation (usually means an unrooted tree)
[ "Rewrites", "a", "newick", "string", "so", "that", "the", "base", "is", "a", "trifurcation", "(", "usually", "means", "an", "unrooted", "tree", ")" ]
python
train
36.333333
zetaops/zengine
zengine/management_commands.py
https://github.com/zetaops/zengine/blob/b5bc32d3b37bca799f8985be916f04528ac79e4a/zengine/management_commands.py#L187-L203
def run(self): """ Starts a development server for the zengine application """ from zengine.wf_daemon import run_workers, Worker worker_count = int(self.manager.args.workers or 1) if not self.manager.args.daemonize: print("Starting worker(s)") if wor...
[ "def", "run", "(", "self", ")", ":", "from", "zengine", ".", "wf_daemon", "import", "run_workers", ",", "Worker", "worker_count", "=", "int", "(", "self", ".", "manager", ".", "args", ".", "workers", "or", "1", ")", "if", "not", "self", ".", "manager",...
Starts a development server for the zengine application
[ "Starts", "a", "development", "server", "for", "the", "zengine", "application" ]
python
train
33.529412
h2oai/h2o-3
h2o-py/h2o/model/multinomial.py
https://github.com/h2oai/h2o-3/blob/dd62aaa1e7f680a8b16ee14bc66b0fb5195c2ad8/h2o-py/h2o/model/multinomial.py#L29-L45
def hit_ratio_table(self, train=False, valid=False, xval=False): """ Retrieve the Hit Ratios. If all are False (default), then return the training metric value. If more than one options is set to True, then return a dictionary of metrics where the keys are "train", "valid", and ...
[ "def", "hit_ratio_table", "(", "self", ",", "train", "=", "False", ",", "valid", "=", "False", ",", "xval", "=", "False", ")", ":", "tm", "=", "ModelBase", ".", "_get_metrics", "(", "self", ",", "train", ",", "valid", ",", "xval", ")", "m", "=", "{...
Retrieve the Hit Ratios. If all are False (default), then return the training metric value. If more than one options is set to True, then return a dictionary of metrics where the keys are "train", "valid", and "xval". :param train: If train is True, then return the hit ratio value for ...
[ "Retrieve", "the", "Hit", "Ratios", "." ]
python
test
54.176471
tensorflow/probability
tensorflow_probability/examples/bayesian_neural_network.py
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/bayesian_neural_network.py#L90-L121
def plot_weight_posteriors(names, qm_vals, qs_vals, fname): """Save a PNG plot with histograms of weight means and stddevs. Args: names: A Python `iterable` of `str` variable names. qm_vals: A Python `iterable`, the same length as `names`, whose elements are Numpy `array`s, of any shape, containing ...
[ "def", "plot_weight_posteriors", "(", "names", ",", "qm_vals", ",", "qs_vals", ",", "fname", ")", ":", "fig", "=", "figure", ".", "Figure", "(", "figsize", "=", "(", "6", ",", "3", ")", ")", "canvas", "=", "backend_agg", ".", "FigureCanvasAgg", "(", "f...
Save a PNG plot with histograms of weight means and stddevs. Args: names: A Python `iterable` of `str` variable names. qm_vals: A Python `iterable`, the same length as `names`, whose elements are Numpy `array`s, of any shape, containing posterior means of weight varibles. qs_vals: A Python `i...
[ "Save", "a", "PNG", "plot", "with", "histograms", "of", "weight", "means", "and", "stddevs", "." ]
python
test
34.53125
acutesoftware/AIKIF
aikif/toolbox/xml_tools.py
https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/toolbox/xml_tools.py#L53-L71
def count_elements(fname, element): """ returns (511, 35082) for ANC__WhereToHongKong.xml """ num = 0 tot = 0 for event, elem in iterparse(fname): tot += 1 if elem.text != '': #print(' tag = ', elem.tag) #print(' event = ', event # always end ...
[ "def", "count_elements", "(", "fname", ",", "element", ")", ":", "num", "=", "0", "tot", "=", "0", "for", "event", ",", "elem", "in", "iterparse", "(", "fname", ")", ":", "tot", "+=", "1", "if", "elem", ".", "text", "!=", "''", ":", "#print(' tag ...
returns (511, 35082) for ANC__WhereToHongKong.xml
[ "returns", "(", "511", "35082", ")", "for", "ANC__WhereToHongKong", ".", "xml" ]
python
train
28.210526
saltstack/salt
salt/states/webutil.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/webutil.py#L36-L104
def user_exists(name, password=None, htpasswd_file=None, options='', force=False, runas=None, update=False): ''' Make sure the user is inside the specified htpasswd file name User name password User password htpasswd_file Path to the htpasswd file opti...
[ "def", "user_exists", "(", "name", ",", "password", "=", "None", ",", "htpasswd_file", "=", "None", ",", "options", "=", "''", ",", "force", "=", "False", ",", "runas", "=", "None", ",", "update", "=", "False", ")", ":", "ret", "=", "{", "'name'", ...
Make sure the user is inside the specified htpasswd file name User name password User password htpasswd_file Path to the htpasswd file options See :mod:`salt.modules.htpasswd.useradd` force Touch the file even if user already created runas Th...
[ "Make", "sure", "the", "user", "is", "inside", "the", "specified", "htpasswd", "file" ]
python
train
30.536232
mongolab/mongoctl
mongoctl/commands/command_utils.py
https://github.com/mongolab/mongoctl/blob/fab15216127ad4bf8ea9aa8a95d75504c0ef01a2/mongoctl/commands/command_utils.py#L365-L374
def is_server_or_cluster_db_address(value): """ checks if the specified value is in the form of [server or cluster id][/database] """ # check if value is an id string id_path = value.split("/") id = id_path[0] return len(id_path) <= 2 and (repository.lookup_server(id) or ...
[ "def", "is_server_or_cluster_db_address", "(", "value", ")", ":", "# check if value is an id string", "id_path", "=", "value", ".", "split", "(", "\"/\"", ")", "id", "=", "id_path", "[", "0", "]", "return", "len", "(", "id_path", ")", "<=", "2", "and", "(", ...
checks if the specified value is in the form of [server or cluster id][/database]
[ "checks", "if", "the", "specified", "value", "is", "in", "the", "form", "of", "[", "server", "or", "cluster", "id", "]", "[", "/", "database", "]" ]
python
train
35.9
rndusr/torf
torf/_utils.py
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_utils.py#L96-L136
def filepaths(path, exclude=(), hidden=True, empty=True): """ Return list of absolute, sorted file paths path: Path to file or directory exclude: List of file name patterns to exclude hidden: Whether to include hidden files empty: Whether to include empty files Raise PathNotFoundError if p...
[ "def", "filepaths", "(", "path", ",", "exclude", "=", "(", ")", ",", "hidden", "=", "True", ",", "empty", "=", "True", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "raise", "error", ".", "PathNotFoundError", "(", ...
Return list of absolute, sorted file paths path: Path to file or directory exclude: List of file name patterns to exclude hidden: Whether to include hidden files empty: Whether to include empty files Raise PathNotFoundError if path doesn't exist.
[ "Return", "list", "of", "absolute", "sorted", "file", "paths" ]
python
train
34.853659
assamite/creamas
creamas/image.py
https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/image.py#L70-L83
def intensity(image): '''Calculates the average intensity of the pixels in an image. Accepts both RGB and grayscale images. :param image: numpy.ndarray :returns: image intensity :rtype: float ''' if len(image.shape) > 2: # Convert to grayscale image = cv2.cvtColor(image, cv2...
[ "def", "intensity", "(", "image", ")", ":", "if", "len", "(", "image", ".", "shape", ")", ">", "2", ":", "# Convert to grayscale", "image", "=", "cv2", ".", "cvtColor", "(", "image", ",", "cv2", ".", "COLOR_RGB2GRAY", ")", "/", "255", "elif", "issubcla...
Calculates the average intensity of the pixels in an image. Accepts both RGB and grayscale images. :param image: numpy.ndarray :returns: image intensity :rtype: float
[ "Calculates", "the", "average", "intensity", "of", "the", "pixels", "in", "an", "image", ".", "Accepts", "both", "RGB", "and", "grayscale", "images", "." ]
python
train
32.571429
singularityhub/singularity-python
singularity/views/trees.py
https://github.com/singularityhub/singularity-python/blob/498c3433724b332f7493fec632d8daf479f47b82/singularity/views/trees.py#L120-L197
def make_container_tree(folders,files,path_delim="/",parse_files=True): '''make_container_tree will convert a list of folders and files into a json structure that represents a graph. :param folders: a list of folders in the image :param files: a list of files in the folder :param parse_files: return 'fi...
[ "def", "make_container_tree", "(", "folders", ",", "files", ",", "path_delim", "=", "\"/\"", ",", "parse_files", "=", "True", ")", ":", "nodes", "=", "{", "}", "# first we will make a list of nodes", "lookup", "=", "{", "}", "count", "=", "1", "# count will ho...
make_container_tree will convert a list of folders and files into a json structure that represents a graph. :param folders: a list of folders in the image :param files: a list of files in the folder :param parse_files: return 'files' lookup in result, to associate ID of node with files (default True) :p...
[ "make_container_tree", "will", "convert", "a", "list", "of", "folders", "and", "files", "into", "a", "json", "structure", "that", "represents", "a", "graph", ".", ":", "param", "folders", ":", "a", "list", "of", "folders", "in", "the", "image", ":", "param...
python
train
43.679487
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L1508-L1519
def getAttributesList(self): ''' getAttributesList - Get a copy of all attributes as a list of tuples (name, value) ALL values are converted to string and copied, so modifications will not affect the original attributes. If you want types like "style" to work as before...
[ "def", "getAttributesList", "(", "self", ")", ":", "return", "[", "(", "tostr", "(", "name", ")", "[", ":", "]", ",", "tostr", "(", "value", ")", "[", ":", "]", ")", "for", "name", ",", "value", "in", "self", ".", "_attributes", ".", "items", "("...
getAttributesList - Get a copy of all attributes as a list of tuples (name, value) ALL values are converted to string and copied, so modifications will not affect the original attributes. If you want types like "style" to work as before, you'll need to recreate those elements (like StyleA...
[ "getAttributesList", "-", "Get", "a", "copy", "of", "all", "attributes", "as", "a", "list", "of", "tuples", "(", "name", "value", ")" ]
python
train
60.166667
genialis/resolwe
resolwe/flow/utils/stats.py
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/utils/stats.py#L59-L73
def _display_interval(i): """Convert a time interval into a human-readable string. :param i: The interval to convert, in seconds. """ sigils = ["d", "h", "m", "s"] factors = [24 * 60 * 60, 60 * 60, 60, 1] remain = int(i) result = "" for fac, sig in zip(factors, sigils): if remai...
[ "def", "_display_interval", "(", "i", ")", ":", "sigils", "=", "[", "\"d\"", ",", "\"h\"", ",", "\"m\"", ",", "\"s\"", "]", "factors", "=", "[", "24", "*", "60", "*", "60", ",", "60", "*", "60", ",", "60", ",", "1", "]", "remain", "=", "int", ...
Convert a time interval into a human-readable string. :param i: The interval to convert, in seconds.
[ "Convert", "a", "time", "interval", "into", "a", "human", "-", "readable", "string", "." ]
python
train
29
SBRG/ssbio
ssbio/protein/sequence/properties/scratch.py
https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/sequence/properties/scratch.py#L147-L150
def accpro_results(self): """Parse the ACCpro output file and return a dict of secondary structure compositions. """ return ssbio.protein.sequence.utils.fasta.load_fasta_file_as_dict_of_seqs(self.out_accpro)
[ "def", "accpro_results", "(", "self", ")", ":", "return", "ssbio", ".", "protein", ".", "sequence", ".", "utils", ".", "fasta", ".", "load_fasta_file_as_dict_of_seqs", "(", "self", ".", "out_accpro", ")" ]
Parse the ACCpro output file and return a dict of secondary structure compositions.
[ "Parse", "the", "ACCpro", "output", "file", "and", "return", "a", "dict", "of", "secondary", "structure", "compositions", "." ]
python
train
57
lorien/grab
grab/document.py
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L260-L279
def copy(self, new_grab=None): """ Clone the Response object. """ obj = self.__class__() obj.process_grab(new_grab if new_grab else self.grab) copy_keys = ('status', 'code', 'head', 'body', 'total_time', 'connect_time', 'name_lookup_time', ...
[ "def", "copy", "(", "self", ",", "new_grab", "=", "None", ")", ":", "obj", "=", "self", ".", "__class__", "(", ")", "obj", ".", "process_grab", "(", "new_grab", "if", "new_grab", "else", "self", ".", "grab", ")", "copy_keys", "=", "(", "'status'", ",...
Clone the Response object.
[ "Clone", "the", "Response", "object", "." ]
python
train
30
saltstack/salt
salt/modules/win_lgpo.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_lgpo.py#L5386-L5404
def _transform_value(value, policy, transform_type): ''' helper function to transform the policy value into something that more closely matches how the policy is displayed in the gpedit GUI ''' t_kwargs = {} if 'Transform' in policy: if transform_type in policy['Transform']: ...
[ "def", "_transform_value", "(", "value", ",", "policy", ",", "transform_type", ")", ":", "t_kwargs", "=", "{", "}", "if", "'Transform'", "in", "policy", ":", "if", "transform_type", "in", "policy", "[", "'Transform'", "]", ":", "_policydata", "=", "_policy_i...
helper function to transform the policy value into something that more closely matches how the policy is displayed in the gpedit GUI
[ "helper", "function", "to", "transform", "the", "policy", "value", "into", "something", "that", "more", "closely", "matches", "how", "the", "policy", "is", "displayed", "in", "the", "gpedit", "GUI" ]
python
train
39.157895
QUANTAXIS/QUANTAXIS
QUANTAXIS/QAMarket/QAMarket.py
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAMarket/QAMarket.py#L193-L245
def login(self, broker_name, account_cookie, account=None): """login 登录到交易前置 2018-07-02 在实盘中,登录到交易前置后,需要同步资产状态 Arguments: broker_name {[type]} -- [description] account_cookie {[type]} -- [description] Keyword Arguments: account {[type]} -- [descript...
[ "def", "login", "(", "self", ",", "broker_name", ",", "account_cookie", ",", "account", "=", "None", ")", ":", "res", "=", "False", "if", "account", "is", "None", ":", "if", "account_cookie", "not", "in", "self", ".", "session", ".", "keys", "(", ")", ...
login 登录到交易前置 2018-07-02 在实盘中,登录到交易前置后,需要同步资产状态 Arguments: broker_name {[type]} -- [description] account_cookie {[type]} -- [description] Keyword Arguments: account {[type]} -- [description] (default: {None}) Returns: [type] -- [descrip...
[ "login", "登录到交易前置" ]
python
train
31.54717
libyal/dtfabric
dtfabric/reader.py
https://github.com/libyal/dtfabric/blob/0d2b5719fa257f6e5c661a406737ebcf8c8db266/dtfabric/reader.py#L1102-L1126
def _ReadUUIDDataTypeDefinition( self, definitions_registry, definition_values, definition_name, is_member=False): """Reads an UUID data type definition. Args: definitions_registry (DataTypeDefinitionsRegistry): data type definitions registry. definition_values (dict[str, obje...
[ "def", "_ReadUUIDDataTypeDefinition", "(", "self", ",", "definitions_registry", ",", "definition_values", ",", "definition_name", ",", "is_member", "=", "False", ")", ":", "return", "self", ".", "_ReadFixedSizeDataTypeDefinition", "(", "definitions_registry", ",", "defi...
Reads an UUID data type definition. Args: definitions_registry (DataTypeDefinitionsRegistry): data type definitions registry. definition_values (dict[str, object]): definition values. definition_name (str): name of the definition. is_member (Optional[bool]): True if the data type ...
[ "Reads", "an", "UUID", "data", "type", "definition", "." ]
python
train
38.72
python-diamond/Diamond
src/diamond/handler/Handler.py
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/Handler.py#L89-L103
def _flush(self): """ Decorator for flushing handlers with an lock, catching exceptions """ if not self.enabled: return try: try: self.lock.acquire() self.flush() except Exception: self.log.error(...
[ "def", "_flush", "(", "self", ")", ":", "if", "not", "self", ".", "enabled", ":", "return", "try", ":", "try", ":", "self", ".", "lock", ".", "acquire", "(", ")", "self", ".", "flush", "(", ")", "except", "Exception", ":", "self", ".", "log", "."...
Decorator for flushing handlers with an lock, catching exceptions
[ "Decorator", "for", "flushing", "handlers", "with", "an", "lock", "catching", "exceptions" ]
python
train
27.8
DiscordBotList/DBL-Python-Library
dbl/client.py
https://github.com/DiscordBotList/DBL-Python-Library/blob/c1461ae0acc644cdeedef8fd6b5e36f76d81c1aa/dbl/client.py#L351-L359
async def close(self): """This function is a coroutine. Closes all connections.""" if self._is_closed: return else: await self.http.close() self._is_closed = True
[ "async", "def", "close", "(", "self", ")", ":", "if", "self", ".", "_is_closed", ":", "return", "else", ":", "await", "self", ".", "http", ".", "close", "(", ")", "self", ".", "_is_closed", "=", "True" ]
This function is a coroutine. Closes all connections.
[ "This", "function", "is", "a", "coroutine", "." ]
python
test
24.777778
Nekroze/partpy
partpy/sourcestring.py
https://github.com/Nekroze/partpy/blob/dbb7d2fb285464fc43d85bc31f5af46192d301f6/partpy/sourcestring.py#L235-L256
def get_lines(self, first, last): """Return SourceLines for lines between and including first & last.""" line = 1 linestring = [] linestrings = [] for char in self.string: if line >= first and line <= last: linestring.append(char) if ch...
[ "def", "get_lines", "(", "self", ",", "first", ",", "last", ")", ":", "line", "=", "1", "linestring", "=", "[", "]", "linestrings", "=", "[", "]", "for", "char", "in", "self", ".", "string", ":", "if", "line", ">=", "first", "and", "line", "<=", ...
Return SourceLines for lines between and including first & last.
[ "Return", "SourceLines", "for", "lines", "between", "and", "including", "first", "&", "last", "." ]
python
train
33.545455
icgood/pymap
pymap/listtree.py
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/listtree.py#L186-L189
def list(self) -> Iterable[ListEntry]: """Return all the entries in the list tree.""" for entry in self._iter(self._root, ''): yield entry
[ "def", "list", "(", "self", ")", "->", "Iterable", "[", "ListEntry", "]", ":", "for", "entry", "in", "self", ".", "_iter", "(", "self", ".", "_root", ",", "''", ")", ":", "yield", "entry" ]
Return all the entries in the list tree.
[ "Return", "all", "the", "entries", "in", "the", "list", "tree", "." ]
python
train
40.75
20c/twentyc.rpc
twentyc/rpc/client.py
https://github.com/20c/twentyc.rpc/blob/23ff07be55eaf21cc2e1a13c2879710b5bc7f933/twentyc/rpc/client.py#L43-L60
def _request(self, typ, id=0, method='GET', params=None, data=None, url=None): """ send the request, return response obj """ headers = { "Accept": "application/json" } auth = None if self.user: auth = (self.user, self.password) if not url: ...
[ "def", "_request", "(", "self", ",", "typ", ",", "id", "=", "0", ",", "method", "=", "'GET'", ",", "params", "=", "None", ",", "data", "=", "None", ",", "url", "=", "None", ")", ":", "headers", "=", "{", "\"Accept\"", ":", "\"application/json\"", "...
send the request, return response obj
[ "send", "the", "request", "return", "response", "obj" ]
python
train
29.611111
pytroll/satpy
satpy/writers/__init__.py
https://github.com/pytroll/satpy/blob/1f21d20ac686b745fb0da9b4030d139893e066dd/satpy/writers/__init__.py#L186-L281
def add_overlay(orig, area, coast_dir, color=(0, 0, 0), width=0.5, resolution=None, level_coast=1, level_borders=1, fill_value=None, grid=None): """Add coastline, political borders and grid(graticules) to image. Uses ``color`` for feature colors where ``color`` is a 3-element tu...
[ "def", "add_overlay", "(", "orig", ",", "area", ",", "coast_dir", ",", "color", "=", "(", "0", ",", "0", ",", "0", ")", ",", "width", "=", "0.5", ",", "resolution", "=", "None", ",", "level_coast", "=", "1", ",", "level_borders", "=", "1", ",", "...
Add coastline, political borders and grid(graticules) to image. Uses ``color`` for feature colors where ``color`` is a 3-element tuple of integers between 0 and 255 representing (R, G, B). .. warning:: This function currently loses the data mask (alpha band). ``resolution`` is chosen automat...
[ "Add", "coastline", "political", "borders", "and", "grid", "(", "graticules", ")", "to", "image", "." ]
python
train
40.1875
cidrblock/modelsettings
modelsettings/__init__.py
https://github.com/cidrblock/modelsettings/blob/09763c111fb38b3ba7a13cc95ca59e4393fe75ba/modelsettings/__init__.py#L289-L303
def generate_kubernetes(self): """ Generate a sample kubernetes """ example = {} example['spec'] = {} example['spec']['containers'] = [] example['spec']['containers'].append({"name": '', "image": '', "env": []}) for key, value in self.spec.items(): if ...
[ "def", "generate_kubernetes", "(", "self", ")", ":", "example", "=", "{", "}", "example", "[", "'spec'", "]", "=", "{", "}", "example", "[", "'spec'", "]", "[", "'containers'", "]", "=", "[", "]", "example", "[", "'spec'", "]", "[", "'containers'", "...
Generate a sample kubernetes
[ "Generate", "a", "sample", "kubernetes" ]
python
train
45.866667
googleads/googleads-python-lib
googleads/adwords.py
https://github.com/googleads/googleads-python-lib/blob/aa3b1b474b0f9789ca55ca46f4b2b57aeae38874/googleads/adwords.py#L2076-L2080
def _CreateMultipleValuesCondition(self, values, operator): """Creates a condition with the provided list of values and operator.""" values = ['"%s"' % value if isinstance(value, str) or isinstance(value, unicode) else str(value) for value in values] return '%s %s [%s]' % (self._field, operato...
[ "def", "_CreateMultipleValuesCondition", "(", "self", ",", "values", ",", "operator", ")", ":", "values", "=", "[", "'\"%s\"'", "%", "value", "if", "isinstance", "(", "value", ",", "str", ")", "or", "isinstance", "(", "value", ",", "unicode", ")", "else", ...
Creates a condition with the provided list of values and operator.
[ "Creates", "a", "condition", "with", "the", "provided", "list", "of", "values", "and", "operator", "." ]
python
train
67.4
saltstack/salt
salt/modules/win_iis.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L1297-L1383
def set_container_setting(name, container, settings): ''' Set the value of the setting for an IIS container. .. versionadded:: 2016.11.0 Args: name (str): The name of the IIS container. container (str): The type of IIS container. The container types are: AppPools, Sites, Ss...
[ "def", "set_container_setting", "(", "name", ",", "container", ",", "settings", ")", ":", "identityType_map2string", "=", "{", "'0'", ":", "'LocalSystem'", ",", "'1'", ":", "'LocalService'", ",", "'2'", ":", "'NetworkService'", ",", "'3'", ":", "'SpecificUser'",...
Set the value of the setting for an IIS container. .. versionadded:: 2016.11.0 Args: name (str): The name of the IIS container. container (str): The type of IIS container. The container types are: AppPools, Sites, SslBindings settings (dict): A dictionary of the setting nam...
[ "Set", "the", "value", "of", "the", "setting", "for", "an", "IIS", "container", "." ]
python
train
37.494253
log2timeline/plaso
docs/conf.py
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/docs/conf.py#L409-L417
def traverse(self, node): """Traverse the document tree rooted at node. node(node): docutils node. """ self.find_and_replace(node) for c in node.children: self.traverse(c)
[ "def", "traverse", "(", "self", ",", "node", ")", ":", "self", ".", "find_and_replace", "(", "node", ")", "for", "c", "in", "node", ".", "children", ":", "self", ".", "traverse", "(", "c", ")" ]
Traverse the document tree rooted at node. node(node): docutils node.
[ "Traverse", "the", "document", "tree", "rooted", "at", "node", "." ]
python
train
21.222222
yougov/pmxbot
pmxbot/commands.py
https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/commands.py#L554-L577
def stab(nick, rest): "Stab, shank or shiv some(one|thing)!" if rest: stabee = rest else: stabee = 'wildly at anything' if random.random() < 0.9: karma.Karma.store.change(stabee, -1) weapon = random.choice(phrases.weapon_opts) weaponadj = random.choice(phrases.weapon_adjs) violentact = random.choice(phr...
[ "def", "stab", "(", "nick", ",", "rest", ")", ":", "if", "rest", ":", "stabee", "=", "rest", "else", ":", "stabee", "=", "'wildly at anything'", "if", "random", ".", "random", "(", ")", "<", "0.9", ":", "karma", ".", "Karma", ".", "store", ".", "ch...
Stab, shank or shiv some(one|thing)!
[ "Stab", "shank", "or", "shiv", "some", "(", "one|thing", ")", "!" ]
python
train
33.333333
tensorlayer/tensorlayer
tensorlayer/cost.py
https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/cost.py#L307-L340
def iou_coe(output, target, threshold=0.5, axis=(1, 2, 3), smooth=1e-5): """Non-differentiable Intersection over Union (IoU) for comparing the similarity of two batch of data, usually be used for evaluating binary image segmentation. The coefficient between 0 to 1, and 1 means totally match. Parameters...
[ "def", "iou_coe", "(", "output", ",", "target", ",", "threshold", "=", "0.5", ",", "axis", "=", "(", "1", ",", "2", ",", "3", ")", ",", "smooth", "=", "1e-5", ")", ":", "pre", "=", "tf", ".", "cast", "(", "output", ">", "threshold", ",", "dtype...
Non-differentiable Intersection over Union (IoU) for comparing the similarity of two batch of data, usually be used for evaluating binary image segmentation. The coefficient between 0 to 1, and 1 means totally match. Parameters ----------- output : tensor A batch of distribution with shape:...
[ "Non", "-", "differentiable", "Intersection", "over", "Union", "(", "IoU", ")", "for", "comparing", "the", "similarity", "of", "two", "batch", "of", "data", "usually", "be", "used", "for", "evaluating", "binary", "image", "segmentation", ".", "The", "coefficie...
python
valid
41.352941
cons3rt/pycons3rt
pycons3rt/assetmailer.py
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/assetmailer.py#L178-L212
def main(): """Handles external calling for this module Execute this python module and provide the args shown below to external call this module to send email messages! :return: None """ log = logging.getLogger(mod_logger + '.main') parser = argparse.ArgumentParser(description='This module...
[ "def", "main", "(", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "mod_logger", "+", "'.main'", ")", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'This module allows sending email messages.'", ")", "parser", ".", "add_arg...
Handles external calling for this module Execute this python module and provide the args shown below to external call this module to send email messages! :return: None
[ "Handles", "external", "calling", "for", "this", "module" ]
python
train
42.828571
tmux-python/libtmux
libtmux/pane.py
https://github.com/tmux-python/libtmux/blob/8eb2f8bbea3a025c1567b1516653414dbc24e1fc/libtmux/pane.py#L157-L179
def split_window(self, attach=False, vertical=True, start_directory=None): """ Split window at pane and return newly created :class:`Pane`. Parameters ---------- attach : bool, optional Attach / select pane after creation. vertical : bool, optional ...
[ "def", "split_window", "(", "self", ",", "attach", "=", "False", ",", "vertical", "=", "True", ",", "start_directory", "=", "None", ")", ":", "return", "self", ".", "window", ".", "split_window", "(", "target", "=", "self", ".", "get", "(", "'pane_id'", ...
Split window at pane and return newly created :class:`Pane`. Parameters ---------- attach : bool, optional Attach / select pane after creation. vertical : bool, optional split vertically start_directory : str, optional specifies the working di...
[ "Split", "window", "at", "pane", "and", "return", "newly", "created", ":", "class", ":", "Pane", "." ]
python
train
30.217391
noirbizarre/minibench
minibench/runner.py
https://github.com/noirbizarre/minibench/blob/a1ac66dc075181c62bb3c0d3a26beb5c46d5f4ab/minibench/runner.py#L65-L72
def load_module(self, filename): '''Load a benchmark module from file''' if not isinstance(filename, string_types): return filename basename = os.path.splitext(os.path.basename(filename))[0] basename = basename.replace('.bench', '') modulename = 'benchmarks.{0}'.forma...
[ "def", "load_module", "(", "self", ",", "filename", ")", ":", "if", "not", "isinstance", "(", "filename", ",", "string_types", ")", ":", "return", "filename", "basename", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", ...
Load a benchmark module from file
[ "Load", "a", "benchmark", "module", "from", "file" ]
python
train
46.625
Opentrons/opentrons
api/src/opentrons/protocol_api/contexts.py
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/protocol_api/contexts.py#L367-L374
def loaded_instruments(self) -> Dict[str, Optional['InstrumentContext']]: """ Get the instruments that have been loaded into the protocol. :returns: A dict mapping mount names in lowercase to the instrument in that mount, or `None` if no instrument is present. """ retu...
[ "def", "loaded_instruments", "(", "self", ")", "->", "Dict", "[", "str", ",", "Optional", "[", "'InstrumentContext'", "]", "]", ":", "return", "{", "mount", ".", "name", ".", "lower", "(", ")", ":", "instr", "for", "mount", ",", "instr", "in", "self", ...
Get the instruments that have been loaded into the protocol. :returns: A dict mapping mount names in lowercase to the instrument in that mount, or `None` if no instrument is present.
[ "Get", "the", "instruments", "that", "have", "been", "loaded", "into", "the", "protocol", "." ]
python
train
50.625
numenta/htmresearch
projects/energy_based_pooling/energy_based_models/weight_updates.py
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/energy_based_pooling/energy_based_models/weight_updates.py#L39-L81
def numenta(self, X, Y): r""" Method that updates the network's connections. Numenta's classic update: - Visible to hidden: $ \Delta W_{ij} = y_i \cdot ( \varepsilon_{\small{+}} \ x_j - \varepsilon_{\small{-}} \ \bar x_j ) $ - Bias: $ b_{i} = B_b \cdot \alpha_i $ """ batc...
[ "def", "numenta", "(", "self", ",", "X", ",", "Y", ")", ":", "batchSize", "=", "len", "(", "X", ")", "W", "=", "self", ".", "connections", ".", "visible_to_hidden", "n", ",", "m", "=", "W", ".", "shape", "bias", "=", "self", ".", "connections", "...
r""" Method that updates the network's connections. Numenta's classic update: - Visible to hidden: $ \Delta W_{ij} = y_i \cdot ( \varepsilon_{\small{+}} \ x_j - \varepsilon_{\small{-}} \ \bar x_j ) $ - Bias: $ b_{i} = B_b \cdot \alpha_i $
[ "r", "Method", "that", "updates", "the", "network", "s", "connections", ".", "Numenta", "s", "classic", "update", ":" ]
python
train
27.790698
dbcli/cli_helpers
cli_helpers/utils.py
https://github.com/dbcli/cli_helpers/blob/3ebd891ac0c02bad061182dbcb54a47fb21980ae/cli_helpers/utils.py#L45-L47
def filter_dict_by_key(d, keys): """Filter the dict *d* to remove keys not in *keys*.""" return {k: v for k, v in d.items() if k in keys}
[ "def", "filter_dict_by_key", "(", "d", ",", "keys", ")", ":", "return", "{", "k", ":", "v", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", "if", "k", "in", "keys", "}" ]
Filter the dict *d* to remove keys not in *keys*.
[ "Filter", "the", "dict", "*", "d", "*", "to", "remove", "keys", "not", "in", "*", "keys", "*", "." ]
python
test
47.666667
SoCo/SoCo
soco/music_library.py
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_library.py#L124-L132
def get_composers(self, *args, **kwargs): """Convenience method for `get_music_library_information` with ``search_type='composers'``. For details of other arguments, see `that method <#soco.music_library.MusicLibrary.get_music_library_information>`_. """ args = tuple(['c...
[ "def", "get_composers", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "args", "=", "tuple", "(", "[", "'composers'", "]", "+", "list", "(", "args", ")", ")", "return", "self", ".", "get_music_library_information", "(", "*", "args", ...
Convenience method for `get_music_library_information` with ``search_type='composers'``. For details of other arguments, see `that method <#soco.music_library.MusicLibrary.get_music_library_information>`_.
[ "Convenience", "method", "for", "get_music_library_information", "with", "search_type", "=", "composers", ".", "For", "details", "of", "other", "arguments", "see", "that", "method", "<#soco", ".", "music_library", ".", "MusicLibrary", ".", "get_music_library_information...
python
train
44.777778
saltstack/salt
salt/sdb/vault.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/sdb/vault.py#L55-L85
def set_(key, value, profile=None): ''' Set a key/value pair in the vault service ''' if '?' in key: __utils__['versions.warn_until']( 'Neon', ( 'Using ? to seperate between the path and key for vault has been deprecated ' 'and will be remo...
[ "def", "set_", "(", "key", ",", "value", ",", "profile", "=", "None", ")", ":", "if", "'?'", "in", "key", ":", "__utils__", "[", "'versions.warn_until'", "]", "(", "'Neon'", ",", "(", "'Using ? to seperate between the path and key for vault has been deprecated '", ...
Set a key/value pair in the vault service
[ "Set", "a", "key", "/", "value", "pair", "in", "the", "vault", "service" ]
python
train
29.096774
wonambi-python/wonambi
wonambi/ioeeg/text.py
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/text.py#L96-L140
def return_dat(self, chan, begsam, endsam): """Return the data as 2D numpy.ndarray. Parameters ---------- chan : list of int index (indices) of the channels to read begsam : int index of the first sample (inclusively) endsam : int inde...
[ "def", "return_dat", "(", "self", ",", "chan", ",", "begsam", ",", "endsam", ")", ":", "#n_sam = self.hdr[4]", "interval", "=", "endsam", "-", "begsam", "dat", "=", "empty", "(", "(", "len", "(", "chan", ")", ",", "interval", ")", ")", "#beg_block = floo...
Return the data as 2D numpy.ndarray. Parameters ---------- chan : list of int index (indices) of the channels to read begsam : int index of the first sample (inclusively) endsam : int index of the last sample (exclusively) Returns ...
[ "Return", "the", "data", "as", "2D", "numpy", ".", "ndarray", "." ]
python
train
29.777778
PlaidWeb/Publ
publ/utils.py
https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/utils.py#L225-L228
def file_fingerprint(fullpath): """ Get a metadata fingerprint for a file """ stat = os.stat(fullpath) return ','.join([str(value) for value in [stat.st_ino, stat.st_mtime, stat.st_size] if value])
[ "def", "file_fingerprint", "(", "fullpath", ")", ":", "stat", "=", "os", ".", "stat", "(", "fullpath", ")", "return", "','", ".", "join", "(", "[", "str", "(", "value", ")", "for", "value", "in", "[", "stat", ".", "st_ino", ",", "stat", ".", "st_mt...
Get a metadata fingerprint for a file
[ "Get", "a", "metadata", "fingerprint", "for", "a", "file" ]
python
train
51.5
EventRegistry/event-registry-python
eventregistry/QueryArticles.py
https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/QueryArticles.py#L218-L235
def initWithComplexQuery(query): """ create a query using a complex article query """ q = QueryArticles() # provided an instance of ComplexArticleQuery if isinstance(query, ComplexArticleQuery): q._setVal("query", json.dumps(query.getQuery())) # provid...
[ "def", "initWithComplexQuery", "(", "query", ")", ":", "q", "=", "QueryArticles", "(", ")", "# provided an instance of ComplexArticleQuery", "if", "isinstance", "(", "query", ",", "ComplexArticleQuery", ")", ":", "q", ".", "_setVal", "(", "\"query\"", ",", "json",...
create a query using a complex article query
[ "create", "a", "query", "using", "a", "complex", "article", "query" ]
python
train
41.777778
victorlei/smop
smop/parse.py
https://github.com/victorlei/smop/blob/bdad96b715d1dd75ce8ab4724f76b9b1bb1f61cd/smop/parse.py#L72-L80
def p_arg1(p): """ arg1 : STRING | NUMBER | IDENT | GLOBAL """ # a hack to support "clear global" p[0] = node.string(value=str(p[1]), lineno=p.lineno(1), lexpos=p.lexpos(1))
[ "def", "p_arg1", "(", "p", ")", ":", "# a hack to support \"clear global\"", "p", "[", "0", "]", "=", "node", ".", "string", "(", "value", "=", "str", "(", "p", "[", "1", "]", ")", ",", "lineno", "=", "p", ".", "lineno", "(", "1", ")", ",", "lexp...
arg1 : STRING | NUMBER | IDENT | GLOBAL
[ "arg1", ":", "STRING", "|", "NUMBER", "|", "IDENT", "|", "GLOBAL" ]
python
train
23.555556
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgets/reftrackwidget.py
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/reftrackwidget.py#L371-L380
def reference(self, ): """Reference a file :returns: None :rtype: None :raises: None """ tfi = self.get_taskfileinfo_selection() if tfi: self.reftrack.reference(tfi)
[ "def", "reference", "(", "self", ",", ")", ":", "tfi", "=", "self", ".", "get_taskfileinfo_selection", "(", ")", "if", "tfi", ":", "self", ".", "reftrack", ".", "reference", "(", "tfi", ")" ]
Reference a file :returns: None :rtype: None :raises: None
[ "Reference", "a", "file" ]
python
train
22.5
google/prettytensor
prettytensor/layers.py
https://github.com/google/prettytensor/blob/75daa0b11252590f548da5647addc0ea610c4c45/prettytensor/layers.py#L147-L150
def spatial_slice_zeros(x): """Experimental summary that shows how many planes are unused for a batch.""" return tf.cast(tf.reduce_all(tf.less_equal(x, 0.0), [0, 1, 2]), tf.float32)
[ "def", "spatial_slice_zeros", "(", "x", ")", ":", "return", "tf", ".", "cast", "(", "tf", ".", "reduce_all", "(", "tf", ".", "less_equal", "(", "x", ",", "0.0", ")", ",", "[", "0", ",", "1", ",", "2", "]", ")", ",", "tf", ".", "float32", ")" ]
Experimental summary that shows how many planes are unused for a batch.
[ "Experimental", "summary", "that", "shows", "how", "many", "planes", "are", "unused", "for", "a", "batch", "." ]
python
train
49.75
jobovy/galpy
galpy/orbit/OrbitTop.py
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/orbit/OrbitTop.py#L257-L275
def vT(self,*args,**kwargs): """ NAME: vT PURPOSE: return tangential velocity at time t INPUT: t - (optional) time at which to get the tangential velocity vo= (Object-wide default) physical scale for velocities to use to convert use_...
[ "def", "vT", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "thiso", "=", "self", "(", "*", "args", ",", "*", "*", "kwargs", ")", "onet", "=", "(", "len", "(", "thiso", ".", "shape", ")", "==", "1", ")", "if", "onet", ":"...
NAME: vT PURPOSE: return tangential velocity at time t INPUT: t - (optional) time at which to get the tangential velocity vo= (Object-wide default) physical scale for velocities to use to convert use_physical= use to override Object-wide default for...
[ "NAME", ":", "vT", "PURPOSE", ":", "return", "tangential", "velocity", "at", "time", "t", "INPUT", ":", "t", "-", "(", "optional", ")", "time", "at", "which", "to", "get", "the", "tangential", "velocity", "vo", "=", "(", "Object", "-", "wide", "default...
python
train
33.210526
fastai/fastai
docs_src/nbval/plugin.py
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/docs_src/nbval/plugin.py#L221-L235
def setup(self): """ Called by pytest to setup the collector cells in . Here we start a kernel and setup the sanitize patterns. """ if self.parent.config.option.current_env: kernel_name = CURRENT_ENV_KERNEL_NAME else: kernel_name = self.nb.metadat...
[ "def", "setup", "(", "self", ")", ":", "if", "self", ".", "parent", ".", "config", ".", "option", ".", "current_env", ":", "kernel_name", "=", "CURRENT_ENV_KERNEL_NAME", "else", ":", "kernel_name", "=", "self", ".", "nb", ".", "metadata", ".", "get", "("...
Called by pytest to setup the collector cells in . Here we start a kernel and setup the sanitize patterns.
[ "Called", "by", "pytest", "to", "setup", "the", "collector", "cells", "in", ".", "Here", "we", "start", "a", "kernel", "and", "setup", "the", "sanitize", "patterns", "." ]
python
train
42.466667
jmurty/xml4h
xml4h/nodes.py
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/nodes.py#L937-L1008
def add_element(self, name, ns_uri=None, attributes=None, text=None, before_this_element=False): """ Add a new child element to this element, with an optional namespace definition. If no namespace is provided the child will be assigned to the default namespace. :para...
[ "def", "add_element", "(", "self", ",", "name", ",", "ns_uri", "=", "None", ",", "attributes", "=", "None", ",", "text", "=", "None", ",", "before_this_element", "=", "False", ")", ":", "# Determine local name, namespace and prefix info from tag name", "prefix", "...
Add a new child element to this element, with an optional namespace definition. If no namespace is provided the child will be assigned to the default namespace. :param string name: a name for the child node. The name may be used to apply a namespace to the child by including: ...
[ "Add", "a", "new", "child", "element", "to", "this", "element", "with", "an", "optional", "namespace", "definition", ".", "If", "no", "namespace", "is", "provided", "the", "child", "will", "be", "assigned", "to", "the", "default", "namespace", "." ]
python
train
49.736111
awslabs/sockeye
sockeye_contrib/autopilot/autopilot.py
https://github.com/awslabs/sockeye/blob/5d64a1ee1ef3cbba17c6d1d94bc061020c43f6ab/sockeye_contrib/autopilot/autopilot.py#L267-L309
def plain_text_iter(fname: str, text_type: str, data_side: str) -> Iterable[str]: """ Extract plain text from file as iterable. Also take steps to ensure that whitespace characters (including unicode newlines) are normalized and outputs are line-parallel with inputs considering ASCII newlines only. ...
[ "def", "plain_text_iter", "(", "fname", ":", "str", ",", "text_type", ":", "str", ",", "data_side", ":", "str", ")", "->", "Iterable", "[", "str", "]", ":", "if", "text_type", "in", "(", "TEXT_UTF8_RAW", ",", "TEXT_UTF8_TOKENIZED", ")", ":", "with", "thi...
Extract plain text from file as iterable. Also take steps to ensure that whitespace characters (including unicode newlines) are normalized and outputs are line-parallel with inputs considering ASCII newlines only. :param fname: Path of possibly gzipped input file. :param text_type: One of TEXT_*, indi...
[ "Extract", "plain", "text", "from", "file", "as", "iterable", ".", "Also", "take", "steps", "to", "ensure", "that", "whitespace", "characters", "(", "including", "unicode", "newlines", ")", "are", "normalized", "and", "outputs", "are", "line", "-", "parallel",...
python
train
47.604651
jneight/django-earthdistance
django_earthdistance/models.py
https://github.com/jneight/django-earthdistance/blob/d9e620778a8bb49ae8e73ea161fee3e832f1af77/django_earthdistance/models.py#L76-L89
def in_distance(self, distance, fields, points, annotate='_ed_distance'): """Filter rows inside a circunference of radius distance `distance` :param distance: max distance to allow :param fields: `tuple` with the fields to filter (latitude, longitude) :param points: center o...
[ "def", "in_distance", "(", "self", ",", "distance", ",", "fields", ",", "points", ",", "annotate", "=", "'_ed_distance'", ")", ":", "clone", "=", "self", ".", "_clone", "(", ")", "return", "clone", ".", "annotate", "(", "*", "*", "{", "annotate", ":", ...
Filter rows inside a circunference of radius distance `distance` :param distance: max distance to allow :param fields: `tuple` with the fields to filter (latitude, longitude) :param points: center of the circunference (latitude, longitude) :param annotate: name where the...
[ "Filter", "rows", "inside", "a", "circunference", "of", "radius", "distance", "distance" ]
python
train
46.714286
euske/pdfminer
pdfminer/lzw.py
https://github.com/euske/pdfminer/blob/8150458718e9024c80b00e74965510b20206e588/pdfminer/lzw.py#L96-L102
def lzwdecode(data): """ >>> lzwdecode(b'\x80\x0b\x60\x50\x22\x0c\x0c\x85\x01') '\x2d\x2d\x2d\x2d\x2d\x41\x2d\x2d\x2d\x42' """ fp = BytesIO(data) return b''.join(LZWDecoder(fp).run())
[ "def", "lzwdecode", "(", "data", ")", ":", "fp", "=", "BytesIO", "(", "data", ")", "return", "b''", ".", "join", "(", "LZWDecoder", "(", "fp", ")", ".", "run", "(", ")", ")" ]
>>> lzwdecode(b'\x80\x0b\x60\x50\x22\x0c\x0c\x85\x01') '\x2d\x2d\x2d\x2d\x2d\x41\x2d\x2d\x2d\x42'
[ ">>>", "lzwdecode", "(", "b", "\\", "x80", "\\", "x0b", "\\", "x60", "\\", "x50", "\\", "x22", "\\", "x0c", "\\", "x0c", "\\", "x85", "\\", "x01", ")", "\\", "x2d", "\\", "x2d", "\\", "x2d", "\\", "x2d", "\\", "x2d", "\\", "x41", "\\", "x2d", ...
python
train
28.714286
Mxit/python-mxit
mxit/services.py
https://github.com/Mxit/python-mxit/blob/6b18a54ef6fbfe1f9d94755ba3d4ad77743c8b0c/mxit/services.py#L289-L301
def get_gallery_folder_list(self, scope='content/read'): """ Retrieve a list of the Mxit user's gallery folders User authentication required with the following scope: 'content/read' """ folder_list = _get( token=self.oauth.get_user_token(scope), uri='/user...
[ "def", "get_gallery_folder_list", "(", "self", ",", "scope", "=", "'content/read'", ")", ":", "folder_list", "=", "_get", "(", "token", "=", "self", ".", "oauth", ".", "get_user_token", "(", "scope", ")", ",", "uri", "=", "'/user/media'", ")", "try", ":", ...
Retrieve a list of the Mxit user's gallery folders User authentication required with the following scope: 'content/read'
[ "Retrieve", "a", "list", "of", "the", "Mxit", "user", "s", "gallery", "folders", "User", "authentication", "required", "with", "the", "following", "scope", ":", "content", "/", "read" ]
python
train
36.076923
jahuth/litus
spikes.py
https://github.com/jahuth/litus/blob/712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e/spikes.py#L392-L403
def constraint_range_dict(self,*args,**kwargs): """ Creates a list of dictionaries which each give a constraint for a certain section of the dimension. bins arguments overwrites resolution """ bins = self.bins(*args,**kwargs) return [{self.name+'__gt...
[ "def", "constraint_range_dict", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "bins", "=", "self", ".", "bins", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "[", "{", "self", ".", "name", "+", "'__gte'", ":", "a",...
Creates a list of dictionaries which each give a constraint for a certain section of the dimension. bins arguments overwrites resolution
[ "Creates", "a", "list", "of", "dictionaries", "which", "each", "give", "a", "constraint", "for", "a", "certain", "section", "of", "the", "dimension", "." ]
python
train
45.083333
CEA-COSMIC/ModOpt
modopt/signal/noise.py
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/signal/noise.py#L15-L88
def add_noise(data, sigma=1.0, noise_type='gauss'): r"""Add noise to data This method adds Gaussian or Poisson noise to the input data Parameters ---------- data : np.ndarray, list or tuple Input data array sigma : float or list, optional Standard deviation of the noise to be a...
[ "def", "add_noise", "(", "data", ",", "sigma", "=", "1.0", ",", "noise_type", "=", "'gauss'", ")", ":", "data", "=", "np", ".", "array", "(", "data", ")", "if", "noise_type", "not", "in", "(", "'gauss'", ",", "'poisson'", ")", ":", "raise", "ValueErr...
r"""Add noise to data This method adds Gaussian or Poisson noise to the input data Parameters ---------- data : np.ndarray, list or tuple Input data array sigma : float or list, optional Standard deviation of the noise to be added ('gauss' only) noise_type : str {'gauss', 'pois...
[ "r", "Add", "noise", "to", "data" ]
python
train
27.932432
neithere/argh
argh/dispatching.py
https://github.com/neithere/argh/blob/dcd3253f2994400a6a58a700c118c53765bc50a4/argh/dispatching.py#L287-L306
def dispatch_command(function, *args, **kwargs): """ A wrapper for :func:`dispatch` that creates a one-command parser. Uses :attr:`PARSER_FORMATTER`. This:: dispatch_command(foo) ...is a shortcut for:: parser = ArgumentParser() set_default_command(parser, foo) dis...
[ "def", "dispatch_command", "(", "function", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "formatter_class", "=", "PARSER_FORMATTER", ")", "set_default_command", "(", "parser", ",", "function", ")",...
A wrapper for :func:`dispatch` that creates a one-command parser. Uses :attr:`PARSER_FORMATTER`. This:: dispatch_command(foo) ...is a shortcut for:: parser = ArgumentParser() set_default_command(parser, foo) dispatch(parser) This function can be also used as a decora...
[ "A", "wrapper", "for", ":", "func", ":", "dispatch", "that", "creates", "a", "one", "-", "command", "parser", ".", "Uses", ":", "attr", ":", "PARSER_FORMATTER", "." ]
python
test
26.25
Gawen/pytun
pytun.py
https://github.com/Gawen/pytun/blob/a1e1f86a5e2b5ed256e3b87dcdd4f6aedc6cde6d/pytun.py#L184-L194
def set_ipv4(self, ip): """ Sets the IP address (ifr_addr) of the device parameter 'ip' should be string representation of IP address This does the same as ifconfig. """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) bin_ip = socket.inet_aton(ip) ...
[ "def", "set_ipv4", "(", "self", ",", "ip", ")", ":", "sock", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "bin_ip", "=", "socket", ".", "inet_aton", "(", "ip", ")", "ifreq", "=", "struct", ".", ...
Sets the IP address (ifr_addr) of the device parameter 'ip' should be string representation of IP address This does the same as ifconfig.
[ "Sets", "the", "IP", "address", "(", "ifr_addr", ")", "of", "the", "device", "parameter", "ip", "should", "be", "string", "representation", "of", "IP", "address", "This", "does", "the", "same", "as", "ifconfig", "." ]
python
train
56.272727
tensorflow/cleverhans
cleverhans/loss.py
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/loss.py#L453-L464
def masked_pick_probability(x, y, temp, cos_distance): """The pairwise sampling probabilities for the elements of x for neighbor points which share labels. :param x: a matrix :param y: a list of labels for each element of x :param temp: Temperature :cos_distance: Boolean for using cosine or Eucl...
[ "def", "masked_pick_probability", "(", "x", ",", "y", ",", "temp", ",", "cos_distance", ")", ":", "return", "SNNLCrossEntropy", ".", "pick_probability", "(", "x", ",", "temp", ",", "cos_distance", ")", "*", "SNNLCrossEntropy", ".", "same_label_mask", "(", "y",...
The pairwise sampling probabilities for the elements of x for neighbor points which share labels. :param x: a matrix :param y: a list of labels for each element of x :param temp: Temperature :cos_distance: Boolean for using cosine or Euclidean distance :returns: A tensor for the pairwise sampli...
[ "The", "pairwise", "sampling", "probabilities", "for", "the", "elements", "of", "x", "for", "neighbor", "points", "which", "share", "labels", ".", ":", "param", "x", ":", "a", "matrix", ":", "param", "y", ":", "a", "list", "of", "labels", "for", "each", ...
python
train
42.916667
pgjones/quart
quart/blueprints.py
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/blueprints.py#L694-L711
def register( self, app: 'Quart', first_registration: bool, *, url_prefix: Optional[str]=None, ) -> None: """Register this blueprint on the app given.""" state = self.make_setup_state(app, first_registration, url_prefix=url_prefix) ...
[ "def", "register", "(", "self", ",", "app", ":", "'Quart'", ",", "first_registration", ":", "bool", ",", "*", ",", "url_prefix", ":", "Optional", "[", "str", "]", "=", "None", ",", ")", "->", "None", ":", "state", "=", "self", ".", "make_setup_state", ...
Register this blueprint on the app given.
[ "Register", "this", "blueprint", "on", "the", "app", "given", "." ]
python
train
31.833333
tcalmant/ipopo
pelix/utilities.py
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/utilities.py#L551-L574
def to_iterable(value, allow_none=True): """ Tries to convert the given value to an iterable, if necessary. If the given value is a list, a list is returned; if it is a string, a list containing one string is returned, ... :param value: Any object :param allow_none: If True, the method returns ...
[ "def", "to_iterable", "(", "value", ",", "allow_none", "=", "True", ")", ":", "if", "value", "is", "None", ":", "# None given", "if", "allow_none", ":", "return", "None", "return", "[", "]", "elif", "isinstance", "(", "value", ",", "(", "list", ",", "t...
Tries to convert the given value to an iterable, if necessary. If the given value is a list, a list is returned; if it is a string, a list containing one string is returned, ... :param value: Any object :param allow_none: If True, the method returns None if value is None, else it...
[ "Tries", "to", "convert", "the", "given", "value", "to", "an", "iterable", "if", "necessary", ".", "If", "the", "given", "value", "is", "a", "list", "a", "list", "is", "returned", ";", "if", "it", "is", "a", "string", "a", "list", "containing", "one", ...
python
train
30.416667
saltstack/salt
salt/modules/vsphere.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L5285-L5374
def create_cluster(cluster_dict, datacenter=None, cluster=None, service_instance=None): ''' Creates a cluster. Note: cluster_dict['name'] will be overridden by the cluster param value config_dict Dictionary with the config values of the new cluster. datacenter N...
[ "def", "create_cluster", "(", "cluster_dict", ",", "datacenter", "=", "None", ",", "cluster", "=", "None", ",", "service_instance", "=", "None", ")", ":", "# Validate cluster dictionary", "schema", "=", "ESXClusterConfigSchema", ".", "serialize", "(", ")", "try", ...
Creates a cluster. Note: cluster_dict['name'] will be overridden by the cluster param value config_dict Dictionary with the config values of the new cluster. datacenter Name of datacenter containing the cluster. Ignored if already contained by proxy details. Default value ...
[ "Creates", "a", "cluster", "." ]
python
train
38.711111
Duke-GCB/lando-messaging
lando_messaging/workqueue.py
https://github.com/Duke-GCB/lando-messaging/blob/b90ccc79a874714e0776af8badf505bb2b56c0ec/lando_messaging/workqueue.py#L82-L91
def delete_queue(self, queue_name): """ Delete a queue with the specified name. :param queue_name: :return: """ self.connect() channel = self.connection.channel() channel.queue_delete(queue=queue_name) self.close()
[ "def", "delete_queue", "(", "self", ",", "queue_name", ")", ":", "self", ".", "connect", "(", ")", "channel", "=", "self", ".", "connection", ".", "channel", "(", ")", "channel", ".", "queue_delete", "(", "queue", "=", "queue_name", ")", "self", ".", "...
Delete a queue with the specified name. :param queue_name: :return:
[ "Delete", "a", "queue", "with", "the", "specified", "name", ".", ":", "param", "queue_name", ":", ":", "return", ":" ]
python
train
27.7
jbloomlab/phydms
phydmslib/weblogo.py
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/weblogo.py#L83-L104
def MWColorMapping(maptype='jet', reverse=True): """Maps amino-acid molecular weights to colors. Otherwise, this function is identical to *KyteDoolittleColorMapping* """ d = {'A':89,'R':174,'N':132,'D':133,'C':121,'Q':146,'E':147,\ 'G':75,'H':155,'I':131,'L':131,'K':146,'M':149,'F':165,\ ...
[ "def", "MWColorMapping", "(", "maptype", "=", "'jet'", ",", "reverse", "=", "True", ")", ":", "d", "=", "{", "'A'", ":", "89", ",", "'R'", ":", "174", ",", "'N'", ":", "132", ",", "'D'", ":", "133", ",", "'C'", ":", "121", ",", "'Q'", ":", "1...
Maps amino-acid molecular weights to colors. Otherwise, this function is identical to *KyteDoolittleColorMapping*
[ "Maps", "amino", "-", "acid", "molecular", "weights", "to", "colors", ".", "Otherwise", "this", "function", "is", "identical", "to", "*", "KyteDoolittleColorMapping", "*" ]
python
train
40.227273
inasafe/inasafe
safe/messaging/item/cell.py
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/messaging/item/cell.py#L104-L141
def to_html(self): """Render a Cell MessageElement as html :returns: The html representation of the Cell MessageElement :rtype: basestring """ # Apply bootstrap alignment classes first if self.align is 'left': if self.style_class is None: self...
[ "def", "to_html", "(", "self", ")", ":", "# Apply bootstrap alignment classes first", "if", "self", ".", "align", "is", "'left'", ":", "if", "self", ".", "style_class", "is", "None", ":", "self", ".", "style_class", "=", "'text-left'", "else", ":", "self", "...
Render a Cell MessageElement as html :returns: The html representation of the Cell MessageElement :rtype: basestring
[ "Render", "a", "Cell", "MessageElement", "as", "html" ]
python
train
39.105263
neuropsychology/NeuroKit.py
neurokit/bio/bio_eda.py
https://github.com/neuropsychology/NeuroKit.py/blob/c9589348fbbde0fa7e986048c48f38e6b488adfe/neurokit/bio/bio_eda.py#L458-L595
def eda_EventRelated(epoch, event_length, window_post=4): """ Extract event-related EDA and Skin Conductance Response (SCR). Parameters ---------- epoch : pandas.DataFrame An epoch contains in the epochs dict returned by :function:`neurokit.create_epochs()` on dataframe returned by :functio...
[ "def", "eda_EventRelated", "(", "epoch", ",", "event_length", ",", "window_post", "=", "4", ")", ":", "# Initialization", "EDA_Response", "=", "{", "}", "window_end", "=", "event_length", "+", "window_post", "# Sanity check", "if", "epoch", ".", "index", "[", ...
Extract event-related EDA and Skin Conductance Response (SCR). Parameters ---------- epoch : pandas.DataFrame An epoch contains in the epochs dict returned by :function:`neurokit.create_epochs()` on dataframe returned by :function:`neurokit.bio_process()`. Index must range from -4s to +4s (relative...
[ "Extract", "event", "-", "related", "EDA", "and", "Skin", "Conductance", "Response", "(", "SCR", ")", "." ]
python
train
35.688406
Telefonica/toolium
toolium/pageobjects/page_object.py
https://github.com/Telefonica/toolium/blob/56847c243b3a98876df74c184b75e43f8810e475/toolium/pageobjects/page_object.py#L60-L69
def _get_page_elements(self): """Return page elements and page objects of this page object :returns: list of page elements and page objects """ page_elements = [] for attribute, value in list(self.__dict__.items()) + list(self.__class__.__dict__.items()): if attribut...
[ "def", "_get_page_elements", "(", "self", ")", ":", "page_elements", "=", "[", "]", "for", "attribute", ",", "value", "in", "list", "(", "self", ".", "__dict__", ".", "items", "(", ")", ")", "+", "list", "(", "self", ".", "__class__", ".", "__dict__", ...
Return page elements and page objects of this page object :returns: list of page elements and page objects
[ "Return", "page", "elements", "and", "page", "objects", "of", "this", "page", "object" ]
python
train
43.4