repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
jxtech/wechatpy | wechatpy/component.py | https://github.com/jxtech/wechatpy/blob/4df0da795618c0895a10f1c2cde9e9d5c0a93aaa/wechatpy/component.py#L247-L283 | def _fetch_access_token(self, url, data):
""" The real fetch access token """
logger.info('Fetching component access token')
res = self._http.post(
url=url,
data=data
)
try:
res.raise_for_status()
except requests.RequestException as req... | [
"def",
"_fetch_access_token",
"(",
"self",
",",
"url",
",",
"data",
")",
":",
"logger",
".",
"info",
"(",
"'Fetching component access token'",
")",
"res",
"=",
"self",
".",
"_http",
".",
"post",
"(",
"url",
"=",
"url",
",",
"data",
"=",
"data",
")",
"t... | The real fetch access token | [
"The",
"real",
"fetch",
"access",
"token"
] | python | train | 30.837838 |
woolfson-group/isambard | isambard/ampal/assembly.py | https://github.com/woolfson-group/isambard/blob/ebc33b48a28ad217e18f93b910dfba46e6e71e07/isambard/ampal/assembly.py#L785-L807 | def tag_atoms_unique_ids(self, force=False):
""" Tags each Atom in the Assembly with its unique_id.
Notes
-----
The unique_id for each atom is a tuple (a double). `unique_id[0]`
is the unique_id for its parent `Monomer` (see `Monomer.unique_id`
for more information). `un... | [
"def",
"tag_atoms_unique_ids",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"tagged",
"=",
"[",
"'unique_id'",
"in",
"x",
".",
"tags",
".",
"keys",
"(",
")",
"for",
"x",
"in",
"self",
".",
"get_atoms",
"(",
")",
"]",
"if",
"(",
"not",
"all",
... | Tags each Atom in the Assembly with its unique_id.
Notes
-----
The unique_id for each atom is a tuple (a double). `unique_id[0]`
is the unique_id for its parent `Monomer` (see `Monomer.unique_id`
for more information). `unique_id[1]` is the atom_type in the
`Assembly` as... | [
"Tags",
"each",
"Atom",
"in",
"the",
"Assembly",
"with",
"its",
"unique_id",
"."
] | python | train | 39.652174 |
mdavidsaver/p4p | src/p4p/disect.py | https://github.com/mdavidsaver/p4p/blob/c5e45eac01edfdad9cc2857bc283c7f2695802b8/src/p4p/disect.py#L34-L76 | def collect(self, file=sys.stderr):
"""Collect stats and print results to file
:param file: A writable file-like object
"""
cur = gcstats()
Ncur = len(cur)
if self.stats is not None and file is not None:
prev = self.stats
Nprev = self.ntypes # ma... | [
"def",
"collect",
"(",
"self",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
":",
"cur",
"=",
"gcstats",
"(",
")",
"Ncur",
"=",
"len",
"(",
"cur",
")",
"if",
"self",
".",
"stats",
"is",
"not",
"None",
"and",
"file",
"is",
"not",
"None",
":",
"pr... | Collect stats and print results to file
:param file: A writable file-like object | [
"Collect",
"stats",
"and",
"print",
"results",
"to",
"file"
] | python | train | 33.27907 |
Nic30/hwt | hwt/hdl/types/bitsCast.py | https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/hdl/types/bitsCast.py#L30-L46 | def convertBits(self, sigOrVal, toType):
"""
Cast signed-unsigned, to int or bool
"""
if isinstance(sigOrVal, Value):
return convertBits__val(self, sigOrVal, toType)
elif isinstance(toType, HBool):
if self.bit_length() == 1:
v = 0 if sigOrVal._dtype.negated else 1
... | [
"def",
"convertBits",
"(",
"self",
",",
"sigOrVal",
",",
"toType",
")",
":",
"if",
"isinstance",
"(",
"sigOrVal",
",",
"Value",
")",
":",
"return",
"convertBits__val",
"(",
"self",
",",
"sigOrVal",
",",
"toType",
")",
"elif",
"isinstance",
"(",
"toType",
... | Cast signed-unsigned, to int or bool | [
"Cast",
"signed",
"-",
"unsigned",
"to",
"int",
"or",
"bool"
] | python | test | 38.588235 |
Syndace/python-x3dh | x3dh/state.py | https://github.com/Syndace/python-x3dh/blob/a6cec1ae858121b88bef1b178f5cda5e43d5c391/x3dh/state.py#L230-L236 | def __checkSPKTimestamp(self):
"""
Check whether the SPK is too old and generate a new one in that case.
"""
if time.time() - self.__spk["timestamp"] > self.__spk_timeout:
self.__generateSPK() | [
"def",
"__checkSPKTimestamp",
"(",
"self",
")",
":",
"if",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"__spk",
"[",
"\"timestamp\"",
"]",
">",
"self",
".",
"__spk_timeout",
":",
"self",
".",
"__generateSPK",
"(",
")"
] | Check whether the SPK is too old and generate a new one in that case. | [
"Check",
"whether",
"the",
"SPK",
"is",
"too",
"old",
"and",
"generate",
"a",
"new",
"one",
"in",
"that",
"case",
"."
] | python | train | 33 |
Kozea/pygal | pygal/graph/graph.py | https://github.com/Kozea/pygal/blob/5e25c98a59a0642eecd9fcc5dbfeeb2190fbb5e7/pygal/graph/graph.py#L1031-L1038 | def _has_data(self):
"""Check if there is any data"""
return any([
len([
v for a in (s[0] if is_list_like(s) else [s])
for v in (a if is_list_like(a) else [a]) if v is not None
]) for s in self.raw_series
]) | [
"def",
"_has_data",
"(",
"self",
")",
":",
"return",
"any",
"(",
"[",
"len",
"(",
"[",
"v",
"for",
"a",
"in",
"(",
"s",
"[",
"0",
"]",
"if",
"is_list_like",
"(",
"s",
")",
"else",
"[",
"s",
"]",
")",
"for",
"v",
"in",
"(",
"a",
"if",
"is_li... | Check if there is any data | [
"Check",
"if",
"there",
"is",
"any",
"data"
] | python | train | 35 |
ianmiell/shutit | shutit_class.py | https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L895-L935 | def send_and_return_status(self,
send,
expect=None,
shutit_pexpect_child=None,
timeout=None,
fail_on_empty_before=True,
record_command=True,
... | [
"def",
"send_and_return_status",
"(",
"self",
",",
"send",
",",
"expect",
"=",
"None",
",",
"shutit_pexpect_child",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"fail_on_empty_before",
"=",
"True",
",",
"record_command",
"=",
"True",
",",
"exit_values",
"=",... | Returns true if a good exit code was received (usually 0) | [
"Returns",
"true",
"if",
"a",
"good",
"exit",
"code",
"was",
"received",
"(",
"usually",
"0",
")"
] | python | train | 57.341463 |
saltstack/salt | salt/modules/boto_secgroup.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_secgroup.py#L647-L710 | def delete_tags(tags,
name=None,
group_id=None,
vpc_name=None,
vpc_id=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
deletes tags from a security group
.. versionadde... | [
"def",
"delete_tags",
"(",
"tags",
",",
"name",
"=",
"None",
",",
"group_id",
"=",
"None",
",",
"vpc_name",
"=",
"None",
",",
"vpc_id",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"="... | deletes tags from a security group
.. versionadded:: 2016.3.0
tags
a list of tags to remove
name
the name of the security group
group_id
the group id of the security group (in lie of a name/vpc combo)
vpc_name
the name of the vpc to search the named group for
... | [
"deletes",
"tags",
"from",
"a",
"security",
"group"
] | python | train | 25.734375 |
cltk/cltk | cltk/corpus/sanskrit/itrans/itrans_transliterator.py | https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/sanskrit/itrans/itrans_transliterator.py#L139-L146 | def _unrecognised(achr):
""" Handle unrecognised characters. """
if options['handleUnrecognised'] == UNRECOGNISED_ECHO:
return achr
elif options['handleUnrecognised'] == UNRECOGNISED_SUBSTITUTE:
return options['substituteChar']
else:
raise KeyError(achr) | [
"def",
"_unrecognised",
"(",
"achr",
")",
":",
"if",
"options",
"[",
"'handleUnrecognised'",
"]",
"==",
"UNRECOGNISED_ECHO",
":",
"return",
"achr",
"elif",
"options",
"[",
"'handleUnrecognised'",
"]",
"==",
"UNRECOGNISED_SUBSTITUTE",
":",
"return",
"options",
"[",... | Handle unrecognised characters. | [
"Handle",
"unrecognised",
"characters",
"."
] | python | train | 35.875 |
openvax/mhcflurry | mhcflurry/class1_affinity_predictor.py | https://github.com/openvax/mhcflurry/blob/deb7c1629111254b484a2711619eb2347db36524/mhcflurry/class1_affinity_predictor.py#L260-L278 | def supported_peptide_lengths(self):
"""
(minimum, maximum) lengths of peptides supported by *all models*,
inclusive.
Returns
-------
(int, int) tuple
"""
if 'supported_peptide_lengths' not in self._cache:
length_ranges = set(
... | [
"def",
"supported_peptide_lengths",
"(",
"self",
")",
":",
"if",
"'supported_peptide_lengths'",
"not",
"in",
"self",
".",
"_cache",
":",
"length_ranges",
"=",
"set",
"(",
"network",
".",
"supported_peptide_lengths",
"for",
"network",
"in",
"self",
".",
"neural_net... | (minimum, maximum) lengths of peptides supported by *all models*,
inclusive.
Returns
-------
(int, int) tuple | [
"(",
"minimum",
"maximum",
")",
"lengths",
"of",
"peptides",
"supported",
"by",
"*",
"all",
"models",
"*",
"inclusive",
"."
] | python | train | 34.631579 |
tensorflow/tensor2tensor | tensor2tensor/envs/trajectory.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/trajectory.py#L42-L51 | def add_time_step(self, **create_time_step_kwargs):
"""Creates a time-step and appends it to the list.
Args:
**create_time_step_kwargs: Forwarded to
time_step.TimeStep.create_time_step.
"""
ts = time_step.TimeStep.create_time_step(**create_time_step_kwargs)
assert isinstance(ts, time_... | [
"def",
"add_time_step",
"(",
"self",
",",
"*",
"*",
"create_time_step_kwargs",
")",
":",
"ts",
"=",
"time_step",
".",
"TimeStep",
".",
"create_time_step",
"(",
"*",
"*",
"create_time_step_kwargs",
")",
"assert",
"isinstance",
"(",
"ts",
",",
"time_step",
".",
... | Creates a time-step and appends it to the list.
Args:
**create_time_step_kwargs: Forwarded to
time_step.TimeStep.create_time_step. | [
"Creates",
"a",
"time",
"-",
"step",
"and",
"appends",
"it",
"to",
"the",
"list",
"."
] | python | train | 35.7 |
hatemile/hatemile-for-python | hatemile/implementation/css.py | https://github.com/hatemile/hatemile-for-python/blob/1e914f9aa09f6f8d78282af131311546ecba9fb8/hatemile/implementation/css.py#L647-L658 | def _speak_none(self, element):
"""
No speak any content of element only.
:param element: The element.
:type element: hatemile.util.html.htmldomelement.HTMLDOMElement
"""
# pylint: disable=no-self-use
element.set_attribute('role', 'presentation')
element... | [
"def",
"_speak_none",
"(",
"self",
",",
"element",
")",
":",
"# pylint: disable=no-self-use",
"element",
".",
"set_attribute",
"(",
"'role'",
",",
"'presentation'",
")",
"element",
".",
"set_attribute",
"(",
"'aria-hidden'",
",",
"'true'",
")",
"element",
".",
"... | No speak any content of element only.
:param element: The element.
:type element: hatemile.util.html.htmldomelement.HTMLDOMElement | [
"No",
"speak",
"any",
"content",
"of",
"element",
"only",
"."
] | python | train | 35.333333 |
spyder-ide/spyder | spyder/config/gui.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/config/gui.py#L86-L92 | def set_font(font, section='appearance', option='font'):
"""Set font"""
CONF.set(section, option+'/family', to_text_string(font.family()))
CONF.set(section, option+'/size', float(font.pointSize()))
CONF.set(section, option+'/italic', int(font.italic()))
CONF.set(section, option+'/bold', int(font.bol... | [
"def",
"set_font",
"(",
"font",
",",
"section",
"=",
"'appearance'",
",",
"option",
"=",
"'font'",
")",
":",
"CONF",
".",
"set",
"(",
"section",
",",
"option",
"+",
"'/family'",
",",
"to_text_string",
"(",
"font",
".",
"family",
"(",
")",
")",
")",
"... | Set font | [
"Set",
"font"
] | python | train | 51.428571 |
serkanyersen/underscore.py | src/underscore.py | https://github.com/serkanyersen/underscore.py/blob/07c25c3f0f789536e4ad47aa315faccc0da9602f/src/underscore.py#L230-L242 | def find(self, func):
"""
Return the first value which passes a truth test.
Aliased as `detect`.
"""
self.ftmp = None
def test(value, index, list):
if func(value, index, list) is True:
self.ftmp = value
return True
self... | [
"def",
"find",
"(",
"self",
",",
"func",
")",
":",
"self",
".",
"ftmp",
"=",
"None",
"def",
"test",
"(",
"value",
",",
"index",
",",
"list",
")",
":",
"if",
"func",
"(",
"value",
",",
"index",
",",
"list",
")",
"is",
"True",
":",
"self",
".",
... | Return the first value which passes a truth test.
Aliased as `detect`. | [
"Return",
"the",
"first",
"value",
"which",
"passes",
"a",
"truth",
"test",
".",
"Aliased",
"as",
"detect",
"."
] | python | train | 27.846154 |
saltstack/salt | salt/modules/capirca_acl.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/capirca_acl.py#L473-L511 | def _get_term_object(filter_name,
term_name,
pillar_key='acl',
pillarenv=None,
saltenv=None,
merge_pillar=True,
**term_fields):
'''
Return an instance of the ``_Term`` class given the te... | [
"def",
"_get_term_object",
"(",
"filter_name",
",",
"term_name",
",",
"pillar_key",
"=",
"'acl'",
",",
"pillarenv",
"=",
"None",
",",
"saltenv",
"=",
"None",
",",
"merge_pillar",
"=",
"True",
",",
"*",
"*",
"term_fields",
")",
":",
"log",
".",
"debug",
"... | Return an instance of the ``_Term`` class given the term options. | [
"Return",
"an",
"instance",
"of",
"the",
"_Term",
"class",
"given",
"the",
"term",
"options",
"."
] | python | train | 37.410256 |
spyder-ide/conda-manager | conda_manager/api/conda_api.py | https://github.com/spyder-ide/conda-manager/blob/89a2126cbecefc92185cf979347ccac1c5ee5d9d/conda_manager/api/conda_api.py#L1002-L1020 | def _pip_cmd(self, name=None, prefix=None):
"""Get pip location based on environment `name` or `prefix`."""
if (name and prefix) or not (name or prefix):
raise TypeError("conda pip: exactly one of 'name' ""or 'prefix' "
"required.")
if name and self.envir... | [
"def",
"_pip_cmd",
"(",
"self",
",",
"name",
"=",
"None",
",",
"prefix",
"=",
"None",
")",
":",
"if",
"(",
"name",
"and",
"prefix",
")",
"or",
"not",
"(",
"name",
"or",
"prefix",
")",
":",
"raise",
"TypeError",
"(",
"\"conda pip: exactly one of 'name' \"... | Get pip location based on environment `name` or `prefix`. | [
"Get",
"pip",
"location",
"based",
"on",
"environment",
"name",
"or",
"prefix",
"."
] | python | train | 36.526316 |
materialsproject/pymatgen | pymatgen/analysis/structure_matcher.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/structure_matcher.py#L387-L409 | def _get_supercell_size(self, s1, s2):
"""
Returns the supercell size, and whether the supercell should
be applied to s1. If fu == 1, s1_supercell is returned as
true, to avoid ambiguity.
"""
if self._supercell_size == 'num_sites':
fu = s2.num_sites / s1.num_s... | [
"def",
"_get_supercell_size",
"(",
"self",
",",
"s1",
",",
"s2",
")",
":",
"if",
"self",
".",
"_supercell_size",
"==",
"'num_sites'",
":",
"fu",
"=",
"s2",
".",
"num_sites",
"/",
"s1",
".",
"num_sites",
"elif",
"self",
".",
"_supercell_size",
"==",
"'num... | Returns the supercell size, and whether the supercell should
be applied to s1. If fu == 1, s1_supercell is returned as
true, to avoid ambiguity. | [
"Returns",
"the",
"supercell",
"size",
"and",
"whether",
"the",
"supercell",
"should",
"be",
"applied",
"to",
"s1",
".",
"If",
"fu",
"==",
"1",
"s1_supercell",
"is",
"returned",
"as",
"true",
"to",
"avoid",
"ambiguity",
"."
] | python | train | 37.565217 |
UCSBarchlab/PyRTL | pyrtl/simulation.py | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/simulation.py#L901-L941 | def render_trace(
self, trace_list=None, file=sys.stdout, render_cls=default_renderer(),
symbol_len=5, segment_size=5, segment_delim=' ', extra_line=True):
""" Render the trace to a file using unicode and ASCII escape sequences.
:param trace_list: A list of signals to be output... | [
"def",
"render_trace",
"(",
"self",
",",
"trace_list",
"=",
"None",
",",
"file",
"=",
"sys",
".",
"stdout",
",",
"render_cls",
"=",
"default_renderer",
"(",
")",
",",
"symbol_len",
"=",
"5",
",",
"segment_size",
"=",
"5",
",",
"segment_delim",
"=",
"' '"... | Render the trace to a file using unicode and ASCII escape sequences.
:param trace_list: A list of signals to be output in the specified order.
:param file: The place to write output, default to stdout.
:param render_cls: A class that translates traces into output bytes.
:param symbol_le... | [
"Render",
"the",
"trace",
"to",
"a",
"file",
"using",
"unicode",
"and",
"ASCII",
"escape",
"sequences",
"."
] | python | train | 52.634146 |
swisscom/cleanerversion | versions/models.py | https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/models.py#L369-L392 | def get_compiler(self, *args, **kwargs):
"""
Add the query time restriction limit at the last moment. Applying it
earlier (e.g. by adding a filter to the queryset) does not allow the
caching of related object to work (they are attached to a queryset;
filter() returns a new query... | [
"def",
"get_compiler",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"querytime",
".",
"active",
"and",
"(",
"not",
"hasattr",
"(",
"self",
",",
"'_querytime_filter_added'",
")",
"or",
"not",
"self",
".",
"_queryt... | Add the query time restriction limit at the last moment. Applying it
earlier (e.g. by adding a filter to the queryset) does not allow the
caching of related object to work (they are attached to a queryset;
filter() returns a new queryset). | [
"Add",
"the",
"query",
"time",
"restriction",
"limit",
"at",
"the",
"last",
"moment",
".",
"Applying",
"it",
"earlier",
"(",
"e",
".",
"g",
".",
"by",
"adding",
"a",
"filter",
"to",
"the",
"queryset",
")",
"does",
"not",
"allow",
"the",
"caching",
"of"... | python | train | 46.916667 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_genobstacles.py | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_genobstacles.py#L309-L359 | def cmd_genobstacles(self, args):
'''genobstacles command parser'''
usage = "usage: genobstacles <start|stop|restart|clearall|status|set>"
if len(args) == 0:
print(usage)
return
if args[0] == "set":
gen_settings.command(args[1:])
elif args[0] =... | [
"def",
"cmd_genobstacles",
"(",
"self",
",",
"args",
")",
":",
"usage",
"=",
"\"usage: genobstacles <start|stop|restart|clearall|status|set>\"",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"print",
"(",
"usage",
")",
"return",
"if",
"args",
"[",
"0",
"]",
... | genobstacles command parser | [
"genobstacles",
"command",
"parser"
] | python | train | 36.058824 |
mfussenegger/cr8 | cr8/misc.py | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/misc.py#L99-L120 | def as_statements(lines: Iterator[str]) -> Iterator[str]:
"""Create an iterator that transforms lines into sql statements.
Statements within the lines must end with ";"
The last statement will be included even if it does not end in ';'
>>> list(as_statements(['select * from', '-- comments are filtered... | [
"def",
"as_statements",
"(",
"lines",
":",
"Iterator",
"[",
"str",
"]",
")",
"->",
"Iterator",
"[",
"str",
"]",
":",
"lines",
"=",
"(",
"l",
".",
"strip",
"(",
")",
"for",
"l",
"in",
"lines",
"if",
"l",
")",
"lines",
"=",
"(",
"l",
"for",
"l",
... | Create an iterator that transforms lines into sql statements.
Statements within the lines must end with ";"
The last statement will be included even if it does not end in ';'
>>> list(as_statements(['select * from', '-- comments are filtered', 't;']))
['select * from t']
>>> list(as_statements(['... | [
"Create",
"an",
"iterator",
"that",
"transforms",
"lines",
"into",
"sql",
"statements",
"."
] | python | train | 33.636364 |
PyCQA/pylint | pylint/pyreverse/vcgutils.py | https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/vcgutils.py#L176-L181 | def node(self, title, **args):
"""draw a node
"""
self._stream.write('%snode: {title:"%s"' % (self._indent, title))
self._write_attributes(NODE_ATTRS, **args)
self._stream.write("}\n") | [
"def",
"node",
"(",
"self",
",",
"title",
",",
"*",
"*",
"args",
")",
":",
"self",
".",
"_stream",
".",
"write",
"(",
"'%snode: {title:\"%s\"'",
"%",
"(",
"self",
".",
"_indent",
",",
"title",
")",
")",
"self",
".",
"_write_attributes",
"(",
"NODE_ATTR... | draw a node | [
"draw",
"a",
"node"
] | python | test | 36.5 |
anomaly/prestans | prestans/ext/data/adapters/__init__.py | https://github.com/anomaly/prestans/blob/13f5b2467bfd403dcd2d085f15cbf4644044f105/prestans/ext/data/adapters/__init__.py#L167-L193 | def adapt_persistent_instance(persistent_object, target_rest_class=None, attribute_filter=None):
"""
Adapts a single persistent instance to a REST model; at present this is a
common method for all persistent backends.
Refer to: https://groups.google.com/forum/#!topic/prestans-discuss/dO1yx8f60as
fo... | [
"def",
"adapt_persistent_instance",
"(",
"persistent_object",
",",
"target_rest_class",
"=",
"None",
",",
"attribute_filter",
"=",
"None",
")",
":",
"# try and get the adapter and the REST class for the persistent object",
"if",
"target_rest_class",
"is",
"None",
":",
"adapte... | Adapts a single persistent instance to a REST model; at present this is a
common method for all persistent backends.
Refer to: https://groups.google.com/forum/#!topic/prestans-discuss/dO1yx8f60as
for discussion on this feature | [
"Adapts",
"a",
"single",
"persistent",
"instance",
"to",
"a",
"REST",
"model",
";",
"at",
"present",
"this",
"is",
"a",
"common",
"method",
"for",
"all",
"persistent",
"backends",
"."
] | python | train | 48.259259 |
PyCQA/pylint | pylint/pyreverse/main.py | https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/main.py#L166-L176 | def _check_graphviz_available(output_format):
"""check if we need graphviz for different output format"""
try:
subprocess.call(["dot", "-V"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except OSError:
print(
"The output format '%s' is currently not available.\n"
... | [
"def",
"_check_graphviz_available",
"(",
"output_format",
")",
":",
"try",
":",
"subprocess",
".",
"call",
"(",
"[",
"\"dot\"",
",",
"\"-V\"",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
"except",... | check if we need graphviz for different output format | [
"check",
"if",
"we",
"need",
"graphviz",
"for",
"different",
"output",
"format"
] | python | test | 40.818182 |
alephdata/memorious | memorious/logic/http.py | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/logic/http.py#L162-L185 | def fetch(self):
"""Lazily trigger download of the data when requested."""
if self._file_path is not None:
return self._file_path
temp_path = self.context.work_path
if self._content_hash is not None:
self._file_path = storage.load_file(self._content_hash,
... | [
"def",
"fetch",
"(",
"self",
")",
":",
"if",
"self",
".",
"_file_path",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_file_path",
"temp_path",
"=",
"self",
".",
"context",
".",
"work_path",
"if",
"self",
".",
"_content_hash",
"is",
"not",
"None",
... | Lazily trigger download of the data when requested. | [
"Lazily",
"trigger",
"download",
"of",
"the",
"data",
"when",
"requested",
"."
] | python | train | 48.583333 |
guma44/GEOparse | GEOparse/GEOparse.py | https://github.com/guma44/GEOparse/blob/7ee8d5b8678d780382a6bf884afa69d2033f5ca0/GEOparse/GEOparse.py#L323-L339 | def parse_table_data(lines):
""""Parse list of lines from SOFT file into DataFrame.
Args:
lines (:obj:`Iterable`): Iterator over the lines.
Returns:
:obj:`pandas.DataFrame`: Table data.
"""
# filter lines that do not start with symbols
data = "\n".join([i.rstrip() for i in lin... | [
"def",
"parse_table_data",
"(",
"lines",
")",
":",
"# filter lines that do not start with symbols",
"data",
"=",
"\"\\n\"",
".",
"join",
"(",
"[",
"i",
".",
"rstrip",
"(",
")",
"for",
"i",
"in",
"lines",
"if",
"not",
"i",
".",
"startswith",
"(",
"(",
"\"^\... | Parse list of lines from SOFT file into DataFrame.
Args:
lines (:obj:`Iterable`): Iterator over the lines.
Returns:
:obj:`pandas.DataFrame`: Table data. | [
"Parse",
"list",
"of",
"lines",
"from",
"SOFT",
"file",
"into",
"DataFrame",
"."
] | python | train | 29.294118 |
sdss/tree | python/tree/misc/logger.py | https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/python/tree/misc/logger.py#L241-L265 | def start_file_logger(self, name, log_file_level=logging.DEBUG, log_file_path='./'):
"""Start file logging."""
log_file_path = os.path.expanduser(log_file_path) / '{}.log'.format(name)
logdir = log_file_path.parent
try:
logdir.mkdir(parents=True, exist_ok=True)
... | [
"def",
"start_file_logger",
"(",
"self",
",",
"name",
",",
"log_file_level",
"=",
"logging",
".",
"DEBUG",
",",
"log_file_path",
"=",
"'./'",
")",
":",
"log_file_path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"log_file_path",
")",
"/",
"'{}.log'",
... | Start file logging. | [
"Start",
"file",
"logging",
"."
] | python | train | 43.16 |
Accelize/pycosio | pycosio/storage/azure_file.py | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/azure_file.py#L137-L146 | def _list_locators(self):
"""
Lists locators.
Returns:
generator of tuple: locator name str, locator header dict
"""
with _handle_azure_exception():
for share in self.client.list_shares():
yield share.name, self._model_to_dict(share) | [
"def",
"_list_locators",
"(",
"self",
")",
":",
"with",
"_handle_azure_exception",
"(",
")",
":",
"for",
"share",
"in",
"self",
".",
"client",
".",
"list_shares",
"(",
")",
":",
"yield",
"share",
".",
"name",
",",
"self",
".",
"_model_to_dict",
"(",
"sha... | Lists locators.
Returns:
generator of tuple: locator name str, locator header dict | [
"Lists",
"locators",
"."
] | python | train | 30.5 |
useblocks/sphinxcontrib-needs | sphinxcontrib/needs/directives/need.py | https://github.com/useblocks/sphinxcontrib-needs/blob/f49af4859a74e9fe76de5b9133c01335ac6ae191/sphinxcontrib/needs/directives/need.py#L617-L651 | def _fix_list_dyn_func(list):
"""
This searches a list for dynamic function fragments, which may have been cut by generic searches for ",|;".
Example:
`link_a, [[copy('links', need_id)]]` this will be splitted in list of 3 parts:
#. link_a
#. [[copy('links'
#. need_id)]]
This function... | [
"def",
"_fix_list_dyn_func",
"(",
"list",
")",
":",
"open_func_string",
"=",
"False",
"new_list",
"=",
"[",
"]",
"for",
"element",
"in",
"list",
":",
"if",
"'[['",
"in",
"element",
":",
"open_func_string",
"=",
"True",
"new_link",
"=",
"[",
"element",
"]",... | This searches a list for dynamic function fragments, which may have been cut by generic searches for ",|;".
Example:
`link_a, [[copy('links', need_id)]]` this will be splitted in list of 3 parts:
#. link_a
#. [[copy('links'
#. need_id)]]
This function fixes the above list to the following:
... | [
"This",
"searches",
"a",
"list",
"for",
"dynamic",
"function",
"fragments",
"which",
"may",
"have",
"been",
"cut",
"by",
"generic",
"searches",
"for",
"|",
";",
"."
] | python | train | 27.8 |
fedora-infra/fmn.rules | fmn/rules/taskotron.py | https://github.com/fedora-infra/fmn.rules/blob/f9ec790619fcc8b41803077c4dec094e5127fc24/fmn/rules/taskotron.py#L58-L80 | def taskotron_task_outcome(config, message, outcome=None):
""" Particular taskotron task outcome
With this rule, you can limit messages to only those of particular
`taskotron <https://taskotron.fedoraproject.org/>`_ task outcome.
You can specify several outcomes by separating them with a comma ',',
... | [
"def",
"taskotron_task_outcome",
"(",
"config",
",",
"message",
",",
"outcome",
"=",
"None",
")",
":",
"# We only operate on taskotron messages, first off.",
"if",
"not",
"taskotron_result_new",
"(",
"config",
",",
"message",
")",
":",
"return",
"False",
"if",
"not"... | Particular taskotron task outcome
With this rule, you can limit messages to only those of particular
`taskotron <https://taskotron.fedoraproject.org/>`_ task outcome.
You can specify several outcomes by separating them with a comma ',',
i.e.: ``PASSED,FAILED``.
The full list of supported outcomes... | [
"Particular",
"taskotron",
"task",
"outcome"
] | python | train | 36.652174 |
skggm/skggm | inverse_covariance/rank_correlation.py | https://github.com/skggm/skggm/blob/a0ed406586c4364ea3297a658f415e13b5cbdaf8/inverse_covariance/rank_correlation.py#L9-L66 | def _compute_ranks(X, winsorize=False, truncation=None, verbose=True):
"""
Transform each column into ranked data. Tied ranks are averaged.
Ranks can optionally be winsorized as described in Liu 2009 otherwise
this returns Tsukahara's scaled rank based Z-estimator.
Parameters
----------
X :... | [
"def",
"_compute_ranks",
"(",
"X",
",",
"winsorize",
"=",
"False",
",",
"truncation",
"=",
"None",
",",
"verbose",
"=",
"True",
")",
":",
"n_samples",
",",
"n_features",
"=",
"X",
".",
"shape",
"Xrank",
"=",
"np",
".",
"zeros",
"(",
"shape",
"=",
"X"... | Transform each column into ranked data. Tied ranks are averaged.
Ranks can optionally be winsorized as described in Liu 2009 otherwise
this returns Tsukahara's scaled rank based Z-estimator.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
The data matrix where each col... | [
"Transform",
"each",
"column",
"into",
"ranked",
"data",
".",
"Tied",
"ranks",
"are",
"averaged",
".",
"Ranks",
"can",
"optionally",
"be",
"winsorized",
"as",
"described",
"in",
"Liu",
"2009",
"otherwise",
"this",
"returns",
"Tsukahara",
"s",
"scaled",
"rank",... | python | train | 33.258621 |
kislyuk/ensure | ensure/main.py | https://github.com/kislyuk/ensure/blob/0a562a4b469ffbaf71c75dc4d394e94334c831f0/ensure/main.py#L526-L533 | def is_numeric(self):
"""
Ensures :attr:`subject` is an int, float, or long.
"""
from decimal import Decimal
numeric_types = (int, float, long, Decimal) if USING_PYTHON2 else (int, float, Decimal) # noqa
if not isinstance(self._subject, numeric_types):
raise ... | [
"def",
"is_numeric",
"(",
"self",
")",
":",
"from",
"decimal",
"import",
"Decimal",
"numeric_types",
"=",
"(",
"int",
",",
"float",
",",
"long",
",",
"Decimal",
")",
"if",
"USING_PYTHON2",
"else",
"(",
"int",
",",
"float",
",",
"Decimal",
")",
"# noqa",
... | Ensures :attr:`subject` is an int, float, or long. | [
"Ensures",
":",
"attr",
":",
"subject",
"is",
"an",
"int",
"float",
"or",
"long",
"."
] | python | train | 51.875 |
Alignak-monitoring/alignak | alignak/objects/satellitelink.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/satellitelink.py#L803-L814 | def has_a_conf(self, magic_hash=None): # pragma: no cover
"""Send a HTTP request to the satellite (GET /have_conf)
Used to know if the satellite has a conf
:param magic_hash: Config hash. Only used for HA arbiter communication
:type magic_hash: int
:return: Boolean indicating i... | [
"def",
"has_a_conf",
"(",
"self",
",",
"magic_hash",
"=",
"None",
")",
":",
"# pragma: no cover",
"logger",
".",
"debug",
"(",
"\"Have a configuration for %s, %s %s\"",
",",
"self",
".",
"name",
",",
"self",
".",
"alive",
",",
"self",
".",
"reachable",
")",
... | Send a HTTP request to the satellite (GET /have_conf)
Used to know if the satellite has a conf
:param magic_hash: Config hash. Only used for HA arbiter communication
:type magic_hash: int
:return: Boolean indicating if the satellite has a (specific) configuration
:type: bool | [
"Send",
"a",
"HTTP",
"request",
"to",
"the",
"satellite",
"(",
"GET",
"/",
"have_conf",
")",
"Used",
"to",
"know",
"if",
"the",
"satellite",
"has",
"a",
"conf"
] | python | train | 49.583333 |
elastic/elasticsearch-py | elasticsearch/client/xpack/ml.py | https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/xpack/ml.py#L336-L347 | def get_calendars(self, calendar_id=None, body=None, params=None):
"""
`<>`_
:arg calendar_id: The ID of the calendar to fetch
:arg body: The from and size parameters optionally sent in the body
:arg from_: skips a number of calendars
:arg size: specifies a max number of... | [
"def",
"get_calendars",
"(",
"self",
",",
"calendar_id",
"=",
"None",
",",
"body",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"return",
"self",
".",
"transport",
".",
"perform_request",
"(",
"\"GET\"",
",",
"_make_path",
"(",
"\"_ml\"",
",",
"\"c... | `<>`_
:arg calendar_id: The ID of the calendar to fetch
:arg body: The from and size parameters optionally sent in the body
:arg from_: skips a number of calendars
:arg size: specifies a max number of calendars to get | [
"<",
">",
"_"
] | python | train | 40.333333 |
ultrabug/uhashring | uhashring/ring_ketama.py | https://github.com/ultrabug/uhashring/blob/2297471a392e28ed913b3276c2f48d0c01523375/uhashring/ring_ketama.py#L24-L31 | def hashi(self, key, replica=0):
"""Returns a ketama compatible hash from the given key.
"""
dh = self._listbytes(md5(str(key).encode('utf-8')).digest())
rd = replica * 4
return (
(dh[3 + rd] << 24) | (dh[2 + rd] << 16) |
(dh[1 + rd] << 8) | dh[0 + rd]) | [
"def",
"hashi",
"(",
"self",
",",
"key",
",",
"replica",
"=",
"0",
")",
":",
"dh",
"=",
"self",
".",
"_listbytes",
"(",
"md5",
"(",
"str",
"(",
"key",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
".",
"digest",
"(",
")",
")",
"rd",
"=",
"rep... | Returns a ketama compatible hash from the given key. | [
"Returns",
"a",
"ketama",
"compatible",
"hash",
"from",
"the",
"given",
"key",
"."
] | python | train | 38.75 |
pandas-dev/pandas | pandas/core/nanops.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/nanops.py#L895-L980 | def nankurt(values, axis=None, skipna=True, mask=None):
"""
Compute the sample excess kurtosis
The statistic computed here is the adjusted Fisher-Pearson standardized
moment coefficient G2, computed directly from the second and fourth
central moment.
Parameters
----------
values : ndar... | [
"def",
"nankurt",
"(",
"values",
",",
"axis",
"=",
"None",
",",
"skipna",
"=",
"True",
",",
"mask",
"=",
"None",
")",
":",
"values",
"=",
"com",
".",
"values_from_object",
"(",
"values",
")",
"if",
"mask",
"is",
"None",
":",
"mask",
"=",
"isna",
"(... | Compute the sample excess kurtosis
The statistic computed here is the adjusted Fisher-Pearson standardized
moment coefficient G2, computed directly from the second and fourth
central moment.
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
mask... | [
"Compute",
"the",
"sample",
"excess",
"kurtosis"
] | python | train | 28.127907 |
materialsproject/pymatgen | pymatgen/io/abinit/tasks.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/tasks.py#L1695-L1699 | def kill(self):
"""Kill the child."""
self.process.kill()
self.set_status(self.S_ERROR, "status set to Error by task.kill")
self._returncode = self.process.returncode | [
"def",
"kill",
"(",
"self",
")",
":",
"self",
".",
"process",
".",
"kill",
"(",
")",
"self",
".",
"set_status",
"(",
"self",
".",
"S_ERROR",
",",
"\"status set to Error by task.kill\"",
")",
"self",
".",
"_returncode",
"=",
"self",
".",
"process",
".",
"... | Kill the child. | [
"Kill",
"the",
"child",
"."
] | python | train | 38.8 |
micheles/decorator | src/decorator.py | https://github.com/micheles/decorator/blob/7495513ee24deffbf5060860eb69b224fe1d0fe4/src/decorator.py#L225-L256 | def decorate(func, caller, extras=()):
"""
decorate(func, caller) decorates a function using a caller.
If the caller is a generator function, the resulting function
will be a generator function.
"""
evaldict = dict(_call_=caller, _func_=func)
es = ''
for i, extra in enumerate(extras):
... | [
"def",
"decorate",
"(",
"func",
",",
"caller",
",",
"extras",
"=",
"(",
")",
")",
":",
"evaldict",
"=",
"dict",
"(",
"_call_",
"=",
"caller",
",",
"_func_",
"=",
"func",
")",
"es",
"=",
"''",
"for",
"i",
",",
"extra",
"in",
"enumerate",
"(",
"ext... | decorate(func, caller) decorates a function using a caller.
If the caller is a generator function, the resulting function
will be a generator function. | [
"decorate",
"(",
"func",
"caller",
")",
"decorates",
"a",
"function",
"using",
"a",
"caller",
".",
"If",
"the",
"caller",
"is",
"a",
"generator",
"function",
"the",
"resulting",
"function",
"will",
"be",
"a",
"generator",
"function",
"."
] | python | train | 38.5 |
seenaburns/Tungsten | tungsten/core.py | https://github.com/seenaburns/Tungsten/blob/9e865c77a11c512464f226a6b025bc43b798a8be/tungsten/core.py#L80-L87 | def pods(self):
"""Return list of all Pod objects in result"""
# Return empty list if xml_tree is not defined (error Result object)
if not self.xml_tree:
return []
# Create a Pod object for every pod group in xml
return [Pod(elem) for elem in self.xml_tree.findall('p... | [
"def",
"pods",
"(",
"self",
")",
":",
"# Return empty list if xml_tree is not defined (error Result object)",
"if",
"not",
"self",
".",
"xml_tree",
":",
"return",
"[",
"]",
"# Create a Pod object for every pod group in xml",
"return",
"[",
"Pod",
"(",
"elem",
")",
"for"... | Return list of all Pod objects in result | [
"Return",
"list",
"of",
"all",
"Pod",
"objects",
"in",
"result"
] | python | valid | 39.75 |
flatangle/flatlib | flatlib/chart.py | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/chart.py#L142-L154 | def getMoonPhase(self):
""" Returns the phase of the moon. """
sun = self.getObject(const.SUN)
moon = self.getObject(const.MOON)
dist = angle.distance(sun.lon, moon.lon)
if dist < 90:
return const.MOON_FIRST_QUARTER
elif dist < 180:
return const.MO... | [
"def",
"getMoonPhase",
"(",
"self",
")",
":",
"sun",
"=",
"self",
".",
"getObject",
"(",
"const",
".",
"SUN",
")",
"moon",
"=",
"self",
".",
"getObject",
"(",
"const",
".",
"MOON",
")",
"dist",
"=",
"angle",
".",
"distance",
"(",
"sun",
".",
"lon",... | Returns the phase of the moon. | [
"Returns",
"the",
"phase",
"of",
"the",
"moon",
"."
] | python | train | 34.692308 |
bretth/woven | woven/environment.py | https://github.com/bretth/woven/blob/ec1da7b401a335f43129e7115fe7a4d145649f1e/woven/environment.py#L536-L546 | def project_version(full_version):
"""
project_version context manager
"""
project_full_version=full_version
v = _parse_project_version(full_version)
name = project_name()
project_fullname = '-'.join([name,v])
return _setenv(project_full_version=project_full_version, project_version=v,... | [
"def",
"project_version",
"(",
"full_version",
")",
":",
"project_full_version",
"=",
"full_version",
"v",
"=",
"_parse_project_version",
"(",
"full_version",
")",
"name",
"=",
"project_name",
"(",
")",
"project_fullname",
"=",
"'-'",
".",
"join",
"(",
"[",
"nam... | project_version context manager | [
"project_version",
"context",
"manager"
] | python | train | 32.909091 |
openstack/python-saharaclient | doc/ext/cli.py | https://github.com/openstack/python-saharaclient/blob/c53831d686d9e94187ce5dfdbfa43883b792280e/doc/ext/cli.py#L25-L37 | def _get_command(classes):
"""Associates each command class with command depending on setup.cfg
"""
commands = {}
setup_file = os.path.join(
os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')),
'setup.cfg')
for line in open(setup_file, 'r'):
for cl in classes:
... | [
"def",
"_get_command",
"(",
"classes",
")",
":",
"commands",
"=",
"{",
"}",
"setup_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(... | Associates each command class with command depending on setup.cfg | [
"Associates",
"each",
"command",
"class",
"with",
"command",
"depending",
"on",
"setup",
".",
"cfg"
] | python | train | 33.230769 |
django-fluent/django-fluent-contents | fluent_contents/extensions/pluginpool.py | https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/extensions/pluginpool.py#L190-L207 | def _import_plugins(self):
"""
Internal function, ensure all plugin packages are imported.
"""
if self.detected:
return
# In some cases, plugin scanning may start during a request.
# Make sure there is only one thread scanning for plugins.
self.scanLo... | [
"def",
"_import_plugins",
"(",
"self",
")",
":",
"if",
"self",
".",
"detected",
":",
"return",
"# In some cases, plugin scanning may start during a request.",
"# Make sure there is only one thread scanning for plugins.",
"self",
".",
"scanLock",
".",
"acquire",
"(",
")",
"i... | Internal function, ensure all plugin packages are imported. | [
"Internal",
"function",
"ensure",
"all",
"plugin",
"packages",
"are",
"imported",
"."
] | python | train | 30.833333 |
mayfield/shellish | shellish/command/command.py | https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/command/command.py#L151-L172 | def run_wrap(self, args):
""" Wrap some standard protocol around a command's run method. This
wrapper should generally never capture exceptions. It can look at
them and do things but prerun and postrun should always be symmetric.
Any exception suppression should happen in the `session.... | [
"def",
"run_wrap",
"(",
"self",
",",
"args",
")",
":",
"self",
".",
"fire_event",
"(",
"'prerun'",
",",
"args",
")",
"self",
".",
"prerun",
"(",
"args",
")",
"try",
":",
"if",
"self",
".",
"session",
".",
"allow_pager",
"and",
"self",
".",
"use_pager... | Wrap some standard protocol around a command's run method. This
wrapper should generally never capture exceptions. It can look at
them and do things but prerun and postrun should always be symmetric.
Any exception suppression should happen in the `session.execute`. | [
"Wrap",
"some",
"standard",
"protocol",
"around",
"a",
"command",
"s",
"run",
"method",
".",
"This",
"wrapper",
"should",
"generally",
"never",
"capture",
"exceptions",
".",
"It",
"can",
"look",
"at",
"them",
"and",
"do",
"things",
"but",
"prerun",
"and",
... | python | train | 45.318182 |
dnanexus/dx-toolkit | doc/examples/dx-apps/report_example/src/report_example.py | https://github.com/dnanexus/dx-toolkit/blob/74befb53ad90fcf902d8983ae6d74580f402d619/doc/examples/dx-apps/report_example/src/report_example.py#L76-L110 | def draw_bar_chart():
"""
Uses sample code from http://matplotlib.org/1.2.1/examples/api/barchart_demo.html
"""
N = 5
menMeans = (20, 35, 30, 35, 27)
menStd = (2, 3, 4, 1, 2)
ind = numpy.arange(N)
width = 0.35
fig = pyplot.figure()
ax = fig.add_subplot(111)
rects1 = ax.bar(... | [
"def",
"draw_bar_chart",
"(",
")",
":",
"N",
"=",
"5",
"menMeans",
"=",
"(",
"20",
",",
"35",
",",
"30",
",",
"35",
",",
"27",
")",
"menStd",
"=",
"(",
"2",
",",
"3",
",",
"4",
",",
"1",
",",
"2",
")",
"ind",
"=",
"numpy",
".",
"arange",
... | Uses sample code from http://matplotlib.org/1.2.1/examples/api/barchart_demo.html | [
"Uses",
"sample",
"code",
"from",
"http",
":",
"//",
"matplotlib",
".",
"org",
"/",
"1",
".",
"2",
".",
"1",
"/",
"examples",
"/",
"api",
"/",
"barchart_demo",
".",
"html"
] | python | train | 28.542857 |
pywbem/pywbem | pywbem_mock/_wbemconnection_mock.py | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L3123-L3145 | def _validate_open_params(**params):
"""
Validate the fql parameters and if invalid, generate exception
"""
if not params['FilterQueryLanguage'] and params['FilterQuery']:
raise CIMError(
CIM_ERR_INVALID_PARAMETER,
"FilterQuery without FilterQu... | [
"def",
"_validate_open_params",
"(",
"*",
"*",
"params",
")",
":",
"if",
"not",
"params",
"[",
"'FilterQueryLanguage'",
"]",
"and",
"params",
"[",
"'FilterQuery'",
"]",
":",
"raise",
"CIMError",
"(",
"CIM_ERR_INVALID_PARAMETER",
",",
"\"FilterQuery without FilterQue... | Validate the fql parameters and if invalid, generate exception | [
"Validate",
"the",
"fql",
"parameters",
"and",
"if",
"invalid",
"generate",
"exception"
] | python | train | 46.478261 |
Rapptz/discord.py | discord/guild.py | https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L622-L705 | async def create_text_channel(self, name, *, overwrites=None, category=None, reason=None, **options):
"""|coro|
Creates a :class:`TextChannel` for the guild.
Note that you need the :attr:`~Permissions.manage_channels` permission
to create the channel.
The ``overwrites`` parame... | [
"async",
"def",
"create_text_channel",
"(",
"self",
",",
"name",
",",
"*",
",",
"overwrites",
"=",
"None",
",",
"category",
"=",
"None",
",",
"reason",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"data",
"=",
"await",
"self",
".",
"_create_channel... | |coro|
Creates a :class:`TextChannel` for the guild.
Note that you need the :attr:`~Permissions.manage_channels` permission
to create the channel.
The ``overwrites`` parameter can be used to create a 'secret'
channel upon creation. This parameter expects a :class:`dict` of
... | [
"|coro|"
] | python | train | 37.452381 |
zooniverse/panoptes-python-client | panoptes_client/project_preferences.py | https://github.com/zooniverse/panoptes-python-client/blob/138d93cb03378501a8d349428e381ad73f928680/panoptes_client/project_preferences.py#L21-L49 | def find(cls, id='', user=None, project=None):
"""
Like :py:meth:`.PanoptesObject.find` but can also query by user and
project.
- **user** and **project** can be either a :py:class:`.User` and
:py:class:`.Project` instance respectively, or they can be given as
IDs. I... | [
"def",
"find",
"(",
"cls",
",",
"id",
"=",
"''",
",",
"user",
"=",
"None",
",",
"project",
"=",
"None",
")",
":",
"if",
"not",
"id",
":",
"if",
"not",
"(",
"user",
"and",
"project",
")",
":",
"raise",
"ValueError",
"(",
"'Both user and project requir... | Like :py:meth:`.PanoptesObject.find` but can also query by user and
project.
- **user** and **project** can be either a :py:class:`.User` and
:py:class:`.Project` instance respectively, or they can be given as
IDs. If either argument is given, the other is also required. | [
"Like",
":",
"py",
":",
"meth",
":",
".",
"PanoptesObject",
".",
"find",
"but",
"can",
"also",
"query",
"by",
"user",
"and",
"project",
"."
] | python | train | 36.827586 |
MacHu-GWU/superjson-project | superjson/pkg/dateutil/parser.py | https://github.com/MacHu-GWU/superjson-project/blob/782ca4b2edbd4b4018b8cedee42eeae7c921b917/superjson/pkg/dateutil/parser.py#L1368-L1374 | def _parsems(value):
"""Parse a I[.F] seconds value into (seconds, microseconds)."""
if "." not in value:
return int(value), 0
else:
i, f = value.split(".")
return int(i), int(f.ljust(6, "0")[:6]) | [
"def",
"_parsems",
"(",
"value",
")",
":",
"if",
"\".\"",
"not",
"in",
"value",
":",
"return",
"int",
"(",
"value",
")",
",",
"0",
"else",
":",
"i",
",",
"f",
"=",
"value",
".",
"split",
"(",
"\".\"",
")",
"return",
"int",
"(",
"i",
")",
",",
... | Parse a I[.F] seconds value into (seconds, microseconds). | [
"Parse",
"a",
"I",
"[",
".",
"F",
"]",
"seconds",
"value",
"into",
"(",
"seconds",
"microseconds",
")",
"."
] | python | valid | 32.285714 |
mitsei/dlkit | dlkit/records/assessment/basic/drag_and_drop_records.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/records/assessment/basic/drag_and_drop_records.py#L358-L362 | def add_zone_condition(self, droppable_id, zone_id, match=True):
"""stub"""
self.my_osid_object_form._my_map['zoneConditions'].append(
{'droppableId': droppable_id, 'zoneId': zone_id, 'match': match})
self.my_osid_object_form._my_map['zoneConditions'].sort(key=lambda k: k['zoneId']) | [
"def",
"add_zone_condition",
"(",
"self",
",",
"droppable_id",
",",
"zone_id",
",",
"match",
"=",
"True",
")",
":",
"self",
".",
"my_osid_object_form",
".",
"_my_map",
"[",
"'zoneConditions'",
"]",
".",
"append",
"(",
"{",
"'droppableId'",
":",
"droppable_id",... | stub | [
"stub"
] | python | train | 63 |
apple/turicreate | src/unity/python/turicreate/toolkits/_tree_model_mixin.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_tree_model_mixin.py#L192-L208 | def _dump_to_text(self, with_stats):
"""
Dump the models into a list of strings. Each
string is a text representation of a tree.
Parameters
----------
with_stats : bool
If true, include node statistics in the output.
Returns
-------
o... | [
"def",
"_dump_to_text",
"(",
"self",
",",
"with_stats",
")",
":",
"return",
"tc",
".",
"extensions",
".",
"_xgboost_dump_model",
"(",
"self",
".",
"__proxy__",
",",
"with_stats",
"=",
"with_stats",
",",
"format",
"=",
"'text'",
")"
] | Dump the models into a list of strings. Each
string is a text representation of a tree.
Parameters
----------
with_stats : bool
If true, include node statistics in the output.
Returns
-------
out : SFrame
A table with two columns: feature... | [
"Dump",
"the",
"models",
"into",
"a",
"list",
"of",
"strings",
".",
"Each",
"string",
"is",
"a",
"text",
"representation",
"of",
"a",
"tree",
"."
] | python | train | 31.529412 |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/quantization_utils.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/quantization_utils.py#L34-L65 | def _convert_1bit_array_to_byte_array(arr):
"""
Convert bit array to byte array.
:param arr: list
Bits as a list where each element is an integer of 0 or 1
Returns
-------
numpy.array
1D numpy array of type uint8
"""
# Padding if necessary
while len(arr) < 8 or len(... | [
"def",
"_convert_1bit_array_to_byte_array",
"(",
"arr",
")",
":",
"# Padding if necessary",
"while",
"len",
"(",
"arr",
")",
"<",
"8",
"or",
"len",
"(",
"arr",
")",
"%",
"8",
":",
"arr",
".",
"append",
"(",
"0",
")",
"arr",
"=",
"_np",
".",
"array",
... | Convert bit array to byte array.
:param arr: list
Bits as a list where each element is an integer of 0 or 1
Returns
-------
numpy.array
1D numpy array of type uint8 | [
"Convert",
"bit",
"array",
"to",
"byte",
"array",
"."
] | python | train | 31.875 |
fredericklussier/Lifepo4weredPy | lifepo4weredPy/functions.py | https://github.com/fredericklussier/Lifepo4weredPy/blob/f5b3fedf896d0d616bf5ae603953e5541d493640/lifepo4weredPy/functions.py#L27-L40 | def canWrite(variable):
"""
mention if an element can be written.
:param variable: the element to evaluate.
:type variable: Lifepo4weredEnum
:return: true when write access is available, otherwise false
:rtype: bool
:raises ValueError: if parameter value is not a member of Lifepo4weredEnum
... | [
"def",
"canWrite",
"(",
"variable",
")",
":",
"if",
"variable",
"not",
"in",
"variablesEnum",
":",
"raise",
"ValueError",
"(",
"'Use a lifepo4wered enum element as parameter.'",
")",
"return",
"lifepo4weredSO",
".",
"access_lifepo4wered",
"(",
"variable",
".",
"value"... | mention if an element can be written.
:param variable: the element to evaluate.
:type variable: Lifepo4weredEnum
:return: true when write access is available, otherwise false
:rtype: bool
:raises ValueError: if parameter value is not a member of Lifepo4weredEnum | [
"mention",
"if",
"an",
"element",
"can",
"be",
"written",
"."
] | python | train | 36.5 |
PyCQA/astroid | astroid/brain/brain_builtin_inference.py | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/brain/brain_builtin_inference.py#L560-L602 | def infer_issubclass(callnode, context=None):
"""Infer issubclass() calls
:param nodes.Call callnode: an `issubclass` call
:param InferenceContext: the context for the inference
:rtype nodes.Const: Boolean Const value of the `issubclass` call
:raises UseInferenceDefault: If the node cannot be infer... | [
"def",
"infer_issubclass",
"(",
"callnode",
",",
"context",
"=",
"None",
")",
":",
"call",
"=",
"arguments",
".",
"CallSite",
".",
"from_call",
"(",
"callnode",
")",
"if",
"call",
".",
"keyword_arguments",
":",
"# issubclass doesn't support keyword arguments",
"ra... | Infer issubclass() calls
:param nodes.Call callnode: an `issubclass` call
:param InferenceContext: the context for the inference
:rtype nodes.Const: Boolean Const value of the `issubclass` call
:raises UseInferenceDefault: If the node cannot be inferred | [
"Infer",
"issubclass",
"()",
"calls"
] | python | train | 40 |
tensorflow/cleverhans | examples/nips17_adversarial_competition/dev_toolkit/sample_targeted_attacks/iter_target_class/attack_iter_target_class.py | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/sample_targeted_attacks/iter_target_class/attack_iter_target_class.py#L92-L106 | def save_images(images, filenames, output_dir):
"""Saves images to the output directory.
Args:
images: array with minibatch of images
filenames: list of filenames without path
If number of file names in this list less than number of images in
the minibatch then only first len(filenames) images ... | [
"def",
"save_images",
"(",
"images",
",",
"filenames",
",",
"output_dir",
")",
":",
"for",
"i",
",",
"filename",
"in",
"enumerate",
"(",
"filenames",
")",
":",
"# Images for inception classifier are normalized to be in [-1, 1] interval,",
"# so rescale them back to [0, 1]."... | Saves images to the output directory.
Args:
images: array with minibatch of images
filenames: list of filenames without path
If number of file names in this list less than number of images in
the minibatch then only first len(filenames) images will be saved.
output_dir: directory where to sav... | [
"Saves",
"images",
"to",
"the",
"output",
"directory",
"."
] | python | train | 44.533333 |
bodylabs/lace | lace/topology.py | https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/topology.py#L367-L377 | def create_from_mesh_and_lines(cls, mesh, lines):
'''
Return a copy of mesh with line vertices and edges added.
mesh: A Mesh
lines: A list of Polyline or Lines objects.
'''
mesh_with_lines = mesh.copy()
mesh_with_lines.add_lines(lines)
return mesh_with_l... | [
"def",
"create_from_mesh_and_lines",
"(",
"cls",
",",
"mesh",
",",
"lines",
")",
":",
"mesh_with_lines",
"=",
"mesh",
".",
"copy",
"(",
")",
"mesh_with_lines",
".",
"add_lines",
"(",
"lines",
")",
"return",
"mesh_with_lines"
] | Return a copy of mesh with line vertices and edges added.
mesh: A Mesh
lines: A list of Polyline or Lines objects. | [
"Return",
"a",
"copy",
"of",
"mesh",
"with",
"line",
"vertices",
"and",
"edges",
"added",
"."
] | python | train | 28.545455 |
tonysimpson/nanomsg-python | _nanomsg_ctypes/__init__.py | https://github.com/tonysimpson/nanomsg-python/blob/3acd9160f90f91034d4a43ce603aaa19fbaf1f2e/_nanomsg_ctypes/__init__.py#L161-L177 | def nn_getsockopt(socket, level, option, value):
"""retrieve a socket option
socket - socket number
level - option level
option - option
value - a writable byte buffer (e.g. a bytearray) which the option value
will be copied to
returns - number of bytes copied or on error nunber < 0
""... | [
"def",
"nn_getsockopt",
"(",
"socket",
",",
"level",
",",
"option",
",",
"value",
")",
":",
"if",
"memoryview",
"(",
"value",
")",
".",
"readonly",
":",
"raise",
"TypeError",
"(",
"'Writable buffer is required'",
")",
"size_t_size",
"=",
"ctypes",
".",
"c_si... | retrieve a socket option
socket - socket number
level - option level
option - option
value - a writable byte buffer (e.g. a bytearray) which the option value
will be copied to
returns - number of bytes copied or on error nunber < 0 | [
"retrieve",
"a",
"socket",
"option"
] | python | train | 35.411765 |
kstateome/django-cas | cas/models.py | https://github.com/kstateome/django-cas/blob/8a871093966f001b4dadf7d097ac326169f3c066/cas/models.py#L97-L106 | def delete_old_tickets(**kwargs):
"""
Delete tickets if they are over 2 days old
kwargs = ['raw', 'signal', 'instance', 'sender', 'created']
"""
sender = kwargs.get('sender', None)
now = datetime.now()
expire = datetime(now.year, now.month, now.day - 2)
sender.objects.filter(created__lt... | [
"def",
"delete_old_tickets",
"(",
"*",
"*",
"kwargs",
")",
":",
"sender",
"=",
"kwargs",
".",
"get",
"(",
"'sender'",
",",
"None",
")",
"now",
"=",
"datetime",
".",
"now",
"(",
")",
"expire",
"=",
"datetime",
"(",
"now",
".",
"year",
",",
"now",
".... | Delete tickets if they are over 2 days old
kwargs = ['raw', 'signal', 'instance', 'sender', 'created'] | [
"Delete",
"tickets",
"if",
"they",
"are",
"over",
"2",
"days",
"old",
"kwargs",
"=",
"[",
"raw",
"signal",
"instance",
"sender",
"created",
"]"
] | python | train | 32.8 |
Nixiware/viper | nx/viper/service/mysql.py | https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/service/mysql.py#L228-L246 | def runInteraction(self, interaction, *args, **kwargs):
"""
Interact with the database and return the result.
:param interaction: <function> method with first argument is a <adbapi.Transaction> instance
:param args: additional positional arguments to be passed to interaction
:pa... | [
"def",
"runInteraction",
"(",
"self",
",",
"interaction",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"self",
".",
"_connectionPool",
".",
"runInteraction",
"(",
"interaction",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
"... | Interact with the database and return the result.
:param interaction: <function> method with first argument is a <adbapi.Transaction> instance
:param args: additional positional arguments to be passed to interaction
:param kwargs: keyword arguments to be passed to interaction
:return: <... | [
"Interact",
"with",
"the",
"database",
"and",
"return",
"the",
"result",
"."
] | python | train | 34.210526 |
BlackEarth/bl | bl/config.py | https://github.com/BlackEarth/bl/blob/edf6f37dac718987260b90ad0e7f7fe084a7c1a3/bl/config.py#L154-L171 | def package_config(path, template='__config__.ini.TEMPLATE', config_name='__config__.ini', **params):
"""configure the module at the given path with a config template and file.
path = the filesystem path to the given module
template = the config template filename within that path
... | [
"def",
"package_config",
"(",
"path",
",",
"template",
"=",
"'__config__.ini.TEMPLATE'",
",",
"config_name",
"=",
"'__config__.ini'",
",",
"*",
"*",
"params",
")",
":",
"config_fns",
"=",
"[",
"]",
"template_fns",
"=",
"rglob",
"(",
"path",
",",
"template",
... | configure the module at the given path with a config template and file.
path = the filesystem path to the given module
template = the config template filename within that path
config_name = the config filename within that path
params = a dict containing config params, ... | [
"configure",
"the",
"module",
"at",
"the",
"given",
"path",
"with",
"a",
"config",
"template",
"and",
"file",
".",
"path",
"=",
"the",
"filesystem",
"path",
"to",
"the",
"given",
"module",
"template",
"=",
"the",
"config",
"template",
"filename",
"within",
... | python | train | 50.777778 |
google/apitools | apitools/base/protorpclite/descriptor.py | https://github.com/google/apitools/blob/f3745a7ea535aa0e88b0650c16479b696d6fd446/apitools/base/protorpclite/descriptor.py#L282-L302 | def describe_enum(enum_definition):
"""Build descriptor for Enum class.
Args:
enum_definition: Enum class to provide descriptor for.
Returns:
Initialized EnumDescriptor instance describing the Enum class.
"""
enum_descriptor = EnumDescriptor()
enum_descriptor.name = enum_definition... | [
"def",
"describe_enum",
"(",
"enum_definition",
")",
":",
"enum_descriptor",
"=",
"EnumDescriptor",
"(",
")",
"enum_descriptor",
".",
"name",
"=",
"enum_definition",
".",
"definition_name",
"(",
")",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
"values... | Build descriptor for Enum class.
Args:
enum_definition: Enum class to provide descriptor for.
Returns:
Initialized EnumDescriptor instance describing the Enum class. | [
"Build",
"descriptor",
"for",
"Enum",
"class",
"."
] | python | train | 27.904762 |
OSSOS/MOP | src/ossos/plotting/scripts/plot_aq.py | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/plotting/scripts/plot_aq.py#L17-L32 | def parse_nate_sims(path):
'''
parts0.dat) contains the id number, particle fraction (ignore) a, ecc, inc, long. asc., arg. per, and mean anomaly
for every particle in the simulation at t=0.
The second (parts3999.dat) contains the same info at t=3.999 Gyrs for these particles.
:return:
'''
... | [
"def",
"parse_nate_sims",
"(",
"path",
")",
":",
"zerostate",
"=",
"pandas",
".",
"read_table",
"(",
"path",
"+",
"'parts0.dat'",
",",
"delim_whitespace",
"=",
"True",
")",
"endstate",
"=",
"pandas",
".",
"read_table",
"(",
"path",
"+",
"'parts3999.dat'",
",... | parts0.dat) contains the id number, particle fraction (ignore) a, ecc, inc, long. asc., arg. per, and mean anomaly
for every particle in the simulation at t=0.
The second (parts3999.dat) contains the same info at t=3.999 Gyrs for these particles.
:return: | [
"parts0",
".",
"dat",
")",
"contains",
"the",
"id",
"number",
"particle",
"fraction",
"(",
"ignore",
")",
"a",
"ecc",
"inc",
"long",
".",
"asc",
".",
"arg",
".",
"per",
"and",
"mean",
"anomaly",
"for",
"every",
"particle",
"in",
"the",
"simulation",
"a... | python | train | 39.1875 |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/slugs.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/slugs.py#L7947-L7965 | def gps_date_time_encode(self, year, month, day, hour, min, sec, clockStat, visSat, useSat, GppGl, sigUsedMask, percentUsed):
'''
Pilot console PWM messges.
year : Year reported by Gps (uint8_t)
month : Month repor... | [
"def",
"gps_date_time_encode",
"(",
"self",
",",
"year",
",",
"month",
",",
"day",
",",
"hour",
",",
"min",
",",
"sec",
",",
"clockStat",
",",
"visSat",
",",
"useSat",
",",
"GppGl",
",",
"sigUsedMask",
",",
"percentUsed",
")",
":",
"return",
"MAVLink_gps... | Pilot console PWM messges.
year : Year reported by Gps (uint8_t)
month : Month reported by Gps (uint8_t)
day : Day reported by Gps (uint8_t)
hour : Hour reported by Gps (u... | [
"Pilot",
"console",
"PWM",
"messges",
"."
] | python | train | 70.631579 |
crocs-muni/roca | roca/detect_tls.py | https://github.com/crocs-muni/roca/blob/74ad6ce63c428d83dcffce9c5e26ef7b9e30faa5/roca/detect_tls.py#L68-L87 | def process_host(self, host_spec, name, line_idx=0):
"""
One host spec processing
:param host_spec:
:param name:
:param line_idx:
:return:
"""
try:
parts = host_spec.split(':', 1)
host = parts[0].strip()
port = parts[1] ... | [
"def",
"process_host",
"(",
"self",
",",
"host_spec",
",",
"name",
",",
"line_idx",
"=",
"0",
")",
":",
"try",
":",
"parts",
"=",
"host_spec",
".",
"split",
"(",
"':'",
",",
"1",
")",
"host",
"=",
"parts",
"[",
"0",
"]",
".",
"strip",
"(",
")",
... | One host spec processing
:param host_spec:
:param name:
:param line_idx:
:return: | [
"One",
"host",
"spec",
"processing",
":",
"param",
"host_spec",
":",
":",
"param",
"name",
":",
":",
"param",
"line_idx",
":",
":",
"return",
":"
] | python | train | 34 |
biocommons/hgvs | hgvs/dataproviders/uta.py | https://github.com/biocommons/hgvs/blob/4d16efb475e1802b2531a2f1c373e8819d8e533b/hgvs/dataproviders/uta.py#L342-L363 | def get_tx_identity_info(self, tx_ac):
"""returns features associated with a single transcript.
:param tx_ac: transcript accession with version (e.g., 'NM_199425.2')
:type tx_ac: str
# database output
-[ RECORD 1 ]--+-------------
tx_ac | NM_199425.2
al... | [
"def",
"get_tx_identity_info",
"(",
"self",
",",
"tx_ac",
")",
":",
"rows",
"=",
"self",
".",
"_fetchall",
"(",
"self",
".",
"_queries",
"[",
"'tx_identity_info'",
"]",
",",
"[",
"tx_ac",
"]",
")",
"if",
"len",
"(",
"rows",
")",
"==",
"0",
":",
"rais... | returns features associated with a single transcript.
:param tx_ac: transcript accession with version (e.g., 'NM_199425.2')
:type tx_ac: str
# database output
-[ RECORD 1 ]--+-------------
tx_ac | NM_199425.2
alt_ac | NM_199425.2
alt_aln_method ... | [
"returns",
"features",
"associated",
"with",
"a",
"single",
"transcript",
"."
] | python | train | 34.272727 |
has2k1/plotnine | plotnine/scales/scales.py | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/scales/scales.py#L20-L32 | def append(self, sc):
"""
Add scale 'sc' and remove any previous
scales that cover the same aesthetics
"""
ae = sc.aesthetics[0]
cover_ae = self.find(ae)
if any(cover_ae):
warn(_TPL_DUPLICATE_SCALE.format(ae), PlotnineWarning)
idx = cover_a... | [
"def",
"append",
"(",
"self",
",",
"sc",
")",
":",
"ae",
"=",
"sc",
".",
"aesthetics",
"[",
"0",
"]",
"cover_ae",
"=",
"self",
".",
"find",
"(",
"ae",
")",
"if",
"any",
"(",
"cover_ae",
")",
":",
"warn",
"(",
"_TPL_DUPLICATE_SCALE",
".",
"format",
... | Add scale 'sc' and remove any previous
scales that cover the same aesthetics | [
"Add",
"scale",
"sc",
"and",
"remove",
"any",
"previous",
"scales",
"that",
"cover",
"the",
"same",
"aesthetics"
] | python | train | 32.846154 |
trailofbits/manticore | manticore/platforms/evm.py | https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L2338-L2346 | def new_address(self, sender=None, nonce=None):
"""Create a fresh 160bit address"""
if sender is not None and nonce is None:
nonce = self.get_nonce(sender)
new_address = self.calculate_new_address(sender, nonce)
if sender is None and new_address in self:
return s... | [
"def",
"new_address",
"(",
"self",
",",
"sender",
"=",
"None",
",",
"nonce",
"=",
"None",
")",
":",
"if",
"sender",
"is",
"not",
"None",
"and",
"nonce",
"is",
"None",
":",
"nonce",
"=",
"self",
".",
"get_nonce",
"(",
"sender",
")",
"new_address",
"="... | Create a fresh 160bit address | [
"Create",
"a",
"fresh",
"160bit",
"address"
] | python | valid | 41 |
Microsoft/nni | tools/nni_annotation/code_generator.py | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_annotation/code_generator.py#L41-L59 | def parse_annotation_function(code, func_name):
"""Parse an annotation function.
Return the value of `name` keyword argument and the AST Call node.
func_name: expected function name
"""
expr = parse_annotation(code)
call = expr.value
assert type(call) is ast.Call, 'Annotation is not a functi... | [
"def",
"parse_annotation_function",
"(",
"code",
",",
"func_name",
")",
":",
"expr",
"=",
"parse_annotation",
"(",
"code",
")",
"call",
"=",
"expr",
".",
"value",
"assert",
"type",
"(",
"call",
")",
"is",
"ast",
".",
"Call",
",",
"'Annotation is not a functi... | Parse an annotation function.
Return the value of `name` keyword argument and the AST Call node.
func_name: expected function name | [
"Parse",
"an",
"annotation",
"function",
".",
"Return",
"the",
"value",
"of",
"name",
"keyword",
"argument",
"and",
"the",
"AST",
"Call",
"node",
".",
"func_name",
":",
"expected",
"function",
"name"
] | python | train | 44.631579 |
etingof/pysnmp | pysnmp/hlapi/v1arch/asyncore/ntforg.py | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/hlapi/v1arch/asyncore/ntforg.py#L20-L211 | def sendNotification(snmpDispatcher, authData, transportTarget,
notifyType, *varBinds, **options):
"""Send SNMP notification.
Based on passed parameters, prepares SNMP TRAP or INFORM
notification (:RFC:`1905#section-4.2.6`) and schedules its
transmission by I/O framework at a later... | [
"def",
"sendNotification",
"(",
"snmpDispatcher",
",",
"authData",
",",
"transportTarget",
",",
"notifyType",
",",
"*",
"varBinds",
",",
"*",
"*",
"options",
")",
":",
"sysUpTime",
"=",
"v2c",
".",
"apiTrapPDU",
".",
"sysUpTime",
"snmpTrapOID",
"=",
"v2c",
"... | Send SNMP notification.
Based on passed parameters, prepares SNMP TRAP or INFORM
notification (:RFC:`1905#section-4.2.6`) and schedules its
transmission by I/O framework at a later point of time.
Parameters
----------
snmpDispatcher: :py:class:`~pysnmp.hlapi.v1arch.asyncore.SnmpDispatcher`
... | [
"Send",
"SNMP",
"notification",
"."
] | python | train | 37.421875 |
glitchassassin/lackey | lackey/RegionMatching.py | https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L686-L717 | def click(self, target=None, modifiers=""):
""" Moves the cursor to the target location and clicks the default mouse button. """
if target is None:
target = self._lastMatch or self # Whichever one is not None
target_location = None
if isinstance(target, Pattern):
... | [
"def",
"click",
"(",
"self",
",",
"target",
"=",
"None",
",",
"modifiers",
"=",
"\"\"",
")",
":",
"if",
"target",
"is",
"None",
":",
"target",
"=",
"self",
".",
"_lastMatch",
"or",
"self",
"# Whichever one is not None",
"target_location",
"=",
"None",
"if"... | Moves the cursor to the target location and clicks the default mouse button. | [
"Moves",
"the",
"cursor",
"to",
"the",
"target",
"location",
"and",
"clicks",
"the",
"default",
"mouse",
"button",
"."
] | python | train | 40.46875 |
tensorflow/tensor2tensor | tensor2tensor/trax/layers/base.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/base.py#L179-L186 | def sizes(x):
"""Get a structure of sizes for a structure of nested arrays."""
def size(x):
try:
return x.size
except Exception: # pylint: disable=broad-except
return 0
return nested_map(x, size) | [
"def",
"sizes",
"(",
"x",
")",
":",
"def",
"size",
"(",
"x",
")",
":",
"try",
":",
"return",
"x",
".",
"size",
"except",
"Exception",
":",
"# pylint: disable=broad-except",
"return",
"0",
"return",
"nested_map",
"(",
"x",
",",
"size",
")"
] | Get a structure of sizes for a structure of nested arrays. | [
"Get",
"a",
"structure",
"of",
"sizes",
"for",
"a",
"structure",
"of",
"nested",
"arrays",
"."
] | python | train | 26.875 |
a1ezzz/wasp-general | wasp_general/task/dependency.py | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/task/dependency.py#L181-L215 | def start_task(self, task_tag, skip_unresolved=False):
""" Check dependency for the given task_tag and start task. For dependency checking see
:meth:`.WTaskDependencyRegistryStorage.dependency_check`. If task is already started then it must be
stopped before it will be started again.
:param task_tag: task to s... | [
"def",
"start_task",
"(",
"self",
",",
"task_tag",
",",
"skip_unresolved",
"=",
"False",
")",
":",
"if",
"self",
".",
"started_tasks",
"(",
"task_registry_id",
"=",
"task_tag",
")",
"is",
"not",
"None",
":",
"return",
"task_cls",
"=",
"self",
".",
"tasks_b... | Check dependency for the given task_tag and start task. For dependency checking see
:meth:`.WTaskDependencyRegistryStorage.dependency_check`. If task is already started then it must be
stopped before it will be started again.
:param task_tag: task to start. Any required dependencies will be started automatically... | [
"Check",
"dependency",
"for",
"the",
"given",
"task_tag",
"and",
"start",
"task",
".",
"For",
"dependency",
"checking",
"see",
":",
"meth",
":",
".",
"WTaskDependencyRegistryStorage",
".",
"dependency_check",
".",
"If",
"task",
"is",
"already",
"started",
"then"... | python | train | 37.485714 |
materialsproject/pymatgen | pymatgen/analysis/chemenv/utils/coordination_geometry_utils.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/chemenv/utils/coordination_geometry_utils.py#L694-L702 | def distances(self, points):
"""
Computes the distances from the plane to each of the points. Positive distances are on the side of the
normal of the plane while negative distances are on the other side
:param points: Points for which distances are computed
:return: Distances fro... | [
"def",
"distances",
"(",
"self",
",",
"points",
")",
":",
"return",
"[",
"np",
".",
"dot",
"(",
"self",
".",
"normal_vector",
",",
"pp",
")",
"+",
"self",
".",
"d",
"for",
"pp",
"in",
"points",
"]"
] | Computes the distances from the plane to each of the points. Positive distances are on the side of the
normal of the plane while negative distances are on the other side
:param points: Points for which distances are computed
:return: Distances from the plane to the points (positive values on the... | [
"Computes",
"the",
"distances",
"from",
"the",
"plane",
"to",
"each",
"of",
"the",
"points",
".",
"Positive",
"distances",
"are",
"on",
"the",
"side",
"of",
"the",
"normal",
"of",
"the",
"plane",
"while",
"negative",
"distances",
"are",
"on",
"the",
"other... | python | train | 59.111111 |
genialis/resolwe | resolwe/flow/filters.py | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/filters.py#L59-L71 | def validate_query_params(self):
"""Ensure no unsupported query params were used."""
allowed_params = set(self.get_filters().keys())
allowed_params.update(self.get_always_allowed_arguments())
unallowed = set(self.request.query_params.keys()) - allowed_params
if unallowed:
... | [
"def",
"validate_query_params",
"(",
"self",
")",
":",
"allowed_params",
"=",
"set",
"(",
"self",
".",
"get_filters",
"(",
")",
".",
"keys",
"(",
")",
")",
"allowed_params",
".",
"update",
"(",
"self",
".",
"get_always_allowed_arguments",
"(",
")",
")",
"u... | Ensure no unsupported query params were used. | [
"Ensure",
"no",
"unsupported",
"query",
"params",
"were",
"used",
"."
] | python | train | 42.692308 |
CZ-NIC/yangson | yangson/schemanode.py | https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/schemanode.py#L351-L369 | def get_child(self, name: YangIdentifier,
ns: YangIdentifier = None) -> Optional[SchemaNode]:
"""Return receiver's schema child.
Args:
name: Child's name.
ns: Child's namespace (= `self.ns` if absent).
"""
ns = ns if ns else self.ns
todo... | [
"def",
"get_child",
"(",
"self",
",",
"name",
":",
"YangIdentifier",
",",
"ns",
":",
"YangIdentifier",
"=",
"None",
")",
"->",
"Optional",
"[",
"SchemaNode",
"]",
":",
"ns",
"=",
"ns",
"if",
"ns",
"else",
"self",
".",
"ns",
"todo",
"=",
"[",
"]",
"... | Return receiver's schema child.
Args:
name: Child's name.
ns: Child's namespace (= `self.ns` if absent). | [
"Return",
"receiver",
"s",
"schema",
"child",
"."
] | python | train | 33.736842 |
jantman/pypi-download-stats | pypi_download_stats/outputgenerator.py | https://github.com/jantman/pypi-download-stats/blob/44a7a6bbcd61a9e7f02bd02c52584a98183f80c5/pypi_download_stats/outputgenerator.py#L93-L123 | def _generate_html(self):
"""
Generate the HTML for the specified graphs.
:return:
:rtype:
"""
logger.debug('Generating templated HTML')
env = Environment(
loader=PackageLoader('pypi_download_stats', 'templates'),
extensions=['jinja2.ext.l... | [
"def",
"_generate_html",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"'Generating templated HTML'",
")",
"env",
"=",
"Environment",
"(",
"loader",
"=",
"PackageLoader",
"(",
"'pypi_download_stats'",
",",
"'templates'",
")",
",",
"extensions",
"=",
"[",
... | Generate the HTML for the specified graphs.
:return:
:rtype: | [
"Generate",
"the",
"HTML",
"for",
"the",
"specified",
"graphs",
"."
] | python | train | 34.387097 |
PBR/MQ2 | MQ2/mq2.py | https://github.com/PBR/MQ2/blob/6d84dea47e6751333004743f588f03158e35c28d/MQ2/mq2.py#L167-L218 | def run_mq2(plugin, folder, lod_threshold=None, session=None,
outputfolder=None):
""" Run the plugin. """
qtls_file = 'qtls.csv'
matrix_file = 'qtls_matrix.csv'
map_file = 'map.csv'
map_qtl_file = 'map_with_qtls.csv'
qtls_mk_file = 'qtls_with_mk.csv'
map_chart_file = 'MapChart.m... | [
"def",
"run_mq2",
"(",
"plugin",
",",
"folder",
",",
"lod_threshold",
"=",
"None",
",",
"session",
"=",
"None",
",",
"outputfolder",
"=",
"None",
")",
":",
"qtls_file",
"=",
"'qtls.csv'",
"matrix_file",
"=",
"'qtls_matrix.csv'",
"map_file",
"=",
"'map.csv'",
... | Run the plugin. | [
"Run",
"the",
"plugin",
"."
] | python | train | 42.134615 |
chaoss/grimoirelab-manuscripts | manuscripts2/report.py | https://github.com/chaoss/grimoirelab-manuscripts/blob/94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9/manuscripts2/report.py#L58-L71 | def create_csv(filename, csv_data, mode="w"):
"""
Create a CSV file with the given data and store it in the
file with the given name.
:param filename: name of the file to store the data in
:pram csv_data: the data to be stored in the file
:param mode: the mode in which we have to open the file.... | [
"def",
"create_csv",
"(",
"filename",
",",
"csv_data",
",",
"mode",
"=",
"\"w\"",
")",
":",
"with",
"open",
"(",
"filename",
",",
"mode",
")",
"as",
"f",
":",
"csv_data",
".",
"replace",
"(",
"\"_\"",
",",
"r\"\\_\"",
")",
"f",
".",
"write",
"(",
"... | Create a CSV file with the given data and store it in the
file with the given name.
:param filename: name of the file to store the data in
:pram csv_data: the data to be stored in the file
:param mode: the mode in which we have to open the file. It can
be 'w', 'a', etc. Default is 'w' | [
"Create",
"a",
"CSV",
"file",
"with",
"the",
"given",
"data",
"and",
"store",
"it",
"in",
"the",
"file",
"with",
"the",
"given",
"name",
"."
] | python | train | 33.714286 |
aleju/imgaug | imgaug/augmentables/bbs.py | https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/bbs.py#L1036-L1048 | def clip_out_of_image(self):
"""
Clip off all parts from all bounding boxes that are outside of the image.
Returns
-------
imgaug.BoundingBoxesOnImage
Bounding boxes, clipped to fall within the image dimensions.
"""
bbs_cut = [bb.clip_out_of_image(se... | [
"def",
"clip_out_of_image",
"(",
"self",
")",
":",
"bbs_cut",
"=",
"[",
"bb",
".",
"clip_out_of_image",
"(",
"self",
".",
"shape",
")",
"for",
"bb",
"in",
"self",
".",
"bounding_boxes",
"if",
"bb",
".",
"is_partly_within_image",
"(",
"self",
".",
"shape",
... | Clip off all parts from all bounding boxes that are outside of the image.
Returns
-------
imgaug.BoundingBoxesOnImage
Bounding boxes, clipped to fall within the image dimensions. | [
"Clip",
"off",
"all",
"parts",
"from",
"all",
"bounding",
"boxes",
"that",
"are",
"outside",
"of",
"the",
"image",
"."
] | python | valid | 36.230769 |
InspectorMustache/base16-builder-python | pybase16_builder/builder.py | https://github.com/InspectorMustache/base16-builder-python/blob/586f1f87ee9f70696ab19c542af6ef55c6548a2e/pybase16_builder/builder.py#L56-L61 | def get_template_dirs():
"""Return a set of all template directories."""
temp_glob = rel_to_cwd('templates', '**', 'templates', 'config.yaml')
temp_groups = glob(temp_glob)
temp_groups = [get_parent_dir(path, 2) for path in temp_groups]
return set(temp_groups) | [
"def",
"get_template_dirs",
"(",
")",
":",
"temp_glob",
"=",
"rel_to_cwd",
"(",
"'templates'",
",",
"'**'",
",",
"'templates'",
",",
"'config.yaml'",
")",
"temp_groups",
"=",
"glob",
"(",
"temp_glob",
")",
"temp_groups",
"=",
"[",
"get_parent_dir",
"(",
"path"... | Return a set of all template directories. | [
"Return",
"a",
"set",
"of",
"all",
"template",
"directories",
"."
] | python | train | 45.833333 |
majerteam/sqla_inspect | sqla_inspect/py3o.py | https://github.com/majerteam/sqla_inspect/blob/67edb5541e6a56b0a657d3774d1e19c1110cd402/sqla_inspect/py3o.py#L39-L48 | def format_py3o_val(value):
"""
format a value to fit py3o's context
* Handle linebreaks
"""
value = force_unicode(value)
value = escape(value)
value = value.replace(u'\n', u'<text:line-break/>')
return Markup(value) | [
"def",
"format_py3o_val",
"(",
"value",
")",
":",
"value",
"=",
"force_unicode",
"(",
"value",
")",
"value",
"=",
"escape",
"(",
"value",
")",
"value",
"=",
"value",
".",
"replace",
"(",
"u'\\n'",
",",
"u'<text:line-break/>'",
")",
"return",
"Markup",
"(",... | format a value to fit py3o's context
* Handle linebreaks | [
"format",
"a",
"value",
"to",
"fit",
"py3o",
"s",
"context"
] | python | train | 24 |
pantsbuild/pex | pex/util.py | https://github.com/pantsbuild/pex/blob/87b2129d860250d3b9edce75b9cb62f9789ee521/pex/util.py#L221-L252 | def iter_pth_paths(filename):
"""Given a .pth file, extract and yield all inner paths without honoring imports. This shadows
python's site.py behavior, which is invoked at interpreter startup."""
try:
f = open(filename, 'rU') # noqa
except IOError:
return
dirname = os.path.dirname(filename)
known_... | [
"def",
"iter_pth_paths",
"(",
"filename",
")",
":",
"try",
":",
"f",
"=",
"open",
"(",
"filename",
",",
"'rU'",
")",
"# noqa",
"except",
"IOError",
":",
"return",
"dirname",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
")",
"known_paths",
"... | Given a .pth file, extract and yield all inner paths without honoring imports. This shadows
python's site.py behavior, which is invoked at interpreter startup. | [
"Given",
"a",
".",
"pth",
"file",
"extract",
"and",
"yield",
"all",
"inner",
"paths",
"without",
"honoring",
"imports",
".",
"This",
"shadows",
"python",
"s",
"site",
".",
"py",
"behavior",
"which",
"is",
"invoked",
"at",
"interpreter",
"startup",
"."
] | python | train | 36.125 |
sebdah/dynamic-dynamodb | dynamic_dynamodb/core/table.py | https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/core/table.py#L13-L78 | def ensure_provisioning(
table_name, key_name,
num_consec_read_checks,
num_consec_write_checks):
""" Ensure that provisioning is correct
:type table_name: str
:param table_name: Name of the DynamoDB table
:type key_name: str
:param key_name: Configuration option key name
... | [
"def",
"ensure_provisioning",
"(",
"table_name",
",",
"key_name",
",",
"num_consec_read_checks",
",",
"num_consec_write_checks",
")",
":",
"if",
"get_global_option",
"(",
"'circuit_breaker_url'",
")",
"or",
"get_table_option",
"(",
"key_name",
",",
"'circuit_breaker_url'"... | Ensure that provisioning is correct
:type table_name: str
:param table_name: Name of the DynamoDB table
:type key_name: str
:param key_name: Configuration option key name
:type num_consec_read_checks: int
:param num_consec_read_checks: How many consecutive checks have we had
:type num_conse... | [
"Ensure",
"that",
"provisioning",
"is",
"correct"
] | python | train | 34.30303 |
twilio/twilio-python | twilio/request_validator.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/request_validator.py#L27-L37 | def remove_port(uri):
"""Remove the port number from a URI
:param uri: full URI that Twilio requested on your server
:returns: full URI without a port number
:rtype: str
"""
new_netloc = uri.netloc.split(':')[0]
new_uri = uri._replace(netloc=new_netloc)
return new_uri.geturl() | [
"def",
"remove_port",
"(",
"uri",
")",
":",
"new_netloc",
"=",
"uri",
".",
"netloc",
".",
"split",
"(",
"':'",
")",
"[",
"0",
"]",
"new_uri",
"=",
"uri",
".",
"_replace",
"(",
"netloc",
"=",
"new_netloc",
")",
"return",
"new_uri",
".",
"geturl",
"(",... | Remove the port number from a URI
:param uri: full URI that Twilio requested on your server
:returns: full URI without a port number
:rtype: str | [
"Remove",
"the",
"port",
"number",
"from",
"a",
"URI"
] | python | train | 27.363636 |
RRZE-HPC/pycachesim | cachesim/cache.py | https://github.com/RRZE-HPC/pycachesim/blob/6dd084d29cf91ec19b016e0db9ccdfc8d1f63c5b/cachesim/cache.py#L131-L148 | def store(self, addr, length=1, non_temporal=False):
"""
Store one or more adresses.
:param addr: byte address of store location
:param length: All address from addr until addr+length (exclusive) are
stored (default: 1)
:param non_temporal: if True, no wri... | [
"def",
"store",
"(",
"self",
",",
"addr",
",",
"length",
"=",
"1",
",",
"non_temporal",
"=",
"False",
")",
":",
"if",
"non_temporal",
":",
"raise",
"ValueError",
"(",
"\"non_temporal stores are not yet supported\"",
")",
"if",
"addr",
"is",
"None",
":",
"ret... | Store one or more adresses.
:param addr: byte address of store location
:param length: All address from addr until addr+length (exclusive) are
stored (default: 1)
:param non_temporal: if True, no write-allocate will be issued, but cacheline will be zeroed | [
"Store",
"one",
"or",
"more",
"adresses",
"."
] | python | train | 38.333333 |
welbornprod/colr | colr/progress.py | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress.py#L397-L411 | def fmt(self, value):
""" Sets self.fmt, with some extra help for plain format strings. """
if isinstance(value, str):
value = value.split(self.join_str)
if not (value and isinstance(value, (list, tuple))):
raise TypeError(
' '.join((
'... | [
"def",
"fmt",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"value",
"=",
"value",
".",
"split",
"(",
"self",
".",
"join_str",
")",
"if",
"not",
"(",
"value",
"and",
"isinstance",
"(",
"value",
",",
... | Sets self.fmt, with some extra help for plain format strings. | [
"Sets",
"self",
".",
"fmt",
"with",
"some",
"extra",
"help",
"for",
"plain",
"format",
"strings",
"."
] | python | train | 38.066667 |
BlueBrain/NeuroM | neurom/core/types.py | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/core/types.py#L95-L97 | def dendrite_filter(n):
'''Select only dendrites'''
return n.type == NeuriteType.basal_dendrite or n.type == NeuriteType.apical_dendrite | [
"def",
"dendrite_filter",
"(",
"n",
")",
":",
"return",
"n",
".",
"type",
"==",
"NeuriteType",
".",
"basal_dendrite",
"or",
"n",
".",
"type",
"==",
"NeuriteType",
".",
"apical_dendrite"
] | Select only dendrites | [
"Select",
"only",
"dendrites"
] | python | train | 47.333333 |
robertpeteuil/multi-cloud-control | mcc/cldcnct.py | https://github.com/robertpeteuil/multi-cloud-control/blob/f1565af1c0b6ed465ff312d3ccc592ba0609f4a2/mcc/cldcnct.py#L134-L145 | def conn_aws(cred, crid):
"""Establish connection to AWS service."""
driver = get_driver(Provider.EC2)
try:
aws_obj = driver(cred['aws_access_key_id'],
cred['aws_secret_access_key'],
region=cred['aws_default_region'])
except SSLError as e:
... | [
"def",
"conn_aws",
"(",
"cred",
",",
"crid",
")",
":",
"driver",
"=",
"get_driver",
"(",
"Provider",
".",
"EC2",
")",
"try",
":",
"aws_obj",
"=",
"driver",
"(",
"cred",
"[",
"'aws_access_key_id'",
"]",
",",
"cred",
"[",
"'aws_secret_access_key'",
"]",
",... | Establish connection to AWS service. | [
"Establish",
"connection",
"to",
"AWS",
"service",
"."
] | python | train | 40.5 |
PolicyStat/docx2html | docx2html/core.py | https://github.com/PolicyStat/docx2html/blob/2dc4afd1e3a3f2f0b357d0bff903eb58bcc94429/docx2html/core.py#L337-L346 | def get_ilvl(li, w_namespace):
"""
The ilvl on an li tag tells the li tag at what level of indentation this
tag is at. This is used to determine if the li tag needs to be nested or
not.
"""
ilvls = li.xpath('.//w:ilvl', namespaces=li.nsmap)
if len(ilvls) == 0:
return -1
return in... | [
"def",
"get_ilvl",
"(",
"li",
",",
"w_namespace",
")",
":",
"ilvls",
"=",
"li",
".",
"xpath",
"(",
"'.//w:ilvl'",
",",
"namespaces",
"=",
"li",
".",
"nsmap",
")",
"if",
"len",
"(",
"ilvls",
")",
"==",
"0",
":",
"return",
"-",
"1",
"return",
"int",
... | The ilvl on an li tag tells the li tag at what level of indentation this
tag is at. This is used to determine if the li tag needs to be nested or
not. | [
"The",
"ilvl",
"on",
"an",
"li",
"tag",
"tells",
"the",
"li",
"tag",
"at",
"what",
"level",
"of",
"indentation",
"this",
"tag",
"is",
"at",
".",
"This",
"is",
"used",
"to",
"determine",
"if",
"the",
"li",
"tag",
"needs",
"to",
"be",
"nested",
"or",
... | python | test | 34.9 |
twisted/mantissa | xmantissa/liveform.py | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/liveform.py#L1097-L1102 | def realForm(self, req, tag):
"""
Render L{liveForm}.
"""
self.liveForm.setFragmentParent(self)
return self.liveForm | [
"def",
"realForm",
"(",
"self",
",",
"req",
",",
"tag",
")",
":",
"self",
".",
"liveForm",
".",
"setFragmentParent",
"(",
"self",
")",
"return",
"self",
".",
"liveForm"
] | Render L{liveForm}. | [
"Render",
"L",
"{",
"liveForm",
"}",
"."
] | python | train | 25.166667 |
jotacor/ComunioPy | ComunioPy/__init__.py | https://github.com/jotacor/ComunioPy/blob/2dd71e3e197b497980ea7b9cfbec1da64dca3ed0/ComunioPy/__init__.py#L43-L61 | def load_info(self):
''' Get info from logged account '''
headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain",'Referer': 'http://'+self.domain+'/login.phtml',"User-Agent": user_agent}
req = self.session.get('http://'+self.domain+'/team_news.phtml',headers=header... | [
"def",
"load_info",
"(",
"self",
")",
":",
"headers",
"=",
"{",
"\"Content-type\"",
":",
"\"application/x-www-form-urlencoded\"",
",",
"\"Accept\"",
":",
"\"text/plain\"",
",",
"'Referer'",
":",
"'http://'",
"+",
"self",
".",
"domain",
"+",
"'/login.phtml'",
",",
... | Get info from logged account | [
"Get",
"info",
"from",
"logged",
"account"
] | python | train | 56.684211 |
KelSolaar/Umbra | umbra/components/factory/script_editor/models.py | https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/components/factory/script_editor/models.py#L938-L947 | def sort_languages(self, order=Qt.AscendingOrder):
"""
Sorts the Model languages.
:param order: Order. ( Qt.SortOrder )
"""
self.beginResetModel()
self.__languages = sorted(self.__languages, key=lambda x: (x.name), reverse=order)
self.endResetModel() | [
"def",
"sort_languages",
"(",
"self",
",",
"order",
"=",
"Qt",
".",
"AscendingOrder",
")",
":",
"self",
".",
"beginResetModel",
"(",
")",
"self",
".",
"__languages",
"=",
"sorted",
"(",
"self",
".",
"__languages",
",",
"key",
"=",
"lambda",
"x",
":",
"... | Sorts the Model languages.
:param order: Order. ( Qt.SortOrder ) | [
"Sorts",
"the",
"Model",
"languages",
"."
] | python | train | 29.9 |
TurboGears/tgext.admin | tgext/admin/controller.py | https://github.com/TurboGears/tgext.admin/blob/7b0cf2cb2894d44840f3c46fb1dd6e5efccc2736/tgext/admin/controller.py#L105-L135 | def make_controller(cls, config, session, left_menu_items=None):
"""New CRUD controllers using the admin configuration can be created using this."""
m = config.model
Controller = config.defaultCrudRestController
class ModelController(Controller):
model = m
... | [
"def",
"make_controller",
"(",
"cls",
",",
"config",
",",
"session",
",",
"left_menu_items",
"=",
"None",
")",
":",
"m",
"=",
"config",
".",
"model",
"Controller",
"=",
"config",
".",
"defaultCrudRestController",
"class",
"ModelController",
"(",
"Controller",
... | New CRUD controllers using the admin configuration can be created using this. | [
"New",
"CRUD",
"controllers",
"using",
"the",
"admin",
"configuration",
"can",
"be",
"created",
"using",
"this",
"."
] | python | train | 47.451613 |
openstack/networking-hyperv | networking_hyperv/neutron/agent/layer2.py | https://github.com/openstack/networking-hyperv/blob/7a89306ab0586c95b99debb44d898f70834508b9/networking_hyperv/neutron/agent/layer2.py#L380-L387 | def _process_removed_port(self, device):
"""Process the removed ports."""
LOG.debug("Trying to remove the port %r", device)
self._update_port_status_cache(device, device_bound=False)
self._port_unbound(device, vnic_deleted=True)
LOG.debug("The port was successfully removed.")
... | [
"def",
"_process_removed_port",
"(",
"self",
",",
"device",
")",
":",
"LOG",
".",
"debug",
"(",
"\"Trying to remove the port %r\"",
",",
"device",
")",
"self",
".",
"_update_port_status_cache",
"(",
"device",
",",
"device_bound",
"=",
"False",
")",
"self",
".",
... | Process the removed ports. | [
"Process",
"the",
"removed",
"ports",
"."
] | python | train | 44.25 |
HazyResearch/metal | synthetic/generate.py | https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/synthetic/generate.py#L107-L118 | def _generate_edges(self, edge_prob):
"""Generate a random tree-structured dependency graph based on a
specified edge probability.
Also create helper data struct mapping child -> parent.
"""
self.E, self.parent = [], {}
for i in range(self.m):
if random() < e... | [
"def",
"_generate_edges",
"(",
"self",
",",
"edge_prob",
")",
":",
"self",
".",
"E",
",",
"self",
".",
"parent",
"=",
"[",
"]",
",",
"{",
"}",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"m",
")",
":",
"if",
"random",
"(",
")",
"<",
"edge_prob... | Generate a random tree-structured dependency graph based on a
specified edge probability.
Also create helper data struct mapping child -> parent. | [
"Generate",
"a",
"random",
"tree",
"-",
"structured",
"dependency",
"graph",
"based",
"on",
"a",
"specified",
"edge",
"probability",
"."
] | python | train | 36.416667 |
DataBiosphere/toil | src/toil/wdl/wdl_functions.py | https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/wdl/wdl_functions.py#L372-L402 | def parse_memory(memory):
"""
Parses a string representing memory and returns
an integer # of bytes.
:param memory:
:return:
"""
memory = str(memory)
if 'None' in memory:
return 2147483648 # toil's default
try:
import re
raw_mem_split = re.split('([a-zA-Z]+)'... | [
"def",
"parse_memory",
"(",
"memory",
")",
":",
"memory",
"=",
"str",
"(",
"memory",
")",
"if",
"'None'",
"in",
"memory",
":",
"return",
"2147483648",
"# toil's default",
"try",
":",
"import",
"re",
"raw_mem_split",
"=",
"re",
".",
"split",
"(",
"'([a-zA-Z... | Parses a string representing memory and returns
an integer # of bytes.
:param memory:
:return: | [
"Parses",
"a",
"string",
"representing",
"memory",
"and",
"returns",
"an",
"integer",
"#",
"of",
"bytes",
"."
] | python | train | 24.806452 |
mwouts/jupytext | jupytext/formats.py | https://github.com/mwouts/jupytext/blob/eb7d6aee889f80ad779cfc53441c648f0db9246d/jupytext/formats.py#L517-L538 | def validate_one_format(jupytext_format):
"""Validate extension and options for the given format"""
if not isinstance(jupytext_format, dict):
raise JupytextFormatError('Jupytext format should be a dictionary')
for key in jupytext_format:
if key not in _VALID_FORMAT_INFO + _VALID_FORMAT_OPTI... | [
"def",
"validate_one_format",
"(",
"jupytext_format",
")",
":",
"if",
"not",
"isinstance",
"(",
"jupytext_format",
",",
"dict",
")",
":",
"raise",
"JupytextFormatError",
"(",
"'Jupytext format should be a dictionary'",
")",
"for",
"key",
"in",
"jupytext_format",
":",
... | Validate extension and options for the given format | [
"Validate",
"extension",
"and",
"options",
"for",
"the",
"given",
"format"
] | python | train | 49.909091 |
mikedh/trimesh | trimesh/voxel.py | https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/voxel.py#L335-L357 | def as_boxes(self, solid=False):
"""
A rough Trimesh representation of the voxels with a box
for each filled voxel.
Parameters
-----------
solid: bool, if True return boxes for sparse_solid
Returns
---------
mesh: Trimesh object made up of one bo... | [
"def",
"as_boxes",
"(",
"self",
",",
"solid",
"=",
"False",
")",
":",
"if",
"solid",
":",
"filled",
"=",
"self",
".",
"sparse_solid",
"else",
":",
"filled",
"=",
"self",
".",
"sparse_surface",
"# center points of voxels",
"centers",
"=",
"indices_to_points",
... | A rough Trimesh representation of the voxels with a box
for each filled voxel.
Parameters
-----------
solid: bool, if True return boxes for sparse_solid
Returns
---------
mesh: Trimesh object made up of one box per filled cell. | [
"A",
"rough",
"Trimesh",
"representation",
"of",
"the",
"voxels",
"with",
"a",
"box",
"for",
"each",
"filled",
"voxel",
"."
] | python | train | 31.086957 |
inveniosoftware/invenio-communities | invenio_communities/forms.py | https://github.com/inveniosoftware/invenio-communities/blob/5c4de6783724d276ae1b6dd13a399a9e22fadc7a/invenio_communities/forms.py#L54-L58 | def data(self):
"""Form data."""
d = super(CommunityForm, self).data
d.pop('csrf_token', None)
return d | [
"def",
"data",
"(",
"self",
")",
":",
"d",
"=",
"super",
"(",
"CommunityForm",
",",
"self",
")",
".",
"data",
"d",
".",
"pop",
"(",
"'csrf_token'",
",",
"None",
")",
"return",
"d"
] | Form data. | [
"Form",
"data",
"."
] | python | train | 26.2 |
nickmckay/LiPD-utilities | Python/lipd/noaa_lpd.py | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/noaa_lpd.py#L647-L658 | def __str_cleanup(line):
"""
Remove the unnecessary characters in the line that we don't want
:param str line:
:return str:
"""
if '#' in line:
line = line.replace("#", "")
line = line.strip()
if '-----------' in line:
line = ''... | [
"def",
"__str_cleanup",
"(",
"line",
")",
":",
"if",
"'#'",
"in",
"line",
":",
"line",
"=",
"line",
".",
"replace",
"(",
"\"#\"",
",",
"\"\"",
")",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"'-----------'",
"in",
"line",
":",
"line",
"=",
... | Remove the unnecessary characters in the line that we don't want
:param str line:
:return str: | [
"Remove",
"the",
"unnecessary",
"characters",
"in",
"the",
"line",
"that",
"we",
"don",
"t",
"want",
":",
"param",
"str",
"line",
":",
":",
"return",
"str",
":"
] | python | train | 27.416667 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.