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
ajyoon/blur
blur/markov/graph.py
https://github.com/ajyoon/blur/blob/25fcf083af112bb003956a7a7e1c6ff7d8fef279/blur/markov/graph.py#L114-L150
def add_nodes(self, nodes): """ Add a given node or list of nodes to self.node_list. Args: node (Node or list[Node]): the node or list of nodes to add to the graph Returns: None Examples: Adding one node: :: >>> from blur.marko...
[ "def", "add_nodes", "(", "self", ",", "nodes", ")", ":", "# Generalize nodes to a list", "if", "not", "isinstance", "(", "nodes", ",", "list", ")", ":", "add_list", "=", "[", "nodes", "]", "else", ":", "add_list", "=", "nodes", "self", ".", "node_list", ...
Add a given node or list of nodes to self.node_list. Args: node (Node or list[Node]): the node or list of nodes to add to the graph Returns: None Examples: Adding one node: :: >>> from blur.markov.node import Node >>> graph = Graph...
[ "Add", "a", "given", "node", "or", "list", "of", "nodes", "to", "self", ".", "node_list", "." ]
python
train
28.405405
tmux-python/tmuxp
tmuxp/workspacebuilder.py
https://github.com/tmux-python/tmuxp/blob/f4aa2e26589a4311131898d2e4a85cb1876b5c9b/tmuxp/workspacebuilder.py#L270-L332
def iter_create_panes(self, w, wconf): """ Return :class:`libtmux.Pane` iterating through window config dict. Run ``shell_command`` with ``$ tmux send-keys``. Parameters ---------- w : :class:`libtmux.Window` window to create panes for wconf : dict ...
[ "def", "iter_create_panes", "(", "self", ",", "w", ",", "wconf", ")", ":", "assert", "isinstance", "(", "w", ",", "Window", ")", "pane_base_index", "=", "int", "(", "w", ".", "show_window_option", "(", "'pane-base-index'", ",", "g", "=", "True", ")", ")"...
Return :class:`libtmux.Pane` iterating through window config dict. Run ``shell_command`` with ``$ tmux send-keys``. Parameters ---------- w : :class:`libtmux.Window` window to create panes for wconf : dict config section for window Returns ...
[ "Return", ":", "class", ":", "libtmux", ".", "Pane", "iterating", "through", "window", "config", "dict", "." ]
python
train
30.84127
google-research/batch-ppo
agents/algorithms/ppo/ppo.py
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/algorithms/ppo/ppo.py#L81-L98
def begin_episode(self, agent_indices): """Reset the recurrent states and stored episode. Args: agent_indices: Tensor containing current batch indices. Returns: Summary tensor. """ with tf.name_scope('begin_episode/'): if self._last_state is None: reset_state = tf.no_op()...
[ "def", "begin_episode", "(", "self", ",", "agent_indices", ")", ":", "with", "tf", ".", "name_scope", "(", "'begin_episode/'", ")", ":", "if", "self", ".", "_last_state", "is", "None", ":", "reset_state", "=", "tf", ".", "no_op", "(", ")", "else", ":", ...
Reset the recurrent states and stored episode. Args: agent_indices: Tensor containing current batch indices. Returns: Summary tensor.
[ "Reset", "the", "recurrent", "states", "and", "stored", "episode", "." ]
python
train
31.722222
gwpy/gwpy
gwpy/cli/spectrogram.py
https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/cli/spectrogram.py#L76-L89
def get_stride(self): """Calculate the stride for the spectrogram This method returns the stride as a `float`, or `None` to indicate selected usage of `TimeSeries.spectrogram2`. """ fftlength = float(self.args.secpfft) overlap = fftlength * self.args.overlap stri...
[ "def", "get_stride", "(", "self", ")", ":", "fftlength", "=", "float", "(", "self", ".", "args", ".", "secpfft", ")", "overlap", "=", "fftlength", "*", "self", ".", "args", ".", "overlap", "stride", "=", "fftlength", "-", "overlap", "nfft", "=", "self"...
Calculate the stride for the spectrogram This method returns the stride as a `float`, or `None` to indicate selected usage of `TimeSeries.spectrogram2`.
[ "Calculate", "the", "stride", "for", "the", "spectrogram" ]
python
train
40.142857
Valuehorizon/valuehorizon-people
people/models.py
https://github.com/Valuehorizon/valuehorizon-people/blob/f32d9f1349c1a9384bae5ea61d10c1b1e0318401/people/models.py#L53-L68
def age(self, as_at_date=None): """ Compute the person's age """ if self.date_of_death != None or self.is_deceased == True: return None as_at_date = date.today() if as_at_date == None else as_at_date if self.date_of_birth != None: if (as_...
[ "def", "age", "(", "self", ",", "as_at_date", "=", "None", ")", ":", "if", "self", ".", "date_of_death", "!=", "None", "or", "self", ".", "is_deceased", "==", "True", ":", "return", "None", "as_at_date", "=", "date", ".", "today", "(", ")", "if", "as...
Compute the person's age
[ "Compute", "the", "person", "s", "age" ]
python
train
36.875
foxx/peewee-extras
old/old.py
https://github.com/foxx/peewee-extras/blob/327e7e63465b3f6e1afc0e6a651f4cb5c8c60889/old/old.py#L141-L146
def python_value(self, value): """Convert the database value to a pythonic value.""" value = coerce_to_bytes(value) obj = HashValue(value) obj.field = self return obj
[ "def", "python_value", "(", "self", ",", "value", ")", ":", "value", "=", "coerce_to_bytes", "(", "value", ")", "obj", "=", "HashValue", "(", "value", ")", "obj", ".", "field", "=", "self", "return", "obj" ]
Convert the database value to a pythonic value.
[ "Convert", "the", "database", "value", "to", "a", "pythonic", "value", "." ]
python
valid
33.5
rosenbrockc/fortpy
fortpy/code.py
https://github.com/rosenbrockc/fortpy/blob/1ed0757c52d549e41d9d44bdea68cb89529293a5/fortpy/code.py#L401-L429
def type_search(self, basetype, symbolstr, origin): """Recursively traverses the module trees looking for the final code element in a sequence of %-separated symbols. :arg basetype: the type name of the first element in the symbol string. :arg symblstr: a %-separated list of symbols, e....
[ "def", "type_search", "(", "self", ",", "basetype", ",", "symbolstr", ",", "origin", ")", ":", "symbols", "=", "symbolstr", ".", "split", "(", "\"%\"", ")", "base", ",", "basemod", "=", "self", ".", "tree_find", "(", "basetype", ",", "origin", ",", "\"...
Recursively traverses the module trees looking for the final code element in a sequence of %-separated symbols. :arg basetype: the type name of the first element in the symbol string. :arg symblstr: a %-separated list of symbols, e.g. this%sym%sym2%go. :arg origin: an instance of the Mo...
[ "Recursively", "traverses", "the", "module", "trees", "looking", "for", "the", "final", "code", "element", "in", "a", "sequence", "of", "%", "-", "separated", "symbols", "." ]
python
train
48.62069
ajenhl/tacl
tacl/data_store.py
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L377-L410
def diff_asymmetric(self, catalogue, prime_label, tokenizer, output_fh): """Returns `output_fh` populated with CSV results giving the difference in n-grams between the witnesses of labelled sets of works in `catalogue`, limited to those works labelled with `prime_label`. :param ...
[ "def", "diff_asymmetric", "(", "self", ",", "catalogue", ",", "prime_label", ",", "tokenizer", ",", "output_fh", ")", ":", "labels", "=", "list", "(", "self", ".", "_set_labels", "(", "catalogue", ")", ")", "if", "len", "(", "labels", ")", "<", "2", ":...
Returns `output_fh` populated with CSV results giving the difference in n-grams between the witnesses of labelled sets of works in `catalogue`, limited to those works labelled with `prime_label`. :param catalogue: catalogue matching filenames to labels :type catalogue: `Catalogu...
[ "Returns", "output_fh", "populated", "with", "CSV", "results", "giving", "the", "difference", "in", "n", "-", "grams", "between", "the", "witnesses", "of", "labelled", "sets", "of", "works", "in", "catalogue", "limited", "to", "those", "works", "labelled", "wi...
python
train
45.794118
Tanganelli/CoAPthon3
coapthon/messages/response.py
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/response.py#L27-L42
def location_path(self, path): """ Set the Location-Path of the response. :type path: String :param path: the Location-Path as a string """ path = path.strip("/") tmp = path.split("?") path = tmp[0] paths = path.split("/") for p in paths: ...
[ "def", "location_path", "(", "self", ",", "path", ")", ":", "path", "=", "path", ".", "strip", "(", "\"/\"", ")", "tmp", "=", "path", ".", "split", "(", "\"?\"", ")", "path", "=", "tmp", "[", "0", "]", "paths", "=", "path", ".", "split", "(", "...
Set the Location-Path of the response. :type path: String :param path: the Location-Path as a string
[ "Set", "the", "Location", "-", "Path", "of", "the", "response", "." ]
python
train
29.4375
bitesofcode/projexui
projexui/widgets/xratingslider.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xratingslider.py#L141-L149
def setPixmapSize( self, size ): """ Sets the pixmap size to the inputed value. :param size | <QSize> """ self._pixmapSize = size self.setMinimumHeight(size.height()) self.adjustMinimumWidth()
[ "def", "setPixmapSize", "(", "self", ",", "size", ")", ":", "self", ".", "_pixmapSize", "=", "size", "self", ".", "setMinimumHeight", "(", "size", ".", "height", "(", ")", ")", "self", ".", "adjustMinimumWidth", "(", ")" ]
Sets the pixmap size to the inputed value. :param size | <QSize>
[ "Sets", "the", "pixmap", "size", "to", "the", "inputed", "value", ".", ":", "param", "size", "|", "<QSize", ">" ]
python
train
29.111111
pandas-dev/pandas
pandas/io/formats/latex.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/formats/latex.py#L229-L238
def _print_cline(self, buf, i, icol): """ Print clines after multirow-blocks are finished """ for cl in self.clinebuf: if cl[0] == i: buf.write('\\cline{{{cl:d}-{icol:d}}}\n' .format(cl=cl[1], icol=icol)) # remove entries that...
[ "def", "_print_cline", "(", "self", ",", "buf", ",", "i", ",", "icol", ")", ":", "for", "cl", "in", "self", ".", "clinebuf", ":", "if", "cl", "[", "0", "]", "==", "i", ":", "buf", ".", "write", "(", "'\\\\cline{{{cl:d}-{icol:d}}}\\n'", ".", "format",...
Print clines after multirow-blocks are finished
[ "Print", "clines", "after", "multirow", "-", "blocks", "are", "finished" ]
python
train
40.3
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L542-L549
def open_in_browser(self, outfile): """Open the given HTML file in a browser. """ if self.browser == 'default': webbrowser.open('file://%s' % outfile) else: browser = webbrowser.get(self.browser) browser.open('file://%s' % outfile)
[ "def", "open_in_browser", "(", "self", ",", "outfile", ")", ":", "if", "self", ".", "browser", "==", "'default'", ":", "webbrowser", ".", "open", "(", "'file://%s'", "%", "outfile", ")", "else", ":", "browser", "=", "webbrowser", ".", "get", "(", "self",...
Open the given HTML file in a browser.
[ "Open", "the", "given", "HTML", "file", "in", "a", "browser", "." ]
python
train
36.5
tomislater/RandomWords
random_words/random_words.py
https://github.com/tomislater/RandomWords/blob/601aa48732d3c389f4c17ba0ed98ffe0e4821d78/random_words/random_words.py#L153-L199
def random_nicks(self, letter=None, gender='u', count=1): """ Return list of random nicks. :param str letter: letter :param str gender: ``'f'`` for female, ``'m'`` for male and None for both :param int count: how much nicks :rtype: list :returns: list of random n...
[ "def", "random_nicks", "(", "self", ",", "letter", "=", "None", ",", "gender", "=", "'u'", ",", "count", "=", "1", ")", ":", "self", ".", "check_count", "(", "count", ")", "nicks", "=", "[", "]", "if", "gender", "not", "in", "(", "'f'", ",", "'m'...
Return list of random nicks. :param str letter: letter :param str gender: ``'f'`` for female, ``'m'`` for male and None for both :param int count: how much nicks :rtype: list :returns: list of random nicks :raises: ValueError
[ "Return", "list", "of", "random", "nicks", "." ]
python
train
33.234043
gwastro/pycbc
pycbc/inference/io/__init__.py
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/io/__init__.py#L258-L293
def get_common_parameters(input_files, collection=None): """Gets a list of variable params that are common across all input files. If no common parameters are found, a ``ValueError`` is raised. Parameters ---------- input_files : list of str List of input files to load. collection : st...
[ "def", "get_common_parameters", "(", "input_files", ",", "collection", "=", "None", ")", ":", "if", "collection", "is", "None", ":", "collection", "=", "\"all\"", "parameters", "=", "[", "]", "for", "fn", "in", "input_files", ":", "fp", "=", "loadfile", "(...
Gets a list of variable params that are common across all input files. If no common parameters are found, a ``ValueError`` is raised. Parameters ---------- input_files : list of str List of input files to load. collection : str, optional What group of parameters to load. Can be the...
[ "Gets", "a", "list", "of", "variable", "params", "that", "are", "common", "across", "all", "input", "files", "." ]
python
train
33.694444
blakev/python-syncthing
syncthing/__init__.py
https://github.com/blakev/python-syncthing/blob/a7f4930f86f7543cd96990277945467896fb523d/syncthing/__init__.py#L445-L460
def pause(self, device): """ Pause the given device. Args: device (str): Device ID. Returns: dict: with keys ``success`` and ``error``. """ resp = self.post('pause', params={'device': device}, return_response=True...
[ "def", "pause", "(", "self", ",", "device", ")", ":", "resp", "=", "self", ".", "post", "(", "'pause'", ",", "params", "=", "{", "'device'", ":", "device", "}", ",", "return_response", "=", "True", ")", "error", "=", "resp", ".", "text", "if", "not...
Pause the given device. Args: device (str): Device ID. Returns: dict: with keys ``success`` and ``error``.
[ "Pause", "the", "given", "device", "." ]
python
train
29.8125
fracpete/python-weka-wrapper
python/weka/plot/classifiers.py
https://github.com/fracpete/python-weka-wrapper/blob/e865915146faf40d3bbfedb440328d1360541633/python/weka/plot/classifiers.py#L30-L98
def plot_classifier_errors(predictions, absolute=True, max_relative_size=50, absolute_size=50, title=None, outfile=None, wait=True): """ Plots the classifers for the given list of predictions. TODO: click events http://matplotlib.org/examples/event_handling/data_browser.html ...
[ "def", "plot_classifier_errors", "(", "predictions", ",", "absolute", "=", "True", ",", "max_relative_size", "=", "50", ",", "absolute_size", "=", "50", ",", "title", "=", "None", ",", "outfile", "=", "None", ",", "wait", "=", "True", ")", ":", "if", "no...
Plots the classifers for the given list of predictions. TODO: click events http://matplotlib.org/examples/event_handling/data_browser.html :param predictions: the predictions to plot :type predictions: list :param absolute: whether to use absolute errors as size or relative ones :type absolute: bo...
[ "Plots", "the", "classifers", "for", "the", "given", "list", "of", "predictions", "." ]
python
train
35.884058
nitmir/django-cas-server
cas_server/auth.py
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/auth.py#L272-L284
def get_conn(cls): """Return a connection object to the ldap database""" conn = cls._conn if conn is None or conn.closed: conn = ldap3.Connection( settings.CAS_LDAP_SERVER, settings.CAS_LDAP_USER, settings.CAS_LDAP_PASSWORD, ...
[ "def", "get_conn", "(", "cls", ")", ":", "conn", "=", "cls", ".", "_conn", "if", "conn", "is", "None", "or", "conn", ".", "closed", ":", "conn", "=", "ldap3", ".", "Connection", "(", "settings", ".", "CAS_LDAP_SERVER", ",", "settings", ".", "CAS_LDAP_U...
Return a connection object to the ldap database
[ "Return", "a", "connection", "object", "to", "the", "ldap", "database" ]
python
train
33.615385
DataDog/integrations-core
datadog_checks_dev/datadog_checks/dev/tooling/commands/release.py
https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/datadog_checks_dev/datadog_checks/dev/tooling/commands/release.py#L182-L240
def changes(ctx, check, dry_run): """Show all the pending PRs for a given check.""" if not dry_run and check not in get_valid_checks(): abort('Check `{}` is not an Agent-based Integration'.format(check)) # get the name of the current release tag cur_version = get_version_string(check) targe...
[ "def", "changes", "(", "ctx", ",", "check", ",", "dry_run", ")", ":", "if", "not", "dry_run", "and", "check", "not", "in", "get_valid_checks", "(", ")", ":", "abort", "(", "'Check `{}` is not an Agent-based Integration'", ".", "format", "(", "check", ")", ")...
Show all the pending PRs for a given check.
[ "Show", "all", "the", "pending", "PRs", "for", "a", "given", "check", "." ]
python
train
40.847458
ministryofjustice/django-form-error-reporting
form_error_reporting.py
https://github.com/ministryofjustice/django-form-error-reporting/blob/2d08dd5cc4321e1abf49241c515ccd7050d9f828/form_error_reporting.py#L24-L30
def urlencode(self): """ Convert dictionary into a query string; keys are assumed to always be str """ output = ('%s=%s' % (k, quote(v)) for k, v in self.items()) return '&'.join(output)
[ "def", "urlencode", "(", "self", ")", ":", "output", "=", "(", "'%s=%s'", "%", "(", "k", ",", "quote", "(", "v", ")", ")", "for", "k", ",", "v", "in", "self", ".", "items", "(", ")", ")", "return", "'&'", ".", "join", "(", "output", ")" ]
Convert dictionary into a query string; keys are assumed to always be str
[ "Convert", "dictionary", "into", "a", "query", "string", ";", "keys", "are", "assumed", "to", "always", "be", "str" ]
python
train
32.571429
OCA/openupgradelib
openupgradelib/openupgrade.py
https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L1298-L1339
def deactivate_workflow_transitions(cr, model, transitions=None): """ Disable workflow transitions for workflows on a given model. This can be necessary for automatic workflow transitions when writing to an object via the ORM in the post migration step. Returns a dictionary to be used on reactivate_...
[ "def", "deactivate_workflow_transitions", "(", "cr", ",", "model", ",", "transitions", "=", "None", ")", ":", "transition_ids", "=", "[", "]", "if", "transitions", ":", "data_obj", "=", "RegistryManager", ".", "get", "(", "cr", ".", "dbname", ")", "[", "'i...
Disable workflow transitions for workflows on a given model. This can be necessary for automatic workflow transitions when writing to an object via the ORM in the post migration step. Returns a dictionary to be used on reactivate_workflow_transitions :param model: the model for which workflow transitio...
[ "Disable", "workflow", "transitions", "for", "workflows", "on", "a", "given", "model", ".", "This", "can", "be", "necessary", "for", "automatic", "workflow", "transitions", "when", "writing", "to", "an", "object", "via", "the", "ORM", "in", "the", "post", "m...
python
train
39.238095
pantsbuild/pex
pex/interpreter.py
https://github.com/pantsbuild/pex/blob/87b2129d860250d3b9edce75b9cb62f9789ee521/pex/interpreter.py#L367-L395
def filter(cls, pythons): """ Given a map of python interpreters in the format provided by PythonInterpreter.find(), filter out duplicate versions and versions we would prefer not to use. Returns a map in the same format as find. """ good = [] MAJOR, MINOR, SUBMINOR = range(3) de...
[ "def", "filter", "(", "cls", ",", "pythons", ")", ":", "good", "=", "[", "]", "MAJOR", ",", "MINOR", ",", "SUBMINOR", "=", "range", "(", "3", ")", "def", "version_filter", "(", "version", ")", ":", "return", "(", "version", "[", "MAJOR", "]", "==",...
Given a map of python interpreters in the format provided by PythonInterpreter.find(), filter out duplicate versions and versions we would prefer not to use. Returns a map in the same format as find.
[ "Given", "a", "map", "of", "python", "interpreters", "in", "the", "format", "provided", "by", "PythonInterpreter", ".", "find", "()", "filter", "out", "duplicate", "versions", "and", "versions", "we", "would", "prefer", "not", "to", "use", "." ]
python
train
37.655172
tus/tus-py-client
tusclient/uploader.py
https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/uploader.py#L294-L303
def upload_chunk(self): """ Upload chunk of file. """ self._retried = 0 self._do_request() self.offset = int(self.request.response_headers.get('upload-offset')) if self.log_func: msg = '{} bytes uploaded ...'.format(self.offset) self.log_fu...
[ "def", "upload_chunk", "(", "self", ")", ":", "self", ".", "_retried", "=", "0", "self", ".", "_do_request", "(", ")", "self", ".", "offset", "=", "int", "(", "self", ".", "request", ".", "response_headers", ".", "get", "(", "'upload-offset'", ")", ")"...
Upload chunk of file.
[ "Upload", "chunk", "of", "file", "." ]
python
train
31.8
deshima-dev/decode
decode/joke/functions.py
https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/joke/functions.py#L21-L30
def youtube(keyword=None): """Open youtube. Args: keyword (optional): Search word. """ if keyword is None: web.open('https://www.youtube.com/watch?v=L_mBVT2jBFw') else: web.open(quote('https://www.youtube.com/results?search_query={}'.format(keyword), RESERVED))
[ "def", "youtube", "(", "keyword", "=", "None", ")", ":", "if", "keyword", "is", "None", ":", "web", ".", "open", "(", "'https://www.youtube.com/watch?v=L_mBVT2jBFw'", ")", "else", ":", "web", ".", "open", "(", "quote", "(", "'https://www.youtube.com/results?sear...
Open youtube. Args: keyword (optional): Search word.
[ "Open", "youtube", "." ]
python
train
29.7
CitrineInformatics/python-citrination-client
citrination_client/data/client.py
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/data/client.py#L217-L241
def download_files(self, dataset_files, destination='.'): """ Downloads file(s) to a local destination. :param dataset_files: :type dataset_files: list of :class: `DatasetFile` :param destination: The path to the desired local download destination :type destination: str ...
[ "def", "download_files", "(", "self", ",", "dataset_files", ",", "destination", "=", "'.'", ")", ":", "if", "not", "isinstance", "(", "dataset_files", ",", "list", ")", ":", "dataset_files", "=", "[", "dataset_files", "]", "for", "f", "in", "dataset_files", ...
Downloads file(s) to a local destination. :param dataset_files: :type dataset_files: list of :class: `DatasetFile` :param destination: The path to the desired local download destination :type destination: str :param chunk: Whether or not to chunk the file. Default True :...
[ "Downloads", "file", "(", "s", ")", "to", "a", "local", "destination", "." ]
python
valid
36.52
facebook/watchman
winbuild/copy-dyn-deps.py
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/winbuild/copy-dyn-deps.py#L168-L179
def resolve_dep_from_path(self, depname): """ If we can find the dep in the PATH, then we consider it to be a system dependency that we should not bundle in the package """ if is_system_dep(depname): return True for d in self._path: name = os.path.join(d, depname...
[ "def", "resolve_dep_from_path", "(", "self", ",", "depname", ")", ":", "if", "is_system_dep", "(", "depname", ")", ":", "return", "True", "for", "d", "in", "self", ".", "_path", ":", "name", "=", "os", ".", "path", ".", "join", "(", "d", ",", "depnam...
If we can find the dep in the PATH, then we consider it to be a system dependency that we should not bundle in the package
[ "If", "we", "can", "find", "the", "dep", "in", "the", "PATH", "then", "we", "consider", "it", "to", "be", "a", "system", "dependency", "that", "we", "should", "not", "bundle", "in", "the", "package" ]
python
train
33.083333
eonpatapon/contrail-api-cli
contrail_api_cli/parser.py
https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/parser.py#L40-L49
def used_options(self): """Return options already used in the command line rtype: command.Option generator """ for option_str in filter(lambda c: c.startswith('-'), self.words): for option in list(self.cmd.options.values()): if option_str in option.op...
[ "def", "used_options", "(", "self", ")", ":", "for", "option_str", "in", "filter", "(", "lambda", "c", ":", "c", ".", "startswith", "(", "'-'", ")", ",", "self", ".", "words", ")", ":", "for", "option", "in", "list", "(", "self", ".", "cmd", ".", ...
Return options already used in the command line rtype: command.Option generator
[ "Return", "options", "already", "used", "in", "the", "command", "line" ]
python
train
35.7
openearth/bmi-python
bmi/api.py
https://github.com/openearth/bmi-python/blob/2f53f24d45515eb0711c2d28ddd6c1582045248f/bmi/api.py#L134-L146
def set_var_index(self, name, index, var): """ Overwrite the values in variable "name" with data from var, at the flattened (C-contiguous style) indices. Indices is a vector of 0-based integers, of the same length as the vector var. For some implementations it can be equi...
[ "def", "set_var_index", "(", "self", ",", "name", ",", "index", ",", "var", ")", ":", "tmp", "=", "self", ".", "get_var", "(", "name", ")", ".", "copy", "(", ")", "tmp", ".", "flat", "[", "index", "]", "=", "var", "self", ".", "set_var", "(", "...
Overwrite the values in variable "name" with data from var, at the flattened (C-contiguous style) indices. Indices is a vector of 0-based integers, of the same length as the vector var. For some implementations it can be equivalent and more efficient to do: `get_var(name)...
[ "Overwrite", "the", "values", "in", "variable", "name", "with", "data", "from", "var", "at", "the", "flattened", "(", "C", "-", "contiguous", "style", ")", "indices", ".", "Indices", "is", "a", "vector", "of", "0", "-", "based", "integers", "of", "the", ...
python
train
38.769231
bloomreach/s4cmd
s4cmd.py
https://github.com/bloomreach/s4cmd/blob/bb51075bf43703e7cd95aa39288cf7732ec13a6d/s4cmd.py#L1500-L1506
def delete(self, source): '''Thread worker for download operation.''' s3url = S3URL(source) message('Delete %s', source) if not self.opt.dry_run: self.s3.delete_object(Bucket=s3url.bucket, Key=s3url.path)
[ "def", "delete", "(", "self", ",", "source", ")", ":", "s3url", "=", "S3URL", "(", "source", ")", "message", "(", "'Delete %s'", ",", "source", ")", "if", "not", "self", ".", "opt", ".", "dry_run", ":", "self", ".", "s3", ".", "delete_object", "(", ...
Thread worker for download operation.
[ "Thread", "worker", "for", "download", "operation", "." ]
python
test
31.571429
pallets/werkzeug
src/werkzeug/local.py
https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/local.py#L142-L148
def push(self, obj): """Pushes a new item to the stack""" rv = getattr(self._local, "stack", None) if rv is None: self._local.stack = rv = [] rv.append(obj) return rv
[ "def", "push", "(", "self", ",", "obj", ")", ":", "rv", "=", "getattr", "(", "self", ".", "_local", ",", "\"stack\"", ",", "None", ")", "if", "rv", "is", "None", ":", "self", ".", "_local", ".", "stack", "=", "rv", "=", "[", "]", "rv", ".", "...
Pushes a new item to the stack
[ "Pushes", "a", "new", "item", "to", "the", "stack" ]
python
train
30.285714
python-gitlab/python-gitlab
gitlab/mixins.py
https://github.com/python-gitlab/python-gitlab/blob/16de1b03fde3dbbe8f851614dd1d8c09de102fe5/gitlab/mixins.py#L487-L503
def time_stats(self, **kwargs): """Get time stats for the object. Args: **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct GitlabTimeTrackingError: If the time tracking update cannot ...
[ "def", "time_stats", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# Use the existing time_stats attribute if it exist, otherwise make an", "# API call", "if", "'time_stats'", "in", "self", ".", "attributes", ":", "return", "self", ".", "attributes", "[", "'time_st...
Get time stats for the object. Args: **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct GitlabTimeTrackingError: If the time tracking update cannot be done
[ "Get", "time", "stats", "for", "the", "object", "." ]
python
train
38
UpCloudLtd/upcloud-python-api
upcloud_api/ip_address.py
https://github.com/UpCloudLtd/upcloud-python-api/blob/954b0ad7c4b932b2be31a95d88975f6b0eeac8ed/upcloud_api/ip_address.py#L32-L38
def save(self): """ IPAddress can only change its PTR record. Saves the current state, PUT /ip_address/uuid. """ body = {'ip_address': {'ptr_record': self.ptr_record}} data = self.cloud_manager.request('PUT', '/ip_address/' + self.address, body) self._reset(**data['ip_add...
[ "def", "save", "(", "self", ")", ":", "body", "=", "{", "'ip_address'", ":", "{", "'ptr_record'", ":", "self", ".", "ptr_record", "}", "}", "data", "=", "self", ".", "cloud_manager", ".", "request", "(", "'PUT'", ",", "'/ip_address/'", "+", "self", "."...
IPAddress can only change its PTR record. Saves the current state, PUT /ip_address/uuid.
[ "IPAddress", "can", "only", "change", "its", "PTR", "record", ".", "Saves", "the", "current", "state", "PUT", "/", "ip_address", "/", "uuid", "." ]
python
train
45.857143
SheffieldML/GPy
GPy/kern/src/mlp.py
https://github.com/SheffieldML/GPy/blob/54c32d79d289d622fb18b898aee65a2a431d90cf/GPy/kern/src/mlp.py#L79-L81
def gradients_X(self, dL_dK, X, X2): """Derivative of the covariance matrix with respect to X""" return self._comp_grads(dL_dK, X, X2)[3]
[ "def", "gradients_X", "(", "self", ",", "dL_dK", ",", "X", ",", "X2", ")", ":", "return", "self", ".", "_comp_grads", "(", "dL_dK", ",", "X", ",", "X2", ")", "[", "3", "]" ]
Derivative of the covariance matrix with respect to X
[ "Derivative", "of", "the", "covariance", "matrix", "with", "respect", "to", "X" ]
python
train
50.333333
PyPSA/PyPSA
pypsa/io.py
https://github.com/PyPSA/PyPSA/blob/46954b1b3c21460550f7104681517065279a53b7/pypsa/io.py#L607-L687
def import_components_from_dataframe(network, dataframe, cls_name): """ Import components from a pandas DataFrame. If columns are missing then defaults are used. If extra columns are added, these are left in the resulting component dataframe. Parameters ---------- dataframe : pandas.DataF...
[ "def", "import_components_from_dataframe", "(", "network", ",", "dataframe", ",", "cls_name", ")", ":", "if", "cls_name", "==", "\"Generator\"", "and", "\"source\"", "in", "dataframe", ".", "columns", ":", "logger", ".", "warning", "(", "\"'source' for generators is...
Import components from a pandas DataFrame. If columns are missing then defaults are used. If extra columns are added, these are left in the resulting component dataframe. Parameters ---------- dataframe : pandas.DataFrame cls_name : string Name of class of component Examples ...
[ "Import", "components", "from", "a", "pandas", "DataFrame", "." ]
python
train
41.567901
sepandhaghighi/pycm
pycm/pycm_class_func.py
https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_class_func.py#L243-L262
def IS_calc(TP, FP, FN, POP): """ Calculate IS (Information score). :param TP: true positive :type TP : int :param FP: false positive :type FP : int :param FN: false negative :type FN : int :param POP: population :type POP : int :return: IS as float """ try: ...
[ "def", "IS_calc", "(", "TP", ",", "FP", ",", "FN", ",", "POP", ")", ":", "try", ":", "result", "=", "-", "math", ".", "log", "(", "(", "(", "TP", "+", "FN", ")", "/", "POP", ")", ",", "2", ")", "+", "math", ".", "log", "(", "(", "TP", "...
Calculate IS (Information score). :param TP: true positive :type TP : int :param FP: false positive :type FP : int :param FN: false negative :type FN : int :param POP: population :type POP : int :return: IS as float
[ "Calculate", "IS", "(", "Information", "score", ")", "." ]
python
train
22.65
vxgmichel/aiostream
aiostream/stream/misc.py
https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/misc.py#L12-L26
def action(source, func): """Perform an action for each element of an asynchronous sequence without modifying it. The given function can be synchronous or asynchronous. """ if asyncio.iscoroutinefunction(func): async def innerfunc(arg): await func(arg) return arg ...
[ "def", "action", "(", "source", ",", "func", ")", ":", "if", "asyncio", ".", "iscoroutinefunction", "(", "func", ")", ":", "async", "def", "innerfunc", "(", "arg", ")", ":", "await", "func", "(", "arg", ")", "return", "arg", "else", ":", "def", "inne...
Perform an action for each element of an asynchronous sequence without modifying it. The given function can be synchronous or asynchronous.
[ "Perform", "an", "action", "for", "each", "element", "of", "an", "asynchronous", "sequence", "without", "modifying", "it", "." ]
python
train
28.2
disqus/nydus
nydus/db/routers/keyvalue.py
https://github.com/disqus/nydus/blob/9b505840da47a34f758a830c3992fa5dcb7bb7ad/nydus/db/routers/keyvalue.py#L66-L79
def _route(self, attr, args, kwargs, **fkwargs): """ The first argument is assumed to be the ``key`` for routing. """ key = get_key(args, kwargs) found = self._hash.get_node(key) if not found and len(self._down_connections) > 0: raise self.HostListExhausted...
[ "def", "_route", "(", "self", ",", "attr", ",", "args", ",", "kwargs", ",", "*", "*", "fkwargs", ")", ":", "key", "=", "get_key", "(", "args", ",", "kwargs", ")", "found", "=", "self", ".", "_hash", ".", "get_node", "(", "key", ")", "if", "not", ...
The first argument is assumed to be the ``key`` for routing.
[ "The", "first", "argument", "is", "assumed", "to", "be", "the", "key", "for", "routing", "." ]
python
train
29.5
sosreport/sos
sos/policies/__init__.py
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L106-L113
def _query_service(self, name): """Query an individual service""" if self.query_cmd: try: return sos_get_command_output("%s %s" % (self.query_cmd, name)) except Exception: return None return None
[ "def", "_query_service", "(", "self", ",", "name", ")", ":", "if", "self", ".", "query_cmd", ":", "try", ":", "return", "sos_get_command_output", "(", "\"%s %s\"", "%", "(", "self", ".", "query_cmd", ",", "name", ")", ")", "except", "Exception", ":", "re...
Query an individual service
[ "Query", "an", "individual", "service" ]
python
train
33.5
crytic/pyevmasm
pyevmasm/evmasm.py
https://github.com/crytic/pyevmasm/blob/d27daf19a36d630a31499e783b716cf1165798d8/pyevmasm/evmasm.py#L516-L539
def assemble(asmcode, pc=0, fork=DEFAULT_FORK): """ Assemble an EVM program :param asmcode: an evm assembler program :type asmcode: str :param pc: program counter of the first instruction(optional) :type pc: int :param fork: fork name (optional) :type fork: str ...
[ "def", "assemble", "(", "asmcode", ",", "pc", "=", "0", ",", "fork", "=", "DEFAULT_FORK", ")", ":", "return", "b''", ".", "join", "(", "x", ".", "bytes", "for", "x", "in", "assemble_all", "(", "asmcode", ",", "pc", "=", "pc", ",", "fork", "=", "f...
Assemble an EVM program :param asmcode: an evm assembler program :type asmcode: str :param pc: program counter of the first instruction(optional) :type pc: int :param fork: fork name (optional) :type fork: str :return: the hex representation of the bytecode ...
[ "Assemble", "an", "EVM", "program" ]
python
valid
34.333333
Azure/blobxfer
blobxfer/models/upload.py
https://github.com/Azure/blobxfer/blob/3eccbe7530cc6a20ab2d30f9e034b6f021817f34/blobxfer/models/upload.py#L734-L771
def _compute_total_chunks(self, chunk_size): # type: (Descriptor, int) -> int """Compute total number of chunks for entity :param Descriptor self: this :param int chunk_size: chunk size :rtype: int :return: num chunks """ try: chunks = int(math...
[ "def", "_compute_total_chunks", "(", "self", ",", "chunk_size", ")", ":", "# type: (Descriptor, int) -> int", "try", ":", "chunks", "=", "int", "(", "math", ".", "ceil", "(", "self", ".", "_ase", ".", "size", "/", "chunk_size", ")", ")", "except", "ZeroDivis...
Compute total number of chunks for entity :param Descriptor self: this :param int chunk_size: chunk size :rtype: int :return: num chunks
[ "Compute", "total", "number", "of", "chunks", "for", "entity", ":", "param", "Descriptor", "self", ":", "this", ":", "param", "int", "chunk_size", ":", "chunk", "size", ":", "rtype", ":", "int", ":", "return", ":", "num", "chunks" ]
python
train
45.973684
mvantellingen/py-soap-wsse
src/soap_wsse/signing.py
https://github.com/mvantellingen/py-soap-wsse/blob/ae01285b9670fe98375312103c0bdf68ea2fe89d/src/soap_wsse/signing.py#L97-L122
def sign_envelope(envelope, key_file): """Sign the given soap request with the given key""" doc = etree.fromstring(envelope) body = get_body(doc) queue = SignQueue() queue.push_and_mark(body) security_node = ensure_security_header(doc, queue) security_token_node = create_binary_security_to...
[ "def", "sign_envelope", "(", "envelope", ",", "key_file", ")", ":", "doc", "=", "etree", ".", "fromstring", "(", "envelope", ")", "body", "=", "get_body", "(", "doc", ")", "queue", "=", "SignQueue", "(", ")", "queue", ".", "push_and_mark", "(", "body", ...
Sign the given soap request with the given key
[ "Sign", "the", "given", "soap", "request", "with", "the", "given", "key" ]
python
train
33.076923
chaimleib/intervaltree
intervaltree/intervaltree.py
https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L244-L250
def from_tuples(cls, tups): """ Create a new IntervalTree from an iterable of 2- or 3-tuples, where the tuple lists begin, end, and optionally data. """ ivs = [Interval(*t) for t in tups] return IntervalTree(ivs)
[ "def", "from_tuples", "(", "cls", ",", "tups", ")", ":", "ivs", "=", "[", "Interval", "(", "*", "t", ")", "for", "t", "in", "tups", "]", "return", "IntervalTree", "(", "ivs", ")" ]
Create a new IntervalTree from an iterable of 2- or 3-tuples, where the tuple lists begin, end, and optionally data.
[ "Create", "a", "new", "IntervalTree", "from", "an", "iterable", "of", "2", "-", "or", "3", "-", "tuples", "where", "the", "tuple", "lists", "begin", "end", "and", "optionally", "data", "." ]
python
train
36.428571
tanghaibao/jcvi
jcvi/compara/reconstruct.py
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/compara/reconstruct.py#L69-L103
def fuse(args): """ %prog fuse *.bed *.anchors Fuse gene orders based on anchors file. """ from jcvi.algorithms.graph import BiGraph p = OptionParser(fuse.__doc__) opts, args = p.parse_args(args) if len(args) < 1: sys.exit(not p.print_help()) bedfiles = [x for x in args i...
[ "def", "fuse", "(", "args", ")", ":", "from", "jcvi", ".", "algorithms", ".", "graph", "import", "BiGraph", "p", "=", "OptionParser", "(", "fuse", ".", "__doc__", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", ...
%prog fuse *.bed *.anchors Fuse gene orders based on anchors file.
[ "%prog", "fuse", "*", ".", "bed", "*", ".", "anchors" ]
python
train
29.514286
GPflow/GPflow
gpflow/training/hmc.py
https://github.com/GPflow/GPflow/blob/549394f0b1b0696c7b521a065e49bdae6e7acf27/gpflow/training/hmc.py#L24-L124
def sample(self, model, num_samples, epsilon, lmin=1, lmax=1, thin=1, burn=0, session=None, initialize=True, anchor=True, logprobs=True): """ A straight-forward HMC implementation. The mass matrix is assumed to be the identity. The gpflow mod...
[ "def", "sample", "(", "self", ",", "model", ",", "num_samples", ",", "epsilon", ",", "lmin", "=", "1", ",", "lmax", "=", "1", ",", "thin", "=", "1", ",", "burn", "=", "0", ",", "session", "=", "None", ",", "initialize", "=", "True", ",", "anchor"...
A straight-forward HMC implementation. The mass matrix is assumed to be the identity. The gpflow model must implement `build_objective` method to build `f` function (tensor) which in turn based on model's internal trainable parameters `x`. f(x) = E(x) we then generate samp...
[ "A", "straight", "-", "forward", "HMC", "implementation", ".", "The", "mass", "matrix", "is", "assumed", "to", "be", "the", "identity", "." ]
python
train
43.623762
alejandroautalan/pygubu
pygubu/stockimage.py
https://github.com/alejandroautalan/pygubu/blob/41c8fb37ef973736ec5d68cbe1cd4ecb78712e40/pygubu/stockimage.py#L124-L136
def get(cls, rkey): """Get image previously registered with key rkey. If key not exist, raise StockImageException """ if rkey in cls._cached: logger.info('Resource %s is in cache.' % rkey) return cls._cached[rkey] if rkey in cls._stock: img = ...
[ "def", "get", "(", "cls", ",", "rkey", ")", ":", "if", "rkey", "in", "cls", ".", "_cached", ":", "logger", ".", "info", "(", "'Resource %s is in cache.'", "%", "rkey", ")", "return", "cls", ".", "_cached", "[", "rkey", "]", "if", "rkey", "in", "cls",...
Get image previously registered with key rkey. If key not exist, raise StockImageException
[ "Get", "image", "previously", "registered", "with", "key", "rkey", ".", "If", "key", "not", "exist", "raise", "StockImageException" ]
python
train
34.230769
brian-rose/climlab
climlab/process/process.py
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/process/process.py#L396-L405
def _add_field(self, field_type, name, value): """Adds a new field to a specified dictionary. The field is also added as a process attribute. field_type can be 'input', 'diagnostics' """ try: self.__getattribute__(field_type).update({name: value}) except: raise Va...
[ "def", "_add_field", "(", "self", ",", "field_type", ",", "name", ",", "value", ")", ":", "try", ":", "self", ".", "__getattribute__", "(", "field_type", ")", ".", "update", "(", "{", "name", ":", "value", "}", ")", "except", ":", "raise", "ValueError"...
Adds a new field to a specified dictionary. The field is also added as a process attribute. field_type can be 'input', 'diagnostics'
[ "Adds", "a", "new", "field", "to", "a", "specified", "dictionary", ".", "The", "field", "is", "also", "added", "as", "a", "process", "attribute", ".", "field_type", "can", "be", "input", "diagnostics" ]
python
train
51.7
lltk/lltk
lltk/decorators.py
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/decorators.py#L6-L19
def language(l): ''' Use this as a decorator (implicitly or explicitly). ''' # Usage: @language('en') or function = language('en')(function) def decorator(f): ''' Decorator used to prepend the language as an argument. ''' @wraps(f) def wrapper(*args, **kwargs): return f(l, *args, **kwargs) return wrapp...
[ "def", "language", "(", "l", ")", ":", "# Usage: @language('en') or function = language('en')(function)", "def", "decorator", "(", "f", ")", ":", "''' Decorator used to prepend the language as an argument. '''", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "...
Use this as a decorator (implicitly or explicitly).
[ "Use", "this", "as", "a", "decorator", "(", "implicitly", "or", "explicitly", ")", "." ]
python
train
23.428571
mitsei/dlkit
dlkit/records/assessment/orthographic_visualization/multi_choice_records.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/records/assessment/orthographic_visualization/multi_choice_records.py#L149-L153
def _init_metadata(self): """stub""" QuestionFilesFormRecord._init_metadata(self) FirstAngleProjectionFormRecord._init_metadata(self) super(MultiChoiceOrthoQuestionFormRecord, self)._init_metadata()
[ "def", "_init_metadata", "(", "self", ")", ":", "QuestionFilesFormRecord", ".", "_init_metadata", "(", "self", ")", "FirstAngleProjectionFormRecord", ".", "_init_metadata", "(", "self", ")", "super", "(", "MultiChoiceOrthoQuestionFormRecord", ",", "self", ")", ".", ...
stub
[ "stub" ]
python
train
45.2
google/prettytensor
prettytensor/pretty_tensor_methods.py
https://github.com/google/prettytensor/blob/75daa0b11252590f548da5647addc0ea610c4c45/prettytensor/pretty_tensor_methods.py#L613-L625
def _zip_with_scalars(args): """Zips across args in order and replaces non-iterables with repeats.""" zipped = [] for arg in args: if isinstance(arg, prettytensor.PrettyTensor): zipped.append(arg if arg.is_sequence() else itertools.repeat(arg)) elif (isinstance(arg, collections.Sequence) and ...
[ "def", "_zip_with_scalars", "(", "args", ")", ":", "zipped", "=", "[", "]", "for", "arg", "in", "args", ":", "if", "isinstance", "(", "arg", ",", "prettytensor", ".", "PrettyTensor", ")", ":", "zipped", ".", "append", "(", "arg", "if", "arg", ".", "i...
Zips across args in order and replaces non-iterables with repeats.
[ "Zips", "across", "args", "in", "order", "and", "replaces", "non", "-", "iterables", "with", "repeats", "." ]
python
train
38.230769
nyaruka/smartmin
smartmin/templatetags/smartmin.py
https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/templatetags/smartmin.py#L24-L29
def get_list_class(context, list): """ Returns the class to use for the passed in list. We just build something up from the object type for the list. """ return "list_%s_%s" % (list.model._meta.app_label, list.model._meta.model_name)
[ "def", "get_list_class", "(", "context", ",", "list", ")", ":", "return", "\"list_%s_%s\"", "%", "(", "list", ".", "model", ".", "_meta", ".", "app_label", ",", "list", ".", "model", ".", "_meta", ".", "model_name", ")" ]
Returns the class to use for the passed in list. We just build something up from the object type for the list.
[ "Returns", "the", "class", "to", "use", "for", "the", "passed", "in", "list", ".", "We", "just", "build", "something", "up", "from", "the", "object", "type", "for", "the", "list", "." ]
python
train
41.5
Becksteinlab/GromacsWrapper
gromacs/setup.py
https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/setup.py#L221-L307
def make_main_index(struct, selection='"Protein"', ndx='main.ndx', oldndx=None): """Make index file with the special groups. This routine adds the group __main__ and the group __environment__ to the end of the index file. __main__ contains what the user defines as the *central* and *most important* par...
[ "def", "make_main_index", "(", "struct", ",", "selection", "=", "'\"Protein\"'", ",", "ndx", "=", "'main.ndx'", ",", "oldndx", "=", "None", ")", ":", "logger", ".", "info", "(", "\"Building the main index file {ndx!r}...\"", ".", "format", "(", "*", "*", "vars...
Make index file with the special groups. This routine adds the group __main__ and the group __environment__ to the end of the index file. __main__ contains what the user defines as the *central* and *most important* parts of the system. __environment__ is everything else. The template mdp file, fo...
[ "Make", "index", "file", "with", "the", "special", "groups", "." ]
python
valid
43.264368
tomi77/pyems
pyems/__init__.py
https://github.com/tomi77/pyems/blob/8c0748b720d389f19d5226fdcceedc26cd6284ee/pyems/__init__.py#L642-L722
def transcode(self, source, destinations, **kwargs): """ Changes the compression characteristics of an audio and/or video stream. Allows you to change the resolution of a source stream, change the bitrate of a stream, change a VP8 or MPEG2 stream into H.264 and much more. Allow u...
[ "def", "transcode", "(", "self", ",", "source", ",", "destinations", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "protocol", ".", "execute", "(", "'transcode'", ",", "source", "=", "source", ",", "destinations", "=", "destinations", ",", "*...
Changes the compression characteristics of an audio and/or video stream. Allows you to change the resolution of a source stream, change the bitrate of a stream, change a VP8 or MPEG2 stream into H.264 and much more. Allow users to create overlays on the final stream as well as crop strea...
[ "Changes", "the", "compression", "characteristics", "of", "an", "audio", "and", "/", "or", "video", "stream", ".", "Allows", "you", "to", "change", "the", "resolution", "of", "a", "source", "stream", "change", "the", "bitrate", "of", "a", "stream", "change",...
python
valid
44.839506
Dentosal/python-sc2
sc2/client.py
https://github.com/Dentosal/python-sc2/blob/608bd25f04e89d39cef68b40101d8e9a8a7f1634/sc2/client.py#L386-L392
def debug_text_screen(self, text: str, pos: Union[Point2, Point3, tuple, list], color=None, size: int = 8): """ Draws a text on the screen with coordinates 0 <= x, y <= 1. Don't forget to add 'await self._client.send_debug'. """ assert len(pos) >= 2 assert 0 <= pos[0] <= 1 assert 0 <= po...
[ "def", "debug_text_screen", "(", "self", ",", "text", ":", "str", ",", "pos", ":", "Union", "[", "Point2", ",", "Point3", ",", "tuple", ",", "list", "]", ",", "color", "=", "None", ",", "size", ":", "int", "=", "8", ")", ":", "assert", "len", "("...
Draws a text on the screen with coordinates 0 <= x, y <= 1. Don't forget to add 'await self._client.send_debug'.
[ "Draws", "a", "text", "on", "the", "screen", "with", "coordinates", "0", "<", "=", "x", "y", "<", "=", "1", ".", "Don", "t", "forget", "to", "add", "await", "self", ".", "_client", ".", "send_debug", "." ]
python
train
63.142857
bitesofcode/projexui
projexui/widgets/xoverlaywidget.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xoverlaywidget.py#L153-L161
def resizeEvent(self, event): """ Handles a resize event for this overlay, centering the central widget if one is found. :param event | <QtCore.QEvent> """ super(XOverlayWidget, self).resizeEvent(event) self.adjustSize()
[ "def", "resizeEvent", "(", "self", ",", "event", ")", ":", "super", "(", "XOverlayWidget", ",", "self", ")", ".", "resizeEvent", "(", "event", ")", "self", ".", "adjustSize", "(", ")" ]
Handles a resize event for this overlay, centering the central widget if one is found. :param event | <QtCore.QEvent>
[ "Handles", "a", "resize", "event", "for", "this", "overlay", "centering", "the", "central", "widget", "if", "one", "is", "found", "." ]
python
train
30.444444
michaelhelmick/lassie
lassie/utils.py
https://github.com/michaelhelmick/lassie/blob/b929f78d7e545cff5fb42eb5edfcaf396456f1ee/lassie/utils.py#L31-L48
def convert_to_int(value): """Attempts to convert a specified value to an integer :param value: Content to be converted into an integer :type value: string or int """ if not value: return None # Apart from numbers also accept values that end with px if isinstance(value, str): ...
[ "def", "convert_to_int", "(", "value", ")", ":", "if", "not", "value", ":", "return", "None", "# Apart from numbers also accept values that end with px", "if", "isinstance", "(", "value", ",", "str", ")", ":", "value", "=", "value", ".", "strip", "(", "' px'", ...
Attempts to convert a specified value to an integer :param value: Content to be converted into an integer :type value: string or int
[ "Attempts", "to", "convert", "a", "specified", "value", "to", "an", "integer" ]
python
train
23.611111
wummel/linkchecker
linkcheck/logger/html.py
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/logger/html.py#L179-L182
def write_name (self, url_data): """Write url_data.name.""" args = (self.part("name"), cgi.escape(url_data.name)) self.writeln(u"<tr><td>%s</td><td>`%s'</td></tr>" % args)
[ "def", "write_name", "(", "self", ",", "url_data", ")", ":", "args", "=", "(", "self", ".", "part", "(", "\"name\"", ")", ",", "cgi", ".", "escape", "(", "url_data", ".", "name", ")", ")", "self", ".", "writeln", "(", "u\"<tr><td>%s</td><td>`%s'</td></tr...
Write url_data.name.
[ "Write", "url_data", ".", "name", "." ]
python
train
48
readbeyond/aeneas
aeneas/tools/abstract_cli_program.py
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tools/abstract_cli_program.py#L260-L268
def print_name_version(self): """ Print program name and version and exit. :rtype: int """ if self.use_sys: self.print_generic(u"%s v%s" % (self.NAME, aeneas_version)) return self.exit(self.HELP_EXIT_CODE)
[ "def", "print_name_version", "(", "self", ")", ":", "if", "self", ".", "use_sys", ":", "self", ".", "print_generic", "(", "u\"%s v%s\"", "%", "(", "self", ".", "NAME", ",", "aeneas_version", ")", ")", "return", "self", ".", "exit", "(", "self", ".", "H...
Print program name and version and exit. :rtype: int
[ "Print", "program", "name", "and", "version", "and", "exit", "." ]
python
train
28.666667
dfm/transit
transit/transit.py
https://github.com/dfm/transit/blob/482d99b506657fa3fd54a388f9c6be13b9e57bce/transit/transit.py#L348-L364
def duration(self): """ The approximate duration of the transit :math:`T_\mathrm{tot}` from Equation (14) in Winn (2010). """ self._check_ps() rstar = self.system.central.radius k = self.r/rstar dur = self.period / np.pi arg = rstar/self.a * np.s...
[ "def", "duration", "(", "self", ")", ":", "self", ".", "_check_ps", "(", ")", "rstar", "=", "self", ".", "system", ".", "central", ".", "radius", "k", "=", "self", ".", "r", "/", "rstar", "dur", "=", "self", ".", "period", "/", "np", ".", "pi", ...
The approximate duration of the transit :math:`T_\mathrm{tot}` from Equation (14) in Winn (2010).
[ "The", "approximate", "duration", "of", "the", "transit", ":", "math", ":", "T_", "\\", "mathrm", "{", "tot", "}", "from", "Equation", "(", "14", ")", "in", "Winn", "(", "2010", ")", "." ]
python
train
30.941176
inasafe/inasafe
safe/plugin.py
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L960-L968
def add_petabencana_layer(self): """Add petabencana layer to the map. This uses the PetaBencana API to fetch the latest floods in JK. See https://data.petabencana.id/floods """ from safe.gui.tools.peta_bencana_dialog import PetaBencanaDialog dialog = PetaBencanaDialog(se...
[ "def", "add_petabencana_layer", "(", "self", ")", ":", "from", "safe", ".", "gui", ".", "tools", ".", "peta_bencana_dialog", "import", "PetaBencanaDialog", "dialog", "=", "PetaBencanaDialog", "(", "self", ".", "iface", ".", "mainWindow", "(", ")", ",", "self",...
Add petabencana layer to the map. This uses the PetaBencana API to fetch the latest floods in JK. See https://data.petabencana.id/floods
[ "Add", "petabencana", "layer", "to", "the", "map", "." ]
python
train
40.888889
openid/python-openid
openid/extensions/draft/pape5.py
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/extensions/draft/pape5.py#L298-L310
def setAuthLevel(self, level_uri, level, alias=None): """Set the value for the given auth level type. @param level: string representation of an authentication level valid for level_uri @param alias: An optional namespace alias for the given auth level URI. May be omitte...
[ "def", "setAuthLevel", "(", "self", ",", "level_uri", ",", "level", ",", "alias", "=", "None", ")", ":", "self", ".", "_addAuthLevelAlias", "(", "level_uri", ",", "alias", ")", "self", ".", "auth_levels", "[", "level_uri", "]", "=", "level" ]
Set the value for the given auth level type. @param level: string representation of an authentication level valid for level_uri @param alias: An optional namespace alias for the given auth level URI. May be omitted if the alias is not significant. The library will u...
[ "Set", "the", "value", "for", "the", "given", "auth", "level", "type", "." ]
python
train
42.153846
oblalex/django-candv-choices
candv_x/django/choices/db.py
https://github.com/oblalex/django-candv-choices/blob/a299cefceebc2fb23e223dfcc63700dff572b6a0/candv_x/django/choices/db.py#L87-L96
def _get_choices(self): """ Redefine standard method. """ if not self._choices: self._choices = tuple( (x.name, getattr(x, 'verbose_name', x.name) or x.name) for x in self.choices_class.constants() ) return self._choices
[ "def", "_get_choices", "(", "self", ")", ":", "if", "not", "self", ".", "_choices", ":", "self", ".", "_choices", "=", "tuple", "(", "(", "x", ".", "name", ",", "getattr", "(", "x", ",", "'verbose_name'", ",", "x", ".", "name", ")", "or", "x", "....
Redefine standard method.
[ "Redefine", "standard", "method", "." ]
python
train
30.7
NLeSC/noodles
noodles/workflow/graphs.py
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/workflow/graphs.py#L1-L18
def find_links_to(links, node): """Find links to a node. :param links: forward links of a workflow :type links: Mapping[NodeId, Set[(NodeId, ArgumentType, [int|str]])] :param node: index to a node :type node: int :returns: dictionary of sources for each argument :r...
[ "def", "find_links_to", "(", "links", ",", "node", ")", ":", "return", "{", "address", ":", "src", "for", "src", ",", "(", "tgt", ",", "address", ")", "in", "_all_valid", "(", "links", ")", "if", "tgt", "==", "node", "}" ]
Find links to a node. :param links: forward links of a workflow :type links: Mapping[NodeId, Set[(NodeId, ArgumentType, [int|str]])] :param node: index to a node :type node: int :returns: dictionary of sources for each argument :rtype: Mapping[(ArgumentType, [int|str])...
[ "Find", "links", "to", "a", "node", "." ]
python
train
26.055556
saltstack/salt
salt/modules/infoblox.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L261-L277
def delete_cname(name=None, canonical=None, **api_opts): ''' Delete CNAME. This is a helper call to delete_object. If record is not found, return True CLI Examples: .. code-block:: bash salt-call infoblox.delete_cname name=example.example.com salt-call infoblox.delete_cname canon...
[ "def", "delete_cname", "(", "name", "=", "None", ",", "canonical", "=", "None", ",", "*", "*", "api_opts", ")", ":", "cname", "=", "get_cname", "(", "name", "=", "name", ",", "canonical", "=", "canonical", ",", "*", "*", "api_opts", ")", "if", "cname...
Delete CNAME. This is a helper call to delete_object. If record is not found, return True CLI Examples: .. code-block:: bash salt-call infoblox.delete_cname name=example.example.com salt-call infoblox.delete_cname canonical=example-ha-0.example.com
[ "Delete", "CNAME", ".", "This", "is", "a", "helper", "call", "to", "delete_object", "." ]
python
train
29
bitesofcode/projexui
projexui/widgets/xtreewidget/xtreewidget.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtreewidget/xtreewidget.py#L1728-L1736
def setGridPen( self, gridPen ): """ Sets the pen that will be used when drawing the grid lines. :param gridPen | <QtGui.QPen> || <QtGui.QColor> """ delegate = self.itemDelegate() if ( isinstance(delegate, XTreeWidgetDelegate) ): delegate...
[ "def", "setGridPen", "(", "self", ",", "gridPen", ")", ":", "delegate", "=", "self", ".", "itemDelegate", "(", ")", "if", "(", "isinstance", "(", "delegate", ",", "XTreeWidgetDelegate", ")", ")", ":", "delegate", ".", "setGridPen", "(", "gridPen", ")" ]
Sets the pen that will be used when drawing the grid lines. :param gridPen | <QtGui.QPen> || <QtGui.QColor>
[ "Sets", "the", "pen", "that", "will", "be", "used", "when", "drawing", "the", "grid", "lines", ".", ":", "param", "gridPen", "|", "<QtGui", ".", "QPen", ">", "||", "<QtGui", ".", "QColor", ">" ]
python
train
36.888889
Kozea/cairocffi
cairocffi/fonts.py
https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/fonts.py#L411-L420
def merge(self, other): """Merges non-default options from :obj:`other`, replacing existing values. This operation can be thought of as somewhat similar to compositing other onto options with the operation of :obj:`OVER <OPERATOR_OVER>`. """ cairo.cairo_font_opti...
[ "def", "merge", "(", "self", ",", "other", ")", ":", "cairo", ".", "cairo_font_options_merge", "(", "self", ".", "_pointer", ",", "other", ".", "_pointer", ")", "_check_status", "(", "cairo", ".", "cairo_font_options_status", "(", "self", ".", "_pointer", ")...
Merges non-default options from :obj:`other`, replacing existing values. This operation can be thought of as somewhat similar to compositing other onto options with the operation of :obj:`OVER <OPERATOR_OVER>`.
[ "Merges", "non", "-", "default", "options", "from", ":", "obj", ":", "other", "replacing", "existing", "values", ".", "This", "operation", "can", "be", "thought", "of", "as", "somewhat", "similar", "to", "compositing", "other", "onto", "options", "with", "th...
python
train
42.1
seznam/shelter
shelter/utils/imports.py
https://github.com/seznam/shelter/blob/c652b0ff1cca70158f8fc97d9210c1fa5961ac1c/shelter/utils/imports.py#L10-L25
def import_object(name): """ Import module and return object from it. *name* is :class:`str` in format ``module.path.ObjectClass``. :: >>> import_command('module.path.ObjectClass') <class 'module.path.ObjectClass'> """ parts = name.split('.') if len(parts) < 2: raise...
[ "def", "import_object", "(", "name", ")", ":", "parts", "=", "name", ".", "split", "(", "'.'", ")", "if", "len", "(", "parts", ")", "<", "2", ":", "raise", "ValueError", "(", "\"Invalid name '%s'\"", "%", "name", ")", "module_name", "=", "\".\"", ".", ...
Import module and return object from it. *name* is :class:`str` in format ``module.path.ObjectClass``. :: >>> import_command('module.path.ObjectClass') <class 'module.path.ObjectClass'>
[ "Import", "module", "and", "return", "object", "from", "it", ".", "*", "name", "*", "is", ":", "class", ":", "str", "in", "format", "module", ".", "path", ".", "ObjectClass", "." ]
python
train
30.9375
hydpy-dev/hydpy
hydpy/core/netcdftools.py
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/netcdftools.py#L2126-L2141
def _product(shape) -> Iterator[Tuple[int, ...]]: """Should return all "subdevice index combinations" for sequences with arbitrary dimensions: >>> from hydpy.core.netcdftools import NetCDFVariableFlat >>> _product = NetCDFVariableFlat.__dict__['_product'].__func__ >>> for comb i...
[ "def", "_product", "(", "shape", ")", "->", "Iterator", "[", "Tuple", "[", "int", ",", "...", "]", "]", ":", "return", "itertools", ".", "product", "(", "*", "(", "range", "(", "nmb", ")", "for", "nmb", "in", "shape", ")", ")" ]
Should return all "subdevice index combinations" for sequences with arbitrary dimensions: >>> from hydpy.core.netcdftools import NetCDFVariableFlat >>> _product = NetCDFVariableFlat.__dict__['_product'].__func__ >>> for comb in _product([1, 2, 3]): ... print(comb) (0...
[ "Should", "return", "all", "subdevice", "index", "combinations", "for", "sequences", "with", "arbitrary", "dimensions", ":" ]
python
train
33.75
elliterate/capybara.py
capybara/selector/selector.py
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/selector/selector.py#L141-L157
def node_filter(self, name, **kwargs): """ Returns a decorator function for adding a node filter. Args: name (str): The name of the filter. **kwargs: Variable keyword arguments for the filter. Returns: Callable[[Callable[[Element, Any], bool]]]: A de...
[ "def", "node_filter", "(", "self", ",", "name", ",", "*", "*", "kwargs", ")", ":", "def", "decorator", "(", "func", ")", ":", "self", ".", "filters", "[", "name", "]", "=", "NodeFilter", "(", "name", ",", "func", ",", "*", "*", "kwargs", ")", "re...
Returns a decorator function for adding a node filter. Args: name (str): The name of the filter. **kwargs: Variable keyword arguments for the filter. Returns: Callable[[Callable[[Element, Any], bool]]]: A decorator function for adding a node filter.
[ "Returns", "a", "decorator", "function", "for", "adding", "a", "node", "filter", "." ]
python
test
29.176471
jonfaustman/django-frontend
djfrontend/templatetags/djfrontend.py
https://github.com/jonfaustman/django-frontend/blob/897934d593fade0eb1998f8fadd18c91a89e5b9a/djfrontend/templatetags/djfrontend.py#L46-L56
def djfrontend_normalize(version=None): """ Returns Normalize CSS file. Included in HTML5 Boilerplate. """ if version is None: version = getattr(settings, 'DJFRONTEND_NORMALIZE', DJFRONTEND_NORMALIZE_DEFAULT) return format_html( '<link rel="stylesheet" href="{0}djfrontend/css/no...
[ "def", "djfrontend_normalize", "(", "version", "=", "None", ")", ":", "if", "version", "is", "None", ":", "version", "=", "getattr", "(", "settings", ",", "'DJFRONTEND_NORMALIZE'", ",", "DJFRONTEND_NORMALIZE_DEFAULT", ")", "return", "format_html", "(", "'<link rel...
Returns Normalize CSS file. Included in HTML5 Boilerplate.
[ "Returns", "Normalize", "CSS", "file", ".", "Included", "in", "HTML5", "Boilerplate", "." ]
python
test
33.545455
hydraplatform/hydra-base
hydra_base/lib/scenario.py
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/scenario.py#L910-L936
def get_attribute_data(attr_ids, node_ids, **kwargs): """ For a given attribute or set of attributes, return all the resources and resource scenarios in the network """ node_attrs = db.DBSession.query(ResourceAttr).\ options(joinedload_all('attr')...
[ "def", "get_attribute_data", "(", "attr_ids", ",", "node_ids", ",", "*", "*", "kwargs", ")", ":", "node_attrs", "=", "db", ".", "DBSession", ".", "query", "(", "ResourceAttr", ")", ".", "options", "(", "joinedload_all", "(", "'attr'", ")", ")", ".", "fil...
For a given attribute or set of attributes, return all the resources and resource scenarios in the network
[ "For", "a", "given", "attribute", "or", "set", "of", "attributes", "return", "all", "the", "resources", "and", "resource", "scenarios", "in", "the", "network" ]
python
train
40.111111
peopledoc/workalendar
workalendar/core.py
https://github.com/peopledoc/workalendar/blob/d044d5dfc1709ec388db34dab583dd554cc66c4e/workalendar/core.py#L421-L424
def get_easter_monday(self, year): "Return the date of the monday after easter" sunday = self.get_easter_sunday(year) return sunday + timedelta(days=1)
[ "def", "get_easter_monday", "(", "self", ",", "year", ")", ":", "sunday", "=", "self", ".", "get_easter_sunday", "(", "year", ")", "return", "sunday", "+", "timedelta", "(", "days", "=", "1", ")" ]
Return the date of the monday after easter
[ "Return", "the", "date", "of", "the", "monday", "after", "easter" ]
python
train
43
awacha/sastool
sastool/classes2/curve.py
https://github.com/awacha/sastool/blob/deaddfa3002f3f6818697e36139633b7e30427a3/sastool/classes2/curve.py#L63-L87
def fit(self, fitfunction, parinit, unfittableparameters=(), *args, **kwargs): """Perform a nonlinear least-squares fit, using sastool.misc.fitter.Fitter() Other arguments and keyword arguments will be passed through to the __init__ method of Fitter. For example, these are: - lbounds ...
[ "def", "fit", "(", "self", ",", "fitfunction", ",", "parinit", ",", "unfittableparameters", "=", "(", ")", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'otherparameters'", "]", "=", "unfittableparameters", "fitter", "=", "Fitter", ...
Perform a nonlinear least-squares fit, using sastool.misc.fitter.Fitter() Other arguments and keyword arguments will be passed through to the __init__ method of Fitter. For example, these are: - lbounds - ubounds - ytransform - loss - method Returns: the...
[ "Perform", "a", "nonlinear", "least", "-", "squares", "fit", "using", "sastool", ".", "misc", ".", "fitter", ".", "Fitter", "()" ]
python
train
43.92
jason-weirather/py-seq-tools
seqtools/structure/gene.py
https://github.com/jason-weirather/py-seq-tools/blob/f642c2c73ffef2acc83656a78059a476fc734ca1/seqtools/structure/gene.py#L408-L448
def trim_ordered_range_list(ranges,start,finish): """A function to help with slicing a mapping Start with a list of ranges and get another list of ranges constrained by start (0-indexed) and finish (1-indexed) :param ranges: ordered non-overlapping ranges on the same chromosome :param start: start 0-i...
[ "def", "trim_ordered_range_list", "(", "ranges", ",", "start", ",", "finish", ")", ":", "z", "=", "0", "keep_ranges", "=", "[", "]", "for", "inrng", "in", "self", ".", "ranges", ":", "z", "+=", "1", "original_rng", "=", "inrng", "rng", "=", "inrng", ...
A function to help with slicing a mapping Start with a list of ranges and get another list of ranges constrained by start (0-indexed) and finish (1-indexed) :param ranges: ordered non-overlapping ranges on the same chromosome :param start: start 0-indexed :param finish: ending 1-indexed :type ...
[ "A", "function", "to", "help", "with", "slicing", "a", "mapping", "Start", "with", "a", "list", "of", "ranges", "and", "get", "another", "list", "of", "ranges", "constrained", "by", "start", "(", "0", "-", "indexed", ")", "and", "finish", "(", "1", "-"...
python
train
39.707317
rhjdjong/SlipLib
sliplib/slipwrapper.py
https://github.com/rhjdjong/SlipLib/blob/8300dba3e512bca282380f234be34d75f4a73ce1/sliplib/slipwrapper.py#L65-L71
def send_msg(self, message): """Send a SLIP-encoded message over the stream. :param bytes message: The message to encode and send """ packet = self.driver.send(message) self.send_bytes(packet)
[ "def", "send_msg", "(", "self", ",", "message", ")", ":", "packet", "=", "self", ".", "driver", ".", "send", "(", "message", ")", "self", ".", "send_bytes", "(", "packet", ")" ]
Send a SLIP-encoded message over the stream. :param bytes message: The message to encode and send
[ "Send", "a", "SLIP", "-", "encoded", "message", "over", "the", "stream", "." ]
python
train
32.428571
glue-viz/glue-vispy-viewers
glue_vispy_viewers/scatter/layer_artist.py
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/scatter/layer_artist.py#L96-L102
def redraw(self): """ Redraw the Vispy canvas """ if self._multiscat is not None: self._multiscat._update() self.vispy_widget.canvas.update()
[ "def", "redraw", "(", "self", ")", ":", "if", "self", ".", "_multiscat", "is", "not", "None", ":", "self", ".", "_multiscat", ".", "_update", "(", ")", "self", ".", "vispy_widget", ".", "canvas", ".", "update", "(", ")" ]
Redraw the Vispy canvas
[ "Redraw", "the", "Vispy", "canvas" ]
python
train
26.714286
marshmallow-code/marshmallow-jsonapi
marshmallow_jsonapi/schema.py
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L280-L301
def format_errors(self, errors, many): """Format validation errors as JSON Error objects.""" if not errors: return {} if isinstance(errors, (list, tuple)): return {'errors': errors} formatted_errors = [] if many: for index, errors in iteritems...
[ "def", "format_errors", "(", "self", ",", "errors", ",", "many", ")", ":", "if", "not", "errors", ":", "return", "{", "}", "if", "isinstance", "(", "errors", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "{", "'errors'", ":", "errors", "...
Format validation errors as JSON Error objects.
[ "Format", "validation", "errors", "as", "JSON", "Error", "objects", "." ]
python
train
39.136364
chrisspen/burlap
burlap/vm.py
https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/vm.py#L383-L526
def get_or_create_ec2_instance(name=None, group=None, release=None, verbose=0, backend_opts=None): """ Creates a new EC2 instance. You should normally run get_or_create() instead of directly calling this. """ from burlap.common import shelf, OrderedDict from boto.exception import EC2ResponseErr...
[ "def", "get_or_create_ec2_instance", "(", "name", "=", "None", ",", "group", "=", "None", ",", "release", "=", "None", ",", "verbose", "=", "0", ",", "backend_opts", "=", "None", ")", ":", "from", "burlap", ".", "common", "import", "shelf", ",", "Ordered...
Creates a new EC2 instance. You should normally run get_or_create() instead of directly calling this.
[ "Creates", "a", "new", "EC2", "instance", "." ]
python
valid
35.493056
apache/airflow
airflow/utils/log/wasb_task_handler.py
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/utils/log/wasb_task_handler.py#L97-L121
def _read(self, ti, try_number, metadata=None): """ Read logs of given task instance and try_number from Wasb remote storage. If failed, read the log from task instance host machine. :param ti: task instance object :param try_number: task instance try_number to read logs from ...
[ "def", "_read", "(", "self", ",", "ti", ",", "try_number", ",", "metadata", "=", "None", ")", ":", "# Explicitly getting log relative path is necessary as the given", "# task instance might be different than task instance passed in", "# in set_context method.", "log_relative_path",...
Read logs of given task instance and try_number from Wasb remote storage. If failed, read the log from task instance host machine. :param ti: task instance object :param try_number: task instance try_number to read logs from :param metadata: log metadata, can be ...
[ "Read", "logs", "of", "given", "task", "instance", "and", "try_number", "from", "Wasb", "remote", "storage", ".", "If", "failed", "read", "the", "log", "from", "task", "instance", "host", "machine", ".", ":", "param", "ti", ":", "task", "instance", "object...
python
test
51.64
inspirehep/harvesting-kit
harvestingkit/inspire_cds_package/from_inspire.py
https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/inspire_cds_package/from_inspire.py#L572-L600
def update_links_and_ffts(self): """FFT (856) Dealing with files.""" for field in record_get_field_instances(self.record, tag='856', ind1='4'): subs = field_get_subfields(field) newsub...
[ "def", "update_links_and_ffts", "(", "self", ")", ":", "for", "field", "in", "record_get_field_instances", "(", "self", ".", "record", ",", "tag", "=", "'856'", ",", "ind1", "=", "'4'", ")", ":", "subs", "=", "field_get_subfields", "(", "field", ")", "news...
FFT (856) Dealing with files.
[ "FFT", "(", "856", ")", "Dealing", "with", "files", "." ]
python
valid
43.862069
osrg/ryu
ryu/services/protocols/bgp/peer.py
https://github.com/osrg/ryu/blob/6f906e72c92e10bd0264c9b91a2f7bb85b97780c/ryu/services/protocols/bgp/peer.py#L1592-L1652
def _extract_and_reconstruct_as_path(self, update_msg): """Extracts advertised AS path attributes in the given update message and reconstructs AS_PATH from AS_PATH and AS4_PATH if needed.""" umsg_pattrs = update_msg.pathattr_map as_aggregator = umsg_pattrs.get(BGP_ATTR_TYPE_AGGREGATOR, ...
[ "def", "_extract_and_reconstruct_as_path", "(", "self", ",", "update_msg", ")", ":", "umsg_pattrs", "=", "update_msg", ".", "pathattr_map", "as_aggregator", "=", "umsg_pattrs", ".", "get", "(", "BGP_ATTR_TYPE_AGGREGATOR", ",", "None", ")", "as4_aggregator", "=", "um...
Extracts advertised AS path attributes in the given update message and reconstructs AS_PATH from AS_PATH and AS4_PATH if needed.
[ "Extracts", "advertised", "AS", "path", "attributes", "in", "the", "given", "update", "message", "and", "reconstructs", "AS_PATH", "from", "AS_PATH", "and", "AS4_PATH", "if", "needed", "." ]
python
train
54.393443
edx/edx-enterprise
enterprise/utils.py
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/utils.py#L715-L730
def is_course_run_enrollable(course_run): """ Return true if the course run is enrollable, false otherwise. We look for the following criteria: - end is greater than now OR null - enrollment_start is less than now OR null - enrollment_end is greater than now OR null """ now = datetime.d...
[ "def", "is_course_run_enrollable", "(", "course_run", ")", ":", "now", "=", "datetime", ".", "datetime", ".", "now", "(", "pytz", ".", "UTC", ")", "end", "=", "parse_datetime_handle_invalid", "(", "course_run", ".", "get", "(", "'end'", ")", ")", "enrollment...
Return true if the course run is enrollable, false otherwise. We look for the following criteria: - end is greater than now OR null - enrollment_start is less than now OR null - enrollment_end is greater than now OR null
[ "Return", "true", "if", "the", "course", "run", "is", "enrollable", "false", "otherwise", "." ]
python
valid
45.3125
tensorflow/tensorboard
tensorboard/plugins/hparams/summary.py
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/hparams/summary.py#L49-L80
def experiment_pb( hparam_infos, metric_infos, user='', description='', time_created_secs=None): """Creates a summary that defines a hyperparameter-tuning experiment. Args: hparam_infos: Array of api_pb2.HParamInfo messages. Describes the hyperparameters used in the experiment. ...
[ "def", "experiment_pb", "(", "hparam_infos", ",", "metric_infos", ",", "user", "=", "''", ",", "description", "=", "''", ",", "time_created_secs", "=", "None", ")", ":", "if", "time_created_secs", "is", "None", ":", "time_created_secs", "=", "time", ".", "ti...
Creates a summary that defines a hyperparameter-tuning experiment. Args: hparam_infos: Array of api_pb2.HParamInfo messages. Describes the hyperparameters used in the experiment. metric_infos: Array of api_pb2.MetricInfo messages. Describes the metrics used in the experiment. See the document...
[ "Creates", "a", "summary", "that", "defines", "a", "hyperparameter", "-", "tuning", "experiment", "." ]
python
train
37.78125
hollenstein/maspy
maspy/proteindb.py
https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/proteindb.py#L334-L367
def _calculateCoverageMasks(proteindb, peptidedb): """Calcualte the sequence coverage masks for all proteindb elements. Private method used by :class:`ProteinDatabase`. A coverage mask is a numpy boolean array with the length of the protein sequence. Each protein position that has been ...
[ "def", "_calculateCoverageMasks", "(", "proteindb", ",", "peptidedb", ")", ":", "for", "proteinId", ",", "proteinEntry", "in", "viewitems", "(", "proteindb", ")", ":", "coverageMaskUnique", "=", "numpy", ".", "zeros", "(", "proteinEntry", ".", "length", "(", "...
Calcualte the sequence coverage masks for all proteindb elements. Private method used by :class:`ProteinDatabase`. A coverage mask is a numpy boolean array with the length of the protein sequence. Each protein position that has been covered in at least one peptide is set to True. Covera...
[ "Calcualte", "the", "sequence", "coverage", "masks", "for", "all", "proteindb", "elements", ".", "Private", "method", "used", "by", ":", "class", ":", "ProteinDatabase", "." ]
python
train
58.088235
tango-controls/pytango
tango/asyncio_tools.py
https://github.com/tango-controls/pytango/blob/9cf78c517c9cdc1081ff6d080a9646a740cc1d36/tango/asyncio_tools.py#L29-L45
def _copy_future_state(source, dest): """Internal helper to copy state from another Future. The other Future may be a concurrent.futures.Future. """ assert source.done() if dest.cancelled(): return assert not dest.done() if source.cancelled(): dest.cancel() else: ...
[ "def", "_copy_future_state", "(", "source", ",", "dest", ")", ":", "assert", "source", ".", "done", "(", ")", "if", "dest", ".", "cancelled", "(", ")", ":", "return", "assert", "not", "dest", ".", "done", "(", ")", "if", "source", ".", "cancelled", "...
Internal helper to copy state from another Future. The other Future may be a concurrent.futures.Future.
[ "Internal", "helper", "to", "copy", "state", "from", "another", "Future", ".", "The", "other", "Future", "may", "be", "a", "concurrent", ".", "futures", ".", "Future", "." ]
python
train
29.235294
port-zero/mite
mite/mite.py
https://github.com/port-zero/mite/blob/b5fa941f60bf43e04ef654ed580ed7ef91211c22/mite/mite.py#L125-L132
def get_daily(self, date=None): """ Get time entries for a date (defaults to today). """ if date == None: return self.get("/daily.json") url = "/daily/{}/{}/{}.json".format(date.year, date.month, date.day) return self.get(url)
[ "def", "get_daily", "(", "self", ",", "date", "=", "None", ")", ":", "if", "date", "==", "None", ":", "return", "self", ".", "get", "(", "\"/daily.json\"", ")", "url", "=", "\"/daily/{}/{}/{}.json\"", ".", "format", "(", "date", ".", "year", ",", "date...
Get time entries for a date (defaults to today).
[ "Get", "time", "entries", "for", "a", "date", "(", "defaults", "to", "today", ")", "." ]
python
train
34.875
Qiskit/qiskit-terra
examples/python/circuit_draw.py
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/examples/python/circuit_draw.py#L16-L24
def build_bell_circuit(): """Returns a circuit putting 2 qubits in the Bell state.""" q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.cx(q[0], q[1]) qc.measure(q, c) return qc
[ "def", "build_bell_circuit", "(", ")", ":", "q", "=", "QuantumRegister", "(", "2", ")", "c", "=", "ClassicalRegister", "(", "2", ")", "qc", "=", "QuantumCircuit", "(", "q", ",", "c", ")", "qc", ".", "h", "(", "q", "[", "0", "]", ")", "qc", ".", ...
Returns a circuit putting 2 qubits in the Bell state.
[ "Returns", "a", "circuit", "putting", "2", "qubits", "in", "the", "Bell", "state", "." ]
python
test
26.555556
rstoneback/pysat
demo/cosmic_and_ivm_demo.py
https://github.com/rstoneback/pysat/blob/4ae1afd80e15e4449397d39dce8c3e969c32c422/demo/cosmic_and_ivm_demo.py#L13-L104
def geo2mag(incoord): """geographic coordinate to magnetic coordinate (coarse): Parameters ---------- incoord : numpy.array of shape (2,*) array([[glat0,glat1,glat2,...],[glon0,glon1,glon2,...]), where glat, glon are geographic latitude and longitude (or if you have only one po...
[ "def", "geo2mag", "(", "incoord", ")", ":", "from", "numpy", "import", "pi", ",", "cos", ",", "sin", ",", "arctan2", ",", "sqrt", ",", "dot", "# SOME 'constants' for location of northern mag pole", "lat", "=", "80.08", "#79.3", "lon", "=", "-", "72.211", "+"...
geographic coordinate to magnetic coordinate (coarse): Parameters ---------- incoord : numpy.array of shape (2,*) array([[glat0,glat1,glat2,...],[glon0,glon1,glon2,...]), where glat, glon are geographic latitude and longitude (or if you have only one point it is [[glat,glon]]). ...
[ "geographic", "coordinate", "to", "magnetic", "coordinate", "(", "coarse", ")", ":" ]
python
train
27.076087
ryanjdillon/pylleo
pylleo/calapp/main.py
https://github.com/ryanjdillon/pylleo/blob/b9b999fef19eaeccce4f207ab1b6198287c1bfec/pylleo/calapp/main.py#L230-L323
def callback_save_poly(): '''Perform polyfit once regions selected Globals: cal_fname, data (read-only, so no declaration) ''' import datetime import pylleo import yamlord import itertools def _check_param_regions(param, regions, cal_dict): msg = ''' <b>{}</b> was...
[ "def", "callback_save_poly", "(", ")", ":", "import", "datetime", "import", "pylleo", "import", "yamlord", "import", "itertools", "def", "_check_param_regions", "(", "param", ",", "regions", ",", "cal_dict", ")", ":", "msg", "=", "'''\n <b>{}</b> was no...
Perform polyfit once regions selected Globals: cal_fname, data (read-only, so no declaration)
[ "Perform", "polyfit", "once", "regions", "selected" ]
python
train
35.053191
saltstack/salt
salt/modules/bigip.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bigip.py#L65-L77
def _load_response(response): ''' Load the response from json data, return the dictionary or raw text ''' try: data = salt.utils.json.loads(response.text) except ValueError: data = response.text ret = {'code': response.status_code, 'content': data} return ret
[ "def", "_load_response", "(", "response", ")", ":", "try", ":", "data", "=", "salt", ".", "utils", ".", "json", ".", "loads", "(", "response", ".", "text", ")", "except", "ValueError", ":", "data", "=", "response", ".", "text", "ret", "=", "{", "'cod...
Load the response from json data, return the dictionary or raw text
[ "Load", "the", "response", "from", "json", "data", "return", "the", "dictionary", "or", "raw", "text" ]
python
train
22.615385
bwohlberg/sporco
sporco/admm/ccmodmd.py
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/ccmodmd.py#L370-L379
def ystep(self): r"""Minimise Augmented Lagrangian with respect to :math:`\mathbf{y}`. """ AXU = self.AX + self.U Y0 = (self.rho*(self.block_sep0(AXU) - self.S)) / (self.W**2 + self.rho) Y1 = self.Pcn(self.block_...
[ "def", "ystep", "(", "self", ")", ":", "AXU", "=", "self", ".", "AX", "+", "self", ".", "U", "Y0", "=", "(", "self", ".", "rho", "*", "(", "self", ".", "block_sep0", "(", "AXU", ")", "-", "self", ".", "S", ")", ")", "/", "(", "self", ".", ...
r"""Minimise Augmented Lagrangian with respect to :math:`\mathbf{y}`.
[ "r", "Minimise", "Augmented", "Lagrangian", "with", "respect", "to", ":", "math", ":", "\\", "mathbf", "{", "y", "}", "." ]
python
train
36.1
ArchiveTeam/wpull
wpull/protocol/abstract/client.py
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/abstract/client.py#L73-L82
def _acquire_request_connection(self, request): '''Return a connection.''' host = request.url_info.hostname port = request.url_info.port use_ssl = request.url_info.scheme == 'https' tunnel = request.url_info.scheme != 'http' connection = yield from self._acquire_connecti...
[ "def", "_acquire_request_connection", "(", "self", ",", "request", ")", ":", "host", "=", "request", ".", "url_info", ".", "hostname", "port", "=", "request", ".", "url_info", ".", "port", "use_ssl", "=", "request", ".", "url_info", ".", "scheme", "==", "'...
Return a connection.
[ "Return", "a", "connection", "." ]
python
train
36.9
sramana/pyatom
pyatom.py
https://github.com/sramana/pyatom/blob/9b937ac86926a1aa0e14ae774d1cc303f46327d5/pyatom.py#L186-L240
def generate(self): """Return a generator that yields pieces of XML.""" # atom demands either an author element in every entry or a global one if not self.author: if False in map(lambda e: bool(e.author), self.entries): self.author = ({'name': u'unbekannter Autor'},) ...
[ "def", "generate", "(", "self", ")", ":", "# atom demands either an author element in every entry or a global one", "if", "not", "self", ".", "author", ":", "if", "False", "in", "map", "(", "lambda", "e", ":", "bool", "(", "e", ".", "author", ")", ",", "self",...
Return a generator that yields pieces of XML.
[ "Return", "a", "generator", "that", "yields", "pieces", "of", "XML", "." ]
python
train
47.672727
wheeler-microfluidics/dmf-control-board-firmware
dmf_control_board_firmware/__init__.py
https://github.com/wheeler-microfluidics/dmf-control-board-firmware/blob/1cd8cc9a148d530f9a11f634f2dbfe73f08aa27c/dmf_control_board_firmware/__init__.py#L1504-L1520
def persistent_write(self, address, byte, refresh_config=False): ''' Write a single byte to an address in persistent memory. Parameters ---------- address : int Address in persistent memory (e.g., EEPROM). byte : int Value to write to address. ...
[ "def", "persistent_write", "(", "self", ",", "address", ",", "byte", ",", "refresh_config", "=", "False", ")", ":", "self", ".", "_persistent_write", "(", "address", ",", "byte", ")", "if", "refresh_config", ":", "self", ".", "load_config", "(", "False", "...
Write a single byte to an address in persistent memory. Parameters ---------- address : int Address in persistent memory (e.g., EEPROM). byte : int Value to write to address. refresh_config : bool, optional Is ``True``, :meth:`load_config()` i...
[ "Write", "a", "single", "byte", "to", "an", "address", "in", "persistent", "memory", "." ]
python
train
34.058824
UCL-INGI/INGInious
base-containers/base/inginious/feedback.py
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/base-containers/base/inginious/feedback.py#L18-L32
def load_feedback(): """ Open existing feedback file """ result = {} if os.path.exists(_feedback_file): f = open(_feedback_file, 'r') cont = f.read() f.close() else: cont = '{}' try: result = json.loads(cont) if cont else {} except ValueError as e: ...
[ "def", "load_feedback", "(", ")", ":", "result", "=", "{", "}", "if", "os", ".", "path", ".", "exists", "(", "_feedback_file", ")", ":", "f", "=", "open", "(", "_feedback_file", ",", "'r'", ")", "cont", "=", "f", ".", "read", "(", ")", "f", ".", ...
Open existing feedback file
[ "Open", "existing", "feedback", "file" ]
python
train
27
ckoepp/TwitterSearch
TwitterSearch/TwitterUserOrder.py
https://github.com/ckoepp/TwitterSearch/blob/627b9f519d49faf6b83859717f9082b3b2622aaf/TwitterSearch/TwitterUserOrder.py#L122-L133
def set_search_url(self, url): """ Reads given query string and stores key-value tuples :param url: A string containing a valid URL to parse arguments from """ if url[0] == '?': url = url[1:] self.arguments = {} for key, value in parse_qs(url).items(): ...
[ "def", "set_search_url", "(", "self", ",", "url", ")", ":", "if", "url", "[", "0", "]", "==", "'?'", ":", "url", "=", "url", "[", "1", ":", "]", "self", ".", "arguments", "=", "{", "}", "for", "key", ",", "value", "in", "parse_qs", "(", "url", ...
Reads given query string and stores key-value tuples :param url: A string containing a valid URL to parse arguments from
[ "Reads", "given", "query", "string", "and", "stores", "key", "-", "value", "tuples" ]
python
train
30.333333
c-soft/satel_integra
satel_integra/satel_integra.py
https://github.com/c-soft/satel_integra/blob/3b6d2020d1e10dc5aa40f30ee4ecc0f3a053eb3c/satel_integra/satel_integra.py#L188-L201
async def start_monitoring(self): """Start monitoring for interesting events.""" data = generate_query( b'\x7F\x01\xDC\x99\x80\x00\x04\x00\x00\x00\x00\x00\x00') await self._send_data(data) resp = await self._read_data() if resp is None: _LOGGER.warning("...
[ "async", "def", "start_monitoring", "(", "self", ")", ":", "data", "=", "generate_query", "(", "b'\\x7F\\x01\\xDC\\x99\\x80\\x00\\x04\\x00\\x00\\x00\\x00\\x00\\x00'", ")", "await", "self", ".", "_send_data", "(", "data", ")", "resp", "=", "await", "self", ".", "_rea...
Start monitoring for interesting events.
[ "Start", "monitoring", "for", "interesting", "events", "." ]
python
test
31.785714
sdispater/orator
orator/orm/scopes/soft_deleting.py
https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/scopes/soft_deleting.py#L88-L97
def _restore(self, builder): """ The restore extension. :param builder: The query builder :type builder: orator.orm.builder.Builder """ builder.with_trashed() return builder.update({builder.get_model().get_deleted_at_column(): None})
[ "def", "_restore", "(", "self", ",", "builder", ")", ":", "builder", ".", "with_trashed", "(", ")", "return", "builder", ".", "update", "(", "{", "builder", ".", "get_model", "(", ")", ".", "get_deleted_at_column", "(", ")", ":", "None", "}", ")" ]
The restore extension. :param builder: The query builder :type builder: orator.orm.builder.Builder
[ "The", "restore", "extension", "." ]
python
train
28.2
deepmipt/DeepPavlov
deeppavlov/core/models/lr_scheduled_model.py
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/models/lr_scheduled_model.py#L40-L56
def from_str(cls, label: str) -> int: """ Convert given string label of decay type to special index Args: label: name of decay type. Set of values: `"linear"`, `"cosine"`, `"exponential"`, `"onecycle"`, `"trapezoid"`, `["polynomial", K]`, where K is ...
[ "def", "from_str", "(", "cls", ",", "label", ":", "str", ")", "->", "int", ":", "label_norm", "=", "label", ".", "replace", "(", "'1'", ",", "'one'", ")", ".", "upper", "(", ")", "if", "label_norm", "in", "cls", ".", "__members__", ":", "return", "...
Convert given string label of decay type to special index Args: label: name of decay type. Set of values: `"linear"`, `"cosine"`, `"exponential"`, `"onecycle"`, `"trapezoid"`, `["polynomial", K]`, where K is a polynomial power Returns: index of ...
[ "Convert", "given", "string", "label", "of", "decay", "type", "to", "special", "index" ]
python
test
33.764706
fastai/fastai
fastai/text/learner.py
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L137-L163
def beam_search(self, text:str, n_words:int, no_unk:bool=True, top_k:int=10, beam_sz:int=1000, temperature:float=1., sep:str=' ', decoder=decode_spec_tokens): "Return the `n_words` that come after `text` using beam search." ds = self.data.single_dl.dataset self.model.reset() ...
[ "def", "beam_search", "(", "self", ",", "text", ":", "str", ",", "n_words", ":", "int", ",", "no_unk", ":", "bool", "=", "True", ",", "top_k", ":", "int", "=", "10", ",", "beam_sz", ":", "int", "=", "1000", ",", "temperature", ":", "float", "=", ...
Return the `n_words` that come after `text` using beam search.
[ "Return", "the", "n_words", "that", "come", "after", "text", "using", "beam", "search", "." ]
python
train
60.333333
openfisca/openfisca-survey-manager
openfisca_survey_manager/surveys.py
https://github.com/openfisca/openfisca-survey-manager/blob/bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358/openfisca_survey_manager/surveys.py#L248-L272
def insert_table(self, label = None, name = None, **kwargs): """ Insert a table in the Survey object """ data_frame = kwargs.pop('data_frame', None) if data_frame is None: data_frame = kwargs.pop('dataframe', None) to_hdf_kwargs = kwargs.pop('to_hdf_kwargs',...
[ "def", "insert_table", "(", "self", ",", "label", "=", "None", ",", "name", "=", "None", ",", "*", "*", "kwargs", ")", ":", "data_frame", "=", "kwargs", ".", "pop", "(", "'data_frame'", ",", "None", ")", "if", "data_frame", "is", "None", ":", "data_f...
Insert a table in the Survey object
[ "Insert", "a", "table", "in", "the", "Survey", "object" ]
python
train
37.24
benmoran56/esper
esper.py
https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L151-L165
def components_for_entity(self, entity: int) -> Tuple[C, ...]: """Retrieve all Components for a specific Entity, as a Tuple. Retrieve all Components for a specific Entity. The method is probably not appropriate to use in your Processors, but might be useful for saving state, or passing ...
[ "def", "components_for_entity", "(", "self", ",", "entity", ":", "int", ")", "->", "Tuple", "[", "C", ",", "...", "]", ":", "return", "tuple", "(", "self", ".", "_entities", "[", "entity", "]", ".", "values", "(", ")", ")" ]
Retrieve all Components for a specific Entity, as a Tuple. Retrieve all Components for a specific Entity. The method is probably not appropriate to use in your Processors, but might be useful for saving state, or passing specific Components between World instances. Unlike most other met...
[ "Retrieve", "all", "Components", "for", "a", "specific", "Entity", "as", "a", "Tuple", "." ]
python
train
54.933333