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 |
|---|---|---|---|---|---|---|---|---|---|
icometrix/dicom2nifti | dicom2nifti/common.py | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/common.py#L638-L660 | def validate_slice_increment(dicoms):
"""
Validate that the distance between all slices is equal (or very close to)
:param dicoms: list of dicoms
"""
first_image_position = numpy.array(dicoms[0].ImagePositionPatient)
previous_image_position = numpy.array(dicoms[1].ImagePositionPatient)
inc... | [
"def",
"validate_slice_increment",
"(",
"dicoms",
")",
":",
"first_image_position",
"=",
"numpy",
".",
"array",
"(",
"dicoms",
"[",
"0",
"]",
".",
"ImagePositionPatient",
")",
"previous_image_position",
"=",
"numpy",
".",
"array",
"(",
"dicoms",
"[",
"1",
"]",... | Validate that the distance between all slices is equal (or very close to)
:param dicoms: list of dicoms | [
"Validate",
"that",
"the",
"distance",
"between",
"all",
"slices",
"is",
"equal",
"(",
"or",
"very",
"close",
"to",
")"
] | python | train | 55.782609 |
marrow/mongo | marrow/mongo/core/trait/collection.py | https://github.com/marrow/mongo/blob/2066dc73e281b8a46cb5fc965267d6b8e1b18467/marrow/mongo/core/trait/collection.py#L70-L82 | def bind(cls, target):
"""Bind a copy of the collection to the class, modified per our class' settings.
The given target (and eventual collection returned) must be safe within the context the document sublcass
being bound is constructed within. E.g. at the module scope this binding must be thread-safe.
"""
... | [
"def",
"bind",
"(",
"cls",
",",
"target",
")",
":",
"if",
"cls",
".",
"__bound__",
"is",
"not",
"None",
":",
"return",
"cls",
"cls",
".",
"__bound__",
"=",
"cls",
".",
"get_collection",
"(",
"target",
")",
"return",
"cls"
] | Bind a copy of the collection to the class, modified per our class' settings.
The given target (and eventual collection returned) must be safe within the context the document sublcass
being bound is constructed within. E.g. at the module scope this binding must be thread-safe. | [
"Bind",
"a",
"copy",
"of",
"the",
"collection",
"to",
"the",
"class",
"modified",
"per",
"our",
"class",
"settings",
".",
"The",
"given",
"target",
"(",
"and",
"eventual",
"collection",
"returned",
")",
"must",
"be",
"safe",
"within",
"the",
"context",
"th... | python | train | 32.230769 |
apple/turicreate | src/unity/python/turicreate/data_structures/sarray.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L3296-L3493 | def unpack(self, column_name_prefix = "X", column_types=None, na_value=None, limit=None):
"""
Convert an SArray of list, array, or dict type to an SFrame with
multiple columns.
`unpack` expands an SArray using the values of each list/array/dict as
elements in a new SFrame of mul... | [
"def",
"unpack",
"(",
"self",
",",
"column_name_prefix",
"=",
"\"X\"",
",",
"column_types",
"=",
"None",
",",
"na_value",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"from",
".",
"sframe",
"import",
"SFrame",
"as",
"_SFrame",
"if",
"self",
".",
"... | Convert an SArray of list, array, or dict type to an SFrame with
multiple columns.
`unpack` expands an SArray using the values of each list/array/dict as
elements in a new SFrame of multiple columns. For example, an SArray of
lists each of length 4 will be expanded into an SFrame of 4 c... | [
"Convert",
"an",
"SArray",
"of",
"list",
"array",
"or",
"dict",
"type",
"to",
"an",
"SFrame",
"with",
"multiple",
"columns",
"."
] | python | train | 37.156566 |
JoelBender/bacpypes | samples/ReadPropertyMultiple25.py | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/samples/ReadPropertyMultiple25.py#L43-L181 | def do_read(self, args):
"""read <addr> ( <objid> ( <prop> [ <indx> ] )... )..."""
args = args.split()
if _debug: ReadPropertyMultipleConsoleCmd._debug("do_read %r", args)
try:
i = 0
addr = args[i]
i += 1
read_access_spec_list = []
... | [
"def",
"do_read",
"(",
"self",
",",
"args",
")",
":",
"args",
"=",
"args",
".",
"split",
"(",
")",
"if",
"_debug",
":",
"ReadPropertyMultipleConsoleCmd",
".",
"_debug",
"(",
"\"do_read %r\"",
",",
"args",
")",
"try",
":",
"i",
"=",
"0",
"addr",
"=",
... | read <addr> ( <objid> ( <prop> [ <indx> ] )... )... | [
"read",
"<addr",
">",
"(",
"<objid",
">",
"(",
"<prop",
">",
"[",
"<indx",
">",
"]",
")",
"...",
")",
"..."
] | python | train | 42.726619 |
etcher-be/epab | epab/cmd/_release.py | https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/cmd/_release.py#L23-L36 | def _clean():
"""
Cleans up build dir
"""
LOGGER.info('Cleaning project directory...')
folders_to_cleanup = [
'.eggs',
'build',
f'{config.PACKAGE_NAME()}.egg-info',
]
for folder in folders_to_cleanup:
if os.path.exists(folder):
LOGGER.info('\tremov... | [
"def",
"_clean",
"(",
")",
":",
"LOGGER",
".",
"info",
"(",
"'Cleaning project directory...'",
")",
"folders_to_cleanup",
"=",
"[",
"'.eggs'",
",",
"'build'",
",",
"f'{config.PACKAGE_NAME()}.egg-info'",
",",
"]",
"for",
"folder",
"in",
"folders_to_cleanup",
":",
"... | Cleans up build dir | [
"Cleans",
"up",
"build",
"dir"
] | python | train | 25.571429 |
wummel/linkchecker | linkcheck/bookmarks/safari.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/bookmarks/safari.py#L34-L49 | def find_bookmark_file ():
"""Return the bookmark file of the Default profile.
Returns absolute filename if found, or empty string if no bookmark file
could be found.
"""
if sys.platform != 'darwin':
return u""
try:
dirname = get_profile_dir()
if os.path.isdir(dirname):
... | [
"def",
"find_bookmark_file",
"(",
")",
":",
"if",
"sys",
".",
"platform",
"!=",
"'darwin'",
":",
"return",
"u\"\"",
"try",
":",
"dirname",
"=",
"get_profile_dir",
"(",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"dirname",
")",
":",
"fname",
"=",
... | Return the bookmark file of the Default profile.
Returns absolute filename if found, or empty string if no bookmark file
could be found. | [
"Return",
"the",
"bookmark",
"file",
"of",
"the",
"Default",
"profile",
".",
"Returns",
"absolute",
"filename",
"if",
"found",
"or",
"empty",
"string",
"if",
"no",
"bookmark",
"file",
"could",
"be",
"found",
"."
] | python | train | 30.125 |
ellethee/argparseinator | argparseinator/utils.py | https://github.com/ellethee/argparseinator/blob/05e9c00dfaa938b9c4ee2aadc6206f5e0918e24e/argparseinator/utils.py#L156-L171 | def has_argument(arg, arguments):
"""
Verifica se ci sono argument con la classe.
"""
try:
if not isinstance(arguments, list):
arguments = arguments.__arguments__
for idx, (args, kwargs) in enumerate(arguments):
arg_name = kwargs.get(
'dest', args[... | [
"def",
"has_argument",
"(",
"arg",
",",
"arguments",
")",
":",
"try",
":",
"if",
"not",
"isinstance",
"(",
"arguments",
",",
"list",
")",
":",
"arguments",
"=",
"arguments",
".",
"__arguments__",
"for",
"idx",
",",
"(",
"args",
",",
"kwargs",
")",
"in"... | Verifica se ci sono argument con la classe. | [
"Verifica",
"se",
"ci",
"sono",
"argument",
"con",
"la",
"classe",
"."
] | python | train | 30.875 |
morepath/more.jwtauth | more/jwtauth/main.py | https://github.com/morepath/more.jwtauth/blob/1c3c5731612069a092e44cf612641c05edf1f083/more/jwtauth/main.py#L335-L352 | def get_jwt(self, request):
"""Extract the JWT token from the authorisation header of the request.
Returns the JWT token or None, if the token cannot be extracted.
:param request: request object.
:type request: :class:`morepath.Request`
"""
try:
authorizatio... | [
"def",
"get_jwt",
"(",
"self",
",",
"request",
")",
":",
"try",
":",
"authorization",
"=",
"request",
".",
"authorization",
"except",
"ValueError",
":",
"return",
"None",
"if",
"authorization",
"is",
"None",
":",
"return",
"None",
"authtype",
",",
"token",
... | Extract the JWT token from the authorisation header of the request.
Returns the JWT token or None, if the token cannot be extracted.
:param request: request object.
:type request: :class:`morepath.Request` | [
"Extract",
"the",
"JWT",
"token",
"from",
"the",
"authorisation",
"header",
"of",
"the",
"request",
"."
] | python | train | 32.555556 |
dcaune/perseus-lib-python-common | majormode/perseus/utils/rdbms.py | https://github.com/dcaune/perseus-lib-python-common/blob/ba48fe0fd9bb4a75b53e7d10c41ada36a72d4496/majormode/perseus/utils/rdbms.py#L426-L479 | def acquire_connection(settings, tag=None, logger_name=None, auto_commit=False):
"""
Return a connection to a Relational DataBase Management System (RDBMS)
the most appropriate for the service requesting this connection.
@param settings: a dictionary of connection properties::
... | [
"def",
"acquire_connection",
"(",
"settings",
",",
"tag",
"=",
"None",
",",
"logger_name",
"=",
"None",
",",
"auto_commit",
"=",
"False",
")",
":",
"try",
":",
"connection_properties",
"=",
"settings",
".",
"get",
"(",
"tag",
",",
"settings",
"[",
"None",
... | Return a connection to a Relational DataBase Management System (RDBMS)
the most appropriate for the service requesting this connection.
@param settings: a dictionary of connection properties::
{
None: {
'rdbms_hostname': "...",
... | [
"Return",
"a",
"connection",
"to",
"a",
"Relational",
"DataBase",
"Management",
"System",
"(",
"RDBMS",
")",
"the",
"most",
"appropriate",
"for",
"the",
"service",
"requesting",
"this",
"connection",
"."
] | python | train | 41.814815 |
gsi-upm/soil | examples/pubcrawl/pubcrawl.py | https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/examples/pubcrawl/pubcrawl.py#L43-L53 | def exit(self, pub_id, *node_ids):
'''Agents will notify the pub they want to leave'''
try:
pub = self['pubs'][pub_id]
except KeyError:
raise ValueError('Pub {} is not available'.format(pub_id))
for node_id in node_ids:
node = self.get_agent(node_id)
... | [
"def",
"exit",
"(",
"self",
",",
"pub_id",
",",
"*",
"node_ids",
")",
":",
"try",
":",
"pub",
"=",
"self",
"[",
"'pubs'",
"]",
"[",
"pub_id",
"]",
"except",
"KeyError",
":",
"raise",
"ValueError",
"(",
"'Pub {} is not available'",
".",
"format",
"(",
"... | Agents will notify the pub they want to leave | [
"Agents",
"will",
"notify",
"the",
"pub",
"they",
"want",
"to",
"leave"
] | python | train | 37.818182 |
fastai/fastai | fastai/vision/image.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L409-L414 | def rle_encode(img:NPArrayMask)->str:
"Return run-length encoding string from `img`."
pixels = np.concatenate([[0], img.flatten() , [0]])
runs = np.where(pixels[1:] != pixels[:-1])[0] + 1
runs[1::2] -= runs[::2]
return ' '.join(str(x) for x in runs) | [
"def",
"rle_encode",
"(",
"img",
":",
"NPArrayMask",
")",
"->",
"str",
":",
"pixels",
"=",
"np",
".",
"concatenate",
"(",
"[",
"[",
"0",
"]",
",",
"img",
".",
"flatten",
"(",
")",
",",
"[",
"0",
"]",
"]",
")",
"runs",
"=",
"np",
".",
"where",
... | Return run-length encoding string from `img`. | [
"Return",
"run",
"-",
"length",
"encoding",
"string",
"from",
"img",
"."
] | python | train | 44 |
basho/riak-python-client | riak/transports/http/connection.py | https://github.com/basho/riak-python-client/blob/91de13a16607cdf553d1a194e762734e3bec4231/riak/transports/http/connection.py#L101-L115 | def _security_auth_headers(self, username, password, headers):
"""
Add in the requisite HTTP Authentication Headers
:param username: Riak Security Username
:type str
:param password: Riak Security Password
:type str
:param headers: Dictionary of headers
:... | [
"def",
"_security_auth_headers",
"(",
"self",
",",
"username",
",",
"password",
",",
"headers",
")",
":",
"userColonPassword",
"=",
"username",
"+",
"\":\"",
"+",
"password",
"b64UserColonPassword",
"=",
"base64",
".",
"b64encode",
"(",
"str_to_bytes",
"(",
"use... | Add in the requisite HTTP Authentication Headers
:param username: Riak Security Username
:type str
:param password: Riak Security Password
:type str
:param headers: Dictionary of headers
:type dict | [
"Add",
"in",
"the",
"requisite",
"HTTP",
"Authentication",
"Headers"
] | python | train | 37.466667 |
pybel/pybel | src/pybel/struct/filters/node_filters.py | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/filters/node_filters.py#L84-L86 | def count_passed_node_filter(graph: BELGraph, node_predicates: NodePredicates) -> int:
"""Count how many nodes pass a given set of node predicates."""
return sum(1 for _ in filter_nodes(graph, node_predicates=node_predicates)) | [
"def",
"count_passed_node_filter",
"(",
"graph",
":",
"BELGraph",
",",
"node_predicates",
":",
"NodePredicates",
")",
"->",
"int",
":",
"return",
"sum",
"(",
"1",
"for",
"_",
"in",
"filter_nodes",
"(",
"graph",
",",
"node_predicates",
"=",
"node_predicates",
"... | Count how many nodes pass a given set of node predicates. | [
"Count",
"how",
"many",
"nodes",
"pass",
"a",
"given",
"set",
"of",
"node",
"predicates",
"."
] | python | train | 77.333333 |
thombashi/SimpleSQLite | simplesqlite/core.py | https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L595-L623 | def update(self, table_name, set_query, where=None):
"""Execute an UPDATE query.
Args:
table_name (|str|):
Table name of executing the query.
set_query (|str|):
``SET`` clause for the update query.
where (|arg_where_type| , optional):
... | [
"def",
"update",
"(",
"self",
",",
"table_name",
",",
"set_query",
",",
"where",
"=",
"None",
")",
":",
"self",
".",
"validate_access_permission",
"(",
"[",
"\"w\"",
",",
"\"a\"",
"]",
")",
"self",
".",
"verify_table_existence",
"(",
"table_name",
")",
"qu... | Execute an UPDATE query.
Args:
table_name (|str|):
Table name of executing the query.
set_query (|str|):
``SET`` clause for the update query.
where (|arg_where_type| , optional):
``WHERE`` clause for the update query.
... | [
"Execute",
"an",
"UPDATE",
"query",
"."
] | python | train | 34.275862 |
bretth/woven | woven/webservers.py | https://github.com/bretth/woven/blob/ec1da7b401a335f43129e7115fe7a4d145649f1e/woven/webservers.py#L277-L284 | def webserver_list():
"""
list of webserver packages
"""
p = set(get_packages())
w = set(['apache2','gunicorn','uwsgi','nginx'])
installed = p & w
return list(installed) | [
"def",
"webserver_list",
"(",
")",
":",
"p",
"=",
"set",
"(",
"get_packages",
"(",
")",
")",
"w",
"=",
"set",
"(",
"[",
"'apache2'",
",",
"'gunicorn'",
",",
"'uwsgi'",
",",
"'nginx'",
"]",
")",
"installed",
"=",
"p",
"&",
"w",
"return",
"list",
"("... | list of webserver packages | [
"list",
"of",
"webserver",
"packages"
] | python | train | 23.75 |
genomoncology/related | src/related/fields.py | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/fields.py#L259-L274 | def UUIDField(default=NOTHING, required=False, repr=True, cmp=True, key=None):
"""
Create new UUID field on a model.
:param default: any value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param ... | [
"def",
"UUIDField",
"(",
"default",
"=",
"NOTHING",
",",
"required",
"=",
"False",
",",
"repr",
"=",
"True",
",",
"cmp",
"=",
"True",
",",
"key",
"=",
"None",
")",
":",
"cls",
"=",
"UUID",
"default",
"=",
"_init_fields",
".",
"init_default",
"(",
"re... | Create new UUID field on a model.
:param default: any value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name ... | [
"Create",
"new",
"UUID",
"field",
"on",
"a",
"model",
"."
] | python | train | 46.875 |
globus/globus-cli | globus_cli/parsing/shared_options.py | https://github.com/globus/globus-cli/blob/336675ff24da64c5ee487243f39ae39fc49a7e14/globus_cli/parsing/shared_options.py#L664-L753 | def server_add_and_update_opts(*args, **kwargs):
"""
shared collection of options for `globus transfer endpoint server add` and
`globus transfer endpoint server update`.
Accepts a toggle to know if it's being used as `add` or `update`.
usage:
>>> @server_add_and_update_opts
>>> def command... | [
"def",
"server_add_and_update_opts",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"port_range_callback",
"(",
"ctx",
",",
"param",
",",
"value",
")",
":",
"if",
"not",
"value",
":",
"return",
"None",
"value",
"=",
"value",
".",
"lower",
... | shared collection of options for `globus transfer endpoint server add` and
`globus transfer endpoint server update`.
Accepts a toggle to know if it's being used as `add` or `update`.
usage:
>>> @server_add_and_update_opts
>>> def command_func(subject, port, scheme, hostname):
>>> ...
... | [
"shared",
"collection",
"of",
"options",
"for",
"globus",
"transfer",
"endpoint",
"server",
"add",
"and",
"globus",
"transfer",
"endpoint",
"server",
"update",
".",
"Accepts",
"a",
"toggle",
"to",
"know",
"if",
"it",
"s",
"being",
"used",
"as",
"add",
"or",
... | python | train | 33.144444 |
SoCo/SoCo | soco/snapshot.py | https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/snapshot.py#L255-L274 | def _save_queue(self):
"""Save the current state of the queue."""
if self.queue is not None:
# Maximum batch is 486, anything larger will still only
# return 486
batch_size = 400
total = 0
num_return = batch_size
# Need to get all ... | [
"def",
"_save_queue",
"(",
"self",
")",
":",
"if",
"self",
".",
"queue",
"is",
"not",
"None",
":",
"# Maximum batch is 486, anything larger will still only",
"# return 486",
"batch_size",
"=",
"400",
"total",
"=",
"0",
"num_return",
"=",
"batch_size",
"# Need to get... | Save the current state of the queue. | [
"Save",
"the",
"current",
"state",
"of",
"the",
"queue",
"."
] | python | train | 43.55 |
numenta/nupic | src/nupic/algorithms/anomaly_likelihood.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/anomaly_likelihood.py#L648-L684 | def _anomalyScoreMovingAverage(anomalyScores,
windowSize=10,
verbosity=0,
):
"""
Given a list of anomaly scores return a list of averaged records.
anomalyScores is assumed to be a list of records of the form:
... | [
"def",
"_anomalyScoreMovingAverage",
"(",
"anomalyScores",
",",
"windowSize",
"=",
"10",
",",
"verbosity",
"=",
"0",
",",
")",
":",
"historicalValues",
"=",
"[",
"]",
"total",
"=",
"0.0",
"averagedRecordList",
"=",
"[",
"]",
"# Aggregated records",
"for",
"rec... | Given a list of anomaly scores return a list of averaged records.
anomalyScores is assumed to be a list of records of the form:
[datetime.datetime(2013, 8, 10, 23, 0), 6.0, 1.0]
Each record in the returned list list contains:
[datetime, value, averagedScore]
*Note:* we only average the ano... | [
"Given",
"a",
"list",
"of",
"anomaly",
"scores",
"return",
"a",
"list",
"of",
"averaged",
"records",
".",
"anomalyScores",
"is",
"assumed",
"to",
"be",
"a",
"list",
"of",
"records",
"of",
"the",
"form",
":",
"[",
"datetime",
".",
"datetime",
"(",
"2013",... | python | valid | 31.702703 |
yakupadakli/python-unsplash | unsplash/stat.py | https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/stat.py#L21-L29 | def month(self):
"""
Get the overall Unsplash stats for the past 30 days.
:return [Stat]: The Unsplash Stat.
"""
url = "/stats/month"
result = self._get(url)
return StatModel.parse(result) | [
"def",
"month",
"(",
"self",
")",
":",
"url",
"=",
"\"/stats/month\"",
"result",
"=",
"self",
".",
"_get",
"(",
"url",
")",
"return",
"StatModel",
".",
"parse",
"(",
"result",
")"
] | Get the overall Unsplash stats for the past 30 days.
:return [Stat]: The Unsplash Stat. | [
"Get",
"the",
"overall",
"Unsplash",
"stats",
"for",
"the",
"past",
"30",
"days",
"."
] | python | train | 26.333333 |
jeffh/rpi_courses | rpi_courses/sis_parser/features.py | https://github.com/jeffh/rpi_courses/blob/c97176f73f866f112c785910ebf3ff8a790e8e9a/rpi_courses/sis_parser/features.py#L32-L52 | def semester_feature(catalog, soup):
"""The year and semester information that this xml file hold courses for.
"""
raw = _text(soup.findAll('h3')).split('\n')[1]
match = RE_SEMESTER_RANGE.match(raw)
catalog.year = int(match.group('year'))
#month_mapping = {'Spring': 1, 'Summer': 5, 'Fall': 9}
... | [
"def",
"semester_feature",
"(",
"catalog",
",",
"soup",
")",
":",
"raw",
"=",
"_text",
"(",
"soup",
".",
"findAll",
"(",
"'h3'",
")",
")",
".",
"split",
"(",
"'\\n'",
")",
"[",
"1",
"]",
"match",
"=",
"RE_SEMESTER_RANGE",
".",
"match",
"(",
"raw",
... | The year and semester information that this xml file hold courses for. | [
"The",
"year",
"and",
"semester",
"information",
"that",
"this",
"xml",
"file",
"hold",
"courses",
"for",
"."
] | python | train | 40.571429 |
mitsei/dlkit | dlkit/primordium/locale/types/time.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/primordium/locale/types/time.py#L70-L100 | def get_type_data(name):
"""Return dictionary representation of type.
Can be used to initialize primordium.type.primitives.Type
"""
name = name.upper()
if name in CELESTIAL_TIME_TYPES:
namespace = 'time'
domain = 'Celestial Time Systems'
time_name = CELESTIAL_TIME_TYPES[nam... | [
"def",
"get_type_data",
"(",
"name",
")",
":",
"name",
"=",
"name",
".",
"upper",
"(",
")",
"if",
"name",
"in",
"CELESTIAL_TIME_TYPES",
":",
"namespace",
"=",
"'time'",
"domain",
"=",
"'Celestial Time Systems'",
"time_name",
"=",
"CELESTIAL_TIME_TYPES",
"[",
"... | Return dictionary representation of type.
Can be used to initialize primordium.type.primitives.Type | [
"Return",
"dictionary",
"representation",
"of",
"type",
"."
] | python | train | 30.419355 |
carpedm20/fbchat | fbchat/_client.py | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L941-L1003 | def fetchThreadInfo(self, *thread_ids):
"""
Get threads' info from IDs, unordered
.. warning::
Sends two requests if users or pages are present, to fetch all available info!
:param thread_ids: One or more thread ID(s) to query
:return: :class:`models.Thread` objects... | [
"def",
"fetchThreadInfo",
"(",
"self",
",",
"*",
"thread_ids",
")",
":",
"queries",
"=",
"[",
"]",
"for",
"thread_id",
"in",
"thread_ids",
":",
"params",
"=",
"{",
"\"id\"",
":",
"thread_id",
",",
"\"message_limit\"",
":",
"0",
",",
"\"load_messages\"",
":... | Get threads' info from IDs, unordered
.. warning::
Sends two requests if users or pages are present, to fetch all available info!
:param thread_ids: One or more thread ID(s) to query
:return: :class:`models.Thread` objects, labeled by their ID
:rtype: dict
:raises: ... | [
"Get",
"threads",
"info",
"from",
"IDs",
"unordered"
] | python | train | 38.396825 |
morpframework/morpfw | morpfw/authn/pas/user/view.py | https://github.com/morpframework/morpfw/blob/803fbf29714e6f29456482f1cfbdbd4922b020b0/morpfw/authn/pas/user/view.py#L60-L89 | def process_login(context, request):
"""Authenticate username and password and log in user"""
username = request.json['username']
password = request.json['password']
# Do the password validation.
user = context.authenticate(username, password)
if not user:
@request.after
def adj... | [
"def",
"process_login",
"(",
"context",
",",
"request",
")",
":",
"username",
"=",
"request",
".",
"json",
"[",
"'username'",
"]",
"password",
"=",
"request",
".",
"json",
"[",
"'password'",
"]",
"# Do the password validation.",
"user",
"=",
"context",
".",
... | Authenticate username and password and log in user | [
"Authenticate",
"username",
"and",
"password",
"and",
"log",
"in",
"user"
] | python | train | 30.6 |
Azure/azure-event-hubs-python | azure/eventhub/common.py | https://github.com/Azure/azure-event-hubs-python/blob/737c5f966557ada2cf10fa0d8f3c19671ae96348/azure/eventhub/common.py#L217-L236 | def body_as_str(self, encoding='UTF-8'):
"""
The body of the event data as a string if the data is of a
compatible type.
:param encoding: The encoding to use for decoding message data.
Default is 'UTF-8'
:rtype: str or unicode
"""
data = self.body
... | [
"def",
"body_as_str",
"(",
"self",
",",
"encoding",
"=",
"'UTF-8'",
")",
":",
"data",
"=",
"self",
".",
"body",
"try",
":",
"return",
"\"\"",
".",
"join",
"(",
"b",
".",
"decode",
"(",
"encoding",
")",
"for",
"b",
"in",
"data",
")",
"except",
"Type... | The body of the event data as a string if the data is of a
compatible type.
:param encoding: The encoding to use for decoding message data.
Default is 'UTF-8'
:rtype: str or unicode | [
"The",
"body",
"of",
"the",
"event",
"data",
"as",
"a",
"string",
"if",
"the",
"data",
"is",
"of",
"a",
"compatible",
"type",
"."
] | python | train | 33.75 |
pyviz/holoviews | holoviews/plotting/bokeh/element.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/plotting/bokeh/element.py#L519-L539 | def _set_active_tools(self, plot):
"Activates the list of active tools"
for tool in self.active_tools:
if isinstance(tool, util.basestring):
tool_type = TOOL_TYPES[tool]
matching = [t for t in plot.toolbar.tools
if isinstance(t, too... | [
"def",
"_set_active_tools",
"(",
"self",
",",
"plot",
")",
":",
"for",
"tool",
"in",
"self",
".",
"active_tools",
":",
"if",
"isinstance",
"(",
"tool",
",",
"util",
".",
"basestring",
")",
":",
"tool_type",
"=",
"TOOL_TYPES",
"[",
"tool",
"]",
"matching"... | Activates the list of active tools | [
"Activates",
"the",
"list",
"of",
"active",
"tools"
] | python | train | 47.52381 |
bykof/billomapy | billomapy/billomapy.py | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L4165-L4177 | def update_template(self, template_id, template_dict):
"""
Updates a template
:param template_id: the template id
:param template_dict: dict
:return: dict
"""
return self._create_put_request(
resource=TEMPLATES,
billomat_id=template_id,
... | [
"def",
"update_template",
"(",
"self",
",",
"template_id",
",",
"template_dict",
")",
":",
"return",
"self",
".",
"_create_put_request",
"(",
"resource",
"=",
"TEMPLATES",
",",
"billomat_id",
"=",
"template_id",
",",
"send_data",
"=",
"template_dict",
")"
] | Updates a template
:param template_id: the template id
:param template_dict: dict
:return: dict | [
"Updates",
"a",
"template"
] | python | train | 27 |
globus/globus-cli | globus_cli/commands/endpoint/server/delete.py | https://github.com/globus/globus-cli/blob/336675ff24da64c5ee487243f39ae39fc49a7e14/globus_cli/commands/endpoint/server/delete.py#L64-L105 | def server_delete(endpoint_id, server):
"""
Executor for `globus endpoint server show`
"""
client = get_client()
mode = _detect_mode(server)
# list (even if not necessary) in order to make errors more consistent when
# mode='id'
endpoint, server_list = get_endpoint_w_server_list(endpoi... | [
"def",
"server_delete",
"(",
"endpoint_id",
",",
"server",
")",
":",
"client",
"=",
"get_client",
"(",
")",
"mode",
"=",
"_detect_mode",
"(",
"server",
")",
"# list (even if not necessary) in order to make errors more consistent when",
"# mode='id'",
"endpoint",
",",
"s... | Executor for `globus endpoint server show` | [
"Executor",
"for",
"globus",
"endpoint",
"server",
"show"
] | python | train | 34.142857 |
numenta/nupic | src/nupic/database/connection.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/connection.py#L212-L235 | def _createDefaultPolicy(cls):
""" [private] Create the default database connection policy instance
Parameters:
----------------------------------------------------------------
retval: The default database connection policy instance
"""
logger = _getLogger(cls)
logger.debug(
... | [
"def",
"_createDefaultPolicy",
"(",
"cls",
")",
":",
"logger",
"=",
"_getLogger",
"(",
"cls",
")",
"logger",
".",
"debug",
"(",
"\"Creating database connection policy: platform=%r; pymysql.VERSION=%r\"",
",",
"platform",
".",
"system",
"(",
")",
",",
"pymysql",
".",... | [private] Create the default database connection policy instance
Parameters:
----------------------------------------------------------------
retval: The default database connection policy instance | [
"[",
"private",
"]",
"Create",
"the",
"default",
"database",
"connection",
"policy",
"instance"
] | python | valid | 36.583333 |
radjkarl/imgProcessor | imgProcessor/measure/SNR/SNR_hinken.py | https://github.com/radjkarl/imgProcessor/blob/7c5a28718f81c01a430152c60a686ac50afbfd7c/imgProcessor/measure/SNR/SNR_hinken.py#L8-L44 | def SNR_hinken(imgs, bg=0, roi=None):
'''
signal-to-noise ratio (SNR) as mean(images) / std(images)
as defined in Hinken et.al. 2011 (DOI: 10.1063/1.3541766)
works on unloaded images
no memory overload if too many images are given
'''
mean = None
M = len(imgs)
if bg is... | [
"def",
"SNR_hinken",
"(",
"imgs",
",",
"bg",
"=",
"0",
",",
"roi",
"=",
"None",
")",
":",
"mean",
"=",
"None",
"M",
"=",
"len",
"(",
"imgs",
")",
"if",
"bg",
"is",
"not",
"0",
":",
"bg",
"=",
"imread",
"(",
"bg",
")",
"[",
"roi",
"]",
"if",... | signal-to-noise ratio (SNR) as mean(images) / std(images)
as defined in Hinken et.al. 2011 (DOI: 10.1063/1.3541766)
works on unloaded images
no memory overload if too many images are given | [
"signal",
"-",
"to",
"-",
"noise",
"ratio",
"(",
"SNR",
")",
"as",
"mean",
"(",
"images",
")",
"/",
"std",
"(",
"images",
")",
"as",
"defined",
"in",
"Hinken",
"et",
".",
"al",
".",
"2011",
"(",
"DOI",
":",
"10",
".",
"1063",
"/",
"1",
".",
"... | python | train | 26.162162 |
pypa/pipenv | pipenv/patched/notpip/_internal/utils/misc.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/misc.py#L295-L310 | def renames(old, new):
# type: (str, str) -> None
"""Like os.renames(), but handles renaming across devices."""
# Implementation borrowed from os.renames().
head, tail = os.path.split(new)
if head and tail and not os.path.exists(head):
os.makedirs(head)
shutil.move(old, new)
head, ... | [
"def",
"renames",
"(",
"old",
",",
"new",
")",
":",
"# type: (str, str) -> None",
"# Implementation borrowed from os.renames().",
"head",
",",
"tail",
"=",
"os",
".",
"path",
".",
"split",
"(",
"new",
")",
"if",
"head",
"and",
"tail",
"and",
"not",
"os",
"."... | Like os.renames(), but handles renaming across devices. | [
"Like",
"os",
".",
"renames",
"()",
"but",
"handles",
"renaming",
"across",
"devices",
"."
] | python | train | 27.375 |
limpyd/redis-limpyd | limpyd/indexes.py | https://github.com/limpyd/redis-limpyd/blob/3c745dde1390a0bd09690b77a089dcc08c6c7e43/limpyd/indexes.py#L827-L847 | def remove(self, *args):
"""Remove the instance tied to the field for the given "value" (via `args`) from the index
For the parameters, see ``BaseIndex.remove``
Notes
-----
This method calls the ``unstore`` method that should be overridden in subclasses
to remove data f... | [
"def",
"remove",
"(",
"self",
",",
"*",
"args",
")",
":",
"key",
"=",
"self",
".",
"get_storage_key",
"(",
"*",
"args",
")",
"args",
"=",
"list",
"(",
"args",
")",
"value",
"=",
"args",
"[",
"-",
"1",
"]",
"pk",
"=",
"self",
".",
"instance",
".... | Remove the instance tied to the field for the given "value" (via `args`) from the index
For the parameters, see ``BaseIndex.remove``
Notes
-----
This method calls the ``unstore`` method that should be overridden in subclasses
to remove data from the index sorted-set key | [
"Remove",
"the",
"instance",
"tied",
"to",
"the",
"field",
"for",
"the",
"given",
"value",
"(",
"via",
"args",
")",
"from",
"the",
"index"
] | python | train | 31.238095 |
gatagat/lap | lap/lapmod.py | https://github.com/gatagat/lap/blob/c2b6309ba246d18205a71228cdaea67210e1a039/lap/lapmod.py#L273-L341 | def lapmod(n, cc, ii, kk, fast=True, return_cost=True,
fp_version=FP_DYNAMIC):
"""Solve sparse linear assignment problem using Jonker-Volgenant algorithm.
n: number of rows of the assignment cost matrix
cc: 1D array of all finite elements of the assignement cost matrix
ii: 1D array of indice... | [
"def",
"lapmod",
"(",
"n",
",",
"cc",
",",
"ii",
",",
"kk",
",",
"fast",
"=",
"True",
",",
"return_cost",
"=",
"True",
",",
"fp_version",
"=",
"FP_DYNAMIC",
")",
":",
"# log = logging.getLogger('lapmod')",
"check_cost",
"(",
"n",
",",
"cc",
",",
"ii",
... | Solve sparse linear assignment problem using Jonker-Volgenant algorithm.
n: number of rows of the assignment cost matrix
cc: 1D array of all finite elements of the assignement cost matrix
ii: 1D array of indices of the row starts in cc. The following must hold:
ii[0] = 0 and ii[n+1] = len(cc).
... | [
"Solve",
"sparse",
"linear",
"assignment",
"problem",
"using",
"Jonker",
"-",
"Volgenant",
"algorithm",
"."
] | python | train | 41.913043 |
JosuaKrause/quick_server | quick_server/quick_server.py | https://github.com/JosuaKrause/quick_server/blob/55dc7c5fe726a341f8476f749fe0f9da156fc1cb/quick_server/quick_server.py#L1189-L1202 | def log_request(self, code='-', size='-'):
"""Logs the current request."""
print_size = getattr(thread_local, 'size', -1)
if size != '-':
size_str = ' (%s)' % size
elif print_size >= 0:
size_str = self.log_size_string(print_size) + ' '
else:
si... | [
"def",
"log_request",
"(",
"self",
",",
"code",
"=",
"'-'",
",",
"size",
"=",
"'-'",
")",
":",
"print_size",
"=",
"getattr",
"(",
"thread_local",
",",
"'size'",
",",
"-",
"1",
")",
"if",
"size",
"!=",
"'-'",
":",
"size_str",
"=",
"' (%s)'",
"%",
"s... | Logs the current request. | [
"Logs",
"the",
"current",
"request",
"."
] | python | train | 39.642857 |
cdeboever3/cdpybio | cdpybio/star.py | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/star.py#L786-L838 | def make_logs_df(fns, define_sample_name=None):
"""Make pandas DataFrame from multiple STAR Log.final.out files.
Parameters
----------
fns : string
List of paths to Log.final.out files.
define_sample_name : function that takes string as input
Function mapping filename to sample nam... | [
"def",
"make_logs_df",
"(",
"fns",
",",
"define_sample_name",
"=",
"None",
")",
":",
"dfs",
"=",
"[",
"]",
"for",
"fn",
"in",
"fns",
":",
"dfs",
".",
"append",
"(",
"_read_log",
"(",
"fn",
",",
"define_sample_name",
"=",
"define_sample_name",
")",
")",
... | Make pandas DataFrame from multiple STAR Log.final.out files.
Parameters
----------
fns : string
List of paths to Log.final.out files.
define_sample_name : function that takes string as input
Function mapping filename to sample name. For instance, you may have the
sample name i... | [
"Make",
"pandas",
"DataFrame",
"from",
"multiple",
"STAR",
"Log",
".",
"final",
".",
"out",
"files",
"."
] | python | train | 35.037736 |
samirelanduk/quickplots | quickplots/series.py | https://github.com/samirelanduk/quickplots/blob/59f5e6ff367b2c1c24ba7cf1805d03552034c6d8/quickplots/series.py#L164-L174 | def remove_data_point(self, x, y):
"""Removes the given data point from the series.
:param x: The numerical x value of the data point to be removed.
:param y: The numerical y value of the data point to be removed.
:raises ValueError: if you try to remove the last data point from\
... | [
"def",
"remove_data_point",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"if",
"len",
"(",
"self",
".",
"_data",
")",
"==",
"1",
":",
"raise",
"ValueError",
"(",
"\"You cannot remove a Series' last data point\"",
")",
"self",
".",
"_data",
".",
"remove",
"("... | Removes the given data point from the series.
:param x: The numerical x value of the data point to be removed.
:param y: The numerical y value of the data point to be removed.
:raises ValueError: if you try to remove the last data point from\
a series. | [
"Removes",
"the",
"given",
"data",
"point",
"from",
"the",
"series",
"."
] | python | train | 42.545455 |
carpedm20/fbchat | fbchat/_client.py | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L108-L118 | def _generatePayload(self, query):
"""Adds the following defaults to the payload:
__rev, __user, __a, ttstamp, fb_dtsg, __req
"""
payload = self._payload_default.copy()
if query:
payload.update(query)
payload["__req"] = str_base(self._req_counter, 36)
... | [
"def",
"_generatePayload",
"(",
"self",
",",
"query",
")",
":",
"payload",
"=",
"self",
".",
"_payload_default",
".",
"copy",
"(",
")",
"if",
"query",
":",
"payload",
".",
"update",
"(",
"query",
")",
"payload",
"[",
"\"__req\"",
"]",
"=",
"str_base",
... | Adds the following defaults to the payload:
__rev, __user, __a, ttstamp, fb_dtsg, __req | [
"Adds",
"the",
"following",
"defaults",
"to",
"the",
"payload",
":",
"__rev",
"__user",
"__a",
"ttstamp",
"fb_dtsg",
"__req"
] | python | train | 35.636364 |
PyCQA/pyflakes | pyflakes/checker.py | https://github.com/PyCQA/pyflakes/blob/232cb1d27ee134bf96adc8f37e53589dc259b159/pyflakes/checker.py#L1091-L1097 | def isDocstring(self, node):
"""
Determine if the given node is a docstring, as long as it is at the
correct place in the node tree.
"""
return isinstance(node, ast.Str) or (isinstance(node, ast.Expr) and
isinstance(node.value, ast.Str... | [
"def",
"isDocstring",
"(",
"self",
",",
"node",
")",
":",
"return",
"isinstance",
"(",
"node",
",",
"ast",
".",
"Str",
")",
"or",
"(",
"isinstance",
"(",
"node",
",",
"ast",
".",
"Expr",
")",
"and",
"isinstance",
"(",
"node",
".",
"value",
",",
"as... | Determine if the given node is a docstring, as long as it is at the
correct place in the node tree. | [
"Determine",
"if",
"the",
"given",
"node",
"is",
"a",
"docstring",
"as",
"long",
"as",
"it",
"is",
"at",
"the",
"correct",
"place",
"in",
"the",
"node",
"tree",
"."
] | python | train | 45.142857 |
geopy/geopy | geopy/units.py | https://github.com/geopy/geopy/blob/02c838d965e76497f3c3d61f53808c86b5c58224/geopy/units.py#L24-L32 | def radians(degrees=0, arcminutes=0, arcseconds=0):
"""
TODO docs.
"""
if arcminutes:
degrees += arcminutes / arcmin(degrees=1.)
if arcseconds:
degrees += arcseconds / arcsec(degrees=1.)
return math.radians(degrees) | [
"def",
"radians",
"(",
"degrees",
"=",
"0",
",",
"arcminutes",
"=",
"0",
",",
"arcseconds",
"=",
"0",
")",
":",
"if",
"arcminutes",
":",
"degrees",
"+=",
"arcminutes",
"/",
"arcmin",
"(",
"degrees",
"=",
"1.",
")",
"if",
"arcseconds",
":",
"degrees",
... | TODO docs. | [
"TODO",
"docs",
"."
] | python | train | 27.444444 |
IAMconsortium/pyam | pyam/core.py | https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/core.py#L1334-L1338 | def _aggregate(df, by):
"""Aggregate `df` by specified column(s), return indexed `pd.Series`"""
by = [by] if isstr(by) else by
cols = [c for c in list(df.columns) if c not in ['value'] + by]
return df.groupby(cols).sum()['value'] | [
"def",
"_aggregate",
"(",
"df",
",",
"by",
")",
":",
"by",
"=",
"[",
"by",
"]",
"if",
"isstr",
"(",
"by",
")",
"else",
"by",
"cols",
"=",
"[",
"c",
"for",
"c",
"in",
"list",
"(",
"df",
".",
"columns",
")",
"if",
"c",
"not",
"in",
"[",
"'val... | Aggregate `df` by specified column(s), return indexed `pd.Series` | [
"Aggregate",
"df",
"by",
"specified",
"column",
"(",
"s",
")",
"return",
"indexed",
"pd",
".",
"Series"
] | python | train | 48.2 |
IAMconsortium/pyam | pyam/plotting.py | https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/plotting.py#L188-L205 | def read_shapefile(fname, region_col=None, **kwargs):
"""Read a shapefile for use in regional plots. Shapefiles must have a
column denoted as "region".
Parameters
----------
fname : string
path to shapefile to be read by geopandas
region_col : string, default None
if provided, r... | [
"def",
"read_shapefile",
"(",
"fname",
",",
"region_col",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"gdf",
"=",
"gpd",
".",
"read_file",
"(",
"fname",
",",
"*",
"*",
"kwargs",
")",
"if",
"region_col",
"is",
"not",
"None",
":",
"gdf",
"=",
"gd... | Read a shapefile for use in regional plots. Shapefiles must have a
column denoted as "region".
Parameters
----------
fname : string
path to shapefile to be read by geopandas
region_col : string, default None
if provided, rename a column in the shapefile to "region" | [
"Read",
"a",
"shapefile",
"for",
"use",
"in",
"regional",
"plots",
".",
"Shapefiles",
"must",
"have",
"a",
"column",
"denoted",
"as",
"region",
"."
] | python | train | 35.222222 |
nschloe/colorio | experiments/new-cs.py | https://github.com/nschloe/colorio/blob/357d6001b3cf30f752e23726bf429dc1d1c60b3a/experiments/new-cs.py#L423-L458 | def apply_M(self, ax, ay):
"""Linear operator that converts ax, ay to abcd.
"""
jac = numpy.array(
[[self.dx.dot(ax), self.dy.dot(ax)], [self.dx.dot(ay), self.dy.dot(ay)]]
)
# jacs and J are of shape (2, 2, k). M must be of the same shape and
# contain the re... | [
"def",
"apply_M",
"(",
"self",
",",
"ax",
",",
"ay",
")",
":",
"jac",
"=",
"numpy",
".",
"array",
"(",
"[",
"[",
"self",
".",
"dx",
".",
"dot",
"(",
"ax",
")",
",",
"self",
".",
"dy",
".",
"dot",
"(",
"ax",
")",
"]",
",",
"[",
"self",
"."... | Linear operator that converts ax, ay to abcd. | [
"Linear",
"operator",
"that",
"converts",
"ax",
"ay",
"to",
"abcd",
"."
] | python | train | 34.916667 |
metagriffin/morph | morph/__init__.py | https://github.com/metagriffin/morph/blob/907f169b0155712c466d3aac29f0907d0f36b443/morph/__init__.py#L95-L111 | def tolist(obj, flat=True, split=True):
'''
Returns `obj` as a list: if it is falsy, returns an empty list; if
it is a string and `split` is truthy, then it is split into
substrings using Unix shell semantics; if it is sequence-like, a
list is returned optionally flattened if `flat` is truthy (see
:func:`fl... | [
"def",
"tolist",
"(",
"obj",
",",
"flat",
"=",
"True",
",",
"split",
"=",
"True",
")",
":",
"# todo: it would be \"pretty awesome\" if this could auto-detect",
"# comma-separation rather than space-separation",
"if",
"not",
"obj",
":",
"return",
"[",
"]",
"if",
... | Returns `obj` as a list: if it is falsy, returns an empty list; if
it is a string and `split` is truthy, then it is split into
substrings using Unix shell semantics; if it is sequence-like, a
list is returned optionally flattened if `flat` is truthy (see
:func:`flatten`). | [
"Returns",
"obj",
"as",
"a",
"list",
":",
"if",
"it",
"is",
"falsy",
"returns",
"an",
"empty",
"list",
";",
"if",
"it",
"is",
"a",
"string",
"and",
"split",
"is",
"truthy",
"then",
"it",
"is",
"split",
"into",
"substrings",
"using",
"Unix",
"shell",
... | python | train | 35.352941 |
choderalab/pymbar | pymbar/timeseries.py | https://github.com/choderalab/pymbar/blob/69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740/pymbar/timeseries.py#L632-L736 | def subsampleCorrelatedData(A_t, g=None, fast=False, conservative=False, verbose=False):
"""Determine the indices of an uncorrelated subsample of the data.
Parameters
----------
A_t : np.ndarray
A_t[t] is the t-th value of timeseries A(t). Length is deduced from vector.
g : float, optional... | [
"def",
"subsampleCorrelatedData",
"(",
"A_t",
",",
"g",
"=",
"None",
",",
"fast",
"=",
"False",
",",
"conservative",
"=",
"False",
",",
"verbose",
"=",
"False",
")",
":",
"# Create np copy of arrays.",
"A_t",
"=",
"np",
".",
"array",
"(",
"A_t",
")",
"# ... | Determine the indices of an uncorrelated subsample of the data.
Parameters
----------
A_t : np.ndarray
A_t[t] is the t-th value of timeseries A(t). Length is deduced from vector.
g : float, optional
if provided, the statistical inefficiency g is used to subsample the timeseries -- othe... | [
"Determine",
"the",
"indices",
"of",
"an",
"uncorrelated",
"subsample",
"of",
"the",
"data",
"."
] | python | train | 42.209524 |
attm2x/m2x-python | m2x/v2/metadata.py | https://github.com/attm2x/m2x-python/blob/df83f590114692b1f96577148b7ba260065905bb/m2x/v2/metadata.py#L39-L55 | def update_metadata(self, params):
""" Generic method for a resource's Update Metadata endpoint.
Example endpoints:
* `Update Device Metadata <https://m2x.att.com/developer/documentation/v2/device#Update-Device-Metadata>`_
* `Update Distribution Metadata <https://m2x.att.com/developer/documentation/v2... | [
"def",
"update_metadata",
"(",
"self",
",",
"params",
")",
":",
"return",
"self",
".",
"api",
".",
"put",
"(",
"self",
".",
"metadata_path",
"(",
")",
",",
"data",
"=",
"params",
")"
] | Generic method for a resource's Update Metadata endpoint.
Example endpoints:
* `Update Device Metadata <https://m2x.att.com/developer/documentation/v2/device#Update-Device-Metadata>`_
* `Update Distribution Metadata <https://m2x.att.com/developer/documentation/v2/distribution#Update-Distribution-Metadata>... | [
"Generic",
"method",
"for",
"a",
"resource",
"s",
"Update",
"Metadata",
"endpoint",
"."
] | python | test | 45.176471 |
Nachtfeuer/pipeline | spline/application.py | https://github.com/Nachtfeuer/pipeline/blob/04ca18c4e95e4349532bb45b768206393e1f2c13/spline/application.py#L130-L160 | def run(self, definition):
"""Processing the pipeline."""
self.logger.info("Running with Python %s", sys.version.replace("\n", ""))
self.logger.info("Running on platform %s", platform.platform())
self.logger.info("Current cpu count is %d", multiprocessing.cpu_count())
self.logger... | [
"def",
"run",
"(",
"self",
",",
"definition",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"Running with Python %s\"",
",",
"sys",
".",
"version",
".",
"replace",
"(",
"\"\\n\"",
",",
"\"\"",
")",
")",
"self",
".",
"logger",
".",
"info",
"(",
... | Processing the pipeline. | [
"Processing",
"the",
"pipeline",
"."
] | python | train | 41.258065 |
sci-bots/mpm | mpm/api.py | https://github.com/sci-bots/mpm/blob/a69651cda4b37ee6b17df4fe0809249e7f4dc536/mpm/api.py#L94-L124 | def _remove_broken_links():
'''
Remove broken links in `<conda prefix>/etc/microdrop/plugins/enabled/`.
Returns
-------
list
List of links removed (if any).
'''
enabled_dir = MICRODROP_CONDA_PLUGINS.joinpath('enabled')
if not enabled_dir.isdir():
return []
broken_li... | [
"def",
"_remove_broken_links",
"(",
")",
":",
"enabled_dir",
"=",
"MICRODROP_CONDA_PLUGINS",
".",
"joinpath",
"(",
"'enabled'",
")",
"if",
"not",
"enabled_dir",
".",
"isdir",
"(",
")",
":",
"return",
"[",
"]",
"broken_links",
"=",
"[",
"]",
"for",
"dir_i",
... | Remove broken links in `<conda prefix>/etc/microdrop/plugins/enabled/`.
Returns
-------
list
List of links removed (if any). | [
"Remove",
"broken",
"links",
"in",
"<conda",
"prefix",
">",
"/",
"etc",
"/",
"microdrop",
"/",
"plugins",
"/",
"enabled",
"/",
"."
] | python | train | 27.451613 |
gwastro/pycbc | pycbc/workflow/core.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L926-L940 | def add_multiifo_output_list_opt(self, opt, outputs):
""" Add an option that determines a list of outputs from multiple
detectors. Files will be supplied as --opt ifo1:input1 ifo2:input2
.....
"""
# NOTE: Here we have to use the raw arguments functionality as the
... | [
"def",
"add_multiifo_output_list_opt",
"(",
"self",
",",
"opt",
",",
"outputs",
")",
":",
"# NOTE: Here we have to use the raw arguments functionality as the",
"# file and ifo are not space separated.",
"self",
".",
"add_raw_arg",
"(",
"opt",
")",
"self",
".",
"add_raw_... | Add an option that determines a list of outputs from multiple
detectors. Files will be supplied as --opt ifo1:input1 ifo2:input2
..... | [
"Add",
"an",
"option",
"that",
"determines",
"a",
"list",
"of",
"outputs",
"from",
"multiple",
"detectors",
".",
"Files",
"will",
"be",
"supplied",
"as",
"--",
"opt",
"ifo1",
":",
"input1",
"ifo2",
":",
"input2",
"....."
] | python | train | 42.266667 |
quora/qcore | qcore/asserts.py | https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/asserts.py#L104-L130 | def assert_eq(expected, actual, message=None, tolerance=None, extra=None):
"""Raises an AssertionError if expected != actual.
If tolerance is specified, raises an AssertionError if either
- expected or actual isn't a number, or
- the difference between expected and actual is larger than the tolerance.
... | [
"def",
"assert_eq",
"(",
"expected",
",",
"actual",
",",
"message",
"=",
"None",
",",
"tolerance",
"=",
"None",
",",
"extra",
"=",
"None",
")",
":",
"if",
"tolerance",
"is",
"None",
":",
"assert",
"expected",
"==",
"actual",
",",
"_assert_fail_message",
... | Raises an AssertionError if expected != actual.
If tolerance is specified, raises an AssertionError if either
- expected or actual isn't a number, or
- the difference between expected and actual is larger than the tolerance. | [
"Raises",
"an",
"AssertionError",
"if",
"expected",
"!",
"=",
"actual",
"."
] | python | train | 38 |
funilrys/PyFunceble | PyFunceble/production.py | https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/production.py#L477-L520 | def _update_setup_py(self):
"""
Update :code:`setup.py` so that it always have the right name.
"""
# We initiate the path to the file we have to filter.
setup_py_path = PyFunceble.CURRENT_DIRECTORY + "setup.py"
if self.is_dev_version():
# The current version... | [
"def",
"_update_setup_py",
"(",
"self",
")",
":",
"# We initiate the path to the file we have to filter.",
"setup_py_path",
"=",
"PyFunceble",
".",
"CURRENT_DIRECTORY",
"+",
"\"setup.py\"",
"if",
"self",
".",
"is_dev_version",
"(",
")",
":",
"# The current version is the `d... | Update :code:`setup.py` so that it always have the right name. | [
"Update",
":",
"code",
":",
"setup",
".",
"py",
"so",
"that",
"it",
"always",
"have",
"the",
"right",
"name",
"."
] | python | test | 36.977273 |
Erotemic/utool | utool/util_cplat.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_cplat.py#L1075-L1104 | def get_flops():
""" # DOESNT WORK """
from sys import stdout
from re import compile
filename = "linpack.out"
fpnum = r'\d+\.\d+E[+-]\d\d'
fpnum_1 = fpnum + r' +'
pattern = compile(r'^ *' + fpnum_1 + fpnum_1 + fpnum_1 + r'(' + fpnum + r') +' + fpnum_1 + fpnum + r' *\n$')
speeds = [0.0, ... | [
"def",
"get_flops",
"(",
")",
":",
"from",
"sys",
"import",
"stdout",
"from",
"re",
"import",
"compile",
"filename",
"=",
"\"linpack.out\"",
"fpnum",
"=",
"r'\\d+\\.\\d+E[+-]\\d\\d'",
"fpnum_1",
"=",
"fpnum",
"+",
"r' +'",
"pattern",
"=",
"compile",
"(",
"r'^ ... | # DOESNT WORK | [
"#",
"DOESNT",
"WORK"
] | python | train | 29.866667 |
mitsei/dlkit | dlkit/services/commenting.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/services/commenting.py#L526-L534 | def get_books(self):
"""Pass through to provider BookLookupSession.get_books"""
# Implemented from kitosid template for -
# osid.resource.BinLookupSession.get_bins_template
catalogs = self._get_provider_session('book_lookup_session').get_books()
cat_list = []
for cat in c... | [
"def",
"get_books",
"(",
"self",
")",
":",
"# Implemented from kitosid template for -",
"# osid.resource.BinLookupSession.get_bins_template",
"catalogs",
"=",
"self",
".",
"_get_provider_session",
"(",
"'book_lookup_session'",
")",
".",
"get_books",
"(",
")",
"cat_list",
"=... | Pass through to provider BookLookupSession.get_books | [
"Pass",
"through",
"to",
"provider",
"BookLookupSession",
".",
"get_books"
] | python | train | 49.444444 |
pysal/giddy | giddy/markov.py | https://github.com/pysal/giddy/blob/13fae6c18933614be78e91a6b5060693bea33a04/giddy/markov.py#L811-L830 | def summary(self, file_name=None):
"""
A summary method to call the Markov homogeneity test to test for
temporally lagged spatial dependence.
To learn more about the properties of the tests, refer to
:cite:`Rey2016a` and :cite:`Kang2018`.
"""
class_names = ["C%d... | [
"def",
"summary",
"(",
"self",
",",
"file_name",
"=",
"None",
")",
":",
"class_names",
"=",
"[",
"\"C%d\"",
"%",
"i",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"k",
")",
"]",
"regime_names",
"=",
"[",
"\"LAG%d\"",
"%",
"i",
"for",
"i",
"in",
"... | A summary method to call the Markov homogeneity test to test for
temporally lagged spatial dependence.
To learn more about the properties of the tests, refer to
:cite:`Rey2016a` and :cite:`Kang2018`. | [
"A",
"summary",
"method",
"to",
"call",
"the",
"Markov",
"homogeneity",
"test",
"to",
"test",
"for",
"temporally",
"lagged",
"spatial",
"dependence",
"."
] | python | train | 37.6 |
bachya/pyflunearyou | pyflunearyou/cdc.py | https://github.com/bachya/pyflunearyou/blob/16a2f839c8df851e925e010a6b5c5708386febac/pyflunearyou/cdc.py#L58-L67 | async def status_by_state(self, state: str) -> dict:
"""Return the CDC status for the specified state."""
data = await self.raw_cdc_data()
try:
info = next((v for k, v in data.items() if state in k))
except StopIteration:
return {}
return adjust_status(i... | [
"async",
"def",
"status_by_state",
"(",
"self",
",",
"state",
":",
"str",
")",
"->",
"dict",
":",
"data",
"=",
"await",
"self",
".",
"raw_cdc_data",
"(",
")",
"try",
":",
"info",
"=",
"next",
"(",
"(",
"v",
"for",
"k",
",",
"v",
"in",
"data",
"."... | Return the CDC status for the specified state. | [
"Return",
"the",
"CDC",
"status",
"for",
"the",
"specified",
"state",
"."
] | python | train | 31.5 |
konstantint/PassportEye | passporteye/mrz/image.py | https://github.com/konstantint/PassportEye/blob/b32afba0f5dc4eb600c4edc4f49e5d49959c5415/passporteye/mrz/image.py#L328-L343 | def read_mrz(file, save_roi=False, extra_cmdline_params=''):
"""The main interface function to this module, encapsulating the recognition pipeline.
Given an image filename, runs MRZPipeline on it, returning the parsed MRZ object.
:param file: A filename or a stream to read the file data from.
:param... | [
"def",
"read_mrz",
"(",
"file",
",",
"save_roi",
"=",
"False",
",",
"extra_cmdline_params",
"=",
"''",
")",
":",
"p",
"=",
"MRZPipeline",
"(",
"file",
",",
"extra_cmdline_params",
")",
"mrz",
"=",
"p",
".",
"result",
"if",
"mrz",
"is",
"not",
"None",
"... | The main interface function to this module, encapsulating the recognition pipeline.
Given an image filename, runs MRZPipeline on it, returning the parsed MRZ object.
:param file: A filename or a stream to read the file data from.
:param save_roi: when this is True, the .aux['roi'] field will contain the... | [
"The",
"main",
"interface",
"function",
"to",
"this",
"module",
"encapsulating",
"the",
"recognition",
"pipeline",
".",
"Given",
"an",
"image",
"filename",
"runs",
"MRZPipeline",
"on",
"it",
"returning",
"the",
"parsed",
"MRZ",
"object",
"."
] | python | train | 43.5 |
StackStorm/pybind | pybind/slxos/v17s_1_02/mpls_state/rsvp/sessions/psbs/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/mpls_state/rsvp/sessions/psbs/__init__.py#L2844-L2867 | def _set_session_style(self, v, load=False):
"""
Setter method for session_style, mapped from YANG variable /mpls_state/rsvp/sessions/psbs/session_style (session-reservation-style)
If this variable is read-only (config: false) in the
source YANG file, then _set_session_style is considered as a private
... | [
"def",
"_set_session_style",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"... | Setter method for session_style, mapped from YANG variable /mpls_state/rsvp/sessions/psbs/session_style (session-reservation-style)
If this variable is read-only (config: false) in the
source YANG file, then _set_session_style is considered as a private
method. Backends looking to populate this variable sho... | [
"Setter",
"method",
"for",
"session_style",
"mapped",
"from",
"YANG",
"variable",
"/",
"mpls_state",
"/",
"rsvp",
"/",
"sessions",
"/",
"psbs",
"/",
"session_style",
"(",
"session",
"-",
"reservation",
"-",
"style",
")",
"If",
"this",
"variable",
"is",
"read... | python | train | 95.916667 |
softlayer/softlayer-python | SoftLayer/managers/hardware.py | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/hardware.py#L616-L639 | def reflash_firmware(self,
hardware_id,
ipmi=True,
raid_controller=True,
bios=True):
"""Reflash hardware firmware.
This will cause the server to be unavailable for ~60 minutes.
The firmware will ... | [
"def",
"reflash_firmware",
"(",
"self",
",",
"hardware_id",
",",
"ipmi",
"=",
"True",
",",
"raid_controller",
"=",
"True",
",",
"bios",
"=",
"True",
")",
":",
"return",
"self",
".",
"hardware",
".",
"createFirmwareReflashTransaction",
"(",
"bool",
"(",
"ipmi... | Reflash hardware firmware.
This will cause the server to be unavailable for ~60 minutes.
The firmware will not be upgraded but rather reflashed to the version installed.
:param int hardware_id: The ID of the hardware to have its firmware
reflashed.
:para... | [
"Reflash",
"hardware",
"firmware",
"."
] | python | train | 39.958333 |
idlesign/django-siteprefs | siteprefs/toolbox.py | https://github.com/idlesign/django-siteprefs/blob/3d6bf5e64220fe921468a36fce68e15d7947cf92/siteprefs/toolbox.py#L183-L193 | def unpatch_locals(depth=3):
"""Restores the original values of module variables
considered preferences if they are still PatchedLocal
and not PrefProxy.
"""
for name, locals_dict in traverse_local_prefs(depth):
if isinstance(locals_dict[name], PatchedLocal):
locals_dict[name] =... | [
"def",
"unpatch_locals",
"(",
"depth",
"=",
"3",
")",
":",
"for",
"name",
",",
"locals_dict",
"in",
"traverse_local_prefs",
"(",
"depth",
")",
":",
"if",
"isinstance",
"(",
"locals_dict",
"[",
"name",
"]",
",",
"PatchedLocal",
")",
":",
"locals_dict",
"[",... | Restores the original values of module variables
considered preferences if they are still PatchedLocal
and not PrefProxy. | [
"Restores",
"the",
"original",
"values",
"of",
"module",
"variables",
"considered",
"preferences",
"if",
"they",
"are",
"still",
"PatchedLocal",
"and",
"not",
"PrefProxy",
"."
] | python | valid | 35.636364 |
OpenKMIP/PyKMIP | kmip/core/messages/payloads/signature_verify.py | https://github.com/OpenKMIP/PyKMIP/blob/b51c5b044bd05f8c85a1d65d13a583a4d8fc1b0e/kmip/core/messages/payloads/signature_verify.py#L323-L381 | def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Write the data encoding the SignatureVerify request payload to a
stream.
Args:
output_stream (stream): A data stream in which to encode object
data, supporting a write method; usuall... | [
"def",
"write",
"(",
"self",
",",
"output_stream",
",",
"kmip_version",
"=",
"enums",
".",
"KMIPVersion",
".",
"KMIP_1_0",
")",
":",
"local_stream",
"=",
"utils",
".",
"BytearrayStream",
"(",
")",
"if",
"self",
".",
"_unique_identifier",
":",
"self",
".",
... | Write the data encoding the SignatureVerify request payload to a
stream.
Args:
output_stream (stream): A data stream in which to encode object
data, supporting a write method; usually a BytearrayStream
object.
kmip_version (KMIPVersion): An enumer... | [
"Write",
"the",
"data",
"encoding",
"the",
"SignatureVerify",
"request",
"payload",
"to",
"a",
"stream",
"."
] | python | test | 34.813559 |
lmjohns3/theanets | theanets/layers/base.py | https://github.com/lmjohns3/theanets/blob/79db9f878ef2071f2f576a1cf5d43a752a55894a/theanets/layers/base.py#L148-L154 | def input_size(self):
'''Size of layer input (for layers with one input).'''
shape = self.input_shape
if shape is None:
raise util.ConfigurationError(
'undefined input size for layer "{}"'.format(self.name))
return shape[-1] | [
"def",
"input_size",
"(",
"self",
")",
":",
"shape",
"=",
"self",
".",
"input_shape",
"if",
"shape",
"is",
"None",
":",
"raise",
"util",
".",
"ConfigurationError",
"(",
"'undefined input size for layer \"{}\"'",
".",
"format",
"(",
"self",
".",
"name",
")",
... | Size of layer input (for layers with one input). | [
"Size",
"of",
"layer",
"input",
"(",
"for",
"layers",
"with",
"one",
"input",
")",
"."
] | python | test | 39.714286 |
google/grr | grr/client_builder/grr_response_client_builder/build.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/client_builder/grr_response_client_builder/build.py#L872-L1000 | def MakeDeployableBinary(self, template_path, output_path):
"""This will add the config to the client template and create a .rpm."""
rpmbuild_binary = "/usr/bin/rpmbuild"
if not os.path.exists(rpmbuild_binary):
logging.error("rpmbuild not found, unable to repack client.")
return
with utils... | [
"def",
"MakeDeployableBinary",
"(",
"self",
",",
"template_path",
",",
"output_path",
")",
":",
"rpmbuild_binary",
"=",
"\"/usr/bin/rpmbuild\"",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"rpmbuild_binary",
")",
":",
"logging",
".",
"error",
"(",
"\"r... | This will add the config to the client template and create a .rpm. | [
"This",
"will",
"add",
"the",
"config",
"to",
"the",
"client",
"template",
"and",
"create",
"a",
".",
"rpm",
"."
] | python | train | 37.844961 |
synw/dataswim | dataswim/charts/__init__.py | https://github.com/synw/dataswim/blob/4a4a53f80daa7cd8e8409d76a19ce07296269da2/dataswim/charts/__init__.py#L83-L96 | def sbar_(self, stack_index=None, label=None, style=None, opts=None,
options={}):
"""
Get a stacked bar chart
"""
self.opts(dict(stack_index=stack_index, color_index=stack_index))
try:
if stack_index is None:
self.err(self.sbar_, "Please provide a stack index parameter")
options["stack_index"] ... | [
"def",
"sbar_",
"(",
"self",
",",
"stack_index",
"=",
"None",
",",
"label",
"=",
"None",
",",
"style",
"=",
"None",
",",
"opts",
"=",
"None",
",",
"options",
"=",
"{",
"}",
")",
":",
"self",
".",
"opts",
"(",
"dict",
"(",
"stack_index",
"=",
"sta... | Get a stacked bar chart | [
"Get",
"a",
"stacked",
"bar",
"chart"
] | python | train | 36 |
twisted/vertex | vertex/q2q.py | https://github.com/twisted/vertex/blob/feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca/vertex/q2q.py#L1134-L1158 | def _write(self, body, id):
"""
Respond to a WRITE command, sending some data over a virtual channel
created by VIRTUAL. The answer is simply an acknowledgement, as it is
simply meant to note that the write went through without errors.
An occurrence of I{Write} on the wire, tog... | [
"def",
"_write",
"(",
"self",
",",
"body",
",",
"id",
")",
":",
"if",
"id",
"not",
"in",
"self",
".",
"connections",
":",
"raise",
"error",
".",
"ConnectionDone",
"(",
")",
"connection",
"=",
"self",
".",
"connections",
"[",
"id",
"]",
"connection",
... | Respond to a WRITE command, sending some data over a virtual channel
created by VIRTUAL. The answer is simply an acknowledgement, as it is
simply meant to note that the write went through without errors.
An occurrence of I{Write} on the wire, together with the response
generated by thi... | [
"Respond",
"to",
"a",
"WRITE",
"command",
"sending",
"some",
"data",
"over",
"a",
"virtual",
"channel",
"created",
"by",
"VIRTUAL",
".",
"The",
"answer",
"is",
"simply",
"an",
"acknowledgement",
"as",
"it",
"is",
"simply",
"meant",
"to",
"note",
"that",
"t... | python | train | 33.08 |
ryanvarley/ExoData | exodata/astroclasses.py | https://github.com/ryanvarley/ExoData/blob/e0d3652117214d2377a707d6778f93b7eb201a41/exodata/astroclasses.py#L645-L657 | def isTransiting(self):
""" Checks the the istransiting tag to see if the planet transits. Note that this only works as of catalogue
version ee12343381ae4106fd2db908e25ffc537a2ee98c (11th March 2014) where the istransiting tag was implemented
"""
try:
isTransiting = self.par... | [
"def",
"isTransiting",
"(",
"self",
")",
":",
"try",
":",
"isTransiting",
"=",
"self",
".",
"params",
"[",
"'istransiting'",
"]",
"except",
"KeyError",
":",
"return",
"False",
"if",
"isTransiting",
"==",
"'1'",
":",
"return",
"True",
"else",
":",
"return",... | Checks the the istransiting tag to see if the planet transits. Note that this only works as of catalogue
version ee12343381ae4106fd2db908e25ffc537a2ee98c (11th March 2014) where the istransiting tag was implemented | [
"Checks",
"the",
"the",
"istransiting",
"tag",
"to",
"see",
"if",
"the",
"planet",
"transits",
".",
"Note",
"that",
"this",
"only",
"works",
"as",
"of",
"catalogue",
"version",
"ee12343381ae4106fd2db908e25ffc537a2ee98c",
"(",
"11th",
"March",
"2014",
")",
"where... | python | train | 36.384615 |
glue-viz/glue-vispy-viewers | glue_vispy_viewers/extern/vispy/util/event.py | https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/util/event.py#L375-L389 | def disconnect(self, callback=None):
"""Disconnect a callback from this emitter.
If no callback is specified, then *all* callbacks are removed.
If the callback was not already connected, then the call does nothing.
"""
if callback is None:
self._callbacks = []
... | [
"def",
"disconnect",
"(",
"self",
",",
"callback",
"=",
"None",
")",
":",
"if",
"callback",
"is",
"None",
":",
"self",
".",
"_callbacks",
"=",
"[",
"]",
"self",
".",
"_callback_refs",
"=",
"[",
"]",
"else",
":",
"callback",
"=",
"self",
".",
"_normal... | Disconnect a callback from this emitter.
If no callback is specified, then *all* callbacks are removed.
If the callback was not already connected, then the call does nothing. | [
"Disconnect",
"a",
"callback",
"from",
"this",
"emitter",
"."
] | python | train | 39.066667 |
bububa/pyTOP | pyTOP/packages/requests/utils.py | https://github.com/bububa/pyTOP/blob/1e48009bcfe886be392628244b370e6374e1f2b2/pyTOP/packages/requests/utils.py#L166-L178 | def randombytes(n):
"""Return n random bytes."""
# Use /dev/urandom if it is available. Fall back to random module
# if not. It might be worthwhile to extend this function to use
# other platform-specific mechanisms for getting random bytes.
if os.path.exists("/dev/urandom"):
f = open("/de... | [
"def",
"randombytes",
"(",
"n",
")",
":",
"# Use /dev/urandom if it is available. Fall back to random module",
"# if not. It might be worthwhile to extend this function to use",
"# other platform-specific mechanisms for getting random bytes.",
"if",
"os",
".",
"path",
".",
"exists",
... | Return n random bytes. | [
"Return",
"n",
"random",
"bytes",
"."
] | python | train | 36.461538 |
inveniosoftware-attic/invenio-utils | invenio_utils/url.py | https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/url.py#L123-L130 | def get_safe_redirect_target(arg='next'):
"""Get URL to redirect to and ensure that it is local."""
for target in request.args.get(arg), request.referrer:
if not target:
continue
if is_local_url(target):
return target
return None | [
"def",
"get_safe_redirect_target",
"(",
"arg",
"=",
"'next'",
")",
":",
"for",
"target",
"in",
"request",
".",
"args",
".",
"get",
"(",
"arg",
")",
",",
"request",
".",
"referrer",
":",
"if",
"not",
"target",
":",
"continue",
"if",
"is_local_url",
"(",
... | Get URL to redirect to and ensure that it is local. | [
"Get",
"URL",
"to",
"redirect",
"to",
"and",
"ensure",
"that",
"it",
"is",
"local",
"."
] | python | train | 34.25 |
sbg/sevenbridges-python | sevenbridges/meta/transformer.py | https://github.com/sbg/sevenbridges-python/blob/f62640d1018d959f0b686f2dbe5e183085336607/sevenbridges/meta/transformer.py#L22-L35 | def to_project(project):
"""Serializes project to id string
:param project: object to serialize
:return: string id
"""
from sevenbridges.models.project import Project
if not project:
raise SbgError('Project is required!')
elif isinstance(project, Proje... | [
"def",
"to_project",
"(",
"project",
")",
":",
"from",
"sevenbridges",
".",
"models",
".",
"project",
"import",
"Project",
"if",
"not",
"project",
":",
"raise",
"SbgError",
"(",
"'Project is required!'",
")",
"elif",
"isinstance",
"(",
"project",
",",
"Project... | Serializes project to id string
:param project: object to serialize
:return: string id | [
"Serializes",
"project",
"to",
"id",
"string",
":",
"param",
"project",
":",
"object",
"to",
"serialize",
":",
"return",
":",
"string",
"id"
] | python | train | 35.071429 |
ThreatConnect-Inc/tcex | tcex/tcex_ti/mappings/tcex_ti_mappings.py | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/mappings/tcex_ti_mappings.py#L150-L164 | def create(self):
"""
Creates the Indicator/Group/Victim or Security Label given Owner
Args:
"""
if not self.can_create():
self._tcex.handle_error(905, [self.type])
response = self.tc_requests.create(self.api_type, self.api_sub_type, self._data, self.owner)
... | [
"def",
"create",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"can_create",
"(",
")",
":",
"self",
".",
"_tcex",
".",
"handle_error",
"(",
"905",
",",
"[",
"self",
".",
"type",
"]",
")",
"response",
"=",
"self",
".",
"tc_requests",
".",
"create... | Creates the Indicator/Group/Victim or Security Label given Owner
Args: | [
"Creates",
"the",
"Indicator",
"/",
"Group",
"/",
"Victim",
"or",
"Security",
"Label",
"given",
"Owner"
] | python | train | 30.666667 |
FactoryBoy/factory_boy | factory/django.py | https://github.com/FactoryBoy/factory_boy/blob/edaa7c7f5a14065b229927903bd7989cc93cd069/factory/django.py#L179-L185 | def _create(cls, model_class, *args, **kwargs):
"""Create an instance of the model, and save it to the database."""
if cls._meta.django_get_or_create:
return cls._get_or_create(model_class, *args, **kwargs)
manager = cls._get_manager(model_class)
return manager.create(*args,... | [
"def",
"_create",
"(",
"cls",
",",
"model_class",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"cls",
".",
"_meta",
".",
"django_get_or_create",
":",
"return",
"cls",
".",
"_get_or_create",
"(",
"model_class",
",",
"*",
"args",
",",
"*",
... | Create an instance of the model, and save it to the database. | [
"Create",
"an",
"instance",
"of",
"the",
"model",
"and",
"save",
"it",
"to",
"the",
"database",
"."
] | python | train | 46.285714 |
SHTOOLS/SHTOOLS | pyshtools/shclasses/shtensor.py | https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shtensor.py#L1510-L1594 | def plot_eigh(self, colorbar=True, cb_orientation='vertical',
tick_interval=[60, 60], minor_tick_interval=[20, 20],
xlabel='Longitude', ylabel='Latitude',
axes_labelsize=9, tick_labelsize=8, show=True, fname=None,
**kwargs):
"""
Plo... | [
"def",
"plot_eigh",
"(",
"self",
",",
"colorbar",
"=",
"True",
",",
"cb_orientation",
"=",
"'vertical'",
",",
"tick_interval",
"=",
"[",
"60",
",",
"60",
"]",
",",
"minor_tick_interval",
"=",
"[",
"20",
",",
"20",
"]",
",",
"xlabel",
"=",
"'Longitude'",
... | Plot the two eigenvalues and maximum absolute value eigenvalue of the
horizontal tensor.
Usage
-----
x.plot_eigh([tick_interval, minor_tick_interval, xlabel, ylabel,
colorbar, cb_orientation, cb_label, axes_labelsize,
tick_labelsize, show, fname... | [
"Plot",
"the",
"two",
"eigenvalues",
"and",
"maximum",
"absolute",
"value",
"eigenvalue",
"of",
"the",
"horizontal",
"tensor",
"."
] | python | train | 43.435294 |
robotpy/pyfrc | docs/conf.py | https://github.com/robotpy/pyfrc/blob/7672ea3f17c8d4b702a9f18a7372d95feee7e37d/docs/conf.py#L146-L172 | def process_child(node):
"""This function changes class references to not have the
intermediate module name by hacking at the doctree"""
# Edit descriptions to be nicer
if isinstance(node, sphinx.addnodes.desc_addname):
if len(node.children) == 1:
child = node.children[0]
... | [
"def",
"process_child",
"(",
"node",
")",
":",
"# Edit descriptions to be nicer",
"if",
"isinstance",
"(",
"node",
",",
"sphinx",
".",
"addnodes",
".",
"desc_addname",
")",
":",
"if",
"len",
"(",
"node",
".",
"children",
")",
"==",
"1",
":",
"child",
"=",
... | This function changes class references to not have the
intermediate module name by hacking at the doctree | [
"This",
"function",
"changes",
"class",
"references",
"to",
"not",
"have",
"the",
"intermediate",
"module",
"name",
"by",
"hacking",
"at",
"the",
"doctree"
] | python | train | 36.555556 |
cimm-kzn/CGRtools | CGRtools/containers/common.py | https://github.com/cimm-kzn/CGRtools/blob/15a19b04f6e4e1d0dab8e0d32a0877c7f7d70f34/CGRtools/containers/common.py#L128-L135 | def environment(self, atom):
"""
pairs of (bond, atom) connected to atom
:param atom: number
:return: list
"""
return tuple((bond, self._node[n]) for n, bond in self._adj[atom].items()) | [
"def",
"environment",
"(",
"self",
",",
"atom",
")",
":",
"return",
"tuple",
"(",
"(",
"bond",
",",
"self",
".",
"_node",
"[",
"n",
"]",
")",
"for",
"n",
",",
"bond",
"in",
"self",
".",
"_adj",
"[",
"atom",
"]",
".",
"items",
"(",
")",
")"
] | pairs of (bond, atom) connected to atom
:param atom: number
:return: list | [
"pairs",
"of",
"(",
"bond",
"atom",
")",
"connected",
"to",
"atom"
] | python | train | 28.375 |
saltstack/salt | salt/utils/stringutils.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/stringutils.py#L594-L609 | def camel_to_snake_case(camel_input):
'''
Converts camelCase (or CamelCase) to snake_case.
From https://codereview.stackexchange.com/questions/185966/functions-to-convert-camelcase-strings-to-snake-case
:param str camel_input: The camelcase or CamelCase string to convert to snake_case
:return str
... | [
"def",
"camel_to_snake_case",
"(",
"camel_input",
")",
":",
"res",
"=",
"camel_input",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"for",
"i",
",",
"letter",
"in",
"enumerate",
"(",
"camel_input",
"[",
"1",
":",
"]",
",",
"1",
")",
":",
"if",
"letter",
... | Converts camelCase (or CamelCase) to snake_case.
From https://codereview.stackexchange.com/questions/185966/functions-to-convert-camelcase-strings-to-snake-case
:param str camel_input: The camelcase or CamelCase string to convert to snake_case
:return str | [
"Converts",
"camelCase",
"(",
"or",
"CamelCase",
")",
"to",
"snake_case",
".",
"From",
"https",
":",
"//",
"codereview",
".",
"stackexchange",
".",
"com",
"/",
"questions",
"/",
"185966",
"/",
"functions",
"-",
"to",
"-",
"convert",
"-",
"camelcase",
"-",
... | python | train | 37.5625 |
fabiocaccamo/django-maintenance-mode | maintenance_mode/http.py | https://github.com/fabiocaccamo/django-maintenance-mode/blob/008221a6b8a687667c2480fa799c7a4228598441/maintenance_mode/http.py#L68-L204 | def need_maintenance_response(request):
"""
Tells if the given request needs a maintenance response or not.
"""
try:
view_match = resolve(request.path)
view_func = view_match[0]
view_dict = view_func.__dict__
view_force_maintenance_mode_off = view_dict.get(
... | [
"def",
"need_maintenance_response",
"(",
"request",
")",
":",
"try",
":",
"view_match",
"=",
"resolve",
"(",
"request",
".",
"path",
")",
"view_func",
"=",
"view_match",
"[",
"0",
"]",
"view_dict",
"=",
"view_func",
".",
"__dict__",
"view_force_maintenance_mode_... | Tells if the given request needs a maintenance response or not. | [
"Tells",
"if",
"the",
"given",
"request",
"needs",
"a",
"maintenance",
"response",
"or",
"not",
"."
] | python | train | 29.635036 |
brainiak/brainiak | brainiak/isc.py | https://github.com/brainiak/brainiak/blob/408f12dec2ff56559a26873a848a09e4c8facfeb/brainiak/isc.py#L1237-L1383 | def timeshift_isc(data, pairwise=False, summary_statistic='median',
n_shifts=1000, tolerate_nans=True, random_state=None):
"""Circular time-shift randomization for one-sample ISC test
For each voxel or ROI, compute the actual ISC and p-values
from a null distribution of ISCs where respon... | [
"def",
"timeshift_isc",
"(",
"data",
",",
"pairwise",
"=",
"False",
",",
"summary_statistic",
"=",
"'median'",
",",
"n_shifts",
"=",
"1000",
",",
"tolerate_nans",
"=",
"True",
",",
"random_state",
"=",
"None",
")",
":",
"# Check response time series input format",... | Circular time-shift randomization for one-sample ISC test
For each voxel or ROI, compute the actual ISC and p-values
from a null distribution of ISCs where response time series
are first circularly shifted by random intervals. If pairwise,
apply time-shift randomization to each subjects and compute pai... | [
"Circular",
"time",
"-",
"shift",
"randomization",
"for",
"one",
"-",
"sample",
"ISC",
"test"
] | python | train | 42.952381 |
alex-kostirin/pyatomac | atomac/ldtpd/value.py | https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/value.py#L30-L50 | def verifyscrollbarvertical(self, window_name, object_name):
"""
Verify scrollbar is vertical
@param window_name: Window name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to type in, eithe... | [
"def",
"verifyscrollbarvertical",
"(",
"self",
",",
"window_name",
",",
"object_name",
")",
":",
"try",
":",
"object_handle",
"=",
"self",
".",
"_get_object_handle",
"(",
"window_name",
",",
"object_name",
")",
"if",
"object_handle",
".",
"AXOrientation",
"==",
... | Verify scrollbar is vertical
@param window_name: Window name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type object... | [
"Verify",
"scrollbar",
"is",
"vertical"
] | python | valid | 33.285714 |
HPENetworking/PYHPEIMC | pyhpeimc/plat/device.py | https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/plat/device.py#L780-L829 | def set_inteface_up(ifindex, auth, url, devid=None, devip=None):
"""
function takest devid and ifindex of specific device and interface and issues a RESTFUL call
to "undo shut" the specified interface on the target device.
:param devid: int or str value of the target device
:param devip: ipv4 addr... | [
"def",
"set_inteface_up",
"(",
"ifindex",
",",
"auth",
",",
"url",
",",
"devid",
"=",
"None",
",",
"devip",
"=",
"None",
")",
":",
"if",
"devip",
"is",
"not",
"None",
":",
"devid",
"=",
"get_dev_details",
"(",
"devip",
",",
"auth",
",",
"url",
")",
... | function takest devid and ifindex of specific device and interface and issues a RESTFUL call
to "undo shut" the specified interface on the target device.
:param devid: int or str value of the target device
:param devip: ipv4 address of the target devices
:param ifindex: int or str value of the target... | [
"function",
"takest",
"devid",
"and",
"ifindex",
"of",
"specific",
"device",
"and",
"interface",
"and",
"issues",
"a",
"RESTFUL",
"call",
"to",
"undo",
"shut",
"the",
"specified",
"interface",
"on",
"the",
"target",
"device",
"."
] | python | train | 34.86 |
gbowerman/azurerm | examples/delete_rg.py | https://github.com/gbowerman/azurerm/blob/79d40431d3b13f8a36aadbff5029888383d72674/examples/delete_rg.py#L9-L38 | def main():
'''Main routine.'''
# check for single command argument
if len(sys.argv) != 2:
sys.exit('Usage: python ' + sys.argv[0] + ' rg_name')
rgname = sys.argv[1]
# if in Azure cloud shell, authenticate using the MSI endpoint
if 'ACC_CLOUD' in os.environ and 'MSI_ENDPOINT' in os.env... | [
"def",
"main",
"(",
")",
":",
"# check for single command argument",
"if",
"len",
"(",
"sys",
".",
"argv",
")",
"!=",
"2",
":",
"sys",
".",
"exit",
"(",
"'Usage: python '",
"+",
"sys",
".",
"argv",
"[",
"0",
"]",
"+",
"' rg_name'",
")",
"rgname",
"=",
... | Main routine. | [
"Main",
"routine",
"."
] | python | train | 38.033333 |
Nike-Inc/cerberus-python-client | cerberus/client.py | https://github.com/Nike-Inc/cerberus-python-client/blob/ef38356822e722fcb6a6ed4a1b38a5b493e753ae/cerberus/client.py#L587-L601 | def _get_all_secret_version_ids(self, secure_data_path, limit=None):
"""
Convenience function that returns a generator that will paginate over the secret version ids
secure_data_path -- full path to the key in the safety deposit box
limit -- Default(100), limits how many records to be re... | [
"def",
"_get_all_secret_version_ids",
"(",
"self",
",",
"secure_data_path",
",",
"limit",
"=",
"None",
")",
":",
"offset",
"=",
"0",
"# Prime the versions dictionary so that all the logic can happen in the loop",
"versions",
"=",
"{",
"'has_next'",
":",
"True",
",",
"'n... | Convenience function that returns a generator that will paginate over the secret version ids
secure_data_path -- full path to the key in the safety deposit box
limit -- Default(100), limits how many records to be returned from the api at once. | [
"Convenience",
"function",
"that",
"returns",
"a",
"generator",
"that",
"will",
"paginate",
"over",
"the",
"secret",
"version",
"ids",
"secure_data_path",
"--",
"full",
"path",
"to",
"the",
"key",
"in",
"the",
"safety",
"deposit",
"box",
"limit",
"--",
"Defaul... | python | train | 51.4 |
saltstack/salt | salt/modules/match.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/match.py#L258-L285 | def pcre(tgt, minion_id=None):
'''
Return True if the minion ID matches the given pcre target
minion_id
Specify the minion ID to match against the target expression
.. versionadded:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' match.pcre '.*'
'''
if minio... | [
"def",
"pcre",
"(",
"tgt",
",",
"minion_id",
"=",
"None",
")",
":",
"if",
"minion_id",
"is",
"not",
"None",
":",
"opts",
"=",
"copy",
".",
"copy",
"(",
"__opts__",
")",
"if",
"not",
"isinstance",
"(",
"minion_id",
",",
"six",
".",
"string_types",
")"... | Return True if the minion ID matches the given pcre target
minion_id
Specify the minion ID to match against the target expression
.. versionadded:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' match.pcre '.*' | [
"Return",
"True",
"if",
"the",
"minion",
"ID",
"matches",
"the",
"given",
"pcre",
"target"
] | python | train | 25.25 |
axltxl/m2bk | m2bk/log.py | https://github.com/axltxl/m2bk/blob/980083dfd17e6e783753a946e9aa809714551141/m2bk/log.py#L112-L120 | def msg_err(message):
"""
Log an error message
:param message: the message to be logged
"""
to_stdout(" !!! {message}".format(message=message), colorf=red, bold=True)
if _logger:
_logger.error(message) | [
"def",
"msg_err",
"(",
"message",
")",
":",
"to_stdout",
"(",
"\" !!! {message}\"",
".",
"format",
"(",
"message",
"=",
"message",
")",
",",
"colorf",
"=",
"red",
",",
"bold",
"=",
"True",
")",
"if",
"_logger",
":",
"_logger",
".",
"error",
"(",
"messa... | Log an error message
:param message: the message to be logged | [
"Log",
"an",
"error",
"message"
] | python | train | 25.111111 |
peri-source/peri | peri/opt/optimize.py | https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L1228-L1231 | def calc_grad(self):
"""The gradient of the cost w.r.t. the parameters."""
residuals = self.calc_residuals()
return 2*np.dot(self.J, residuals) | [
"def",
"calc_grad",
"(",
"self",
")",
":",
"residuals",
"=",
"self",
".",
"calc_residuals",
"(",
")",
"return",
"2",
"*",
"np",
".",
"dot",
"(",
"self",
".",
"J",
",",
"residuals",
")"
] | The gradient of the cost w.r.t. the parameters. | [
"The",
"gradient",
"of",
"the",
"cost",
"w",
".",
"r",
".",
"t",
".",
"the",
"parameters",
"."
] | python | valid | 41 |
sloria/pypi-cli | pypi_cli.py | https://github.com/sloria/pypi-cli/blob/beb007bf2bdd285209876ce2758982b5d8b54d5d/pypi_cli.py#L451-L456 | def min_version(self):
"""Version with the fewest downloads."""
data = self.version_downloads
if not data:
return (None, 0)
return min(data.items(), key=lambda item: item[1]) | [
"def",
"min_version",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"version_downloads",
"if",
"not",
"data",
":",
"return",
"(",
"None",
",",
"0",
")",
"return",
"min",
"(",
"data",
".",
"items",
"(",
")",
",",
"key",
"=",
"lambda",
"item",
":"... | Version with the fewest downloads. | [
"Version",
"with",
"the",
"fewest",
"downloads",
"."
] | python | train | 35.5 |
sanger-pathogens/Fastaq | pyfastaq/sequences.py | https://github.com/sanger-pathogens/Fastaq/blob/2c775c846d2491678a9637daa320592e02c26c72/pyfastaq/sequences.py#L237-L248 | def add_insertions(self, skip=10, window=1, test=False):
'''Adds a random base within window bases around every skip bases. e.g. skip=10, window=1 means a random base added somwhere in theintervals [9,11], [19,21] ... '''
assert 2 * window < skip
new_seq = list(self.seq)
for i in range(l... | [
"def",
"add_insertions",
"(",
"self",
",",
"skip",
"=",
"10",
",",
"window",
"=",
"1",
",",
"test",
"=",
"False",
")",
":",
"assert",
"2",
"*",
"window",
"<",
"skip",
"new_seq",
"=",
"list",
"(",
"self",
".",
"seq",
")",
"for",
"i",
"in",
"range"... | Adds a random base within window bases around every skip bases. e.g. skip=10, window=1 means a random base added somwhere in theintervals [9,11], [19,21] ... | [
"Adds",
"a",
"random",
"base",
"within",
"window",
"bases",
"around",
"every",
"skip",
"bases",
".",
"e",
".",
"g",
".",
"skip",
"=",
"10",
"window",
"=",
"1",
"means",
"a",
"random",
"base",
"added",
"somwhere",
"in",
"theintervals",
"[",
"9",
"11",
... | python | valid | 48.083333 |
radjkarl/imgProcessor | imgProcessor/camera/flatField/vignettingFromRandomSteps.py | https://github.com/radjkarl/imgProcessor/blob/7c5a28718f81c01a430152c60a686ac50afbfd7c/imgProcessor/camera/flatField/vignettingFromRandomSteps.py#L169-L197 | def error(self, nCells=15):
'''
calculate the standard deviation of all fitted images,
averaged to a grid
'''
s0, s1 = self.fits[0].shape
aR = s0 / s1
if aR > 1:
ss0 = int(nCells)
ss1 = int(ss0 / aR)
else:
ss... | [
"def",
"error",
"(",
"self",
",",
"nCells",
"=",
"15",
")",
":",
"s0",
",",
"s1",
"=",
"self",
".",
"fits",
"[",
"0",
"]",
".",
"shape",
"aR",
"=",
"s0",
"/",
"s1",
"if",
"aR",
">",
"1",
":",
"ss0",
"=",
"int",
"(",
"nCells",
")",
"ss1",
... | calculate the standard deviation of all fitted images,
averaged to a grid | [
"calculate",
"the",
"standard",
"deviation",
"of",
"all",
"fitted",
"images",
"averaged",
"to",
"a",
"grid"
] | python | train | 29.689655 |
ranaroussi/ezibpy | ezibpy/utils.py | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/utils.py#L204-L207 | def order_to_dict(order):
"""Convert an IBPy Order object to a dict containing any non-default values."""
default = Order()
return {field: val for field, val in vars(order).items() if val != getattr(default, field, None)} | [
"def",
"order_to_dict",
"(",
"order",
")",
":",
"default",
"=",
"Order",
"(",
")",
"return",
"{",
"field",
":",
"val",
"for",
"field",
",",
"val",
"in",
"vars",
"(",
"order",
")",
".",
"items",
"(",
")",
"if",
"val",
"!=",
"getattr",
"(",
"default"... | Convert an IBPy Order object to a dict containing any non-default values. | [
"Convert",
"an",
"IBPy",
"Order",
"object",
"to",
"a",
"dict",
"containing",
"any",
"non",
"-",
"default",
"values",
"."
] | python | train | 57.5 |
GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/boto/compute_auth.py | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/boto/compute_auth.py#L50-L57 | def _GetGsScopes(self):
"""Return all Google Storage scopes available on this VM."""
service_accounts = self.watcher.GetMetadata(metadata_key=self.metadata_key)
try:
scopes = service_accounts[self.service_account]['scopes']
return list(GS_SCOPES.intersection(set(scopes))) if scopes else None
... | [
"def",
"_GetGsScopes",
"(",
"self",
")",
":",
"service_accounts",
"=",
"self",
".",
"watcher",
".",
"GetMetadata",
"(",
"metadata_key",
"=",
"self",
".",
"metadata_key",
")",
"try",
":",
"scopes",
"=",
"service_accounts",
"[",
"self",
".",
"service_account",
... | Return all Google Storage scopes available on this VM. | [
"Return",
"all",
"Google",
"Storage",
"scopes",
"available",
"on",
"this",
"VM",
"."
] | python | train | 43.5 |
siznax/wptools | wptools/query.py | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/query.py#L370-L392 | def wikidata(self, title, wikibase=None):
"""
Returns Wikidata query string
"""
self.domain = 'www.wikidata.org'
self.uri = self.wiki_uri(self.domain)
query = self.WIKIDATA.substitute(
WIKI=self.uri,
ENDPOINT=self.endpoint,
LANG=self.v... | [
"def",
"wikidata",
"(",
"self",
",",
"title",
",",
"wikibase",
"=",
"None",
")",
":",
"self",
".",
"domain",
"=",
"'www.wikidata.org'",
"self",
".",
"uri",
"=",
"self",
".",
"wiki_uri",
"(",
"self",
".",
"domain",
")",
"query",
"=",
"self",
".",
"WIK... | Returns Wikidata query string | [
"Returns",
"Wikidata",
"query",
"string"
] | python | train | 29.521739 |
saltstack/salt | salt/cli/daemons.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/daemons.py#L130-L190 | def prepare(self):
'''
Run the preparation sequence required to start a salt master server.
If sub-classed, don't **ever** forget to run:
super(YourSubClass, self).prepare()
'''
super(Master, self).prepare()
try:
if self.config['verify_env']:
... | [
"def",
"prepare",
"(",
"self",
")",
":",
"super",
"(",
"Master",
",",
"self",
")",
".",
"prepare",
"(",
")",
"try",
":",
"if",
"self",
".",
"config",
"[",
"'verify_env'",
"]",
":",
"v_dirs",
"=",
"[",
"self",
".",
"config",
"[",
"'pki_dir'",
"]",
... | Run the preparation sequence required to start a salt master server.
If sub-classed, don't **ever** forget to run:
super(YourSubClass, self).prepare() | [
"Run",
"the",
"preparation",
"sequence",
"required",
"to",
"start",
"a",
"salt",
"master",
"server",
"."
] | python | train | 41.868852 |
aiogram/aiogram | aiogram/types/user.py | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/user.py#L48-L58 | def locale(self) -> babel.core.Locale or None:
"""
Get user's locale
:return: :class:`babel.core.Locale`
"""
if not self.language_code:
return None
if not hasattr(self, '_locale'):
setattr(self, '_locale', babel.core.Locale.parse(self.language_cod... | [
"def",
"locale",
"(",
"self",
")",
"->",
"babel",
".",
"core",
".",
"Locale",
"or",
"None",
":",
"if",
"not",
"self",
".",
"language_code",
":",
"return",
"None",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_locale'",
")",
":",
"setattr",
"(",
"self"... | Get user's locale
:return: :class:`babel.core.Locale` | [
"Get",
"user",
"s",
"locale"
] | python | train | 32.909091 |
scheibler/khard | khard/khard.py | https://github.com/scheibler/khard/blob/0f69430c2680f1ff5f073a977a3c5b753b96cc17/khard/khard.py#L567-L593 | def load_address_books(names, config, search_queries):
"""Load all address books with the given names from the config.
:param names: the address books to load
:type names: list(str)
:param config: the config instance to use when looking up address books
:type config: config.Config
:param search... | [
"def",
"load_address_books",
"(",
"names",
",",
"config",
",",
"search_queries",
")",
":",
"all_names",
"=",
"{",
"str",
"(",
"book",
")",
"for",
"book",
"in",
"config",
".",
"abooks",
"}",
"if",
"not",
"names",
":",
"names",
"=",
"all_names",
"elif",
... | Load all address books with the given names from the config.
:param names: the address books to load
:type names: list(str)
:param config: the config instance to use when looking up address books
:type config: config.Config
:param search_queries: a mapping of address book names to search queries
... | [
"Load",
"all",
"address",
"books",
"with",
"the",
"given",
"names",
"from",
"the",
"config",
"."
] | python | test | 42.111111 |
RRZE-HPC/kerncraft | kerncraft/models/roofline.py | https://github.com/RRZE-HPC/kerncraft/blob/c60baf8043e4da8d8d66da7575021c2f4c6c78af/kerncraft/models/roofline.py#L62-L161 | def calculate_cache_access(self):
"""Apply cache prediction to generate cache access behaviour."""
self.results = {'misses': self.predictor.get_misses(),
'hits': self.predictor.get_hits(),
'evicts': self.predictor.get_evicts(),
'ver... | [
"def",
"calculate_cache_access",
"(",
"self",
")",
":",
"self",
".",
"results",
"=",
"{",
"'misses'",
":",
"self",
".",
"predictor",
".",
"get_misses",
"(",
")",
",",
"'hits'",
":",
"self",
".",
"predictor",
".",
"get_hits",
"(",
")",
",",
"'evicts'",
... | Apply cache prediction to generate cache access behaviour. | [
"Apply",
"cache",
"prediction",
"to",
"generate",
"cache",
"access",
"behaviour",
"."
] | python | test | 49.01 |
DLR-RM/RAFCON | source/rafcon/utils/execution_log.py | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/utils/execution_log.py#L78-L302 | def log_to_collapsed_structure(execution_history_items, throw_on_pickle_error=True,
include_erroneous_data_ports=False, full_next=False):
"""
Collapsed structure means that all history items belonging to the same state execution are
merged together into one object (e.g. CallIt... | [
"def",
"log_to_collapsed_structure",
"(",
"execution_history_items",
",",
"throw_on_pickle_error",
"=",
"True",
",",
"include_erroneous_data_ports",
"=",
"False",
",",
"full_next",
"=",
"False",
")",
":",
"# for debugging purposes",
"# execution_history_items_dict = dict()",
... | Collapsed structure means that all history items belonging to the same state execution are
merged together into one object (e.g. CallItem and ReturnItem of an ExecutionState). This
is based on the log structure in which all Items which belong together have the same run_id.
The collapsed items hold input as ... | [
"Collapsed",
"structure",
"means",
"that",
"all",
"history",
"items",
"belonging",
"to",
"the",
"same",
"state",
"execution",
"are",
"merged",
"together",
"into",
"one",
"object",
"(",
"e",
".",
"g",
".",
"CallItem",
"and",
"ReturnItem",
"of",
"an",
"Executi... | python | train | 55.528889 |
assemblerflow/flowcraft | flowcraft/generator/recipe.py | https://github.com/assemblerflow/flowcraft/blob/fc3f4bddded1efc76006600016dc71a06dd908c0/flowcraft/generator/recipe.py#L528-L561 | def brew_innuendo(args):
"""Brews a given list of processes according to the recipe
Parameters
----------
args : argparse.Namespace
The arguments passed through argparser that will be used to check the
the recipe, tasks and brew the process
Returns
-------
str
The f... | [
"def",
"brew_innuendo",
"(",
"args",
")",
":",
"# Create recipe class instance",
"automatic_pipeline",
"=",
"Innuendo",
"(",
")",
"if",
"not",
"args",
".",
"tasks",
":",
"input_processes",
"=",
"\" \"",
".",
"join",
"(",
"automatic_pipeline",
".",
"process_descrip... | Brews a given list of processes according to the recipe
Parameters
----------
args : argparse.Namespace
The arguments passed through argparser that will be used to check the
the recipe, tasks and brew the process
Returns
-------
str
The final pipeline string, ready for ... | [
"Brews",
"a",
"given",
"list",
"of",
"processes",
"according",
"to",
"the",
"recipe"
] | python | test | 27.029412 |
onnx/onnxmltools | onnxmltools/convert/sparkml/_parse.py | https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxmltools/convert/sparkml/_parse.py#L15-L37 | def _get_variable_for_input(scope, input_name, global_inputs, output_dict):
'''
Find the corresponding Variable for a given raw operator (model) name
The variable is either supplied as graph/global inputs or has been generated as output by previous ops
:param input_name:
:param global_inputs:
:p... | [
"def",
"_get_variable_for_input",
"(",
"scope",
",",
"input_name",
",",
"global_inputs",
",",
"output_dict",
")",
":",
"if",
"input_name",
"in",
"output_dict",
":",
"value",
"=",
"output_dict",
"[",
"input_name",
"]",
"ref_count",
"=",
"value",
"[",
"0",
"]",
... | Find the corresponding Variable for a given raw operator (model) name
The variable is either supplied as graph/global inputs or has been generated as output by previous ops
:param input_name:
:param global_inputs:
:param output_dict:
:return: | [
"Find",
"the",
"corresponding",
"Variable",
"for",
"a",
"given",
"raw",
"operator",
"(",
"model",
")",
"name",
"The",
"variable",
"is",
"either",
"supplied",
"as",
"graph",
"/",
"global",
"inputs",
"or",
"has",
"been",
"generated",
"as",
"output",
"by",
"p... | python | train | 32.521739 |
redhat-cip/python-dciclient | dciclient/v1/shell_commands/purge.py | https://github.com/redhat-cip/python-dciclient/blob/a4aa5899062802bbe4c30a075d8447f8d222d214/dciclient/v1/shell_commands/purge.py#L29-L87 | def purge(context, resource, force):
"""purge(context, resource, force)
Purge soft-deleted resources.
>>> dcictl purge --resource remotecis
"""
resources = ['components', 'topics', 'tests', 'teams', 'feeders',
'remotecis', 'jobs', 'files', 'users', 'products']
l_resources = ... | [
"def",
"purge",
"(",
"context",
",",
"resource",
",",
"force",
")",
":",
"resources",
"=",
"[",
"'components'",
",",
"'topics'",
",",
"'tests'",
",",
"'teams'",
",",
"'feeders'",
",",
"'remotecis'",
",",
"'jobs'",
",",
"'files'",
",",
"'users'",
",",
"'p... | purge(context, resource, force)
Purge soft-deleted resources.
>>> dcictl purge --resource remotecis | [
"purge",
"(",
"context",
"resource",
"force",
")"
] | python | train | 40.40678 |
jsocol/pystatsd | statsd/client/base.py | https://github.com/jsocol/pystatsd/blob/006a86394c44ff71e6e8e52529daa3c0fdcc93fb/statsd/client/base.py#L37-L39 | def decr(self, stat, count=1, rate=1):
"""Decrement a stat by `count`."""
self.incr(stat, -count, rate) | [
"def",
"decr",
"(",
"self",
",",
"stat",
",",
"count",
"=",
"1",
",",
"rate",
"=",
"1",
")",
":",
"self",
".",
"incr",
"(",
"stat",
",",
"-",
"count",
",",
"rate",
")"
] | Decrement a stat by `count`. | [
"Decrement",
"a",
"stat",
"by",
"count",
"."
] | python | train | 39 |
gwastro/pycbc-glue | pycbc_glue/ligolw/utils/process.py | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/process.py#L204-L209 | def doc_includes_process(xmldoc, program):
"""
Return True if the process table in xmldoc includes entries for a
program named program.
"""
return program in lsctables.ProcessTable.get_table(xmldoc).getColumnByName(u"program") | [
"def",
"doc_includes_process",
"(",
"xmldoc",
",",
"program",
")",
":",
"return",
"program",
"in",
"lsctables",
".",
"ProcessTable",
".",
"get_table",
"(",
"xmldoc",
")",
".",
"getColumnByName",
"(",
"u\"program\"",
")"
] | Return True if the process table in xmldoc includes entries for a
program named program. | [
"Return",
"True",
"if",
"the",
"process",
"table",
"in",
"xmldoc",
"includes",
"entries",
"for",
"a",
"program",
"named",
"program",
"."
] | python | train | 37.666667 |
thombashi/pytablewriter | pytablewriter/writer/text/_jsonlines.py | https://github.com/thombashi/pytablewriter/blob/52ea85ed8e89097afa64f137c6a1b3acdfefdbda/pytablewriter/writer/text/_jsonlines.py#L32-L48 | def write_table(self):
"""
|write_table| with
`Line-delimited JSON(LDJSON) <https://en.wikipedia.org/wiki/JSON_streaming#Line-delimited_JSON>`__
/NDJSON/JSON Lines format.
:raises pytablewriter.EmptyHeaderError: If the |headers| is empty.
:Example:
:ref:`exam... | [
"def",
"write_table",
"(",
"self",
")",
":",
"with",
"self",
".",
"_logger",
":",
"self",
".",
"_verify_property",
"(",
")",
"self",
".",
"_preprocess",
"(",
")",
"for",
"values",
"in",
"self",
".",
"_table_value_matrix",
":",
"self",
".",
"_write_line",
... | |write_table| with
`Line-delimited JSON(LDJSON) <https://en.wikipedia.org/wiki/JSON_streaming#Line-delimited_JSON>`__
/NDJSON/JSON Lines format.
:raises pytablewriter.EmptyHeaderError: If the |headers| is empty.
:Example:
:ref:`example-jsonl-writer` | [
"|write_table|",
"with",
"Line",
"-",
"delimited",
"JSON",
"(",
"LDJSON",
")",
"<https",
":",
"//",
"en",
".",
"wikipedia",
".",
"org",
"/",
"wiki",
"/",
"JSON_streaming#Line",
"-",
"delimited_JSON",
">",
"__",
"/",
"NDJSON",
"/",
"JSON",
"Lines",
"format"... | python | train | 31.411765 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.