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 |
|---|---|---|---|---|---|---|---|---|---|
ionelmc/python-matrix | src/matrix/__init__.py | https://github.com/ionelmc/python-matrix/blob/e1a63879a6c94c37c3883386f1d86eb7c2179a5b/src/matrix/__init__.py#L131-L156 | def from_config(config):
"""
Generate a matrix from a configuration dictionary.
"""
matrix = {}
variables = config.keys()
for entries in product(*config.values()):
combination = dict(zip(variables, entries))
include = True
for value in combination.values():
fo... | [
"def",
"from_config",
"(",
"config",
")",
":",
"matrix",
"=",
"{",
"}",
"variables",
"=",
"config",
".",
"keys",
"(",
")",
"for",
"entries",
"in",
"product",
"(",
"*",
"config",
".",
"values",
"(",
")",
")",
":",
"combination",
"=",
"dict",
"(",
"z... | Generate a matrix from a configuration dictionary. | [
"Generate",
"a",
"matrix",
"from",
"a",
"configuration",
"dictionary",
"."
] | python | train | 39.115385 |
jupyter/jupyter-drive | jupyterdrive/mixednbmanager.py | https://github.com/jupyter/jupyter-drive/blob/545813377cb901235e8ea81f83b0ac7755dbd7a9/jupyterdrive/mixednbmanager.py#L186-L208 | def path_dispatch_rename(rename_like_method):
"""
decorator for rename-like function, that need dispatch on 2 arguments
"""
def _wrapper_method(self, old_path, new_path):
old_path, _old_path, old_sentinel = _split_path(old_path);
new_path, _new_path, new_sentine... | [
"def",
"path_dispatch_rename",
"(",
"rename_like_method",
")",
":",
"def",
"_wrapper_method",
"(",
"self",
",",
"old_path",
",",
"new_path",
")",
":",
"old_path",
",",
"_old_path",
",",
"old_sentinel",
"=",
"_split_path",
"(",
"old_path",
")",
"new_path",
",",
... | decorator for rename-like function, that need dispatch on 2 arguments | [
"decorator",
"for",
"rename",
"-",
"like",
"function",
"that",
"need",
"dispatch",
"on",
"2",
"arguments"
] | python | train | 39.391304 |
worstcase/blockade | blockade/net.py | https://github.com/worstcase/blockade/blob/3dc6ad803f0b0d56586dec9542a6a06aa06cf569/blockade/net.py#L235-L251 | def insert_rule(self, chain, src=None, dest=None, target=None):
"""Insert a new rule in the chain
"""
if not chain:
raise ValueError("Invalid chain")
if not target:
raise ValueError("Invalid target")
if not (src or dest):
raise ValueError("Need... | [
"def",
"insert_rule",
"(",
"self",
",",
"chain",
",",
"src",
"=",
"None",
",",
"dest",
"=",
"None",
",",
"target",
"=",
"None",
")",
":",
"if",
"not",
"chain",
":",
"raise",
"ValueError",
"(",
"\"Invalid chain\"",
")",
"if",
"not",
"target",
":",
"ra... | Insert a new rule in the chain | [
"Insert",
"a",
"new",
"rule",
"in",
"the",
"chain"
] | python | valid | 29.941176 |
watson-developer-cloud/python-sdk | ibm_watson/discovery_v1.py | https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/discovery_v1.py#L6699-L6704 | def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'collections') and self.collections is not None:
_dict['collections'] = [x._to_dict() for x in self.collections]
return _dict | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'collections'",
")",
"and",
"self",
".",
"collections",
"is",
"not",
"None",
":",
"_dict",
"[",
"'collections'",
"]",
"=",
"[",
"x",
".",
"_to_dict"... | Return a json dictionary representing this model. | [
"Return",
"a",
"json",
"dictionary",
"representing",
"this",
"model",
"."
] | python | train | 44.666667 |
basecrm/basecrm-python | basecrm/services.py | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L105-L121 | def destroy(self, deal_id, contact_id) :
"""
Remove an associated contact
Remove a deal's associated contact
If a deal with the supplied unique identifier does not exist, it returns an error
This operation cannot be undone
:calls: ``delete /deals/{deal_id}/associated_co... | [
"def",
"destroy",
"(",
"self",
",",
"deal_id",
",",
"contact_id",
")",
":",
"status_code",
",",
"_",
",",
"_",
"=",
"self",
".",
"http_client",
".",
"delete",
"(",
"\"/deals/{deal_id}/associated_contacts/{contact_id}\"",
".",
"format",
"(",
"deal_id",
"=",
"de... | Remove an associated contact
Remove a deal's associated contact
If a deal with the supplied unique identifier does not exist, it returns an error
This operation cannot be undone
:calls: ``delete /deals/{deal_id}/associated_contacts/{contact_id}``
:param int deal_id: Unique iden... | [
"Remove",
"an",
"associated",
"contact"
] | python | train | 42.058824 |
linkedin/shiv | src/shiv/cli.py | https://github.com/linkedin/shiv/blob/6bda78676170b35d0877f67b71095c39ce41a74a/src/shiv/cli.py#L128-L204 | def main(
output_file: str,
entry_point: Optional[str],
console_script: Optional[str],
python: Optional[str],
site_packages: Optional[str],
compressed: bool,
compile_pyc: bool,
extend_pythonpath: bool,
pip_args: List[str],
) -> None:
"""
Shiv is a command line utility for bui... | [
"def",
"main",
"(",
"output_file",
":",
"str",
",",
"entry_point",
":",
"Optional",
"[",
"str",
"]",
",",
"console_script",
":",
"Optional",
"[",
"str",
"]",
",",
"python",
":",
"Optional",
"[",
"str",
"]",
",",
"site_packages",
":",
"Optional",
"[",
"... | Shiv is a command line utility for building fully self-contained Python zipapps
as outlined in PEP 441, but with all their dependencies included! | [
"Shiv",
"is",
"a",
"command",
"line",
"utility",
"for",
"building",
"fully",
"self",
"-",
"contained",
"Python",
"zipapps",
"as",
"outlined",
"in",
"PEP",
"441",
"but",
"with",
"all",
"their",
"dependencies",
"included!"
] | python | train | 32.779221 |
jaraco/jaraco.windows | jaraco/windows/dpapi.py | https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/dpapi.py#L54-L57 | def get_data(self):
"Get the data for this blob"
array = ctypes.POINTER(ctypes.c_char * len(self))
return ctypes.cast(self.data, array).contents.raw | [
"def",
"get_data",
"(",
"self",
")",
":",
"array",
"=",
"ctypes",
".",
"POINTER",
"(",
"ctypes",
".",
"c_char",
"*",
"len",
"(",
"self",
")",
")",
"return",
"ctypes",
".",
"cast",
"(",
"self",
".",
"data",
",",
"array",
")",
".",
"contents",
".",
... | Get the data for this blob | [
"Get",
"the",
"data",
"for",
"this",
"blob"
] | python | train | 37.75 |
Diviyan-Kalainathan/CausalDiscoveryToolbox | cdt/utils/Settings.py | https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/utils/Settings.py#L95-L132 | def get_default(self, *args, **kwargs):
"""Get the default parameters as defined in the Settings instance.
This function proceeds to seamlessly retrieve the argument to pass
through, depending on either it was overidden or not: If no argument
was overridden in a function of the toolbox,... | [
"def",
"get_default",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"retrieve_param",
"(",
"i",
")",
":",
"try",
":",
"return",
"self",
".",
"__getattribute__",
"(",
"i",
")",
"except",
"AttributeError",
":",
"if",
"i",
"==... | Get the default parameters as defined in the Settings instance.
This function proceeds to seamlessly retrieve the argument to pass
through, depending on either it was overidden or not: If no argument
was overridden in a function of the toolbox, the default argument will
be set to ``None... | [
"Get",
"the",
"default",
"parameters",
"as",
"defined",
"in",
"the",
"Settings",
"instance",
"."
] | python | valid | 43.947368 |
pydata/xarray | xarray/core/dataset.py | https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/core/dataset.py#L3202-L3250 | def apply(self, func, keep_attrs=None, args=(), **kwargs):
"""Apply a function over the data variables in this dataset.
Parameters
----------
func : function
Function which can be called in the form `func(x, *args, **kwargs)`
to transform each DataArray `x` in th... | [
"def",
"apply",
"(",
"self",
",",
"func",
",",
"keep_attrs",
"=",
"None",
",",
"args",
"=",
"(",
")",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa",
"variables",
"=",
"OrderedDict",
"(",
"(",
"k",
",",
"maybe_wrap_array",
"(",
"v",
",",
"func",
"(",
... | Apply a function over the data variables in this dataset.
Parameters
----------
func : function
Function which can be called in the form `func(x, *args, **kwargs)`
to transform each DataArray `x` in this dataset into another
DataArray.
keep_attrs : bo... | [
"Apply",
"a",
"function",
"over",
"the",
"data",
"variables",
"in",
"this",
"dataset",
"."
] | python | train | 39.816327 |
LionelR/pyair | pyair/xair.py | https://github.com/LionelR/pyair/blob/467e8a843ca9f882f8bb2958805b7293591996ad/pyair/xair.py#L519-L570 | def get_manuelles(self, site, code_parametre, debut, fin, court=False):
"""
Recupération des mesures manuelles (labo) pour un site
site: numéro du site (voir fonction liste_sites_prelevement)
code_parametre: code ISO du paramètre à rechercher (C6H6=V4)
debut: date de début du pr... | [
"def",
"get_manuelles",
"(",
"self",
",",
"site",
",",
"code_parametre",
",",
"debut",
",",
"fin",
",",
"court",
"=",
"False",
")",
":",
"condition",
"=",
"\"WHERE MESLA.NOPOL='%s' \"",
"%",
"code_parametre",
"condition",
"+=",
"\"AND SITMETH.NSIT=%s \"",
"%",
"... | Recupération des mesures manuelles (labo) pour un site
site: numéro du site (voir fonction liste_sites_prelevement)
code_parametre: code ISO du paramètre à rechercher (C6H6=V4)
debut: date de début du premier prélèvement
fin: date de fin du dernier prélèvement
court: Renvoie un ... | [
"Recupération",
"des",
"mesures",
"manuelles",
"(",
"labo",
")",
"pour",
"un",
"site"
] | python | valid | 48.769231 |
log2timeline/plaso | plaso/parsers/winreg_plugins/task_scheduler.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/parsers/winreg_plugins/task_scheduler.py#L73-L181 | def ExtractEvents(self, parser_mediator, registry_key, **kwargs):
"""Extracts events from a Windows Registry key.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
registry_key (dfwinreg.WinRegistryKey): Windows ... | [
"def",
"ExtractEvents",
"(",
"self",
",",
"parser_mediator",
",",
"registry_key",
",",
"*",
"*",
"kwargs",
")",
":",
"dynamic_info_size_error_reported",
"=",
"False",
"tasks_key",
"=",
"registry_key",
".",
"GetSubkeyByName",
"(",
"'Tasks'",
")",
"tree_key",
"=",
... | Extracts events from a Windows Registry key.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
registry_key (dfwinreg.WinRegistryKey): Windows Registry key. | [
"Extracts",
"events",
"from",
"a",
"Windows",
"Registry",
"key",
"."
] | python | train | 40.541284 |
bird-house/twitcher | twitcher/__init__.py | https://github.com/bird-house/twitcher/blob/e6a36b3aeeacf44eec537434b0fb87c09ab54b5f/twitcher/__init__.py#L4-L24 | def main(global_config, **settings):
"""
This function returns a Pyramid WSGI application.
"""
from pyramid.config import Configurator
config = Configurator(settings=settings)
# include twitcher components
config.include('twitcher.config')
config.include('twitcher.frontpage')
confi... | [
"def",
"main",
"(",
"global_config",
",",
"*",
"*",
"settings",
")",
":",
"from",
"pyramid",
".",
"config",
"import",
"Configurator",
"config",
"=",
"Configurator",
"(",
"settings",
"=",
"settings",
")",
"# include twitcher components",
"config",
".",
"include",... | This function returns a Pyramid WSGI application. | [
"This",
"function",
"returns",
"a",
"Pyramid",
"WSGI",
"application",
"."
] | python | valid | 27.142857 |
rhgrant10/Groupy | groupy/api/bots.py | https://github.com/rhgrant10/Groupy/blob/ffd8cac57586fa1c218e3b4bfaa531142c3be766/groupy/api/bots.py#L88-L97 | def post(self, text, attachments=None):
"""Post a message as the bot.
:param str text: the text of the message
:param attachments: a list of attachments
:type attachments: :class:`list`
:return: ``True`` if successful
:rtype: bool
"""
return self.manager.... | [
"def",
"post",
"(",
"self",
",",
"text",
",",
"attachments",
"=",
"None",
")",
":",
"return",
"self",
".",
"manager",
".",
"post",
"(",
"self",
".",
"bot_id",
",",
"text",
",",
"attachments",
")"
] | Post a message as the bot.
:param str text: the text of the message
:param attachments: a list of attachments
:type attachments: :class:`list`
:return: ``True`` if successful
:rtype: bool | [
"Post",
"a",
"message",
"as",
"the",
"bot",
"."
] | python | train | 34.7 |
Brazelton-Lab/bio_utils | bio_utils/blast_tools/filter_b6_evalue.py | https://github.com/Brazelton-Lab/bio_utils/blob/5a7ddf13ee0bf4baaaeb6b2b99e01bf74aa132b7/bio_utils/blast_tools/filter_b6_evalue.py#L73-L77 | def main():
"""Open B6/M8 file, filter entries by E-Value, and write said entries"""
for entry in b6_evalue_filter(args.b6, args.e_value):
args.output.write(entry.write()) | [
"def",
"main",
"(",
")",
":",
"for",
"entry",
"in",
"b6_evalue_filter",
"(",
"args",
".",
"b6",
",",
"args",
".",
"e_value",
")",
":",
"args",
".",
"output",
".",
"write",
"(",
"entry",
".",
"write",
"(",
")",
")"
] | Open B6/M8 file, filter entries by E-Value, and write said entries | [
"Open",
"B6",
"/",
"M8",
"file",
"filter",
"entries",
"by",
"E",
"-",
"Value",
"and",
"write",
"said",
"entries"
] | python | train | 36.8 |
pypa/pipenv | pipenv/environment.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/environment.py#L481-L489 | def is_installed(self, pkgname):
"""Given a package name, returns whether it is installed in the environment
:param str pkgname: The name of a package
:return: Whether the supplied package is installed in the environment
:rtype: bool
"""
return any(d for d in self.get_d... | [
"def",
"is_installed",
"(",
"self",
",",
"pkgname",
")",
":",
"return",
"any",
"(",
"d",
"for",
"d",
"in",
"self",
".",
"get_distributions",
"(",
")",
"if",
"d",
".",
"project_name",
"==",
"pkgname",
")"
] | Given a package name, returns whether it is installed in the environment
:param str pkgname: The name of a package
:return: Whether the supplied package is installed in the environment
:rtype: bool | [
"Given",
"a",
"package",
"name",
"returns",
"whether",
"it",
"is",
"installed",
"in",
"the",
"environment"
] | python | train | 39.555556 |
materialsproject/pymatgen | pymatgen/core/spectrum.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/core/spectrum.py#L70-L87 | def normalize(self, mode="max", value=1):
"""
Normalize the spectrum with respect to the sum of intensity
Args:
mode (str): Normalization mode. Supported modes are "max" (set the
max y value to value, e.g., in XRD patterns), "sum" (set the
sum of y to... | [
"def",
"normalize",
"(",
"self",
",",
"mode",
"=",
"\"max\"",
",",
"value",
"=",
"1",
")",
":",
"if",
"mode",
".",
"lower",
"(",
")",
"==",
"\"sum\"",
":",
"factor",
"=",
"np",
".",
"sum",
"(",
"self",
".",
"y",
",",
"axis",
"=",
"0",
")",
"e... | Normalize the spectrum with respect to the sum of intensity
Args:
mode (str): Normalization mode. Supported modes are "max" (set the
max y value to value, e.g., in XRD patterns), "sum" (set the
sum of y to a value, i.e., like a probability density).
value... | [
"Normalize",
"the",
"spectrum",
"with",
"respect",
"to",
"the",
"sum",
"of",
"intensity"
] | python | train | 39.111111 |
poppy-project/pypot | pypot/vrep/remoteApiBindings/vrep.py | https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/vrep/remoteApiBindings/vrep.py#L857-L872 | def simxCopyPasteObjects(clientID, objectHandles, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
c_objectHandles = (ct.c_int*len(objectHandles))(*objectHandles)
c_objectHandles = ct.cast(c_objectHandles,ct.POINTER(ct.c_int)) # IronPytho... | [
"def",
"simxCopyPasteObjects",
"(",
"clientID",
",",
"objectHandles",
",",
"operationMode",
")",
":",
"c_objectHandles",
"=",
"(",
"ct",
".",
"c_int",
"*",
"len",
"(",
"objectHandles",
")",
")",
"(",
"*",
"objectHandles",
")",
"c_objectHandles",
"=",
"ct",
"... | Please have a look at the function description/documentation in the V-REP user manual | [
"Please",
"have",
"a",
"look",
"at",
"the",
"function",
"description",
"/",
"documentation",
"in",
"the",
"V",
"-",
"REP",
"user",
"manual"
] | python | train | 43.3125 |
pycontribs/pyrax | pyrax/clouddns.py | https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/clouddns.py#L1209-L1213 | def list_subdomains(self, domain, limit=None, offset=None):
"""
Returns a list of all subdomains for the specified domain.
"""
return domain.list_subdomains(limit=limit, offset=offset) | [
"def",
"list_subdomains",
"(",
"self",
",",
"domain",
",",
"limit",
"=",
"None",
",",
"offset",
"=",
"None",
")",
":",
"return",
"domain",
".",
"list_subdomains",
"(",
"limit",
"=",
"limit",
",",
"offset",
"=",
"offset",
")"
] | Returns a list of all subdomains for the specified domain. | [
"Returns",
"a",
"list",
"of",
"all",
"subdomains",
"for",
"the",
"specified",
"domain",
"."
] | python | train | 42.4 |
tensorpack/tensorpack | tensorpack/utils/viz.py | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/viz.py#L265-L322 | def dump_dataflow_images(df, index=0, batched=True,
number=1000, output_dir=None,
scale=1, resize=None, viz=None,
flipRGB=False):
"""
Dump or visualize images of a :class:`DataFlow`.
Args:
df (DataFlow): the DataFlow.
... | [
"def",
"dump_dataflow_images",
"(",
"df",
",",
"index",
"=",
"0",
",",
"batched",
"=",
"True",
",",
"number",
"=",
"1000",
",",
"output_dir",
"=",
"None",
",",
"scale",
"=",
"1",
",",
"resize",
"=",
"None",
",",
"viz",
"=",
"None",
",",
"flipRGB",
... | Dump or visualize images of a :class:`DataFlow`.
Args:
df (DataFlow): the DataFlow.
index (int): the index of the image component.
batched (bool): whether the component contains batched images (NHW or
NHWC) or not (HW or HWC).
number (int): how many datapoint to take fro... | [
"Dump",
"or",
"visualize",
"images",
"of",
"a",
":",
"class",
":",
"DataFlow",
"."
] | python | train | 37.862069 |
PyCQA/pydocstyle | src/pydocstyle/violations.py | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/violations.py#L153-L168 | def to_rst(cls) -> str:
"""Output the registry as reStructuredText, for documentation."""
sep_line = '+' + 6 * '-' + '+' + '-' * 71 + '+\n'
blank_line = '|' + 78 * ' ' + '|\n'
table = ''
for group in cls.groups:
table += sep_line
table += blank_line
... | [
"def",
"to_rst",
"(",
"cls",
")",
"->",
"str",
":",
"sep_line",
"=",
"'+'",
"+",
"6",
"*",
"'-'",
"+",
"'+'",
"+",
"'-'",
"*",
"71",
"+",
"'+\\n'",
"blank_line",
"=",
"'|'",
"+",
"78",
"*",
"' '",
"+",
"'|\\n'",
"table",
"=",
"''",
"for",
"grou... | Output the registry as reStructuredText, for documentation. | [
"Output",
"the",
"registry",
"as",
"reStructuredText",
"for",
"documentation",
"."
] | python | train | 40.5 |
unixsurfer/anycast_healthchecker | anycast_healthchecker/servicecheck.py | https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/servicecheck.py#L88-L123 | def _run_check(self):
"""Execute a check command.
Returns:
True if the exit code of the command is 0 otherwise False.
"""
cmd = shlex.split(self.config['check_cmd'])
self.log.info("running %s", ' '.join(cmd))
proc = subprocess.Popen(cmd, stdout=subprocess.PI... | [
"def",
"_run_check",
"(",
"self",
")",
":",
"cmd",
"=",
"shlex",
".",
"split",
"(",
"self",
".",
"config",
"[",
"'check_cmd'",
"]",
")",
"self",
".",
"log",
".",
"info",
"(",
"\"running %s\"",
",",
"' '",
".",
"join",
"(",
"cmd",
")",
")",
"proc",
... | Execute a check command.
Returns:
True if the exit code of the command is 0 otherwise False. | [
"Execute",
"a",
"check",
"command",
"."
] | python | train | 36.138889 |
SecurityInnovation/PGPy | pgpy/pgp.py | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L1287-L1295 | def is_unlocked(self):
"""``False`` if this is a private key that is protected with a passphrase and has not yet been unlocked, otherwise ``True``"""
if self.is_public:
return True
if not self.is_protected:
return True
return self._key.unlocked | [
"def",
"is_unlocked",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_public",
":",
"return",
"True",
"if",
"not",
"self",
".",
"is_protected",
":",
"return",
"True",
"return",
"self",
".",
"_key",
".",
"unlocked"
] | ``False`` if this is a private key that is protected with a passphrase and has not yet been unlocked, otherwise ``True`` | [
"False",
"if",
"this",
"is",
"a",
"private",
"key",
"that",
"is",
"protected",
"with",
"a",
"passphrase",
"and",
"has",
"not",
"yet",
"been",
"unlocked",
"otherwise",
"True"
] | python | train | 32.666667 |
bearyinnovative/bearychat.py | bearychat/rtm_client_service.py | https://github.com/bearyinnovative/bearychat.py/blob/6c7af2d215c2ff7135bb5af66ca333d0ea1089fd/bearychat/rtm_client_service.py#L33-L48 | def members(self):
"""Gets members of current team
Returns:
list of User
Throws:
RTMServiceError when request failed
"""
resp = self._rtm_client.get('v1/current_team.members?all=true')
if resp.is_fail():
raise RTMServiceError(
... | [
"def",
"members",
"(",
"self",
")",
":",
"resp",
"=",
"self",
".",
"_rtm_client",
".",
"get",
"(",
"'v1/current_team.members?all=true'",
")",
"if",
"resp",
".",
"is_fail",
"(",
")",
":",
"raise",
"RTMServiceError",
"(",
"'Failed to get members of current team'",
... | Gets members of current team
Returns:
list of User
Throws:
RTMServiceError when request failed | [
"Gets",
"members",
"of",
"current",
"team"
] | python | train | 26.5 |
wbond/oscrypto | oscrypto/_win/symmetric.py | https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_win/symmetric.py#L738-L796 | def _encrypt(cipher, key, data, iv, padding):
"""
Encrypts plaintext
:param cipher:
A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key",
"rc2", "rc4"
:param key:
The encryption key - a byte string 5-16 bytes long
:param data:
The plaintext - a byte... | [
"def",
"_encrypt",
"(",
"cipher",
",",
"key",
",",
"data",
",",
"iv",
",",
"padding",
")",
":",
"if",
"not",
"isinstance",
"(",
"key",
",",
"byte_cls",
")",
":",
"raise",
"TypeError",
"(",
"pretty_message",
"(",
"'''\n key must be a byte string, not... | Encrypts plaintext
:param cipher:
A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key",
"rc2", "rc4"
:param key:
The encryption key - a byte string 5-16 bytes long
:param data:
The plaintext - a byte string
:param iv:
The initialization vector ... | [
"Encrypts",
"plaintext"
] | python | valid | 26.779661 |
wummel/linkchecker | linkcheck/colorama.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/colorama.py#L93-L96 | def SetConsoleTextAttribute(stream_id, attrs):
"""Set a console text attribute."""
handle = handles[stream_id]
return windll.kernel32.SetConsoleTextAttribute(handle, attrs) | [
"def",
"SetConsoleTextAttribute",
"(",
"stream_id",
",",
"attrs",
")",
":",
"handle",
"=",
"handles",
"[",
"stream_id",
"]",
"return",
"windll",
".",
"kernel32",
".",
"SetConsoleTextAttribute",
"(",
"handle",
",",
"attrs",
")"
] | Set a console text attribute. | [
"Set",
"a",
"console",
"text",
"attribute",
"."
] | python | train | 45.25 |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/utils/_process_posix.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/_process_posix.py#L119-L187 | def system(self, cmd):
"""Execute a command in a subshell.
Parameters
----------
cmd : str
A command to be executed in the system shell.
Returns
-------
int : child's exitstatus
"""
# Get likely encoding for the output.
enc = DE... | [
"def",
"system",
"(",
"self",
",",
"cmd",
")",
":",
"# Get likely encoding for the output.",
"enc",
"=",
"DEFAULT_ENCODING",
"# Patterns to match on the output, for pexpect. We read input and",
"# allow either a short timeout or EOF",
"patterns",
"=",
"[",
"pexpect",
".",
"TIM... | Execute a command in a subshell.
Parameters
----------
cmd : str
A command to be executed in the system shell.
Returns
-------
int : child's exitstatus | [
"Execute",
"a",
"command",
"in",
"a",
"subshell",
"."
] | python | test | 44.478261 |
Hackerfleet/hfos | hfos/ui/auth.py | https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/ui/auth.py#L190-L275 | def _handle_login(self, event):
"""Manual password based login"""
# TODO: Refactor to simplify
self.log("Auth request for ", event.username, 'client:',
event.clientuuid)
# TODO: Define the requirements for secure passwords etc.
# They're also required in the E... | [
"def",
"_handle_login",
"(",
"self",
",",
"event",
")",
":",
"# TODO: Refactor to simplify",
"self",
".",
"log",
"(",
"\"Auth request for \"",
",",
"event",
".",
"username",
",",
"'client:'",
",",
"event",
".",
"clientuuid",
")",
"# TODO: Define the requirements for... | Manual password based login | [
"Manual",
"password",
"based",
"login"
] | python | train | 36.5 |
piotr-rusin/spam-lists | spam_lists/host_collections.py | https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/host_collections.py#L64-L74 | def add(self, host_value):
"""Add the given value to the collection.
:param host: an ip address or a hostname
:raises InvalidHostError: raised when the given value
is not a valid ip address nor a hostname
"""
host_obj = self._host_factory(host_value)
if self._get... | [
"def",
"add",
"(",
"self",
",",
"host_value",
")",
":",
"host_obj",
"=",
"self",
".",
"_host_factory",
"(",
"host_value",
")",
"if",
"self",
".",
"_get_match",
"(",
"host_obj",
")",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_add_new",
"(",
"hos... | Add the given value to the collection.
:param host: an ip address or a hostname
:raises InvalidHostError: raised when the given value
is not a valid ip address nor a hostname | [
"Add",
"the",
"given",
"value",
"to",
"the",
"collection",
"."
] | python | train | 35.454545 |
noxdafox/clipspy | clips/classes.py | https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/classes.py#L632-L634 | def instance_class(self):
"""Instance class."""
return Class(self._env, lib.EnvGetInstanceClass(self._env, self._ist)) | [
"def",
"instance_class",
"(",
"self",
")",
":",
"return",
"Class",
"(",
"self",
".",
"_env",
",",
"lib",
".",
"EnvGetInstanceClass",
"(",
"self",
".",
"_env",
",",
"self",
".",
"_ist",
")",
")"
] | Instance class. | [
"Instance",
"class",
"."
] | python | train | 44 |
saghul/evergreen | evergreen/futures/_base.py | https://github.com/saghul/evergreen/blob/22f22f45892f397c23c3e09e6ea1ad4c00b3add8/evergreen/futures/_base.py#L180-L223 | def as_completed(fs, timeout=None):
"""An iterator over the given futures that yields each as it completes.
Args:
fs: The sequence of Futures (possibly created by different Executors) to
iterate over.
timeout: The maximum number of seconds to wait. If None, then there
is... | [
"def",
"as_completed",
"(",
"fs",
",",
"timeout",
"=",
"None",
")",
":",
"with",
"_AcquireFutures",
"(",
"fs",
")",
":",
"finished",
"=",
"set",
"(",
"f",
"for",
"f",
"in",
"fs",
"if",
"f",
".",
"_state",
"in",
"[",
"CANCELLED_AND_NOTIFIED",
",",
"FI... | An iterator over the given futures that yields each as it completes.
Args:
fs: The sequence of Futures (possibly created by different Executors) to
iterate over.
timeout: The maximum number of seconds to wait. If None, then there
is no limit on the wait time.
Returns:
... | [
"An",
"iterator",
"over",
"the",
"given",
"futures",
"that",
"yields",
"each",
"as",
"it",
"completes",
"."
] | python | train | 33.136364 |
dshean/pygeotools | pygeotools/lib/warplib.py | https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/warplib.py#L416-L515 | def warp_multi(src_ds_list, res='first', extent='intersection', t_srs='first', r='cubic', warptype=memwarp, outdir=None, dst_ndv=None, verbose=True, debug=False):
"""This parses and checks inputs, then calls desired warp function with appropriate arguments for each input ds
Parameters
----------
sr... | [
"def",
"warp_multi",
"(",
"src_ds_list",
",",
"res",
"=",
"'first'",
",",
"extent",
"=",
"'intersection'",
",",
"t_srs",
"=",
"'first'",
",",
"r",
"=",
"'cubic'",
",",
"warptype",
"=",
"memwarp",
",",
"outdir",
"=",
"None",
",",
"dst_ndv",
"=",
"None",
... | This parses and checks inputs, then calls desired warp function with appropriate arguments for each input ds
Parameters
----------
src_ds_list : list of gdal.Dataset objects
List of original datasets to be warped
res : arbitrary type
Desired output resolution
extent : arbitrary ... | [
"This",
"parses",
"and",
"checks",
"inputs",
"then",
"calls",
"desired",
"warp",
"function",
"with",
"appropriate",
"arguments",
"for",
"each",
"input",
"ds",
"Parameters",
"----------",
"src_ds_list",
":",
"list",
"of",
"gdal",
".",
"Dataset",
"objects",
"List"... | python | train | 34.01 |
hellosign/hellosign-python-sdk | hellosign_sdk/hsclient.py | https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L1001-L1074 | def create_unclaimed_draft(self, test_mode=False, files=None, file_urls=None, draft_type=None, subject=None, message=None, signers=None, cc_email_addresses=None, signing_redirect_url=None, form_fields_per_document=None, metadata=None, use_preexisting_fields=False, allow_decline=False):
''' Creates a new Draft t... | [
"def",
"create_unclaimed_draft",
"(",
"self",
",",
"test_mode",
"=",
"False",
",",
"files",
"=",
"None",
",",
"file_urls",
"=",
"None",
",",
"draft_type",
"=",
"None",
",",
"subject",
"=",
"None",
",",
"message",
"=",
"None",
",",
"signers",
"=",
"None",... | Creates a new Draft that can be claimed using the claim URL
Creates a new Draft that can be claimed using the claim URL. The first
authenticated user to access the URL will claim the Draft and will be
shown either the "Sign and send" or the "Request signature" page with
the Draft loaded... | [
"Creates",
"a",
"new",
"Draft",
"that",
"can",
"be",
"claimed",
"using",
"the",
"claim",
"URL"
] | python | train | 53.810811 |
rackerlabs/rackspace-python-neutronclient | neutronclient/v2_0/client.py | https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/v2_0/client.py#L583-L585 | def update_ext(self, path, id, body=None):
"""Client extension hook for update."""
return self.put(path % id, body=body) | [
"def",
"update_ext",
"(",
"self",
",",
"path",
",",
"id",
",",
"body",
"=",
"None",
")",
":",
"return",
"self",
".",
"put",
"(",
"path",
"%",
"id",
",",
"body",
"=",
"body",
")"
] | Client extension hook for update. | [
"Client",
"extension",
"hook",
"for",
"update",
"."
] | python | train | 44.666667 |
theelous3/asks | asks/request_object.py | https://github.com/theelous3/asks/blob/ea522ea971ecb031d488a6301dc2718516cadcd6/asks/request_object.py#L462-L509 | async def _multipart(self, files_dict):
'''
Forms multipart requests from a dict with name, path k/vs. Name
does not have to be the actual file name.
Args:
files_dict (dict): A dict of `filename:filepath`s, to be sent
as multipart files.
Returns:
... | [
"async",
"def",
"_multipart",
"(",
"self",
",",
"files_dict",
")",
":",
"boundary",
"=",
"bytes",
"(",
"_BOUNDARY",
",",
"self",
".",
"encoding",
")",
"hder_format",
"=",
"'Content-Disposition: form-data; name=\"{}\"'",
"hder_format_io",
"=",
"'; filename=\"{}\"'",
... | Forms multipart requests from a dict with name, path k/vs. Name
does not have to be the actual file name.
Args:
files_dict (dict): A dict of `filename:filepath`s, to be sent
as multipart files.
Returns:
multip_pkg (str): The strings representation of the con... | [
"Forms",
"multipart",
"requests",
"from",
"a",
"dict",
"with",
"name",
"path",
"k",
"/",
"vs",
".",
"Name",
"does",
"not",
"have",
"to",
"be",
"the",
"actual",
"file",
"name",
"."
] | python | train | 37.75 |
openstack/networking-cisco | networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py#L1361-L1376 | def create_dcnm_out_part(self, tenant_id, fw_dict, is_fw_virt=False):
"""Create the DCNM OUT partition and update the result. """
res = fw_const.DCNM_OUT_PART_CREATE_SUCCESS
tenant_name = fw_dict.get('tenant_name')
ret = True
try:
self._create_out_partition(tenant_id,... | [
"def",
"create_dcnm_out_part",
"(",
"self",
",",
"tenant_id",
",",
"fw_dict",
",",
"is_fw_virt",
"=",
"False",
")",
":",
"res",
"=",
"fw_const",
".",
"DCNM_OUT_PART_CREATE_SUCCESS",
"tenant_name",
"=",
"fw_dict",
".",
"get",
"(",
"'tenant_name'",
")",
"ret",
"... | Create the DCNM OUT partition and update the result. | [
"Create",
"the",
"DCNM",
"OUT",
"partition",
"and",
"update",
"the",
"result",
"."
] | python | train | 45.875 |
materialsproject/pymatgen | pymatgen/core/surface.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/core/surface.py#L614-L637 | def symmetrically_add_atom(self, specie, point, coords_are_cartesian=False):
"""
Class method for adding a site at a specified point in a slab.
Will add the corresponding site on the other side of the
slab to maintain equivalent surfaces.
Arg:
specie (str): ... | [
"def",
"symmetrically_add_atom",
"(",
"self",
",",
"specie",
",",
"point",
",",
"coords_are_cartesian",
"=",
"False",
")",
":",
"# For now just use the species of the",
"# surface atom as the element to add",
"# Get the index of the corresponding site at the bottom",
"point2",
"=... | Class method for adding a site at a specified point in a slab.
Will add the corresponding site on the other side of the
slab to maintain equivalent surfaces.
Arg:
specie (str): The specie to add
point (coords): The coordinate of the site in the slab to add.
... | [
"Class",
"method",
"for",
"adding",
"a",
"site",
"at",
"a",
"specified",
"point",
"in",
"a",
"slab",
".",
"Will",
"add",
"the",
"corresponding",
"site",
"on",
"the",
"other",
"side",
"of",
"the",
"slab",
"to",
"maintain",
"equivalent",
"surfaces",
"."
] | python | train | 38.791667 |
JarryShaw/PyPCAPKit | src/protocols/internet/hip.py | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/internet/hip.py#L380-L418 | def _read_para_r1_counter(self, code, cbit, clen, *, desc, length, version):
"""Read HIP R1_COUNTER parameter.
Structure of HIP R1_COUNTER parameter [RFC 5201][RFC 7401]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 ... | [
"def",
"_read_para_r1_counter",
"(",
"self",
",",
"code",
",",
"cbit",
",",
"clen",
",",
"*",
",",
"desc",
",",
"length",
",",
"version",
")",
":",
"if",
"clen",
"!=",
"12",
":",
"raise",
"ProtocolError",
"(",
"f'HIPv{version}: [Parano {code}] invalid format'"... | Read HIP R1_COUNTER parameter.
Structure of HIP R1_COUNTER parameter [RFC 5201][RFC 7401]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-... | [
"Read",
"HIP",
"R1_COUNTER",
"parameter",
"."
] | python | train | 47.333333 |
mfcloud/python-zvm-sdk | zvmsdk/smtclient.py | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/smtclient.py#L261-L334 | def _parse_vswitch_inspect_data(self, rd_list):
""" Parse the Virtual_Network_Vswitch_Query_Byte_Stats data to get
inspect data.
"""
def _parse_value(data_list, idx, keyword, offset):
return idx + offset, data_list[idx].rpartition(keyword)[2].strip()
vsw_dict = {}
... | [
"def",
"_parse_vswitch_inspect_data",
"(",
"self",
",",
"rd_list",
")",
":",
"def",
"_parse_value",
"(",
"data_list",
",",
"idx",
",",
"keyword",
",",
"offset",
")",
":",
"return",
"idx",
"+",
"offset",
",",
"data_list",
"[",
"idx",
"]",
".",
"rpartition",... | Parse the Virtual_Network_Vswitch_Query_Byte_Stats data to get
inspect data. | [
"Parse",
"the",
"Virtual_Network_Vswitch_Query_Byte_Stats",
"data",
"to",
"get",
"inspect",
"data",
"."
] | python | train | 50.310811 |
PolicyStat/docx2html | docx2html/core.py | https://github.com/PolicyStat/docx2html/blob/2dc4afd1e3a3f2f0b357d0bff903eb58bcc94429/docx2html/core.py#L816-L882 | def _get_document_data(f, image_handler=None):
'''
``f`` is a ``ZipFile`` that is open
Extract out the document data, numbering data and the relationship data.
'''
if image_handler is None:
def image_handler(image_id, relationship_dict):
return relationship_dict.get(image_id)
... | [
"def",
"_get_document_data",
"(",
"f",
",",
"image_handler",
"=",
"None",
")",
":",
"if",
"image_handler",
"is",
"None",
":",
"def",
"image_handler",
"(",
"image_id",
",",
"relationship_dict",
")",
":",
"return",
"relationship_dict",
".",
"get",
"(",
"image_id... | ``f`` is a ``ZipFile`` that is open
Extract out the document data, numbering data and the relationship data. | [
"f",
"is",
"a",
"ZipFile",
"that",
"is",
"open",
"Extract",
"out",
"the",
"document",
"data",
"numbering",
"data",
"and",
"the",
"relationship",
"data",
"."
] | python | test | 37.238806 |
skyfielders/python-skyfield | skyfield/earthlib.py | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/earthlib.py#L166-L175 | def refraction(alt_degrees, temperature_C, pressure_mbar):
"""Given an observed altitude, return how much the image is refracted.
Zero refraction is returned both for objects very near the zenith,
as well as for objects more than one degree below the horizon.
"""
r = 0.016667 / tan((alt_degrees + ... | [
"def",
"refraction",
"(",
"alt_degrees",
",",
"temperature_C",
",",
"pressure_mbar",
")",
":",
"r",
"=",
"0.016667",
"/",
"tan",
"(",
"(",
"alt_degrees",
"+",
"7.31",
"/",
"(",
"alt_degrees",
"+",
"4.4",
")",
")",
"*",
"DEG2RAD",
")",
"d",
"=",
"r",
... | Given an observed altitude, return how much the image is refracted.
Zero refraction is returned both for objects very near the zenith,
as well as for objects more than one degree below the horizon. | [
"Given",
"an",
"observed",
"altitude",
"return",
"how",
"much",
"the",
"image",
"is",
"refracted",
"."
] | python | train | 48.2 |
a1ezzz/wasp-general | wasp_general/datetime.py | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/datetime.py#L42-L61 | def utc_datetime(dt=None, local_value=True):
""" Convert local datetime and/or datetime without timezone information to UTC datetime with timezone
information.
:param dt: local datetime to convert. If is None, then system datetime value is used
:param local_value: whether dt is a datetime in system timezone or UTC... | [
"def",
"utc_datetime",
"(",
"dt",
"=",
"None",
",",
"local_value",
"=",
"True",
")",
":",
"# TODO: rename local_value to local_tz or in_local_tz",
"if",
"dt",
"is",
"None",
":",
"return",
"datetime",
".",
"now",
"(",
"tz",
"=",
"timezone",
".",
"utc",
")",
"... | Convert local datetime and/or datetime without timezone information to UTC datetime with timezone
information.
:param dt: local datetime to convert. If is None, then system datetime value is used
:param local_value: whether dt is a datetime in system timezone or UTC datetime without timezone information
:return: d... | [
"Convert",
"local",
"datetime",
"and",
"/",
"or",
"datetime",
"without",
"timezone",
"information",
"to",
"UTC",
"datetime",
"with",
"timezone",
"information",
"."
] | python | train | 35.3 |
google/grumpy | third_party/stdlib/csv.py | https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/csv.py#L295-L397 | def _guess_delimiter(self, data, delimiters):
"""
The delimiter /should/ occur the same number of times on
each row. However, due to malformed data, it may not. We don't want
an all or nothing approach, so we allow for small variations in this
number.
1) build a table o... | [
"def",
"_guess_delimiter",
"(",
"self",
",",
"data",
",",
"delimiters",
")",
":",
"data",
"=",
"filter",
"(",
"None",
",",
"data",
".",
"split",
"(",
"'\\n'",
")",
")",
"ascii",
"=",
"[",
"chr",
"(",
"c",
")",
"for",
"c",
"in",
"range",
"(",
"127... | The delimiter /should/ occur the same number of times on
each row. However, due to malformed data, it may not. We don't want
an all or nothing approach, so we allow for small variations in this
number.
1) build a table of the frequency of each character on every line.
2) buil... | [
"The",
"delimiter",
"/",
"should",
"/",
"occur",
"the",
"same",
"number",
"of",
"times",
"on",
"each",
"row",
".",
"However",
"due",
"to",
"malformed",
"data",
"it",
"may",
"not",
".",
"We",
"don",
"t",
"want",
"an",
"all",
"or",
"nothing",
"approach",... | python | valid | 41.543689 |
allenai/allennlp | allennlp/nn/util.py | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L132-L169 | def sort_batch_by_length(tensor: torch.Tensor, sequence_lengths: torch.Tensor):
"""
Sort a batch first tensor by some specified lengths.
Parameters
----------
tensor : torch.FloatTensor, required.
A batch first Pytorch tensor.
sequence_lengths : torch.LongTensor, required.
A ten... | [
"def",
"sort_batch_by_length",
"(",
"tensor",
":",
"torch",
".",
"Tensor",
",",
"sequence_lengths",
":",
"torch",
".",
"Tensor",
")",
":",
"if",
"not",
"isinstance",
"(",
"tensor",
",",
"torch",
".",
"Tensor",
")",
"or",
"not",
"isinstance",
"(",
"sequence... | Sort a batch first tensor by some specified lengths.
Parameters
----------
tensor : torch.FloatTensor, required.
A batch first Pytorch tensor.
sequence_lengths : torch.LongTensor, required.
A tensor representing the lengths of some dimension of the tensor which
we want to sort b... | [
"Sort",
"a",
"batch",
"first",
"tensor",
"by",
"some",
"specified",
"lengths",
"."
] | python | train | 47.342105 |
pytest-dev/pytest-xprocess | xprocess.py | https://github.com/pytest-dev/pytest-xprocess/blob/c3ee760b02dce2d0eed960b3ab0e28379853c3ef/xprocess.py#L227-L238 | def prep(self, wait, args, env=None):
"""
Given the return value of a preparefunc, prepare this
CompatStarter.
"""
self.pattern = wait
self.env = env
self.args = args
# wait is a function, supersedes the default behavior
if callable(wait):
... | [
"def",
"prep",
"(",
"self",
",",
"wait",
",",
"args",
",",
"env",
"=",
"None",
")",
":",
"self",
".",
"pattern",
"=",
"wait",
"self",
".",
"env",
"=",
"env",
"self",
".",
"args",
"=",
"args",
"# wait is a function, supersedes the default behavior",
"if",
... | Given the return value of a preparefunc, prepare this
CompatStarter. | [
"Given",
"the",
"return",
"value",
"of",
"a",
"preparefunc",
"prepare",
"this",
"CompatStarter",
"."
] | python | train | 28.833333 |
bcbio/bcbio-nextgen | bcbio/cwl/hpc.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/hpc.py#L61-L69 | def _load_custom_config(run_config):
"""Load custom configuration input HOCON file for cromwell.
"""
from pyhocon import ConfigFactory, HOCONConverter, ConfigTree
conf = ConfigFactory.parse_file(run_config)
out = {}
if "database" in conf:
out["database"] = HOCONConverter.to_hocon(ConfigT... | [
"def",
"_load_custom_config",
"(",
"run_config",
")",
":",
"from",
"pyhocon",
"import",
"ConfigFactory",
",",
"HOCONConverter",
",",
"ConfigTree",
"conf",
"=",
"ConfigFactory",
".",
"parse_file",
"(",
"run_config",
")",
"out",
"=",
"{",
"}",
"if",
"\"database\""... | Load custom configuration input HOCON file for cromwell. | [
"Load",
"custom",
"configuration",
"input",
"HOCON",
"file",
"for",
"cromwell",
"."
] | python | train | 41.555556 |
doakey3/DashTable | dashtable/html2data/html2data.py | https://github.com/doakey3/DashTable/blob/744cfb6a717fa75a8092c83ebcd49b2668023681/dashtable/html2data/html2data.py#L7-L40 | def html2data(html_string):
"""
Convert an html table to a data table and spans.
Parameters
----------
html_string : str
The string containing the html table
Returns
-------
table : list of lists of str
spans : list of lists of lists of int
A span is a list of [row,... | [
"def",
"html2data",
"(",
"html_string",
")",
":",
"spans",
"=",
"extract_spans",
"(",
"html_string",
")",
"column_count",
"=",
"get_html_column_count",
"(",
"html_string",
")",
"row_count",
"=",
"get_html_row_count",
"(",
"spans",
")",
"count",
"=",
"0",
"while"... | Convert an html table to a data table and spans.
Parameters
----------
html_string : str
The string containing the html table
Returns
-------
table : list of lists of str
spans : list of lists of lists of int
A span is a list of [row, column] pairs that define what cells
... | [
"Convert",
"an",
"html",
"table",
"to",
"a",
"data",
"table",
"and",
"spans",
"."
] | python | train | 24.088235 |
ISA-tools/biopy-isatab | bcbio/isatab/parser.py | https://github.com/ISA-tools/biopy-isatab/blob/fe42c98184d5eb5f28d8c0b7c3fc63a9b9729f27/bcbio/isatab/parser.py#L142-L162 | def _parse_keyvals(self, line_iter):
"""Generate dictionary from key/value pairs.
"""
out = None
line = None
for line in line_iter:
if len(line) == 1 and line[0].upper() == line[0]:
break
else:
# setup output dictionaries, t... | [
"def",
"_parse_keyvals",
"(",
"self",
",",
"line_iter",
")",
":",
"out",
"=",
"None",
"line",
"=",
"None",
"for",
"line",
"in",
"line_iter",
":",
"if",
"len",
"(",
"line",
")",
"==",
"1",
"and",
"line",
"[",
"0",
"]",
".",
"upper",
"(",
")",
"=="... | Generate dictionary from key/value pairs. | [
"Generate",
"dictionary",
"from",
"key",
"/",
"value",
"pairs",
"."
] | python | train | 37.190476 |
nficano/python-lambda | aws_lambda/aws_lambda.py | https://github.com/nficano/python-lambda/blob/b0bd25404df70212d7fa057758760366406d64f2/aws_lambda/aws_lambda.py#L190-L248 | def invoke(
src, event_file='event.json',
config_file='config.yaml', profile_name=None,
verbose=False,
):
"""Simulates a call to your function.
:param str src:
The path to your Lambda ready project (folder must contain a valid
config.yaml and handler module (e.g.: service.py).
:... | [
"def",
"invoke",
"(",
"src",
",",
"event_file",
"=",
"'event.json'",
",",
"config_file",
"=",
"'config.yaml'",
",",
"profile_name",
"=",
"None",
",",
"verbose",
"=",
"False",
",",
")",
":",
"# Load and parse the config file.",
"path_to_config_file",
"=",
"os",
"... | Simulates a call to your function.
:param str src:
The path to your Lambda ready project (folder must contain a valid
config.yaml and handler module (e.g.: service.py).
:param str alt_event:
An optional argument to override which event file to use.
:param bool verbose:
Wheth... | [
"Simulates",
"a",
"call",
"to",
"your",
"function",
"."
] | python | valid | 32.677966 |
hobson/aima | aima/learning.py | https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L99-L102 | def add_example(self, example):
"Add an example to the list of examples, checking it first."
self.check_example(example)
self.examples.append(example) | [
"def",
"add_example",
"(",
"self",
",",
"example",
")",
":",
"self",
".",
"check_example",
"(",
"example",
")",
"self",
".",
"examples",
".",
"append",
"(",
"example",
")"
] | Add an example to the list of examples, checking it first. | [
"Add",
"an",
"example",
"to",
"the",
"list",
"of",
"examples",
"checking",
"it",
"first",
"."
] | python | valid | 42.75 |
twilio/authy-python | authy/api/resources.py | https://github.com/twilio/authy-python/blob/7a0073b39a56bac495b10e4b4fca3f09982de6ed/authy/api/resources.py#L327-L360 | def verification_start(self, phone_number, country_code, via='sms',
locale=None, code_length=4):
"""
:param string phone_number: stored in your databse or you provided while creating new user.
:param string country_code: stored in your databse or you provided while cre... | [
"def",
"verification_start",
"(",
"self",
",",
"phone_number",
",",
"country_code",
",",
"via",
"=",
"'sms'",
",",
"locale",
"=",
"None",
",",
"code_length",
"=",
"4",
")",
":",
"if",
"via",
"!=",
"'sms'",
"and",
"via",
"!=",
"'call'",
":",
"raise",
"A... | :param string phone_number: stored in your databse or you provided while creating new user.
:param string country_code: stored in your databse or you provided while creating new user.
:param string via: verification method either sms or call
:param string locale: optional default none
:p... | [
":",
"param",
"string",
"phone_number",
":",
"stored",
"in",
"your",
"databse",
"or",
"you",
"provided",
"while",
"creating",
"new",
"user",
".",
":",
"param",
"string",
"country_code",
":",
"stored",
"in",
"your",
"databse",
"or",
"you",
"provided",
"while"... | python | train | 36.294118 |
bcbio/bcbio-nextgen | bcbio/rnaseq/variation.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/variation.py#L154-L184 | def gatk_filter_rnaseq(vrn_file, data):
"""
this incorporates filters listed here, dropping clusters of variants
within a 35 nucleotide window, high fischer strand values and low
quality by depth
https://software.broadinstitute.org/gatk/guide/article?id=3891
java -jar GenomeAnalysisTK.jar -T Var... | [
"def",
"gatk_filter_rnaseq",
"(",
"vrn_file",
",",
"data",
")",
":",
"out_file",
"=",
"\"%s-filter%s\"",
"%",
"utils",
".",
"splitext_plus",
"(",
"vrn_file",
")",
"if",
"not",
"file_exists",
"(",
"out_file",
")",
":",
"ref_file",
"=",
"dd",
".",
"get_ref_fil... | this incorporates filters listed here, dropping clusters of variants
within a 35 nucleotide window, high fischer strand values and low
quality by depth
https://software.broadinstitute.org/gatk/guide/article?id=3891
java -jar GenomeAnalysisTK.jar -T VariantFiltration -R hg_19.fasta -V
input.vcf -wind... | [
"this",
"incorporates",
"filters",
"listed",
"here",
"dropping",
"clusters",
"of",
"variants",
"within",
"a",
"35",
"nucleotide",
"window",
"high",
"fischer",
"strand",
"values",
"and",
"low",
"quality",
"by",
"depth",
"https",
":",
"//",
"software",
".",
"bro... | python | train | 51.096774 |
matthewdeanmartin/jiggle_version | jiggle_version/package_info_finder.py | https://github.com/matthewdeanmartin/jiggle_version/blob/963656a0a47b7162780a5f6c8f4b8bbbebc148f5/jiggle_version/package_info_finder.py#L270-L290 | def find_single_file_project(self): # type: () -> List[str]
"""
Find well formed singler file project
:return:
"""
files = [f for f in os.listdir(".") if os.path.isfile(f)]
candidates = []
setup_source = self.setup_py_source()
for file in files:
... | [
"def",
"find_single_file_project",
"(",
"self",
")",
":",
"# type: () -> List[str]",
"files",
"=",
"[",
"f",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"\".\"",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"f",
")",
"]",
"candidates",
"=",
"[",
... | Find well formed singler file project
:return: | [
"Find",
"well",
"formed",
"singler",
"file",
"project",
":",
"return",
":"
] | python | train | 31.666667 |
larsyencken/csvdiff | csvdiff/patch.py | https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/patch.py#L106-L116 | def apply(diff, recs, strict=True):
"""
Transform the records with the patch. May fail if the records do not
match those expected in the patch.
"""
index_columns = diff['_index']
indexed = records.index(copy.deepcopy(list(recs)), index_columns)
_add_records(indexed, diff['added'], index_colu... | [
"def",
"apply",
"(",
"diff",
",",
"recs",
",",
"strict",
"=",
"True",
")",
":",
"index_columns",
"=",
"diff",
"[",
"'_index'",
"]",
"indexed",
"=",
"records",
".",
"index",
"(",
"copy",
".",
"deepcopy",
"(",
"list",
"(",
"recs",
")",
")",
",",
"ind... | Transform the records with the patch. May fail if the records do not
match those expected in the patch. | [
"Transform",
"the",
"records",
"with",
"the",
"patch",
".",
"May",
"fail",
"if",
"the",
"records",
"do",
"not",
"match",
"those",
"expected",
"in",
"the",
"patch",
"."
] | python | train | 46.181818 |
singularityhub/sregistry-cli | sregistry/main/globus/utils.py | https://github.com/singularityhub/sregistry-cli/blob/abc96140a1d15b5e96d83432e1e0e1f4f8f36331/sregistry/main/globus/utils.py#L57-L70 | def create_endpoint_folder(self, endpoint_id, folder):
'''create an endpoint folder, catching the error if it exists.
Parameters
==========
endpoint_id: the endpoint id parameters
folder: the relative path of the folder to create
'''
try:
res = self.transfer_client.oper... | [
"def",
"create_endpoint_folder",
"(",
"self",
",",
"endpoint_id",
",",
"folder",
")",
":",
"try",
":",
"res",
"=",
"self",
".",
"transfer_client",
".",
"operation_mkdir",
"(",
"endpoint_id",
",",
"folder",
")",
"bot",
".",
"info",
"(",
"\"%s --> %s\"",
"%",
... | create an endpoint folder, catching the error if it exists.
Parameters
==========
endpoint_id: the endpoint id parameters
folder: the relative path of the folder to create | [
"create",
"an",
"endpoint",
"folder",
"catching",
"the",
"error",
"if",
"it",
"exists",
"."
] | python | test | 34.428571 |
matrix-org/matrix-python-sdk | matrix_client/api.py | https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/api.py#L915-L926 | def set_join_rule(self, room_id, join_rule):
"""Set the rule for users wishing to join the room.
Args:
room_id(str): The room to set the rules for.
join_rule(str): The chosen rule. One of: ["public", "knock",
"invite", "private"]
"""
content = {
... | [
"def",
"set_join_rule",
"(",
"self",
",",
"room_id",
",",
"join_rule",
")",
":",
"content",
"=",
"{",
"\"join_rule\"",
":",
"join_rule",
"}",
"return",
"self",
".",
"send_state_event",
"(",
"room_id",
",",
"\"m.room.join_rules\"",
",",
"content",
")"
] | Set the rule for users wishing to join the room.
Args:
room_id(str): The room to set the rules for.
join_rule(str): The chosen rule. One of: ["public", "knock",
"invite", "private"] | [
"Set",
"the",
"rule",
"for",
"users",
"wishing",
"to",
"join",
"the",
"room",
"."
] | python | train | 35.666667 |
secynic/ipwhois | ipwhois/asn.py | https://github.com/secynic/ipwhois/blob/b5d634d36b0b942d538d38d77b3bdcd815f155a0/ipwhois/asn.py#L306-L404 | def parse_fields_http(self, response, extra_org_map=None):
"""
The function for parsing ASN fields from a http response.
Args:
response (:obj:`str`): The response from the ASN http server.
extra_org_map (:obj:`dict`): Dictionary mapping org handles to
RIR... | [
"def",
"parse_fields_http",
"(",
"self",
",",
"response",
",",
"extra_org_map",
"=",
"None",
")",
":",
"# Set the org_map. Map the orgRef handle to an RIR.",
"org_map",
"=",
"self",
".",
"org_map",
".",
"copy",
"(",
")",
"try",
":",
"org_map",
".",
"update",
"("... | The function for parsing ASN fields from a http response.
Args:
response (:obj:`str`): The response from the ASN http server.
extra_org_map (:obj:`dict`): Dictionary mapping org handles to
RIRs. This is for limited cases where ARIN REST (ASN fallback
HTTP... | [
"The",
"function",
"for",
"parsing",
"ASN",
"fields",
"from",
"a",
"http",
"response",
"."
] | python | train | 30.777778 |
Unidata/MetPy | metpy/interpolate/grid.py | https://github.com/Unidata/MetPy/blob/16f68a94919b9a82dcf9cada2169cf039129e67b/metpy/interpolate/grid.py#L87-L108 | def get_xy_steps(bbox, h_dim):
r"""Return meshgrid spacing based on bounding box.
bbox: dictionary
Dictionary containing coordinates for corners of study area.
h_dim: integer
Horizontal resolution in meters.
Returns
-------
x_steps, (X, ) ndarray
Number of grids in x di... | [
"def",
"get_xy_steps",
"(",
"bbox",
",",
"h_dim",
")",
":",
"x_range",
",",
"y_range",
"=",
"get_xy_range",
"(",
"bbox",
")",
"x_steps",
"=",
"np",
".",
"ceil",
"(",
"x_range",
"/",
"h_dim",
")",
"y_steps",
"=",
"np",
".",
"ceil",
"(",
"y_range",
"/"... | r"""Return meshgrid spacing based on bounding box.
bbox: dictionary
Dictionary containing coordinates for corners of study area.
h_dim: integer
Horizontal resolution in meters.
Returns
-------
x_steps, (X, ) ndarray
Number of grids in x dimension.
y_steps: (Y, ) ndarray... | [
"r",
"Return",
"meshgrid",
"spacing",
"based",
"on",
"bounding",
"box",
"."
] | python | train | 24.681818 |
gesellkammer/sndfileio | sndfileio/sndfileio.py | https://github.com/gesellkammer/sndfileio/blob/8e2b264cadb652f09d2e775f54090c0a3cb2ced2/sndfileio/sndfileio.py#L228-L268 | def sndwrite(samples:np.ndarray, sr:int, outfile:str, encoding:str='auto') -> None:
"""
samples --> Array-like. the actual samples, shape=(nframes, channels)
sr --> Sampling-rate
outfile --> The name of the outfile. the extension will determine
the file-format.
... | [
"def",
"sndwrite",
"(",
"samples",
":",
"np",
".",
"ndarray",
",",
"sr",
":",
"int",
",",
"outfile",
":",
"str",
",",
"encoding",
":",
"str",
"=",
"'auto'",
")",
"->",
"None",
":",
"if",
"encoding",
"in",
"(",
"'auto'",
",",
"None",
")",
":",
"en... | samples --> Array-like. the actual samples, shape=(nframes, channels)
sr --> Sampling-rate
outfile --> The name of the outfile. the extension will determine
the file-format.
The formats supported depend on the available backends
Without additional backe... | [
"samples",
"--",
">",
"Array",
"-",
"like",
".",
"the",
"actual",
"samples",
"shape",
"=",
"(",
"nframes",
"channels",
")",
"sr",
"--",
">",
"Sampling",
"-",
"rate",
"outfile",
"--",
">",
"The",
"name",
"of",
"the",
"outfile",
".",
"the",
"extension",
... | python | train | 48.341463 |
chrisrink10/basilisp | src/basilisp/lang/runtime.py | https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/runtime.py#L759-L767 | def cons(o, seq) -> ISeq:
"""Creates a new sequence where o is the first element and seq is the rest.
If seq is None, return a list containing o. If seq is not a ISeq, attempt
to coerce it to a ISeq and then cons o onto the resulting sequence."""
if seq is None:
return llist.l(o)
if isinstan... | [
"def",
"cons",
"(",
"o",
",",
"seq",
")",
"->",
"ISeq",
":",
"if",
"seq",
"is",
"None",
":",
"return",
"llist",
".",
"l",
"(",
"o",
")",
"if",
"isinstance",
"(",
"seq",
",",
"ISeq",
")",
":",
"return",
"seq",
".",
"cons",
"(",
"o",
")",
"retu... | Creates a new sequence where o is the first element and seq is the rest.
If seq is None, return a list containing o. If seq is not a ISeq, attempt
to coerce it to a ISeq and then cons o onto the resulting sequence. | [
"Creates",
"a",
"new",
"sequence",
"where",
"o",
"is",
"the",
"first",
"element",
"and",
"seq",
"is",
"the",
"rest",
".",
"If",
"seq",
"is",
"None",
"return",
"a",
"list",
"containing",
"o",
".",
"If",
"seq",
"is",
"not",
"a",
"ISeq",
"attempt",
"to"... | python | test | 48.444444 |
edwards-lab/libGWAS | libgwas/pheno_covar.py | https://github.com/edwards-lab/libGWAS/blob/d68c9a083d443dfa5d7c5112de29010909cfe23f/libgwas/pheno_covar.py#L94-L102 | def freeze_subjects(self):
"""Converts variable data into numpy arrays.
This is required after all subjects have been added via the
add_subject function, since we don't know ahead of time who is
participating in the analysis due to various filtering possibilities.
"""
se... | [
"def",
"freeze_subjects",
"(",
"self",
")",
":",
"self",
".",
"phenotype_data",
"=",
"numpy",
".",
"array",
"(",
"self",
".",
"phenotype_data",
")",
"self",
".",
"covariate_data",
"=",
"numpy",
".",
"array",
"(",
"self",
".",
"covariate_data",
")"
] | Converts variable data into numpy arrays.
This is required after all subjects have been added via the
add_subject function, since we don't know ahead of time who is
participating in the analysis due to various filtering possibilities. | [
"Converts",
"variable",
"data",
"into",
"numpy",
"arrays",
"."
] | python | train | 47.444444 |
google/grr | grr/server/grr_response_server/artifact_registry.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/artifact_registry.py#L40-L52 | def AddDir(self, dirpath):
"""Adds a directory path as a source.
Args:
dirpath: a string representing a path to the directory.
Returns:
True if the directory is not an already existing source.
"""
if dirpath not in self._dirs:
self._dirs.add(dirpath)
return True
return ... | [
"def",
"AddDir",
"(",
"self",
",",
"dirpath",
")",
":",
"if",
"dirpath",
"not",
"in",
"self",
".",
"_dirs",
":",
"self",
".",
"_dirs",
".",
"add",
"(",
"dirpath",
")",
"return",
"True",
"return",
"False"
] | Adds a directory path as a source.
Args:
dirpath: a string representing a path to the directory.
Returns:
True if the directory is not an already existing source. | [
"Adds",
"a",
"directory",
"path",
"as",
"a",
"source",
"."
] | python | train | 24.076923 |
albert12132/templar | templar/markdown.py | https://github.com/albert12132/templar/blob/39851c89730ab69e5c73d0a46adca2a44ecc4165/templar/markdown.py#L382-L408 | def hash_codeblocks(text, hashes):
"""Hashes codeblocks (<pre> elements).
Codeblocks are strictly defined to be (non-list) lines that are
indented at least 4 spaces from the newline. Exactly 4 spaces will
be stripped from the beginning of the line -- any leading
whitespace after that is preserved.
... | [
"def",
"hash_codeblocks",
"(",
"text",
",",
"hashes",
")",
":",
"def",
"sub",
"(",
"match",
")",
":",
"block",
"=",
"match",
".",
"group",
"(",
"1",
")",
".",
"rstrip",
"(",
"'\\n'",
")",
"block",
"=",
"re",
".",
"sub",
"(",
"r'(?:(?<=\\n)|(?<=\\A)) ... | Hashes codeblocks (<pre> elements).
Codeblocks are strictly defined to be (non-list) lines that are
indented at least 4 spaces from the newline. Exactly 4 spaces will
be stripped from the beginning of the line -- any leading
whitespace after that is preserved.
Codeblock lines that are separated on... | [
"Hashes",
"codeblocks",
"(",
"<pre",
">",
"elements",
")",
"."
] | python | train | 40.592593 |
iotile/coretools | iotilecore/iotile/core/hw/transport/adapterstream.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapterstream.py#L467-L481 | def close(self):
"""Close this adapter stream.
This method may only be called once in the lifetime of an
AdapterStream and it will shutdown the underlying device adapter,
disconnect all devices and stop all background activity.
If this stream is configured to save a record of a... | [
"def",
"close",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_loop",
".",
"run_coroutine",
"(",
"self",
".",
"adapter",
".",
"stop",
"(",
")",
")",
"finally",
":",
"self",
".",
"_save_recording",
"(",
")"
] | Close this adapter stream.
This method may only be called once in the lifetime of an
AdapterStream and it will shutdown the underlying device adapter,
disconnect all devices and stop all background activity.
If this stream is configured to save a record of all RPCs, the RPCs
wi... | [
"Close",
"this",
"adapter",
"stream",
"."
] | python | train | 33.8 |
acutesoftware/virtual-AI-simulator | vais/examples/game_incremental.py | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/examples/game_incremental.py#L202-L211 | def get_inventory_by_name(nme, character):
"""
returns the inventory index by name
"""
for ndx, sk in enumerate(character["inventory"]):
#print("sk = ", sk, " , nme = ", nme)
if sk["name"] == nme:
return ndx
return 0 | [
"def",
"get_inventory_by_name",
"(",
"nme",
",",
"character",
")",
":",
"for",
"ndx",
",",
"sk",
"in",
"enumerate",
"(",
"character",
"[",
"\"inventory\"",
"]",
")",
":",
"#print(\"sk = \", sk, \" , nme = \", nme)",
"if",
"sk",
"[",
"\"name\"",
"]",
"==",
"nme... | returns the inventory index by name | [
"returns",
"the",
"inventory",
"index",
"by",
"name"
] | python | train | 25.6 |
portantier/habu | habu/cli/cmd_nc.py | https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_nc.py#L30-L118 | def cmd_nc(host, port, family, ssl_enable, crlf, source_ip, source_port, protocol):
"""Some kind of netcat/ncat replacement.
The execution emulates the feeling of this popular tools.
Example:
\b
$ habu.nc --crlf www.portantier.com 80
Connected to 45.77.113.133 80
HEAD / HTTP/1.0
\b
... | [
"def",
"cmd_nc",
"(",
"host",
",",
"port",
",",
"family",
",",
"ssl_enable",
",",
"crlf",
",",
"source_ip",
",",
"source_port",
",",
"protocol",
")",
":",
"resolved",
"=",
"socket",
".",
"getaddrinfo",
"(",
"host",
",",
"port",
")",
"families",
"=",
"{... | Some kind of netcat/ncat replacement.
The execution emulates the feeling of this popular tools.
Example:
\b
$ habu.nc --crlf www.portantier.com 80
Connected to 45.77.113.133 80
HEAD / HTTP/1.0
\b
HTTP/1.0 301 Moved Permanently
Date: Thu, 26 Jul 2018 21:10:51 GMT
Server: OpenB... | [
"Some",
"kind",
"of",
"netcat",
"/",
"ncat",
"replacement",
"."
] | python | train | 26.730337 |
msmbuilder/msmbuilder | msmbuilder/decomposition/ksparsetica.py | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/decomposition/ksparsetica.py#L129-L133 | def _truncate(self, x, k):
''' given a vector x, leave its top-k absolute-value entries alone, and set the rest to 0 '''
not_F = np.argsort(np.abs(x))[:-k]
x[not_F] = 0
return x | [
"def",
"_truncate",
"(",
"self",
",",
"x",
",",
"k",
")",
":",
"not_F",
"=",
"np",
".",
"argsort",
"(",
"np",
".",
"abs",
"(",
"x",
")",
")",
"[",
":",
"-",
"k",
"]",
"x",
"[",
"not_F",
"]",
"=",
"0",
"return",
"x"
] | given a vector x, leave its top-k absolute-value entries alone, and set the rest to 0 | [
"given",
"a",
"vector",
"x",
"leave",
"its",
"top",
"-",
"k",
"absolute",
"-",
"value",
"entries",
"alone",
"and",
"set",
"the",
"rest",
"to",
"0"
] | python | train | 41 |
crocs-muni/roca | roca/detect.py | https://github.com/crocs-muni/roca/blob/74ad6ce63c428d83dcffce9c5e26ef7b9e30faa5/roca/detect.py#L343-L351 | def strip_spaces(x):
"""
Strips spaces
:param x:
:return:
"""
x = x.replace(b' ', b'')
x = x.replace(b'\t', b'')
return x | [
"def",
"strip_spaces",
"(",
"x",
")",
":",
"x",
"=",
"x",
".",
"replace",
"(",
"b' '",
",",
"b''",
")",
"x",
"=",
"x",
".",
"replace",
"(",
"b'\\t'",
",",
"b''",
")",
"return",
"x"
] | Strips spaces
:param x:
:return: | [
"Strips",
"spaces",
":",
"param",
"x",
":",
":",
"return",
":"
] | python | train | 16.111111 |
gc3-uzh-ch/elasticluster | elasticluster/cluster.py | https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/cluster.py#L1321-L1338 | def stop(self, wait=False):
"""
Terminate the VM instance launched on the cloud for this specific node.
"""
if self.instance_id is not None:
log.info("Shutting down node `%s` (VM instance `%s`) ...",
self.name, self.instance_id)
self._cloud_p... | [
"def",
"stop",
"(",
"self",
",",
"wait",
"=",
"False",
")",
":",
"if",
"self",
".",
"instance_id",
"is",
"not",
"None",
":",
"log",
".",
"info",
"(",
"\"Shutting down node `%s` (VM instance `%s`) ...\"",
",",
"self",
".",
"name",
",",
"self",
".",
"instanc... | Terminate the VM instance launched on the cloud for this specific node. | [
"Terminate",
"the",
"VM",
"instance",
"launched",
"on",
"the",
"cloud",
"for",
"this",
"specific",
"node",
"."
] | python | train | 44.5 |
molmod/molmod | molmod/molecules.py | https://github.com/molmod/molmod/blob/a7b5b4364ed514ad4c465856c05b5eda1cb561e0/molmod/molecules.py#L191-L202 | def chemical_formula(self):
"""the chemical formula of the molecule"""
counts = {}
for number in self.numbers:
counts[number] = counts.get(number, 0)+1
items = []
for number, count in sorted(counts.items(), reverse=True):
if count == 1:
ite... | [
"def",
"chemical_formula",
"(",
"self",
")",
":",
"counts",
"=",
"{",
"}",
"for",
"number",
"in",
"self",
".",
"numbers",
":",
"counts",
"[",
"number",
"]",
"=",
"counts",
".",
"get",
"(",
"number",
",",
"0",
")",
"+",
"1",
"items",
"=",
"[",
"]"... | the chemical formula of the molecule | [
"the",
"chemical",
"formula",
"of",
"the",
"molecule"
] | python | train | 38.583333 |
facelessuser/pyspelling | pyspelling/filters/stylesheets.py | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/stylesheets.py#L62-L71 | def setup(self):
"""Setup."""
self.blocks = self.config['block_comments']
self.lines = self.config['line_comments']
self.group_comments = self.config['group_comments']
# If the style isn't found, just go with CSS, then use the appropriate prefix.
self.stylesheets = STYLE... | [
"def",
"setup",
"(",
"self",
")",
":",
"self",
".",
"blocks",
"=",
"self",
".",
"config",
"[",
"'block_comments'",
"]",
"self",
".",
"lines",
"=",
"self",
".",
"config",
"[",
"'line_comments'",
"]",
"self",
".",
"group_comments",
"=",
"self",
".",
"con... | Setup. | [
"Setup",
"."
] | python | train | 51.4 |
Opentrons/opentrons | api/src/opentrons/hardware_control/modules/update.py | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/hardware_control/modules/update.py#L44-L88 | async def update_firmware(port: str,
firmware_file_path: str,
loop: Optional[asyncio.AbstractEventLoop])\
-> Tuple[str, Tuple[bool, str]]:
"""
Run avrdude firmware upload command. Switch back to normal module port
Note: For modul... | [
"async",
"def",
"update_firmware",
"(",
"port",
":",
"str",
",",
"firmware_file_path",
":",
"str",
",",
"loop",
":",
"Optional",
"[",
"asyncio",
".",
"AbstractEventLoop",
"]",
")",
"->",
"Tuple",
"[",
"str",
",",
"Tuple",
"[",
"bool",
",",
"str",
"]",
... | Run avrdude firmware upload command. Switch back to normal module port
Note: For modules with old bootloader, the kernel could assign the module
a new port after the update (since the board is automatically reset).
Scan for such a port change and use the appropriate port.
Returns a tuple of the new po... | [
"Run",
"avrdude",
"firmware",
"upload",
"command",
".",
"Switch",
"back",
"to",
"normal",
"module",
"port"
] | python | train | 38.466667 |
tanghaibao/jcvi | jcvi/projects/ies.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/projects/ies.py#L244-L379 | def deletion(args):
"""
%prog deletion [mac.mic.bam|mac.mic.bed] mic.gaps.bed
Find IES based on mapping MAC reads to MIC genome.
"""
p = OptionParser(deletion.__doc__)
p.add_option("--mindepth", default=3, type="int",
help="Minimum depth to call a deletion")
p.add_option("-... | [
"def",
"deletion",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"deletion",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--mindepth\"",
",",
"default",
"=",
"3",
",",
"type",
"=",
"\"int\"",
",",
"help",
"=",
"\"Minimum depth to call a del... | %prog deletion [mac.mic.bam|mac.mic.bed] mic.gaps.bed
Find IES based on mapping MAC reads to MIC genome. | [
"%prog",
"deletion",
"[",
"mac",
".",
"mic",
".",
"bam|mac",
".",
"mic",
".",
"bed",
"]",
"mic",
".",
"gaps",
".",
"bed"
] | python | train | 39.691176 |
pyviz/holoviews | holoviews/plotting/bokeh/heatmap.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/plotting/bokeh/heatmap.py#L400-L420 | def _get_ann_labels_data(self, order_ann, bins_ann):
"""Generate ColumnDataSource dictionary for annular labels.
"""
if self.yticks is None:
return dict(x=[], y=[], text=[], angle=[])
mapping = self._compute_tick_mapping("radius", order_ann, bins_ann)
values = [(la... | [
"def",
"_get_ann_labels_data",
"(",
"self",
",",
"order_ann",
",",
"bins_ann",
")",
":",
"if",
"self",
".",
"yticks",
"is",
"None",
":",
"return",
"dict",
"(",
"x",
"=",
"[",
"]",
",",
"y",
"=",
"[",
"]",
",",
"text",
"=",
"[",
"]",
",",
"angle",... | Generate ColumnDataSource dictionary for annular labels. | [
"Generate",
"ColumnDataSource",
"dictionary",
"for",
"annular",
"labels",
"."
] | python | train | 34.571429 |
sepandhaghighi/art | art/art.py | https://github.com/sepandhaghighi/art/blob/c5b0409de76464b0714c377f8fca17716f3a9482/art/art.py#L181-L194 | def tprint(text, font=DEFAULT_FONT, chr_ignore=True):
r"""
Print art text (support \n).
:param text: input text
:type text:str
:param font: input font
:type font:str
:param chr_ignore: ignore not supported character
:type chr_ignore:bool
:return: None
"""
result = text2art(t... | [
"def",
"tprint",
"(",
"text",
",",
"font",
"=",
"DEFAULT_FONT",
",",
"chr_ignore",
"=",
"True",
")",
":",
"result",
"=",
"text2art",
"(",
"text",
",",
"font",
"=",
"font",
",",
"chr_ignore",
"=",
"chr_ignore",
")",
"print",
"(",
"result",
")"
] | r"""
Print art text (support \n).
:param text: input text
:type text:str
:param font: input font
:type font:str
:param chr_ignore: ignore not supported character
:type chr_ignore:bool
:return: None | [
"r",
"Print",
"art",
"text",
"(",
"support",
"\\",
"n",
")",
"."
] | python | train | 25.928571 |
happyleavesaoc/python-snapcast | snapcast/control/protocol.py | https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/protocol.py#L71-L79 | def request(self, method, params):
"""Send a JSONRPC request."""
identifier = random.randint(1, 1000)
self._transport.write(jsonrpc_request(method, identifier, params))
self._buffer[identifier] = {'flag': asyncio.Event()}
yield from self._buffer[identifier]['flag'].wait()
... | [
"def",
"request",
"(",
"self",
",",
"method",
",",
"params",
")",
":",
"identifier",
"=",
"random",
".",
"randint",
"(",
"1",
",",
"1000",
")",
"self",
".",
"_transport",
".",
"write",
"(",
"jsonrpc_request",
"(",
"method",
",",
"identifier",
",",
"par... | Send a JSONRPC request. | [
"Send",
"a",
"JSONRPC",
"request",
"."
] | python | train | 46.777778 |
secure-systems-lab/securesystemslib | securesystemslib/interface.py | https://github.com/secure-systems-lab/securesystemslib/blob/beb3109d5bb462e5a60eed88fb40ed1167bd354e/securesystemslib/interface.py#L823-L900 | def import_ecdsa_privatekey_from_file(filepath, password=None):
"""
<Purpose>
Import the encrypted ECDSA key file in 'filepath', decrypt it, and return
the key object in 'securesystemslib.formats.ECDSAKEY_SCHEMA' format.
The 'cryptography' library is currently supported and performs the actual
cryp... | [
"def",
"import_ecdsa_privatekey_from_file",
"(",
"filepath",
",",
"password",
"=",
"None",
")",
":",
"# Does 'filepath' have the correct format?",
"# Ensure the arguments have the appropriate number of objects and object",
"# types, and that all dict keys are properly named.",
"# Raise 'se... | <Purpose>
Import the encrypted ECDSA key file in 'filepath', decrypt it, and return
the key object in 'securesystemslib.formats.ECDSAKEY_SCHEMA' format.
The 'cryptography' library is currently supported and performs the actual
cryptographic routine.
<Arguments>
filepath:
<filepath> file, a... | [
"<Purpose",
">",
"Import",
"the",
"encrypted",
"ECDSA",
"key",
"file",
"in",
"filepath",
"decrypt",
"it",
"and",
"return",
"the",
"key",
"object",
"in",
"securesystemslib",
".",
"formats",
".",
"ECDSAKEY_SCHEMA",
"format",
"."
] | python | train | 39.5 |
CalebBell/thermo | thermo/viscosity.py | https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/viscosity.py#L690-L719 | def calculate_P(self, T, P, method):
r'''Method to calculate pressure-dependent liquid viscosity at
temperature `T` and pressure `P` with a given method.
This method has no exception handling; see `TP_dependent_property`
for that.
Parameters
----------
T : float... | [
"def",
"calculate_P",
"(",
"self",
",",
"T",
",",
"P",
",",
"method",
")",
":",
"if",
"method",
"==",
"LUCAS",
":",
"mu",
"=",
"self",
".",
"T_dependent_property",
"(",
"T",
")",
"Psat",
"=",
"self",
".",
"Psat",
"(",
"T",
")",
"if",
"hasattr",
"... | r'''Method to calculate pressure-dependent liquid viscosity at
temperature `T` and pressure `P` with a given method.
This method has no exception handling; see `TP_dependent_property`
for that.
Parameters
----------
T : float
Temperature at which to calculat... | [
"r",
"Method",
"to",
"calculate",
"pressure",
"-",
"dependent",
"liquid",
"viscosity",
"at",
"temperature",
"T",
"and",
"pressure",
"P",
"with",
"a",
"given",
"method",
"."
] | python | valid | 34.366667 |
tensorforce/tensorforce | docs/mistune.py | https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/docs/mistune.py#L854-L863 | def autolink(self, link, is_email=False):
"""Rendering a given link or email address.
:param link: link content or email address.
:param is_email: whether this is an email or not.
"""
text = link = escape(link)
if is_email:
link = 'mailto:%s' % link
r... | [
"def",
"autolink",
"(",
"self",
",",
"link",
",",
"is_email",
"=",
"False",
")",
":",
"text",
"=",
"link",
"=",
"escape",
"(",
"link",
")",
"if",
"is_email",
":",
"link",
"=",
"'mailto:%s'",
"%",
"link",
"return",
"'<a href=\"%s\">%s</a>'",
"%",
"(",
"... | Rendering a given link or email address.
:param link: link content or email address.
:param is_email: whether this is an email or not. | [
"Rendering",
"a",
"given",
"link",
"or",
"email",
"address",
"."
] | python | valid | 35.3 |
aloetesting/aloe_webdriver | aloe_webdriver/__init__.py | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/__init__.py#L440-L448 | def press_button(self, value):
"""
Click the button with the given label.
"""
button = find_button(world.browser, value)
if not button:
raise AssertionError(
"Cannot find a button named '{}'.".format(value))
button.click() | [
"def",
"press_button",
"(",
"self",
",",
"value",
")",
":",
"button",
"=",
"find_button",
"(",
"world",
".",
"browser",
",",
"value",
")",
"if",
"not",
"button",
":",
"raise",
"AssertionError",
"(",
"\"Cannot find a button named '{}'.\"",
".",
"format",
"(",
... | Click the button with the given label. | [
"Click",
"the",
"button",
"with",
"the",
"given",
"label",
"."
] | python | train | 28.666667 |
MisterWil/abodepy | abodepy/event_controller.py | https://github.com/MisterWil/abodepy/blob/6f84bb428fd1da98855f55083cd427bebbcc57ae/abodepy/event_controller.py#L183-L212 | def _on_timeline_update(self, event):
"""Timeline update broadcast from Abode SocketIO server."""
if isinstance(event, (tuple, list)):
event = event[0]
event_type = event.get('event_type')
event_code = event.get('event_code')
if not event_type or not event_code:
... | [
"def",
"_on_timeline_update",
"(",
"self",
",",
"event",
")",
":",
"if",
"isinstance",
"(",
"event",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"event",
"=",
"event",
"[",
"0",
"]",
"event_type",
"=",
"event",
".",
"get",
"(",
"'event_type'",
")"... | Timeline update broadcast from Abode SocketIO server. | [
"Timeline",
"update",
"broadcast",
"from",
"Abode",
"SocketIO",
"server",
"."
] | python | train | 39.333333 |
cebel/pyctd | src/pyctd/manager/query.py | https://github.com/cebel/pyctd/blob/38ba02adaddb60cef031d3b75516773fe8a046b5/src/pyctd/manager/query.py#L13-L29 | def _limit_and_df(self, query, limit, as_df=False):
"""adds a limit (limit==None := no limit) to any query and allow a return as pandas.DataFrame
:param bool as_df: if is set to True results return as pandas.DataFrame
:param `sqlalchemy.orm.query.Query` query: SQL Alchemy query
:param ... | [
"def",
"_limit_and_df",
"(",
"self",
",",
"query",
",",
"limit",
",",
"as_df",
"=",
"False",
")",
":",
"if",
"limit",
":",
"query",
"=",
"query",
".",
"limit",
"(",
"limit",
")",
"if",
"as_df",
":",
"results",
"=",
"read_sql",
"(",
"query",
".",
"s... | adds a limit (limit==None := no limit) to any query and allow a return as pandas.DataFrame
:param bool as_df: if is set to True results return as pandas.DataFrame
:param `sqlalchemy.orm.query.Query` query: SQL Alchemy query
:param int limit: maximum number of results
:return: query res... | [
"adds",
"a",
"limit",
"(",
"limit",
"==",
"None",
":",
"=",
"no",
"limit",
")",
"to",
"any",
"query",
"and",
"allow",
"a",
"return",
"as",
"pandas",
".",
"DataFrame"
] | python | train | 36.823529 |
veeti/decent | decent/validators.py | https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L11-L21 | def All(*validators):
"""
Combines all the given validator callables into one, running all the
validators in sequence on the given value.
"""
@wraps(All)
def built(value):
for validator in validators:
value = validator(value)
return value
return built | [
"def",
"All",
"(",
"*",
"validators",
")",
":",
"@",
"wraps",
"(",
"All",
")",
"def",
"built",
"(",
"value",
")",
":",
"for",
"validator",
"in",
"validators",
":",
"value",
"=",
"validator",
"(",
"value",
")",
"return",
"value",
"return",
"built"
] | Combines all the given validator callables into one, running all the
validators in sequence on the given value. | [
"Combines",
"all",
"the",
"given",
"validator",
"callables",
"into",
"one",
"running",
"all",
"the",
"validators",
"in",
"sequence",
"on",
"the",
"given",
"value",
"."
] | python | train | 27 |
pythongssapi/python-gssapi | gssapi/creds.py | https://github.com/pythongssapi/python-gssapi/blob/b6efe72aa35a4c1fe21b397e15fcb41611e365ce/gssapi/creds.py#L303-L386 | def add(self, name, mech, usage='both',
init_lifetime=None, accept_lifetime=None, impersonator=None,
store=None):
"""Acquire more credentials to add to the current set
This method works like :meth:`acquire`, except that it adds the
acquired credentials for a single mecha... | [
"def",
"add",
"(",
"self",
",",
"name",
",",
"mech",
",",
"usage",
"=",
"'both'",
",",
"init_lifetime",
"=",
"None",
",",
"accept_lifetime",
"=",
"None",
",",
"impersonator",
"=",
"None",
",",
"store",
"=",
"None",
")",
":",
"if",
"store",
"is",
"not... | Acquire more credentials to add to the current set
This method works like :meth:`acquire`, except that it adds the
acquired credentials for a single mechanism to a copy of the current
set, instead of creating a new set for multiple mechanisms.
Unlike :meth:`acquire`, you cannot pass Non... | [
"Acquire",
"more",
"credentials",
"to",
"add",
"to",
"the",
"current",
"set"
] | python | train | 45.642857 |
orbingol/NURBS-Python | geomdl/convert.py | https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/convert.py#L34-L65 | def nurbs_to_bspline(obj, **kwargs):
""" Extracts the non-rational components from rational parametric shapes, if possible.
The possibility of converting a rational shape to a non-rational one depends on the weights vector.
:param obj: NURBS shape
:type obj: NURBS.Curve, NURBS.Surface or NURBS.Volume
... | [
"def",
"nurbs_to_bspline",
"(",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"obj",
".",
"rational",
":",
"raise",
"TypeError",
"(",
"\"The input must be a rational shape\"",
")",
"# Get keyword arguments",
"tol",
"=",
"kwargs",
".",
"get",
"(",
"'to... | Extracts the non-rational components from rational parametric shapes, if possible.
The possibility of converting a rational shape to a non-rational one depends on the weights vector.
:param obj: NURBS shape
:type obj: NURBS.Curve, NURBS.Surface or NURBS.Volume
:return: B-Spline shape
:rtype: BSpli... | [
"Extracts",
"the",
"non",
"-",
"rational",
"components",
"from",
"rational",
"parametric",
"shapes",
"if",
"possible",
"."
] | python | train | 35.875 |
albertz/py_better_exchook | better_exchook.py | https://github.com/albertz/py_better_exchook/blob/3d524a027d7fc4e83e47e39a1978849561da69b3/better_exchook.py#L265-L343 | def debug_shell(user_ns, user_global_ns, traceback=None, execWrapper=None):
"""
Spawns some interactive shell. Tries to use IPython if available.
Falls back to :func:`pdb.post_mortem` or :func:`simple_debug_shell`.
:param dict[str] user_ns:
:param dict[str] user_global_ns:
:param traceback:
... | [
"def",
"debug_shell",
"(",
"user_ns",
",",
"user_global_ns",
",",
"traceback",
"=",
"None",
",",
"execWrapper",
"=",
"None",
")",
":",
"ipshell",
"=",
"None",
"try",
":",
"# noinspection PyPackageRequirements",
"import",
"IPython",
"have_ipython",
"=",
"True",
"... | Spawns some interactive shell. Tries to use IPython if available.
Falls back to :func:`pdb.post_mortem` or :func:`simple_debug_shell`.
:param dict[str] user_ns:
:param dict[str] user_global_ns:
:param traceback:
:param execWrapper:
:return: nothing | [
"Spawns",
"some",
"interactive",
"shell",
".",
"Tries",
"to",
"use",
"IPython",
"if",
"available",
".",
"Falls",
"back",
"to",
":",
"func",
":",
"pdb",
".",
"post_mortem",
"or",
":",
"func",
":",
"simple_debug_shell",
"."
] | python | train | 36.658228 |
praekeltfoundation/seaworthy | seaworthy/helpers.py | https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/helpers.py#L414-L424 | def teardown(self):
"""
Clean up all resources when we're done with them.
"""
self.containers._teardown()
self.networks._teardown()
self.volumes._teardown()
# We need to close the underlying APIClient explicitly to avoid
# ResourceWarnings from unclosed H... | [
"def",
"teardown",
"(",
"self",
")",
":",
"self",
".",
"containers",
".",
"_teardown",
"(",
")",
"self",
".",
"networks",
".",
"_teardown",
"(",
")",
"self",
".",
"volumes",
".",
"_teardown",
"(",
")",
"# We need to close the underlying APIClient explicitly to a... | Clean up all resources when we're done with them. | [
"Clean",
"up",
"all",
"resources",
"when",
"we",
"re",
"done",
"with",
"them",
"."
] | python | train | 32.636364 |
pymc-devs/pymc | pymc/Matplot.py | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/Matplot.py#L314-L381 | def plotwrapper(f):
"""
This decorator allows for PyMC arguments of various types to be passed to
the plotting functions. It identifies the type of object and locates its
trace(s), then passes the data to the wrapped plotting function.
"""
def wrapper(pymc_obj, *args, **kwargs):
start ... | [
"def",
"plotwrapper",
"(",
"f",
")",
":",
"def",
"wrapper",
"(",
"pymc_obj",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"start",
"=",
"0",
"if",
"'start'",
"in",
"kwargs",
":",
"start",
"=",
"kwargs",
".",
"pop",
"(",
"'start'",
")",
"#... | This decorator allows for PyMC arguments of various types to be passed to
the plotting functions. It identifies the type of object and locates its
trace(s), then passes the data to the wrapped plotting function. | [
"This",
"decorator",
"allows",
"for",
"PyMC",
"arguments",
"of",
"various",
"types",
"to",
"be",
"passed",
"to",
"the",
"plotting",
"functions",
".",
"It",
"identifies",
"the",
"type",
"of",
"object",
"and",
"locates",
"its",
"trace",
"(",
"s",
")",
"then"... | python | train | 32.426471 |
ansible/molecule | molecule/command/init/role.py | https://github.com/ansible/molecule/blob/766dc35b0b0ce498cd5e3a62b40f828742d0d08c/molecule/command/init/role.py#L56-L93 | def execute(self):
"""
Execute the actions necessary to perform a `molecule init role` and
returns None.
:return: None
"""
role_name = self._command_args['role_name']
role_directory = os.getcwd()
msg = 'Initializing new role {}...'.format(role_name)
... | [
"def",
"execute",
"(",
"self",
")",
":",
"role_name",
"=",
"self",
".",
"_command_args",
"[",
"'role_name'",
"]",
"role_directory",
"=",
"os",
".",
"getcwd",
"(",
")",
"msg",
"=",
"'Initializing new role {}...'",
".",
"format",
"(",
"role_name",
")",
"LOG",
... | Execute the actions necessary to perform a `molecule init role` and
returns None.
:return: None | [
"Execute",
"the",
"actions",
"necessary",
"to",
"perform",
"a",
"molecule",
"init",
"role",
"and",
"returns",
"None",
"."
] | python | train | 39 |
osrg/ryu | ryu/services/protocols/bgp/core_managers/table_manager.py | https://github.com/osrg/ryu/blob/6f906e72c92e10bd0264c9b91a2f7bb85b97780c/ryu/services/protocols/bgp/core_managers/table_manager.py#L372-L385 | def get_vpnv4fs_table(self):
"""Returns global VPNv4 Flow Specification table.
Creates the table if it does not exist.
"""
vpnv4fs_table = self._global_tables.get(RF_VPNv4_FLOWSPEC)
# Lazy initialization of the table.
if not vpnv4fs_table:
vpnv4fs_table = VPN... | [
"def",
"get_vpnv4fs_table",
"(",
"self",
")",
":",
"vpnv4fs_table",
"=",
"self",
".",
"_global_tables",
".",
"get",
"(",
"RF_VPNv4_FLOWSPEC",
")",
"# Lazy initialization of the table.",
"if",
"not",
"vpnv4fs_table",
":",
"vpnv4fs_table",
"=",
"VPNv4FlowSpecTable",
"("... | Returns global VPNv4 Flow Specification table.
Creates the table if it does not exist. | [
"Returns",
"global",
"VPNv4",
"Flow",
"Specification",
"table",
"."
] | python | train | 40.857143 |
GoogleCloudPlatform/appengine-mapreduce | python/src/mapreduce/input_readers.py | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/input_readers.py#L1794-L1804 | def to_json(self):
"""Returns an input shard state for the remaining inputs.
Returns:
A json-izable version of the remaining InputReader.
"""
return {self.BLOB_KEY_PARAM: self._blob_key,
self.START_FILE_INDEX_PARAM: self._start_file_index,
self.END_FILE_INDEX_PARAM: self.... | [
"def",
"to_json",
"(",
"self",
")",
":",
"return",
"{",
"self",
".",
"BLOB_KEY_PARAM",
":",
"self",
".",
"_blob_key",
",",
"self",
".",
"START_FILE_INDEX_PARAM",
":",
"self",
".",
"_start_file_index",
",",
"self",
".",
"END_FILE_INDEX_PARAM",
":",
"self",
".... | Returns an input shard state for the remaining inputs.
Returns:
A json-izable version of the remaining InputReader. | [
"Returns",
"an",
"input",
"shard",
"state",
"for",
"the",
"remaining",
"inputs",
"."
] | python | train | 34.363636 |
tomplus/kubernetes_asyncio | kubernetes_asyncio/client/api/core_v1_api.py | https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/client/api/core_v1_api.py#L4143-L4166 | def connect_post_namespaced_pod_proxy_with_path(self, name, namespace, path, **kwargs): # noqa: E501
"""connect_post_namespaced_pod_proxy_with_path # noqa: E501
connect POST requests to proxy of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asyn... | [
"def",
"connect_post_namespaced_pod_proxy_with_path",
"(",
"self",
",",
"name",
",",
"namespace",
",",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'as... | connect_post_namespaced_pod_proxy_with_path # noqa: E501
connect POST requests to proxy of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_post_namespaced_pod_proxy_with... | [
"connect_post_namespaced_pod_proxy_with_path",
"#",
"noqa",
":",
"E501"
] | python | train | 56.291667 |
loli/medpy | medpy/features/utilities.py | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/features/utilities.py#L181-L221 | def join(*vectors):
r"""
Takes an arbitrary number of aligned vectors of the same length and combines
them into a single vector (vertically).
E.g. taking two 100-sample feature vectors of once 5 and once 7 features, a 100x12
feature vector is created and returned.
The feature vectors ... | [
"def",
"join",
"(",
"*",
"vectors",
")",
":",
"# check supplied arguments",
"if",
"len",
"(",
"vectors",
")",
"<",
"2",
":",
"return",
"vectors",
"[",
"0",
"]",
"# process supplied arguments",
"vectors",
"=",
"list",
"(",
"vectors",
")",
"for",
"i",
"in",
... | r"""
Takes an arbitrary number of aligned vectors of the same length and combines
them into a single vector (vertically).
E.g. taking two 100-sample feature vectors of once 5 and once 7 features, a 100x12
feature vector is created and returned.
The feature vectors are expected to have the... | [
"r",
"Takes",
"an",
"arbitrary",
"number",
"of",
"aligned",
"vectors",
"of",
"the",
"same",
"length",
"and",
"combines",
"them",
"into",
"a",
"single",
"vector",
"(",
"vertically",
")",
".",
"E",
".",
"g",
".",
"taking",
"two",
"100",
"-",
"sample",
"f... | python | train | 27.95122 |
Kortemme-Lab/klab | klab/bio/ligand.py | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/ligand.py#L318-L326 | def parse_pdb_ligand_info(self, pdb_ligand_info):
'''This only parses the ligand type as all the other information should be in the .cif file. The XML file has
proper capitalization whereas the .cif file uses all caps for the ligand type.'''
mtchs = re.findall('(<ligand.*?</ligand>)', pdb_lig... | [
"def",
"parse_pdb_ligand_info",
"(",
"self",
",",
"pdb_ligand_info",
")",
":",
"mtchs",
"=",
"re",
".",
"findall",
"(",
"'(<ligand.*?</ligand>)'",
",",
"pdb_ligand_info",
",",
"re",
".",
"DOTALL",
")",
"for",
"m",
"in",
"mtchs",
":",
"if",
"m",
".",
"upper... | This only parses the ligand type as all the other information should be in the .cif file. The XML file has
proper capitalization whereas the .cif file uses all caps for the ligand type. | [
"This",
"only",
"parses",
"the",
"ligand",
"type",
"as",
"all",
"the",
"other",
"information",
"should",
"be",
"in",
"the",
".",
"cif",
"file",
".",
"The",
"XML",
"file",
"has",
"proper",
"capitalization",
"whereas",
"the",
".",
"cif",
"file",
"uses",
"a... | python | train | 68.666667 |
ethereum/eth-abi | eth_abi/registry.py | https://github.com/ethereum/eth-abi/blob/0a5cab0bdeae30b77efa667379427581784f1707/eth_abi/registry.py#L433-L439 | def unregister(self, label: str) -> None:
"""
Unregisters the entries in the encoder and decoder registries which
have the label ``label``.
"""
self.unregister_encoder(label)
self.unregister_decoder(label) | [
"def",
"unregister",
"(",
"self",
",",
"label",
":",
"str",
")",
"->",
"None",
":",
"self",
".",
"unregister_encoder",
"(",
"label",
")",
"self",
".",
"unregister_decoder",
"(",
"label",
")"
] | Unregisters the entries in the encoder and decoder registries which
have the label ``label``. | [
"Unregisters",
"the",
"entries",
"in",
"the",
"encoder",
"and",
"decoder",
"registries",
"which",
"have",
"the",
"label",
"label",
"."
] | python | train | 35.285714 |
CyberReboot/vent | vent/helpers/templates.py | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/helpers/templates.py#L37-L43 | def option(self, section, option):
""" Returns the value of the option """
if self.config.has_section(section):
if self.config.has_option(section, option):
return (True, self.config.get(section, option))
return (False, 'Option: ' + option + ' does not exist')
... | [
"def",
"option",
"(",
"self",
",",
"section",
",",
"option",
")",
":",
"if",
"self",
".",
"config",
".",
"has_section",
"(",
"section",
")",
":",
"if",
"self",
".",
"config",
".",
"has_option",
"(",
"section",
",",
"option",
")",
":",
"return",
"(",
... | Returns the value of the option | [
"Returns",
"the",
"value",
"of",
"the",
"option"
] | python | train | 53.571429 |
marazt/object-mapper | mapper/casedict.py | https://github.com/marazt/object-mapper/blob/b02c6d68c5bf86462aa8080aff3e93b133afd43e/mapper/casedict.py#L56-L71 | def get(self, key, default=_sentinel):
"""
Gets the value from the key.
If the key doesn't exist, the default value is returned, otherwise None.
:param key: The key
:param default: The default value
:return: The value
"""
tup = self._data.get(key.lower())... | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"default",
"=",
"_sentinel",
")",
":",
"tup",
"=",
"self",
".",
"_data",
".",
"get",
"(",
"key",
".",
"lower",
"(",
")",
")",
"if",
"tup",
"is",
"not",
"None",
":",
"return",
"tup",
"[",
"1",
"]",
"... | Gets the value from the key.
If the key doesn't exist, the default value is returned, otherwise None.
:param key: The key
:param default: The default value
:return: The value | [
"Gets",
"the",
"value",
"from",
"the",
"key",
".",
"If",
"the",
"key",
"doesn",
"t",
"exist",
"the",
"default",
"value",
"is",
"returned",
"otherwise",
"None",
"."
] | python | valid | 28.9375 |
fabric-bolt/fabric-bolt | fabric_bolt/projects/models.py | https://github.com/fabric-bolt/fabric-bolt/blob/0f434783026f1b9ce16a416fa496d76921fe49ca/fabric_bolt/projects/models.py#L320-L332 | def get_next_input(self):
"""
Returns the next line of input
:return: string of input
"""
# TODO: could override input if we get input coming in at the same time
all_input = Deployment.objects.get(pk=self.id).input or ''
lines = all_input.splitlines()
fir... | [
"def",
"get_next_input",
"(",
"self",
")",
":",
"# TODO: could override input if we get input coming in at the same time",
"all_input",
"=",
"Deployment",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"self",
".",
"id",
")",
".",
"input",
"or",
"''",
"lines",
"=",
... | Returns the next line of input
:return: string of input | [
"Returns",
"the",
"next",
"line",
"of",
"input",
":",
"return",
":",
"string",
"of",
"input"
] | python | train | 38.846154 |
abe-winter/pg13-py | pg13/treepath.py | https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/treepath.py#L9-L14 | def child(self,index):
"helper for __getitem__/__setitem__"
if isinstance(index,tuple):
attr,i = index
return getattr(self,attr)[i]
else: return getattr(self,index) | [
"def",
"child",
"(",
"self",
",",
"index",
")",
":",
"if",
"isinstance",
"(",
"index",
",",
"tuple",
")",
":",
"attr",
",",
"i",
"=",
"index",
"return",
"getattr",
"(",
"self",
",",
"attr",
")",
"[",
"i",
"]",
"else",
":",
"return",
"getattr",
"(... | helper for __getitem__/__setitem__ | [
"helper",
"for",
"__getitem__",
"/",
"__setitem__"
] | python | train | 30.5 |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_keras2_converter.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_keras2_converter.py#L117-L131 | def _get_layer_converter_fn(layer, add_custom_layers = False):
"""Get the right converter function for Keras
"""
layer_type = type(layer)
if layer_type in _KERAS_LAYER_REGISTRY:
convert_func = _KERAS_LAYER_REGISTRY[layer_type]
if convert_func is _layers2.convert_activation:
a... | [
"def",
"_get_layer_converter_fn",
"(",
"layer",
",",
"add_custom_layers",
"=",
"False",
")",
":",
"layer_type",
"=",
"type",
"(",
"layer",
")",
"if",
"layer_type",
"in",
"_KERAS_LAYER_REGISTRY",
":",
"convert_func",
"=",
"_KERAS_LAYER_REGISTRY",
"[",
"layer_type",
... | Get the right converter function for Keras | [
"Get",
"the",
"right",
"converter",
"function",
"for",
"Keras"
] | python | train | 40.133333 |
andy29485/embypy | embypy/objects/object.py | https://github.com/andy29485/embypy/blob/cde658d380965caaf4789d4d182d045b0346797b/embypy/objects/object.py#L249-L272 | async def update(self, fields=''):
'''reload object info from emby
|coro|
Parameters
----------
fields : str
additional fields to request when updating
See Also
--------
refresh : same thing
send :
post :
'''
path = 'Users/{{UserId}}/Items/{}'.format(self.i... | [
"async",
"def",
"update",
"(",
"self",
",",
"fields",
"=",
"''",
")",
":",
"path",
"=",
"'Users/{{UserId}}/Items/{}'",
".",
"format",
"(",
"self",
".",
"id",
")",
"info",
"=",
"await",
"self",
".",
"connector",
".",
"getJson",
"(",
"path",
",",
"remote... | reload object info from emby
|coro|
Parameters
----------
fields : str
additional fields to request when updating
See Also
--------
refresh : same thing
send :
post : | [
"reload",
"object",
"info",
"from",
"emby"
] | python | train | 22.791667 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.