repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
tomasbasham/dominos
dominos/api.py
https://github.com/tomasbasham/dominos/blob/59729a8bdca0ae30a84115a0e93e9b1f259faf0e/dominos/api.py#L173-L190
def add_side_to_basket(self, item, quantity=1): ''' Add a side to the current basket. :param Item item: Item from menu. :param int quantity: The quantity of side to be added. :return: A response having added a side to the current basket. :rtype: requests.Response ...
[ "def", "add_side_to_basket", "(", "self", ",", "item", ",", "quantity", "=", "1", ")", ":", "item_variant", "=", "item", "[", "VARIANT", ".", "PERSONAL", "]", "params", "=", "{", "'productSkuId'", ":", "item_variant", "[", "'productSkuId'", "]", ",", "'qua...
Add a side to the current basket. :param Item item: Item from menu. :param int quantity: The quantity of side to be added. :return: A response having added a side to the current basket. :rtype: requests.Response
[ "Add", "a", "side", "to", "the", "current", "basket", "." ]
python
test
kislyuk/aegea
aegea/packages/github3/repos/repo.py
https://github.com/kislyuk/aegea/blob/94957e9dba036eae3052e2662c208b259c08399a/aegea/packages/github3/repos/repo.py#L512-L539
def create_deployment(self, ref, force=False, payload='', auto_merge=False, description='', environment=None): """Create a deployment. :param str ref: (required), The ref to deploy. This can be a branch, tag, or sha. :param bool force: Optional parameter to...
[ "def", "create_deployment", "(", "self", ",", "ref", ",", "force", "=", "False", ",", "payload", "=", "''", ",", "auto_merge", "=", "False", ",", "description", "=", "''", ",", "environment", "=", "None", ")", ":", "json", "=", "None", "if", "ref", "...
Create a deployment. :param str ref: (required), The ref to deploy. This can be a branch, tag, or sha. :param bool force: Optional parameter to bypass any ahead/behind checks or commit status checks. Default: False :param str payload: Optional JSON payload with extra inf...
[ "Create", "a", "deployment", "." ]
python
train
logston/py3s3
py3s3/storage.py
https://github.com/logston/py3s3/blob/1910ca60c53a53d839d6f7b09c05b555f3bfccf4/py3s3/storage.py#L194-L203
def _prepend_name_prefix(self, name): """Return file name (ie. path) with the prefix directory prepended""" if not self.name_prefix: return name base = self.name_prefix if base[0] != '/': base = '/' + base if name[0] != '/': name = '/' + name ...
[ "def", "_prepend_name_prefix", "(", "self", ",", "name", ")", ":", "if", "not", "self", ".", "name_prefix", ":", "return", "name", "base", "=", "self", ".", "name_prefix", "if", "base", "[", "0", "]", "!=", "'/'", ":", "base", "=", "'/'", "+", "base"...
Return file name (ie. path) with the prefix directory prepended
[ "Return", "file", "name", "(", "ie", ".", "path", ")", "with", "the", "prefix", "directory", "prepended" ]
python
train
openstack/proliantutils
proliantutils/ilo/ris.py
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/ilo/ris.py#L199-L213
def _get_host_details(self): """Get the system details.""" # Assuming only one system present as part of collection, # as we are dealing with iLO's here. status, headers, system = self._rest_get('/rest/v1/Systems/1') if status < 300: stype = self._get_type(system) ...
[ "def", "_get_host_details", "(", "self", ")", ":", "# Assuming only one system present as part of collection,", "# as we are dealing with iLO's here.", "status", ",", "headers", ",", "system", "=", "self", ".", "_rest_get", "(", "'/rest/v1/Systems/1'", ")", "if", "status", ...
Get the system details.
[ "Get", "the", "system", "details", "." ]
python
train
dsoprea/NsqSpinner
nsq/master.py
https://github.com/dsoprea/NsqSpinner/blob/972237b8ddce737983bfed001fde52e5236be695/nsq/master.py#L44-L76
def __start_connection(self, context, node, ccallbacks=None): """Start a new connection, and manage it from a new greenlet.""" _logger.debug("Creating connection object: CONTEXT=[%s] NODE=[%s]", context, node) c = nsq.connection.Connection( context, ...
[ "def", "__start_connection", "(", "self", ",", "context", ",", "node", ",", "ccallbacks", "=", "None", ")", ":", "_logger", ".", "debug", "(", "\"Creating connection object: CONTEXT=[%s] NODE=[%s]\"", ",", "context", ",", "node", ")", "c", "=", "nsq", ".", "co...
Start a new connection, and manage it from a new greenlet.
[ "Start", "a", "new", "connection", "and", "manage", "it", "from", "a", "new", "greenlet", "." ]
python
train
istresearch/scrapy-cluster
utils/scutils/log_factory.py
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/log_factory.py#L62-L66
def is_subdict(self, a,b): ''' Return True if a is a subdict of b ''' return all((k in b and b[k]==v) for k,v in a.iteritems())
[ "def", "is_subdict", "(", "self", ",", "a", ",", "b", ")", ":", "return", "all", "(", "(", "k", "in", "b", "and", "b", "[", "k", "]", "==", "v", ")", "for", "k", ",", "v", "in", "a", ".", "iteritems", "(", ")", ")" ]
Return True if a is a subdict of b
[ "Return", "True", "if", "a", "is", "a", "subdict", "of", "b" ]
python
train
rocky/python-spark
example/python2/py2_scan.py
https://github.com/rocky/python-spark/blob/8899954bcf0e166726841a43e87c23790eb3441f/example/python2/py2_scan.py#L170-L186
def t_whitespace_or_comment(self, s): r'([ \t]*[#].*[^\x04][\n]?)|([ \t]+)' if '#' in s: # We have a comment matches = re.match('(\s+)(.*[\n]?)', s) if matches and self.is_newline: self.handle_indent_dedent(matches.group(1)) s = matches...
[ "def", "t_whitespace_or_comment", "(", "self", ",", "s", ")", ":", "if", "'#'", "in", "s", ":", "# We have a comment", "matches", "=", "re", ".", "match", "(", "'(\\s+)(.*[\\n]?)'", ",", "s", ")", "if", "matches", "and", "self", ".", "is_newline", ":", "...
r'([ \t]*[#].*[^\x04][\n]?)|([ \t]+)
[ "r", "(", "[", "\\", "t", "]", "*", "[", "#", "]", ".", "*", "[", "^", "\\", "x04", "]", "[", "\\", "n", "]", "?", ")", "|", "(", "[", "\\", "t", "]", "+", ")" ]
python
train
geophysics-ubonn/reda
lib/reda/configs/configManager.py
https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/configs/configManager.py#L675-L753
def gen_configs_permutate(self, injections_raw, only_same_dipole_length=False, ignore_crossed_dipoles=False, silent=False): """ Create measurement configurations out of a pool of current ...
[ "def", "gen_configs_permutate", "(", "self", ",", "injections_raw", ",", "only_same_dipole_length", "=", "False", ",", "ignore_crossed_dipoles", "=", "False", ",", "silent", "=", "False", ")", ":", "injections", "=", "np", ".", "atleast_2d", "(", "injections_raw",...
Create measurement configurations out of a pool of current injections. Use only the provided dipoles for potential dipole selection. This means that we have always reciprocal measurements. Remove quadpoles where electrodes are used both as current and voltage dipoles. Paramete...
[ "Create", "measurement", "configurations", "out", "of", "a", "pool", "of", "current", "injections", ".", "Use", "only", "the", "provided", "dipoles", "for", "potential", "dipole", "selection", ".", "This", "means", "that", "we", "have", "always", "reciprocal", ...
python
train
hydpy-dev/hydpy
hydpy/core/sequencetools.py
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/sequencetools.py#L1158-L1237
def average_series(self, *args, **kwargs) -> InfoArray: """Average the actual time series of the |Variable| object for all time points. Method |IOSequence.average_series| works similarly as method |Variable.average_values| of class |Variable|, from which we borrow some examples....
[ "def", "average_series", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "InfoArray", ":", "try", ":", "if", "not", "self", ".", "NDIM", ":", "array", "=", "self", ".", "series", "else", ":", "mask", "=", "self", ".", "get_submas...
Average the actual time series of the |Variable| object for all time points. Method |IOSequence.average_series| works similarly as method |Variable.average_values| of class |Variable|, from which we borrow some examples. However, firstly, we have to prepare a |Timegrids| object ...
[ "Average", "the", "actual", "time", "series", "of", "the", "|Variable|", "object", "for", "all", "time", "points", "." ]
python
train
saltstack/salt
salt/utils/thin.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/thin.py#L184-L233
def get_ext_tops(config): ''' Get top directories for the dependencies, based on external configuration. :return: ''' config = copy.deepcopy(config) alternatives = {} required = ['jinja2', 'yaml', 'tornado', 'msgpack'] tops = [] for ns, cfg in salt.ext.six.iteritems(config or {}): ...
[ "def", "get_ext_tops", "(", "config", ")", ":", "config", "=", "copy", ".", "deepcopy", "(", "config", ")", "alternatives", "=", "{", "}", "required", "=", "[", "'jinja2'", ",", "'yaml'", ",", "'tornado'", ",", "'msgpack'", "]", "tops", "=", "[", "]", ...
Get top directories for the dependencies, based on external configuration. :return:
[ "Get", "top", "directories", "for", "the", "dependencies", "based", "on", "external", "configuration", "." ]
python
train
adewes/blitzdb
blitzdb/backends/file/backend.py
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/backend.py#L567-L589
def _canonicalize_query(self, query): """ Transform the query dictionary to replace e.g. documents with __ref__ fields. """ def transform_query(q): if isinstance(q, dict): nq = {} for key,value in q.items(): nq[key] = tra...
[ "def", "_canonicalize_query", "(", "self", ",", "query", ")", ":", "def", "transform_query", "(", "q", ")", ":", "if", "isinstance", "(", "q", ",", "dict", ")", ":", "nq", "=", "{", "}", "for", "key", ",", "value", "in", "q", ".", "items", "(", "...
Transform the query dictionary to replace e.g. documents with __ref__ fields.
[ "Transform", "the", "query", "dictionary", "to", "replace", "e", ".", "g", ".", "documents", "with", "__ref__", "fields", "." ]
python
train
hickeroar/simplebayes
simplebayes/__init__.py
https://github.com/hickeroar/simplebayes/blob/b8da72c50d20b6f8c0df2c2f39620715b08ddd32/simplebayes/__init__.py#L60-L75
def count_token_occurrences(cls, words): """ Creates a key/value set of word/count for a given sample of text :param words: full list of all tokens, non-unique :type words: list :return: key/value pairs of words and their counts in the list :rtype: dict """ ...
[ "def", "count_token_occurrences", "(", "cls", ",", "words", ")", ":", "counts", "=", "{", "}", "for", "word", "in", "words", ":", "if", "word", "in", "counts", ":", "counts", "[", "word", "]", "+=", "1", "else", ":", "counts", "[", "word", "]", "="...
Creates a key/value set of word/count for a given sample of text :param words: full list of all tokens, non-unique :type words: list :return: key/value pairs of words and their counts in the list :rtype: dict
[ "Creates", "a", "key", "/", "value", "set", "of", "word", "/", "count", "for", "a", "given", "sample", "of", "text" ]
python
train
MillionIntegrals/vel
vel/util/math.py
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/util/math.py#L3-L11
def divide_ceiling(numerator, denominator): """ Determine the smallest number k such, that denominator * k >= numerator """ split_val = numerator // denominator rest = numerator % denominator if rest > 0: return split_val + 1 else: return split_val
[ "def", "divide_ceiling", "(", "numerator", ",", "denominator", ")", ":", "split_val", "=", "numerator", "//", "denominator", "rest", "=", "numerator", "%", "denominator", "if", "rest", ">", "0", ":", "return", "split_val", "+", "1", "else", ":", "return", ...
Determine the smallest number k such, that denominator * k >= numerator
[ "Determine", "the", "smallest", "number", "k", "such", "that", "denominator", "*", "k", ">", "=", "numerator" ]
python
train
argaen/aiocache
aiocache/base.py
https://github.com/argaen/aiocache/blob/fdd282f37283ca04e22209f4d2ae4900f29e1688/aiocache/base.py#L440-L459
async def raw(self, command, *args, _conn=None, **kwargs): """ Send the raw command to the underlying client. Note that by using this CMD you will lose compatibility with other backends. Due to limitations with aiomcache client, args have to be provided as bytes. For rest of bac...
[ "async", "def", "raw", "(", "self", ",", "command", ",", "*", "args", ",", "_conn", "=", "None", ",", "*", "*", "kwargs", ")", ":", "start", "=", "time", ".", "monotonic", "(", ")", "ret", "=", "await", "self", ".", "_raw", "(", "command", ",", ...
Send the raw command to the underlying client. Note that by using this CMD you will lose compatibility with other backends. Due to limitations with aiomcache client, args have to be provided as bytes. For rest of backends, str. :param command: str with the command. :param timeo...
[ "Send", "the", "raw", "command", "to", "the", "underlying", "client", ".", "Note", "that", "by", "using", "this", "CMD", "you", "will", "lose", "compatibility", "with", "other", "backends", "." ]
python
train
sprockets/sprockets-influxdb
sprockets_influxdb.py
https://github.com/sprockets/sprockets-influxdb/blob/cce73481b8f26b02e65e3f9914a9a22eceff3063/sprockets_influxdb.py#L896-L906
def set_tags(self, tags): """Set multiple tags for the measurement. :param dict tags: Tag key/value pairs to assign This will overwrite the current value assigned to a tag if one exists with the same name. """ for key, value in tags.items(): self.set_tag(ke...
[ "def", "set_tags", "(", "self", ",", "tags", ")", ":", "for", "key", ",", "value", "in", "tags", ".", "items", "(", ")", ":", "self", ".", "set_tag", "(", "key", ",", "value", ")" ]
Set multiple tags for the measurement. :param dict tags: Tag key/value pairs to assign This will overwrite the current value assigned to a tag if one exists with the same name.
[ "Set", "multiple", "tags", "for", "the", "measurement", "." ]
python
train
apache/incubator-heron
heron/tools/cli/src/python/args.py
https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/cli/src/python/args.py#L180-L211
def add_dry_run(parser): ''' :param parser: :return: ''' default_format = 'table' resp_formats = ['raw', 'table', 'colored_table', 'json'] available_options = ', '.join(['%s' % opt for opt in resp_formats]) def dry_run_resp_format(value): if value not in resp_formats: raise argparse.ArgumentT...
[ "def", "add_dry_run", "(", "parser", ")", ":", "default_format", "=", "'table'", "resp_formats", "=", "[", "'raw'", ",", "'table'", ",", "'colored_table'", ",", "'json'", "]", "available_options", "=", "', '", ".", "join", "(", "[", "'%s'", "%", "opt", "fo...
:param parser: :return:
[ ":", "param", "parser", ":", ":", "return", ":" ]
python
valid
funilrys/PyFunceble
PyFunceble/syntax.py
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/syntax.py#L74-L104
def get(cls): """ Execute the logic behind the Syntax handling. :return: The syntax status. :rtype: str """ if PyFunceble.INTERN["to_test_type"] == "domain": # We are testing for domain or ip. if Check().is_domain_valid() or Check().is_ip_valid(...
[ "def", "get", "(", "cls", ")", ":", "if", "PyFunceble", ".", "INTERN", "[", "\"to_test_type\"", "]", "==", "\"domain\"", ":", "# We are testing for domain or ip.", "if", "Check", "(", ")", ".", "is_domain_valid", "(", ")", "or", "Check", "(", ")", ".", "is...
Execute the logic behind the Syntax handling. :return: The syntax status. :rtype: str
[ "Execute", "the", "logic", "behind", "the", "Syntax", "handling", "." ]
python
test
markchil/gptools
gptools/utils.py
https://github.com/markchil/gptools/blob/225db52bfe6baef1516529ad22177aa2cf7b71e4/gptools/utils.py#L1767-L1899
def compute_stats(vals, check_nan=False, robust=False, axis=1, plot_QQ=False, bins=15, name=''): """Compute the average statistics (mean, std dev) for the given values. Parameters ---------- vals : array-like, (`M`, `D`) Values to compute the average statistics along the specified axis of. ...
[ "def", "compute_stats", "(", "vals", ",", "check_nan", "=", "False", ",", "robust", "=", "False", ",", "axis", "=", "1", ",", "plot_QQ", "=", "False", ",", "bins", "=", "15", ",", "name", "=", "''", ")", ":", "if", "axis", "!=", "1", "and", "robu...
Compute the average statistics (mean, std dev) for the given values. Parameters ---------- vals : array-like, (`M`, `D`) Values to compute the average statistics along the specified axis of. check_nan : bool, optional Whether or not to check for (and exclude) NaN's. Default is False...
[ "Compute", "the", "average", "statistics", "(", "mean", "std", "dev", ")", "for", "the", "given", "values", ".", "Parameters", "----------", "vals", ":", "array", "-", "like", "(", "M", "D", ")", "Values", "to", "compute", "the", "average", "statistics", ...
python
train
googledatalab/pydatalab
google/datalab/stackdriver/commands/_monitoring.py
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/stackdriver/commands/_monitoring.py#L28-L42
def sd(line, cell=None): """Implements the stackdriver cell magic for ipython notebooks. Args: line: the contents of the storage line. Returns: The results of executing the cell. """ parser = google.datalab.utils.commands.CommandParser(prog='%sd', description=( 'Execute various Stackdriver rela...
[ "def", "sd", "(", "line", ",", "cell", "=", "None", ")", ":", "parser", "=", "google", ".", "datalab", ".", "utils", ".", "commands", ".", "CommandParser", "(", "prog", "=", "'%sd'", ",", "description", "=", "(", "'Execute various Stackdriver related operati...
Implements the stackdriver cell magic for ipython notebooks. Args: line: the contents of the storage line. Returns: The results of executing the cell.
[ "Implements", "the", "stackdriver", "cell", "magic", "for", "ipython", "notebooks", "." ]
python
train
dbcli/cli_helpers
cli_helpers/tabular_output/tsv_output_adapter.py
https://github.com/dbcli/cli_helpers/blob/3ebd891ac0c02bad061182dbcb54a47fb21980ae/cli_helpers/tabular_output/tsv_output_adapter.py#L13-L16
def adapter(data, headers, **kwargs): """Wrap the formatting inside a function for TabularOutputFormatter.""" for row in chain((headers,), data): yield "\t".join((replace(r, (('\n', r'\n'), ('\t', r'\t'))) for r in row))
[ "def", "adapter", "(", "data", ",", "headers", ",", "*", "*", "kwargs", ")", ":", "for", "row", "in", "chain", "(", "(", "headers", ",", ")", ",", "data", ")", ":", "yield", "\"\\t\"", ".", "join", "(", "(", "replace", "(", "r", ",", "(", "(", ...
Wrap the formatting inside a function for TabularOutputFormatter.
[ "Wrap", "the", "formatting", "inside", "a", "function", "for", "TabularOutputFormatter", "." ]
python
test
materialsproject/pymatgen
pymatgen/core/structure.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/core/structure.py#L3199-L3215
def append(self, species, coords, validate_proximity=True, properties=None): """ Appends a site to the molecule. Args: species: Species of inserted site coords: Coordinates of inserted site validate_proximity (bool): Whether to check if inserted site is ...
[ "def", "append", "(", "self", ",", "species", ",", "coords", ",", "validate_proximity", "=", "True", ",", "properties", "=", "None", ")", ":", "return", "self", ".", "insert", "(", "len", "(", "self", ")", ",", "species", ",", "coords", ",", "validate_...
Appends a site to the molecule. Args: species: Species of inserted site coords: Coordinates of inserted site validate_proximity (bool): Whether to check if inserted site is too close to an existing site. Defaults to True. properties (dict): A dict...
[ "Appends", "a", "site", "to", "the", "molecule", "." ]
python
train
praekelt/panya
panya/templatetags/panya_template_tags.py
https://github.com/praekelt/panya/blob/0fd621e15a7c11a2716a9554a2f820d6259818e5/panya/templatetags/panya_template_tags.py#L12-L25
def smart_query_string(parser, token): """ Outputs current GET query string with additions appended. Additions are provided in token pairs. """ args = token.split_contents() additions = args[1:] addition_pairs = [] while additions: addition_pairs.append(additions[0:2]) ...
[ "def", "smart_query_string", "(", "parser", ",", "token", ")", ":", "args", "=", "token", ".", "split_contents", "(", ")", "additions", "=", "args", "[", "1", ":", "]", "addition_pairs", "=", "[", "]", "while", "additions", ":", "addition_pairs", ".", "a...
Outputs current GET query string with additions appended. Additions are provided in token pairs.
[ "Outputs", "current", "GET", "query", "string", "with", "additions", "appended", ".", "Additions", "are", "provided", "in", "token", "pairs", "." ]
python
train
DLR-RM/RAFCON
source/rafcon/core/storage/storage.py
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/storage/storage.py#L374-L467
def load_state_recursively(parent, state_path=None, dirty_states=[]): """Recursively loads the state It calls this method on each sub-state of a container state. :param parent: the root state of the last load call to which the loaded state will be added :param state_path: the path on the filesystem w...
[ "def", "load_state_recursively", "(", "parent", ",", "state_path", "=", "None", ",", "dirty_states", "=", "[", "]", ")", ":", "from", "rafcon", ".", "core", ".", "states", ".", "execution_state", "import", "ExecutionState", "from", "rafcon", ".", "core", "."...
Recursively loads the state It calls this method on each sub-state of a container state. :param parent: the root state of the last load call to which the loaded state will be added :param state_path: the path on the filesystem where to find the meta file for the state :param dirty_states: a dict of s...
[ "Recursively", "loads", "the", "state" ]
python
train
crs4/hl7apy
hl7apy/core.py
https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/core.py#L788-L809
def encoding_chars(self): """ A ``dict`` with the encoding chars of the :class:`Element <hl7apy.core.Element>`. If the :class:`Element <hl7apy.core.Element>` has a parent it is the parent's ``encoding_chars`` otherwise the ones returned by :func:`get_default_encoding_chars <hl7ap...
[ "def", "encoding_chars", "(", "self", ")", ":", "if", "self", ".", "parent", "is", "not", "None", ":", "return", "self", ".", "parent", ".", "encoding_chars", "return", "get_default_encoding_chars", "(", "self", ".", "version", ")" ]
A ``dict`` with the encoding chars of the :class:`Element <hl7apy.core.Element>`. If the :class:`Element <hl7apy.core.Element>` has a parent it is the parent's ``encoding_chars`` otherwise the ones returned by :func:`get_default_encoding_chars <hl7apy.get_default_encoding_chars>` The str...
[ "A", "dict", "with", "the", "encoding", "chars", "of", "the", ":", "class", ":", "Element", "<hl7apy", ".", "core", ".", "Element", ">", ".", "If", "the", ":", "class", ":", "Element", "<hl7apy", ".", "core", ".", "Element", ">", "has", "a", "parent"...
python
train
senaite/senaite.core
bika/lims/browser/referencesample.py
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/referencesample.py#L209-L237
def folderitem(self, obj, item, index): """Service triggered each time an item is iterated in folderitems. The use of this service prevents the extra-loops in child objects. :obj: the instance of the class to be foldered :item: dict containing the properties of the object to be used by...
[ "def", "folderitem", "(", "self", ",", "obj", ",", "item", ",", "index", ")", ":", "item", "=", "super", "(", "ReferenceAnalysesView", ",", "self", ")", ".", "folderitem", "(", "obj", ",", "item", ",", "index", ")", "if", "not", "item", ":", "return"...
Service triggered each time an item is iterated in folderitems. The use of this service prevents the extra-loops in child objects. :obj: the instance of the class to be foldered :item: dict containing the properties of the object to be used by the template :index: current i...
[ "Service", "triggered", "each", "time", "an", "item", "is", "iterated", "in", "folderitems", "." ]
python
train
UDST/orca
orca/orca.py
https://github.com/UDST/orca/blob/07b34aeef13cc87c966b2e30cbe7e76cc9d3622c/orca/orca.py#L1146-L1169
def column(table_name, column_name=None, cache=False, cache_scope=_CS_FOREVER): """ Decorates functions that return a Series. Decorator version of `add_column`. Series index must match the named table. Column name defaults to name of function. The function's argument names and keyword argument val...
[ "def", "column", "(", "table_name", ",", "column_name", "=", "None", ",", "cache", "=", "False", ",", "cache_scope", "=", "_CS_FOREVER", ")", ":", "def", "decorator", "(", "func", ")", ":", "if", "column_name", ":", "name", "=", "column_name", "else", ":...
Decorates functions that return a Series. Decorator version of `add_column`. Series index must match the named table. Column name defaults to name of function. The function's argument names and keyword argument values will be matched to registered variables when the function needs to be evaluated ...
[ "Decorates", "functions", "that", "return", "a", "Series", "." ]
python
train
saltstack/salt
salt/states/pyenv.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pyenv.py#L104-L139
def installed(name, default=False, user=None): ''' Verify that the specified python is installed with pyenv. pyenv is installed if necessary. name The version of python to install default : False Whether to make this python the default. user: None The user to run pyenv...
[ "def", "installed", "(", "name", ",", "default", "=", "False", ",", "user", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "None", ",", "'comment'", ":", "''", ",", "'changes'", ":", "{", "}", "}", "if", "nam...
Verify that the specified python is installed with pyenv. pyenv is installed if necessary. name The version of python to install default : False Whether to make this python the default. user: None The user to run pyenv as. .. versionadded:: 0.17.0 .. versionadded...
[ "Verify", "that", "the", "specified", "python", "is", "installed", "with", "pyenv", ".", "pyenv", "is", "installed", "if", "necessary", "." ]
python
train
JoelBender/bacpypes
py27/bacpypes/primitivedata.py
https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py27/bacpypes/primitivedata.py#L1731-L1746
def get_tuple(self): """Return the unsigned integer tuple of the identifier.""" objType, objInstance = self.value if isinstance(objType, int): pass elif isinstance(objType, long): objType = int(objType) elif isinstance(objType, basestring): # ...
[ "def", "get_tuple", "(", "self", ")", ":", "objType", ",", "objInstance", "=", "self", ".", "value", "if", "isinstance", "(", "objType", ",", "int", ")", ":", "pass", "elif", "isinstance", "(", "objType", ",", "long", ")", ":", "objType", "=", "int", ...
Return the unsigned integer tuple of the identifier.
[ "Return", "the", "unsigned", "integer", "tuple", "of", "the", "identifier", "." ]
python
train
TissueMAPS/TmClient
src/python/tmclient/base.py
https://github.com/TissueMAPS/TmClient/blob/6fb40622af19142cb5169a64b8c2965993a25ab1/src/python/tmclient/base.py#L63-L91
def _init_session(self): ''' Delayed initialization of Requests Session object. This is done in order *not* to share the Session object across a multiprocessing pool. ''' self._real_session = requests.Session() # FIXME: this fails when one runs HTTPS on non-stand...
[ "def", "_init_session", "(", "self", ")", ":", "self", ".", "_real_session", "=", "requests", ".", "Session", "(", ")", "# FIXME: this fails when one runs HTTPS on non-standard ports,", "# e.g. https://tissuemaps.example.org:8443/", "if", "self", ".", "_port", "==", "443"...
Delayed initialization of Requests Session object. This is done in order *not* to share the Session object across a multiprocessing pool.
[ "Delayed", "initialization", "of", "Requests", "Session", "object", "." ]
python
train
zalando/patroni
patroni/scripts/aws.py
https://github.com/zalando/patroni/blob/f6d29081c90af52064b981cdd877a07338d86038/patroni/scripts/aws.py#L43-L47
def _tag_ebs(self, conn, role): """ set tags, carrying the cluster name, instance role and instance id for the EBS storage """ tags = {'Name': 'spilo_' + self.cluster_name, 'Role': role, 'Instance': self.instance_id} volumes = conn.get_all_volumes(filters={'attachment.instance-id': self.instance...
[ "def", "_tag_ebs", "(", "self", ",", "conn", ",", "role", ")", ":", "tags", "=", "{", "'Name'", ":", "'spilo_'", "+", "self", ".", "cluster_name", ",", "'Role'", ":", "role", ",", "'Instance'", ":", "self", ".", "instance_id", "}", "volumes", "=", "c...
set tags, carrying the cluster name, instance role and instance id for the EBS storage
[ "set", "tags", "carrying", "the", "cluster", "name", "instance", "role", "and", "instance", "id", "for", "the", "EBS", "storage" ]
python
train
log2timeline/dfdatetime
dfdatetime/precisions.py
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/precisions.py#L131-L157
def CopyToDateTimeString(cls, time_elements_tuple, fraction_of_second): """Copies the time elements and fraction of second to a string. Args: time_elements_tuple (tuple[int, int, int, int, int, int]): time elements, contains year, month, day of month, hours, minutes and seconds. ...
[ "def", "CopyToDateTimeString", "(", "cls", ",", "time_elements_tuple", ",", "fraction_of_second", ")", ":", "if", "fraction_of_second", "<", "0.0", "or", "fraction_of_second", ">=", "1.0", ":", "raise", "ValueError", "(", "'Fraction of second value: {0:f} out of bounds.'"...
Copies the time elements and fraction of second to a string. Args: time_elements_tuple (tuple[int, int, int, int, int, int]): time elements, contains year, month, day of month, hours, minutes and seconds. fraction_of_second (decimal.Decimal): fraction of second, which must be a ...
[ "Copies", "the", "time", "elements", "and", "fraction", "of", "second", "to", "a", "string", "." ]
python
train
klen/aioauth-client
aioauth_client.py
https://github.com/klen/aioauth-client/blob/54f58249496c26965adb4f752f2b24cfe18d0084/aioauth_client.py#L852-L861
def user_parse(data): """Parse information from provider.""" yield 'id', data.get('id') yield 'email', data.get('email') yield 'first_name', data.get('given_name') yield 'last_name', data.get('family_name') yield 'link', data.get('link') yield 'locale', data.get('...
[ "def", "user_parse", "(", "data", ")", ":", "yield", "'id'", ",", "data", ".", "get", "(", "'id'", ")", "yield", "'email'", ",", "data", ".", "get", "(", "'email'", ")", "yield", "'first_name'", ",", "data", ".", "get", "(", "'given_name'", ")", "yie...
Parse information from provider.
[ "Parse", "information", "from", "provider", "." ]
python
train
saltstack/salt
salt/states/redismod.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/redismod.py#L120-L173
def slaveof(name, sentinel_host=None, sentinel_port=None, sentinel_password=None, **connection_args): ''' Set this redis instance as a slave. .. versionadded: 2016.3.0 name Master to make this a slave of sentinel_host Ip of the sentinel to check for the master sentinel_port ...
[ "def", "slaveof", "(", "name", ",", "sentinel_host", "=", "None", ",", "sentinel_port", "=", "None", ",", "sentinel_password", "=", "None", ",", "*", "*", "connection_args", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", ...
Set this redis instance as a slave. .. versionadded: 2016.3.0 name Master to make this a slave of sentinel_host Ip of the sentinel to check for the master sentinel_port Port of the sentinel to check for the master
[ "Set", "this", "redis", "instance", "as", "a", "slave", "." ]
python
train
pr-omethe-us/PyKED
pyked/converters.py
https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/converters.py#L318-L471
def get_datapoints(root): """Parse datapoints with ignition delay from file. Args: root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file Returns: properties (`dict`): Dictionary with ignition delay data """ # Shock tube experiment will have one data group, while RCM ma...
[ "def", "get_datapoints", "(", "root", ")", ":", "# Shock tube experiment will have one data group, while RCM may have one", "# or two (one for ignition delay, one for volume-history)", "dataGroups", "=", "root", ".", "findall", "(", "'dataGroup'", ")", "if", "not", "dataGroups", ...
Parse datapoints with ignition delay from file. Args: root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file Returns: properties (`dict`): Dictionary with ignition delay data
[ "Parse", "datapoints", "with", "ignition", "delay", "from", "file", "." ]
python
train
PaulHancock/Aegean
AegeanTools/wcs_helpers.py
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/wcs_helpers.py#L62-L97
def from_header(cls, header, beam=None, lat=None): """ Create a new WCSHelper class from the given header. Parameters ---------- header : `astropy.fits.HDUHeader` or string The header to be used to create the WCS helper beam : :class:`AegeanTools.fits_image....
[ "def", "from_header", "(", "cls", ",", "header", ",", "beam", "=", "None", ",", "lat", "=", "None", ")", ":", "try", ":", "wcs", "=", "pywcs", ".", "WCS", "(", "header", ",", "naxis", "=", "2", ")", "except", ":", "# TODO: figure out what error is bein...
Create a new WCSHelper class from the given header. Parameters ---------- header : `astropy.fits.HDUHeader` or string The header to be used to create the WCS helper beam : :class:`AegeanTools.fits_image.Beam` or None The synthesized beam. If the supplied beam is...
[ "Create", "a", "new", "WCSHelper", "class", "from", "the", "given", "header", "." ]
python
train
DataDog/integrations-core
snmp/datadog_checks/snmp/snmp.py
https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/snmp/datadog_checks/snmp/snmp.py#L444-L471
def report_raw_metrics(self, metrics, results, tags): ''' For all the metrics that are specified as oid, the conf oid is going to exactly match or be a prefix of the oid sent back by the device Use the instance configuration to find the name to give to the metric Submit the resu...
[ "def", "report_raw_metrics", "(", "self", ",", "metrics", ",", "results", ",", "tags", ")", ":", "for", "metric", "in", "metrics", ":", "forced_type", "=", "metric", ".", "get", "(", "'forced_type'", ")", "if", "'OID'", "in", "metric", ":", "queried_oid", ...
For all the metrics that are specified as oid, the conf oid is going to exactly match or be a prefix of the oid sent back by the device Use the instance configuration to find the name to give to the metric Submit the results to the aggregator.
[ "For", "all", "the", "metrics", "that", "are", "specified", "as", "oid", "the", "conf", "oid", "is", "going", "to", "exactly", "match", "or", "be", "a", "prefix", "of", "the", "oid", "sent", "back", "by", "the", "device", "Use", "the", "instance", "con...
python
train
ARMmbed/yotta
yotta/lib/github_access.py
https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/github_access.py#L278-L285
def availableBranches(self): ''' return a list of GithubComponentVersion objects for the tip of each branch ''' return [ GithubComponentVersion( '', b[0], b[1], self.name, cache_key=None ) for b in _getBranchHeads(self.repo).items() ]
[ "def", "availableBranches", "(", "self", ")", ":", "return", "[", "GithubComponentVersion", "(", "''", ",", "b", "[", "0", "]", ",", "b", "[", "1", "]", ",", "self", ".", "name", ",", "cache_key", "=", "None", ")", "for", "b", "in", "_getBranchHeads"...
return a list of GithubComponentVersion objects for the tip of each branch
[ "return", "a", "list", "of", "GithubComponentVersion", "objects", "for", "the", "tip", "of", "each", "branch" ]
python
valid
ejeschke/ginga
ginga/util/plots.py
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/util/plots.py#L160-L170
def cuts(self, data, xtitle=None, ytitle=None, title=None, rtitle=None, color=None): """data: pixel values along a line. """ y = data x = np.arange(len(data)) self.plot(x, y, color=color, drawstyle='steps-mid', xtitle=xtitle, ytitle=yt...
[ "def", "cuts", "(", "self", ",", "data", ",", "xtitle", "=", "None", ",", "ytitle", "=", "None", ",", "title", "=", "None", ",", "rtitle", "=", "None", ",", "color", "=", "None", ")", ":", "y", "=", "data", "x", "=", "np", ".", "arange", "(", ...
data: pixel values along a line.
[ "data", ":", "pixel", "values", "along", "a", "line", "." ]
python
train
deepmind/sonnet
sonnet/python/modules/attention.py
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/attention.py#L60-L183
def _build(self, memory, query, memory_mask=None): """Perform a differentiable read. Args: memory: [batch_size, memory_size, memory_word_size]-shaped Tensor of dtype float32. This represents, for each example and memory slot, a single embedding to attend over. query: [batch_size, qu...
[ "def", "_build", "(", "self", ",", "memory", ",", "query", ",", "memory_mask", "=", "None", ")", ":", "if", "len", "(", "memory", ".", "get_shape", "(", ")", ")", "!=", "3", ":", "raise", "base", ".", "IncompatibleShapeError", "(", "\"memory must have sh...
Perform a differentiable read. Args: memory: [batch_size, memory_size, memory_word_size]-shaped Tensor of dtype float32. This represents, for each example and memory slot, a single embedding to attend over. query: [batch_size, query_word_size]-shaped Tensor of dtype float32. Rep...
[ "Perform", "a", "differentiable", "read", "." ]
python
train
google/pyringe
pyringe/payload/gdb_service.py
https://github.com/google/pyringe/blob/76dff5d1ac29cd5e7bf32677654a83291a15ad8a/pyringe/payload/gdb_service.py#L492-L511
def Call(self, position, function_call): """Perform a function call in the inferior. WARNING: Since Gdb's concept of threads can't be directly identified with python threads, the function call will be made from what has to be assumed is an arbitrary thread. This *will* interrupt the inferior. Continuin...
[ "def", "Call", "(", "self", ",", "position", ",", "function_call", ")", ":", "self", ".", "EnsureGdbPosition", "(", "position", "[", "0", "]", ",", "None", ",", "None", ")", "if", "not", "gdb", ".", "selected_thread", "(", ")", ".", "is_stopped", "(", ...
Perform a function call in the inferior. WARNING: Since Gdb's concept of threads can't be directly identified with python threads, the function call will be made from what has to be assumed is an arbitrary thread. This *will* interrupt the inferior. Continuing it after the call is the responsibility of...
[ "Perform", "a", "function", "call", "in", "the", "inferior", "." ]
python
train
saltstack/salt
salt/modules/boto_lambda.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_lambda.py#L788-L819
def update_alias(FunctionName, Name, FunctionVersion=None, Description=None, region=None, key=None, keyid=None, profile=None): ''' Update the named alias to the configuration. Returns {updated: true} if the alias was updated and returns {updated: False} if the alias was not updated. ...
[ "def", "update_alias", "(", "FunctionName", ",", "Name", ",", "FunctionVersion", "=", "None", ",", "Description", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try",...
Update the named alias to the configuration. Returns {updated: true} if the alias was updated and returns {updated: False} if the alias was not updated. CLI Example: .. code-block:: bash salt myminion boto_lamba.update_alias my_lambda my_alias $LATEST
[ "Update", "the", "named", "alias", "to", "the", "configuration", "." ]
python
train
IAMconsortium/pyam
pyam/core.py
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/core.py#L1036-L1047
def to_csv(self, path, iamc_index=False, **kwargs): """Write timeseries data to a csv file Parameters ---------- path: string file path iamc_index: bool, default False if True, use `['model', 'scenario', 'region', 'variable', 'unit']`; else, u...
[ "def", "to_csv", "(", "self", ",", "path", ",", "iamc_index", "=", "False", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_to_file_format", "(", "iamc_index", ")", ".", "to_csv", "(", "path", ",", "index", "=", "False", ",", "*", "*", "kwargs", ...
Write timeseries data to a csv file Parameters ---------- path: string file path iamc_index: bool, default False if True, use `['model', 'scenario', 'region', 'variable', 'unit']`; else, use all `data` columns
[ "Write", "timeseries", "data", "to", "a", "csv", "file" ]
python
train
secdev/scapy
scapy/packet.py
https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/packet.py#L1857-L1874
def fuzz(p, _inplace=0): """Transform a layer into a fuzzy layer by replacing some default values by random objects""" # noqa: E501 if not _inplace: p = p.copy() q = p while not isinstance(q, NoPayload): for f in q.fields_desc: if isinstance(f, PacketListField): ...
[ "def", "fuzz", "(", "p", ",", "_inplace", "=", "0", ")", ":", "# noqa: E501", "if", "not", "_inplace", ":", "p", "=", "p", ".", "copy", "(", ")", "q", "=", "p", "while", "not", "isinstance", "(", "q", ",", "NoPayload", ")", ":", "for", "f", "in...
Transform a layer into a fuzzy layer by replacing some default values by random objects
[ "Transform", "a", "layer", "into", "a", "fuzzy", "layer", "by", "replacing", "some", "default", "values", "by", "random", "objects" ]
python
train
neptune-ml/steppy
steppy/base.py
https://github.com/neptune-ml/steppy/blob/856b95f1f5189e1d2ca122b891bc670adac9692b/steppy/base.py#L434-L455
def reset(self): """Reset all upstream Steps to the default training parameters and cleans cache for all upstream Steps including this Step. Defaults are: 'mode': 'train', 'is_fittable': True, 'force_fitting': True, 'persist_output': False, ...
[ "def", "reset", "(", "self", ")", ":", "self", ".", "clean_cache_upstream", "(", ")", "self", ".", "set_mode_train", "(", ")", "for", "step_obj", "in", "self", ".", "all_upstream_steps", ".", "values", "(", ")", ":", "step_obj", ".", "is_fittable", "=", ...
Reset all upstream Steps to the default training parameters and cleans cache for all upstream Steps including this Step. Defaults are: 'mode': 'train', 'is_fittable': True, 'force_fitting': True, 'persist_output': False, 'cache_output': False, ...
[ "Reset", "all", "upstream", "Steps", "to", "the", "default", "training", "parameters", "and", "cleans", "cache", "for", "all", "upstream", "Steps", "including", "this", "Step", ".", "Defaults", "are", ":", "mode", ":", "train", "is_fittable", ":", "True", "f...
python
train
pneff/wsgiservice
wsgiservice/application.py
https://github.com/pneff/wsgiservice/blob/03c064ac2e8c53a1aac9c7b99970f23cf79e20f4/wsgiservice/application.py#L82-L103
def _handle_request(self, request): """Finds the resource to which a request maps and then calls it. Instantiates, fills and returns a :class:`webob.Response` object. If no resource matches the request, a 404 status is set on the response object. :param request: Object represent...
[ "def", "_handle_request", "(", "self", ",", "request", ")", ":", "response", "=", "webob", ".", "Response", "(", "request", "=", "request", ")", "path", "=", "request", ".", "path_info", "parsed", "=", "self", ".", "_urlmap", "(", "path", ")", "if", "p...
Finds the resource to which a request maps and then calls it. Instantiates, fills and returns a :class:`webob.Response` object. If no resource matches the request, a 404 status is set on the response object. :param request: Object representing the current request. :type request:...
[ "Finds", "the", "resource", "to", "which", "a", "request", "maps", "and", "then", "calls", "it", ".", "Instantiates", "fills", "and", "returns", "a", ":", "class", ":", "webob", ".", "Response", "object", ".", "If", "no", "resource", "matches", "the", "r...
python
train
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L1168-L1207
def add_op_create_replicated_pool(self, name, replica_count=3, pg_num=None, weight=None, group=None, namespace=None, app_name=None, max_bytes=None, max_objects=None): """Adds an operation to create ...
[ "def", "add_op_create_replicated_pool", "(", "self", ",", "name", ",", "replica_count", "=", "3", ",", "pg_num", "=", "None", ",", "weight", "=", "None", ",", "group", "=", "None", ",", "namespace", "=", "None", ",", "app_name", "=", "None", ",", "max_by...
Adds an operation to create a replicated pool. :param name: Name of pool to create :type name: str :param replica_count: Number of copies Ceph should keep of your data. :type replica_count: int :param pg_num: Request specific number of Placement Groups to create ...
[ "Adds", "an", "operation", "to", "create", "a", "replicated", "pool", "." ]
python
train
globocom/GloboNetworkAPI-client-python
networkapiclient/ApiNetworkIPv4.py
https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/ApiNetworkIPv4.py#L61-L71
def undeploy(self, id_networkv4): """Remove deployment of network in equipments and set column 'active = 0' in tables redeipv4 ] :param id_networkv4: ID for NetworkIPv4 :return: Equipments configuration output """ uri = 'api/networkv4/%s/equipments/' % id_networkv4 re...
[ "def", "undeploy", "(", "self", ",", "id_networkv4", ")", ":", "uri", "=", "'api/networkv4/%s/equipments/'", "%", "id_networkv4", "return", "super", "(", "ApiNetworkIPv4", ",", "self", ")", ".", "delete", "(", "uri", ")" ]
Remove deployment of network in equipments and set column 'active = 0' in tables redeipv4 ] :param id_networkv4: ID for NetworkIPv4 :return: Equipments configuration output
[ "Remove", "deployment", "of", "network", "in", "equipments", "and", "set", "column", "active", "=", "0", "in", "tables", "redeipv4", "]" ]
python
train
ewels/MultiQC
multiqc/plots/heatmap.py
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/plots/heatmap.py#L40-L84
def highcharts_heatmap (data, xcats, ycats, pconfig=None): """ Build the HTML needed for a HighCharts line graph. Should be called by plot_xy_data, which properly formats input data. """ if pconfig is None: pconfig = {} # Reformat the data for highcharts pdata = [] for i, arr in...
[ "def", "highcharts_heatmap", "(", "data", ",", "xcats", ",", "ycats", ",", "pconfig", "=", "None", ")", ":", "if", "pconfig", "is", "None", ":", "pconfig", "=", "{", "}", "# Reformat the data for highcharts", "pdata", "=", "[", "]", "for", "i", ",", "arr...
Build the HTML needed for a HighCharts line graph. Should be called by plot_xy_data, which properly formats input data.
[ "Build", "the", "HTML", "needed", "for", "a", "HighCharts", "line", "graph", ".", "Should", "be", "called", "by", "plot_xy_data", "which", "properly", "formats", "input", "data", "." ]
python
train
Erotemic/utool
utool/util_alg.py
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L547-L591
def colwise_diag_idxs(size, num=2): r""" dont trust this implementation or this function name Args: size (int): Returns: ?: upper_diag_idxs CommandLine: python -m utool.util_alg --exec-colwise_diag_idxs --size=5 --num=2 python -m utool.util_alg --exec-colwise_diag_...
[ "def", "colwise_diag_idxs", "(", "size", ",", "num", "=", "2", ")", ":", "# diag_idxs = list(diagonalized_iter(size))", "# upper_diag_idxs = [(r, c) for r, c in diag_idxs if r < c]", "# # diag_idxs = list(diagonalized_iter(size))", "import", "utool", "as", "ut", "diag_idxs", "=",...
r""" dont trust this implementation or this function name Args: size (int): Returns: ?: upper_diag_idxs CommandLine: python -m utool.util_alg --exec-colwise_diag_idxs --size=5 --num=2 python -m utool.util_alg --exec-colwise_diag_idxs --size=3 --num=3 Example: ...
[ "r", "dont", "trust", "this", "implementation", "or", "this", "function", "name" ]
python
train
robotframework/Rammbock
src/Rammbock/core.py
https://github.com/robotframework/Rammbock/blob/c906058d055a6f7c68fe1a6096d78c2e3f642b1c/src/Rammbock/core.py#L935-L950
def value(self, name, value): """Defines a default `value` for a template field identified by `name`. Default values for header fields can be set with header:field syntax. Examples: | Value | foo | 42 | | Value | struct.sub_field | 0xcafe | | Value | header:version | 0x...
[ "def", "value", "(", "self", ",", "name", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "_StructuredElement", ")", ":", "self", ".", "_struct_fields_as_values", "(", "name", ",", "value", ")", "elif", "name", ".", "startswith", "(", "'he...
Defines a default `value` for a template field identified by `name`. Default values for header fields can be set with header:field syntax. Examples: | Value | foo | 42 | | Value | struct.sub_field | 0xcafe | | Value | header:version | 0x02 |
[ "Defines", "a", "default", "value", "for", "a", "template", "field", "identified", "by", "name", "." ]
python
train
tamasgal/km3pipe
km3pipe/math.py
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/math.py#L257-L278
def rotation_matrix(axis, theta): """The Euler–Rodrigues formula. Return the rotation matrix associated with counterclockwise rotation about the given axis by theta radians. Parameters ---------- axis: vector to rotate around theta: rotation angle, in rad """ axis = np.asarray(axis...
[ "def", "rotation_matrix", "(", "axis", ",", "theta", ")", ":", "axis", "=", "np", ".", "asarray", "(", "axis", ")", "axis", "=", "axis", "/", "np", ".", "linalg", ".", "norm", "(", "axis", ")", "a", "=", "np", ".", "cos", "(", "theta", "/", "2"...
The Euler–Rodrigues formula. Return the rotation matrix associated with counterclockwise rotation about the given axis by theta radians. Parameters ---------- axis: vector to rotate around theta: rotation angle, in rad
[ "The", "Euler–Rodrigues", "formula", "." ]
python
train
django-ses/django-ses
django_ses/views.py
https://github.com/django-ses/django-ses/blob/2f0fd8e3fdc76d3512982c0bb8e2f6e93e09fa3c/django_ses/views.py#L40-L63
def stats_to_list(stats_dict, localize=pytz): """ Parse the output of ``SESConnection.get_send_statistics()`` in to an ordered list of 15-minute summaries. """ result = stats_dict['GetSendStatisticsResponse']['GetSendStatisticsResult'] # Make a copy, so we don't change the original stats_dict. ...
[ "def", "stats_to_list", "(", "stats_dict", ",", "localize", "=", "pytz", ")", ":", "result", "=", "stats_dict", "[", "'GetSendStatisticsResponse'", "]", "[", "'GetSendStatisticsResult'", "]", "# Make a copy, so we don't change the original stats_dict.", "result", "=", "co...
Parse the output of ``SESConnection.get_send_statistics()`` in to an ordered list of 15-minute summaries.
[ "Parse", "the", "output", "of", "SESConnection", ".", "get_send_statistics", "()", "in", "to", "an", "ordered", "list", "of", "15", "-", "minute", "summaries", "." ]
python
train
TC01/python-xkcd
xkcd.py
https://github.com/TC01/python-xkcd/blob/6998d4073507eea228185e02ad1d9071c77fa955/xkcd.py#L350-L371
def getComic(number, silent=True): """ Produces a :class:`Comic` object with index equal to the provided argument. Prints an error in the event of a failure (i.e. the number is less than zero or greater than the latest comic number) and returns an empty Comic object. Arguments: an integer or string that repr...
[ "def", "getComic", "(", "number", ",", "silent", "=", "True", ")", ":", "numComics", "=", "getLatestComicNum", "(", ")", "if", "type", "(", "number", ")", "is", "str", "and", "number", ".", "isdigit", "(", ")", ":", "number", "=", "int", "(", "number...
Produces a :class:`Comic` object with index equal to the provided argument. Prints an error in the event of a failure (i.e. the number is less than zero or greater than the latest comic number) and returns an empty Comic object. Arguments: an integer or string that represents a number, "number", that is the i...
[ "Produces", "a", ":", "class", ":", "Comic", "object", "with", "index", "equal", "to", "the", "provided", "argument", ".", "Prints", "an", "error", "in", "the", "event", "of", "a", "failure", "(", "i", ".", "e", ".", "the", "number", "is", "less", "t...
python
train
coleifer/irc
irc.py
https://github.com/coleifer/irc/blob/f9d2bd6369aafe6cb0916c9406270ca8ecea2080/irc.py#L284-L291
def register_callbacks(self): """\ Hook for registering callbacks with connection -- handled by __init__() """ self.conn.register_callbacks(( (re.compile(pattern), callback) \ for pattern, callback in self.command_patterns() ))
[ "def", "register_callbacks", "(", "self", ")", ":", "self", ".", "conn", ".", "register_callbacks", "(", "(", "(", "re", ".", "compile", "(", "pattern", ")", ",", "callback", ")", "for", "pattern", ",", "callback", "in", "self", ".", "command_patterns", ...
\ Hook for registering callbacks with connection -- handled by __init__()
[ "\\", "Hook", "for", "registering", "callbacks", "with", "connection", "--", "handled", "by", "__init__", "()" ]
python
test
tchellomello/python-arlo
pyarlo/camera.py
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/camera.py#L128-L132
def unseen_videos_reset(self): """Reset the unseen videos counter.""" url = RESET_CAM_ENDPOINT.format(self.unique_id) ret = self._session.query(url).get('success') return ret
[ "def", "unseen_videos_reset", "(", "self", ")", ":", "url", "=", "RESET_CAM_ENDPOINT", ".", "format", "(", "self", ".", "unique_id", ")", "ret", "=", "self", ".", "_session", ".", "query", "(", "url", ")", ".", "get", "(", "'success'", ")", "return", "...
Reset the unseen videos counter.
[ "Reset", "the", "unseen", "videos", "counter", "." ]
python
train
jlmadurga/permabots
permabots/views/api/state.py
https://github.com/jlmadurga/permabots/blob/781a91702529a23fe7bc2aa84c5d88e961412466/permabots/views/api/state.py#L25-L34
def get(self, request, bot_id, format=None): """ Get list of states --- serializer: StateSerializer responseMessages: - code: 401 message: Not authenticated """ return super(StateList, self).get(request, bot_id, format)
[ "def", "get", "(", "self", ",", "request", ",", "bot_id", ",", "format", "=", "None", ")", ":", "return", "super", "(", "StateList", ",", "self", ")", ".", "get", "(", "request", ",", "bot_id", ",", "format", ")" ]
Get list of states --- serializer: StateSerializer responseMessages: - code: 401 message: Not authenticated
[ "Get", "list", "of", "states", "---", "serializer", ":", "StateSerializer", "responseMessages", ":", "-", "code", ":", "401", "message", ":", "Not", "authenticated" ]
python
train
edx/edx-enterprise
integrated_channels/degreed/client.py
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/degreed/client.py#L175-L188
def _delete(self, url, data, scope): """ Make a DELETE request using the session object to a Degreed endpoint. Args: url (str): The url to send a DELETE request to. data (str): The json encoded payload to DELETE. scope (str): Must be one of the scopes Degreed...
[ "def", "_delete", "(", "self", ",", "url", ",", "data", ",", "scope", ")", ":", "self", ".", "_create_session", "(", "scope", ")", "response", "=", "self", ".", "session", ".", "delete", "(", "url", ",", "data", "=", "data", ")", "return", "response"...
Make a DELETE request using the session object to a Degreed endpoint. Args: url (str): The url to send a DELETE request to. data (str): The json encoded payload to DELETE. scope (str): Must be one of the scopes Degreed expects: - `CONTENT_PROVIDER_SCO...
[ "Make", "a", "DELETE", "request", "using", "the", "session", "object", "to", "a", "Degreed", "endpoint", "." ]
python
valid
krinj/k-util
k_util/core.py
https://github.com/krinj/k-util/blob/b118826b1d6f49ca4e1ca7327d5b171db332ac23/k_util/core.py#L21-L23
def interpolate(f1: float, f2: float, factor: float) -> float: """ Linearly interpolate between two float values. """ return f1 + (f2 - f1) * factor
[ "def", "interpolate", "(", "f1", ":", "float", ",", "f2", ":", "float", ",", "factor", ":", "float", ")", "->", "float", ":", "return", "f1", "+", "(", "f2", "-", "f1", ")", "*", "factor" ]
Linearly interpolate between two float values.
[ "Linearly", "interpolate", "between", "two", "float", "values", "." ]
python
train
QUANTAXIS/QUANTAXIS
QUANTAXIS/QAARP/QARisk.py
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QARisk.py#L643-L733
def plot_assets_curve(self, length=14, height=12): """ 资金曲线叠加图 @Roy T.Burns 2018/05/29 修改百分比显示错误 """ plt.style.use('ggplot') plt.figure(figsize=(length, height)) plt.subplot(211) plt.title('BASIC INFO', fontsize=12) plt.axis([0, length, 0, 0.6]) ...
[ "def", "plot_assets_curve", "(", "self", ",", "length", "=", "14", ",", "height", "=", "12", ")", ":", "plt", ".", "style", ".", "use", "(", "'ggplot'", ")", "plt", ".", "figure", "(", "figsize", "=", "(", "length", ",", "height", ")", ")", "plt", ...
资金曲线叠加图 @Roy T.Burns 2018/05/29 修改百分比显示错误
[ "资金曲线叠加图" ]
python
train
klahnakoski/pyLibrary
tuid/clogger.py
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/tuid/clogger.py#L399-L463
def update_tip(self): ''' Returns False if the tip is already at the newest, or True if an update has taken place. :return: ''' clog_obj = self._get_clog(self.tuid_service.hg_url / self.config.hg.branch / 'json-log' / 'tip') # Get current tip in DB with s...
[ "def", "update_tip", "(", "self", ")", ":", "clog_obj", "=", "self", ".", "_get_clog", "(", "self", ".", "tuid_service", ".", "hg_url", "/", "self", ".", "config", ".", "hg", ".", "branch", "/", "'json-log'", "/", "'tip'", ")", "# Get current tip in DB", ...
Returns False if the tip is already at the newest, or True if an update has taken place. :return:
[ "Returns", "False", "if", "the", "tip", "is", "already", "at", "the", "newest", "or", "True", "if", "an", "update", "has", "taken", "place", ".", ":", "return", ":" ]
python
train
globus/globus-cli
globus_cli/parsing/shared_options.py
https://github.com/globus/globus-cli/blob/336675ff24da64c5ee487243f39ae39fc49a7e14/globus_cli/parsing/shared_options.py#L431-L531
def task_submission_options(f): """ Options shared by both transfer and delete task submission """ def notify_opt_callback(ctx, param, value): """ Parse --notify - "" is the same as "off" - parse by lowercase, comma-split, strip spaces - "off,x" is invalid for an...
[ "def", "task_submission_options", "(", "f", ")", ":", "def", "notify_opt_callback", "(", "ctx", ",", "param", ",", "value", ")", ":", "\"\"\"\n Parse --notify\n - \"\" is the same as \"off\"\n - parse by lowercase, comma-split, strip spaces\n - \"off,x\" i...
Options shared by both transfer and delete task submission
[ "Options", "shared", "by", "both", "transfer", "and", "delete", "task", "submission" ]
python
train
santoshphilip/eppy
eppy/modeleditor.py
https://github.com/santoshphilip/eppy/blob/55410ff7c11722f35bc4331ff5e00a0b86f787e1/eppy/modeleditor.py#L598-L612
def setidd(cls, iddinfo, iddindex, block, idd_version): """Set the IDD to be used by eppy. Parameters ---------- iddinfo : list Comments and metadata about fields in the IDD. block : list Field names in the IDD. """ cls.idd_info = iddinfo...
[ "def", "setidd", "(", "cls", ",", "iddinfo", ",", "iddindex", ",", "block", ",", "idd_version", ")", ":", "cls", ".", "idd_info", "=", "iddinfo", "cls", ".", "block", "=", "block", "cls", ".", "idd_index", "=", "iddindex", "cls", ".", "idd_version", "=...
Set the IDD to be used by eppy. Parameters ---------- iddinfo : list Comments and metadata about fields in the IDD. block : list Field names in the IDD.
[ "Set", "the", "IDD", "to", "be", "used", "by", "eppy", "." ]
python
train
CalebBell/ht
ht/conv_internal.py
https://github.com/CalebBell/ht/blob/3097ef9524c4cf0068ad453c17b10ec9ce551eee/ht/conv_internal.py#L1554-L1624
def helical_turbulent_Nu_Mori_Nakayama(Re, Pr, Di, Dc): r'''Calculates Nusselt number for a fluid flowing inside a curved pipe such as a helical coil under turbulent conditions, using the method of Mori and Nakayama [1]_, also shown in [2]_ and [3]_. For :math:`Pr < 1`: .. ma...
[ "def", "helical_turbulent_Nu_Mori_Nakayama", "(", "Re", ",", "Pr", ",", "Di", ",", "Dc", ")", ":", "D_ratio", "=", "Di", "/", "Dc", "if", "Pr", "<", "1", ":", "term1", "=", "Pr", "/", "(", "26.2", "*", "(", "Pr", "**", "(", "2", "/", "3.", ")",...
r'''Calculates Nusselt number for a fluid flowing inside a curved pipe such as a helical coil under turbulent conditions, using the method of Mori and Nakayama [1]_, also shown in [2]_ and [3]_. For :math:`Pr < 1`: .. math:: Nu = \frac{Pr}{26.2(Pr^{2/3}-0.074)}Re^{0.8}\le...
[ "r", "Calculates", "Nusselt", "number", "for", "a", "fluid", "flowing", "inside", "a", "curved", "pipe", "such", "as", "a", "helical", "coil", "under", "turbulent", "conditions", "using", "the", "method", "of", "Mori", "and", "Nakayama", "[", "1", "]", "_"...
python
train
maxfischer2781/include
include/__init__.py
https://github.com/maxfischer2781/include/blob/d8b0404f4996b6abcd39fdebf282b31fad8bb6f5/include/__init__.py#L81-L91
def enable(identifier, exclude_children=False): """ Enable a previously disabled include type :param identifier: module or name of the include type :param exclude_children: disable the include type only for child processes, not the current process The ``identifier`` can be specified in multiple wa...
[ "def", "enable", "(", "identifier", ",", "exclude_children", "=", "False", ")", ":", "DISABLED_TYPES", ".", "enable", "(", "identifier", "=", "identifier", ",", "exclude_children", "=", "exclude_children", ")" ]
Enable a previously disabled include type :param identifier: module or name of the include type :param exclude_children: disable the include type only for child processes, not the current process The ``identifier`` can be specified in multiple ways to disable an include type. See :py:meth:`~.DisabledI...
[ "Enable", "a", "previously", "disabled", "include", "type" ]
python
train
aguinane/nem-reader
nemreader/nem_reader.py
https://github.com/aguinane/nem-reader/blob/5405a5cba4bb8ebdad05c28455d12bb34a6d3ce5/nemreader/nem_reader.py#L175-L183
def parse_250_row(row: list) -> BasicMeterData: """ Parse basic meter data record (250) """ return BasicMeterData(row[1], row[2], row[3], row[4], row[5], row[6], row[7], float(row[8]), parse_datetime(row[9]), row[10], row[11], row[12], ...
[ "def", "parse_250_row", "(", "row", ":", "list", ")", "->", "BasicMeterData", ":", "return", "BasicMeterData", "(", "row", "[", "1", "]", ",", "row", "[", "2", "]", ",", "row", "[", "3", "]", ",", "row", "[", "4", "]", ",", "row", "[", "5", "]"...
Parse basic meter data record (250)
[ "Parse", "basic", "meter", "data", "record", "(", "250", ")" ]
python
train
CityOfZion/neo-python
neo/Core/State/AccountState.py
https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/State/AccountState.py#L232-L242
def AllBalancesZeroOrLess(self): """ Flag indicating if all balances are 0 or less. Returns: bool: True if all balances are <= 0. False, otherwise. """ for key, fixed8 in self.Balances.items(): if fixed8.value > 0: return False ret...
[ "def", "AllBalancesZeroOrLess", "(", "self", ")", ":", "for", "key", ",", "fixed8", "in", "self", ".", "Balances", ".", "items", "(", ")", ":", "if", "fixed8", ".", "value", ">", "0", ":", "return", "False", "return", "True" ]
Flag indicating if all balances are 0 or less. Returns: bool: True if all balances are <= 0. False, otherwise.
[ "Flag", "indicating", "if", "all", "balances", "are", "0", "or", "less", "." ]
python
train
StackStorm/pybind
pybind/slxos/v17r_1_01a/show/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17r_1_01a/show/__init__.py#L503-L526
def _set_vnetwork(self, v, load=False): """ Setter method for vnetwork, mapped from YANG variable /show/vnetwork (container) If this variable is read-only (config: false) in the source YANG file, then _set_vnetwork is considered as a private method. Backends looking to populate this variable should ...
[ "def", "_set_vnetwork", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base"...
Setter method for vnetwork, mapped from YANG variable /show/vnetwork (container) If this variable is read-only (config: false) in the source YANG file, then _set_vnetwork is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_vnetwork() direct...
[ "Setter", "method", "for", "vnetwork", "mapped", "from", "YANG", "variable", "/", "show", "/", "vnetwork", "(", "container", ")", "If", "this", "variable", "is", "read", "-", "only", "(", "config", ":", "false", ")", "in", "the", "source", "YANG", "file"...
python
train
mommermi/callhorizons
callhorizons/callhorizons.py
https://github.com/mommermi/callhorizons/blob/fdd7ad9e87cac107c1b7f88e594d118210da3b1a/callhorizons/callhorizons.py#L46-L53
def _char2int(char): """ translate characters to integer values (upper and lower case)""" if char.isdigit(): return int(float(char)) if char.isupper(): return int(char, 36) else: return 26 + int(char, 36)
[ "def", "_char2int", "(", "char", ")", ":", "if", "char", ".", "isdigit", "(", ")", ":", "return", "int", "(", "float", "(", "char", ")", ")", "if", "char", ".", "isupper", "(", ")", ":", "return", "int", "(", "char", ",", "36", ")", "else", ":"...
translate characters to integer values (upper and lower case)
[ "translate", "characters", "to", "integer", "values", "(", "upper", "and", "lower", "case", ")" ]
python
train
Erotemic/utool
utool/util_cplat.py
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_cplat.py#L1264-L1300
def change_term_title(title): """ only works on unix systems only tested on Ubuntu GNOME changes text on terminal title for identifying debugging tasks. The title will remain until python exists Args: title (str): References: http://stackoverflow.com/questions/5343265/setting-...
[ "def", "change_term_title", "(", "title", ")", ":", "if", "True", ":", "# Disabled", "return", "if", "not", "WIN32", ":", "#print(\"CHANGE TERM TITLE to %r\" % (title,))", "if", "title", ":", "#os.environ['PS1'] = os.environ['PS1'] + '''\"\\e]2;\\\"''' + title + '''\\\"\\a\"'''...
only works on unix systems only tested on Ubuntu GNOME changes text on terminal title for identifying debugging tasks. The title will remain until python exists Args: title (str): References: http://stackoverflow.com/questions/5343265/setting-title-for-tabs-in-terminator-console-appli...
[ "only", "works", "on", "unix", "systems", "only", "tested", "on", "Ubuntu", "GNOME", "changes", "text", "on", "terminal", "title", "for", "identifying", "debugging", "tasks", "." ]
python
train
MartinThoma/hwrt
hwrt/utils.py
https://github.com/MartinThoma/hwrt/blob/725c21a3d0f5a30b8492cbc184b3688ceb364e1c/hwrt/utils.py#L393-L402
def create_adjusted_model_for_percentages(model_src, model_use): """Replace logreg layer by sigmoid to get probabilities.""" # Copy model file shutil.copyfile(model_src, model_use) # Adjust model file with open(model_src) as f: content = f.read() content = content.replace("logreg", "sigm...
[ "def", "create_adjusted_model_for_percentages", "(", "model_src", ",", "model_use", ")", ":", "# Copy model file", "shutil", ".", "copyfile", "(", "model_src", ",", "model_use", ")", "# Adjust model file", "with", "open", "(", "model_src", ")", "as", "f", ":", "co...
Replace logreg layer by sigmoid to get probabilities.
[ "Replace", "logreg", "layer", "by", "sigmoid", "to", "get", "probabilities", "." ]
python
train
edx/edx-enterprise
enterprise/admin/views.py
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/views.py#L796-L814
def get(self, request, customer_uuid): """ Handle GET request - render linked learners list and "Link learner" form. Arguments: request (django.http.request.HttpRequest): Request instance customer_uuid (str): Enterprise Customer UUID Returns: django....
[ "def", "get", "(", "self", ",", "request", ",", "customer_uuid", ")", ":", "context", "=", "self", ".", "_build_context", "(", "request", ",", "customer_uuid", ")", "manage_learners_form", "=", "ManageLearnersForm", "(", "user", "=", "request", ".", "user", ...
Handle GET request - render linked learners list and "Link learner" form. Arguments: request (django.http.request.HttpRequest): Request instance customer_uuid (str): Enterprise Customer UUID Returns: django.http.response.HttpResponse: HttpResponse
[ "Handle", "GET", "request", "-", "render", "linked", "learners", "list", "and", "Link", "learner", "form", "." ]
python
valid
openearth/mmi-python
mmi/runner.py
https://github.com/openearth/mmi-python/blob/a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d/mmi/runner.py#L92-L110
def create_ports(port, mpi, rank): """create a list of ports for the current rank""" if port == "random" or port is None: # ports will be filled in using random binding ports = {} else: port = int(port) ports = { "REQ": port + 0, ...
[ "def", "create_ports", "(", "port", ",", "mpi", ",", "rank", ")", ":", "if", "port", "==", "\"random\"", "or", "port", "is", "None", ":", "# ports will be filled in using random binding", "ports", "=", "{", "}", "else", ":", "port", "=", "int", "(", "port"...
create a list of ports for the current rank
[ "create", "a", "list", "of", "ports", "for", "the", "current", "rank" ]
python
train
KnorrFG/pyparadigm
pyparadigm/extras.py
https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/extras.py#L20-L23
def to_24bit_gray(mat: np.ndarray): """returns a matrix that contains RGB channels, and colors scaled from 0 to 255""" return np.repeat(np.expand_dims(_normalize(mat), axis=2), 3, axis=2)
[ "def", "to_24bit_gray", "(", "mat", ":", "np", ".", "ndarray", ")", ":", "return", "np", ".", "repeat", "(", "np", ".", "expand_dims", "(", "_normalize", "(", "mat", ")", ",", "axis", "=", "2", ")", ",", "3", ",", "axis", "=", "2", ")" ]
returns a matrix that contains RGB channels, and colors scaled from 0 to 255
[ "returns", "a", "matrix", "that", "contains", "RGB", "channels", "and", "colors", "scaled", "from", "0", "to", "255" ]
python
train
joke2k/faker
faker/utils/datasets.py
https://github.com/joke2k/faker/blob/965824b61132e52d92d1a6ce470396dbbe01c96c/faker/utils/datasets.py#L8-L24
def add_dicts(*args): """ Adds two or more dicts together. Common keys will have their values added. For example:: >>> t1 = {'a':1, 'b':2} >>> t2 = {'b':1, 'c':3} >>> t3 = {'d':4} >>> add_dicts(t1, t2, t3) {'a': 1, 'c': 3, 'b': 3, 'd': 4} """ counters = [...
[ "def", "add_dicts", "(", "*", "args", ")", ":", "counters", "=", "[", "Counter", "(", "arg", ")", "for", "arg", "in", "args", "]", "return", "dict", "(", "reduce", "(", "operator", ".", "add", ",", "counters", ")", ")" ]
Adds two or more dicts together. Common keys will have their values added. For example:: >>> t1 = {'a':1, 'b':2} >>> t2 = {'b':1, 'c':3} >>> t3 = {'d':4} >>> add_dicts(t1, t2, t3) {'a': 1, 'c': 3, 'b': 3, 'd': 4}
[ "Adds", "two", "or", "more", "dicts", "together", ".", "Common", "keys", "will", "have", "their", "values", "added", "." ]
python
train
Opentrons/opentrons
api/src/opentrons/helpers/helpers.py
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/helpers/helpers.py#L145-L156
def _compress_for_repeater(max_vol, plan, **kwargs): """ Reduce size of transfer plan, if mode is distribute or consolidate """ max_vol = float(max_vol) mode = kwargs.get('mode', 'transfer') if mode == 'distribute': # combine target volumes into single aspirate return _compress_for_dis...
[ "def", "_compress_for_repeater", "(", "max_vol", ",", "plan", ",", "*", "*", "kwargs", ")", ":", "max_vol", "=", "float", "(", "max_vol", ")", "mode", "=", "kwargs", ".", "get", "(", "'mode'", ",", "'transfer'", ")", "if", "mode", "==", "'distribute'", ...
Reduce size of transfer plan, if mode is distribute or consolidate
[ "Reduce", "size", "of", "transfer", "plan", "if", "mode", "is", "distribute", "or", "consolidate" ]
python
train
google/grumpy
third_party/stdlib/optparse.py
https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/optparse.py#L1706-L1728
def _match_abbrev(s, wordmap): """_match_abbrev(s : string, wordmap : {string : Option}) -> string Return the string key in 'wordmap' for which 's' is an unambiguous abbreviation. If 's' is found to be ambiguous or doesn't match any of 'words', raise BadOptionError. """ # Is there an exact mat...
[ "def", "_match_abbrev", "(", "s", ",", "wordmap", ")", ":", "# Is there an exact match?", "if", "s", "in", "wordmap", ":", "return", "s", "else", ":", "# Isolate all words with s as a prefix.", "possibilities", "=", "[", "word", "for", "word", "in", "wordmap", "...
_match_abbrev(s : string, wordmap : {string : Option}) -> string Return the string key in 'wordmap' for which 's' is an unambiguous abbreviation. If 's' is found to be ambiguous or doesn't match any of 'words', raise BadOptionError.
[ "_match_abbrev", "(", "s", ":", "string", "wordmap", ":", "{", "string", ":", "Option", "}", ")", "-", ">", "string" ]
python
valid
fastai/fastai
fastai/tabular/transform.py
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/tabular/transform.py#L106-L113
def cont_cat_split(df, max_card=20, dep_var=None)->Tuple[List,List]: "Helper function that returns column names of cont and cat variables from given df." cont_names, cat_names = [], [] for label in df: if label == dep_var: continue if df[label].dtype == int and df[label].unique().shape[0] > ...
[ "def", "cont_cat_split", "(", "df", ",", "max_card", "=", "20", ",", "dep_var", "=", "None", ")", "->", "Tuple", "[", "List", ",", "List", "]", ":", "cont_names", ",", "cat_names", "=", "[", "]", ",", "[", "]", "for", "label", "in", "df", ":", "i...
Helper function that returns column names of cont and cat variables from given df.
[ "Helper", "function", "that", "returns", "column", "names", "of", "cont", "and", "cat", "variables", "from", "given", "df", "." ]
python
train
numberoverzero/bloop
bloop/models.py
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/models.py#L943-L1047
def bind_index(model, name, index, force=False, recursive=True, copy=False) -> Index: """Bind an index to the model with the given name. This method is primarily used during BaseModel.__init_subclass__, although it can be used to easily attach a new index to an existing model: .. code-bloc...
[ "def", "bind_index", "(", "model", ",", "name", ",", "index", ",", "force", "=", "False", ",", "recursive", "=", "True", ",", "copy", "=", "False", ")", "->", "Index", ":", "if", "not", "subclassof", "(", "model", ",", "BaseModel", ")", ":", "raise",...
Bind an index to the model with the given name. This method is primarily used during BaseModel.__init_subclass__, although it can be used to easily attach a new index to an existing model: .. code-block:: python import bloop.models class User(BaseModel): ...
[ "Bind", "an", "index", "to", "the", "model", "with", "the", "given", "name", "." ]
python
train
DistrictDataLabs/yellowbrick
yellowbrick/utils/decorators.py
https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/utils/decorators.py#L27-L51
def memoized(fget): """ Return a property attribute for new-style classes that only calls its getter on the first access. The result is stored and on subsequent accesses is returned, preventing the need to call the getter any more. Parameters ---------- fget: function The getter met...
[ "def", "memoized", "(", "fget", ")", ":", "attr_name", "=", "'_{0}'", ".", "format", "(", "fget", ".", "__name__", ")", "@", "wraps", "(", "fget", ")", "def", "fget_memoized", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "attr_nam...
Return a property attribute for new-style classes that only calls its getter on the first access. The result is stored and on subsequent accesses is returned, preventing the need to call the getter any more. Parameters ---------- fget: function The getter method to memoize for subsequent ac...
[ "Return", "a", "property", "attribute", "for", "new", "-", "style", "classes", "that", "only", "calls", "its", "getter", "on", "the", "first", "access", ".", "The", "result", "is", "stored", "and", "on", "subsequent", "accesses", "is", "returned", "preventin...
python
train
DigitalGlobe/gbdxtools
gbdxtools/simpleworkflows.py
https://github.com/DigitalGlobe/gbdxtools/blob/def62f8f2d77b168aa2bd115290aaa0f9a08a4bb/gbdxtools/simpleworkflows.py#L769-L806
def stderr(self): '''Get stderr from all the tasks of a workflow. Returns: (list): tasks with their stderr Example: >>> workflow.stderr [ { "id": "4488895771403082552", "taskType": "AOP_Strip_Processor"...
[ "def", "stderr", "(", "self", ")", ":", "if", "not", "self", ".", "id", ":", "raise", "WorkflowError", "(", "'Workflow is not running. Cannot get stderr.'", ")", "if", "self", ".", "batch_values", ":", "raise", "NotImplementedError", "(", "\"Query Each Workflow Id ...
Get stderr from all the tasks of a workflow. Returns: (list): tasks with their stderr Example: >>> workflow.stderr [ { "id": "4488895771403082552", "taskType": "AOP_Strip_Processor", "name":...
[ "Get", "stderr", "from", "all", "the", "tasks", "of", "a", "workflow", "." ]
python
valid
Hackerfleet/hfos
hfos/tool/templates.py
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/tool/templates.py#L53-L63
def write_template_file(source, target, content): """Write a new file from a given pystache template file and content""" # print(formatTemplateFile(source, content)) print(target) data = format_template_file(source, content) with open(target, 'w') as f: for line in data: if type...
[ "def", "write_template_file", "(", "source", ",", "target", ",", "content", ")", ":", "# print(formatTemplateFile(source, content))", "print", "(", "target", ")", "data", "=", "format_template_file", "(", "source", ",", "content", ")", "with", "open", "(", "target...
Write a new file from a given pystache template file and content
[ "Write", "a", "new", "file", "from", "a", "given", "pystache", "template", "file", "and", "content" ]
python
train
EventTeam/beliefs
src/beliefs/cells/posets.py
https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/posets.py#L67-L78
def set_domain(clz, dag): """ Sets the domain. Should only be called once per class instantiation. """ logging.info("Setting domain for poset %s" % clz.__name__) if nx.number_of_nodes(dag) == 0: raise CellConstructionFailure("Empty DAG structure.") if not nx.is_...
[ "def", "set_domain", "(", "clz", ",", "dag", ")", ":", "logging", ".", "info", "(", "\"Setting domain for poset %s\"", "%", "clz", ".", "__name__", ")", "if", "nx", ".", "number_of_nodes", "(", "dag", ")", "==", "0", ":", "raise", "CellConstructionFailure", ...
Sets the domain. Should only be called once per class instantiation.
[ "Sets", "the", "domain", ".", "Should", "only", "be", "called", "once", "per", "class", "instantiation", "." ]
python
train
riga/scinum
scinum.py
https://github.com/riga/scinum/blob/55eb6d8aa77beacee5a07443392954b8a0aad8cb/scinum.py#L1433-L1460
def match_precision(val, ref, *args, **kwargs): """ Returns a string version of a value *val* matching the significant digits as given in *ref*. *val* might also be a numpy array. All remaining *args* and *kwargs* are forwarded to ``Decimal.quantize``. Example: .. code-block:: python match...
[ "def", "match_precision", "(", "val", ",", "ref", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "val", "=", "ensure_nominal", "(", "val", ")", "if", "not", "is_numpy", "(", "val", ")", ":", "ret", "=", "_match_precision", "(", "val", ",", "r...
Returns a string version of a value *val* matching the significant digits as given in *ref*. *val* might also be a numpy array. All remaining *args* and *kwargs* are forwarded to ``Decimal.quantize``. Example: .. code-block:: python match_precision(1.234, ".1") # -> "1.2" match_precision(1...
[ "Returns", "a", "string", "version", "of", "a", "value", "*", "val", "*", "matching", "the", "significant", "digits", "as", "given", "in", "*", "ref", "*", ".", "*", "val", "*", "might", "also", "be", "a", "numpy", "array", ".", "All", "remaining", "...
python
train
mattja/distob
distob/arrays.py
https://github.com/mattja/distob/blob/b0fc49e157189932c70231077ed35e1aa5717da9/distob/arrays.py#L1030-L1062
def mean(self, axis=None, dtype=None, out=None, keepdims=False): """Compute the arithmetic mean along the specified axis. See np.mean() for details.""" if axis == -1: axis = self.ndim if axis is None: results = vectorize(mean)(self, axis, dtype, keepdims=False) ...
[ "def", "mean", "(", "self", ",", "axis", "=", "None", ",", "dtype", "=", "None", ",", "out", "=", "None", ",", "keepdims", "=", "False", ")", ":", "if", "axis", "==", "-", "1", ":", "axis", "=", "self", ".", "ndim", "if", "axis", "is", "None", ...
Compute the arithmetic mean along the specified axis. See np.mean() for details.
[ "Compute", "the", "arithmetic", "mean", "along", "the", "specified", "axis", ".", "See", "np", ".", "mean", "()", "for", "details", "." ]
python
valid
PmagPy/PmagPy
dialogs/pmag_gui_dialogs2.py
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/pmag_gui_dialogs2.py#L2697-L2782
def on_m_calc_orient(self,event): ''' This fucntion does exactly what the 'import orientation' fuction does in MagIC.py after some dialog boxes the function calls orientation_magic.py ''' # first see if demag_orient.txt self.on_m_save_file(None) orient_convention_...
[ "def", "on_m_calc_orient", "(", "self", ",", "event", ")", ":", "# first see if demag_orient.txt", "self", ".", "on_m_save_file", "(", "None", ")", "orient_convention_dia", "=", "orient_convention", "(", "None", ")", "orient_convention_dia", ".", "Center", "(", ")",...
This fucntion does exactly what the 'import orientation' fuction does in MagIC.py after some dialog boxes the function calls orientation_magic.py
[ "This", "fucntion", "does", "exactly", "what", "the", "import", "orientation", "fuction", "does", "in", "MagIC", ".", "py", "after", "some", "dialog", "boxes", "the", "function", "calls", "orientation_magic", ".", "py" ]
python
train
nevimov/django-easycart
easycart/cart.py
https://github.com/nevimov/django-easycart/blob/81b7d7d4b197e34d21dcd8cb9eb9104b565041a9/easycart/cart.py#L437-L469
def create_items(self, session_items): """Instantiate cart items from session data. The value returned by this method is used to populate the cart's `items` attribute. Parameters ---------- session_items : dict A dictionary of pk-quantity mappings (each pk i...
[ "def", "create_items", "(", "self", ",", "session_items", ")", ":", "pks", "=", "list", "(", "session_items", ".", "keys", "(", ")", ")", "items", "=", "{", "}", "item_class", "=", "self", ".", "item_class", "process_object", "=", "self", ".", "process_o...
Instantiate cart items from session data. The value returned by this method is used to populate the cart's `items` attribute. Parameters ---------- session_items : dict A dictionary of pk-quantity mappings (each pk is a string). For example: ``{'1': 5, '...
[ "Instantiate", "cart", "items", "from", "session", "data", "." ]
python
train
pydata/xarray
xarray/core/variable.py
https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/core/variable.py#L2027-L2040
def broadcast_variables(*variables): """Given any number of variables, return variables with matching dimensions and broadcast data. The data on the returned variables will be a view of the data on the corresponding original arrays, but dimensions will be reordered and inserted so that both broadca...
[ "def", "broadcast_variables", "(", "*", "variables", ")", ":", "dims_map", "=", "_unified_dims", "(", "variables", ")", "dims_tuple", "=", "tuple", "(", "dims_map", ")", "return", "tuple", "(", "var", ".", "set_dims", "(", "dims_map", ")", "if", "var", "."...
Given any number of variables, return variables with matching dimensions and broadcast data. The data on the returned variables will be a view of the data on the corresponding original arrays, but dimensions will be reordered and inserted so that both broadcast arrays have the same dimensions. The new ...
[ "Given", "any", "number", "of", "variables", "return", "variables", "with", "matching", "dimensions", "and", "broadcast", "data", "." ]
python
train
numenta/nupic
src/nupic/frameworks/opf/two_gram_model.py
https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/two_gram_model.py#L152-L176
def read(cls, proto): """ :param proto: capnp TwoGramModelProto message reader """ instance = object.__new__(cls) super(TwoGramModel, instance).__init__(proto=proto.modelBase) instance._logger = opf_utils.initLogger(instance) instance._reset = proto.reset instance._hashToValueDict = {x...
[ "def", "read", "(", "cls", ",", "proto", ")", ":", "instance", "=", "object", ".", "__new__", "(", "cls", ")", "super", "(", "TwoGramModel", ",", "instance", ")", ".", "__init__", "(", "proto", "=", "proto", ".", "modelBase", ")", "instance", ".", "_...
:param proto: capnp TwoGramModelProto message reader
[ ":", "param", "proto", ":", "capnp", "TwoGramModelProto", "message", "reader" ]
python
valid
Nexmo/nexmo-python
nexmo/__init__.py
https://github.com/Nexmo/nexmo-python/blob/c5300541233f3dbd7319c7d2ca6d9f7f70404d11/nexmo/__init__.py#L172-L188
def submit_sms_conversion(self, message_id, delivered=True, timestamp=None): """ Notify Nexmo that an SMS was successfully received. :param message_id: The `message-id` str returned by the send_message call. :param delivered: A `bool` indicating that the message was or was not successfu...
[ "def", "submit_sms_conversion", "(", "self", ",", "message_id", ",", "delivered", "=", "True", ",", "timestamp", "=", "None", ")", ":", "params", "=", "{", "\"message-id\"", ":", "message_id", ",", "\"delivered\"", ":", "delivered", ",", "\"timestamp\"", ":", ...
Notify Nexmo that an SMS was successfully received. :param message_id: The `message-id` str returned by the send_message call. :param delivered: A `bool` indicating that the message was or was not successfully delivered. :param timestamp: A `datetime` object containing the time the SMS arrived....
[ "Notify", "Nexmo", "that", "an", "SMS", "was", "successfully", "received", "." ]
python
train
gwpy/gwpy
gwpy/segments/io/hdf5.py
https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/segments/io/hdf5.py#L239-L287
def write_hdf5_dict(flags, output, path=None, append=False, overwrite=False, **kwargs): """Write this `DataQualityFlag` to a `h5py.Group`. This allows writing to an HDF5-format file. Parameters ---------- output : `str`, :class:`h5py.Group` path to new output file, or o...
[ "def", "write_hdf5_dict", "(", "flags", ",", "output", ",", "path", "=", "None", ",", "append", "=", "False", ",", "overwrite", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "path", ":", "try", ":", "parent", "=", "output", "[", "path", "]...
Write this `DataQualityFlag` to a `h5py.Group`. This allows writing to an HDF5-format file. Parameters ---------- output : `str`, :class:`h5py.Group` path to new output file, or open h5py `Group` to write to. path : `str` the HDF5 group path in which to write a new group for this ...
[ "Write", "this", "DataQualityFlag", "to", "a", "h5py", ".", "Group", "." ]
python
train
OldhamMade/PySO8601
PySO8601/durations.py
https://github.com/OldhamMade/PySO8601/blob/b7d3b3cb3ed3e12eb2a21caa26a3abeab3c96fe4/PySO8601/durations.py#L12-L28
def parse_duration(duration, start=None, end=None): """ Attepmt to parse an ISO8601 formatted duration. Accepts a ``duration`` and optionally a start or end ``datetime``. ``duration`` must be an ISO8601 formatted string. Returns a ``datetime.timedelta`` object. """ if not start and not end...
[ "def", "parse_duration", "(", "duration", ",", "start", "=", "None", ",", "end", "=", "None", ")", ":", "if", "not", "start", "and", "not", "end", ":", "return", "parse_simple_duration", "(", "duration", ")", "if", "start", ":", "return", "parse_duration_w...
Attepmt to parse an ISO8601 formatted duration. Accepts a ``duration`` and optionally a start or end ``datetime``. ``duration`` must be an ISO8601 formatted string. Returns a ``datetime.timedelta`` object.
[ "Attepmt", "to", "parse", "an", "ISO8601", "formatted", "duration", "." ]
python
train
Opentrons/opentrons
api/src/opentrons/protocol_api/labware.py
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/protocol_api/labware.py#L452-L482
def next_tip(self, num_tips: int = 1) -> Optional[Well]: """ Find the next valid well for pick-up. Determines the next valid start tip from which to retrieve the specified number of tips. There must be at least `num_tips` sequential wells for which all wells have tips, in the sa...
[ "def", "next_tip", "(", "self", ",", "num_tips", ":", "int", "=", "1", ")", "->", "Optional", "[", "Well", "]", ":", "assert", "num_tips", ">", "0", "columns", ":", "List", "[", "List", "[", "Well", "]", "]", "=", "self", ".", "columns", "(", ")"...
Find the next valid well for pick-up. Determines the next valid start tip from which to retrieve the specified number of tips. There must be at least `num_tips` sequential wells for which all wells have tips, in the same column. :param num_tips: target number of sequential tips in the ...
[ "Find", "the", "next", "valid", "well", "for", "pick", "-", "up", "." ]
python
train
fastai/fastai
fastai/callbacks/tensorboard.py
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L221-L228
def _queue_processor(self)->None: "Processes queued up write requests asynchronously to Tensorboard." while not self.stop_request.isSet(): while not self.queue.empty(): if self.stop_request.isSet(): return request = self.queue.get() request.wri...
[ "def", "_queue_processor", "(", "self", ")", "->", "None", ":", "while", "not", "self", ".", "stop_request", ".", "isSet", "(", ")", ":", "while", "not", "self", ".", "queue", ".", "empty", "(", ")", ":", "if", "self", ".", "stop_request", ".", "isSe...
Processes queued up write requests asynchronously to Tensorboard.
[ "Processes", "queued", "up", "write", "requests", "asynchronously", "to", "Tensorboard", "." ]
python
train
StyXman/ayrton
ayrton/parser/error.py
https://github.com/StyXman/ayrton/blob/e1eed5c7ef230e3c2340a1f0bf44c72bbdc0debb/ayrton/parser/error.py#L147-L164
def print_detailed_traceback(self, space=None, file=None): """NOT_RPYTHON: Dump a nice detailed interpreter- and application-level traceback, useful to debug the interpreter.""" if file is None: file = sys.stderr f = io.StringIO() for i in range(len(self.debug_excs)-1...
[ "def", "print_detailed_traceback", "(", "self", ",", "space", "=", "None", ",", "file", "=", "None", ")", ":", "if", "file", "is", "None", ":", "file", "=", "sys", ".", "stderr", "f", "=", "io", ".", "StringIO", "(", ")", "for", "i", "in", "range",...
NOT_RPYTHON: Dump a nice detailed interpreter- and application-level traceback, useful to debug the interpreter.
[ "NOT_RPYTHON", ":", "Dump", "a", "nice", "detailed", "interpreter", "-", "and", "application", "-", "level", "traceback", "useful", "to", "debug", "the", "interpreter", "." ]
python
train
tensorflow/tensor2tensor
tensor2tensor/models/xception.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/xception.py#L33-L45
def residual_block(x, hparams): """A stack of convolution blocks with residual connection.""" k = (hparams.kernel_height, hparams.kernel_width) dilations_and_kernels = [((1, 1), k) for _ in range(3)] y = common_layers.subseparable_conv_block( x, hparams.hidden_size, dilations_and_kernels, ...
[ "def", "residual_block", "(", "x", ",", "hparams", ")", ":", "k", "=", "(", "hparams", ".", "kernel_height", ",", "hparams", ".", "kernel_width", ")", "dilations_and_kernels", "=", "[", "(", "(", "1", ",", "1", ")", ",", "k", ")", "for", "_", "in", ...
A stack of convolution blocks with residual connection.
[ "A", "stack", "of", "convolution", "blocks", "with", "residual", "connection", "." ]
python
train
senaite/senaite.core
bika/lims/upgrade/v01_03_000.py
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/upgrade/v01_03_000.py#L1758-L1764
def remove_stale_css(portal): """Removes stale CSS """ logger.info("Removing stale css ...") for css in CSS_TO_REMOVE: logger.info("Unregistering CSS %s" % css) portal.portal_css.unregisterResource(css)
[ "def", "remove_stale_css", "(", "portal", ")", ":", "logger", ".", "info", "(", "\"Removing stale css ...\"", ")", "for", "css", "in", "CSS_TO_REMOVE", ":", "logger", ".", "info", "(", "\"Unregistering CSS %s\"", "%", "css", ")", "portal", ".", "portal_css", "...
Removes stale CSS
[ "Removes", "stale", "CSS" ]
python
train
ninjaaron/libaaron
libaaron/libaaron.py
https://github.com/ninjaaron/libaaron/blob/a2ee417b784ca72c89c05bddb2e3e815a6b95154/libaaron/libaaron.py#L249-L255
def pipe(value, *functions, funcs=None): """pipe(value, f, g, h) == h(g(f(value)))""" if funcs: functions = funcs for function in functions: value = function(value) return value
[ "def", "pipe", "(", "value", ",", "*", "functions", ",", "funcs", "=", "None", ")", ":", "if", "funcs", ":", "functions", "=", "funcs", "for", "function", "in", "functions", ":", "value", "=", "function", "(", "value", ")", "return", "value" ]
pipe(value, f, g, h) == h(g(f(value)))
[ "pipe", "(", "value", "f", "g", "h", ")", "==", "h", "(", "g", "(", "f", "(", "value", ")))" ]
python
test
wummel/dosage
dosagelib/plugins/s.py
https://github.com/wummel/dosage/blob/a0109c3a46219f280e6e5e77183674e40da0f304/dosagelib/plugins/s.py#L481-L486
def namer(cls, imageUrl, pageUrl): """Use page URL to construct meaningful image name.""" parts, year, month, stripname = pageUrl.rsplit('/', 3) stripname = stripname.rsplit('.', 1)[0] parts, imagename = imageUrl.rsplit('/', 1) return '%s-%s-%s-%s' % (year, month, stripname, imag...
[ "def", "namer", "(", "cls", ",", "imageUrl", ",", "pageUrl", ")", ":", "parts", ",", "year", ",", "month", ",", "stripname", "=", "pageUrl", ".", "rsplit", "(", "'/'", ",", "3", ")", "stripname", "=", "stripname", ".", "rsplit", "(", "'.'", ",", "1...
Use page URL to construct meaningful image name.
[ "Use", "page", "URL", "to", "construct", "meaningful", "image", "name", "." ]
python
train
infothrill/python-dyndnsc
dyndnsc/detector/webcheck.py
https://github.com/infothrill/python-dyndnsc/blob/2196d48aa6098da9835a7611fbdb0b5f0fbf51e4/dyndnsc/detector/webcheck.py#L63-L70
def _parser_jsonip(text): """Parse response text like the one returned by http://jsonip.com/.""" import json try: return str(json.loads(text).get("ip")) except ValueError as exc: LOG.debug("Text '%s' could not be parsed", exc_info=exc) return None
[ "def", "_parser_jsonip", "(", "text", ")", ":", "import", "json", "try", ":", "return", "str", "(", "json", ".", "loads", "(", "text", ")", ".", "get", "(", "\"ip\"", ")", ")", "except", "ValueError", "as", "exc", ":", "LOG", ".", "debug", "(", "\"...
Parse response text like the one returned by http://jsonip.com/.
[ "Parse", "response", "text", "like", "the", "one", "returned", "by", "http", ":", "//", "jsonip", ".", "com", "/", "." ]
python
train
google/grr
grr/server/grr_response_server/aff4_objects/aff4_grr.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/aff4_objects/aff4_grr.py#L636-L642
def Initialize(self): """Open the delegate object.""" if "r" in self.mode: delegate = self.Get(self.Schema.DELEGATE) if delegate: self.delegate = aff4.FACTORY.Open( delegate, mode=self.mode, token=self.token, age=self.age_policy)
[ "def", "Initialize", "(", "self", ")", ":", "if", "\"r\"", "in", "self", ".", "mode", ":", "delegate", "=", "self", ".", "Get", "(", "self", ".", "Schema", ".", "DELEGATE", ")", "if", "delegate", ":", "self", ".", "delegate", "=", "aff4", ".", "FAC...
Open the delegate object.
[ "Open", "the", "delegate", "object", "." ]
python
train