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 |
|---|---|---|---|---|---|---|---|---|---|
saltstack/salt | salt/auth/file.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/file.py#L193-L206 | def _htpasswd(username, password, **kwargs):
'''
Provide authentication via Apache-style htpasswd files
'''
from passlib.apache import HtpasswdFile
pwfile = HtpasswdFile(kwargs['filename'])
# passlib below version 1.6 uses 'verify' function instead of 'check_password'
if salt.utils.versio... | [
"def",
"_htpasswd",
"(",
"username",
",",
"password",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"passlib",
".",
"apache",
"import",
"HtpasswdFile",
"pwfile",
"=",
"HtpasswdFile",
"(",
"kwargs",
"[",
"'filename'",
"]",
")",
"# passlib below version 1.6 uses 'ver... | Provide authentication via Apache-style htpasswd files | [
"Provide",
"authentication",
"via",
"Apache",
"-",
"style",
"htpasswd",
"files"
] | python | train | 34 |
LionelAuroux/pyrser | pyrser/ast/state.py | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/ast/state.py#L92-L99 | def to_png_file(self, fname: str):
"""
write a '.png' file.
"""
cmd = pipes.Template()
cmd.append('dot -Tpng > %s' % fname, '-.')
with cmd.open('pipefile', 'w') as f:
f.write(self.to_dot()) | [
"def",
"to_png_file",
"(",
"self",
",",
"fname",
":",
"str",
")",
":",
"cmd",
"=",
"pipes",
".",
"Template",
"(",
")",
"cmd",
".",
"append",
"(",
"'dot -Tpng > %s'",
"%",
"fname",
",",
"'-.'",
")",
"with",
"cmd",
".",
"open",
"(",
"'pipefile'",
",",
... | write a '.png' file. | [
"write",
"a",
".",
"png",
"file",
"."
] | python | test | 30.25 |
webrecorder/pywb | pywb/apps/frontendapp.py | https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/apps/frontendapp.py#L641-L666 | def load(self, coll):
"""Load and receive the metadata associated with a collection.
If the metadata for the collection is not cached yet its metadata file is read in and stored.
If the cache has seen the collection before the mtime of the metadata file is checked and if it is more recent
... | [
"def",
"load",
"(",
"self",
",",
"coll",
")",
":",
"path",
"=",
"self",
".",
"template_str",
".",
"format",
"(",
"coll",
"=",
"coll",
")",
"try",
":",
"mtime",
"=",
"os",
".",
"path",
".",
"getmtime",
"(",
"path",
")",
"obj",
"=",
"self",
".",
... | Load and receive the metadata associated with a collection.
If the metadata for the collection is not cached yet its metadata file is read in and stored.
If the cache has seen the collection before the mtime of the metadata file is checked and if it is more recent
than the cached time, the cach... | [
"Load",
"and",
"receive",
"the",
"metadata",
"associated",
"with",
"a",
"collection",
"."
] | python | train | 36.038462 |
svartalf/python-2gis | dgis/__init__.py | https://github.com/svartalf/python-2gis/blob/6eccd6073c99494b7abf20b38a5455cbd55d6420/dgis/__init__.py#L89-L109 | def search_in_rubric(self, **kwargs):
"""Firms search in rubric
http://api.2gis.ru/doc/firms/searches/searchinrubric/
"""
point = kwargs.pop('point', False)
if point:
kwargs['point'] = '%s,%s' % point
bound = kwargs.pop('bound', False)
if bound:
... | [
"def",
"search_in_rubric",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"point",
"=",
"kwargs",
".",
"pop",
"(",
"'point'",
",",
"False",
")",
"if",
"point",
":",
"kwargs",
"[",
"'point'",
"]",
"=",
"'%s,%s'",
"%",
"point",
"bound",
"=",
"kwargs",... | Firms search in rubric
http://api.2gis.ru/doc/firms/searches/searchinrubric/ | [
"Firms",
"search",
"in",
"rubric"
] | python | train | 28.285714 |
larsmans/seqlearn | doc/hash-tree.py | https://github.com/larsmans/seqlearn/blob/32d4bfaebdd877733f180ea6072e8fc1266bc559/doc/hash-tree.py#L35-L45 | def hash_dir(path):
"""Write directory at path to Git index, return its SHA1 as a string."""
dir_hash = {}
for root, dirs, files in os.walk(path, topdown=False):
f_hash = ((f, hash_file(join(root, f))) for f in files)
d_hash = ((d, dir_hash[join(root, d)]) for d in dirs)
# split+joi... | [
"def",
"hash_dir",
"(",
"path",
")",
":",
"dir_hash",
"=",
"{",
"}",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"path",
",",
"topdown",
"=",
"False",
")",
":",
"f_hash",
"=",
"(",
"(",
"f",
",",
"hash_file",
"(",
"j... | Write directory at path to Git index, return its SHA1 as a string. | [
"Write",
"directory",
"at",
"path",
"to",
"Git",
"index",
"return",
"its",
"SHA1",
"as",
"a",
"string",
"."
] | python | train | 40.727273 |
blockstack/blockstack-core | blockstack/lib/operations/namespacereveal.py | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/operations/namespacereveal.py#L66-L107 | def namespacereveal_sanity_check( namespace_id, version, lifetime, coeff, base, bucket_exponents, nonalpha_discount, no_vowel_discount ):
"""
Verify the validity of a namespace reveal.
Return True if valid
Raise an Exception if not valid.
"""
# sanity check
if not is_b40( namespace_id ) or "+" in ... | [
"def",
"namespacereveal_sanity_check",
"(",
"namespace_id",
",",
"version",
",",
"lifetime",
",",
"coeff",
",",
"base",
",",
"bucket_exponents",
",",
"nonalpha_discount",
",",
"no_vowel_discount",
")",
":",
"# sanity check ",
"if",
"not",
"is_b40",
"(",
"namespace_i... | Verify the validity of a namespace reveal.
Return True if valid
Raise an Exception if not valid. | [
"Verify",
"the",
"validity",
"of",
"a",
"namespace",
"reveal",
".",
"Return",
"True",
"if",
"valid",
"Raise",
"an",
"Exception",
"if",
"not",
"valid",
"."
] | python | train | 45.309524 |
sernst/cauldron | cauldron/cli/commands/run/__init__.py | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/cli/commands/run/__init__.py#L229-L322 | def run_local(
context: cli.CommandContext,
project: projects.Project,
project_steps: typing.List[projects.ProjectStep],
force: bool,
continue_after: bool,
single_step: bool,
limit: int,
print_status: bool,
skip_library_reload: bool = False
) -> en... | [
"def",
"run_local",
"(",
"context",
":",
"cli",
".",
"CommandContext",
",",
"project",
":",
"projects",
".",
"Project",
",",
"project_steps",
":",
"typing",
".",
"List",
"[",
"projects",
".",
"ProjectStep",
"]",
",",
"force",
":",
"bool",
",",
"continue_af... | Execute the run command locally within this cauldron environment
:param context:
:param project:
:param project_steps:
:param force:
:param continue_after:
:param single_step:
:param limit:
:param print_status:
:param skip_library_reload:
Whether or not to skip reloading all... | [
"Execute",
"the",
"run",
"command",
"locally",
"within",
"this",
"cauldron",
"environment"
] | python | train | 29.542553 |
IAMconsortium/pyam | pyam/iiasa.py | https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/iiasa.py#L256-L286 | def read_iiasa(name, meta=False, **kwargs):
"""
Query an IIASA database. See Connection.query() for more documentation
Parameters
----------
name : str
A valid IIASA database name, see pyam.iiasa.valid_connection_names()
meta : bool or list of strings
If not False, also include ... | [
"def",
"read_iiasa",
"(",
"name",
",",
"meta",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"Connection",
"(",
"name",
")",
"# data",
"df",
"=",
"conn",
".",
"query",
"(",
"*",
"*",
"kwargs",
")",
"df",
"=",
"IamDataFrame",
"(",
... | Query an IIASA database. See Connection.query() for more documentation
Parameters
----------
name : str
A valid IIASA database name, see pyam.iiasa.valid_connection_names()
meta : bool or list of strings
If not False, also include metadata indicators (or subset if provided).
kwargs ... | [
"Query",
"an",
"IIASA",
"database",
".",
"See",
"Connection",
".",
"query",
"()",
"for",
"more",
"documentation"
] | python | train | 33.870968 |
henzk/featuremonkey | featuremonkey/composer.py | https://github.com/henzk/featuremonkey/blob/e44414fc68427bcd71ad33ec2d816da0dd78eefa/featuremonkey/composer.py#L275-L320 | def select(self, *features):
"""
selects the features given as string
e.g
passing 'hello' and 'world' will result in imports of
'hello' and 'world'. Then, if possible 'hello.feature'
and 'world.feature' are imported and select is called
in each feature module.
... | [
"def",
"select",
"(",
"self",
",",
"*",
"features",
")",
":",
"for",
"feature_name",
"in",
"features",
":",
"feature_module",
"=",
"importlib",
".",
"import_module",
"(",
"feature_name",
")",
"# if available, import feature.py and select the feature",
"try",
":",
"f... | selects the features given as string
e.g
passing 'hello' and 'world' will result in imports of
'hello' and 'world'. Then, if possible 'hello.feature'
and 'world.feature' are imported and select is called
in each feature module. | [
"selects",
"the",
"features",
"given",
"as",
"string",
"e",
".",
"g",
"passing",
"hello",
"and",
"world",
"will",
"result",
"in",
"imports",
"of",
"hello",
"and",
"world",
".",
"Then",
"if",
"possible",
"hello",
".",
"feature",
"and",
"world",
".",
"feat... | python | train | 43.608696 |
saltstack/salt | salt/modules/zypperpkg.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L729-L858 | def list_pkgs(versions_as_list=False, root=None, includes=None, **kwargs):
'''
List the packages currently installed as a dict. By default, the dict
contains versions as a comma separated string::
{'<package_name>': '<version>[,<version>...]'}
versions_as_list:
If set to true, the vers... | [
"def",
"list_pkgs",
"(",
"versions_as_list",
"=",
"False",
",",
"root",
"=",
"None",
",",
"includes",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"versions_as_list",
"=",
"salt",
".",
"utils",
".",
"data",
".",
"is_true",
"(",
"versions_as_list",
")"... | List the packages currently installed as a dict. By default, the dict
contains versions as a comma separated string::
{'<package_name>': '<version>[,<version>...]'}
versions_as_list:
If set to true, the versions are provided as a list
{'<package_name>': ['<version>', '<version>']}
... | [
"List",
"the",
"packages",
"currently",
"installed",
"as",
"a",
"dict",
".",
"By",
"default",
"the",
"dict",
"contains",
"versions",
"as",
"a",
"comma",
"separated",
"string",
"::"
] | python | train | 34.361538 |
log2timeline/plaso | plaso/analysis/viper.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/analysis/viper.py#L202-L214 | def SetProtocol(self, protocol):
"""Sets the protocol that will be used to query Viper.
Args:
protocol (str): protocol to use to query Viper. Either 'http' or 'https'.
Raises:
ValueError: If an invalid protocol is selected.
"""
protocol = protocol.lower().strip()
if protocol not in... | [
"def",
"SetProtocol",
"(",
"self",
",",
"protocol",
")",
":",
"protocol",
"=",
"protocol",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"if",
"protocol",
"not",
"in",
"[",
"'http'",
",",
"'https'",
"]",
":",
"raise",
"ValueError",
"(",
"'Invalid pro... | Sets the protocol that will be used to query Viper.
Args:
protocol (str): protocol to use to query Viper. Either 'http' or 'https'.
Raises:
ValueError: If an invalid protocol is selected. | [
"Sets",
"the",
"protocol",
"that",
"will",
"be",
"used",
"to",
"query",
"Viper",
"."
] | python | train | 33.692308 |
sorgerlab/indra | indra/tools/assemble_corpus.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/assemble_corpus.py#L122-L201 | def merge_groundings(stmts_in):
"""Gather and merge original grounding information from evidences.
Each Statement's evidences are traversed to find original grounding
information. These groundings are then merged into an overall consensus
grounding dict with as much detail as possible.
The current... | [
"def",
"merge_groundings",
"(",
"stmts_in",
")",
":",
"def",
"surface_grounding",
"(",
"stmt",
")",
":",
"# Find the \"best\" grounding for a given concept and its evidences",
"# and surface that",
"for",
"idx",
",",
"concept",
"in",
"enumerate",
"(",
"stmt",
".",
"agen... | Gather and merge original grounding information from evidences.
Each Statement's evidences are traversed to find original grounding
information. These groundings are then merged into an overall consensus
grounding dict with as much detail as possible.
The current implementation is only applicable to S... | [
"Gather",
"and",
"merge",
"original",
"grounding",
"information",
"from",
"evidences",
"."
] | python | train | 45.425 |
jleinonen/pytmatrix | pytmatrix/scatter.py | https://github.com/jleinonen/pytmatrix/blob/8803507fe5332786feab105fa74acf63e7121718/pytmatrix/scatter.py#L100-L133 | def ext_xsect(scatterer, h_pol=True):
"""Extinction cross section for the current setup, with polarization.
Args:
scatterer: a Scatterer instance.
h_pol: If True (default), use horizontal polarization.
If False, use vertical polarization.
Returns:
The extinction cross s... | [
"def",
"ext_xsect",
"(",
"scatterer",
",",
"h_pol",
"=",
"True",
")",
":",
"if",
"scatterer",
".",
"psd_integrator",
"is",
"not",
"None",
":",
"try",
":",
"return",
"scatterer",
".",
"psd_integrator",
".",
"get_angular_integrated",
"(",
"scatterer",
".",
"ps... | Extinction cross section for the current setup, with polarization.
Args:
scatterer: a Scatterer instance.
h_pol: If True (default), use horizontal polarization.
If False, use vertical polarization.
Returns:
The extinction cross section. | [
"Extinction",
"cross",
"section",
"for",
"the",
"current",
"setup",
"with",
"polarization",
"."
] | python | train | 29.941176 |
log2timeline/dfvfs | dfvfs/vfs/zip_file_system.py | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/zip_file_system.py#L80-L111 | def FileEntryExistsByPathSpec(self, path_spec):
"""Determines if a file entry for a path specification exists.
Args:
path_spec (PathSpec): path specification of the file entry.
Returns:
bool: True if the file entry exists.
"""
location = getattr(path_spec, 'location', None)
if (lo... | [
"def",
"FileEntryExistsByPathSpec",
"(",
"self",
",",
"path_spec",
")",
":",
"location",
"=",
"getattr",
"(",
"path_spec",
",",
"'location'",
",",
"None",
")",
"if",
"(",
"location",
"is",
"None",
"or",
"not",
"location",
".",
"startswith",
"(",
"self",
".... | Determines if a file entry for a path specification exists.
Args:
path_spec (PathSpec): path specification of the file entry.
Returns:
bool: True if the file entry exists. | [
"Determines",
"if",
"a",
"file",
"entry",
"for",
"a",
"path",
"specification",
"exists",
"."
] | python | train | 25.4375 |
saltstack/salt | salt/modules/boto_lambda.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_lambda.py#L761-L785 | def describe_alias(FunctionName, Name, region=None, key=None,
keyid=None, profile=None):
'''
Given a function name and alias name describe the properties of the alias.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_... | [
"def",
"describe_alias",
"(",
"FunctionName",
",",
"Name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"alias",
"=",
"_find_alias",
"(",
"FunctionName",
",",
"Name",... | Given a function name and alias name describe the properties of the alias.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_lambda.describe_alias myalias | [
"Given",
"a",
"function",
"name",
"and",
"alias",
"name",
"describe",
"the",
"properties",
"of",
"the",
"alias",
"."
] | python | train | 30.88 |
romansalin/django-seo2 | djangoseo/utils.py | https://github.com/romansalin/django-seo2/blob/f788699a88e286ab9a698759d9b42f57852865d8/djangoseo/utils.py#L116-L122 | def _get_seo_content_types(seo_models):
"""Returns a list of content types from the models defined in settings."""
try:
return [ContentType.objects.get_for_model(m).id for m in seo_models]
except Exception: # previously caught DatabaseError
# Return an empty list if this is called too early... | [
"def",
"_get_seo_content_types",
"(",
"seo_models",
")",
":",
"try",
":",
"return",
"[",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"m",
")",
".",
"id",
"for",
"m",
"in",
"seo_models",
"]",
"except",
"Exception",
":",
"# previously caught Databa... | Returns a list of content types from the models defined in settings. | [
"Returns",
"a",
"list",
"of",
"content",
"types",
"from",
"the",
"models",
"defined",
"in",
"settings",
"."
] | python | train | 47.428571 |
mk-fg/python-pulse-control | pulsectl/pulsectl.py | https://github.com/mk-fg/python-pulse-control/blob/902d5e9e5591b89c356e5194a370212e23fb0e93/pulsectl/pulsectl.py#L805-L815 | def set_poll_func(self, func, func_err_handler=None):
'''Can be used to integrate pulse client into existing eventloop.
Function will be passed a list of pollfd structs and timeout value (seconds, float),
which it is responsible to use and modify (set poll flags) accordingly,
returning int value >= 0 with ... | [
"def",
"set_poll_func",
"(",
"self",
",",
"func",
",",
"func_err_handler",
"=",
"None",
")",
":",
"if",
"not",
"func_err_handler",
":",
"func_err_handler",
"=",
"traceback",
".",
"print_exception",
"self",
".",
"_pa_poll_cb",
"=",
"c",
".",
"PA_POLL_FUNC_T",
"... | Can be used to integrate pulse client into existing eventloop.
Function will be passed a list of pollfd structs and timeout value (seconds, float),
which it is responsible to use and modify (set poll flags) accordingly,
returning int value >= 0 with number of fds that had any new events within timeout.
fu... | [
"Can",
"be",
"used",
"to",
"integrate",
"pulse",
"client",
"into",
"existing",
"eventloop",
".",
"Function",
"will",
"be",
"passed",
"a",
"list",
"of",
"pollfd",
"structs",
"and",
"timeout",
"value",
"(",
"seconds",
"float",
")",
"which",
"it",
"is",
"resp... | python | train | 72.272727 |
QualiSystems/cloudshell-networking-devices | cloudshell/devices/standards/networking/configuration_attributes_structure.py | https://github.com/QualiSystems/cloudshell-networking-devices/blob/009aab33edb30035b52fe10dbb91db61c95ba4d9/cloudshell/devices/standards/networking/configuration_attributes_structure.py#L213-L233 | def create_networking_resource_from_context(shell_name, supported_os, context):
"""
Creates an instance of Networking Resource by given context
:param shell_name: Shell Name
:type shell_name: str
:param supported_os: list of supported OS
:type supported_os: list
:param context: cloudshell.sh... | [
"def",
"create_networking_resource_from_context",
"(",
"shell_name",
",",
"supported_os",
",",
"context",
")",
":",
"result",
"=",
"GenericNetworkingResource",
"(",
"shell_name",
"=",
"shell_name",
",",
"name",
"=",
"context",
".",
"resource",
".",
"name",
",",
"s... | Creates an instance of Networking Resource by given context
:param shell_name: Shell Name
:type shell_name: str
:param supported_os: list of supported OS
:type supported_os: list
:param context: cloudshell.shell.core.driver_context.ResourceCommandContext
:type context: cloudshell.shell.core.driv... | [
"Creates",
"an",
"instance",
"of",
"Networking",
"Resource",
"by",
"given",
"context",
":",
"param",
"shell_name",
":",
"Shell",
"Name",
":",
"type",
"shell_name",
":",
"str",
":",
"param",
"supported_os",
":",
"list",
"of",
"supported",
"OS",
":",
"type",
... | python | train | 38.904762 |
secdev/scapy | scapy/layers/ntp.py | https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/layers/ntp.py#L199-L208 | def pre_dissect(self, s):
"""
Check that the payload is long enough to build a NTP packet.
"""
length = len(s)
if length < _NTP_PACKET_MIN_SIZE:
err = " ({}".format(length) + " is < _NTP_PACKET_MIN_SIZE "
err += "({})).".format(_NTP_PACKET_MIN_SIZE)
... | [
"def",
"pre_dissect",
"(",
"self",
",",
"s",
")",
":",
"length",
"=",
"len",
"(",
"s",
")",
"if",
"length",
"<",
"_NTP_PACKET_MIN_SIZE",
":",
"err",
"=",
"\" ({}\"",
".",
"format",
"(",
"length",
")",
"+",
"\" is < _NTP_PACKET_MIN_SIZE \"",
"err",
"+=",
... | Check that the payload is long enough to build a NTP packet. | [
"Check",
"that",
"the",
"payload",
"is",
"long",
"enough",
"to",
"build",
"a",
"NTP",
"packet",
"."
] | python | train | 36.9 |
OpenKMIP/PyKMIP | kmip/core/messages/payloads/query.py | https://github.com/OpenKMIP/PyKMIP/blob/b51c5b044bd05f8c85a1d65d13a583a4d8fc1b0e/kmip/core/messages/payloads/query.py#L694-L882 | def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Read the data encoding the QueryResponsePayload object and decode it
into its constituent parts.
Args:
input_buffer (Stream): A data stream containing encoded object
data, supporting a... | [
"def",
"read",
"(",
"self",
",",
"input_buffer",
",",
"kmip_version",
"=",
"enums",
".",
"KMIPVersion",
".",
"KMIP_1_0",
")",
":",
"super",
"(",
"QueryResponsePayload",
",",
"self",
")",
".",
"read",
"(",
"input_buffer",
",",
"kmip_version",
"=",
"kmip_versi... | Read the data encoding the QueryResponsePayload object and decode it
into its constituent parts.
Args:
input_buffer (Stream): A data stream containing encoded object
data, supporting a read method; usually a BytearrayStream
object.
kmip_version (K... | [
"Read",
"the",
"data",
"encoding",
"the",
"QueryResponsePayload",
"object",
"and",
"decode",
"it",
"into",
"its",
"constituent",
"parts",
"."
] | python | test | 39.920635 |
475Cumulus/TBone | tbone/dispatch/signals.py | https://github.com/475Cumulus/TBone/blob/5a6672d8bbac449a0ab9e99560609f671fe84d4d/tbone/dispatch/signals.py#L58-L70 | async def send(self, sender, **kwargs):
''' send a signal from the sender to all connected receivers '''
if not self.receivers:
return []
responses = []
futures = []
for receiver in self._get_receivers(sender):
method = receiver()
if callable(m... | [
"async",
"def",
"send",
"(",
"self",
",",
"sender",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"receivers",
":",
"return",
"[",
"]",
"responses",
"=",
"[",
"]",
"futures",
"=",
"[",
"]",
"for",
"receiver",
"in",
"self",
".",
"_g... | send a signal from the sender to all connected receivers | [
"send",
"a",
"signal",
"from",
"the",
"sender",
"to",
"all",
"connected",
"receivers"
] | python | train | 37.538462 |
sassoo/goldman | goldman/deserializers/comma_sep.py | https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/deserializers/comma_sep.py#L51-L73 | def _parse_keys(row, line_num):
""" Perform some sanity checks on they keys
Each key in the row should not be named None cause
(that's an overrun). A key named `type` MUST be
present on the row & have a string value.
:param row: dict
:param line_num: int
"""
... | [
"def",
"_parse_keys",
"(",
"row",
",",
"line_num",
")",
":",
"link",
"=",
"'tools.ietf.org/html/rfc4180#section-2'",
"none_keys",
"=",
"[",
"key",
"for",
"key",
"in",
"row",
".",
"keys",
"(",
")",
"if",
"key",
"is",
"None",
"]",
"if",
"none_keys",
":",
"... | Perform some sanity checks on they keys
Each key in the row should not be named None cause
(that's an overrun). A key named `type` MUST be
present on the row & have a string value.
:param row: dict
:param line_num: int | [
"Perform",
"some",
"sanity",
"checks",
"on",
"they",
"keys"
] | python | train | 35.26087 |
openstack/quark | quark/tools/async_worker.py | https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/tools/async_worker.py#L99-L113 | def serve_rpc(self):
"""Launches configured # of workers per loaded plugin."""
if cfg.CONF.QUARK_ASYNC.rpc_workers < 1:
cfg.CONF.set_override('rpc_workers', 1, "QUARK_ASYNC")
try:
rpc = service.RpcWorker(self.plugins)
launcher = common_service.ProcessLauncher... | [
"def",
"serve_rpc",
"(",
"self",
")",
":",
"if",
"cfg",
".",
"CONF",
".",
"QUARK_ASYNC",
".",
"rpc_workers",
"<",
"1",
":",
"cfg",
".",
"CONF",
".",
"set_override",
"(",
"'rpc_workers'",
",",
"1",
",",
"\"QUARK_ASYNC\"",
")",
"try",
":",
"rpc",
"=",
... | Launches configured # of workers per loaded plugin. | [
"Launches",
"configured",
"#",
"of",
"workers",
"per",
"loaded",
"plugin",
"."
] | python | valid | 43.133333 |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/parallel/apps/baseapp.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/apps/baseapp.py#L202-L218 | def write_pid_file(self, overwrite=False):
"""Create a .pid file in the pid_dir with my pid.
This must be called after pre_construct, which sets `self.pid_dir`.
This raises :exc:`PIDFileError` if the pid file exists already.
"""
pid_file = os.path.join(self.profile_dir.pid_dir, ... | [
"def",
"write_pid_file",
"(",
"self",
",",
"overwrite",
"=",
"False",
")",
":",
"pid_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"profile_dir",
".",
"pid_dir",
",",
"self",
".",
"name",
"+",
"u'.pid'",
")",
"if",
"os",
".",
"path",
... | Create a .pid file in the pid_dir with my pid.
This must be called after pre_construct, which sets `self.pid_dir`.
This raises :exc:`PIDFileError` if the pid file exists already. | [
"Create",
"a",
".",
"pid",
"file",
"in",
"the",
"pid_dir",
"with",
"my",
"pid",
"."
] | python | test | 47 |
zetaops/zengine | zengine/middlewares.py | https://github.com/zetaops/zengine/blob/b5bc32d3b37bca799f8985be916f04528ac79e4a/zengine/middlewares.py#L26-L45 | def process_response(self, request, response, resource):
"""
Do response processing
"""
origin = request.get_header('Origin')
if not settings.DEBUG:
if origin in settings.ALLOWED_ORIGINS or not origin:
response.set_header('Access-Control-Allow-Origin',... | [
"def",
"process_response",
"(",
"self",
",",
"request",
",",
"response",
",",
"resource",
")",
":",
"origin",
"=",
"request",
".",
"get_header",
"(",
"'Origin'",
")",
"if",
"not",
"settings",
".",
"DEBUG",
":",
"if",
"origin",
"in",
"settings",
".",
"ALL... | Do response processing | [
"Do",
"response",
"processing"
] | python | train | 51.8 |
senaite/senaite.core | bika/lims/upgrade/v01_03_000.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/upgrade/v01_03_000.py#L2213-L2233 | def get_workflow_actions_for(brain_or_object):
"""Returns a list with the actions (transitions) supported by the workflows
the object pass in is bound to. Note it returns all actions, not only those
allowed for the object based on its current state and permissions.
"""
portal_type = api.get_portal_t... | [
"def",
"get_workflow_actions_for",
"(",
"brain_or_object",
")",
":",
"portal_type",
"=",
"api",
".",
"get_portal_type",
"(",
"brain_or_object",
")",
"actions",
"=",
"actions_by_type",
".",
"get",
"(",
"portal_type",
",",
"None",
")",
"if",
"actions",
":",
"retur... | Returns a list with the actions (transitions) supported by the workflows
the object pass in is bound to. Note it returns all actions, not only those
allowed for the object based on its current state and permissions. | [
"Returns",
"a",
"list",
"with",
"the",
"actions",
"(",
"transitions",
")",
"supported",
"by",
"the",
"workflows",
"the",
"object",
"pass",
"in",
"is",
"bound",
"to",
".",
"Note",
"it",
"returns",
"all",
"actions",
"not",
"only",
"those",
"allowed",
"for",
... | python | train | 41.142857 |
bcbio/bcbio-nextgen | bcbio/structural/__init__.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/__init__.py#L174-L187 | def run(samples, run_parallel, stage):
"""Run structural variation detection.
The stage indicates which level of structural variant calling to run.
- initial, callers that can be used in subsequent structural variation steps (cnvkit -> lumpy)
- standard, regular batch calling
- ensemble, post... | [
"def",
"run",
"(",
"samples",
",",
"run_parallel",
",",
"stage",
")",
":",
"to_process",
",",
"extras",
",",
"background",
"=",
"_batch_split_by_sv",
"(",
"samples",
",",
"stage",
")",
"processed",
"=",
"run_parallel",
"(",
"\"detect_sv\"",
",",
"(",
"[",
... | Run structural variation detection.
The stage indicates which level of structural variant calling to run.
- initial, callers that can be used in subsequent structural variation steps (cnvkit -> lumpy)
- standard, regular batch calling
- ensemble, post-calling, combine other callers or prioritize ... | [
"Run",
"structural",
"variation",
"detection",
"."
] | python | train | 54.642857 |
bio2bel/bio2bel | src/bio2bel/models.py | https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/models.py#L124-L131 | def count(cls, session: Optional[Session] = None) -> int:
"""Count all actions."""
if session is None:
session = _make_session()
count = session.query(cls).count()
session.close()
return count | [
"def",
"count",
"(",
"cls",
",",
"session",
":",
"Optional",
"[",
"Session",
"]",
"=",
"None",
")",
"->",
"int",
":",
"if",
"session",
"is",
"None",
":",
"session",
"=",
"_make_session",
"(",
")",
"count",
"=",
"session",
".",
"query",
"(",
"cls",
... | Count all actions. | [
"Count",
"all",
"actions",
"."
] | python | valid | 29.75 |
saltstack/salt | salt/modules/dockermod.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dockermod.py#L5651-L5684 | def restart(name, timeout=10):
'''
Restarts a container
name
Container name or ID
timeout : 10
Timeout in seconds after which the container will be killed (if it has
not yet gracefully shut down)
**RETURN DATA**
A dictionary will be returned, containing the following... | [
"def",
"restart",
"(",
"name",
",",
"timeout",
"=",
"10",
")",
":",
"ret",
"=",
"_change_state",
"(",
"name",
",",
"'restart'",
",",
"'running'",
",",
"timeout",
"=",
"timeout",
")",
"if",
"ret",
"[",
"'result'",
"]",
":",
"ret",
"[",
"'restarted'",
... | Restarts a container
name
Container name or ID
timeout : 10
Timeout in seconds after which the container will be killed (if it has
not yet gracefully shut down)
**RETURN DATA**
A dictionary will be returned, containing the following keys:
- ``status`` - A dictionary sho... | [
"Restarts",
"a",
"container"
] | python | train | 26.058824 |
google/grr | grr/core/grr_response_core/lib/rdfvalues/paths.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/core/grr_response_core/lib/rdfvalues/paths.py#L110-L123 | def Append(self, component=None, **kwarg):
"""Append a new pathspec component to this pathspec."""
if component is None:
component = self.__class__(**kwarg)
if self.HasField("pathtype"):
self.last.nested_path = component
else:
for k, v in iteritems(kwarg):
setattr(self, k, v)
... | [
"def",
"Append",
"(",
"self",
",",
"component",
"=",
"None",
",",
"*",
"*",
"kwarg",
")",
":",
"if",
"component",
"is",
"None",
":",
"component",
"=",
"self",
".",
"__class__",
"(",
"*",
"*",
"kwarg",
")",
"if",
"self",
".",
"HasField",
"(",
"\"pat... | Append a new pathspec component to this pathspec. | [
"Append",
"a",
"new",
"pathspec",
"component",
"to",
"this",
"pathspec",
"."
] | python | train | 26.428571 |
vecnet/vecnet.openmalaria | vecnet/openmalaria/scenario/interventions.py | https://github.com/vecnet/vecnet.openmalaria/blob/795bc9d1b81a6c664f14879edda7a7c41188e95a/vecnet/openmalaria/scenario/interventions.py#L182-L194 | def changeHS(self):
"""
Change health system interventions
https://github.com/SwissTPH/openmalaria/wiki/GeneratedSchema32Doc#change-health-system
Returns: list of HealthSystems together with timestep when they are applied
"""
health_systems = []
change_hs = self.e... | [
"def",
"changeHS",
"(",
"self",
")",
":",
"health_systems",
"=",
"[",
"]",
"change_hs",
"=",
"self",
".",
"et",
".",
"find",
"(",
"\"changeHS\"",
")",
"if",
"change_hs",
"is",
"None",
":",
"return",
"health_systems",
"for",
"health_system",
"in",
"change_h... | Change health system interventions
https://github.com/SwissTPH/openmalaria/wiki/GeneratedSchema32Doc#change-health-system
Returns: list of HealthSystems together with timestep when they are applied | [
"Change",
"health",
"system",
"interventions",
"https",
":",
"//",
"github",
".",
"com",
"/",
"SwissTPH",
"/",
"openmalaria",
"/",
"wiki",
"/",
"GeneratedSchema32Doc#change",
"-",
"health",
"-",
"system",
"Returns",
":",
"list",
"of",
"HealthSystems",
"together"... | python | train | 44.692308 |
DeepHorizons/iarm | iarm/arm_instructions/memory.py | https://github.com/DeepHorizons/iarm/blob/b913c9fd577b793a6bbced78b78a5d8d7cd88de4/iarm/arm_instructions/memory.py#L336-L357 | def PUSH(self, params):
"""
PUSH {RPushList}
Push to the stack from a list of registers
List must contain only low registers or LR
"""
# TODO what registers are allowed to PUSH to? Low registers and LR
# TODO PUSH should reverse the list, not POP
RPushLis... | [
"def",
"PUSH",
"(",
"self",
",",
"params",
")",
":",
"# TODO what registers are allowed to PUSH to? Low registers and LR",
"# TODO PUSH should reverse the list, not POP",
"RPushList",
"=",
"self",
".",
"get_one_parameter",
"(",
"r'\\s*{(.*)}(.*)'",
",",
"params",
")",
".",
... | PUSH {RPushList}
Push to the stack from a list of registers
List must contain only low registers or LR | [
"PUSH",
"{",
"RPushList",
"}"
] | python | train | 36.909091 |
m32/endesive | endesive/pdf/fpdf/fpdf.py | https://github.com/m32/endesive/blob/973091dc69847fe2df594c80ac9235a8d08460ff/endesive/pdf/fpdf/fpdf.py#L248-L306 | def add_page(self, orientation=''):
"Start a new page"
if(self.state==0):
self.open()
family=self.font_family
if self.underline:
style = self.font_style + 'U'
else:
style = self.font_style
size=self.font_size_pt
lw=self.line_wid... | [
"def",
"add_page",
"(",
"self",
",",
"orientation",
"=",
"''",
")",
":",
"if",
"(",
"self",
".",
"state",
"==",
"0",
")",
":",
"self",
".",
"open",
"(",
")",
"family",
"=",
"self",
".",
"font_family",
"if",
"self",
".",
"underline",
":",
"style",
... | Start a new page | [
"Start",
"a",
"new",
"page"
] | python | train | 27.457627 |
mdavidsaver/p4p | src/p4p/nt/__init__.py | https://github.com/mdavidsaver/p4p/blob/c5e45eac01edfdad9cc2857bc283c7f2695802b8/src/p4p/nt/__init__.py#L220-L238 | def unwrap(value):
"""Iterate an NTTable
:returns: An iterator yielding an OrderedDict for each column
"""
ret = []
# build lists of column names, and value
lbl, cols = [], []
for cname, cval in value.value.items():
lbl.append(cname)
cols... | [
"def",
"unwrap",
"(",
"value",
")",
":",
"ret",
"=",
"[",
"]",
"# build lists of column names, and value",
"lbl",
",",
"cols",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"cname",
",",
"cval",
"in",
"value",
".",
"value",
".",
"items",
"(",
")",
":",
"lbl",... | Iterate an NTTable
:returns: An iterator yielding an OrderedDict for each column | [
"Iterate",
"an",
"NTTable"
] | python | train | 28.105263 |
yatiml/yatiml | yatiml/helpers.py | https://github.com/yatiml/yatiml/blob/4f55c058b72388350f0af3076ac3ea9bc1c142b0/yatiml/helpers.py#L600-L604 | def require_mapping(self) -> None:
"""Require the node to be a mapping."""
if not isinstance(self.yaml_node, yaml.MappingNode):
raise RecognitionError(('{}{}A mapping is required here').format(
self.yaml_node.start_mark, os.linesep)) | [
"def",
"require_mapping",
"(",
"self",
")",
"->",
"None",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"yaml_node",
",",
"yaml",
".",
"MappingNode",
")",
":",
"raise",
"RecognitionError",
"(",
"(",
"'{}{}A mapping is required here'",
")",
".",
"format",
... | Require the node to be a mapping. | [
"Require",
"the",
"node",
"to",
"be",
"a",
"mapping",
"."
] | python | train | 54.6 |
inasafe/inasafe | safe/report/extractors/analysis_question.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/extractors/analysis_question.py#L11-L44 | def analysis_question_extractor(impact_report, component_metadata):
"""Extracting analysis question from the impact layer.
:param impact_report: the impact report that acts as a proxy to fetch
all the data that extractor needed
:type impact_report: safe.report.impact_report.ImpactReport
:param... | [
"def",
"analysis_question_extractor",
"(",
"impact_report",
",",
"component_metadata",
")",
":",
"multi_exposure",
"=",
"impact_report",
".",
"multi_exposure_impact_function",
"if",
"multi_exposure",
":",
"return",
"multi_exposure_analysis_question_extractor",
"(",
"impact_repo... | Extracting analysis question from the impact layer.
:param impact_report: the impact report that acts as a proxy to fetch
all the data that extractor needed
:type impact_report: safe.report.impact_report.ImpactReport
:param component_metadata: the component metadata. Used to obtain
informa... | [
"Extracting",
"analysis",
"question",
"from",
"the",
"impact",
"layer",
"."
] | python | train | 34.882353 |
Kaggle/kaggle-api | kaggle/models/dataset_new_request.py | https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/models/dataset_new_request.py#L194-L209 | def license_name(self, license_name):
"""Sets the license_name of this DatasetNewRequest.
The license that should be associated with the dataset # noqa: E501
:param license_name: The license_name of this DatasetNewRequest. # noqa: E501
:type: str
"""
allowed_values = ... | [
"def",
"license_name",
"(",
"self",
",",
"license_name",
")",
":",
"allowed_values",
"=",
"[",
"\"CC0-1.0\"",
",",
"\"CC-BY-SA-4.0\"",
",",
"\"GPL-2.0\"",
",",
"\"ODbL-1.0\"",
",",
"\"CC-BY-NC-SA-4.0\"",
",",
"\"unknown\"",
",",
"\"DbCL-1.0\"",
",",
"\"CC-BY-SA-3.0\... | Sets the license_name of this DatasetNewRequest.
The license that should be associated with the dataset # noqa: E501
:param license_name: The license_name of this DatasetNewRequest. # noqa: E501
:type: str | [
"Sets",
"the",
"license_name",
"of",
"this",
"DatasetNewRequest",
"."
] | python | train | 47.75 |
geronimp/graftM | graftm/getaxnseq.py | https://github.com/geronimp/graftM/blob/c82576517290167f605fd0bc4facd009cee29f48/graftm/getaxnseq.py#L106-L203 | def write_taxonomy_and_seqinfo_files(self, taxonomies, output_taxonomy_file, output_seqinfo_file):
'''Write out taxonomy and seqinfo files as required by taxtastic
from known taxonomies
Parameters
----------
taxonomies:
hash of taxon_id to array of taxonomic ... | [
"def",
"write_taxonomy_and_seqinfo_files",
"(",
"self",
",",
"taxonomies",
",",
"output_taxonomy_file",
",",
"output_seqinfo_file",
")",
":",
"first_pass_id_and_taxonomies",
"=",
"[",
"]",
"tc",
"=",
"TaxonomyCleaner",
"(",
")",
"max_number_of_ranks",
"=",
"0",
"for",... | Write out taxonomy and seqinfo files as required by taxtastic
from known taxonomies
Parameters
----------
taxonomies:
hash of taxon_id to array of taxonomic information
output_taxonomy_file:
write taxtastic-compatible 'taxonomy' file here
... | [
"Write",
"out",
"taxonomy",
"and",
"seqinfo",
"files",
"as",
"required",
"by",
"taxtastic",
"from",
"known",
"taxonomies",
"Parameters",
"----------",
"taxonomies",
":",
"hash",
"of",
"taxon_id",
"to",
"array",
"of",
"taxonomic",
"information",
"output_taxonomy_file... | python | train | 46.265306 |
bcbio/bcbio-nextgen | bcbio/structural/shared.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/shared.py#L25-L39 | def finalize_sv(orig_vcf, data, items):
"""Finalize structural variants, adding effects and splitting if needed.
"""
paired = vcfutils.get_paired(items)
# For paired/somatic, attach combined calls to tumor sample
if paired:
sample_vcf = orig_vcf if paired.tumor_name == dd.get_sample_name(dat... | [
"def",
"finalize_sv",
"(",
"orig_vcf",
",",
"data",
",",
"items",
")",
":",
"paired",
"=",
"vcfutils",
".",
"get_paired",
"(",
"items",
")",
"# For paired/somatic, attach combined calls to tumor sample",
"if",
"paired",
":",
"sample_vcf",
"=",
"orig_vcf",
"if",
"p... | Finalize structural variants, adding effects and splitting if needed. | [
"Finalize",
"structural",
"variants",
"adding",
"effects",
"and",
"splitting",
"if",
"needed",
"."
] | python | train | 46.666667 |
Jajcus/pyxmpp2 | pyxmpp2/roster.py | https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/roster.py#L856-L884 | def update_item(self, jid, name = NO_CHANGE, groups = NO_CHANGE,
callback = None, error_callback = None):
"""Modify a contact in the roster.
:Parameters:
- `jid`: contact's jid
- `name`: a new name for the contact
- `groups`: a sequenc... | [
"def",
"update_item",
"(",
"self",
",",
"jid",
",",
"name",
"=",
"NO_CHANGE",
",",
"groups",
"=",
"NO_CHANGE",
",",
"callback",
"=",
"None",
",",
"error_callback",
"=",
"None",
")",
":",
"# pylint: disable=R0913",
"item",
"=",
"self",
".",
"roster",
"[",
... | Modify a contact in the roster.
:Parameters:
- `jid`: contact's jid
- `name`: a new name for the contact
- `groups`: a sequence of group names the contact should belong to
- `callback`: function to call when the request succeeds. It should
accept a ... | [
"Modify",
"a",
"contact",
"in",
"the",
"roster",
"."
] | python | valid | 41.586207 |
ianmiell/shutit | shutit_login_stack.py | https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_login_stack.py#L85-L99 | def has_blocking_background_send(self):
"""Check whether any blocking background commands are waiting to run.
If any are, return True. If none are, return False.
"""
for background_object in self.background_objects:
# If it's running, or not started yet, it should block other tasks.
if background_ob... | [
"def",
"has_blocking_background_send",
"(",
"self",
")",
":",
"for",
"background_object",
"in",
"self",
".",
"background_objects",
":",
"# If it's running, or not started yet, it should block other tasks.",
"if",
"background_object",
".",
"block_other_commands",
"and",
"backgro... | Check whether any blocking background commands are waiting to run.
If any are, return True. If none are, return False. | [
"Check",
"whether",
"any",
"blocking",
"background",
"commands",
"are",
"waiting",
"to",
"run",
".",
"If",
"any",
"are",
"return",
"True",
".",
"If",
"none",
"are",
"return",
"False",
"."
] | python | train | 61.6 |
facebook/pyre-check | sapp/sapp/base_parser.py | https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/base_parser.py#L109-L180 | def analysis_output_to_dict_entries(
self,
inputfile: AnalysisOutput,
previous_inputfile: Optional[AnalysisOutput],
previous_issue_handles: Optional[AnalysisOutput],
linemapfile: Optional[str],
) -> DictEntries:
"""Here we take input generators and return a dict with ... | [
"def",
"analysis_output_to_dict_entries",
"(",
"self",
",",
"inputfile",
":",
"AnalysisOutput",
",",
"previous_inputfile",
":",
"Optional",
"[",
"AnalysisOutput",
"]",
",",
"previous_issue_handles",
":",
"Optional",
"[",
"AnalysisOutput",
"]",
",",
"linemapfile",
":",... | Here we take input generators and return a dict with issues,
preconditions, and postconditions separated. If there is only a single
generator file, it's simple. If we also pass in a generator from a
previous inputfile then there are a couple extra steps:
1. If an issue was seen in the p... | [
"Here",
"we",
"take",
"input",
"generators",
"and",
"return",
"a",
"dict",
"with",
"issues",
"preconditions",
"and",
"postconditions",
"separated",
".",
"If",
"there",
"is",
"only",
"a",
"single",
"generator",
"file",
"it",
"s",
"simple",
".",
"If",
"we",
... | python | train | 43.444444 |
Chyroc/WechatSogou | wechatsogou/tools.py | https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/tools.py#L73-L95 | def _replace_str_html(s):
"""替换html‘"’等转义内容为正常内容
Args:
s: 文字内容
Returns:
s: 处理反转义后的文字
"""
html_str_list = [
(''', '\''),
('"', '"'),
('&', '&'),
('¥', '¥'),
('amp;', ''),
('<', '<'),
('>', '>'),
... | [
"def",
"_replace_str_html",
"(",
"s",
")",
":",
"html_str_list",
"=",
"[",
"(",
"'''",
",",
"'\\''",
")",
",",
"(",
"'"'",
",",
"'\"'",
")",
",",
"(",
"'&'",
",",
"'&'",
")",
",",
"(",
"'¥'",
",",
"'¥')",
",",
"",
"(",
"'amp;'",
... | 替换html‘"’等转义内容为正常内容
Args:
s: 文字内容
Returns:
s: 处理反转义后的文字 | [
"替换html‘"",
";",
"’等转义内容为正常内容"
] | python | train | 18.173913 |
cga-harvard/Hypermap-Registry | hypermap/aggregator/utils.py | https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/utils.py#L335-L349 | def service_url_parse(url):
"""
Function that parses from url the service and folder of services.
"""
endpoint = get_sanitized_endpoint(url)
url_split_list = url.split(endpoint + '/')
if len(url_split_list) != 0:
url_split_list = url_split_list[1].split('/')
else:
raise Excep... | [
"def",
"service_url_parse",
"(",
"url",
")",
":",
"endpoint",
"=",
"get_sanitized_endpoint",
"(",
"url",
")",
"url_split_list",
"=",
"url",
".",
"split",
"(",
"endpoint",
"+",
"'/'",
")",
"if",
"len",
"(",
"url_split_list",
")",
"!=",
"0",
":",
"url_split_... | Function that parses from url the service and folder of services. | [
"Function",
"that",
"parses",
"from",
"url",
"the",
"service",
"and",
"folder",
"of",
"services",
"."
] | python | train | 33 |
saltstack/salt | salt/cloud/clouds/joyent.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/joyent.py#L785-L802 | def _get_proto():
'''
Checks configuration to see whether the user has SSL turned on. Default is:
.. code-block:: yaml
use_ssl: True
'''
use_ssl = config.get_cloud_config_value(
'use_ssl',
get_configured_provider(),
__opts__,
search_global=False,
def... | [
"def",
"_get_proto",
"(",
")",
":",
"use_ssl",
"=",
"config",
".",
"get_cloud_config_value",
"(",
"'use_ssl'",
",",
"get_configured_provider",
"(",
")",
",",
"__opts__",
",",
"search_global",
"=",
"False",
",",
"default",
"=",
"True",
")",
"if",
"use_ssl",
"... | Checks configuration to see whether the user has SSL turned on. Default is:
.. code-block:: yaml
use_ssl: True | [
"Checks",
"configuration",
"to",
"see",
"whether",
"the",
"user",
"has",
"SSL",
"turned",
"on",
".",
"Default",
"is",
":"
] | python | train | 21.277778 |
kubernetes-client/python | kubernetes/client/apis/certificates_v1beta1_api.py | https://github.com/kubernetes-client/python/blob/5e512ff564c244c50cab780d821542ed56aa965a/kubernetes/client/apis/certificates_v1beta1_api.py#L1157-L1180 | def replace_certificate_signing_request_approval(self, name, body, **kwargs):
"""
replace approval of the specified CertificateSigningRequest
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api... | [
"def",
"replace_certificate_signing_request_approval",
"(",
"self",
",",
"name",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
... | replace approval of the specified CertificateSigningRequest
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_certificate_signing_request_approval(name, body, async_req=True)
>>> result = thr... | [
"replace",
"approval",
"of",
"the",
"specified",
"CertificateSigningRequest",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"pass",
"async_req",
"=",
"True",... | python | train | 70.541667 |
sibirrer/lenstronomy | lenstronomy/LensModel/single_plane.py | https://github.com/sibirrer/lenstronomy/blob/4edb100a4f3f4fdc4fac9b0032d2b0283d0aa1d6/lenstronomy/LensModel/single_plane.py#L84-L109 | def alpha(self, x, y, kwargs, k=None):
"""
deflection angles
:param x: x-position (preferentially arcsec)
:type x: numpy array
:param y: y-position (preferentially arcsec)
:type y: numpy array
:param kwargs: list of keyword arguments of lens model parameters matc... | [
"def",
"alpha",
"(",
"self",
",",
"x",
",",
"y",
",",
"kwargs",
",",
"k",
"=",
"None",
")",
":",
"x",
"=",
"np",
".",
"array",
"(",
"x",
",",
"dtype",
"=",
"float",
")",
"y",
"=",
"np",
".",
"array",
"(",
"y",
",",
"dtype",
"=",
"float",
... | deflection angles
:param x: x-position (preferentially arcsec)
:type x: numpy array
:param y: y-position (preferentially arcsec)
:type y: numpy array
:param kwargs: list of keyword arguments of lens model parameters matching the lens model classes
:param k: only evaluate ... | [
"deflection",
"angles",
":",
"param",
"x",
":",
"x",
"-",
"position",
"(",
"preferentially",
"arcsec",
")",
":",
"type",
"x",
":",
"numpy",
"array",
":",
"param",
"y",
":",
"y",
"-",
"position",
"(",
"preferentially",
"arcsec",
")",
":",
"type",
"y",
... | python | train | 41.076923 |
inveniosoftware/invenio-pidrelations | invenio_pidrelations/serializers/utils.py | https://github.com/inveniosoftware/invenio-pidrelations/blob/a49f3725cf595b663c5b04814280b231f88bc333/invenio_pidrelations/serializers/utils.py#L47-L54 | def dump_relation(api, rel_cfg, pid, data):
"""Dump a specific relation to a data dict."""
schema_class = rel_cfg.schema
if schema_class is not None:
schema = schema_class()
schema.context['pid'] = pid
result, errors = schema.dump(api)
data.setdefault(rel_cfg.name, []).append... | [
"def",
"dump_relation",
"(",
"api",
",",
"rel_cfg",
",",
"pid",
",",
"data",
")",
":",
"schema_class",
"=",
"rel_cfg",
".",
"schema",
"if",
"schema_class",
"is",
"not",
"None",
":",
"schema",
"=",
"schema_class",
"(",
")",
"schema",
".",
"context",
"[",
... | Dump a specific relation to a data dict. | [
"Dump",
"a",
"specific",
"relation",
"to",
"a",
"data",
"dict",
"."
] | python | train | 40.125 |
cons3rt/pycons3rt | pycons3rt/pygit.py | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/pygit.py#L152-L191 | def encode_character(char):
"""Returns URL encoding for a single character
:param char (str) Single character to encode
:returns (str) URL-encoded character
"""
if char == '!': return '%21'
elif char == '"': return '%22'
elif char == '#': return '%23'
elif char == '$': return '%24'
... | [
"def",
"encode_character",
"(",
"char",
")",
":",
"if",
"char",
"==",
"'!'",
":",
"return",
"'%21'",
"elif",
"char",
"==",
"'\"'",
":",
"return",
"'%22'",
"elif",
"char",
"==",
"'#'",
":",
"return",
"'%23'",
"elif",
"char",
"==",
"'$'",
":",
"return",
... | Returns URL encoding for a single character
:param char (str) Single character to encode
:returns (str) URL-encoded character | [
"Returns",
"URL",
"encoding",
"for",
"a",
"single",
"character"
] | python | train | 32.875 |
Azure/msrest-for-python | msrest/serialization.py | https://github.com/Azure/msrest-for-python/blob/0732bc90bdb290e5f58c675ffdd7dbfa9acefc93/msrest/serialization.py#L1633-L1642 | def deserialize_bytearray(attr):
"""Deserialize string into bytearray.
:param str attr: response string to be deserialized.
:rtype: bytearray
:raises: TypeError if string format invalid.
"""
if isinstance(attr, ET.Element):
attr = attr.text
return byt... | [
"def",
"deserialize_bytearray",
"(",
"attr",
")",
":",
"if",
"isinstance",
"(",
"attr",
",",
"ET",
".",
"Element",
")",
":",
"attr",
"=",
"attr",
".",
"text",
"return",
"bytearray",
"(",
"b64decode",
"(",
"attr",
")",
")"
] | Deserialize string into bytearray.
:param str attr: response string to be deserialized.
:rtype: bytearray
:raises: TypeError if string format invalid. | [
"Deserialize",
"string",
"into",
"bytearray",
"."
] | python | train | 33.4 |
deepmind/sonnet | sonnet/python/modules/relational_memory.py | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/relational_memory.py#L184-L210 | def _create_gates(self, inputs, memory):
"""Create input and forget gates for this step using `inputs` and `memory`.
Args:
inputs: Tensor input.
memory: The current state of memory.
Returns:
input_gate: A LSTM-like insert gate.
forget_gate: A LSTM-like forget gate.
"""
# We... | [
"def",
"_create_gates",
"(",
"self",
",",
"inputs",
",",
"memory",
")",
":",
"# We'll create the input and forget gates at once. Hence, calculate double",
"# the gate size.",
"num_gates",
"=",
"2",
"*",
"self",
".",
"_calculate_gate_size",
"(",
")",
"memory",
"=",
"tf",... | Create input and forget gates for this step using `inputs` and `memory`.
Args:
inputs: Tensor input.
memory: The current state of memory.
Returns:
input_gate: A LSTM-like insert gate.
forget_gate: A LSTM-like forget gate. | [
"Create",
"input",
"and",
"forget",
"gates",
"for",
"this",
"step",
"using",
"inputs",
"and",
"memory",
"."
] | python | train | 36.185185 |
Microsoft/malmo | Malmo/samples/Python_examples/tutorial_6.py | https://github.com/Microsoft/malmo/blob/4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a/Malmo/samples/Python_examples/tutorial_6.py#L136-L200 | def run(self, agent_host):
"""run the agent on the world"""
total_reward = 0
self.prev_s = None
self.prev_a = None
is_first_action = True
# main loop:
world_state = agent_host.getWorldState()
while world_state.is_mission_running... | [
"def",
"run",
"(",
"self",
",",
"agent_host",
")",
":",
"total_reward",
"=",
"0",
"self",
".",
"prev_s",
"=",
"None",
"self",
".",
"prev_a",
"=",
"None",
"is_first_action",
"=",
"True",
"# main loop:",
"world_state",
"=",
"agent_host",
".",
"getWorldState",
... | run the agent on the world | [
"run",
"the",
"agent",
"on",
"the",
"world"
] | python | train | 41.415385 |
JasonKessler/scattertext | scattertext/TermDocMatrixWithoutCategories.py | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/TermDocMatrixWithoutCategories.py#L268-L281 | def remove_terms_used_in_less_than_num_docs(self, threshold):
'''
Parameters
----------
threshold: int
Minimum number of documents term should appear in to be kept
Returns
-------
TermDocMatrix, new object with terms removed.
'''
term_... | [
"def",
"remove_terms_used_in_less_than_num_docs",
"(",
"self",
",",
"threshold",
")",
":",
"term_counts",
"=",
"self",
".",
"_X",
".",
"astype",
"(",
"bool",
")",
".",
"astype",
"(",
"int",
")",
".",
"sum",
"(",
"axis",
"=",
"0",
")",
".",
"A",
"[",
... | Parameters
----------
threshold: int
Minimum number of documents term should appear in to be kept
Returns
-------
TermDocMatrix, new object with terms removed. | [
"Parameters",
"----------",
"threshold",
":",
"int",
"Minimum",
"number",
"of",
"documents",
"term",
"should",
"appear",
"in",
"to",
"be",
"kept"
] | python | train | 34.928571 |
sacrud/pyramid_sacrud | pyramid_sacrud/routes.py | https://github.com/sacrud/pyramid_sacrud/blob/05c30e219a32166b4e09ec3524767fe4a4d3c788/pyramid_sacrud/routes.py#L27-L37 | def resources_preparing_factory(app, wrapper):
""" Factory which wrap all resources in settings.
"""
settings = app.app.registry.settings
config = settings.get(CONFIG_RESOURCES, None)
if not config:
return
resources = [(k, [wrapper(r, GroupResource(k, v)) for r in v])
f... | [
"def",
"resources_preparing_factory",
"(",
"app",
",",
"wrapper",
")",
":",
"settings",
"=",
"app",
".",
"app",
".",
"registry",
".",
"settings",
"config",
"=",
"settings",
".",
"get",
"(",
"CONFIG_RESOURCES",
",",
"None",
")",
"if",
"not",
"config",
":",
... | Factory which wrap all resources in settings. | [
"Factory",
"which",
"wrap",
"all",
"resources",
"in",
"settings",
"."
] | python | train | 33.727273 |
Robpol86/libnl | libnl/nl.py | https://github.com/Robpol86/libnl/blob/274e9fdaa39822d06ef70b799ed4a95937a4d923/libnl/nl.py#L42-L83 | def nl_connect(sk, protocol):
"""Create file descriptor and bind socket.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L96
Creates a new Netlink socket using `socket.socket()` and binds the socket to the protocol and local port specified
in the `sk` socket object (if any). Fails if the so... | [
"def",
"nl_connect",
"(",
"sk",
",",
"protocol",
")",
":",
"flags",
"=",
"getattr",
"(",
"socket",
",",
"'SOCK_CLOEXEC'",
",",
"0",
")",
"if",
"sk",
".",
"s_fd",
"!=",
"-",
"1",
":",
"return",
"-",
"NLE_BAD_SOCK",
"try",
":",
"sk",
".",
"socket_insta... | Create file descriptor and bind socket.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L96
Creates a new Netlink socket using `socket.socket()` and binds the socket to the protocol and local port specified
in the `sk` socket object (if any). Fails if the socket is already connected.
Posit... | [
"Create",
"file",
"descriptor",
"and",
"bind",
"socket",
"."
] | python | train | 32.761905 |
trevisanj/f311 | f311/hapi.py | https://github.com/trevisanj/f311/blob/9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7/f311/hapi.py#L11816-L11823 | def SLIT_GAUSSIAN(x,g):
"""
Instrumental (slit) function.
B(x) = sqrt(ln(2)/pi)/γ*exp(-ln(2)*(x/γ)**2),
where γ/2 is a gaussian half-width at half-maximum.
"""
g /= 2
return sqrt(log(2))/(sqrt(pi)*g)*exp(-log(2)*(x/g)**2) | [
"def",
"SLIT_GAUSSIAN",
"(",
"x",
",",
"g",
")",
":",
"g",
"/=",
"2",
"return",
"sqrt",
"(",
"log",
"(",
"2",
")",
")",
"/",
"(",
"sqrt",
"(",
"pi",
")",
"*",
"g",
")",
"*",
"exp",
"(",
"-",
"log",
"(",
"2",
")",
"*",
"(",
"x",
"/",
"g"... | Instrumental (slit) function.
B(x) = sqrt(ln(2)/pi)/γ*exp(-ln(2)*(x/γ)**2),
where γ/2 is a gaussian half-width at half-maximum. | [
"Instrumental",
"(",
"slit",
")",
"function",
".",
"B",
"(",
"x",
")",
"=",
"sqrt",
"(",
"ln",
"(",
"2",
")",
"/",
"pi",
")",
"/",
"γ",
"*",
"exp",
"(",
"-",
"ln",
"(",
"2",
")",
"*",
"(",
"x",
"/",
"γ",
")",
"**",
"2",
")",
"where",
"γ... | python | train | 30.25 |
manns/pyspread | pyspread/src/gui/_main_window.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/gui/_main_window.py#L518-L527 | def OnSafeModeEntry(self, event):
"""Safe mode entry event handler"""
# Enable menu item for leaving safe mode
self.main_window.main_menu.enable_file_approve(True)
self.main_window.grid.Refresh()
event.Skip() | [
"def",
"OnSafeModeEntry",
"(",
"self",
",",
"event",
")",
":",
"# Enable menu item for leaving safe mode",
"self",
".",
"main_window",
".",
"main_menu",
".",
"enable_file_approve",
"(",
"True",
")",
"self",
".",
"main_window",
".",
"grid",
".",
"Refresh",
"(",
"... | Safe mode entry event handler | [
"Safe",
"mode",
"entry",
"event",
"handler"
] | python | train | 24.3 |
CityOfZion/neo-python | neo/Core/BlockBase.py | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/BlockBase.py#L205-L226 | def ToJson(self):
"""
Convert object members to a dictionary that can be parsed as JSON.
Returns:
dict:
"""
json = {}
json["hash"] = self.Hash.To0xString()
json["size"] = self.Size()
json["version"] = self.Version
json["previousblockh... | [
"def",
"ToJson",
"(",
"self",
")",
":",
"json",
"=",
"{",
"}",
"json",
"[",
"\"hash\"",
"]",
"=",
"self",
".",
"Hash",
".",
"To0xString",
"(",
")",
"json",
"[",
"\"size\"",
"]",
"=",
"self",
".",
"Size",
"(",
")",
"json",
"[",
"\"version\"",
"]",... | Convert object members to a dictionary that can be parsed as JSON.
Returns:
dict: | [
"Convert",
"object",
"members",
"to",
"a",
"dictionary",
"that",
"can",
"be",
"parsed",
"as",
"JSON",
"."
] | python | train | 36.727273 |
RiotGames/cloud-inquisitor | plugins/public/cinq-auditor-domain-hijacking/cinq_auditor_domain_hijacking/__init__.py | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-domain-hijacking/cinq_auditor_domain_hijacking/__init__.py#L197-L216 | def return_resource_name(self, record, resource_type):
""" Removes the trailing AWS domain from a DNS record
to return the resource name
e.g bucketname.s3.amazonaws.com will return bucketname
Args:
record (str): DNS record
resource_type: AWS Resource typ... | [
"def",
"return_resource_name",
"(",
"self",
",",
"record",
",",
"resource_type",
")",
":",
"try",
":",
"if",
"resource_type",
"==",
"'s3'",
":",
"regex",
"=",
"re",
".",
"compile",
"(",
"'.*(\\.(?:s3-|s3){1}(?:.*)?\\.amazonaws\\.com)'",
")",
"bucket_name",
"=",
... | Removes the trailing AWS domain from a DNS record
to return the resource name
e.g bucketname.s3.amazonaws.com will return bucketname
Args:
record (str): DNS record
resource_type: AWS Resource type (i.e. S3 Bucket, Elastic Beanstalk, etc..) | [
"Removes",
"the",
"trailing",
"AWS",
"domain",
"from",
"a",
"DNS",
"record",
"to",
"return",
"the",
"resource",
"name"
] | python | train | 38.95 |
Yubico/python-yubico | yubico/yubikey_usb_hid.py | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_usb_hid.py#L260-L313 | def _waitfor(self, mode, mask, may_block, timeout=2):
"""
Wait for the YubiKey to either turn ON or OFF certain bits in the status byte.
mode is either 'and' or 'nand'
timeout is a number of seconds (precision about ~0.5 seconds)
"""
finished = False
sleep = 0.01... | [
"def",
"_waitfor",
"(",
"self",
",",
"mode",
",",
"mask",
",",
"may_block",
",",
"timeout",
"=",
"2",
")",
":",
"finished",
"=",
"False",
"sleep",
"=",
"0.01",
"# After six sleeps, we've slept 0.64 seconds.",
"wait_num",
"=",
"(",
"timeout",
"*",
"2",
")",
... | Wait for the YubiKey to either turn ON or OFF certain bits in the status byte.
mode is either 'and' or 'nand'
timeout is a number of seconds (precision about ~0.5 seconds) | [
"Wait",
"for",
"the",
"YubiKey",
"to",
"either",
"turn",
"ON",
"or",
"OFF",
"certain",
"bits",
"in",
"the",
"status",
"byte",
"."
] | python | train | 42.37037 |
IdentityPython/fedoidcmsg | src/fedoidcmsg/entity.py | https://github.com/IdentityPython/fedoidcmsg/blob/d30107be02521fa6cdfe285da3b6b0cdd153c8cc/src/fedoidcmsg/entity.py#L505-L569 | def make_federation_entity(config, eid='', httpcli=None, verify_ssl=True):
"""
Construct a :py:class:`fedoidcmsg.entity.FederationEntity` instance based
on given configuration.
:param config: Federation entity configuration
:param eid: Entity ID
:param httpcli: A http client instance to use whe... | [
"def",
"make_federation_entity",
"(",
"config",
",",
"eid",
"=",
"''",
",",
"httpcli",
"=",
"None",
",",
"verify_ssl",
"=",
"True",
")",
":",
"args",
"=",
"{",
"}",
"if",
"not",
"eid",
":",
"try",
":",
"eid",
"=",
"config",
"[",
"'entity_id'",
"]",
... | Construct a :py:class:`fedoidcmsg.entity.FederationEntity` instance based
on given configuration.
:param config: Federation entity configuration
:param eid: Entity ID
:param httpcli: A http client instance to use when sending HTTP requests
:param verify_ssl: Whether TLS/SSL certificates should be v... | [
"Construct",
"a",
":",
"py",
":",
"class",
":",
"fedoidcmsg",
".",
"entity",
".",
"FederationEntity",
"instance",
"based",
"on",
"given",
"configuration",
"."
] | python | test | 33.307692 |
tyiannak/pyAudioAnalysis | pyAudioAnalysis/audioFeatureExtraction.py | https://github.com/tyiannak/pyAudioAnalysis/blob/e3da991e7247492deba50648a4c7c0f41e684af4/pyAudioAnalysis/audioFeatureExtraction.py#L240-L255 | def stChromaFeaturesInit(nfft, fs):
"""
This function initializes the chroma matrices used in the calculation of the chroma features
"""
freqs = numpy.array([((f + 1) * fs) / (2 * nfft) for f in range(nfft)])
Cp = 27.50
nChroma = numpy.round(12.0 * numpy.log2(freqs / Cp)).astype(int)
... | [
"def",
"stChromaFeaturesInit",
"(",
"nfft",
",",
"fs",
")",
":",
"freqs",
"=",
"numpy",
".",
"array",
"(",
"[",
"(",
"(",
"f",
"+",
"1",
")",
"*",
"fs",
")",
"/",
"(",
"2",
"*",
"nfft",
")",
"for",
"f",
"in",
"range",
"(",
"nfft",
")",
"]",
... | This function initializes the chroma matrices used in the calculation of the chroma features | [
"This",
"function",
"initializes",
"the",
"chroma",
"matrices",
"used",
"in",
"the",
"calculation",
"of",
"the",
"chroma",
"features"
] | python | train | 34 |
10gen/mongo-orchestration | mongo_orchestration/sharded_clusters.py | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/sharded_clusters.py#L360-L400 | def member_add(self, member_id=None, params=None):
"""add new member into existing configuration"""
member_id = member_id or str(uuid4())
if self.enable_ipv6:
common.enable_ipv6_repl(params)
if 'members' in params:
# is replica set
for member in params... | [
"def",
"member_add",
"(",
"self",
",",
"member_id",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"member_id",
"=",
"member_id",
"or",
"str",
"(",
"uuid4",
"(",
")",
")",
"if",
"self",
".",
"enable_ipv6",
":",
"common",
".",
"enable_ipv6_repl",
"(... | add new member into existing configuration | [
"add",
"new",
"member",
"into",
"existing",
"configuration"
] | python | train | 51.658537 |
GustavePate/distarkcli | distarkcli/utils/MyConfiguration.py | https://github.com/GustavePate/distarkcli/blob/44b0e637e94ebb2687a1b7e2f6c5d0658d775238/distarkcli/utils/MyConfiguration.py#L92-L100 | def getbroker():
'''
return settings dictionnary
'''
if not Configuration.broker_initialized:
Configuration._initconf()
Configuration.broker_settings = Configuration.settings['broker']
Configuration.broker_initialized = True
return Configuratio... | [
"def",
"getbroker",
"(",
")",
":",
"if",
"not",
"Configuration",
".",
"broker_initialized",
":",
"Configuration",
".",
"_initconf",
"(",
")",
"Configuration",
".",
"broker_settings",
"=",
"Configuration",
".",
"settings",
"[",
"'broker'",
"]",
"Configuration",
"... | return settings dictionnary | [
"return",
"settings",
"dictionnary"
] | python | train | 36.555556 |
puiterwijk/flask-oidc | flask_oidc/__init__.py | https://github.com/puiterwijk/flask-oidc/blob/7f16e27b926fc12953d6b2ae78a9b9cc9b8d1769/flask_oidc/__init__.py#L793-L846 | def _validate_token(self, token, scopes_required=None):
"""The actual implementation of validate_token."""
if scopes_required is None:
scopes_required = []
scopes_required = set(scopes_required)
token_info = None
valid_token = False
has_required_scopes = Fals... | [
"def",
"_validate_token",
"(",
"self",
",",
"token",
",",
"scopes_required",
"=",
"None",
")",
":",
"if",
"scopes_required",
"is",
"None",
":",
"scopes_required",
"=",
"[",
"]",
"scopes_required",
"=",
"set",
"(",
"scopes_required",
")",
"token_info",
"=",
"... | The actual implementation of validate_token. | [
"The",
"actual",
"implementation",
"of",
"validate_token",
"."
] | python | train | 35.518519 |
biosustain/optlang | optlang/util.py | https://github.com/biosustain/optlang/blob/13673ac26f6b3ba37a2ef392489722c52e3c5ff1/optlang/util.py#L33-L83 | def solve_with_glpsol(glp_prob):
"""Solve glpk problem with glpsol commandline solver. Mainly for testing purposes.
# Examples
# --------
# >>> problem = glp_create_prob()
# ... glp_read_lp(problem, None, "../tests/data/model.lp")
# ... solution = solve_with_glpsol(problem)
# ... print 'as... | [
"def",
"solve_with_glpsol",
"(",
"glp_prob",
")",
":",
"from",
"swiglpk",
"import",
"glp_get_row_name",
",",
"glp_get_col_name",
",",
"glp_write_lp",
",",
"glp_get_num_rows",
",",
"glp_get_num_cols",
"row_ids",
"=",
"[",
"glp_get_row_name",
"(",
"glp_prob",
",",
"i"... | Solve glpk problem with glpsol commandline solver. Mainly for testing purposes.
# Examples
# --------
# >>> problem = glp_create_prob()
# ... glp_read_lp(problem, None, "../tests/data/model.lp")
# ... solution = solve_with_glpsol(problem)
# ... print 'asdf'
# 'asdf'
# >>> print solutio... | [
"Solve",
"glpk",
"problem",
"with",
"glpsol",
"commandline",
"solver",
".",
"Mainly",
"for",
"testing",
"purposes",
"."
] | python | train | 35.862745 |
swharden/SWHLab | swhlab/common.py | https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/common.py#L260-L268 | def parent(groups,ID):
"""given a groups dictionary and an ID, return its actual parent ID."""
if ID in groups.keys():
return ID # already a parent
if not ID in groups.keys():
for actualParent in groups.keys():
if ID in groups[actualParent]:
return actualParent # ... | [
"def",
"parent",
"(",
"groups",
",",
"ID",
")",
":",
"if",
"ID",
"in",
"groups",
".",
"keys",
"(",
")",
":",
"return",
"ID",
"# already a parent",
"if",
"not",
"ID",
"in",
"groups",
".",
"keys",
"(",
")",
":",
"for",
"actualParent",
"in",
"groups",
... | given a groups dictionary and an ID, return its actual parent ID. | [
"given",
"a",
"groups",
"dictionary",
"and",
"an",
"ID",
"return",
"its",
"actual",
"parent",
"ID",
"."
] | python | valid | 39 |
mapbox/mapbox-cli-py | mapboxcli/scripts/geocoding.py | https://github.com/mapbox/mapbox-cli-py/blob/b75544a2f83a4fda79d78b5673058e16e64a4f6d/mapboxcli/scripts/geocoding.py#L24-L31 | def coords_from_query(query):
"""Transform a query line into a (lng, lat) pair of coordinates."""
try:
coords = json.loads(query)
except ValueError:
vals = re.split(r'[,\s]+', query.strip())
coords = [float(v) for v in vals]
return tuple(coords[:2]) | [
"def",
"coords_from_query",
"(",
"query",
")",
":",
"try",
":",
"coords",
"=",
"json",
".",
"loads",
"(",
"query",
")",
"except",
"ValueError",
":",
"vals",
"=",
"re",
".",
"split",
"(",
"r'[,\\s]+'",
",",
"query",
".",
"strip",
"(",
")",
")",
"coord... | Transform a query line into a (lng, lat) pair of coordinates. | [
"Transform",
"a",
"query",
"line",
"into",
"a",
"(",
"lng",
"lat",
")",
"pair",
"of",
"coordinates",
"."
] | python | train | 35.25 |
tensorflow/tensor2tensor | tensor2tensor/models/research/glow_ops.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/glow_ops.py#L1156-L1193 | def revnet_step(name, x, hparams, reverse=True):
"""One step of glow generative flow.
Actnorm + invertible 1X1 conv + affine_coupling.
Args:
name: used for variable scope.
x: input
hparams: coupling_width is the only hparam that is being used in
this function.
reverse: forward or re... | [
"def",
"revnet_step",
"(",
"name",
",",
"x",
",",
"hparams",
",",
"reverse",
"=",
"True",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"reuse",
"=",
"tf",
".",
"AUTO_REUSE",
")",
":",
"if",
"hparams",
".",
"coupling",
"==",
"\"add... | One step of glow generative flow.
Actnorm + invertible 1X1 conv + affine_coupling.
Args:
name: used for variable scope.
x: input
hparams: coupling_width is the only hparam that is being used in
this function.
reverse: forward or reverse pass.
Returns:
z: Output of one step of re... | [
"One",
"step",
"of",
"glow",
"generative",
"flow",
"."
] | python | train | 33.552632 |
liftoff/pyminifier | pyminifier/minification.py | https://github.com/liftoff/pyminifier/blob/087ea7b0c8c964f1f907c3f350f5ce281798db86/pyminifier/minification.py#L163-L234 | def reduce_operators(source):
"""
Remove spaces between operators in *source* and returns the result.
Example::
def foo(foo, bar, blah):
test = "This is a %s" % foo
Will become::
def foo(foo,bar,blah):
test="This is a %s"%foo
.. note::
Also remov... | [
"def",
"reduce_operators",
"(",
"source",
")",
":",
"io_obj",
"=",
"io",
".",
"StringIO",
"(",
"source",
")",
"prev_tok",
"=",
"None",
"out_tokens",
"=",
"[",
"]",
"out",
"=",
"\"\"",
"last_lineno",
"=",
"-",
"1",
"last_col",
"=",
"0",
"nl_types",
"=",... | Remove spaces between operators in *source* and returns the result.
Example::
def foo(foo, bar, blah):
test = "This is a %s" % foo
Will become::
def foo(foo,bar,blah):
test="This is a %s"%foo
.. note::
Also removes trailing commas and joins disjointed st... | [
"Remove",
"spaces",
"between",
"operators",
"in",
"*",
"source",
"*",
"and",
"returns",
"the",
"result",
".",
"Example",
"::"
] | python | train | 37.291667 |
deepmind/sonnet | sonnet/python/modules/conv.py | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/conv.py#L713-L719 | def output_channels(self):
"""Returns the number of output channels."""
if callable(self._output_channels):
self._output_channels = self._output_channels()
# Channel must be integer.
self._output_channels = int(self._output_channels)
return self._output_channels | [
"def",
"output_channels",
"(",
"self",
")",
":",
"if",
"callable",
"(",
"self",
".",
"_output_channels",
")",
":",
"self",
".",
"_output_channels",
"=",
"self",
".",
"_output_channels",
"(",
")",
"# Channel must be integer.",
"self",
".",
"_output_channels",
"="... | Returns the number of output channels. | [
"Returns",
"the",
"number",
"of",
"output",
"channels",
"."
] | python | train | 40.285714 |
tensorflow/mesh | mesh_tensorflow/simd_mesh_impl.py | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/simd_mesh_impl.py#L443-L458 | def slice(self, tf_tensor, tensor_shape):
""""Slice out the corresponding part of tensor given the pnum variable."""
tensor_layout = self.tensor_layout(tensor_shape)
if tensor_layout.is_fully_replicated:
return self.LaidOutTensor([tf_tensor])
else:
slice_shape = self.slice_shape(tensor_shap... | [
"def",
"slice",
"(",
"self",
",",
"tf_tensor",
",",
"tensor_shape",
")",
":",
"tensor_layout",
"=",
"self",
".",
"tensor_layout",
"(",
"tensor_shape",
")",
"if",
"tensor_layout",
".",
"is_fully_replicated",
":",
"return",
"self",
".",
"LaidOutTensor",
"(",
"["... | Slice out the corresponding part of tensor given the pnum variable. | [
"Slice",
"out",
"the",
"corresponding",
"part",
"of",
"tensor",
"given",
"the",
"pnum",
"variable",
"."
] | python | train | 42.25 |
benhoff/pluginmanager | pluginmanager/file_manager.py | https://github.com/benhoff/pluginmanager/blob/a8a184f9ebfbb521703492cb88c1dbda4cd04c06/pluginmanager/file_manager.py#L111-L121 | def remove_plugin_filepaths(self, filepaths):
"""
Removes `filepaths` from `self.plugin_filepaths`.
Recommend passing in absolute filepaths. Method will
attempt to convert to absolute paths if not passed in.
`filepaths` can be a single object or an iterable.
"""
... | [
"def",
"remove_plugin_filepaths",
"(",
"self",
",",
"filepaths",
")",
":",
"filepaths",
"=",
"util",
".",
"to_absolute_paths",
"(",
"filepaths",
")",
"self",
".",
"plugin_filepaths",
"=",
"util",
".",
"remove_from_set",
"(",
"self",
".",
"plugin_filepaths",
",",... | Removes `filepaths` from `self.plugin_filepaths`.
Recommend passing in absolute filepaths. Method will
attempt to convert to absolute paths if not passed in.
`filepaths` can be a single object or an iterable. | [
"Removes",
"filepaths",
"from",
"self",
".",
"plugin_filepaths",
".",
"Recommend",
"passing",
"in",
"absolute",
"filepaths",
".",
"Method",
"will",
"attempt",
"to",
"convert",
"to",
"absolute",
"paths",
"if",
"not",
"passed",
"in",
"."
] | python | train | 45 |
reanahub/reana-commons | reana_commons/publisher.py | https://github.com/reanahub/reana-commons/blob/abf31d9f495e0d93171c43fc4a414cd292091b11/reana_commons/publisher.py#L100-L118 | def publish_workflow_status(self, workflow_uuid, status,
logs='', message=None):
"""Publish workflow status using the configured.
:param workflow_uudid: String which represents the workflow UUID.
:param status: Integer which represents the status of the workflow,... | [
"def",
"publish_workflow_status",
"(",
"self",
",",
"workflow_uuid",
",",
"status",
",",
"logs",
"=",
"''",
",",
"message",
"=",
"None",
")",
":",
"msg",
"=",
"{",
"\"workflow_uuid\"",
":",
"workflow_uuid",
",",
"\"logs\"",
":",
"logs",
",",
"\"status\"",
... | Publish workflow status using the configured.
:param workflow_uudid: String which represents the workflow UUID.
:param status: Integer which represents the status of the workflow,
this is defined in the `reana-db` `Workflow` models.
:param logs: String which represents the logs whic... | [
"Publish",
"workflow",
"status",
"using",
"the",
"configured",
"."
] | python | train | 43.105263 |
riggsd/davies | davies/compass/__init__.py | https://github.com/riggsd/davies/blob/8566c626202a875947ad01c087300108c68d80b5/davies/compass/__init__.py#L60-L70 | def azm(self):
"""Corrected azimuth, taking into account backsight, declination, and compass corrections."""
azm1 = self.get('BEARING', None)
azm2 = self.get('AZM2', None)
if azm1 is None and azm2 is None:
return None
if azm2 is None:
return azm1 + self.de... | [
"def",
"azm",
"(",
"self",
")",
":",
"azm1",
"=",
"self",
".",
"get",
"(",
"'BEARING'",
",",
"None",
")",
"azm2",
"=",
"self",
".",
"get",
"(",
"'AZM2'",
",",
"None",
")",
"if",
"azm1",
"is",
"None",
"and",
"azm2",
"is",
"None",
":",
"return",
... | Corrected azimuth, taking into account backsight, declination, and compass corrections. | [
"Corrected",
"azimuth",
"taking",
"into",
"account",
"backsight",
"declination",
"and",
"compass",
"corrections",
"."
] | python | train | 42.636364 |
tensorflow/lucid | lucid/scratch/atlas_pipeline/render_tile.py | https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/scratch/atlas_pipeline/render_tile.py#L11-L51 | def render_tile(cells, ti, tj, render, params, metadata, layout, summary):
"""
Render each cell in the tile and stitch it into a single image
"""
image_size = params["cell_size"] * params["n_tile"]
tile = Image.new("RGB", (image_size, image_size), (255,255,255))
keys = cells.keys()
for i,key in enumerat... | [
"def",
"render_tile",
"(",
"cells",
",",
"ti",
",",
"tj",
",",
"render",
",",
"params",
",",
"metadata",
",",
"layout",
",",
"summary",
")",
":",
"image_size",
"=",
"params",
"[",
"\"cell_size\"",
"]",
"*",
"params",
"[",
"\"n_tile\"",
"]",
"tile",
"="... | Render each cell in the tile and stitch it into a single image | [
"Render",
"each",
"cell",
"in",
"the",
"tile",
"and",
"stitch",
"it",
"into",
"a",
"single",
"image"
] | python | train | 37.146341 |
pypa/pipenv | pipenv/vendor/jinja2/filters.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L499-L533 | def do_urlize(eval_ctx, value, trim_url_limit=None, nofollow=False,
target=None, rel=None):
"""Converts URLs in plain text into clickable links.
If you pass the filter an additional integer it will shorten the urls
to that number. Also a third argument exists that makes the urls
"nofollow... | [
"def",
"do_urlize",
"(",
"eval_ctx",
",",
"value",
",",
"trim_url_limit",
"=",
"None",
",",
"nofollow",
"=",
"False",
",",
"target",
"=",
"None",
",",
"rel",
"=",
"None",
")",
":",
"policies",
"=",
"eval_ctx",
".",
"environment",
".",
"policies",
"rel",
... | Converts URLs in plain text into clickable links.
If you pass the filter an additional integer it will shorten the urls
to that number. Also a third argument exists that makes the urls
"nofollow":
.. sourcecode:: jinja
{{ mytext|urlize(40, true) }}
links are shortened to 40 chars ... | [
"Converts",
"URLs",
"in",
"plain",
"text",
"into",
"clickable",
"links",
"."
] | python | train | 31.428571 |
koriakin/binflakes | binflakes/types/word.py | https://github.com/koriakin/binflakes/blob/f059cecadf1c605802a713c62375b5bd5606d53f/binflakes/types/word.py#L242-L249 | def sext(self, width):
"""Sign-extends a word to a larger width. It is an error to specify
a smaller width (use ``extract`` instead to crop off the extra bits).
"""
width = operator.index(width)
if width < self._width:
raise ValueError('sign extending to a smaller wi... | [
"def",
"sext",
"(",
"self",
",",
"width",
")",
":",
"width",
"=",
"operator",
".",
"index",
"(",
"width",
")",
"if",
"width",
"<",
"self",
".",
"_width",
":",
"raise",
"ValueError",
"(",
"'sign extending to a smaller width'",
")",
"return",
"BinWord",
"(",... | Sign-extends a word to a larger width. It is an error to specify
a smaller width (use ``extract`` instead to crop off the extra bits). | [
"Sign",
"-",
"extends",
"a",
"word",
"to",
"a",
"larger",
"width",
".",
"It",
"is",
"an",
"error",
"to",
"specify",
"a",
"smaller",
"width",
"(",
"use",
"extract",
"instead",
"to",
"crop",
"off",
"the",
"extra",
"bits",
")",
"."
] | python | train | 47 |
SuperCowPowers/bat | bat/utils/cache.py | https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/bat/utils/cache.py#L77-L86 | def _compress(self):
"""Internal method to compress the cache. This method will
expire any old items in the cache, making the cache smaller"""
# Don't compress too often
now = time.time()
if self._last_compression + self._compression_timer < now:
self._last_compre... | [
"def",
"_compress",
"(",
"self",
")",
":",
"# Don't compress too often",
"now",
"=",
"time",
".",
"time",
"(",
")",
"if",
"self",
".",
"_last_compression",
"+",
"self",
".",
"_compression_timer",
"<",
"now",
":",
"self",
".",
"_last_compression",
"=",
"now",... | Internal method to compress the cache. This method will
expire any old items in the cache, making the cache smaller | [
"Internal",
"method",
"to",
"compress",
"the",
"cache",
".",
"This",
"method",
"will",
"expire",
"any",
"old",
"items",
"in",
"the",
"cache",
"making",
"the",
"cache",
"smaller"
] | python | train | 40.1 |
inasafe/inasafe | safe/utilities/utilities.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/utilities.py#L332-L357 | def human_sorting(the_list):
"""Sort the given list in the way that humans expect.
From http://stackoverflow.com/a/4623518
:param the_list: The list to sort.
:type the_list: list
:return: The new sorted list.
:rtype: list
"""
def try_int(s):
try:
return int(s)
... | [
"def",
"human_sorting",
"(",
"the_list",
")",
":",
"def",
"try_int",
"(",
"s",
")",
":",
"try",
":",
"return",
"int",
"(",
"s",
")",
"except",
"ValueError",
":",
"return",
"s",
"def",
"alphanum_key",
"(",
"s",
")",
":",
"\"\"\"Turn a string into a list of ... | Sort the given list in the way that humans expect.
From http://stackoverflow.com/a/4623518
:param the_list: The list to sort.
:type the_list: list
:return: The new sorted list.
:rtype: list | [
"Sort",
"the",
"given",
"list",
"in",
"the",
"way",
"that",
"humans",
"expect",
"."
] | python | train | 23.423077 |
ga4gh/ga4gh-server | ga4gh/server/datamodel/datasets.py | https://github.com/ga4gh/ga4gh-server/blob/1aa18922ef136db8604f6f098cb1732cba6f2a76/ga4gh/server/datamodel/datasets.py#L402-L409 | def getRnaQuantificationSetByName(self, name):
"""
Returns the RnaQuantification set with the specified name, or raises
an exception otherwise.
"""
if name not in self._rnaQuantificationSetNameMap:
raise exceptions.RnaQuantificationSetNameNotFoundException(name)
... | [
"def",
"getRnaQuantificationSetByName",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"_rnaQuantificationSetNameMap",
":",
"raise",
"exceptions",
".",
"RnaQuantificationSetNameNotFoundException",
"(",
"name",
")",
"return",
"self",
".",... | Returns the RnaQuantification set with the specified name, or raises
an exception otherwise. | [
"Returns",
"the",
"RnaQuantification",
"set",
"with",
"the",
"specified",
"name",
"or",
"raises",
"an",
"exception",
"otherwise",
"."
] | python | train | 45.25 |
modin-project/modin | modin/engines/base/frame/partition_manager.py | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/engines/base/frame/partition_manager.py#L685-L803 | def apply_func_to_select_indices(self, axis, func, indices, keep_remaining=False):
"""Applies a function to select indices.
Note: Your internal function must take a kwarg `internal_indices` for
this to work correctly. This prevents information leakage of the
internal index to th... | [
"def",
"apply_func_to_select_indices",
"(",
"self",
",",
"axis",
",",
"func",
",",
"indices",
",",
"keep_remaining",
"=",
"False",
")",
":",
"if",
"self",
".",
"partitions",
".",
"size",
"==",
"0",
":",
"return",
"np",
".",
"array",
"(",
"[",
"[",
"]",... | Applies a function to select indices.
Note: Your internal function must take a kwarg `internal_indices` for
this to work correctly. This prevents information leakage of the
internal index to the external representation.
Args:
axis: The axis to apply the func over.
... | [
"Applies",
"a",
"function",
"to",
"select",
"indices",
"."
] | python | train | 44.02521 |
miguelgrinberg/python-socketio | socketio/namespace.py | https://github.com/miguelgrinberg/python-socketio/blob/c0c1bf8d21e3597389b18938550a0724dd9676b7/socketio/namespace.py#L8-L18 | def trigger_event(self, event, *args):
"""Dispatch an event to the proper handler method.
In the most common usage, this method is not overloaded by subclasses,
as it performs the routing of events to methods. However, this
method can be overriden if special dispatching rules are needed... | [
"def",
"trigger_event",
"(",
"self",
",",
"event",
",",
"*",
"args",
")",
":",
"handler_name",
"=",
"'on_'",
"+",
"event",
"if",
"hasattr",
"(",
"self",
",",
"handler_name",
")",
":",
"return",
"getattr",
"(",
"self",
",",
"handler_name",
")",
"(",
"*"... | Dispatch an event to the proper handler method.
In the most common usage, this method is not overloaded by subclasses,
as it performs the routing of events to methods. However, this
method can be overriden if special dispatching rules are needed, or if
having a single method that catche... | [
"Dispatch",
"an",
"event",
"to",
"the",
"proper",
"handler",
"method",
"."
] | python | train | 47.909091 |
xtream1101/cutil | cutil/__init__.py | https://github.com/xtream1101/cutil/blob/2e4d1f00e66154b44d4ccffb9b1db3f37e87f2e8/cutil/__init__.py#L473-L491 | def timeit(stat_tracker_func, name):
"""
Pass in a function and the name of the stat
Will time the function that this is a decorator to and send
the `name` as well as the value (in seconds) to `stat_tracker_func`
`stat_tracker_func` can be used to either print out the data or save it
"""
de... | [
"def",
"timeit",
"(",
"stat_tracker_func",
",",
"name",
")",
":",
"def",
"_timeit",
"(",
"func",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"result",
"=",
"func",
... | Pass in a function and the name of the stat
Will time the function that this is a decorator to and send
the `name` as well as the value (in seconds) to `stat_tracker_func`
`stat_tracker_func` can be used to either print out the data or save it | [
"Pass",
"in",
"a",
"function",
"and",
"the",
"name",
"of",
"the",
"stat",
"Will",
"time",
"the",
"function",
"that",
"this",
"is",
"a",
"decorator",
"to",
"and",
"send",
"the",
"name",
"as",
"well",
"as",
"the",
"value",
"(",
"in",
"seconds",
")",
"t... | python | train | 31.263158 |
openvax/datacache | datacache/download.py | https://github.com/openvax/datacache/blob/73bcac02d37cf153710a07fbdc636aa55cb214ca/datacache/download.py#L145-L156 | def file_exists(
download_url,
filename=None,
decompress=False,
subdir=None):
"""
Return True if a local file corresponding to these arguments
exists.
"""
filename = build_local_filename(download_url, filename, decompress)
full_path = build_path(filename, subdir)
... | [
"def",
"file_exists",
"(",
"download_url",
",",
"filename",
"=",
"None",
",",
"decompress",
"=",
"False",
",",
"subdir",
"=",
"None",
")",
":",
"filename",
"=",
"build_local_filename",
"(",
"download_url",
",",
"filename",
",",
"decompress",
")",
"full_path",
... | Return True if a local file corresponding to these arguments
exists. | [
"Return",
"True",
"if",
"a",
"local",
"file",
"corresponding",
"to",
"these",
"arguments",
"exists",
"."
] | python | train | 28.75 |
google/openhtf | openhtf/plugs/usb/adb_device.py | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/adb_device.py#L191-L224 | def _check_remote_command(self, destination, timeout_ms, success_msgs=None):
"""Open a stream to destination, check for remote errors.
Used for reboot, remount, and root services. If this method returns, the
command was successful, otherwise an appropriate error will have been
raised.
Args:
... | [
"def",
"_check_remote_command",
"(",
"self",
",",
"destination",
",",
"timeout_ms",
",",
"success_msgs",
"=",
"None",
")",
":",
"timeout",
"=",
"timeouts",
".",
"PolledTimeout",
".",
"from_millis",
"(",
"timeout_ms",
")",
"stream",
"=",
"self",
".",
"_adb_conn... | Open a stream to destination, check for remote errors.
Used for reboot, remount, and root services. If this method returns, the
command was successful, otherwise an appropriate error will have been
raised.
Args:
destination: Stream destination to open.
timeout_ms: Timeout in milliseconds ... | [
"Open",
"a",
"stream",
"to",
"destination",
"check",
"for",
"remote",
"errors",
"."
] | python | train | 41.558824 |
Cadasta/django-tutelary | tutelary/wildtree.py | https://github.com/Cadasta/django-tutelary/blob/66bb05de7098777c0a383410c287bf48433cde87/tutelary/wildtree.py#L159-L184 | def find_in_tree(tree, key, perfect=False):
"""
Helper to perform find in dictionary tree.
"""
if len(key) == 0:
if tree['item'] is not None:
return tree['item'], ()
else:
for i in range(len(tree['subtrees'])):
if not perfect and tree['subtrees'][i... | [
"def",
"find_in_tree",
"(",
"tree",
",",
"key",
",",
"perfect",
"=",
"False",
")",
":",
"if",
"len",
"(",
"key",
")",
"==",
"0",
":",
"if",
"tree",
"[",
"'item'",
"]",
"is",
"not",
"None",
":",
"return",
"tree",
"[",
"'item'",
"]",
",",
"(",
")... | Helper to perform find in dictionary tree. | [
"Helper",
"to",
"perform",
"find",
"in",
"dictionary",
"tree",
"."
] | python | train | 38.807692 |
scott-maddox/openbandparams | src/openbandparams/iii_v_zinc_blende_strained.py | https://github.com/scott-maddox/openbandparams/blob/bc24e59187326bcb8948117434536082c9055777/src/openbandparams/iii_v_zinc_blende_strained.py#L180-L184 | def Eg(self, **kwargs):
'''
Returns the strain-shifted bandgap, ``Eg``.
'''
return self.unstrained.Eg(**kwargs) + self.Eg_strain_shift(**kwargs) | [
"def",
"Eg",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"unstrained",
".",
"Eg",
"(",
"*",
"*",
"kwargs",
")",
"+",
"self",
".",
"Eg_strain_shift",
"(",
"*",
"*",
"kwargs",
")"
] | Returns the strain-shifted bandgap, ``Eg``. | [
"Returns",
"the",
"strain",
"-",
"shifted",
"bandgap",
"Eg",
"."
] | python | train | 34.4 |
hustlzp/Flask-Boost | flask_boost/cli.py | https://github.com/hustlzp/Flask-Boost/blob/d0308408ebb248dd752b77123b845f8ec637fab2/flask_boost/cli.py#L303-L313 | def _mkdir_p(path):
"""mkdir -p path"""
try:
os.makedirs(path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
else:
logger.info("New: %s%s", path, os.path.sep) | [
"def",
"_mkdir_p",
"(",
"path",
")",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"path",
")",
"except",
"OSError",
"as",
"exc",
":",
"if",
"exc",
".",
"errno",
"==",
"errno",
".",
"EEXIST",
"and",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")... | mkdir -p path | [
"mkdir",
"-",
"p",
"path"
] | python | test | 24.363636 |
GluuFederation/oxd-python | oxdpython/client.py | https://github.com/GluuFederation/oxd-python/blob/a0448cda03b4384bc50a8c20bd65eacd983bceb8/oxdpython/client.py#L513-L536 | def uma_rp_get_claims_gathering_url(self, ticket):
"""UMA RP function to get the claims gathering URL.
Parameters:
* **ticket (str):** ticket to pass to the auth server. for 90% of the cases, this will be obtained from 'need_info' error of get_rpt
Returns:
**string** sp... | [
"def",
"uma_rp_get_claims_gathering_url",
"(",
"self",
",",
"ticket",
")",
":",
"params",
"=",
"{",
"'oxd_id'",
":",
"self",
".",
"oxd_id",
",",
"'claims_redirect_uri'",
":",
"self",
".",
"config",
".",
"get",
"(",
"'client'",
",",
"'claims_redirect_uri'",
")"... | UMA RP function to get the claims gathering URL.
Parameters:
* **ticket (str):** ticket to pass to the auth server. for 90% of the cases, this will be obtained from 'need_info' error of get_rpt
Returns:
**string** specifying the claims gathering url | [
"UMA",
"RP",
"function",
"to",
"get",
"the",
"claims",
"gathering",
"URL",
"."
] | python | train | 41.666667 |
20c/xbahn | xbahn/engineer.py | https://github.com/20c/xbahn/blob/afb27b0576841338a366d7cac0200a782bd84be6/xbahn/engineer.py#L163-L176 | def connect(self, ctx):
"""
establish xbahn connection and store on click context
"""
if hasattr(ctx,"conn") or "host" not in ctx.params:
return
ctx.conn = conn = connect(ctx.params["host"])
lnk = link.Link()
lnk.wire("main", receive=conn, send=conn... | [
"def",
"connect",
"(",
"self",
",",
"ctx",
")",
":",
"if",
"hasattr",
"(",
"ctx",
",",
"\"conn\"",
")",
"or",
"\"host\"",
"not",
"in",
"ctx",
".",
"params",
":",
"return",
"ctx",
".",
"conn",
"=",
"conn",
"=",
"connect",
"(",
"ctx",
".",
"params",
... | establish xbahn connection and store on click context | [
"establish",
"xbahn",
"connection",
"and",
"store",
"on",
"click",
"context"
] | python | train | 29.142857 |
wiheto/teneto | teneto/timeseries/derive.py | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/timeseries/derive.py#L16-L237 | def derive_temporalnetwork(data, params):
"""
Derives connectivity from the data. A lot of data is inherently built with edges
(e.g. communication between two individuals).
However other networks are derived from the covariance of time series
(e.g. brain networks between two regions).
Covaria... | [
"def",
"derive_temporalnetwork",
"(",
"data",
",",
"params",
")",
":",
"report",
"=",
"{",
"}",
"if",
"'dimord'",
"not",
"in",
"params",
".",
"keys",
"(",
")",
":",
"params",
"[",
"'dimord'",
"]",
"=",
"'node,time'",
"if",
"'report'",
"not",
"in",
"par... | Derives connectivity from the data. A lot of data is inherently built with edges
(e.g. communication between two individuals).
However other networks are derived from the covariance of time series
(e.g. brain networks between two regions).
Covariance based metrics deriving time-resolved networks can ... | [
"Derives",
"connectivity",
"from",
"the",
"data",
".",
"A",
"lot",
"of",
"data",
"is",
"inherently",
"built",
"with",
"edges",
"(",
"e",
".",
"g",
".",
"communication",
"between",
"two",
"individuals",
")",
".",
"However",
"other",
"networks",
"are",
"deri... | python | train | 39.995495 |
oasis-open/cti-stix-validator | stix2validator/v21/shoulds.py | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L854-L870 | def socket_options(instance):
"""Ensure the keys of the 'options' property of the socket-ext extension of
network-traffic objects are only valid socket options (SO_*).
"""
for key, obj in instance['objects'].items():
if ('type' in obj and obj['type'] == 'network-traffic'):
try:
... | [
"def",
"socket_options",
"(",
"instance",
")",
":",
"for",
"key",
",",
"obj",
"in",
"instance",
"[",
"'objects'",
"]",
".",
"items",
"(",
")",
":",
"if",
"(",
"'type'",
"in",
"obj",
"and",
"obj",
"[",
"'type'",
"]",
"==",
"'network-traffic'",
")",
":... | Ensure the keys of the 'options' property of the socket-ext extension of
network-traffic objects are only valid socket options (SO_*). | [
"Ensure",
"the",
"keys",
"of",
"the",
"options",
"property",
"of",
"the",
"socket",
"-",
"ext",
"extension",
"of",
"network",
"-",
"traffic",
"objects",
"are",
"only",
"valid",
"socket",
"options",
"(",
"SO_",
"*",
")",
"."
] | python | train | 47.529412 |
marcomusy/vtkplotter | vtkplotter/actors.py | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L2212-L2220 | def cellCenters(self):
"""Get the list of cell centers of the mesh surface.
.. hint:: |delaunay2d| |delaunay2d.py|_
"""
vcen = vtk.vtkCellCenters()
vcen.SetInputData(self.polydata(True))
vcen.Update()
return vtk_to_numpy(vcen.GetOutput().GetPoints().GetData()) | [
"def",
"cellCenters",
"(",
"self",
")",
":",
"vcen",
"=",
"vtk",
".",
"vtkCellCenters",
"(",
")",
"vcen",
".",
"SetInputData",
"(",
"self",
".",
"polydata",
"(",
"True",
")",
")",
"vcen",
".",
"Update",
"(",
")",
"return",
"vtk_to_numpy",
"(",
"vcen",
... | Get the list of cell centers of the mesh surface.
.. hint:: |delaunay2d| |delaunay2d.py|_ | [
"Get",
"the",
"list",
"of",
"cell",
"centers",
"of",
"the",
"mesh",
"surface",
"."
] | python | train | 34.333333 |
portfors-lab/sparkle | sparkle/gui/stim/abstract_stim_editor.py | https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/stim/abstract_stim_editor.py#L51-L68 | def closeEvent(self, event):
"""Verifies the stimulus before closing, warns user with a
dialog if there are any problems"""
self.ok.setText("Checking...")
QtGui.QApplication.processEvents()
self.model().cleanComponents()
self.model().purgeAutoSelected()
msg = self... | [
"def",
"closeEvent",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"ok",
".",
"setText",
"(",
"\"Checking...\"",
")",
"QtGui",
".",
"QApplication",
".",
"processEvents",
"(",
")",
"self",
".",
"model",
"(",
")",
".",
"cleanComponents",
"(",
")",
"s... | Verifies the stimulus before closing, warns user with a
dialog if there are any problems | [
"Verifies",
"the",
"stimulus",
"before",
"closing",
"warns",
"user",
"with",
"a",
"dialog",
"if",
"there",
"are",
"any",
"problems"
] | python | train | 47.611111 |
benvanwerkhoven/kernel_tuner | kernel_tuner/c.py | https://github.com/benvanwerkhoven/kernel_tuner/blob/cfcb5da5e510db494f8219c22566ab65d5fcbd9f/kernel_tuner/c.py#L296-L308 | def memset(self, allocation, value, size):
"""set the memory in allocation to the value in value
:param allocation: An Argument for some memory allocation unit
:type allocation: Argument
:param value: The value to set the memory to
:type value: a single 8-bit unsigned int
... | [
"def",
"memset",
"(",
"self",
",",
"allocation",
",",
"value",
",",
"size",
")",
":",
"C",
".",
"memset",
"(",
"allocation",
".",
"ctypes",
",",
"value",
",",
"size",
")"
] | set the memory in allocation to the value in value
:param allocation: An Argument for some memory allocation unit
:type allocation: Argument
:param value: The value to set the memory to
:type value: a single 8-bit unsigned int
:param size: The size of to the allocation unit in... | [
"set",
"the",
"memory",
"in",
"allocation",
"to",
"the",
"value",
"in",
"value"
] | python | train | 34.846154 |
sentinel-hub/eo-learn | mask/eolearn/mask/masking.py | https://github.com/sentinel-hub/eo-learn/blob/b8c390b9f553c561612fe9eb64e720611633a035/mask/eolearn/mask/masking.py#L67-L87 | def execute(self, eopatch):
""" Mask values of `feature` according to the `mask_values` in `mask_feature`
:param eopatch: `eopatch` to be processed
:return: Same `eopatch` instance with masked `feature`
"""
feature_type, feature_name, new_feature_name = next(self.feature(eopatch... | [
"def",
"execute",
"(",
"self",
",",
"eopatch",
")",
":",
"feature_type",
",",
"feature_name",
",",
"new_feature_name",
"=",
"next",
"(",
"self",
".",
"feature",
"(",
"eopatch",
")",
")",
"mask_feature_type",
",",
"mask_feature_name",
"=",
"next",
"(",
"self"... | Mask values of `feature` according to the `mask_values` in `mask_feature`
:param eopatch: `eopatch` to be processed
:return: Same `eopatch` instance with masked `feature` | [
"Mask",
"values",
"of",
"feature",
"according",
"to",
"the",
"mask_values",
"in",
"mask_feature"
] | python | train | 39.761905 |
senseobservationsystems/commonsense-python-lib | senseapi.py | https://github.com/senseobservationsystems/commonsense-python-lib/blob/aac59a1751ef79eb830b3ca1fab6ef2c83931f87/senseapi.py#L1830-L1842 | def DataProcessorsDelete(self, dataProcessorId):
"""
Delete a data processor in CommonSense.
@param dataProcessorId - The id of the data processor that will be deleted.
@return (bool) - Boolean indicating whether GroupsP... | [
"def",
"DataProcessorsDelete",
"(",
"self",
",",
"dataProcessorId",
")",
":",
"if",
"self",
".",
"__SenseApiCall__",
"(",
"'/dataprocessors/{id}.json'",
".",
"format",
"(",
"id",
"=",
"dataProcessorId",
")",
",",
"'DELETE'",
")",
":",
"return",
"True",
"else",
... | Delete a data processor in CommonSense.
@param dataProcessorId - The id of the data processor that will be deleted.
@return (bool) - Boolean indicating whether GroupsPost was successful. | [
"Delete",
"a",
"data",
"processor",
"in",
"CommonSense",
"."
] | python | train | 43.307692 |
nickpandolfi/Cyther | cyther/processing.py | https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/processing.py#L24-L33 | def initiateCompilation(args, file):
"""
Starts the entire compilation procedure
"""
####commands = finalizeCommands(args, file)
commands = makeCommands(0, file)
if not args['concise'] and args['print_args']:
print_commands = bool(args['watch'])
response = multiCall(*commands, print_... | [
"def",
"initiateCompilation",
"(",
"args",
",",
"file",
")",
":",
"####commands = finalizeCommands(args, file)",
"commands",
"=",
"makeCommands",
"(",
"0",
",",
"file",
")",
"if",
"not",
"args",
"[",
"'concise'",
"]",
"and",
"args",
"[",
"'print_args'",
"]",
"... | Starts the entire compilation procedure | [
"Starts",
"the",
"entire",
"compilation",
"procedure"
] | python | train | 35.5 |
pandas-dev/pandas | pandas/core/series.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/series.py#L4095-L4168 | def between(self, left, right, inclusive=True):
"""
Return boolean Series equivalent to left <= series <= right.
This function returns a boolean vector containing `True` wherever the
corresponding Series element is between the boundary values `left` and
`right`. NA values are tr... | [
"def",
"between",
"(",
"self",
",",
"left",
",",
"right",
",",
"inclusive",
"=",
"True",
")",
":",
"if",
"inclusive",
":",
"lmask",
"=",
"self",
">=",
"left",
"rmask",
"=",
"self",
"<=",
"right",
"else",
":",
"lmask",
"=",
"self",
">",
"left",
"rma... | Return boolean Series equivalent to left <= series <= right.
This function returns a boolean vector containing `True` wherever the
corresponding Series element is between the boundary values `left` and
`right`. NA values are treated as `False`.
Parameters
----------
lef... | [
"Return",
"boolean",
"Series",
"equivalent",
"to",
"left",
"<",
"=",
"series",
"<",
"=",
"right",
"."
] | python | train | 24.864865 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.