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
sethmlarson/virtualbox-python
virtualbox/library.py
https://github.com/sethmlarson/virtualbox-python/blob/706c8e3f6e3aee17eb06458e73cbb4bc2d37878b/virtualbox/library.py#L16309-L16343
def add_disk_encryption_passwords(self, ids, passwords, clear_on_suspend): """Adds a password used for hard disk encryption/decryption. in ids of type str List of identifiers for the passwords. Must match the identifier used when the encrypted medium was created. in pas...
[ "def", "add_disk_encryption_passwords", "(", "self", ",", "ids", ",", "passwords", ",", "clear_on_suspend", ")", ":", "if", "not", "isinstance", "(", "ids", ",", "list", ")", ":", "raise", "TypeError", "(", "\"ids can only be an instance of type list\"", ")", "for...
Adds a password used for hard disk encryption/decryption. in ids of type str List of identifiers for the passwords. Must match the identifier used when the encrypted medium was created. in passwords of type str List of passwords. in clear_on_suspend of type...
[ "Adds", "a", "password", "used", "for", "hard", "disk", "encryption", "/", "decryption", "." ]
python
train
45.085714
softlayer/softlayer-python
SoftLayer/shell/cmd_help.py
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/shell/cmd_help.py#L15-L40
def cli(ctx, env): """Print shell help text.""" env.out("Welcome to the SoftLayer shell.") env.out("") formatter = formatting.HelpFormatter() commands = [] shell_commands = [] for name in cli_core.cli.list_commands(ctx): command = cli_core.cli.get_command(ctx, name) if comma...
[ "def", "cli", "(", "ctx", ",", "env", ")", ":", "env", ".", "out", "(", "\"Welcome to the SoftLayer shell.\"", ")", "env", ".", "out", "(", "\"\"", ")", "formatter", "=", "formatting", ".", "HelpFormatter", "(", ")", "commands", "=", "[", "]", "shell_com...
Print shell help text.
[ "Print", "shell", "help", "text", "." ]
python
train
30.230769
brandon-rhodes/uncommitted
uncommitted/command.py
https://github.com/brandon-rhodes/uncommitted/blob/80ebd95a3735e26bd8b9b7b62ff25e1e749a7472/uncommitted/command.py#L50-L65
def find_repositories_with_locate(path): """Use locate to return a sequence of (directory, dotdir) pairs.""" command = [b'locate', b'-0'] for dotdir in DOTDIRS: # Escaping the slash (using '\/' rather than '/') is an # important signal to locate(1) that these glob patterns are # supp...
[ "def", "find_repositories_with_locate", "(", "path", ")", ":", "command", "=", "[", "b'locate'", ",", "b'-0'", "]", "for", "dotdir", "in", "DOTDIRS", ":", "# Escaping the slash (using '\\/' rather than '/') is an", "# important signal to locate(1) that these glob patterns are",...
Use locate to return a sequence of (directory, dotdir) pairs.
[ "Use", "locate", "to", "return", "a", "sequence", "of", "(", "directory", "dotdir", ")", "pairs", "." ]
python
train
48.375
idlesign/uwsgiconf
uwsgiconf/runtime/caching.py
https://github.com/idlesign/uwsgiconf/blob/475407acb44199edbf7e0a66261bfeb51de1afae/uwsgiconf/runtime/caching.py#L138-L147
def div(self, key, value=2): """Divides the specified key value by the specified value. :param str|unicode key: :param int value: :rtype: bool """ return uwsgi.cache_mul(key, value, self.timeout, self.name)
[ "def", "div", "(", "self", ",", "key", ",", "value", "=", "2", ")", ":", "return", "uwsgi", ".", "cache_mul", "(", "key", ",", "value", ",", "self", ".", "timeout", ",", "self", ".", "name", ")" ]
Divides the specified key value by the specified value. :param str|unicode key: :param int value: :rtype: bool
[ "Divides", "the", "specified", "key", "value", "by", "the", "specified", "value", "." ]
python
train
24.8
ARMmbed/icetea
icetea_lib/tools/HTTP/Api.py
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/HTTP/Api.py#L136-L170
def post(self, path, data=None, json=None, headers=None, **kwargs): """ Sends a POST request to host/path. :param path: String, resource path on server :param data: Dictionary, bytes or file-like object to send in the body of the request :param json: JSON formatted data to send ...
[ "def", "post", "(", "self", ",", "path", ",", "data", "=", "None", ",", "json", "=", "None", ",", "headers", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "headers", "is", "not", "None", ":", "merger", "=", "jsonmerge", ".", "Merger", "("...
Sends a POST request to host/path. :param path: String, resource path on server :param data: Dictionary, bytes or file-like object to send in the body of the request :param json: JSON formatted data to send in the body of the request :param headers: Dictionary of HTTP headers to be sent...
[ "Sends", "a", "POST", "request", "to", "host", "/", "path", "." ]
python
train
39.514286
crate/crate-python
src/crate/client/http.py
https://github.com/crate/crate-python/blob/68e39c95f5bbe88b74bbfa26de4347fc644636a8/src/crate/client/http.py#L453-L484
def _get_server(self): """ Get server to use for request. Also process inactive server list, re-add them after given interval. """ with self._lock: inactive_server_count = len(self._inactive_servers) for i in range(inactive_server_count): t...
[ "def", "_get_server", "(", "self", ")", ":", "with", "self", ".", "_lock", ":", "inactive_server_count", "=", "len", "(", "self", ".", "_inactive_servers", ")", "for", "i", "in", "range", "(", "inactive_server_count", ")", ":", "try", ":", "ts", ",", "se...
Get server to use for request. Also process inactive server list, re-add them after given interval.
[ "Get", "server", "to", "use", "for", "request", ".", "Also", "process", "inactive", "server", "list", "re", "-", "add", "them", "after", "given", "interval", "." ]
python
train
40.25
sixty-north/added-value
source/added_value/pyobj_role.py
https://github.com/sixty-north/added-value/blob/7ae75b56712822b074fc874612d6058bb7d16a1e/source/added_value/pyobj_role.py#L10-L40
def pyobj_role(make_node, name, rawtext, text, lineno, inliner, options=None, content=None): """Include Python object value, rendering it to text using str. Returns 2 part tuple containing list of nodes to insert into the document and a list of system messages. Both are allowed to be empty. :para...
[ "def", "pyobj_role", "(", "make_node", ",", "name", ",", "rawtext", ",", "text", ",", "lineno", ",", "inliner", ",", "options", "=", "None", ",", "content", "=", "None", ")", ":", "if", "options", "is", "None", ":", "options", "=", "{", "}", "if", ...
Include Python object value, rendering it to text using str. Returns 2 part tuple containing list of nodes to insert into the document and a list of system messages. Both are allowed to be empty. :param make_node: A callable which accepts (rawtext, app, prefixed_name, obj, parent, modname, options) a...
[ "Include", "Python", "object", "value", "rendering", "it", "to", "text", "using", "str", "." ]
python
train
43.548387
sassoftware/saspy
saspy/sasbase.py
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasbase.py#L733-L753
def read_csv(self, file: str, table: str = '_csv', libref: str = '', results: str = '', opts: dict = None) -> 'SASdata': """ :param file: either the OS filesystem path of the file, or HTTP://... for a url accessible file :param table: the name of the SAS Data Set to create ...
[ "def", "read_csv", "(", "self", ",", "file", ":", "str", ",", "table", ":", "str", "=", "'_csv'", ",", "libref", ":", "str", "=", "''", ",", "results", ":", "str", "=", "''", ",", "opts", ":", "dict", "=", "None", ")", "->", "'SASdata'", ":", "...
:param file: either the OS filesystem path of the file, or HTTP://... for a url accessible file :param table: the name of the SAS Data Set to create :param libref: the libref for the SAS Data Set being created. Defaults to WORK, or USER if assigned :param results: format of results, SASsession.r...
[ ":", "param", "file", ":", "either", "the", "OS", "filesystem", "path", "of", "the", "file", "or", "HTTP", ":", "//", "...", "for", "a", "url", "accessible", "file", ":", "param", "table", ":", "the", "name", "of", "the", "SAS", "Data", "Set", "to", ...
python
train
47.714286
rodricios/eatiht
eatiht/eatiht.py
https://github.com/rodricios/eatiht/blob/7341c46327cfe7e0c9f226ef5e9808975c4d43da/eatiht/eatiht.py#L189-L216
def get_sentence_xpath_tuples(filename_url_or_filelike, xpath_to_text=TEXT_FINDER_XPATH): """ Given a url and xpath, this function will download, parse, then iterate though queried text-nodes. From the resulting text-nodes, extract a list of (text, exact-xpath) tuples....
[ "def", "get_sentence_xpath_tuples", "(", "filename_url_or_filelike", ",", "xpath_to_text", "=", "TEXT_FINDER_XPATH", ")", ":", "parsed_html", "=", "get_html_tree", "(", "filename_url_or_filelike", ")", "try", ":", "xpath_finder", "=", "parsed_html", ".", "getroot", "(",...
Given a url and xpath, this function will download, parse, then iterate though queried text-nodes. From the resulting text-nodes, extract a list of (text, exact-xpath) tuples.
[ "Given", "a", "url", "and", "xpath", "this", "function", "will", "download", "parse", "then", "iterate", "though", "queried", "text", "-", "nodes", ".", "From", "the", "resulting", "text", "-", "nodes", "extract", "a", "list", "of", "(", "text", "exact", ...
python
train
36.535714
kensho-technologies/graphql-compiler
graphql_compiler/compiler/blocks.py
https://github.com/kensho-technologies/graphql-compiler/blob/f6079c6d10f64932f6b3af309b79bcea2123ca8f/graphql_compiler/compiler/blocks.py#L446-L450
def validate(self): """Ensure the Fold block is valid.""" if not isinstance(self.fold_scope_location, FoldScopeLocation): raise TypeError(u'Expected a FoldScopeLocation for fold_scope_location, got: {} ' u'{}'.format(type(self.fold_scope_location), self.fold_scope...
[ "def", "validate", "(", "self", ")", ":", "if", "not", "isinstance", "(", "self", ".", "fold_scope_location", ",", "FoldScopeLocation", ")", ":", "raise", "TypeError", "(", "u'Expected a FoldScopeLocation for fold_scope_location, got: {} '", "u'{}'", ".", "format", "(...
Ensure the Fold block is valid.
[ "Ensure", "the", "Fold", "block", "is", "valid", "." ]
python
train
65.4
titilambert/pyebox
pyebox/client.py
https://github.com/titilambert/pyebox/blob/f35fb75ab5f0df38e1d16a0420e4c13b4908c63d/pyebox/client.py#L192-L197
def close_session(self): """Close current session.""" if not self._session.closed: if self._session._connector_owner: self._session._connector.close() self._session._connector = None
[ "def", "close_session", "(", "self", ")", ":", "if", "not", "self", ".", "_session", ".", "closed", ":", "if", "self", ".", "_session", ".", "_connector_owner", ":", "self", ".", "_session", ".", "_connector", ".", "close", "(", ")", "self", ".", "_ses...
Close current session.
[ "Close", "current", "session", "." ]
python
train
38.833333
marrabld/planarradpy
libplanarradpy/planrad.py
https://github.com/marrabld/planarradpy/blob/5095d1cb98d4f67a7c3108c9282f2d59253e89a8/libplanarradpy/planrad.py#L324-L330
def update_filenames(self): """Does nothing currently. May not need this method""" self.sky_file = os.path.abspath(os.path.join(os.path.join(self.input_path, 'sky_files'), 'sky_' + self.sky_state + '_z' + str( ...
[ "def", "update_filenames", "(", "self", ")", ":", "self", ".", "sky_file", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "join", "(", "self", ".", "input_path", ",", "'sky_files'", ")", ",...
Does nothing currently. May not need this method
[ "Does", "nothing", "currently", ".", "May", "not", "need", "this", "method" ]
python
test
77.857143
last-partizan/pytils
pytils/templatetags/pytils_translit.py
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/templatetags/pytils_translit.py#L36-L43
def detranslify(text): """Detranslify russian text""" try: res = translit.detranslify(text) except Exception as err: # because filter must die silently res = default_value % {'error': err, 'value': text} return res
[ "def", "detranslify", "(", "text", ")", ":", "try", ":", "res", "=", "translit", ".", "detranslify", "(", "text", ")", "except", "Exception", "as", "err", ":", "# because filter must die silently", "res", "=", "default_value", "%", "{", "'error'", ":", "err"...
Detranslify russian text
[ "Detranslify", "russian", "text" ]
python
train
30.875
hobson/aima
aima/search.py
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L739-L741
def score(self): "The total score for the words found, according to the rules." return sum([self.scores[len(w)] for w in self.words()])
[ "def", "score", "(", "self", ")", ":", "return", "sum", "(", "[", "self", ".", "scores", "[", "len", "(", "w", ")", "]", "for", "w", "in", "self", ".", "words", "(", ")", "]", ")" ]
The total score for the words found, according to the rules.
[ "The", "total", "score", "for", "the", "words", "found", "according", "to", "the", "rules", "." ]
python
valid
49.666667
francois-vincent/clingon
clingon/clingon.py
https://github.com/francois-vincent/clingon/blob/afc9db073dbc72b2562ce3e444152986a555dcbf/clingon/clingon.py#L147-L163
def eval_option_value(self, option): """ Evaluates an option :param option: a string :return: an object of type str, bool, int, float or list """ try: value = eval(option, {}, {}) except (SyntaxError, NameError, TypeError): return option if...
[ "def", "eval_option_value", "(", "self", ",", "option", ")", ":", "try", ":", "value", "=", "eval", "(", "option", ",", "{", "}", ",", "{", "}", ")", "except", "(", "SyntaxError", ",", "NameError", ",", "TypeError", ")", ":", "return", "option", "if"...
Evaluates an option :param option: a string :return: an object of type str, bool, int, float or list
[ "Evaluates", "an", "option", ":", "param", "option", ":", "a", "string", ":", "return", ":", "an", "object", "of", "type", "str", "bool", "int", "float", "or", "list" ]
python
train
37.705882
mozillazg/python-shanbay
shanbay/__init__.py
https://github.com/mozillazg/python-shanbay/blob/d505ba614dc13a36afce46969d13fc64e10dde0d/shanbay/__init__.py#L68-L82
def login(self, **kwargs): """登录""" payload = { 'username': self.username, 'password': self.password, } headers = kwargs.setdefault('headers', {}) headers.setdefault( 'Referer', 'https://www.shanbay.com/web/account/login' ) ...
[ "def", "login", "(", "self", ",", "*", "*", "kwargs", ")", ":", "payload", "=", "{", "'username'", ":", "self", ".", "username", ",", "'password'", ":", "self", ".", "password", ",", "}", "headers", "=", "kwargs", ".", "setdefault", "(", "'headers'", ...
登录
[ "登录" ]
python
train
34.266667
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/_backends/billing/models/service_package_quota_history_response.py
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/_backends/billing/models/service_package_quota_history_response.py#L182-L199
def object(self, object): """ Sets the object of this ServicePackageQuotaHistoryResponse. Always set to 'service-package-quota-history'. :param object: The object of this ServicePackageQuotaHistoryResponse. :type: str """ if object is None: raise Valu...
[ "def", "object", "(", "self", ",", "object", ")", ":", "if", "object", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid value for `object`, must not be `None`\"", ")", "allowed_values", "=", "[", "\"service-package-quota-history\"", "]", "if", "object", "no...
Sets the object of this ServicePackageQuotaHistoryResponse. Always set to 'service-package-quota-history'. :param object: The object of this ServicePackageQuotaHistoryResponse. :type: str
[ "Sets", "the", "object", "of", "this", "ServicePackageQuotaHistoryResponse", ".", "Always", "set", "to", "service", "-", "package", "-", "quota", "-", "history", "." ]
python
train
36.277778
HazyResearch/metal
metal/classifier.py
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/classifier.py#L172-L289
def _train_model( self, train_data, loss_fn, valid_data=None, log_writer=None, restore_state={} ): """The internal training routine called by train_model() after setup Args: train_data: a tuple of Tensors (X,Y), a Dataset, or a DataLoader of X (data) and Y (label...
[ "def", "_train_model", "(", "self", ",", "train_data", ",", "loss_fn", ",", "valid_data", "=", "None", ",", "log_writer", "=", "None", ",", "restore_state", "=", "{", "}", ")", ":", "# Set model to train mode", "self", ".", "train", "(", ")", "train_config",...
The internal training routine called by train_model() after setup Args: train_data: a tuple of Tensors (X,Y), a Dataset, or a DataLoader of X (data) and Y (labels) for the train split loss_fn: the loss function to minimize (maps *data -> loss) valid_data: a t...
[ "The", "internal", "training", "routine", "called", "by", "train_model", "()", "after", "setup" ]
python
train
36.008475
upsight/doctor
doctor/docs/base.py
https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/docs/base.py#L124-L139
def get_object_reference(obj: Object) -> str: """Gets an object reference string from the obj instance. This adds the object type to ALL_RESOURCES so that it gets documented and returns a str which contains a sphinx reference to the documented object. :param obj: The Object instance. :returns: A s...
[ "def", "get_object_reference", "(", "obj", ":", "Object", ")", "->", "str", ":", "resource_name", "=", "obj", ".", "title", "if", "resource_name", "is", "None", ":", "class_name", "=", "obj", ".", "__name__", "resource_name", "=", "class_name_to_resource_name", ...
Gets an object reference string from the obj instance. This adds the object type to ALL_RESOURCES so that it gets documented and returns a str which contains a sphinx reference to the documented object. :param obj: The Object instance. :returns: A sphinx docs reference str.
[ "Gets", "an", "object", "reference", "string", "from", "the", "obj", "instance", "." ]
python
train
40.0625
deepmind/pysc2
pysc2/lib/renderer_human.py
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L669-L679
def get_mouse_pos(self, window_pos=None): """Return a MousePos filled with the world position and surf it hit.""" window_pos = window_pos or pygame.mouse.get_pos() # +0.5 to center the point on the middle of the pixel. window_pt = point.Point(*window_pos) + 0.5 for surf in reversed(self._surfaces): ...
[ "def", "get_mouse_pos", "(", "self", ",", "window_pos", "=", "None", ")", ":", "window_pos", "=", "window_pos", "or", "pygame", ".", "mouse", ".", "get_pos", "(", ")", "# +0.5 to center the point on the middle of the pixel.", "window_pt", "=", "point", ".", "Point...
Return a MousePos filled with the world position and surf it hit.
[ "Return", "a", "MousePos", "filled", "with", "the", "world", "position", "and", "surf", "it", "hit", "." ]
python
train
51
nephics/mat4py
mat4py/savemat.py
https://github.com/nephics/mat4py/blob/6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1/mat4py/savemat.py#L207-L225
def write_numeric_array(fd, header, array): """Write the numeric array""" # make a memory file for writing array data bd = BytesIO() # write matrix header to memory file write_var_header(bd, header) if not isinstance(array, basestring) and header['dims'][0] > 1: # list array data in co...
[ "def", "write_numeric_array", "(", "fd", ",", "header", ",", "array", ")", ":", "# make a memory file for writing array data", "bd", "=", "BytesIO", "(", ")", "# write matrix header to memory file", "write_var_header", "(", "bd", ",", "header", ")", "if", "not", "is...
Write the numeric array
[ "Write", "the", "numeric", "array" ]
python
valid
29.842105
edx/edx-enterprise
enterprise/api/v1/decorators.py
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/decorators.py#L55-L91
def require_at_least_one_query_parameter(*query_parameter_names): """ Ensure at least one of the specified query parameters are included in the request. This decorator checks for the existence of at least one of the specified query parameters and passes the values as function parameters to the decorate...
[ "def", "require_at_least_one_query_parameter", "(", "*", "query_parameter_names", ")", ":", "def", "outer_wrapper", "(", "view", ")", ":", "\"\"\" Allow the passing of parameters to require_at_least_one_query_parameter. \"\"\"", "@", "wraps", "(", "view", ")", "def", "wrapper...
Ensure at least one of the specified query parameters are included in the request. This decorator checks for the existence of at least one of the specified query parameters and passes the values as function parameters to the decorated view. If none of the specified query parameters are included in the requ...
[ "Ensure", "at", "least", "one", "of", "the", "specified", "query", "parameters", "are", "included", "in", "the", "request", "." ]
python
valid
46.648649
synw/dataswim
dataswim/data/count.py
https://github.com/synw/dataswim/blob/4a4a53f80daa7cd8e8409d76a19ce07296269da2/dataswim/data/count.py#L35-L44
def count_(self): """ Returns the number of rows of the main dataframe """ try: num = len(self.df.index) except Exception as e: self.err(e, "Can not count data") return return num
[ "def", "count_", "(", "self", ")", ":", "try", ":", "num", "=", "len", "(", "self", ".", "df", ".", "index", ")", "except", "Exception", "as", "e", ":", "self", ".", "err", "(", "e", ",", "\"Can not count data\"", ")", "return", "return", "num" ]
Returns the number of rows of the main dataframe
[ "Returns", "the", "number", "of", "rows", "of", "the", "main", "dataframe" ]
python
train
25.4
MozillaSecurity/laniakea
laniakea/core/providers/packet/manager.py
https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/packet/manager.py#L216-L224
def attach_volume_to_device(self, volume_id, device_id): """Attaches the created Volume to a Device. """ try: volume = self.manager.get_volume(volume_id) volume.attach(device_id) except packet.baseapi.Error as msg: raise PacketManagerException(msg) ...
[ "def", "attach_volume_to_device", "(", "self", ",", "volume_id", ",", "device_id", ")", ":", "try", ":", "volume", "=", "self", ".", "manager", ".", "get_volume", "(", "volume_id", ")", "volume", ".", "attach", "(", "device_id", ")", "except", "packet", "....
Attaches the created Volume to a Device.
[ "Attaches", "the", "created", "Volume", "to", "a", "Device", "." ]
python
train
36.666667
leetrout/python-nutritionix
nutritionix.py
https://github.com/leetrout/python-nutritionix/blob/2f900bf78dce5928b2a1c9d568f87e0c1d81455f/nutritionix.py#L38-L47
def mock_attr(self, *args, **kwargs): """ Empty method to call to slurp up args and kwargs. `args` get pushed onto the url path. `kwargs` are converted to a query string and appended to the URL. """ self.path.extend(args) self.qs.update(kwargs) return sel...
[ "def", "mock_attr", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "path", ".", "extend", "(", "args", ")", "self", ".", "qs", ".", "update", "(", "kwargs", ")", "return", "self" ]
Empty method to call to slurp up args and kwargs. `args` get pushed onto the url path. `kwargs` are converted to a query string and appended to the URL.
[ "Empty", "method", "to", "call", "to", "slurp", "up", "args", "and", "kwargs", "." ]
python
train
31.2
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/thread.py
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/thread.py#L269-L295
def open_handle(self, dwDesiredAccess = win32.THREAD_ALL_ACCESS): """ Opens a new handle to the thread, closing the previous one. The new handle is stored in the L{hThread} property. @warn: Normally you should call L{get_handle} instead, since it's much "smarter" and tries ...
[ "def", "open_handle", "(", "self", ",", "dwDesiredAccess", "=", "win32", ".", "THREAD_ALL_ACCESS", ")", ":", "hThread", "=", "win32", ".", "OpenThread", "(", "dwDesiredAccess", ",", "win32", ".", "FALSE", ",", "self", ".", "dwThreadId", ")", "# In case hThread...
Opens a new handle to the thread, closing the previous one. The new handle is stored in the L{hThread} property. @warn: Normally you should call L{get_handle} instead, since it's much "smarter" and tries to reuse handles and merge access rights. @type dwDesiredAccess: int ...
[ "Opens", "a", "new", "handle", "to", "the", "thread", "closing", "the", "previous", "one", "." ]
python
train
45.37037
aio-libs/aiomysql
aiomysql/cursors.py
https://github.com/aio-libs/aiomysql/blob/131fb9f914739ff01a24b402d29bfd719f2d1a8b/aiomysql/cursors.py#L181-L193
async def nextset(self): """Get the next query set""" conn = self._get_db() current_result = self._result if current_result is None or current_result is not conn._result: return if not current_result.has_next: return self._result = None sel...
[ "async", "def", "nextset", "(", "self", ")", ":", "conn", "=", "self", ".", "_get_db", "(", ")", "current_result", "=", "self", ".", "_result", "if", "current_result", "is", "None", "or", "current_result", "is", "not", "conn", ".", "_result", ":", "retur...
Get the next query set
[ "Get", "the", "next", "query", "set" ]
python
train
31.846154
chaoss/grimoirelab-perceval
perceval/backend.py
https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backend.py#L404-L412
def _set_output_arguments(self): """Activate output arguments parsing""" group = self.parser.add_argument_group('output arguments') group.add_argument('-o', '--output', type=argparse.FileType('w'), dest='outfile', default=sys.stdout, help="o...
[ "def", "_set_output_arguments", "(", "self", ")", ":", "group", "=", "self", ".", "parser", ".", "add_argument_group", "(", "'output arguments'", ")", "group", ".", "add_argument", "(", "'-o'", ",", "'--output'", ",", "type", "=", "argparse", ".", "FileType", ...
Activate output arguments parsing
[ "Activate", "output", "arguments", "parsing" ]
python
test
53.444444
twisted/mantissa
xmantissa/websession.py
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/websession.py#L300-L311
def savorSessionCookie(self, request): """ Make the session cookie last as long as the persistent session. @type request: L{nevow.inevow.IRequest} @param request: The HTTP request object for the guard login URL. """ cookieValue = request.getSession().uid request....
[ "def", "savorSessionCookie", "(", "self", ",", "request", ")", ":", "cookieValue", "=", "request", ".", "getSession", "(", ")", ".", "uid", "request", ".", "addCookie", "(", "self", ".", "cookieKey", ",", "cookieValue", ",", "path", "=", "'/'", ",", "max...
Make the session cookie last as long as the persistent session. @type request: L{nevow.inevow.IRequest} @param request: The HTTP request object for the guard login URL.
[ "Make", "the", "session", "cookie", "last", "as", "long", "as", "the", "persistent", "session", "." ]
python
train
39.666667
google/transitfeed
transitfeed/problems.py
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/problems.py#L431-L440
def ContextTupleToDict(context): """Convert a tuple representing a context into a dict of (key, value) pairs """ d = {} if not context: return d for k, v in zip(ExceptionWithContext.CONTEXT_PARTS, context): if v != '' and v != None: # Don't ignore int(0), a valid row_num d[k] = ...
[ "def", "ContextTupleToDict", "(", "context", ")", ":", "d", "=", "{", "}", "if", "not", "context", ":", "return", "d", "for", "k", ",", "v", "in", "zip", "(", "ExceptionWithContext", ".", "CONTEXT_PARTS", ",", "context", ")", ":", "if", "v", "!=", "'...
Convert a tuple representing a context into a dict of (key, value) pairs
[ "Convert", "a", "tuple", "representing", "a", "context", "into", "a", "dict", "of", "(", "key", "value", ")", "pairs" ]
python
train
32.5
yvesalexandre/bandicoot
bandicoot/spatial.py
https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/spatial.py#L133-L173
def churn_rate(user, summary='default', **kwargs): """ Computes the frequency spent at every towers each week, and returns the distribution of the cosine similarity between two consecutives week. .. note:: The churn rate is always computed between pairs of weeks. """ if len(user.records) == 0: ...
[ "def", "churn_rate", "(", "user", ",", "summary", "=", "'default'", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "user", ".", "records", ")", "==", "0", ":", "return", "statistics", "(", "[", "]", ",", "summary", "=", "summary", ")", "query...
Computes the frequency spent at every towers each week, and returns the distribution of the cosine similarity between two consecutives week. .. note:: The churn rate is always computed between pairs of weeks.
[ "Computes", "the", "frequency", "spent", "at", "every", "towers", "each", "week", "and", "returns", "the", "distribution", "of", "the", "cosine", "similarity", "between", "two", "consecutives", "week", "." ]
python
train
32.756098
RedHatInsights/insights-core
insights/client/connection.py
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/connection.py#L434-L478
def get_branch_info(self): """ Retrieve branch_info from Satellite Server """ branch_info = None if os.path.exists(constants.cached_branch_info): # use cached branch info file if less than 10 minutes old # (failsafe, should be deleted at end of client run...
[ "def", "get_branch_info", "(", "self", ")", ":", "branch_info", "=", "None", "if", "os", ".", "path", ".", "exists", "(", "constants", ".", "cached_branch_info", ")", ":", "# use cached branch info file if less than 10 minutes old", "# (failsafe, should be deleted at end...
Retrieve branch_info from Satellite Server
[ "Retrieve", "branch_info", "from", "Satellite", "Server" ]
python
train
47.688889
tensorflow/cleverhans
cleverhans/attacks_tf.py
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks_tf.py#L55-L79
def apply_perturbations(i, j, X, increase, theta, clip_min, clip_max): """ TensorFlow implementation for apply perturbations to input features based on salency maps :param i: index of first selected feature :param j: index of second selected feature :param X: a matrix containing our input features for our s...
[ "def", "apply_perturbations", "(", "i", ",", "j", ",", "X", ",", "increase", ",", "theta", ",", "clip_min", ",", "clip_max", ")", ":", "warnings", ".", "warn", "(", "\"This function is dead code and will be removed on or after 2019-07-18\"", ")", "# perturb our input ...
TensorFlow implementation for apply perturbations to input features based on salency maps :param i: index of first selected feature :param j: index of second selected feature :param X: a matrix containing our input features for our sample :param increase: boolean; true if we are increasing pixels, false other...
[ "TensorFlow", "implementation", "for", "apply", "perturbations", "to", "input", "features", "based", "on", "salency", "maps", ":", "param", "i", ":", "index", "of", "first", "selected", "feature", ":", "param", "j", ":", "index", "of", "second", "selected", ...
python
train
39.6
openstack/proliantutils
proliantutils/redfish/resources/manager/virtual_media.py
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/redfish/resources/manager/virtual_media.py#L30-L34
def _get_media(media_types): """Helper method to map the media types.""" get_mapped_media = (lambda x: maps.VIRTUAL_MEDIA_TYPES_MAP[x] if x in maps.VIRTUAL_MEDIA_TYPES_MAP else None) return list(map(get_mapped_media, media_types))
[ "def", "_get_media", "(", "media_types", ")", ":", "get_mapped_media", "=", "(", "lambda", "x", ":", "maps", ".", "VIRTUAL_MEDIA_TYPES_MAP", "[", "x", "]", "if", "x", "in", "maps", ".", "VIRTUAL_MEDIA_TYPES_MAP", "else", "None", ")", "return", "list", "(", ...
Helper method to map the media types.
[ "Helper", "method", "to", "map", "the", "media", "types", "." ]
python
train
52.4
jopohl/urh
src/urh/plugins/MessageBreak/MessageBreakAction.py
https://github.com/jopohl/urh/blob/2eb33b125c8407964cd1092843cde5010eb88aae/src/urh/plugins/MessageBreak/MessageBreakAction.py#L33-L54
def __get_zero_seq_indexes(self, message: str, following_zeros: int): """ :rtype: list[tuple of int] """ result = [] if following_zeros > len(message): return result zero_counter = 0 for i in range(0, len(message)): if message[i] == "0": ...
[ "def", "__get_zero_seq_indexes", "(", "self", ",", "message", ":", "str", ",", "following_zeros", ":", "int", ")", ":", "result", "=", "[", "]", "if", "following_zeros", ">", "len", "(", "message", ")", ":", "return", "result", "zero_counter", "=", "0", ...
:rtype: list[tuple of int]
[ ":", "rtype", ":", "list", "[", "tuple", "of", "int", "]" ]
python
train
29.181818
rigetti/quantumflow
quantumflow/backend/numpybk.py
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/backend/numpybk.py#L125-L128
def inner(tensor0: BKTensor, tensor1: BKTensor) -> BKTensor: """Return the inner product between two tensors""" # Note: Relying on fact that vdot flattens arrays return np.vdot(tensor0, tensor1)
[ "def", "inner", "(", "tensor0", ":", "BKTensor", ",", "tensor1", ":", "BKTensor", ")", "->", "BKTensor", ":", "# Note: Relying on fact that vdot flattens arrays", "return", "np", ".", "vdot", "(", "tensor0", ",", "tensor1", ")" ]
Return the inner product between two tensors
[ "Return", "the", "inner", "product", "between", "two", "tensors" ]
python
train
50.75
user-cont/conu
conu/backend/podman/image.py
https://github.com/user-cont/conu/blob/08caae7bb6bdd265b55bb106c3da6a7946a5a352/conu/backend/podman/image.py#L367-L380
def get_volume_options(volumes): """ Generates volume options to run methods. :param volumes: tuple or list of tuples in form target x source,target x source,target,mode. :return: list of the form ["-v", "/source:/target", "-v", "/other/source:/destination:z", ...] """ i...
[ "def", "get_volume_options", "(", "volumes", ")", ":", "if", "not", "isinstance", "(", "volumes", ",", "list", ")", ":", "volumes", "=", "[", "volumes", "]", "volumes", "=", "[", "Volume", ".", "create_from_tuple", "(", "v", ")", "for", "v", "in", "vol...
Generates volume options to run methods. :param volumes: tuple or list of tuples in form target x source,target x source,target,mode. :return: list of the form ["-v", "/source:/target", "-v", "/other/source:/destination:z", ...]
[ "Generates", "volume", "options", "to", "run", "methods", "." ]
python
train
38.642857
SALib/SALib
src/SALib/analyze/morris.py
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/analyze/morris.py#L224-L258
def compute_elementary_effects(model_inputs, model_outputs, trajectory_size, delta): ''' Arguments --------- model_inputs : matrix of inputs to the model under analysis. x-by-r where x is the number of variables and r is the number of rows (a function of x ...
[ "def", "compute_elementary_effects", "(", "model_inputs", ",", "model_outputs", ",", "trajectory_size", ",", "delta", ")", ":", "num_vars", "=", "model_inputs", ".", "shape", "[", "1", "]", "num_rows", "=", "model_inputs", ".", "shape", "[", "0", "]", "num_tra...
Arguments --------- model_inputs : matrix of inputs to the model under analysis. x-by-r where x is the number of variables and r is the number of rows (a function of x and num_trajectories) model_outputs an r-length vector of model outputs trajectory_size a scalar indicat...
[ "Arguments", "---------", "model_inputs", ":", "matrix", "of", "inputs", "to", "the", "model", "under", "analysis", ".", "x", "-", "by", "-", "r", "where", "x", "is", "the", "number", "of", "variables", "and", "r", "is", "the", "number", "of", "rows", ...
python
train
33.685714
networks-lab/metaknowledge
metaknowledge/graphHelpers.py
https://github.com/networks-lab/metaknowledge/blob/8162bf95e66bb6f9916081338e6e2a6132faff75/metaknowledge/graphHelpers.py#L691-L732
def mergeGraphs(targetGraph, addedGraph, incrementedNodeVal = 'count', incrementedEdgeVal = 'weight'): """A quick way of merging graphs, this is meant to be quick and is only intended for graphs generated by metaknowledge. This does not check anything and as such may cause unexpected results if the source and targe...
[ "def", "mergeGraphs", "(", "targetGraph", ",", "addedGraph", ",", "incrementedNodeVal", "=", "'count'", ",", "incrementedEdgeVal", "=", "'weight'", ")", ":", "for", "addedNode", ",", "attribs", "in", "addedGraph", ".", "nodes", "(", "data", "=", "True", ")", ...
A quick way of merging graphs, this is meant to be quick and is only intended for graphs generated by metaknowledge. This does not check anything and as such may cause unexpected results if the source and target were not generated by the same method. **mergeGraphs**() will **modify** _targetGraph_ in place by addi...
[ "A", "quick", "way", "of", "merging", "graphs", "this", "is", "meant", "to", "be", "quick", "and", "is", "only", "intended", "for", "graphs", "generated", "by", "metaknowledge", ".", "This", "does", "not", "check", "anything", "and", "as", "such", "may", ...
python
train
53.452381
bigchaindb/bigchaindb
bigchaindb/core.py
https://github.com/bigchaindb/bigchaindb/blob/835fdfcf598918f76139e3b88ee33dd157acaaa7/bigchaindb/core.py#L173-L193
def deliver_tx(self, raw_transaction): """Validate the transaction before mutating the state. Args: raw_tx: a raw string (in bytes) transaction. """ self.abort_if_abci_chain_is_not_synced() logger.debug('deliver_tx: %s', raw_transaction) transaction = self....
[ "def", "deliver_tx", "(", "self", ",", "raw_transaction", ")", ":", "self", ".", "abort_if_abci_chain_is_not_synced", "(", ")", "logger", ".", "debug", "(", "'deliver_tx: %s'", ",", "raw_transaction", ")", "transaction", "=", "self", ".", "bigchaindb", ".", "is_...
Validate the transaction before mutating the state. Args: raw_tx: a raw string (in bytes) transaction.
[ "Validate", "the", "transaction", "before", "mutating", "the", "state", "." ]
python
train
36.047619
deep-compute/deeputil
deeputil/misc.py
https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/misc.py#L223-L259
def deepgetattr(obj, attr, default=AttributeError): """ Recurses through an attribute chain to get the ultimate value (obj/data/member/value) from: http://pingfive.typepad.com/blog/2010/04/deep-getattr-python-function.html >>> class Universe(object): ... def __init__(self, galaxy): ... ...
[ "def", "deepgetattr", "(", "obj", ",", "attr", ",", "default", "=", "AttributeError", ")", ":", "try", ":", "return", "reduce", "(", "getattr", ",", "attr", ".", "split", "(", "'.'", ")", ",", "obj", ")", "except", "AttributeError", ":", "if", "default...
Recurses through an attribute chain to get the ultimate value (obj/data/member/value) from: http://pingfive.typepad.com/blog/2010/04/deep-getattr-python-function.html >>> class Universe(object): ... def __init__(self, galaxy): ... self.galaxy = galaxy ... >>> class Galaxy(objec...
[ "Recurses", "through", "an", "attribute", "chain", "to", "get", "the", "ultimate", "value", "(", "obj", "/", "data", "/", "member", "/", "value", ")", "from", ":", "http", ":", "//", "pingfive", ".", "typepad", ".", "com", "/", "blog", "/", "2010", "...
python
train
30.189189
biolink/ontobio
ontobio/golr/golr_query.py
https://github.com/biolink/ontobio/blob/4e512a7831cfe6bc1b32f2c3be2ba41bc5cf7345/ontobio/golr/golr_query.py#L1669-L1679
def run_solr_text_on(solrInstance, category, q, qf, fields, optionals): """ Return the result of a solr query on the given solrInstance (Enum ESOLR), for a certain document_category (ESOLRDoc) and id """ if optionals == None: optionals = "" query = solrInstance.value + "select?q=" + q + "&qf...
[ "def", "run_solr_text_on", "(", "solrInstance", ",", "category", ",", "q", ",", "qf", ",", "fields", ",", "optionals", ")", ":", "if", "optionals", "==", "None", ":", "optionals", "=", "\"\"", "query", "=", "solrInstance", ".", "value", "+", "\"select?q=\"...
Return the result of a solr query on the given solrInstance (Enum ESOLR), for a certain document_category (ESOLRDoc) and id
[ "Return", "the", "result", "of", "a", "solr", "query", "on", "the", "given", "solrInstance", "(", "Enum", "ESOLR", ")", "for", "a", "certain", "document_category", "(", "ESOLRDoc", ")", "and", "id" ]
python
train
48.272727
scivision/pymap3d
pymap3d/azelradec.py
https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/azelradec.py#L59-L105
def radec2azel(ra_deg: float, dec_deg: float, lat_deg: float, lon_deg: float, time: datetime, usevallado: bool = False) -> Tuple[float, float]: """ sky coordinates (ra, dec) to viewing angle (az, el) Parameters ---------- ra_deg : float or numpy.ndarray of float ...
[ "def", "radec2azel", "(", "ra_deg", ":", "float", ",", "dec_deg", ":", "float", ",", "lat_deg", ":", "float", ",", "lon_deg", ":", "float", ",", "time", ":", "datetime", ",", "usevallado", ":", "bool", "=", "False", ")", "->", "Tuple", "[", "float", ...
sky coordinates (ra, dec) to viewing angle (az, el) Parameters ---------- ra_deg : float or numpy.ndarray of float ecliptic right ascension (degress) dec_deg : float or numpy.ndarray of float ecliptic declination (degrees) lat_deg : float observer latitude [-90, 90] ...
[ "sky", "coordinates", "(", "ra", "dec", ")", "to", "viewing", "angle", "(", "az", "el", ")" ]
python
train
32.744681
dswah/pyGAM
pygam/pygam.py
https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/pygam.py#L2164-L2191
def _simulate_coef_from_bootstraps( self, n_draws, coef_bootstraps, cov_bootstraps): """Simulate coefficients using bootstrap samples.""" # Sample indices uniformly from {0, ..., n_bootstraps - 1} # (Wood pg. 199 step 6) random_bootstrap_indices = np.random.choice( ...
[ "def", "_simulate_coef_from_bootstraps", "(", "self", ",", "n_draws", ",", "coef_bootstraps", ",", "cov_bootstraps", ")", ":", "# Sample indices uniformly from {0, ..., n_bootstraps - 1}", "# (Wood pg. 199 step 6)", "random_bootstrap_indices", "=", "np", ".", "random", ".", "...
Simulate coefficients using bootstrap samples.
[ "Simulate", "coefficients", "using", "bootstrap", "samples", "." ]
python
train
53.714286
inspirehep/harvesting-kit
harvestingkit/utils.py
https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/utils.py#L262-L269
def run_shell_command(commands, **kwargs): """Run a shell command.""" p = subprocess.Popen(commands, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs) output, error = p.communicate() return p.returncode, output, error
[ "def", "run_shell_command", "(", "commands", ",", "*", "*", "kwargs", ")", ":", "p", "=", "subprocess", ".", "Popen", "(", "commands", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ",", "*", "*", "kwargs"...
Run a shell command.
[ "Run", "a", "shell", "command", "." ]
python
valid
38.625
saltstack/salt
salt/modules/postgres.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L553-L607
def db_create(name, user=None, host=None, port=None, maintenance_db=None, password=None, tablespace=None, encoding=None, lc_collate=None, lc_ctype=None, owner=None, t...
[ "def", "db_create", "(", "name", ",", "user", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ",", "maintenance_db", "=", "None", ",", "password", "=", "None", ",", "tablespace", "=", "None", ",", "encoding", "=", "None", ",", "lc_co...
Adds a databases to the Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_create 'dbname' salt '*' postgres.db_create 'dbname' template=template_postgis
[ "Adds", "a", "databases", "to", "the", "Postgres", "server", "." ]
python
train
30.618182
python-bugzilla/python-bugzilla
bugzilla/bug.py
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/bug.py#L282-L292
def addcomment(self, comment, private=False): """ Add the given comment to this bug. Set private to True to mark this comment as private. """ # Note: fedora bodhi uses this function vals = self.bugzilla.build_update(comment=comment, ...
[ "def", "addcomment", "(", "self", ",", "comment", ",", "private", "=", "False", ")", ":", "# Note: fedora bodhi uses this function", "vals", "=", "self", ".", "bugzilla", ".", "build_update", "(", "comment", "=", "comment", ",", "comment_private", "=", "private"...
Add the given comment to this bug. Set private to True to mark this comment as private.
[ "Add", "the", "given", "comment", "to", "this", "bug", ".", "Set", "private", "to", "True", "to", "mark", "this", "comment", "as", "private", "." ]
python
train
40.636364
saltstack/salt
salt/modules/boto_cloudwatch.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cloudwatch.py#L103-L124
def _safe_dump(data): ''' this presenter magic makes yaml.safe_dump work with the objects returned from boto.describe_alarms() ''' custom_dumper = __utils__['yaml.get_dumper']('SafeOrderedDumper') def boto_listelement_presenter(dumper, data): return dumper.represent_list(list(data))...
[ "def", "_safe_dump", "(", "data", ")", ":", "custom_dumper", "=", "__utils__", "[", "'yaml.get_dumper'", "]", "(", "'SafeOrderedDumper'", ")", "def", "boto_listelement_presenter", "(", "dumper", ",", "data", ")", ":", "return", "dumper", ".", "represent_list", "...
this presenter magic makes yaml.safe_dump work with the objects returned from boto.describe_alarms()
[ "this", "presenter", "magic", "makes", "yaml", ".", "safe_dump", "work", "with", "the", "objects", "returned", "from", "boto", ".", "describe_alarms", "()" ]
python
train
34.590909
liminspace/dju-image
dju_image/tools.py
https://github.com/liminspace/dju-image/blob/b06eb3be2069cd6cb52cf1e26c2c761883142d4e/dju_image/tools.py#L251-L257
def remove_tmp_prefix_from_filename(filename): """ Remove tmp prefix from filename. """ if not filename.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): raise RuntimeError(ERROR_MESSAGES['filename_hasnt_tmp_prefix'] % {'filename': filename}) return filename[len(dju_settings.DJU_IMG_UPLOAD...
[ "def", "remove_tmp_prefix_from_filename", "(", "filename", ")", ":", "if", "not", "filename", ".", "startswith", "(", "dju_settings", ".", "DJU_IMG_UPLOAD_TMP_PREFIX", ")", ":", "raise", "RuntimeError", "(", "ERROR_MESSAGES", "[", "'filename_hasnt_tmp_prefix'", "]", "...
Remove tmp prefix from filename.
[ "Remove", "tmp", "prefix", "from", "filename", "." ]
python
train
46.857143
elyase/masstable
masstable/masstable.py
https://github.com/elyase/masstable/blob/3eb72b22cd3337bc5c6bb95bb7bb73fdbe6ae9e2/masstable/masstable.py#L70-L89
def from_ZNM(cls, Z, N, M, name=''): """ Creates a table from arrays Z, N and M Example: ________ >>> Z = [82, 82, 83] >>> N = [126, 127, 130] >>> M = [-21.34, -18.0, -14.45] >>> Table.from_ZNM(Z, N, M, name='Custom Table') Z N 82 126 ...
[ "def", "from_ZNM", "(", "cls", ",", "Z", ",", "N", ",", "M", ",", "name", "=", "''", ")", ":", "df", "=", "pd", ".", "DataFrame", ".", "from_dict", "(", "{", "'Z'", ":", "Z", ",", "'N'", ":", "N", ",", "'M'", ":", "M", "}", ")", ".", "set...
Creates a table from arrays Z, N and M Example: ________ >>> Z = [82, 82, 83] >>> N = [126, 127, 130] >>> M = [-21.34, -18.0, -14.45] >>> Table.from_ZNM(Z, N, M, name='Custom Table') Z N 82 126 -21.34 127 -18.00 83 130 -14.4...
[ "Creates", "a", "table", "from", "arrays", "Z", "N", "and", "M" ]
python
test
28.15
bioasp/iggy
src/profile_parser.py
https://github.com/bioasp/iggy/blob/451dee74f277d822d64cf8f3859c94b2f2b6d4db/src/profile_parser.py#L108-L110
def p_plus_assignment(self, t): '''plus_assignment : IDENT EQ PLUS''' self.accu.add(Term('obs_vlabel', [self.name,"gen(\""+t[1]+"\")","1"]))
[ "def", "p_plus_assignment", "(", "self", ",", "t", ")", ":", "self", ".", "accu", ".", "add", "(", "Term", "(", "'obs_vlabel'", ",", "[", "self", ".", "name", ",", "\"gen(\\\"\"", "+", "t", "[", "1", "]", "+", "\"\\\")\"", ",", "\"1\"", "]", ")", ...
plus_assignment : IDENT EQ PLUS
[ "plus_assignment", ":", "IDENT", "EQ", "PLUS" ]
python
train
48.666667
linuxwhatelse/mapper
mapper.py
https://github.com/linuxwhatelse/mapper/blob/3481715b2a36d2da8bf5e9c6da80ceaed0d7ca59/mapper.py#L64-L84
def url(self, pattern, method=None, type_cast=None): """Decorator for registering a path pattern. Args: pattern (str): Regex pattern to match a certain path method (str, optional): Usually used to define one of GET, POST, PUT, DELETE. You may use whatever fits yo...
[ "def", "url", "(", "self", ",", "pattern", ",", "method", "=", "None", ",", "type_cast", "=", "None", ")", ":", "if", "not", "type_cast", ":", "type_cast", "=", "{", "}", "def", "decorator", "(", "function", ")", ":", "self", ".", "add", "(", "patt...
Decorator for registering a path pattern. Args: pattern (str): Regex pattern to match a certain path method (str, optional): Usually used to define one of GET, POST, PUT, DELETE. You may use whatever fits your situation though. Defaults to None. ...
[ "Decorator", "for", "registering", "a", "path", "pattern", "." ]
python
test
39.333333
HDI-Project/ballet
ballet/util/io.py
https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/util/io.py#L118-L130
def load_table_from_config(input_dir, config): """Load table from table config dict Args: input_dir (path-like): directory containing input files config (dict): mapping with keys 'name', 'path', and 'pd_read_kwargs'. Returns: pd.DataFrame """ path = pathlib.Path(input_dir)....
[ "def", "load_table_from_config", "(", "input_dir", ",", "config", ")", ":", "path", "=", "pathlib", ".", "Path", "(", "input_dir", ")", ".", "joinpath", "(", "config", "[", "'path'", "]", ")", "kwargs", "=", "config", "[", "'pd_read_kwargs'", "]", "return"...
Load table from table config dict Args: input_dir (path-like): directory containing input files config (dict): mapping with keys 'name', 'path', and 'pd_read_kwargs'. Returns: pd.DataFrame
[ "Load", "table", "from", "table", "config", "dict" ]
python
train
31.461538
todddeluca/dones
dones.py
https://github.com/todddeluca/dones/blob/6ef56565556987e701fed797a405f0825fe2e15a/dones.py#L64-L73
def _get_k(self): ''' Accessing self.k indirectly allows for creating the kvstore table if necessary. ''' if not self.ready: self.k.create() # create table if it does not exist. self.ready = True return self.k
[ "def", "_get_k", "(", "self", ")", ":", "if", "not", "self", ".", "ready", ":", "self", ".", "k", ".", "create", "(", ")", "# create table if it does not exist.", "self", ".", "ready", "=", "True", "return", "self", ".", "k" ]
Accessing self.k indirectly allows for creating the kvstore table if necessary.
[ "Accessing", "self", ".", "k", "indirectly", "allows", "for", "creating", "the", "kvstore", "table", "if", "necessary", "." ]
python
train
27.3
polyaxon/polyaxon
polyaxon/scopes/permissions/projects.py
https://github.com/polyaxon/polyaxon/blob/e1724f0756b1a42f9e7aa08a976584a84ef7f016/polyaxon/scopes/permissions/projects.py#L19-L26
def has_project_permissions(user: 'User', project: 'Project', request_method: str) -> bool: """This logic is extracted here to be used also with Sanic api.""" # Superusers and the creator is allowed to do everything if user.is_staff or user.is_superuser or project.user == user: return True # Ot...
[ "def", "has_project_permissions", "(", "user", ":", "'User'", ",", "project", ":", "'Project'", ",", "request_method", ":", "str", ")", "->", "bool", ":", "# Superusers and the creator is allowed to do everything", "if", "user", ".", "is_staff", "or", "user", ".", ...
This logic is extracted here to be used also with Sanic api.
[ "This", "logic", "is", "extracted", "here", "to", "be", "used", "also", "with", "Sanic", "api", "." ]
python
train
49.625
pgmpy/pgmpy
pgmpy/factors/discrete/DiscreteFactor.py
https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/factors/discrete/DiscreteFactor.py#L615-L680
def divide(self, phi1, inplace=True): """ DiscreteFactor division by `phi1`. Parameters ---------- phi1 : `DiscreteFactor` instance The denominator for division. inplace: boolean If inplace=True it will modify the factor itself, else would return...
[ "def", "divide", "(", "self", ",", "phi1", ",", "inplace", "=", "True", ")", ":", "phi", "=", "self", "if", "inplace", "else", "self", ".", "copy", "(", ")", "phi1", "=", "phi1", ".", "copy", "(", ")", "if", "set", "(", "phi1", ".", "variables", ...
DiscreteFactor division by `phi1`. Parameters ---------- phi1 : `DiscreteFactor` instance The denominator for division. inplace: boolean If inplace=True it will modify the factor itself, else would return a new factor. Returns ------...
[ "DiscreteFactor", "division", "by", "phi1", "." ]
python
train
35.257576
ClimateImpactLab/DataFS
datafs/core/data_api.py
https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/core/data_api.py#L190-L233
def get_archive(self, archive_name, default_version=None): ''' Retrieve a data archive Parameters ---------- archive_name: str Name of the archive to retrieve default_version: version str or :py:class:`~distutils.StrictVersion` giving the defaul...
[ "def", "get_archive", "(", "self", ",", "archive_name", ",", "default_version", "=", "None", ")", ":", "auth", ",", "archive_name", "=", "self", ".", "_normalize_archive_name", "(", "archive_name", ")", "res", "=", "self", ".", "manager", ".", "get_archive", ...
Retrieve a data archive Parameters ---------- archive_name: str Name of the archive to retrieve default_version: version str or :py:class:`~distutils.StrictVersion` giving the default version number to be used on read operations Returns ...
[ "Retrieve", "a", "data", "archive" ]
python
train
28.477273
pymc-devs/pymc
pymc/StepMethods.py
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/StepMethods.py#L1631-L1661
def walk(self): """Walk proposal kernel""" if self.verbose > 1: print_('\t' + self._id + ' Running Walk proposal kernel') # Mask for values to move phi = self.phi theta = self.walk_theta u = random(len(phi)) z = (theta / (1 + theta)) * (theta * u *...
[ "def", "walk", "(", "self", ")", ":", "if", "self", ".", "verbose", ">", "1", ":", "print_", "(", "'\\t'", "+", "self", ".", "_id", "+", "' Running Walk proposal kernel'", ")", "# Mask for values to move", "phi", "=", "self", ".", "phi", "theta", "=", "s...
Walk proposal kernel
[ "Walk", "proposal", "kernel" ]
python
train
23.483871
Kronuz/pyScss
scss/source.py
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/source.py#L224-L256
def from_string(cls, string, relpath=None, encoding=None, is_sass=None): """Read Sass source from the contents of a string. The origin is always None. `relpath` defaults to "string:...". """ if isinstance(string, six.text_type): # Already decoded; we don't know what encodin...
[ "def", "from_string", "(", "cls", ",", "string", ",", "relpath", "=", "None", ",", "encoding", "=", "None", ",", "is_sass", "=", "None", ")", ":", "if", "isinstance", "(", "string", ",", "six", ".", "text_type", ")", ":", "# Already decoded; we don't know ...
Read Sass source from the contents of a string. The origin is always None. `relpath` defaults to "string:...".
[ "Read", "Sass", "source", "from", "the", "contents", "of", "a", "string", "." ]
python
train
38.757576
pndurette/gTTS
gtts/tokenizer/pre_processors.py
https://github.com/pndurette/gTTS/blob/b01ac4eb22d40c6241202e202d0418ccf4f98460/gtts/tokenizer/pre_processors.py#L31-L48
def abbreviations(text): """Remove periods after an abbreviation from a list of known abbrevations that can be spoken the same without that period. This prevents having to handle tokenization of that period. Note: Could potentially remove the ending period of a sentence. Note: Abbr...
[ "def", "abbreviations", "(", "text", ")", ":", "return", "PreProcessorRegex", "(", "search_args", "=", "symbols", ".", "ABBREVIATIONS", ",", "search_func", "=", "lambda", "x", ":", "r\"(?<={})(?=\\.).\"", ".", "format", "(", "x", ")", ",", "repl", "=", "''",...
Remove periods after an abbreviation from a list of known abbrevations that can be spoken the same without that period. This prevents having to handle tokenization of that period. Note: Could potentially remove the ending period of a sentence. Note: Abbreviations that Google Translate ...
[ "Remove", "periods", "after", "an", "abbreviation", "from", "a", "list", "of", "known", "abbrevations", "that", "can", "be", "spoken", "the", "same", "without", "that", "period", ".", "This", "prevents", "having", "to", "handle", "tokenization", "of", "that", ...
python
train
38.722222
flatangle/flatlib
flatlib/chart.py
https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/chart.py#L130-L140
def isDiurnal(self): """ Returns true if this chart is diurnal. """ sun = self.getObject(const.SUN) mc = self.getAngle(const.MC) # Get ecliptical positions and check if the # sun is above the horizon. lat = self.pos.lat sunRA, sunDecl = utils.eqCoords(sun...
[ "def", "isDiurnal", "(", "self", ")", ":", "sun", "=", "self", ".", "getObject", "(", "const", ".", "SUN", ")", "mc", "=", "self", ".", "getAngle", "(", "const", ".", "MC", ")", "# Get ecliptical positions and check if the", "# sun is above the horizon.", "lat...
Returns true if this chart is diurnal.
[ "Returns", "true", "if", "this", "chart", "is", "diurnal", "." ]
python
train
39.636364
saltstack/salt
salt/modules/introspect.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/introspect.py#L107-L146
def service_highstate(requires=True): ''' Return running and enabled services in a highstate structure. By default also returns package dependencies for those services, which means that package definitions must be created outside this function. To drop the package dependencies, set ``requires`` to F...
[ "def", "service_highstate", "(", "requires", "=", "True", ")", ":", "ret", "=", "{", "}", "running", "=", "running_service_owners", "(", ")", "for", "service", "in", "running", ":", "ret", "[", "service", "]", "=", "{", "'service'", ":", "[", "'running'"...
Return running and enabled services in a highstate structure. By default also returns package dependencies for those services, which means that package definitions must be created outside this function. To drop the package dependencies, set ``requires`` to False. CLI Example: salt myminion int...
[ "Return", "running", "and", "enabled", "services", "in", "a", "highstate", "structure", ".", "By", "default", "also", "returns", "package", "dependencies", "for", "those", "services", "which", "means", "that", "package", "definitions", "must", "be", "created", "...
python
train
32.725
apache/incubator-superset
superset/connectors/druid/models.py
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/connectors/druid/models.py#L1361-L1484
def get_filters(cls, raw_filters, num_cols, columns_dict): # noqa """Given Superset filter data structure, returns pydruid Filter(s)""" filters = None for flt in raw_filters: col = flt.get('col') op = flt.get('op') eq = flt.get('val') if ( ...
[ "def", "get_filters", "(", "cls", ",", "raw_filters", ",", "num_cols", ",", "columns_dict", ")", ":", "# noqa", "filters", "=", "None", "for", "flt", "in", "raw_filters", ":", "col", "=", "flt", ".", "get", "(", "'col'", ")", "op", "=", "flt", ".", "...
Given Superset filter data structure, returns pydruid Filter(s)
[ "Given", "Superset", "filter", "data", "structure", "returns", "pydruid", "Filter", "(", "s", ")" ]
python
train
37.451613
fgmacedo/django-export-action
export_action/introspection.py
https://github.com/fgmacedo/django-export-action/blob/215fecb9044d22e3ae19d86c3b220041a11fad07/export_action/introspection.py#L77-L99
def get_model_from_path_string(root_model, path): """ Return a model class for a related model root_model is the class of the initial model path is like foo__bar where bar is related to foo """ for path_section in path.split('__'): if path_section: try: field, mod...
[ "def", "get_model_from_path_string", "(", "root_model", ",", "path", ")", ":", "for", "path_section", "in", "path", ".", "split", "(", "'__'", ")", ":", "if", "path_section", ":", "try", ":", "field", ",", "model", ",", "direct", ",", "m2m", "=", "_get_f...
Return a model class for a related model root_model is the class of the initial model path is like foo__bar where bar is related to foo
[ "Return", "a", "model", "class", "for", "a", "related", "model", "root_model", "is", "the", "class", "of", "the", "initial", "model", "path", "is", "like", "foo__bar", "where", "bar", "is", "related", "to", "foo" ]
python
train
40.217391
zsethna/OLGA
olga/utils.py
https://github.com/zsethna/OLGA/blob/e825c333f0f9a4eb02132e0bcf86f0dca9123114/olga/utils.py#L340-L361
def calc_steady_state_dist(R): """Calculate the steady state dist of a 4 state markov transition matrix. Parameters ---------- R : ndarray Markov transition matrix Returns ------- p_ss : ndarray Steady state probability distribution """ #Calc steady state d...
[ "def", "calc_steady_state_dist", "(", "R", ")", ":", "#Calc steady state distribution for a dinucleotide bias matrix", "w", ",", "v", "=", "np", ".", "linalg", ".", "eig", "(", "R", ")", "for", "i", "in", "range", "(", "4", ")", ":", "if", "np", ".", "abs"...
Calculate the steady state dist of a 4 state markov transition matrix. Parameters ---------- R : ndarray Markov transition matrix Returns ------- p_ss : ndarray Steady state probability distribution
[ "Calculate", "the", "steady", "state", "dist", "of", "a", "4", "state", "markov", "transition", "matrix", "." ]
python
train
23
futapi/fut
fut/log.py
https://github.com/futapi/fut/blob/3792c9eee8f5884f38a02210e649c46c6c7a756d/fut/log.py#L20-L36
def logger(name=None, save=False): """Init and configure logger.""" logger = logging.getLogger(name) if save: logformat = '%(asctime)s [%(levelname)s] [%(name)s] %(funcName)s: %(message)s (line %(lineno)d)' log_file_path = 'fut.log' # TODO: define logpath open(log_file_path, 'w').w...
[ "def", "logger", "(", "name", "=", "None", ",", "save", "=", "False", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "name", ")", "if", "save", ":", "logformat", "=", "'%(asctime)s [%(levelname)s] [%(name)s] %(funcName)s: %(message)s (line %(lineno)d)'",...
Init and configure logger.
[ "Init", "and", "configure", "logger", "." ]
python
valid
35.470588
jantman/awslimitchecker
awslimitchecker/services/elasticache.py
https://github.com/jantman/awslimitchecker/blob/e50197f70f3d0abcc5cfc7fde6336f548b790e34/awslimitchecker/services/elasticache.py#L55-L70
def find_usage(self): """ Determine the current usage for each limit of this service, and update corresponding Limit via :py:meth:`~.AwsLimit._add_current_usage`. """ logger.debug("Checking usage for service %s", self.service_name) self.connect() for lim i...
[ "def", "find_usage", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"Checking usage for service %s\"", ",", "self", ".", "service_name", ")", "self", ".", "connect", "(", ")", "for", "lim", "in", "self", ".", "limits", ".", "values", "(", ")", ":"...
Determine the current usage for each limit of this service, and update corresponding Limit via :py:meth:`~.AwsLimit._add_current_usage`.
[ "Determine", "the", "current", "usage", "for", "each", "limit", "of", "this", "service", "and", "update", "corresponding", "Limit", "via", ":", "py", ":", "meth", ":", "~", ".", "AwsLimit", ".", "_add_current_usage", "." ]
python
train
37.3125
fhcrc/taxtastic
taxtastic/utils.py
https://github.com/fhcrc/taxtastic/blob/4e874b7f2cc146178828bfba386314f8c342722b/taxtastic/utils.py#L76-L109
def parse_raxml(handle): """Parse RAxML's summary output. *handle* should be an open file handle containing the RAxML output. It is parsed and a dictionary returned. """ s = ''.join(handle.readlines()) result = {} try_set_fields(result, r'(?P<program>RAxML version [0-9.]+)', s) try_set...
[ "def", "parse_raxml", "(", "handle", ")", ":", "s", "=", "''", ".", "join", "(", "handle", ".", "readlines", "(", ")", ")", "result", "=", "{", "}", "try_set_fields", "(", "result", ",", "r'(?P<program>RAxML version [0-9.]+)'", ",", "s", ")", "try_set_fiel...
Parse RAxML's summary output. *handle* should be an open file handle containing the RAxML output. It is parsed and a dictionary returned.
[ "Parse", "RAxML", "s", "summary", "output", "." ]
python
train
48.088235
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgets/browser.py
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/browser.py#L345-L358
def current_changed(self, i): """Slot for when the current index changes. Emits the :data:`AbstractLevel.new_root` signal. :param index: the new current index :type index: int :returns: None :rtype: None :raises: None """ m = self.model() ...
[ "def", "current_changed", "(", "self", ",", "i", ")", ":", "m", "=", "self", ".", "model", "(", ")", "ri", "=", "self", ".", "rootModelIndex", "(", ")", "index", "=", "m", ".", "index", "(", "i", ",", "0", ",", "ri", ")", "self", ".", "new_root...
Slot for when the current index changes. Emits the :data:`AbstractLevel.new_root` signal. :param index: the new current index :type index: int :returns: None :rtype: None :raises: None
[ "Slot", "for", "when", "the", "current", "index", "changes", ".", "Emits", "the", ":", "data", ":", "AbstractLevel", ".", "new_root", "signal", "." ]
python
train
28.642857
Kozea/pygal
pygal/graph/line.py
https://github.com/Kozea/pygal/blob/5e25c98a59a0642eecd9fcc5dbfeeb2190fbb5e7/pygal/graph/line.py#L86-L187
def line(self, serie, rescale=False): """Draw the line serie""" serie_node = self.svg.serie(serie) if rescale and self.secondary_series: points = self._rescale(serie.points) else: points = serie.points view_values = list(map(self.view, points)) if ...
[ "def", "line", "(", "self", ",", "serie", ",", "rescale", "=", "False", ")", ":", "serie_node", "=", "self", ".", "svg", ".", "serie", "(", "serie", ")", "if", "rescale", "and", "self", ".", "secondary_series", ":", "points", "=", "self", ".", "_resc...
Draw the line serie
[ "Draw", "the", "line", "serie" ]
python
train
38.009804
Pringley/spyglass
spyglass/torrent.py
https://github.com/Pringley/spyglass/blob/091d74f34837673af936daa9f462ad8216be9916/spyglass/torrent.py#L114-L128
def as_dict(self, cache=None, fetch=True): """Return torrent properties as a dictionary. Set the cache flag to False to disable the cache. On the other hand, set the fetch flag to False to avoid fetching data if it's not cached. """ if not self._fetched and fetch: i...
[ "def", "as_dict", "(", "self", ",", "cache", "=", "None", ",", "fetch", "=", "True", ")", ":", "if", "not", "self", ".", "_fetched", "and", "fetch", ":", "info", "=", "self", ".", "fetch", "(", "cache", ")", "elif", "self", ".", "_use_cache", "(", ...
Return torrent properties as a dictionary. Set the cache flag to False to disable the cache. On the other hand, set the fetch flag to False to avoid fetching data if it's not cached.
[ "Return", "torrent", "properties", "as", "a", "dictionary", "." ]
python
train
32.933333
sci-bots/pygtkhelpers
pygtkhelpers/ui/form_view_dialog.py
https://github.com/sci-bots/pygtkhelpers/blob/3a6e6d6340221c686229cd1c951d7537dae81b07/pygtkhelpers/ui/form_view_dialog.py#L70-L108
def create_ui(self): ''' .. versionchanged:: 0.21.2 Load the builder configuration file using :func:`pkgutil.getdata`, which supports loading from `.zip` archives (e.g., in an app packaged with Py2Exe). ''' builder = gtk.Builder() # Read glade ...
[ "def", "create_ui", "(", "self", ")", ":", "builder", "=", "gtk", ".", "Builder", "(", ")", "# Read glade file using `pkgutil` to also support loading from `.zip`", "# files (e.g., in app packaged with Py2Exe).", "glade_str", "=", "pkgutil", ".", "get_data", "(", "__name__"...
.. versionchanged:: 0.21.2 Load the builder configuration file using :func:`pkgutil.getdata`, which supports loading from `.zip` archives (e.g., in an app packaged with Py2Exe).
[ "..", "versionchanged", "::", "0", ".", "21", ".", "2", "Load", "the", "builder", "configuration", "file", "using", ":", "func", ":", "pkgutil", ".", "getdata", "which", "supports", "loading", "from", ".", "zip", "archives", "(", "e", ".", "g", ".", "i...
python
train
45.025641
materialsvirtuallab/monty
monty/os/path.py
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/os/path.py#L15-L41
def which(cmd): """ Returns full path to a executable. Args: cmd (str): Executable command to search for. Returns: (str) Full path to command. None if it is not found. Example:: full_path_to_python = which("python") """ def is_exe(fp): return os.path.isfil...
[ "def", "which", "(", "cmd", ")", ":", "def", "is_exe", "(", "fp", ")", ":", "return", "os", ".", "path", ".", "isfile", "(", "fp", ")", "and", "os", ".", "access", "(", "fp", ",", "os", ".", "X_OK", ")", "fpath", ",", "fname", "=", "os", ".",...
Returns full path to a executable. Args: cmd (str): Executable command to search for. Returns: (str) Full path to command. None if it is not found. Example:: full_path_to_python = which("python")
[ "Returns", "full", "path", "to", "a", "executable", "." ]
python
train
23.037037
OLC-LOC-Bioinformatics/GenomeQAML
genomeqaml/extract_features.py
https://github.com/OLC-LOC-Bioinformatics/GenomeQAML/blob/2953e574c185afab23075641da4ce5392bc003e9/genomeqaml/extract_features.py#L245-L266
def find_n50(contig_lengths_dict, genome_length_dict): """ Calculate the N50 for each strain. N50 is defined as the largest contig such that at least half of the total genome size is contained in contigs equal to or larger than this contig :param contig_lengths_dict: dictionary of strain name: reverse-s...
[ "def", "find_n50", "(", "contig_lengths_dict", ",", "genome_length_dict", ")", ":", "# Initialise the dictionary", "n50_dict", "=", "dict", "(", ")", "for", "file_name", ",", "contig_lengths", "in", "contig_lengths_dict", ".", "items", "(", ")", ":", "# Initialise a...
Calculate the N50 for each strain. N50 is defined as the largest contig such that at least half of the total genome size is contained in contigs equal to or larger than this contig :param contig_lengths_dict: dictionary of strain name: reverse-sorted list of all contig lengths :param genome_length_dict: dic...
[ "Calculate", "the", "N50", "for", "each", "strain", ".", "N50", "is", "defined", "as", "the", "largest", "contig", "such", "that", "at", "least", "half", "of", "the", "total", "genome", "size", "is", "contained", "in", "contigs", "equal", "to", "or", "la...
python
train
54.590909
gwastro/pycbc
pycbc/transforms.py
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/transforms.py#L422-L454
def transform(self, maps): """This function transforms from chirp mass and symmetric mass ratio to component masses. Parameters ---------- maps : a mapping object Examples -------- Convert a dict of numpy.array: >>> import numpy >>> from...
[ "def", "transform", "(", "self", ",", "maps", ")", ":", "out", "=", "{", "}", "out", "[", "parameters", ".", "mass1", "]", "=", "conversions", ".", "mass1_from_mchirp_eta", "(", "maps", "[", "parameters", ".", "mchirp", "]", ",", "maps", "[", "paramete...
This function transforms from chirp mass and symmetric mass ratio to component masses. Parameters ---------- maps : a mapping object Examples -------- Convert a dict of numpy.array: >>> import numpy >>> from pycbc import transforms >>> t...
[ "This", "function", "transforms", "from", "chirp", "mass", "and", "symmetric", "mass", "ratio", "to", "component", "masses", "." ]
python
train
37.454545
santoshphilip/eppy
eppy/loops.py
https://github.com/santoshphilip/eppy/blob/55410ff7c11722f35bc4331ff5e00a0b86f787e1/eppy/loops.py#L116-L120
def splitterfields(data, commdct): """get splitter fields to diagram it""" objkey = "Connector:Splitter".upper() fieldlists = splittermixerfieldlists(data, commdct, objkey) return extractfields(data, commdct, objkey, fieldlists)
[ "def", "splitterfields", "(", "data", ",", "commdct", ")", ":", "objkey", "=", "\"Connector:Splitter\"", ".", "upper", "(", ")", "fieldlists", "=", "splittermixerfieldlists", "(", "data", ",", "commdct", ",", "objkey", ")", "return", "extractfields", "(", "dat...
get splitter fields to diagram it
[ "get", "splitter", "fields", "to", "diagram", "it" ]
python
train
48
davenquinn/Attitude
attitude/__dustbin/__report/__init__.py
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/__dustbin/__report/__init__.py#L34-L78
def report(*arrays, **kwargs): """ Outputs a standalone HTML 'report card' for a measurement (or several grouped measurements), including relevant statistical information. """ name = kwargs.pop("name",None) grouped = len(arrays) > 1 if grouped: arr = N.concatenate(arrays) ...
[ "def", "report", "(", "*", "arrays", ",", "*", "*", "kwargs", ")", ":", "name", "=", "kwargs", ".", "pop", "(", "\"name\"", ",", "None", ")", "grouped", "=", "len", "(", "arrays", ")", ">", "1", "if", "grouped", ":", "arr", "=", "N", ".", "conc...
Outputs a standalone HTML 'report card' for a measurement (or several grouped measurements), including relevant statistical information.
[ "Outputs", "a", "standalone", "HTML", "report", "card", "for", "a", "measurement", "(", "or", "several", "grouped", "measurements", ")", "including", "relevant", "statistical", "information", "." ]
python
train
25.577778
WoLpH/python-statsd
statsd/client.py
https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/client.py#L104-L110
def get_timer(self, name=None): '''Shortcut for getting a :class:`~statsd.timer.Timer` instance :keyword name: See :func:`~statsd.client.Client.get_client` :type name: str ''' return self.get_client(name=name, class_=statsd.Timer)
[ "def", "get_timer", "(", "self", ",", "name", "=", "None", ")", ":", "return", "self", ".", "get_client", "(", "name", "=", "name", ",", "class_", "=", "statsd", ".", "Timer", ")" ]
Shortcut for getting a :class:`~statsd.timer.Timer` instance :keyword name: See :func:`~statsd.client.Client.get_client` :type name: str
[ "Shortcut", "for", "getting", "a", ":", "class", ":", "~statsd", ".", "timer", ".", "Timer", "instance" ]
python
train
37.857143
allenai/allennlp
allennlp/models/semantic_role_labeler.py
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/semantic_role_labeler.py#L226-L268
def write_to_conll_eval_file(prediction_file: TextIO, gold_file: TextIO, verb_index: Optional[int], sentence: List[str], prediction: List[str], gold_labels: List[str]): ""...
[ "def", "write_to_conll_eval_file", "(", "prediction_file", ":", "TextIO", ",", "gold_file", ":", "TextIO", ",", "verb_index", ":", "Optional", "[", "int", "]", ",", "sentence", ":", "List", "[", "str", "]", ",", "prediction", ":", "List", "[", "str", "]", ...
Prints predicate argument predictions and gold labels for a single verbal predicate in a sentence to two provided file references. Parameters ---------- prediction_file : TextIO, required. A file reference to print predictions to. gold_file : TextIO, required. A file reference to pr...
[ "Prints", "predicate", "argument", "predictions", "and", "gold", "labels", "for", "a", "single", "verbal", "predicate", "in", "a", "sentence", "to", "two", "provided", "file", "references", "." ]
python
train
41
MartijnBraam/python-isc-dhcp-leases
isc_dhcp_leases/iscdhcpleases.py
https://github.com/MartijnBraam/python-isc-dhcp-leases/blob/e96c00e31f3a52c01ef98193577d614d08a93285/isc_dhcp_leases/iscdhcpleases.py#L65-L98
def _extract_properties(config): """ Parse a line within a lease block The line should basically match the expression: >>> r"\s+(?P<key>(?:option|set)\s+\S+|\S+) (?P<value>[\s\S]+?);" For easier seperation of the cases and faster parsing this is done using substrings etc.. :param config: :re...
[ "def", "_extract_properties", "(", "config", ")", ":", "general", ",", "options", ",", "sets", "=", "{", "}", ",", "{", "}", ",", "{", "}", "for", "line", "in", "config", ".", "splitlines", "(", ")", ":", "# skip empty & malformed lines", "if", "not", ...
Parse a line within a lease block The line should basically match the expression: >>> r"\s+(?P<key>(?:option|set)\s+\S+|\S+) (?P<value>[\s\S]+?);" For easier seperation of the cases and faster parsing this is done using substrings etc.. :param config: :return: tuple of properties dict, options dict ...
[ "Parse", "a", "line", "within", "a", "lease", "block", "The", "line", "should", "basically", "match", "the", "expression", ":", ">>>", "r", "\\", "s", "+", "(", "?P<key", ">", "(", "?", ":", "option|set", ")", "\\", "s", "+", "\\", "S", "+", "|", ...
python
train
32.794118
fracpete/python-weka-wrapper3
python/weka/core/classes.py
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/core/classes.py#L1471-L1485
def find(self, name): """ Returns the Tag that matches the name. :param name: the string representation of the tag :type name: str :return: the tag, None if not found :rtype: Tag """ result = None for t in self.array: if str(t) == name...
[ "def", "find", "(", "self", ",", "name", ")", ":", "result", "=", "None", "for", "t", "in", "self", ".", "array", ":", "if", "str", "(", "t", ")", "==", "name", ":", "result", "=", "Tag", "(", "t", ".", "jobject", ")", "break", "return", "resul...
Returns the Tag that matches the name. :param name: the string representation of the tag :type name: str :return: the tag, None if not found :rtype: Tag
[ "Returns", "the", "Tag", "that", "matches", "the", "name", "." ]
python
train
26.066667
Cadair/jupyter_environment_kernels
environment_kernels/core.py
https://github.com/Cadair/jupyter_environment_kernels/blob/3da304550b511bda7d5d39280379b5ca39bb31bc/environment_kernels/core.py#L187-L195
def find_kernel_specs(self): """Returns a dict mapping kernel names to resource directories.""" # let real installed kernels overwrite envs with the same name: # this is the same order as the get_kernel_spec way, which also prefers # kernels from the jupyter dir over env kernels. ...
[ "def", "find_kernel_specs", "(", "self", ")", ":", "# let real installed kernels overwrite envs with the same name:", "# this is the same order as the get_kernel_spec way, which also prefers", "# kernels from the jupyter dir over env kernels.", "specs", "=", "self", ".", "find_kernel_specs...
Returns a dict mapping kernel names to resource directories.
[ "Returns", "a", "dict", "mapping", "kernel", "names", "to", "resource", "directories", "." ]
python
train
54
RedHatInsights/insights-core
insights/contrib/importlib.py
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/contrib/importlib.py#L20-L38
def import_module(name, package=None): """Import a module. The 'package' argument is required when performing a relative import. It specifies the package to use as the anchor point from which to resolve the relative import to an absolute import. """ if name.startswith('.'): if not pack...
[ "def", "import_module", "(", "name", ",", "package", "=", "None", ")", ":", "if", "name", ".", "startswith", "(", "'.'", ")", ":", "if", "not", "package", ":", "raise", "TypeError", "(", "\"relative imports require the 'package' argument\"", ")", "level", "=",...
Import a module. The 'package' argument is required when performing a relative import. It specifies the package to use as the anchor point from which to resolve the relative import to an absolute import.
[ "Import", "a", "module", "." ]
python
train
32.684211
Jaymon/endpoints
endpoints/http.py
https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/http.py#L943-L968
def url(self): """return the full request url as an Url() instance""" scheme = self.scheme host = self.host path = self.path query = self.query port = self.port # normalize the port host_domain, host_port = Url.split_hostname_from_port(host) if ho...
[ "def", "url", "(", "self", ")", ":", "scheme", "=", "self", ".", "scheme", "host", "=", "self", ".", "host", "path", "=", "self", ".", "path", "query", "=", "self", ".", "query", "port", "=", "self", ".", "port", "# normalize the port", "host_domain", ...
return the full request url as an Url() instance
[ "return", "the", "full", "request", "url", "as", "an", "Url", "()", "instance" ]
python
train
26.038462
geophysics-ubonn/crtomo_tools
lib/crtomo/plotManager.py
https://github.com/geophysics-ubonn/crtomo_tools/blob/27c3e21a557f8df1c12455b96c4c2e00e08a5b4a/lib/crtomo/plotManager.py#L501-L526
def converter_pm_log10(data): """Convert the given data to: log10(subdata) for subdata > 0 log10(-subdata') for subdata' < 0 0 for subdata'' == 0 Parameters ---------- data: array input data Returns ------- array_converted: array converted data ...
[ "def", "converter_pm_log10", "(", "data", ")", ":", "# indices_zero = np.where(data == 0)", "indices_gt_zero", "=", "np", ".", "where", "(", "data", ">", "0", ")", "indices_lt_zero", "=", "np", ".", "where", "(", "data", "<", "0", ")", "data_converted", "=", ...
Convert the given data to: log10(subdata) for subdata > 0 log10(-subdata') for subdata' < 0 0 for subdata'' == 0 Parameters ---------- data: array input data Returns ------- array_converted: array converted data
[ "Convert", "the", "given", "data", "to", ":" ]
python
train
25.653846
pandas-dev/pandas
pandas/core/internals/concat.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/internals/concat.py#L366-L384
def is_uniform_join_units(join_units): """ Check if the join units consist of blocks of uniform type that can be concatenated using Block.concat_same_type instead of the generic concatenate_join_units (which uses `_concat._concat_compat`). """ return ( # all blocks need to have the same...
[ "def", "is_uniform_join_units", "(", "join_units", ")", ":", "return", "(", "# all blocks need to have the same type", "all", "(", "type", "(", "ju", ".", "block", ")", "is", "type", "(", "join_units", "[", "0", "]", ".", "block", ")", "for", "ju", "in", "...
Check if the join units consist of blocks of uniform type that can be concatenated using Block.concat_same_type instead of the generic concatenate_join_units (which uses `_concat._concat_compat`).
[ "Check", "if", "the", "join", "units", "consist", "of", "blocks", "of", "uniform", "type", "that", "can", "be", "concatenated", "using", "Block", ".", "concat_same_type", "instead", "of", "the", "generic", "concatenate_join_units", "(", "which", "uses", "_concat...
python
train
47.263158
jeremymcrae/denovonear
denovonear/__main__.py
https://github.com/jeremymcrae/denovonear/blob/feaab0fc77e89d70b31e8092899e4f0e68bac9fe/denovonear/__main__.py#L93-L133
def get_mutation_rates(transcripts, mut_dict, ensembl): """ determines mutation rates per functional category for transcripts Args: transcripts: list of transcript IDs for a gene mut_dict: dictionary of local sequence context mutation rates ensembl: EnsemblRequest object, to retriev...
[ "def", "get_mutation_rates", "(", "transcripts", ",", "mut_dict", ",", "ensembl", ")", ":", "rates", "=", "{", "'missense'", ":", "0", ",", "'nonsense'", ":", "0", ",", "'splice_lof'", ":", "0", ",", "'splice_region'", ":", "0", ",", "'synonymous'", ":", ...
determines mutation rates per functional category for transcripts Args: transcripts: list of transcript IDs for a gene mut_dict: dictionary of local sequence context mutation rates ensembl: EnsemblRequest object, to retrieve information from Ensembl. Returns: tuple of (...
[ "determines", "mutation", "rates", "per", "functional", "category", "for", "transcripts", "Args", ":", "transcripts", ":", "list", "of", "transcript", "IDs", "for", "a", "gene", "mut_dict", ":", "dictionary", "of", "local", "sequence", "context", "mutation", "ra...
python
train
32.829268
spulec/moto
moto/batch/models.py
https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/batch/models.py#L310-L405
def run(self): """ Run the container. Logic is as follows: Generate container info (eventually from task definition) Start container Loop whilst not asked to stop and the container is running. Get all logs from container between the last time I checked and now....
[ "def", "run", "(", "self", ")", ":", "try", ":", "self", ".", "job_state", "=", "'PENDING'", "time", ".", "sleep", "(", "1", ")", "image", "=", "'alpine:latest'", "cmd", "=", "'/bin/sh -c \"for a in `seq 1 10`; do echo Hello World; sleep 1; done\"'", "name", "=", ...
Run the container. Logic is as follows: Generate container info (eventually from task definition) Start container Loop whilst not asked to stop and the container is running. Get all logs from container between the last time I checked and now. Convert logs into cloudwat...
[ "Run", "the", "container", "." ]
python
train
44.125
diffeo/rejester
rejester/_registry.py
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L104-L129
def _acquire_lock(self, identifier, atime=30, ltime=5): '''Acquire a lock for a given identifier. If the lock cannot be obtained immediately, keep trying at random intervals, up to 3 seconds, until `atime` has passed. Once the lock has been obtained, continue to hold it for `ltime`. ...
[ "def", "_acquire_lock", "(", "self", ",", "identifier", ",", "atime", "=", "30", ",", "ltime", "=", "5", ")", ":", "conn", "=", "redis", ".", "Redis", "(", "connection_pool", "=", "self", ".", "pool", ")", "end", "=", "time", ".", "time", "(", ")",...
Acquire a lock for a given identifier. If the lock cannot be obtained immediately, keep trying at random intervals, up to 3 seconds, until `atime` has passed. Once the lock has been obtained, continue to hold it for `ltime`. :param str identifier: lock token to write :param in...
[ "Acquire", "a", "lock", "for", "a", "given", "identifier", "." ]
python
train
41.653846
vtkiorg/vtki
vtki/common.py
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L250-L259
def set_active_scalar(self, name, preference='cell'): """Finds the scalar by name and appropriately sets it as active""" _, field = get_scalar(self, name, preference=preference, info=True) if field == POINT_DATA_FIELD: self.GetPointData().SetActiveScalars(name) elif field == ...
[ "def", "set_active_scalar", "(", "self", ",", "name", ",", "preference", "=", "'cell'", ")", ":", "_", ",", "field", "=", "get_scalar", "(", "self", ",", "name", ",", "preference", "=", "preference", ",", "info", "=", "True", ")", "if", "field", "==", ...
Finds the scalar by name and appropriately sets it as active
[ "Finds", "the", "scalar", "by", "name", "and", "appropriately", "sets", "it", "as", "active" ]
python
train
52
quora/qcore
qcore/enum.py
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/enum.py#L175-L214
def create(cls, name, members): """Creates a new enum type based on this one (cls) and adds newly passed members to the newly created subclass of cls. This method helps to create enums having the same member values as values of other enum(s). :param name: name of the newly crea...
[ "def", "create", "(", "cls", ",", "name", ",", "members", ")", ":", "NewEnum", "=", "type", "(", "name", ",", "(", "cls", ",", ")", ",", "{", "}", ")", "if", "isinstance", "(", "members", ",", "dict", ")", ":", "members", "=", "members", ".", "...
Creates a new enum type based on this one (cls) and adds newly passed members to the newly created subclass of cls. This method helps to create enums having the same member values as values of other enum(s). :param name: name of the newly created type :param members: 1) a dict ...
[ "Creates", "a", "new", "enum", "type", "based", "on", "this", "one", "(", "cls", ")", "and", "adds", "newly", "passed", "members", "to", "the", "newly", "created", "subclass", "of", "cls", "." ]
python
train
36.3
kdeldycke/chessboard
setup.py
https://github.com/kdeldycke/chessboard/blob/ac7a14dc7b6905701e3f6d4e01e8fe1869241bed/setup.py#L117-L126
def long_description(): """ Collates project README and latest changes. """ changes = latest_changes() changes[0] = "`Changes for v{}".format(changes[0][1:]) changes[1] = '-' * len(changes[0]) return "\n\n\n".join([ read_file('README.rst'), '\n'.join(changes), "`Full changelo...
[ "def", "long_description", "(", ")", ":", "changes", "=", "latest_changes", "(", ")", "changes", "[", "0", "]", "=", "\"`Changes for v{}\"", ".", "format", "(", "changes", "[", "0", "]", "[", "1", ":", "]", ")", "changes", "[", "1", "]", "=", "'-'", ...
Collates project README and latest changes.
[ "Collates", "project", "README", "and", "latest", "changes", "." ]
python
train
39.8
EUDAT-B2SAFE/B2HANDLE
b2handle/handlesystemconnector.py
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/handlesystemconnector.py#L236-L247
def __set_basic_auth_string(self, username, password): ''' Creates and sets the authentication string for (write-)accessing the Handle Server. No return, the string is set as an attribute to the client instance. :param username: Username handle with index: index:prefix/s...
[ "def", "__set_basic_auth_string", "(", "self", ",", "username", ",", "password", ")", ":", "auth", "=", "b2handle", ".", "utilhandle", ".", "create_authentication_string", "(", "username", ",", "password", ")", "self", ".", "__basic_authentication_string", "=", "a...
Creates and sets the authentication string for (write-)accessing the Handle Server. No return, the string is set as an attribute to the client instance. :param username: Username handle with index: index:prefix/suffix. :param password: The password contained in the index of the ...
[ "Creates", "and", "sets", "the", "authentication", "string", "for", "(", "write", "-", ")", "accessing", "the", "Handle", "Server", ".", "No", "return", "the", "string", "is", "set", "as", "an", "attribute", "to", "the", "client", "instance", "." ]
python
train
46.5
getpelican/pelican-plugins
feed_summary/magic_set.py
https://github.com/getpelican/pelican-plugins/blob/cfc7a3f224f1743063b034561f89a6a712d13587/feed_summary/magic_set.py#L9-L86
def magic_set(obj): """ Adds a function/method to an object. Uses the name of the first argument as a hint about whether it is a method (``self``), class method (``cls`` or ``klass``), or static method (anything else). Works on both instances and classes. >>> class color: ... def __init__(self, r, g, b): ... self....
[ "def", "magic_set", "(", "obj", ")", ":", "def", "decorator", "(", "func", ")", ":", "is_class", "=", "isinstance", "(", "obj", ",", "six", ".", "class_types", ")", "args", ",", "varargs", ",", "varkw", ",", "defaults", "=", "inspect", ".", "getargspec...
Adds a function/method to an object. Uses the name of the first argument as a hint about whether it is a method (``self``), class method (``cls`` or ``klass``), or static method (anything else). Works on both instances and classes. >>> class color: ... def __init__(self, r, g, b): ... self.r, self.g, self.b = r, g, b ...
[ "Adds", "a", "function", "/", "method", "to", "an", "object", ".", "Uses", "the", "name", "of", "the", "first", "argument", "as", "a", "hint", "about", "whether", "it", "is", "a", "method", "(", "self", ")", "class", "method", "(", "cls", "or", "klas...
python
train
26.153846
napalm-automation/napalm
napalm/ios/ios.py
https://github.com/napalm-automation/napalm/blob/c11ae8bb5ce395698704a0051cdf8d144fbb150d/napalm/ios/ios.py#L2246-L2254
def get_ntp_peers(self): """Implementation of get_ntp_peers for IOS.""" ntp_stats = self.get_ntp_stats() return { ntp_peer.get("remote"): {} for ntp_peer in ntp_stats if ntp_peer.get("remote") }
[ "def", "get_ntp_peers", "(", "self", ")", ":", "ntp_stats", "=", "self", ".", "get_ntp_stats", "(", ")", "return", "{", "ntp_peer", ".", "get", "(", "\"remote\"", ")", ":", "{", "}", "for", "ntp_peer", "in", "ntp_stats", "if", "ntp_peer", ".", "get", "...
Implementation of get_ntp_peers for IOS.
[ "Implementation", "of", "get_ntp_peers", "for", "IOS", "." ]
python
train
28.333333
chrisjrn/registrasion
registrasion/reporting/views.py
https://github.com/chrisjrn/registrasion/blob/461d5846c6f9f3b7099322a94f5d9911564448e4/registrasion/reporting/views.py#L457-L566
def attendee(request, form, user_id=None): ''' Returns a list of all manifested attendees if no attendee is specified, else displays the attendee manifest. ''' if user_id is None and form.cleaned_data["user"] is not None: user_id = form.cleaned_data["user"] if user_id is None: return a...
[ "def", "attendee", "(", "request", ",", "form", ",", "user_id", "=", "None", ")", ":", "if", "user_id", "is", "None", "and", "form", ".", "cleaned_data", "[", "\"user\"", "]", "is", "not", "None", ":", "user_id", "=", "form", ".", "cleaned_data", "[", ...
Returns a list of all manifested attendees if no attendee is specified, else displays the attendee manifest.
[ "Returns", "a", "list", "of", "all", "manifested", "attendees", "if", "no", "attendee", "is", "specified", "else", "displays", "the", "attendee", "manifest", "." ]
python
test
28.772727
log2timeline/plaso
plaso/analysis/viper.py
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/analysis/viper.py#L39-L63
def _QueryHash(self, digest): """Queries the Viper Server for a specfic hash. Args: digest (str): hash to look up. Returns: dict[str, object]: JSON response or None on error. """ if not self._url: self._url = '{0:s}://{1:s}:{2:d}/file/find'.format( self._protocol, self....
[ "def", "_QueryHash", "(", "self", ",", "digest", ")", ":", "if", "not", "self", ".", "_url", ":", "self", ".", "_url", "=", "'{0:s}://{1:s}:{2:d}/file/find'", ".", "format", "(", "self", ".", "_protocol", ",", "self", ".", "_host", ",", "self", ".", "_...
Queries the Viper Server for a specfic hash. Args: digest (str): hash to look up. Returns: dict[str, object]: JSON response or None on error.
[ "Queries", "the", "Viper", "Server", "for", "a", "specfic", "hash", "." ]
python
train
26.64
JnyJny/Geometry
Geometry/ellipse.py
https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/ellipse.py#L111-L115
def xAxisIsMajor(self): ''' Returns True if the major axis is parallel to the X axis, boolean. ''' return max(self.radius.x, self.radius.y) == self.radius.x
[ "def", "xAxisIsMajor", "(", "self", ")", ":", "return", "max", "(", "self", ".", "radius", ".", "x", ",", "self", ".", "radius", ".", "y", ")", "==", "self", ".", "radius", ".", "x" ]
Returns True if the major axis is parallel to the X axis, boolean.
[ "Returns", "True", "if", "the", "major", "axis", "is", "parallel", "to", "the", "X", "axis", "boolean", "." ]
python
train
36.8
helgi/python-command
command/core.py
https://github.com/helgi/python-command/blob/c41fb8cdd9074b847c7bc5b5ee7f027508f52d7f/command/core.py#L212-L248
def which(program, environ=None): """ Find out if an executable exists in the supplied PATH. If so, the absolute path to the executable is returned. If not, an exception is raised. :type string :param program: Executable to be checked for :param dict :param environ: Any additional ENV ...
[ "def", "which", "(", "program", ",", "environ", "=", "None", ")", ":", "def", "is_exe", "(", "path", ")", ":", "\"\"\"\n Helper method to check if a file exists and is executable\n \"\"\"", "return", "isfile", "(", "path", ")", "and", "os", ".", "acces...
Find out if an executable exists in the supplied PATH. If so, the absolute path to the executable is returned. If not, an exception is raised. :type string :param program: Executable to be checked for :param dict :param environ: Any additional ENV variables required, specifically PATH :re...
[ "Find", "out", "if", "an", "executable", "exists", "in", "the", "supplied", "PATH", ".", "If", "so", "the", "absolute", "path", "to", "the", "executable", "is", "returned", ".", "If", "not", "an", "exception", "is", "raised", "." ]
python
train
29.594595
IceflowRE/unidown
unidown/core/updater.py
https://github.com/IceflowRE/unidown/blob/2a6f82ab780bb825668bfc55b67c11c4f72ec05c/unidown/core/updater.py#L13-L28
def get_newest_app_version() -> Version: """ Download the version tag from remote. :return: version from remote :rtype: ~packaging.version.Version """ with urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where()) as p_man: pypi_json = p_man.urlopen('GET', static_data.PYP...
[ "def", "get_newest_app_version", "(", ")", "->", "Version", ":", "with", "urllib3", ".", "PoolManager", "(", "cert_reqs", "=", "'CERT_REQUIRED'", ",", "ca_certs", "=", "certifi", ".", "where", "(", ")", ")", "as", "p_man", ":", "pypi_json", "=", "p_man", "...
Download the version tag from remote. :return: version from remote :rtype: ~packaging.version.Version
[ "Download", "the", "version", "tag", "from", "remote", "." ]
python
train
39.375