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 |
|---|---|---|---|---|---|---|---|---|---|
PGower/PyCanvas | pycanvas/apis/courses.py | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/courses.py#L1275-L1315 | def copy_course_content(self, course_id, exclude=None, only=None, source_course=None):
"""
Copy course content.
DEPRECATED: Please use the {api:ContentMigrationsController#create Content Migrations API}
Copies content from one course into another. The default is to copy a... | [
"def",
"copy_course_content",
"(",
"self",
",",
"course_id",
",",
"exclude",
"=",
"None",
",",
"only",
"=",
"None",
",",
"source_course",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH -... | Copy course content.
DEPRECATED: Please use the {api:ContentMigrationsController#create Content Migrations API}
Copies content from one course into another. The default is to copy all course
content. You can control specific types to copy by using either the 'except' option
... | [
"Copy",
"course",
"content",
".",
"DEPRECATED",
":",
"Please",
"use",
"the",
"{",
"api",
":",
"ContentMigrationsController#create",
"Content",
"Migrations",
"API",
"}",
"Copies",
"content",
"from",
"one",
"course",
"into",
"another",
".",
"The",
"default",
"is",... | python | train | 47.317073 |
skorch-dev/skorch | skorch/utils.py | https://github.com/skorch-dev/skorch/blob/5b9b8b7b7712cb6e5aaa759d9608ea6269d5bcd3/skorch/utils.py#L220-L228 | def _normalize_numpy_indices(i):
"""Normalize the index in case it is a numpy integer or boolean
array."""
if isinstance(i, np.ndarray):
if i.dtype == bool:
i = tuple(j.tolist() for j in i.nonzero())
elif i.dtype == int:
i = i.tolist()
return i | [
"def",
"_normalize_numpy_indices",
"(",
"i",
")",
":",
"if",
"isinstance",
"(",
"i",
",",
"np",
".",
"ndarray",
")",
":",
"if",
"i",
".",
"dtype",
"==",
"bool",
":",
"i",
"=",
"tuple",
"(",
"j",
".",
"tolist",
"(",
")",
"for",
"j",
"in",
"i",
"... | Normalize the index in case it is a numpy integer or boolean
array. | [
"Normalize",
"the",
"index",
"in",
"case",
"it",
"is",
"a",
"numpy",
"integer",
"or",
"boolean",
"array",
"."
] | python | train | 32.444444 |
cloudbase/python-hnvclient | hnv/client.py | https://github.com/cloudbase/python-hnvclient/blob/b019452af01db22629809b8930357a2ebf6494be/hnv/client.py#L105-L120 | def _reset_model(self, response):
"""Update the fields value with the received information."""
# pylint: disable=no-member
# Reset the model to the initial state
self._provision_done = False # Set back the provision flag
self._changes.clear() # Clear the changes
... | [
"def",
"_reset_model",
"(",
"self",
",",
"response",
")",
":",
"# pylint: disable=no-member",
"# Reset the model to the initial state",
"self",
".",
"_provision_done",
"=",
"False",
"# Set back the provision flag",
"self",
".",
"_changes",
".",
"clear",
"(",
")",
"# Cle... | Update the fields value with the received information. | [
"Update",
"the",
"fields",
"value",
"with",
"the",
"received",
"information",
"."
] | python | train | 35.0625 |
IdentityPython/pysaml2 | src/saml2/server.py | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/server.py#L121-L188 | def init_config(self, stype="idp"):
""" Remaining init of the server configuration
:param stype: The type of Server ("idp"/"aa")
"""
if stype == "aa":
return
# subject information is stored in a database
# default database is in memory which is OK in some se... | [
"def",
"init_config",
"(",
"self",
",",
"stype",
"=",
"\"idp\"",
")",
":",
"if",
"stype",
"==",
"\"aa\"",
":",
"return",
"# subject information is stored in a database",
"# default database is in memory which is OK in some setups",
"dbspec",
"=",
"self",
".",
"config",
... | Remaining init of the server configuration
:param stype: The type of Server ("idp"/"aa") | [
"Remaining",
"init",
"of",
"the",
"server",
"configuration"
] | python | train | 36.588235 |
jason-weirather/py-seq-tools | seqtools/statistics/__init__.py | https://github.com/jason-weirather/py-seq-tools/blob/f642c2c73ffef2acc83656a78059a476fc734ca1/seqtools/statistics/__init__.py#L24-L41 | def median(arr):
"""median of the values, must have more than 0 entries.
:param arr: list of numbers
:type arr: number[] a number array
:return: median
:rtype: float
"""
if len(arr) == 0:
sys.stderr.write("ERROR: no content in array to take average\n")
sys.exit()
if len(arr) == 1: return arr[0... | [
"def",
"median",
"(",
"arr",
")",
":",
"if",
"len",
"(",
"arr",
")",
"==",
"0",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"ERROR: no content in array to take average\\n\"",
")",
"sys",
".",
"exit",
"(",
")",
"if",
"len",
"(",
"arr",
")",
"==",
... | median of the values, must have more than 0 entries.
:param arr: list of numbers
:type arr: number[] a number array
:return: median
:rtype: float | [
"median",
"of",
"the",
"values",
"must",
"have",
"more",
"than",
"0",
"entries",
"."
] | python | train | 24.666667 |
inveniosoftware/invenio-communities | invenio_communities/links.py | https://github.com/inveniosoftware/invenio-communities/blob/5c4de6783724d276ae1b6dd13a399a9e22fadc7a/invenio_communities/links.py#L48-L63 | def default_links_pagination_factory(page, urlkwargs):
"""Factory for record links generation."""
endpoint = '.communities_list'
links = {
'self': url_for(endpoint, page=page.page, _external=True, **urlkwargs),
}
if page.has_prev:
links['prev'] = url_for(endpoint, page=page.prev_nu... | [
"def",
"default_links_pagination_factory",
"(",
"page",
",",
"urlkwargs",
")",
":",
"endpoint",
"=",
"'.communities_list'",
"links",
"=",
"{",
"'self'",
":",
"url_for",
"(",
"endpoint",
",",
"page",
"=",
"page",
".",
"page",
",",
"_external",
"=",
"True",
",... | Factory for record links generation. | [
"Factory",
"for",
"record",
"links",
"generation",
"."
] | python | train | 33.1875 |
ChristopherRabotin/bungiesearch | bungiesearch/utils.py | https://github.com/ChristopherRabotin/bungiesearch/blob/13768342bc2698b214eb0003c2d113b6e273c30d/bungiesearch/utils.py#L67-L87 | def delete_index_item(item, model_name, refresh=True):
'''
Deletes an item from the index.
:param item: must be a serializable object.
:param model_name: doctype, which must also be the model name.
:param refresh: a boolean that determines whether to refresh the index, making all operations performe... | [
"def",
"delete_index_item",
"(",
"item",
",",
"model_name",
",",
"refresh",
"=",
"True",
")",
":",
"src",
"=",
"Bungiesearch",
"(",
")",
"logger",
".",
"info",
"(",
"'Getting index for model {}.'",
".",
"format",
"(",
"model_name",
")",
")",
"for",
"index_na... | Deletes an item from the index.
:param item: must be a serializable object.
:param model_name: doctype, which must also be the model name.
:param refresh: a boolean that determines whether to refresh the index, making all operations performed since the last refresh
immediately available for search, inst... | [
"Deletes",
"an",
"item",
"from",
"the",
"index",
".",
":",
"param",
"item",
":",
"must",
"be",
"a",
"serializable",
"object",
".",
":",
"param",
"model_name",
":",
"doctype",
"which",
"must",
"also",
"be",
"the",
"model",
"name",
".",
":",
"param",
"re... | python | train | 50.952381 |
esterhui/pypu | scripts/build_json_from_flickr.py | https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/scripts/build_json_from_flickr.py#L77-L98 | def redistribute_duplicates(data):
"""Given a dictionary of photo sets, will look at lat/lon between
sets, if they match, randomly move them around so the google map
markeres do not overlap
"""
coordinate_list=[]
# Build a list of coordinates
for myset in data['sets']:
coordinat... | [
"def",
"redistribute_duplicates",
"(",
"data",
")",
":",
"coordinate_list",
"=",
"[",
"]",
"# Build a list of coordinates",
"for",
"myset",
"in",
"data",
"[",
"'sets'",
"]",
":",
"coordinate_list",
".",
"append",
"(",
"(",
"myset",
"[",
"'latitude'",
"]",
",",... | Given a dictionary of photo sets, will look at lat/lon between
sets, if they match, randomly move them around so the google map
markeres do not overlap | [
"Given",
"a",
"dictionary",
"of",
"photo",
"sets",
"will",
"look",
"at",
"lat",
"/",
"lon",
"between",
"sets",
"if",
"they",
"match",
"randomly",
"move",
"them",
"around",
"so",
"the",
"google",
"map",
"markeres",
"do",
"not",
"overlap"
] | python | train | 37.545455 |
zomux/deepy | deepy/layers/layer.py | https://github.com/zomux/deepy/blob/090fbad22a08a809b12951cd0d4984f5bd432698/deepy/layers/layer.py#L47-L68 | def init(self, input_dim=0, input_dims=None, no_prepare=False):
"""
Initialize the layer.
:param no_prepare: avoid calling preparation function
"""
if self.initialized:
return
# configure input dimensions
if input_dims:
self.input_dims = in... | [
"def",
"init",
"(",
"self",
",",
"input_dim",
"=",
"0",
",",
"input_dims",
"=",
"None",
",",
"no_prepare",
"=",
"False",
")",
":",
"if",
"self",
".",
"initialized",
":",
"return",
"# configure input dimensions",
"if",
"input_dims",
":",
"self",
".",
"input... | Initialize the layer.
:param no_prepare: avoid calling preparation function | [
"Initialize",
"the",
"layer",
".",
":",
"param",
"no_prepare",
":",
"avoid",
"calling",
"preparation",
"function"
] | python | test | 31.454545 |
ryanmcgrath/twython | twython/api.py | https://github.com/ryanmcgrath/twython/blob/7366de80efcbbdfaf615d3f1fea72546196916fc/twython/api.py#L367-L403 | def get_authorized_tokens(self, oauth_verifier):
"""Returns a dict of authorized tokens after they go through the
:class:`get_authentication_tokens` phase.
:param oauth_verifier: (required) The oauth_verifier (or a.k.a PIN
for non web apps) retrieved from the callback url querystring
... | [
"def",
"get_authorized_tokens",
"(",
"self",
",",
"oauth_verifier",
")",
":",
"if",
"self",
".",
"oauth_version",
"!=",
"1",
":",
"raise",
"TwythonError",
"(",
"'This method can only be called when your \\\n OAuth version is 1.0.'",
")",
"respons... | Returns a dict of authorized tokens after they go through the
:class:`get_authentication_tokens` phase.
:param oauth_verifier: (required) The oauth_verifier (or a.k.a PIN
for non web apps) retrieved from the callback url querystring
:rtype: dict | [
"Returns",
"a",
"dict",
"of",
"authorized",
"tokens",
"after",
"they",
"go",
"through",
"the",
":",
"class",
":",
"get_authentication_tokens",
"phase",
"."
] | python | train | 39.594595 |
chrisspen/burlap | burlap/vm.py | https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/vm.py#L529-L545 | def exists(name=None, group=None, release=None, except_release=None, verbose=1):
"""
Determines if a virtual machine instance exists.
"""
verbose = int(verbose)
instances = list_instances(
name=name,
group=group,
release=release,
except_release=except_release,
... | [
"def",
"exists",
"(",
"name",
"=",
"None",
",",
"group",
"=",
"None",
",",
"release",
"=",
"None",
",",
"except_release",
"=",
"None",
",",
"verbose",
"=",
"1",
")",
":",
"verbose",
"=",
"int",
"(",
"verbose",
")",
"instances",
"=",
"list_instances",
... | Determines if a virtual machine instance exists. | [
"Determines",
"if",
"a",
"virtual",
"machine",
"instance",
"exists",
"."
] | python | valid | 29 |
aws/sagemaker-python-sdk | src/sagemaker/estimator.py | https://github.com/aws/sagemaker-python-sdk/blob/a9e724c7d3f5572b68c3903548c792a59d99799a/src/sagemaker/estimator.py#L408-L462 | def _prepare_init_params_from_job_description(cls, job_details, model_channel_name=None):
"""Convert the job description to init params that can be handled by the class constructor
Args:
job_details: the returned job details from a describe_training_job API call.
model_channel_n... | [
"def",
"_prepare_init_params_from_job_description",
"(",
"cls",
",",
"job_details",
",",
"model_channel_name",
"=",
"None",
")",
":",
"init_params",
"=",
"dict",
"(",
")",
"init_params",
"[",
"'role'",
"]",
"=",
"job_details",
"[",
"'RoleArn'",
"]",
"init_params",... | Convert the job description to init params that can be handled by the class constructor
Args:
job_details: the returned job details from a describe_training_job API call.
model_channel_name (str): Name of the channel where pre-trained model data will be downloaded.
Returns:
... | [
"Convert",
"the",
"job",
"description",
"to",
"init",
"params",
"that",
"can",
"be",
"handled",
"by",
"the",
"class",
"constructor"
] | python | train | 53.272727 |
topic2k/pygcgen | pygcgen/generator.py | https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L1073-L1086 | def filter_excluded_tags(self, all_tags):
"""
Filter tags according exclude_tags and exclude_tags_regex option.
:param list(dict) all_tags: Pre-filtered tags.
:rtype: list(dict)
:return: Filtered tags.
"""
filtered_tags = copy.deepcopy(all_tags)
if self.o... | [
"def",
"filter_excluded_tags",
"(",
"self",
",",
"all_tags",
")",
":",
"filtered_tags",
"=",
"copy",
".",
"deepcopy",
"(",
"all_tags",
")",
"if",
"self",
".",
"options",
".",
"exclude_tags",
":",
"filtered_tags",
"=",
"self",
".",
"apply_exclude_tags",
"(",
... | Filter tags according exclude_tags and exclude_tags_regex option.
:param list(dict) all_tags: Pre-filtered tags.
:rtype: list(dict)
:return: Filtered tags. | [
"Filter",
"tags",
"according",
"exclude_tags",
"and",
"exclude_tags_regex",
"option",
"."
] | python | valid | 38.571429 |
dyachan/django-usuario | usuario/models.py | https://github.com/dyachan/django-usuario/blob/10712cf78d202721b965c6b89b11d4b3bd6bb67b/usuario/models.py#L49-L96 | def save(self, UserSave=True, *args, **kwargs):
""" Se sobreescribe el método salvar para poder gestionar la creación de un
User en caso que no se haya creado y enlazado uno antes.
Se puede elegir si se desea guardar los cambios efectuados en user.
"""
if hasattr(self, 'user') and self.user is not ... | [
"def",
"save",
"(",
"self",
",",
"UserSave",
"=",
"True",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'user'",
")",
"and",
"self",
".",
"user",
"is",
"not",
"None",
":",
"# caso que se le asigna un usuario d... | Se sobreescribe el método salvar para poder gestionar la creación de un
User en caso que no se haya creado y enlazado uno antes.
Se puede elegir si se desea guardar los cambios efectuados en user. | [
"Se",
"sobreescribe",
"el",
"método",
"salvar",
"para",
"poder",
"gestionar",
"la",
"creación",
"de",
"un",
"User",
"en",
"caso",
"que",
"no",
"se",
"haya",
"creado",
"y",
"enlazado",
"uno",
"antes",
".",
"Se",
"puede",
"elegir",
"si",
"se",
"desea",
"gu... | python | train | 40.166667 |
dcaune/perseus-lib-python-common | majormode/perseus/model/obj.py | https://github.com/dcaune/perseus-lib-python-common/blob/ba48fe0fd9bb4a75b53e7d10c41ada36a72d4496/majormode/perseus/model/obj.py#L279-L315 | def shallow_copy(obj, attribute_names,
ignore_missing_attributes=True):
"""
Return a shallow copy of the given object, including only the
specified attributes of this object.
@param obj: an object to copy.
@param attribute_names: a list of names of the attributes to copy.
@param igno... | [
"def",
"shallow_copy",
"(",
"obj",
",",
"attribute_names",
",",
"ignore_missing_attributes",
"=",
"True",
")",
":",
"shallow_object",
"=",
"copy",
".",
"copy",
"(",
"obj",
")",
"shallow_object",
".",
"__dict__",
"=",
"{",
"}",
"for",
"attribute_name",
"in",
... | Return a shallow copy of the given object, including only the
specified attributes of this object.
@param obj: an object to copy.
@param attribute_names: a list of names of the attributes to copy.
@param ignore_missing_attributes: ``False`` indicates that the function
can ignore attributes t... | [
"Return",
"a",
"shallow",
"copy",
"of",
"the",
"given",
"object",
"including",
"only",
"the",
"specified",
"attributes",
"of",
"this",
"object",
"."
] | python | train | 33.162162 |
spotify/luigi | luigi/tools/range.py | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/tools/range.py#L491-L528 | def _constrain_glob(glob, paths, limit=5):
"""
Tweaks glob into a list of more specific globs that together still cover paths and not too much extra.
Saves us minutes long listings for long dataset histories.
Specifically, in this implementation the leftmost occurrences of "[0-9]"
give rise to a f... | [
"def",
"_constrain_glob",
"(",
"glob",
",",
"paths",
",",
"limit",
"=",
"5",
")",
":",
"def",
"digit_set_wildcard",
"(",
"chars",
")",
":",
"\"\"\"\n Makes a wildcard expression for the set, a bit readable, e.g. [1-5].\n \"\"\"",
"chars",
"=",
"sorted",
"(",... | Tweaks glob into a list of more specific globs that together still cover paths and not too much extra.
Saves us minutes long listings for long dataset histories.
Specifically, in this implementation the leftmost occurrences of "[0-9]"
give rise to a few separate globs that each specialize the expression t... | [
"Tweaks",
"glob",
"into",
"a",
"list",
"of",
"more",
"specific",
"globs",
"that",
"together",
"still",
"cover",
"paths",
"and",
"not",
"too",
"much",
"extra",
"."
] | python | train | 40.157895 |
saltstack/salt | salt/modules/boto_datapipeline.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_datapipeline.py#L57-L79 | def create_pipeline(name, unique_id, description='', region=None, key=None, keyid=None,
profile=None):
'''
Create a new, empty pipeline. This function is idempotent.
CLI example:
.. code-block:: bash
salt myminion boto_datapipeline.create_pipeline my_name my_unique_id
... | [
"def",
"create_pipeline",
"(",
"name",
",",
"unique_id",
",",
"description",
"=",
"''",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"client",
"=",
"_get_client",
"(",
"region",
... | Create a new, empty pipeline. This function is idempotent.
CLI example:
.. code-block:: bash
salt myminion boto_datapipeline.create_pipeline my_name my_unique_id | [
"Create",
"a",
"new",
"empty",
"pipeline",
".",
"This",
"function",
"is",
"idempotent",
"."
] | python | train | 30.521739 |
datapythonista/mnist | mnist/__init__.py | https://github.com/datapythonista/mnist/blob/d91df2b27ee62d07396b5b64c7cfead59833b563/mnist/__init__.py#L123-L146 | def download_and_parse_mnist_file(fname, target_dir=None, force=False):
"""Download the IDX file named fname from the URL specified in dataset_url
and return it as a numpy array.
Parameters
----------
fname : str
File name to download and parse
target_dir : str
Directory where ... | [
"def",
"download_and_parse_mnist_file",
"(",
"fname",
",",
"target_dir",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"fname",
"=",
"download_file",
"(",
"fname",
",",
"target_dir",
"=",
"target_dir",
",",
"force",
"=",
"force",
")",
"fopen",
"=",
"g... | Download the IDX file named fname from the URL specified in dataset_url
and return it as a numpy array.
Parameters
----------
fname : str
File name to download and parse
target_dir : str
Directory where to store the file
force : bool
Force downloading the file, if it a... | [
"Download",
"the",
"IDX",
"file",
"named",
"fname",
"from",
"the",
"URL",
"specified",
"in",
"dataset_url",
"and",
"return",
"it",
"as",
"a",
"numpy",
"array",
"."
] | python | train | 30 |
tylerbutler/engineer | engineer/conf.py | https://github.com/tylerbutler/engineer/blob/8884f587297f37646c40e5553174852b444a4024/engineer/conf.py#L432-L440 | def create_required_directories(self):
"""Creates any directories required for Engineer to function if they don't already exist."""
required = (self.CACHE_DIR,
self.LOG_DIR,
self.OUTPUT_DIR,
self.ENGINEER.JINJA_CACHE_DIR,)
for folder i... | [
"def",
"create_required_directories",
"(",
"self",
")",
":",
"required",
"=",
"(",
"self",
".",
"CACHE_DIR",
",",
"self",
".",
"LOG_DIR",
",",
"self",
".",
"OUTPUT_DIR",
",",
"self",
".",
"ENGINEER",
".",
"JINJA_CACHE_DIR",
",",
")",
"for",
"folder",
"in",... | Creates any directories required for Engineer to function if they don't already exist. | [
"Creates",
"any",
"directories",
"required",
"for",
"Engineer",
"to",
"function",
"if",
"they",
"don",
"t",
"already",
"exist",
"."
] | python | train | 41.666667 |
chaoss/grimoirelab-perceval | perceval/backends/core/git.py | https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/git.py#L1043-L1081 | def show(self, commits=None, encoding='utf-8'):
"""Show the data of a set of commits.
The method returns the output of Git show command for a
set of commits using the following options:
git show --raw --numstat --pretty=fuller --decorate=full
--parents -M -C -c [<co... | [
"def",
"show",
"(",
"self",
",",
"commits",
"=",
"None",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"if",
"self",
".",
"is_empty",
"(",
")",
":",
"logger",
".",
"warning",
"(",
"\"Git %s repository is empty; unable to run show\"",
",",
"self",
".",
"uri",
... | Show the data of a set of commits.
The method returns the output of Git show command for a
set of commits using the following options:
git show --raw --numstat --pretty=fuller --decorate=full
--parents -M -C -c [<commit>...<commit>]
When the list of commits is empt... | [
"Show",
"the",
"data",
"of",
"a",
"set",
"of",
"commits",
"."
] | python | test | 37.051282 |
sp4ke/howto | howto/howto.py | https://github.com/sp4ke/howto/blob/2588144a587be5138d45ca9db0ce6ab125fa7d0c/howto/howto.py#L78-L84 | def cli_run():
"""docstring for argparse"""
parser = argparse.ArgumentParser(description='Stupidly simple code answers from StackOverflow')
parser.add_argument('query', help="What's the problem ?", type=str, nargs='+')
parser.add_argument('-t','--tags', help='semicolon separated tags -> python;lambda')
... | [
"def",
"cli_run",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Stupidly simple code answers from StackOverflow'",
")",
"parser",
".",
"add_argument",
"(",
"'query'",
",",
"help",
"=",
"\"What's the problem ?\"",
",",
"t... | docstring for argparse | [
"docstring",
"for",
"argparse"
] | python | test | 51.285714 |
spotify/docker_interface | docker_interface/plugins/base.py | https://github.com/spotify/docker_interface/blob/4df80e1fe072d958020080d32c16551ff7703d51/docker_interface/plugins/base.py#L199-L224 | def execute_command(self, parts, dry_run):
"""
Execute a command.
Parameters
----------
parts : list
Sequence of strings constituting a command.
dry_run : bool
Whether to just log the command instead of executing it.
Returns
-----... | [
"def",
"execute_command",
"(",
"self",
",",
"parts",
",",
"dry_run",
")",
":",
"if",
"dry_run",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"dry-run command '%s'\"",
",",
"\" \"",
".",
"join",
"(",
"map",
"(",
"str",
",",
"parts",
")",
")",
")",
... | Execute a command.
Parameters
----------
parts : list
Sequence of strings constituting a command.
dry_run : bool
Whether to just log the command instead of executing it.
Returns
-------
status : int
Status code of the executed... | [
"Execute",
"a",
"command",
"."
] | python | train | 35.923077 |
openpaperwork/paperwork-backend | paperwork_backend/util.py | https://github.com/openpaperwork/paperwork-backend/blob/114b831e94e039e68b339751fd18250877abad76/paperwork_backend/util.py#L68-L116 | def split_words(sentence, modify=True, keep_shorts=False):
"""
Extract and yield the keywords from the sentence:
- Drop keywords that are too short (keep_shorts=False)
- Drop the accents (modify=True)
- Make everything lower case (modify=True)
- Try to separate the words as much as possible (usi... | [
"def",
"split_words",
"(",
"sentence",
",",
"modify",
"=",
"True",
",",
"keep_shorts",
"=",
"False",
")",
":",
"if",
"(",
"sentence",
"==",
"\"*\"",
")",
":",
"yield",
"sentence",
"return",
"# TODO: i18n",
"if",
"modify",
":",
"sentence",
"=",
"sentence",
... | Extract and yield the keywords from the sentence:
- Drop keywords that are too short (keep_shorts=False)
- Drop the accents (modify=True)
- Make everything lower case (modify=True)
- Try to separate the words as much as possible (using 2 list of
separators, one being more complete than the others) | [
"Extract",
"and",
"yield",
"the",
"keywords",
"from",
"the",
"sentence",
":",
"-",
"Drop",
"keywords",
"that",
"are",
"too",
"short",
"(",
"keep_shorts",
"=",
"False",
")",
"-",
"Drop",
"the",
"accents",
"(",
"modify",
"=",
"True",
")",
"-",
"Make",
"e... | python | train | 31.714286 |
facelessuser/backrefs | backrefs/_bre_parse.py | https://github.com/facelessuser/backrefs/blob/3b3d60f5d57b02044f880aa29c9c5add0e31a34f/backrefs/_bre_parse.py#L356-L399 | def subgroup(self, t, i):
"""Handle parenthesis."""
current = []
# (?flags)
flags = self.get_flags(i)
if flags:
self.flags(flags[2:-1])
return [flags]
# (?#comment)
comments = self.get_comments(i)
if comments:
return ... | [
"def",
"subgroup",
"(",
"self",
",",
"t",
",",
"i",
")",
":",
"current",
"=",
"[",
"]",
"# (?flags)",
"flags",
"=",
"self",
".",
"get_flags",
"(",
"i",
")",
"if",
"flags",
":",
"self",
".",
"flags",
"(",
"flags",
"[",
"2",
":",
"-",
"1",
"]",
... | Handle parenthesis. | [
"Handle",
"parenthesis",
"."
] | python | train | 22.636364 |
numenta/htmresearch | projects/l2_pooling/noise_tolerance_l2_l4.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/l2_pooling/noise_tolerance_l2_l4.py#L45-L77 | def noisy(pattern, noiseLevel, totalNumCells):
"""
Generate a noisy copy of a pattern.
Given number of active bits w = len(pattern),
deactivate noiseLevel*w cells, and activate noiseLevel*w other cells.
@param pattern (set)
A set of active indices
@param noiseLevel (float)
The percentage of the bits ... | [
"def",
"noisy",
"(",
"pattern",
",",
"noiseLevel",
",",
"totalNumCells",
")",
":",
"n",
"=",
"int",
"(",
"noiseLevel",
"*",
"len",
"(",
"pattern",
")",
")",
"noised",
"=",
"set",
"(",
"pattern",
")",
"noised",
".",
"difference_update",
"(",
"random",
"... | Generate a noisy copy of a pattern.
Given number of active bits w = len(pattern),
deactivate noiseLevel*w cells, and activate noiseLevel*w other cells.
@param pattern (set)
A set of active indices
@param noiseLevel (float)
The percentage of the bits to shuffle
@param totalNumCells (int)
The number o... | [
"Generate",
"a",
"noisy",
"copy",
"of",
"a",
"pattern",
"."
] | python | train | 22.393939 |
sci-bots/pygtkhelpers | pygtkhelpers/proxy.py | https://github.com/sci-bots/pygtkhelpers/blob/3a6e6d6340221c686229cd1c951d7537dae81b07/pygtkhelpers/proxy.py#L124-L133 | def connect_widget(self):
"""Perform the initial connection of the widget
the default implementation will connect to the widgets signal
based on self.signal_name
"""
if self.signal_name is not None:
# None for read only widgets
sid = self.widget.connect(s... | [
"def",
"connect_widget",
"(",
"self",
")",
":",
"if",
"self",
".",
"signal_name",
"is",
"not",
"None",
":",
"# None for read only widgets",
"sid",
"=",
"self",
".",
"widget",
".",
"connect",
"(",
"self",
".",
"signal_name",
",",
"self",
".",
"widget_changed"... | Perform the initial connection of the widget
the default implementation will connect to the widgets signal
based on self.signal_name | [
"Perform",
"the",
"initial",
"connection",
"of",
"the",
"widget"
] | python | train | 38.9 |
hobson/pug-invest | pug/invest/plot.py | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/plot.py#L30-L188 | def animate_panel(panel, keys=None, columns=None, interval=1000, blit=False, titles='', path='animate_panel', xlabel='Time', ylabel='Value', ext='gif',
replot=False, linewidth=3, close=False, fontsize=24, background_color='white', alpha=1, figsize=(12,8), xlabel_rotation=-25, plot_kwargs=(('rotation'... | [
"def",
"animate_panel",
"(",
"panel",
",",
"keys",
"=",
"None",
",",
"columns",
"=",
"None",
",",
"interval",
"=",
"1000",
",",
"blit",
"=",
"False",
",",
"titles",
"=",
"''",
",",
"path",
"=",
"'animate_panel'",
",",
"xlabel",
"=",
"'Time'",
",",
"y... | Animate a pandas.Panel by flipping through plots of the data in each dataframe
Arguments:
panel (pandas.Panel): Pandas Panel of DataFrames to animate (each DataFrame is an animation video frame)
keys (list of str): ordered list of panel keys (pages) to animate
columns (list of str): ordered list ... | [
"Animate",
"a",
"pandas",
".",
"Panel",
"by",
"flipping",
"through",
"plots",
"of",
"the",
"data",
"in",
"each",
"dataframe"
] | python | train | 40.471698 |
nir0s/jocker | jocker/jocker.py | https://github.com/nir0s/jocker/blob/b03c78adeb59ac836b388e4a7f14337d834c4b71/jocker/jocker.py#L55-L72 | def _import_config(config_file):
"""returns a configuration object
:param string config_file: path to config file
"""
# get config file path
jocker_lgr.debug('config file is: {0}'.format(config_file))
# append to path for importing
try:
jocker_lgr.debug('importing config...')
... | [
"def",
"_import_config",
"(",
"config_file",
")",
":",
"# get config file path",
"jocker_lgr",
".",
"debug",
"(",
"'config file is: {0}'",
".",
"format",
"(",
"config_file",
")",
")",
"# append to path for importing",
"try",
":",
"jocker_lgr",
".",
"debug",
"(",
"'i... | returns a configuration object
:param string config_file: path to config file | [
"returns",
"a",
"configuration",
"object"
] | python | valid | 36.111111 |
aws/aws-xray-sdk-python | aws_xray_sdk/core/models/entity.py | https://github.com/aws/aws-xray-sdk-python/blob/707358cd3a516d51f2ebf71cf34f00e8d906a667/aws_xray_sdk/core/models/entity.py#L123-L146 | def put_annotation(self, key, value):
"""
Annotate segment or subsegment with a key-value pair.
Annotations will be indexed for later search query.
:param str key: annotation key
:param object value: annotation value. Any type other than
string/number/bool will be dr... | [
"def",
"put_annotation",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"self",
".",
"_check_ended",
"(",
")",
"if",
"not",
"isinstance",
"(",
"key",
",",
"string_types",
")",
":",
"log",
".",
"warning",
"(",
"\"ignoring non string type annotation key with t... | Annotate segment or subsegment with a key-value pair.
Annotations will be indexed for later search query.
:param str key: annotation key
:param object value: annotation value. Any type other than
string/number/bool will be dropped | [
"Annotate",
"segment",
"or",
"subsegment",
"with",
"a",
"key",
"-",
"value",
"pair",
".",
"Annotations",
"will",
"be",
"indexed",
"for",
"later",
"search",
"query",
"."
] | python | train | 37.791667 |
ioos/compliance-checker | compliance_checker/suite.py | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/suite.py#L455-L480 | def standard_output(self, ds, limit, check_name, groups):
"""
Generates the Terminal Output for Standard cases
Returns the dataset needed for the verbose output, as well as the failure flags.
"""
score_list, points, out_of = self.get_points(groups, limit)
issue_count = ... | [
"def",
"standard_output",
"(",
"self",
",",
"ds",
",",
"limit",
",",
"check_name",
",",
"groups",
")",
":",
"score_list",
",",
"points",
",",
"out_of",
"=",
"self",
".",
"get_points",
"(",
"groups",
",",
"limit",
")",
"issue_count",
"=",
"out_of",
"-",
... | Generates the Terminal Output for Standard cases
Returns the dataset needed for the verbose output, as well as the failure flags. | [
"Generates",
"the",
"Terminal",
"Output",
"for",
"Standard",
"cases"
] | python | train | 42.653846 |
dhermes/bezier | src/bezier/__config__.py | https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/__config__.py#L48-L72 | def handle_import_error(caught_exc, name):
"""Allow or re-raise an import error.
This is to distinguish between expected and unexpected import errors.
If the module is not found, it simply means the Cython / Fortran speedups
were not built with the package. If the error message is different, e.g.
`... | [
"def",
"handle_import_error",
"(",
"caught_exc",
",",
"name",
")",
":",
"for",
"template",
"in",
"TEMPLATES",
":",
"expected_msg",
"=",
"template",
".",
"format",
"(",
"name",
")",
"if",
"caught_exc",
".",
"args",
"==",
"(",
"expected_msg",
",",
")",
":",
... | Allow or re-raise an import error.
This is to distinguish between expected and unexpected import errors.
If the module is not found, it simply means the Cython / Fortran speedups
were not built with the package. If the error message is different, e.g.
``... undefined symbol: __curve_intersection_MOD_al... | [
"Allow",
"or",
"re",
"-",
"raise",
"an",
"import",
"error",
"."
] | python | train | 38.88 |
PlaidWeb/Publ | publ/index.py | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/index.py#L209-L230 | def scan_index(content_dir):
""" Scan all files in a content directory """
def scan_directory(root, files):
""" Helper function to scan a single directory """
try:
for file in files:
fullpath = os.path.join(root, file)
relpath = os.path.relpath(fullpa... | [
"def",
"scan_index",
"(",
"content_dir",
")",
":",
"def",
"scan_directory",
"(",
"root",
",",
"files",
")",
":",
"\"\"\" Helper function to scan a single directory \"\"\"",
"try",
":",
"for",
"file",
"in",
"files",
":",
"fullpath",
"=",
"os",
".",
"path",
".",
... | Scan all files in a content directory | [
"Scan",
"all",
"files",
"in",
"a",
"content",
"directory"
] | python | train | 43.590909 |
HPAC/matchpy | matchpy/matching/many_to_one.py | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/many_to_one.py#L369-L392 | def _internal_add(self, pattern: Pattern, label, renaming) -> int:
"""Add a new pattern to the matcher.
Equivalent patterns are not added again. However, patterns that are structurally equivalent,
but have different constraints or different variable names are distinguished by the matcher.
... | [
"def",
"_internal_add",
"(",
"self",
",",
"pattern",
":",
"Pattern",
",",
"label",
",",
"renaming",
")",
"->",
"int",
":",
"pattern_index",
"=",
"len",
"(",
"self",
".",
"patterns",
")",
"renamed_constraints",
"=",
"[",
"c",
".",
"with_renamed_vars",
"(",
... | Add a new pattern to the matcher.
Equivalent patterns are not added again. However, patterns that are structurally equivalent,
but have different constraints or different variable names are distinguished by the matcher.
Args:
pattern: The pattern to add.
Returns:
... | [
"Add",
"a",
"new",
"pattern",
"to",
"the",
"matcher",
"."
] | python | train | 45.333333 |
gwastro/pycbc | pycbc/events/veto.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/veto.py#L39-L68 | def indices_within_times(times, start, end):
"""
Return an index array into times that lie within the durations defined by start end arrays
Parameters
----------
times: numpy.ndarray
Array of times
start: numpy.ndarray
Array of duration start times
end: numpy.ndarray
... | [
"def",
"indices_within_times",
"(",
"times",
",",
"start",
",",
"end",
")",
":",
"# coalesce the start/end segments",
"start",
",",
"end",
"=",
"segments_to_start_end",
"(",
"start_end_to_segments",
"(",
"start",
",",
"end",
")",
".",
"coalesce",
"(",
")",
")",
... | Return an index array into times that lie within the durations defined by start end arrays
Parameters
----------
times: numpy.ndarray
Array of times
start: numpy.ndarray
Array of duration start times
end: numpy.ndarray
Array of duration end times
Returns
-------
... | [
"Return",
"an",
"index",
"array",
"into",
"times",
"that",
"lie",
"within",
"the",
"durations",
"defined",
"by",
"start",
"end",
"arrays"
] | python | train | 28.366667 |
nielstron/pysyncthru | pysyncthru/__init__.py | https://github.com/nielstron/pysyncthru/blob/850a85ba0a74cbd5c408102bb02fd005d8b61ffb/pysyncthru/__init__.py#L116-L129 | def toner_status(self, filter_supported: bool = True) -> Dict[str, Any]:
"""Return the state of all toners cartridges."""
toner_status = {}
for color in self.COLOR_NAMES:
try:
toner_stat = self.data.get(
'{}_{}'.format(SyncThru.TONER, color),... | [
"def",
"toner_status",
"(",
"self",
",",
"filter_supported",
":",
"bool",
"=",
"True",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"toner_status",
"=",
"{",
"}",
"for",
"color",
"in",
"self",
".",
"COLOR_NAMES",
":",
"try",
":",
"toner_stat",
... | Return the state of all toners cartridges. | [
"Return",
"the",
"state",
"of",
"all",
"toners",
"cartridges",
"."
] | python | train | 43.5 |
biocore/burrito-fillings | bfillings/blast.py | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/blast.py#L798-L871 | def ids_from_seq_two_step(seq, n, max_iterations, app, core_threshold, \
extra_threshold, lower_threshold, second_db=None):
"""Returns ids that match a seq, using a 2-tiered strategy.
Optionally uses a second database for the second search.
"""
#first time through: reset 'h' and 'e' to core
#-h... | [
"def",
"ids_from_seq_two_step",
"(",
"seq",
",",
"n",
",",
"max_iterations",
",",
"app",
",",
"core_threshold",
",",
"extra_threshold",
",",
"lower_threshold",
",",
"second_db",
"=",
"None",
")",
":",
"#first time through: reset 'h' and 'e' to core",
"#-h is the e-value... | Returns ids that match a seq, using a 2-tiered strategy.
Optionally uses a second database for the second search. | [
"Returns",
"ids",
"that",
"match",
"a",
"seq",
"using",
"a",
"2",
"-",
"tiered",
"strategy",
"."
] | python | train | 36.459459 |
C4ptainCrunch/ics.py | ics/timeline.py | https://github.com/C4ptainCrunch/ics.py/blob/bd918ec7453a7cf73a906cdcc78bd88eb4bab71b/ics/timeline.py#L80-L89 | def at(self, instant):
"""Iterates (in chronological order) over all events that are occuring during `instant`.
Args:
instant (Arrow object)
"""
for event in self:
if event.begin <= instant <= event.end:
yield event | [
"def",
"at",
"(",
"self",
",",
"instant",
")",
":",
"for",
"event",
"in",
"self",
":",
"if",
"event",
".",
"begin",
"<=",
"instant",
"<=",
"event",
".",
"end",
":",
"yield",
"event"
] | Iterates (in chronological order) over all events that are occuring during `instant`.
Args:
instant (Arrow object) | [
"Iterates",
"(",
"in",
"chronological",
"order",
")",
"over",
"all",
"events",
"that",
"are",
"occuring",
"during",
"instant",
"."
] | python | train | 28 |
SetBased/py-etlt | etlt/helper/Type2Helper.py | https://github.com/SetBased/py-etlt/blob/1c5b8ea60293c14f54d7845a9fe5c595021f66f2/etlt/helper/Type2Helper.py#L161-L178 | def _get_date_type(date):
"""
Returns the type of a date.
:param str|datetime.date date: The date.
:rtype: str
"""
if isinstance(date, str):
return 'str'
if isinstance(date, datetime.date):
return 'date'
if isinstance(date, int)... | [
"def",
"_get_date_type",
"(",
"date",
")",
":",
"if",
"isinstance",
"(",
"date",
",",
"str",
")",
":",
"return",
"'str'",
"if",
"isinstance",
"(",
"date",
",",
"datetime",
".",
"date",
")",
":",
"return",
"'date'",
"if",
"isinstance",
"(",
"date",
",",... | Returns the type of a date.
:param str|datetime.date date: The date.
:rtype: str | [
"Returns",
"the",
"type",
"of",
"a",
"date",
"."
] | python | train | 22.388889 |
yjzhang/uncurl_python | uncurl/state_estimation.py | https://github.com/yjzhang/uncurl_python/blob/55c58ca5670f87699d3bd5752fdfa4baa07724dd/uncurl/state_estimation.py#L353-L420 | def update_m(data, old_M, old_W, selected_genes, disp=False, inner_max_iters=100, parallel=True, threads=4, write_progress_file=None, tol=0.0, regularization=0.0, **kwargs):
"""
This returns a new M matrix that contains all genes, given an M that was
created from running state estimation with a subset of ge... | [
"def",
"update_m",
"(",
"data",
",",
"old_M",
",",
"old_W",
",",
"selected_genes",
",",
"disp",
"=",
"False",
",",
"inner_max_iters",
"=",
"100",
",",
"parallel",
"=",
"True",
",",
"threads",
"=",
"4",
",",
"write_progress_file",
"=",
"None",
",",
"tol",... | This returns a new M matrix that contains all genes, given an M that was
created from running state estimation with a subset of genes.
Args:
data (sparse matrix or dense array): data matrix of shape (genes, cells), containing all genes
old_M (array): shape is (selected_genes, k)
old_W (... | [
"This",
"returns",
"a",
"new",
"M",
"matrix",
"that",
"contains",
"all",
"genes",
"given",
"an",
"M",
"that",
"was",
"created",
"from",
"running",
"state",
"estimation",
"with",
"a",
"subset",
"of",
"genes",
"."
] | python | train | 40.5 |
AnthonyBloomer/daftlistings | daftlistings/listing.py | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/listing.py#L349-L362 | def contact_number(self):
"""
This method returns the contact phone number.
:return:
"""
try:
number = self._ad_page_content.find(
'button', {'class': 'phone-number'})
return (base64.b64decode(number.attrs['data-p'])).decode('ascii')
... | [
"def",
"contact_number",
"(",
"self",
")",
":",
"try",
":",
"number",
"=",
"self",
".",
"_ad_page_content",
".",
"find",
"(",
"'button'",
",",
"{",
"'class'",
":",
"'phone-number'",
"}",
")",
"return",
"(",
"base64",
".",
"b64decode",
"(",
"number",
".",... | This method returns the contact phone number.
:return: | [
"This",
"method",
"returns",
"the",
"contact",
"phone",
"number",
".",
":",
"return",
":"
] | python | train | 35.428571 |
markovmodel/msmtools | msmtools/flux/dense/tpt.py | https://github.com/markovmodel/msmtools/blob/54dc76dd2113a0e8f3d15d5316abab41402941be/msmtools/flux/dense/tpt.py#L123-L151 | def flux_producers(F, rtol=1e-05, atol=1e-12):
r"""Return indexes of states that are net flux producers.
Parameters
----------
F : (n, n) ndarray
Matrix of flux values between pairs of states.
rtol : float
relative tolerance. fulfilled if max(outflux-influx, 0) / max(outflux,influx)... | [
"def",
"flux_producers",
"(",
"F",
",",
"rtol",
"=",
"1e-05",
",",
"atol",
"=",
"1e-12",
")",
":",
"n",
"=",
"F",
".",
"shape",
"[",
"0",
"]",
"influxes",
"=",
"np",
".",
"array",
"(",
"np",
".",
"sum",
"(",
"F",
",",
"axis",
"=",
"0",
")",
... | r"""Return indexes of states that are net flux producers.
Parameters
----------
F : (n, n) ndarray
Matrix of flux values between pairs of states.
rtol : float
relative tolerance. fulfilled if max(outflux-influx, 0) / max(outflux,influx) < rtol
atol : float
absolute tolerance... | [
"r",
"Return",
"indexes",
"of",
"states",
"that",
"are",
"net",
"flux",
"producers",
"."
] | python | train | 39.931034 |
celiao/rtsimple | rtsimple/lists.py | https://github.com/celiao/rtsimple/blob/91f82cbd61a745bbe3a2cca54dfbb6b0ac123b86/rtsimple/lists.py#L153-L168 | def dvds_current_releases(self, **kwargs):
"""Gets the upcoming movies from the API.
Args:
page_limit (optional): number of movies to show per page, default=16
page (optional): results page number, default=1
country (optional): localized data for selected country, default=... | [
"def",
"dvds_current_releases",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"path",
"=",
"self",
".",
"_get_path",
"(",
"'dvds_current_releases'",
")",
"response",
"=",
"self",
".",
"_GET",
"(",
"path",
",",
"kwargs",
")",
"self",
".",
"_set_attrs_to_v... | Gets the upcoming movies from the API.
Args:
page_limit (optional): number of movies to show per page, default=16
page (optional): results page number, default=1
country (optional): localized data for selected country, default="us"
Returns:
A dict respresentatio... | [
"Gets",
"the",
"upcoming",
"movies",
"from",
"the",
"API",
"."
] | python | train | 35.875 |
SuperCowPowers/bat | bat/dataframe_to_parquet.py | https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/bat/dataframe_to_parquet.py#L35-L45 | def parquet_to_df(filename, use_threads=1):
"""parquet_to_df: Reads a Parquet file into a Pandas DataFrame
Args:
filename (string): The full path to the filename for the Parquet file
ntreads (int): The number of threads to use (defaults to 1)
"""
try:
return pq.read_t... | [
"def",
"parquet_to_df",
"(",
"filename",
",",
"use_threads",
"=",
"1",
")",
":",
"try",
":",
"return",
"pq",
".",
"read_table",
"(",
"filename",
",",
"use_threads",
"=",
"use_threads",
")",
".",
"to_pandas",
"(",
")",
"except",
"pa",
".",
"lib",
".",
"... | parquet_to_df: Reads a Parquet file into a Pandas DataFrame
Args:
filename (string): The full path to the filename for the Parquet file
ntreads (int): The number of threads to use (defaults to 1) | [
"parquet_to_df",
":",
"Reads",
"a",
"Parquet",
"file",
"into",
"a",
"Pandas",
"DataFrame",
"Args",
":",
"filename",
"(",
"string",
")",
":",
"The",
"full",
"path",
"to",
"the",
"filename",
"for",
"the",
"Parquet",
"file",
"ntreads",
"(",
"int",
")",
":",... | python | train | 43.636364 |
mdickinson/refcycle | refcycle/annotated_graph.py | https://github.com/mdickinson/refcycle/blob/627fad74c74efc601209c96405f8118cd99b2241/refcycle/annotated_graph.py#L318-L356 | def export_image(self, filename='refcycle.png', format=None,
dot_executable='dot'):
"""
Export graph as an image.
This requires that Graphviz is installed and that the ``dot``
executable is in your path.
The *filename* argument specifies the output filename... | [
"def",
"export_image",
"(",
"self",
",",
"filename",
"=",
"'refcycle.png'",
",",
"format",
"=",
"None",
",",
"dot_executable",
"=",
"'dot'",
")",
":",
"# Figure out what output format to use.",
"if",
"format",
"is",
"None",
":",
"_",
",",
"extension",
"=",
"os... | Export graph as an image.
This requires that Graphviz is installed and that the ``dot``
executable is in your path.
The *filename* argument specifies the output filename.
The *format* argument lets you specify the output format. It may be
any format that ``dot`` understands, ... | [
"Export",
"graph",
"as",
"an",
"image",
"."
] | python | train | 35.384615 |
utiasSTARS/pykitti | pykitti/tracking.py | https://github.com/utiasSTARS/pykitti/blob/d3e1bb81676e831886726cc5ed79ce1f049aef2c/pykitti/tracking.py#L181-L212 | def to_array_list(df, length=None, by_id=True):
"""Converts a dataframe to a list of arrays, with one array for every unique index entry.
Index is assumed to be 0-based contiguous. If there is a missing index entry, an empty
numpy array is returned for it.
Elements in the arrays are sorted by their id.
... | [
"def",
"to_array_list",
"(",
"df",
",",
"length",
"=",
"None",
",",
"by_id",
"=",
"True",
")",
":",
"if",
"by_id",
":",
"assert",
"'id'",
"in",
"df",
".",
"columns",
"# if `id` is the only column, don't sort it (and don't remove it)",
"if",
"len",
"(",
"df",
"... | Converts a dataframe to a list of arrays, with one array for every unique index entry.
Index is assumed to be 0-based contiguous. If there is a missing index entry, an empty
numpy array is returned for it.
Elements in the arrays are sorted by their id.
:param df:
:param length:
:return: | [
"Converts",
"a",
"dataframe",
"to",
"a",
"list",
"of",
"arrays",
"with",
"one",
"array",
"for",
"every",
"unique",
"index",
"entry",
".",
"Index",
"is",
"assumed",
"to",
"be",
"0",
"-",
"based",
"contiguous",
".",
"If",
"there",
"is",
"a",
"missing",
"... | python | train | 29.15625 |
sibirrer/lenstronomy | lenstronomy/Util/util.py | https://github.com/sibirrer/lenstronomy/blob/4edb100a4f3f4fdc4fac9b0032d2b0283d0aa1d6/lenstronomy/Util/util.py#L244-L256 | def averaging(grid, numGrid, numPix):
"""
resize 2d pixel grid with numGrid to numPix and averages over the pixels
:param grid: higher resolution pixel grid
:param numGrid: number of pixels per axis in the high resolution input image
:param numPix: lower number of pixels per axis in the output image... | [
"def",
"averaging",
"(",
"grid",
",",
"numGrid",
",",
"numPix",
")",
":",
"Nbig",
"=",
"numGrid",
"Nsmall",
"=",
"numPix",
"small",
"=",
"grid",
".",
"reshape",
"(",
"[",
"int",
"(",
"Nsmall",
")",
",",
"int",
"(",
"Nbig",
"/",
"Nsmall",
")",
",",
... | resize 2d pixel grid with numGrid to numPix and averages over the pixels
:param grid: higher resolution pixel grid
:param numGrid: number of pixels per axis in the high resolution input image
:param numPix: lower number of pixels per axis in the output image (numGrid/numPix is integer number)
:return: | [
"resize",
"2d",
"pixel",
"grid",
"with",
"numGrid",
"to",
"numPix",
"and",
"averages",
"over",
"the",
"pixels",
":",
"param",
"grid",
":",
"higher",
"resolution",
"pixel",
"grid",
":",
"param",
"numGrid",
":",
"number",
"of",
"pixels",
"per",
"axis",
"in",... | python | train | 40.461538 |
idlesign/django-siteprefs | siteprefs/toolbox.py | https://github.com/idlesign/django-siteprefs/blob/3d6bf5e64220fe921468a36fce68e15d7947cf92/siteprefs/toolbox.py#L303-L332 | def pref(preference, field=None, verbose_name=None, help_text='', static=True, readonly=False):
"""Marks a preference.
:param preference: Preference variable.
:param Field field: Django model field to represent this preference.
:param str|unicode verbose_name: Field verbose name.
:param str|unic... | [
"def",
"pref",
"(",
"preference",
",",
"field",
"=",
"None",
",",
"verbose_name",
"=",
"None",
",",
"help_text",
"=",
"''",
",",
"static",
"=",
"True",
",",
"readonly",
"=",
"False",
")",
":",
"try",
":",
"bound",
"=",
"bind_proxy",
"(",
"(",
"prefer... | Marks a preference.
:param preference: Preference variable.
:param Field field: Django model field to represent this preference.
:param str|unicode verbose_name: Field verbose name.
:param str|unicode help_text: Field help text.
:param bool static: Leave this preference static (do not store in ... | [
"Marks",
"a",
"preference",
"."
] | python | valid | 26 |
abseil/abseil-py | absl/flags/_defines.py | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_defines.py#L185-L214 | def adopt_module_key_flags(module, flag_values=_flagvalues.FLAGS):
"""Declares that all flags key to a module are key to the current module.
Args:
module: module, the module object from which all key flags will be declared
as key flags to the current module.
flag_values: FlagValues, the FlagValues ... | [
"def",
"adopt_module_key_flags",
"(",
"module",
",",
"flag_values",
"=",
"_flagvalues",
".",
"FLAGS",
")",
":",
"if",
"not",
"isinstance",
"(",
"module",
",",
"types",
".",
"ModuleType",
")",
":",
"raise",
"_exceptions",
".",
"Error",
"(",
"'Expected a module ... | Declares that all flags key to a module are key to the current module.
Args:
module: module, the module object from which all key flags will be declared
as key flags to the current module.
flag_values: FlagValues, the FlagValues instance in which the flags will
be declared as key flags. This ... | [
"Declares",
"that",
"all",
"flags",
"key",
"to",
"a",
"module",
"are",
"key",
"to",
"the",
"current",
"module",
"."
] | python | train | 49.7 |
eaton-lab/toytree | toytree/html.py | https://github.com/eaton-lab/toytree/blob/0347ed2098acc5f707fadf52a0ecd411a6d1859c/toytree/html.py#L257-L363 | def get_edge_mark(ttree):
""" makes a simple Graph Mark object"""
## tree style
if ttree._kwargs["tree_style"] in ["c", "cladogram"]:
a=ttree.edges
vcoordinates=ttree.verts
else:
a=ttree._lines
vcoordinates=ttree._coords
## fixed args
a... | [
"def",
"get_edge_mark",
"(",
"ttree",
")",
":",
"## tree style",
"if",
"ttree",
".",
"_kwargs",
"[",
"\"tree_style\"",
"]",
"in",
"[",
"\"c\"",
",",
"\"cladogram\"",
"]",
":",
"a",
"=",
"ttree",
".",
"edges",
"vcoordinates",
"=",
"ttree",
".",
"verts",
"... | makes a simple Graph Mark object | [
"makes",
"a",
"simple",
"Graph",
"Mark",
"object"
] | python | train | 32.056075 |
wtsi-hgi/consul-lock | consullock/_logging.py | https://github.com/wtsi-hgi/consul-lock/blob/deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2/consullock/_logging.py#L6-L14 | def create_logger(name: str) -> Logger:
"""
Creates a logger with the given name.
:param name: name of the logger (gets prefixed with the package name)
:return: the created logger
"""
logger = logging.getLogger(f"{PACKAGE_NAME}.{name}")
logger.addHandler(StreamHandler())
return logger | [
"def",
"create_logger",
"(",
"name",
":",
"str",
")",
"->",
"Logger",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"f\"{PACKAGE_NAME}.{name}\"",
")",
"logger",
".",
"addHandler",
"(",
"StreamHandler",
"(",
")",
")",
"return",
"logger"
] | Creates a logger with the given name.
:param name: name of the logger (gets prefixed with the package name)
:return: the created logger | [
"Creates",
"a",
"logger",
"with",
"the",
"given",
"name",
".",
":",
"param",
"name",
":",
"name",
"of",
"the",
"logger",
"(",
"gets",
"prefixed",
"with",
"the",
"package",
"name",
")",
":",
"return",
":",
"the",
"created",
"logger"
] | python | train | 34.333333 |
fr33jc/bang | bang/config.py | https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/config.py#L308-L354 | def _prepare_servers(self):
"""
Prepare the variables that are exposed to the servers.
Most attributes in the server config are used directly. However, due
to variations in how cloud providers treat regions and availability
zones, this method allows either the ``availability_zo... | [
"def",
"_prepare_servers",
"(",
"self",
")",
":",
"stack",
"=",
"{",
"A",
".",
"NAME",
":",
"self",
"[",
"A",
".",
"NAME",
"]",
",",
"A",
".",
"VERSION",
":",
"self",
"[",
"A",
".",
"VERSION",
"]",
",",
"}",
"for",
"server",
"in",
"self",
".",
... | Prepare the variables that are exposed to the servers.
Most attributes in the server config are used directly. However, due
to variations in how cloud providers treat regions and availability
zones, this method allows either the ``availability_zone`` or the
``region_name`` to be used a... | [
"Prepare",
"the",
"variables",
"that",
"are",
"exposed",
"to",
"the",
"servers",
"."
] | python | train | 43.617021 |
Contraz/demosys-py | demosys/management/commands/createeffect.py | https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/management/commands/createeffect.py#L75-L78 | def root_path():
"""Get the absolute path to the root of the demosys package"""
module_dir = os.path.dirname(globals()['__file__'])
return os.path.dirname(os.path.dirname(module_dir)) | [
"def",
"root_path",
"(",
")",
":",
"module_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"globals",
"(",
")",
"[",
"'__file__'",
"]",
")",
"return",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"module_dir",
... | Get the absolute path to the root of the demosys package | [
"Get",
"the",
"absolute",
"path",
"to",
"the",
"root",
"of",
"the",
"demosys",
"package"
] | python | valid | 48 |
StackStorm/pybind | pybind/nos/v7_2_0/rbridge_id/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v7_2_0/rbridge_id/__init__.py#L709-L733 | def _set_system_max(self, v, load=False):
"""
Setter method for system_max, mapped from YANG variable /rbridge_id/system_max (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_system_max is considered as a private
method. Backends looking to populate this va... | [
"def",
"_set_system_max",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"bas... | Setter method for system_max, mapped from YANG variable /rbridge_id/system_max (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_system_max is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_syste... | [
"Setter",
"method",
"for",
"system_max",
"mapped",
"from",
"YANG",
"variable",
"/",
"rbridge_id",
"/",
"system_max",
"(",
"container",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
"in",
"the",
"source",
"YANG"... | python | train | 73.36 |
Dfenestrator/GooPyCharts | gpcharts.py | https://github.com/Dfenestrator/GooPyCharts/blob/57117f213111dfe0401b1dc9720cdba8a23c3028/gpcharts.py#L450-L483 | def bar(self,xdata,ydata,disp=True,**kwargs):
'''Displays a bar graph.
xdata: list of bar graph categories/bins. Can optionally include a header, see testGraph_barAndHist.py in https://github.com/Dfenestrator/GooPyCharts for an example.
ydata: list of values associated with categories i... | [
"def",
"bar",
"(",
"self",
",",
"xdata",
",",
"ydata",
",",
"disp",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"#combine data into proper format",
"data",
"=",
"combineData",
"(",
"xdata",
",",
"ydata",
",",
"self",
".",
"xlabel",
")",
"#Include oth... | Displays a bar graph.
xdata: list of bar graph categories/bins. Can optionally include a header, see testGraph_barAndHist.py in https://github.com/Dfenestrator/GooPyCharts for an example.
ydata: list of values associated with categories in xdata. If xdata includes a header, include a header lis... | [
"Displays",
"a",
"bar",
"graph",
".",
"xdata",
":",
"list",
"of",
"bar",
"graph",
"categories",
"/",
"bins",
".",
"Can",
"optionally",
"include",
"a",
"header",
"see",
"testGraph_barAndHist",
".",
"py",
"in",
"https",
":",
"//",
"github",
".",
"com",
"/"... | python | train | 46.205882 |
jut-io/jut-python-tools | jut/api/deployments.py | https://github.com/jut-io/jut-python-tools/blob/65574d23f51a7bbced9bb25010d02da5ca5d906f/jut/api/deployments.py#L173-L206 | def create_space(deployment_name,
space_name,
security_policy='public',
events_retention_days=0,
metrics_retention_days=0,
token_manager=None,
app_url=defaults.APP_URL):
"""
create a space within the deployment... | [
"def",
"create_space",
"(",
"deployment_name",
",",
"space_name",
",",
"security_policy",
"=",
"'public'",
",",
"events_retention_days",
"=",
"0",
",",
"metrics_retention_days",
"=",
"0",
",",
"token_manager",
"=",
"None",
",",
"app_url",
"=",
"defaults",
".",
"... | create a space within the deployment specified and with the various
rentention values set | [
"create",
"a",
"space",
"within",
"the",
"deployment",
"specified",
"and",
"with",
"the",
"various",
"rentention",
"values",
"set"
] | python | train | 36.852941 |
googlesamples/assistant-sdk-python | google-assistant-sdk/googlesamples/assistant/grpc/textinput.py | https://github.com/googlesamples/assistant-sdk-python/blob/84995692f35be8e085de8dfa7032039a13ae3fab/google-assistant-sdk/googlesamples/assistant/grpc/textinput.py#L80-L121 | def assist(self, text_query):
"""Send a text request to the Assistant and playback the response.
"""
def iter_assist_requests():
config = embedded_assistant_pb2.AssistConfig(
audio_out_config=embedded_assistant_pb2.AudioOutConfig(
encoding='LINEAR1... | [
"def",
"assist",
"(",
"self",
",",
"text_query",
")",
":",
"def",
"iter_assist_requests",
"(",
")",
":",
"config",
"=",
"embedded_assistant_pb2",
".",
"AssistConfig",
"(",
"audio_out_config",
"=",
"embedded_assistant_pb2",
".",
"AudioOutConfig",
"(",
"encoding",
"... | Send a text request to the Assistant and playback the response. | [
"Send",
"a",
"text",
"request",
"to",
"the",
"Assistant",
"and",
"playback",
"the",
"response",
"."
] | python | train | 47.428571 |
delfick/nose-of-yeti | noseOfYeti/tokeniser/tracker.py | https://github.com/delfick/nose-of-yeti/blob/0b545ff350cebd59b40b601333c13033ce40d6dc/noseOfYeti/tokeniser/tracker.py#L387-L400 | def add_tokens_for_group(self, with_pass=False):
"""Add the tokens for the group signature"""
kls = self.groups.super_kls
name = self.groups.kls_name
# Reset indentation to beginning and add signature
self.reset_indentation('')
self.result.extend(self.tokens.make_describ... | [
"def",
"add_tokens_for_group",
"(",
"self",
",",
"with_pass",
"=",
"False",
")",
":",
"kls",
"=",
"self",
".",
"groups",
".",
"super_kls",
"name",
"=",
"self",
".",
"groups",
".",
"kls_name",
"# Reset indentation to beginning and add signature",
"self",
".",
"re... | Add the tokens for the group signature | [
"Add",
"the",
"tokens",
"for",
"the",
"group",
"signature"
] | python | train | 32.428571 |
ibis-project/ibis | ibis/expr/datatypes.py | https://github.com/ibis-project/ibis/blob/1e39a5fd9ef088b45c155e8a5f541767ee8ef2e7/ibis/expr/datatypes.py#L1330-L1334 | def infer_list(values: List[GenericAny]) -> Array:
"""Infer the :class:`~ibis.expr.datatypes.Array` type of `values`."""
if not values:
return Array(null)
return Array(highest_precedence(map(infer, values))) | [
"def",
"infer_list",
"(",
"values",
":",
"List",
"[",
"GenericAny",
"]",
")",
"->",
"Array",
":",
"if",
"not",
"values",
":",
"return",
"Array",
"(",
"null",
")",
"return",
"Array",
"(",
"highest_precedence",
"(",
"map",
"(",
"infer",
",",
"values",
")... | Infer the :class:`~ibis.expr.datatypes.Array` type of `values`. | [
"Infer",
"the",
":",
"class",
":",
"~ibis",
".",
"expr",
".",
"datatypes",
".",
"Array",
"type",
"of",
"values",
"."
] | python | train | 44.6 |
ozgur/python-firebase | firebase/firebase.py | https://github.com/ozgur/python-firebase/blob/6b96b326f6d8f477503ca42fdfbd81bcbe1f9e0d/firebase/firebase.py#L134-L157 | def make_delete_request(url, params, headers, connection):
"""
Helper function that makes an HTTP DELETE request to the given firebase
endpoint. Timeout is 60 seconds.
`url`: The full URL of the firebase endpoint (DSN appended.)
`params`: Python dict that is appended to the URL like a querystring.
... | [
"def",
"make_delete_request",
"(",
"url",
",",
"params",
",",
"headers",
",",
"connection",
")",
":",
"timeout",
"=",
"getattr",
"(",
"connection",
",",
"'timeout'",
")",
"response",
"=",
"connection",
".",
"delete",
"(",
"url",
",",
"params",
"=",
"params... | Helper function that makes an HTTP DELETE request to the given firebase
endpoint. Timeout is 60 seconds.
`url`: The full URL of the firebase endpoint (DSN appended.)
`params`: Python dict that is appended to the URL like a querystring.
`headers`: Python dict. HTTP request headers.
`connection`: Pred... | [
"Helper",
"function",
"that",
"makes",
"an",
"HTTP",
"DELETE",
"request",
"to",
"the",
"given",
"firebase",
"endpoint",
".",
"Timeout",
"is",
"60",
"seconds",
".",
"url",
":",
"The",
"full",
"URL",
"of",
"the",
"firebase",
"endpoint",
"(",
"DSN",
"appended... | python | valid | 48.166667 |
ultrabug/py3status | py3status/parse_config.py | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/parse_config.py#L248-L272 | def tokenize(self, config):
"""
Break the config into a series of tokens
"""
tokens = []
reg_ex = re.compile(self.TOKENS[0], re.M | re.I)
for token in re.finditer(reg_ex, config):
value = token.group(0)
if token.group("operator"):
... | [
"def",
"tokenize",
"(",
"self",
",",
"config",
")",
":",
"tokens",
"=",
"[",
"]",
"reg_ex",
"=",
"re",
".",
"compile",
"(",
"self",
".",
"TOKENS",
"[",
"0",
"]",
",",
"re",
".",
"M",
"|",
"re",
".",
"I",
")",
"for",
"token",
"in",
"re",
".",
... | Break the config into a series of tokens | [
"Break",
"the",
"config",
"into",
"a",
"series",
"of",
"tokens"
] | python | train | 32.92 |
thespacedoctor/sloancone | build/lib/sloancone/check_coverage.py | https://github.com/thespacedoctor/sloancone/blob/106ea6533ad57f5f0ca82bf6db3053132bdb42e1/build/lib/sloancone/check_coverage.py#L167-L197 | def _query(
self,
sql,
url,
fmt,
log
):
"""* query*
"""
self.log.info('starting the ``_query`` method')
try:
response = requests.get(
url=url,
params={
"cmd": self._filtercomment(... | [
"def",
"_query",
"(",
"self",
",",
"sql",
",",
"url",
",",
"fmt",
",",
"log",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'starting the ``_query`` method'",
")",
"try",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
"=",
"url",
",",
... | * query* | [
"*",
"query",
"*"
] | python | train | 29.774194 |
ooici/elasticpy | elasticpy/query.py | https://github.com/ooici/elasticpy/blob/ec221800a80c39e80d8c31667c5b138da39219f2/elasticpy/query.py#L83-L98 | def match(cls, field, query, operator=None):
'''
A family of match queries that accept text/numerics/dates, analyzes it, and constructs a query out of it. For example:
{
"match" : {
"message" : "this is a test"
}
}
Note, message is the nam... | [
"def",
"match",
"(",
"cls",
",",
"field",
",",
"query",
",",
"operator",
"=",
"None",
")",
":",
"instance",
"=",
"cls",
"(",
"match",
"=",
"{",
"field",
":",
"{",
"'query'",
":",
"query",
"}",
"}",
")",
"if",
"operator",
"is",
"not",
"None",
":",... | A family of match queries that accept text/numerics/dates, analyzes it, and constructs a query out of it. For example:
{
"match" : {
"message" : "this is a test"
}
}
Note, message is the name of a field, you can subsitute the name of any field (including ... | [
"A",
"family",
"of",
"match",
"queries",
"that",
"accept",
"text",
"/",
"numerics",
"/",
"dates",
"analyzes",
"it",
"and",
"constructs",
"a",
"query",
"out",
"of",
"it",
".",
"For",
"example",
":"
] | python | train | 35.625 |
Cadasta/django-tutelary | tutelary/decorators.py | https://github.com/Cadasta/django-tutelary/blob/66bb05de7098777c0a383410c287bf48433cde87/tutelary/decorators.py#L11-L38 | def permission_required(*actions, obj=None, raise_exception=False):
"""Permission checking decorator -- works like the
``permission_required`` decorator in the default Django
authentication system, except that it takes a sequence of actions
to check, an object must be supplied, and the user must have
... | [
"def",
"permission_required",
"(",
"*",
"actions",
",",
"obj",
"=",
"None",
",",
"raise_exception",
"=",
"False",
")",
":",
"def",
"checker",
"(",
"user",
")",
":",
"ok",
"=",
"False",
"if",
"user",
".",
"is_authenticated",
"(",
")",
"and",
"check_perms"... | Permission checking decorator -- works like the
``permission_required`` decorator in the default Django
authentication system, except that it takes a sequence of actions
to check, an object must be supplied, and the user must have
permission to perform all of the actions on the given object for
the ... | [
"Permission",
"checking",
"decorator",
"--",
"works",
"like",
"the",
"permission_required",
"decorator",
"in",
"the",
"default",
"Django",
"authentication",
"system",
"except",
"that",
"it",
"takes",
"a",
"sequence",
"of",
"actions",
"to",
"check",
"an",
"object",... | python | train | 41.178571 |
marshallward/f90nml | f90nml/parser.py | https://github.com/marshallward/f90nml/blob/4932cabc5221afc844ee6a5b4a05ceb8bd4a2711/f90nml/parser.py#L865-L881 | def merge_lists(src, new):
"""Update a value list with a list of new or updated values."""
l_min, l_max = (src, new) if len(src) < len(new) else (new, src)
l_min.extend(None for i in range(len(l_min), len(l_max)))
for i, val in enumerate(new):
if isinstance(val, dict) and isinstance(src[i], di... | [
"def",
"merge_lists",
"(",
"src",
",",
"new",
")",
":",
"l_min",
",",
"l_max",
"=",
"(",
"src",
",",
"new",
")",
"if",
"len",
"(",
"src",
")",
"<",
"len",
"(",
"new",
")",
"else",
"(",
"new",
",",
"src",
")",
"l_min",
".",
"extend",
"(",
"Non... | Update a value list with a list of new or updated values. | [
"Update",
"a",
"value",
"list",
"with",
"a",
"list",
"of",
"new",
"or",
"updated",
"values",
"."
] | python | train | 34 |
google/transitfeed | transitfeed/util.py | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/util.py#L473-L482 | def DateStringToDateObject(date_string):
"""Return a date object for a string "YYYYMMDD"."""
# If this becomes a bottleneck date objects could be cached
if re.match('^\d{8}$', date_string) == None:
return None
try:
return datetime.date(int(date_string[0:4]), int(date_string[4:6]),
... | [
"def",
"DateStringToDateObject",
"(",
"date_string",
")",
":",
"# If this becomes a bottleneck date objects could be cached",
"if",
"re",
".",
"match",
"(",
"'^\\d{8}$'",
",",
"date_string",
")",
"==",
"None",
":",
"return",
"None",
"try",
":",
"return",
"datetime",
... | Return a date object for a string "YYYYMMDD". | [
"Return",
"a",
"date",
"object",
"for",
"a",
"string",
"YYYYMMDD",
"."
] | python | train | 37.3 |
Genida/archan | src/archan/config.py | https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/config.py#L156-L191 | def inflate_plugin_list(plugin_list, inflate_plugin):
"""
Inflate a list of strings/dictionaries to a list of plugin instances.
Args:
plugin_list (list): a list of str/dict.
inflate_plugin (method): the method to inflate the plugin.
Returns:
list: a ... | [
"def",
"inflate_plugin_list",
"(",
"plugin_list",
",",
"inflate_plugin",
")",
":",
"plugins",
"=",
"[",
"]",
"for",
"plugin_def",
"in",
"plugin_list",
":",
"if",
"isinstance",
"(",
"plugin_def",
",",
"str",
")",
":",
"try",
":",
"plugins",
".",
"append",
"... | Inflate a list of strings/dictionaries to a list of plugin instances.
Args:
plugin_list (list): a list of str/dict.
inflate_plugin (method): the method to inflate the plugin.
Returns:
list: a plugin instances list.
Raises:
ValueError: when a dic... | [
"Inflate",
"a",
"list",
"of",
"strings",
"/",
"dictionaries",
"to",
"a",
"list",
"of",
"plugin",
"instances",
"."
] | python | train | 42.611111 |
titusjan/argos | argos/collect/collector.py | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/collect/collector.py#L145-L156 | def blockChildrenSignals(self, block):
""" If block equals True, the signals of the combo boxes and spin boxes are blocked
Returns the old blocking state.
"""
logger.debug("Blocking collector signals")
for spinBox in self._spinBoxes:
spinBox.blockSignals(block)
... | [
"def",
"blockChildrenSignals",
"(",
"self",
",",
"block",
")",
":",
"logger",
".",
"debug",
"(",
"\"Blocking collector signals\"",
")",
"for",
"spinBox",
"in",
"self",
".",
"_spinBoxes",
":",
"spinBox",
".",
"blockSignals",
"(",
"block",
")",
"for",
"comboBox"... | If block equals True, the signals of the combo boxes and spin boxes are blocked
Returns the old blocking state. | [
"If",
"block",
"equals",
"True",
"the",
"signals",
"of",
"the",
"combo",
"boxes",
"and",
"spin",
"boxes",
"are",
"blocked",
"Returns",
"the",
"old",
"blocking",
"state",
"."
] | python | train | 40.5 |
materialsproject/pymatgen | pymatgen/analysis/interface_reactions.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/interface_reactions.py#L509-L564 | def get_chempot_correction(element, temp, pres):
"""
Get the normalized correction term Δμ for chemical potential of a gas
phase consisting of element at given temperature and pressure,
referenced to that in the standard state (T_std = 298.15 K,
T_std = 1 bar). The gas phase is l... | [
"def",
"get_chempot_correction",
"(",
"element",
",",
"temp",
",",
"pres",
")",
":",
"if",
"element",
"not",
"in",
"[",
"\"O\"",
",",
"\"N\"",
",",
"\"Cl\"",
",",
"\"F\"",
",",
"\"H\"",
"]",
":",
"return",
"0",
"std_temp",
"=",
"298.15",
"std_pres",
"=... | Get the normalized correction term Δμ for chemical potential of a gas
phase consisting of element at given temperature and pressure,
referenced to that in the standard state (T_std = 298.15 K,
T_std = 1 bar). The gas phase is limited to be one of O2, N2, Cl2,
F2, H2. Calculation formula ... | [
"Get",
"the",
"normalized",
"correction",
"term",
"Δμ",
"for",
"chemical",
"potential",
"of",
"a",
"gas",
"phase",
"consisting",
"of",
"element",
"at",
"given",
"temperature",
"and",
"pressure",
"referenced",
"to",
"that",
"in",
"the",
"standard",
"state",
"("... | python | train | 41.017857 |
gem/oq-engine | openquake/commonlib/readinput.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/readinput.py#L442-L471 | def get_gsim_lt(oqparam, trts=['*']):
"""
:param oqparam:
an :class:`openquake.commonlib.oqvalidation.OqParam` instance
:param trts:
a sequence of tectonic region types as strings; trts=['*']
means that there is no filtering
:returns:
a GsimLogicTree instance obtained by ... | [
"def",
"get_gsim_lt",
"(",
"oqparam",
",",
"trts",
"=",
"[",
"'*'",
"]",
")",
":",
"if",
"'gsim_logic_tree'",
"not",
"in",
"oqparam",
".",
"inputs",
":",
"return",
"logictree",
".",
"GsimLogicTree",
".",
"from_",
"(",
"oqparam",
".",
"gsim",
")",
"gsim_f... | :param oqparam:
an :class:`openquake.commonlib.oqvalidation.OqParam` instance
:param trts:
a sequence of tectonic region types as strings; trts=['*']
means that there is no filtering
:returns:
a GsimLogicTree instance obtained by filtering on the provided
tectonic region ... | [
":",
"param",
"oqparam",
":",
"an",
":",
"class",
":",
"openquake",
".",
"commonlib",
".",
"oqvalidation",
".",
"OqParam",
"instance",
":",
"param",
"trts",
":",
"a",
"sequence",
"of",
"tectonic",
"region",
"types",
"as",
"strings",
";",
"trts",
"=",
"["... | python | train | 45.2 |
marl/jams | jams/eval.py | https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/eval.py#L243-L276 | def hierarchy_flatten(annotation):
'''Flatten a multi_segment annotation into mir_eval style.
Parameters
----------
annotation : jams.Annotation
An annotation in the `multi_segment` namespace
Returns
-------
hier_intervalss : list
A list of lists of intervals, ordered by in... | [
"def",
"hierarchy_flatten",
"(",
"annotation",
")",
":",
"intervals",
",",
"values",
"=",
"annotation",
".",
"to_interval_values",
"(",
")",
"ordering",
"=",
"dict",
"(",
")",
"for",
"interval",
",",
"value",
"in",
"zip",
"(",
"intervals",
",",
"values",
"... | Flatten a multi_segment annotation into mir_eval style.
Parameters
----------
annotation : jams.Annotation
An annotation in the `multi_segment` namespace
Returns
-------
hier_intervalss : list
A list of lists of intervals, ordered by increasing specificity.
hier_labels : l... | [
"Flatten",
"a",
"multi_segment",
"annotation",
"into",
"mir_eval",
"style",
"."
] | python | valid | 29.676471 |
AustralianSynchrotron/lightflow | lightflow/models/mongo_proxy.py | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/mongo_proxy.py#L18-L25 | def get_methods(*objs):
""" Return the names of all callable attributes of an object"""
return set(
attr
for obj in objs
for attr in dir(obj)
if not attr.startswith('_') and callable(getattr(obj, attr))
) | [
"def",
"get_methods",
"(",
"*",
"objs",
")",
":",
"return",
"set",
"(",
"attr",
"for",
"obj",
"in",
"objs",
"for",
"attr",
"in",
"dir",
"(",
"obj",
")",
"if",
"not",
"attr",
".",
"startswith",
"(",
"'_'",
")",
"and",
"callable",
"(",
"getattr",
"("... | Return the names of all callable attributes of an object | [
"Return",
"the",
"names",
"of",
"all",
"callable",
"attributes",
"of",
"an",
"object"
] | python | train | 30.125 |
adamcharnock/python-hue-client | hueclient/monitor.py | https://github.com/adamcharnock/python-hue-client/blob/b934d8eab29ad301ff4e43462e37f0f2d4e682e5/hueclient/monitor.py#L112-L165 | def monitor(self, field, callback, poll_interval=None):
""" Monitor `field` for change
Will monitor ``field`` for change and execute ``callback`` when
change is detected.
Example usage::
def handle(resource, field, previous, current):
print "Change from {} ... | [
"def",
"monitor",
"(",
"self",
",",
"field",
",",
"callback",
",",
"poll_interval",
"=",
"None",
")",
":",
"poll_interval",
"=",
"poll_interval",
"or",
"self",
".",
"api",
".",
"poll_interval",
"monitor",
"=",
"self",
".",
"monitor_class",
"(",
"resource",
... | Monitor `field` for change
Will monitor ``field`` for change and execute ``callback`` when
change is detected.
Example usage::
def handle(resource, field, previous, current):
print "Change from {} to {}".format(previous, current)
switch = TapSwitch.obj... | [
"Monitor",
"field",
"for",
"change"
] | python | train | 34.796296 |
oseledets/ttpy | tt/eigb/eigb.py | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/eigb/eigb.py#L7-L65 | def eigb(A, y0, eps, rmax=150, nswp=20, max_full_size=1000, verb=1):
""" Approximate computation of minimal eigenvalues in tensor train format
This function uses alternating least-squares algorithm for the computation of several
minimal eigenvalues. If you want maximal eigenvalues, just send -A to the funct... | [
"def",
"eigb",
"(",
"A",
",",
"y0",
",",
"eps",
",",
"rmax",
"=",
"150",
",",
"nswp",
"=",
"20",
",",
"max_full_size",
"=",
"1000",
",",
"verb",
"=",
"1",
")",
":",
"ry",
"=",
"y0",
".",
"r",
".",
"copy",
"(",
")",
"lam",
"=",
"tt_eigb",
".... | Approximate computation of minimal eigenvalues in tensor train format
This function uses alternating least-squares algorithm for the computation of several
minimal eigenvalues. If you want maximal eigenvalues, just send -A to the function.
:Reference:
S. V. Dolgov, B. N. Khoromskij, I. V. Oselede... | [
"Approximate",
"computation",
"of",
"minimal",
"eigenvalues",
"in",
"tensor",
"train",
"format",
"This",
"function",
"uses",
"alternating",
"least",
"-",
"squares",
"algorithm",
"for",
"the",
"computation",
"of",
"several",
"minimal",
"eigenvalues",
".",
"If",
"yo... | python | train | 36.118644 |
facelessuser/backrefs | backrefs/_bre_parse.py | https://github.com/facelessuser/backrefs/blob/3b3d60f5d57b02044f880aa29c9c5add0e31a34f/backrefs/_bre_parse.py#L95-L133 | def process_quotes(self, text):
"""Process quotes."""
escaped = False
in_quotes = False
current = []
quoted = []
i = _util.StringIter(text)
iter(i)
for t in i:
if not escaped and t == "\\":
escaped = True
elif escap... | [
"def",
"process_quotes",
"(",
"self",
",",
"text",
")",
":",
"escaped",
"=",
"False",
"in_quotes",
"=",
"False",
"current",
"=",
"[",
"]",
"quoted",
"=",
"[",
"]",
"i",
"=",
"_util",
".",
"StringIter",
"(",
"text",
")",
"iter",
"(",
"i",
")",
"for"... | Process quotes. | [
"Process",
"quotes",
"."
] | python | train | 28.230769 |
bodylabs/lace | lace/serialization/obj/__init__.py | https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/serialization/obj/__init__.py#L105-L223 | def _dump(f, obj, flip_faces=False, ungroup=False, comments=None, split_normals=False, write_mtl=True): # pylint: disable=redefined-outer-name
'''
write_mtl: When True and mesh has a texture, includes a mtllib
reference in the .obj and writes a .mtl alongside.
'''
import os
import numpy as np... | [
"def",
"_dump",
"(",
"f",
",",
"obj",
",",
"flip_faces",
"=",
"False",
",",
"ungroup",
"=",
"False",
",",
"comments",
"=",
"None",
",",
"split_normals",
"=",
"False",
",",
"write_mtl",
"=",
"True",
")",
":",
"# pylint: disable=redefined-outer-name",
"import"... | write_mtl: When True and mesh has a texture, includes a mtllib
reference in the .obj and writes a .mtl alongside. | [
"write_mtl",
":",
"When",
"True",
"and",
"mesh",
"has",
"a",
"texture",
"includes",
"a",
"mtllib",
"reference",
"in",
"the",
".",
"obj",
"and",
"writes",
"a",
".",
"mtl",
"alongside",
"."
] | python | train | 41.991597 |
angr/angr | angr/state_plugins/gdb.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/state_plugins/gdb.py#L33-L49 | def set_stack(self, stack_dump, stack_top):
"""
Stack dump is a dump of the stack from gdb, i.e. the result of the following gdb command :
``dump binary memory [stack_dump] [begin_addr] [end_addr]``
We set the stack to the same addresses as the gdb session to avoid pointers corruption.... | [
"def",
"set_stack",
"(",
"self",
",",
"stack_dump",
",",
"stack_top",
")",
":",
"data",
"=",
"self",
".",
"_read_data",
"(",
"stack_dump",
")",
"self",
".",
"real_stack_top",
"=",
"stack_top",
"addr",
"=",
"stack_top",
"-",
"len",
"(",
"data",
")",
"# Ad... | Stack dump is a dump of the stack from gdb, i.e. the result of the following gdb command :
``dump binary memory [stack_dump] [begin_addr] [end_addr]``
We set the stack to the same addresses as the gdb session to avoid pointers corruption.
:param stack_dump: The dump file.
:param stac... | [
"Stack",
"dump",
"is",
"a",
"dump",
"of",
"the",
"stack",
"from",
"gdb",
"i",
".",
"e",
".",
"the",
"result",
"of",
"the",
"following",
"gdb",
"command",
":"
] | python | train | 46.235294 |
bunq/sdk_python | bunq/sdk/model/generated/object_.py | https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/model/generated/object_.py#L1712-L1726 | def is_all_field_none(self):
"""
:rtype: bool
"""
if self._id_ is not None:
return False
if self._country is not None:
return False
if self._expiry_time is not None:
return False
return True | [
"def",
"is_all_field_none",
"(",
"self",
")",
":",
"if",
"self",
".",
"_id_",
"is",
"not",
"None",
":",
"return",
"False",
"if",
"self",
".",
"_country",
"is",
"not",
"None",
":",
"return",
"False",
"if",
"self",
".",
"_expiry_time",
"is",
"not",
"None... | :rtype: bool | [
":",
"rtype",
":",
"bool"
] | python | train | 18.133333 |
StackStorm/pybind | pybind/nos/v6_0_2f/ntp/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v6_0_2f/ntp/__init__.py#L128-L149 | def _set_authentication_key(self, v, load=False):
"""
Setter method for authentication_key, mapped from YANG variable /ntp/authentication_key (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_authentication_key is considered as a private
method. Backends looking... | [
"def",
"_set_authentication_key",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
","... | Setter method for authentication_key, mapped from YANG variable /ntp/authentication_key (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_authentication_key is considered as a private
method. Backends looking to populate this variable should
do so via calling thisOb... | [
"Setter",
"method",
"for",
"authentication_key",
"mapped",
"from",
"YANG",
"variable",
"/",
"ntp",
"/",
"authentication_key",
"(",
"list",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
"in",
"the",
"source",
"Y... | python | train | 150.681818 |
gwastro/pycbc-glue | pycbc_glue/ligolw/param.py | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/param.py#L144-L150 | def from_pyvalue(name, value, **kwargs):
"""
Convenience wrapper for new_param() that constructs a Param element
from an instance of a Python builtin type. See new_param() for a
description of the valid keyword arguments.
"""
return new_param(name, ligolwtypes.FromPyType[type(value)], value, **kwargs) | [
"def",
"from_pyvalue",
"(",
"name",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"new_param",
"(",
"name",
",",
"ligolwtypes",
".",
"FromPyType",
"[",
"type",
"(",
"value",
")",
"]",
",",
"value",
",",
"*",
"*",
"kwargs",
")"
] | Convenience wrapper for new_param() that constructs a Param element
from an instance of a Python builtin type. See new_param() for a
description of the valid keyword arguments. | [
"Convenience",
"wrapper",
"for",
"new_param",
"()",
"that",
"constructs",
"a",
"Param",
"element",
"from",
"an",
"instance",
"of",
"a",
"Python",
"builtin",
"type",
".",
"See",
"new_param",
"()",
"for",
"a",
"description",
"of",
"the",
"valid",
"keyword",
"a... | python | train | 43.285714 |
tanghaibao/jcvi | jcvi/formats/gff.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/gff.py#L341-L373 | def make_attributes(s, gff3=True, keep_attr_order=True):
"""
In GFF3, the last column is typically:
ID=cds00002;Parent=mRNA00002;
In GFF2, the last column is typically:
Gene 22240.t000374; Note "Carbonic anhydrase"
"""
if gff3:
"""
hack: temporarily replace the '+' sign in t... | [
"def",
"make_attributes",
"(",
"s",
",",
"gff3",
"=",
"True",
",",
"keep_attr_order",
"=",
"True",
")",
":",
"if",
"gff3",
":",
"\"\"\"\n hack: temporarily replace the '+' sign in the attributes column\n with the string 'PlusSign' to prevent urlparse.parse_qsl() from\... | In GFF3, the last column is typically:
ID=cds00002;Parent=mRNA00002;
In GFF2, the last column is typically:
Gene 22240.t000374; Note "Carbonic anhydrase" | [
"In",
"GFF3",
"the",
"last",
"column",
"is",
"typically",
":",
"ID",
"=",
"cds00002",
";",
"Parent",
"=",
"mRNA00002",
";"
] | python | train | 33.969697 |
aleju/imgaug | imgaug/imgaug.py | https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/imgaug.py#L1989-L2003 | def postprocess(self, images, augmenter, parents):
"""
A function to be called after the augmentation of images was
performed.
Returns
-------
(N,H,W,C) ndarray or (N,H,W) ndarray or list of (H,W,C) ndarray or list of (H,W) ndarray
The input images, optionall... | [
"def",
"postprocess",
"(",
"self",
",",
"images",
",",
"augmenter",
",",
"parents",
")",
":",
"if",
"self",
".",
"postprocessor",
"is",
"None",
":",
"return",
"images",
"else",
":",
"return",
"self",
".",
"postprocessor",
"(",
"images",
",",
"augmenter",
... | A function to be called after the augmentation of images was
performed.
Returns
-------
(N,H,W,C) ndarray or (N,H,W) ndarray or list of (H,W,C) ndarray or list of (H,W) ndarray
The input images, optionally modified. | [
"A",
"function",
"to",
"be",
"called",
"after",
"the",
"augmentation",
"of",
"images",
"was",
"performed",
"."
] | python | valid | 31.666667 |
StackStorm/pybind | pybind/nos/v6_0_2f/interface/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v6_0_2f/interface/__init__.py#L271-L301 | def _set_hundredgigabitethernet(self, v, load=False):
"""
Setter method for hundredgigabitethernet, mapped from YANG variable /interface/hundredgigabitethernet (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_hundredgigabitethernet is considered as a private
me... | [
"def",
"_set_hundredgigabitethernet",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
... | Setter method for hundredgigabitethernet, mapped from YANG variable /interface/hundredgigabitethernet (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_hundredgigabitethernet is considered as a private
method. Backends looking to populate this variable should
do so ... | [
"Setter",
"method",
"for",
"hundredgigabitethernet",
"mapped",
"from",
"YANG",
"variable",
"/",
"interface",
"/",
"hundredgigabitethernet",
"(",
"list",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
"in",
"the",
... | python | train | 145.870968 |
cmap/cmapPy | cmapPy/pandasGEXpress/concat.py | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/concat.py#L370-L420 | def build_mismatched_common_meta_report(common_meta_df_shapes, sources, all_meta_df, all_meta_df_with_dups):
"""
Generate a report (dataframe) that indicates for the common metadata that does not match across the common metadata
which source file had which of the different mismatch values
Args:
... | [
"def",
"build_mismatched_common_meta_report",
"(",
"common_meta_df_shapes",
",",
"sources",
",",
"all_meta_df",
",",
"all_meta_df_with_dups",
")",
":",
"expanded_sources",
"=",
"[",
"]",
"for",
"(",
"i",
",",
"shape",
")",
"in",
"enumerate",
"(",
"common_meta_df_sha... | Generate a report (dataframe) that indicates for the common metadata that does not match across the common metadata
which source file had which of the different mismatch values
Args:
common_meta_df_shapes: list of tuples that are the shapes of the common meta dataframes
sources: list of th... | [
"Generate",
"a",
"report",
"(",
"dataframe",
")",
"that",
"indicates",
"for",
"the",
"common",
"metadata",
"that",
"does",
"not",
"match",
"across",
"the",
"common",
"metadata",
"which",
"source",
"file",
"had",
"which",
"of",
"the",
"different",
"mismatch",
... | python | train | 47.215686 |
bitprophet/ssh | ssh/transport.py | https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/transport.py#L865-L888 | def renegotiate_keys(self):
"""
Force this session to switch to new keys. Normally this is done
automatically after the session hits a certain number of packets or
bytes sent or received, but this method gives you the option of forcing
new keys whenever you want. Negotiating ne... | [
"def",
"renegotiate_keys",
"(",
"self",
")",
":",
"self",
".",
"completion_event",
"=",
"threading",
".",
"Event",
"(",
")",
"self",
".",
"_send_kex_init",
"(",
")",
"while",
"True",
":",
"self",
".",
"completion_event",
".",
"wait",
"(",
"0.1",
")",
"if... | Force this session to switch to new keys. Normally this is done
automatically after the session hits a certain number of packets or
bytes sent or received, but this method gives you the option of forcing
new keys whenever you want. Negotiating new keys causes a pause in
traffic both wa... | [
"Force",
"this",
"session",
"to",
"switch",
"to",
"new",
"keys",
".",
"Normally",
"this",
"is",
"done",
"automatically",
"after",
"the",
"session",
"hits",
"a",
"certain",
"number",
"of",
"packets",
"or",
"bytes",
"sent",
"or",
"received",
"but",
"this",
"... | python | train | 41.958333 |
Chilipp/psyplot | psyplot/data.py | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L1171-L1208 | def get_t(self, var, coords=None):
"""
Get the time coordinate of a variable
This method searches for the time coordinate in the :attr:`ds`. It
first checks whether there is one dimension that holds an ``'axis'``
attribute with 'T', otherwise it looks whether there is an interse... | [
"def",
"get_t",
"(",
"self",
",",
"var",
",",
"coords",
"=",
"None",
")",
":",
"coords",
"=",
"coords",
"or",
"self",
".",
"ds",
".",
"coords",
"coord",
"=",
"self",
".",
"get_variable_by_axis",
"(",
"var",
",",
"'t'",
",",
"coords",
")",
"if",
"co... | Get the time coordinate of a variable
This method searches for the time coordinate in the :attr:`ds`. It
first checks whether there is one dimension that holds an ``'axis'``
attribute with 'T', otherwise it looks whether there is an intersection
between the :attr:`t` attribute and the v... | [
"Get",
"the",
"time",
"coordinate",
"of",
"a",
"variable"
] | python | train | 40.578947 |
mitsei/dlkit | dlkit/records/osid/base_records.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/records/osid/base_records.py#L2961-L2970 | def get_display_names_metadata(self):
"""Gets the metadata for all display_names.
return: (osid.Metadata) - metadata for the display_names
*compliance: mandatory -- This method must be implemented.*
"""
metadata = dict(self._display_names_metadata)
metadata.update({'exi... | [
"def",
"get_display_names_metadata",
"(",
"self",
")",
":",
"metadata",
"=",
"dict",
"(",
"self",
".",
"_display_names_metadata",
")",
"metadata",
".",
"update",
"(",
"{",
"'existing_string_values'",
":",
"[",
"t",
"[",
"'text'",
"]",
"for",
"t",
"in",
"self... | Gets the metadata for all display_names.
return: (osid.Metadata) - metadata for the display_names
*compliance: mandatory -- This method must be implemented.* | [
"Gets",
"the",
"metadata",
"for",
"all",
"display_names",
"."
] | python | train | 44 |
gwastro/pycbc | pycbc/fft/func_api.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/fft/func_api.py#L64-L92 | def ifft(invec, outvec):
""" Inverse fourier transform from invec to outvec.
Perform an inverse fourier transform. The type of transform is determined
by the dtype of invec and outvec.
Parameters
----------
invec : TimeSeries or FrequencySeries
The input vector.
outvec : TimeSeries... | [
"def",
"ifft",
"(",
"invec",
",",
"outvec",
")",
":",
"prec",
",",
"itype",
",",
"otype",
"=",
"_check_fft_args",
"(",
"invec",
",",
"outvec",
")",
"_check_inv_args",
"(",
"invec",
",",
"itype",
",",
"outvec",
",",
"otype",
",",
"1",
",",
"None",
")"... | Inverse fourier transform from invec to outvec.
Perform an inverse fourier transform. The type of transform is determined
by the dtype of invec and outvec.
Parameters
----------
invec : TimeSeries or FrequencySeries
The input vector.
outvec : TimeSeries or FrequencySeries
The o... | [
"Inverse",
"fourier",
"transform",
"from",
"invec",
"to",
"outvec",
"."
] | python | train | 36.793103 |
mozilla/mozdownload | mozdownload/cli.py | https://github.com/mozilla/mozdownload/blob/97796a028455bb5200434562d23b66d5a5eb537b/mozdownload/cli.py#L21-L143 | def parse_arguments(argv):
"""Setup argument parser for command line arguments."""
parser = argparse.ArgumentParser(description=__doc__.format(__version__))
parser.add_argument('--application', '-a',
dest='application',
choices=scraper.APPLICATIONS,
... | [
"def",
"parse_arguments",
"(",
"argv",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"__doc__",
".",
"format",
"(",
"__version__",
")",
")",
"parser",
".",
"add_argument",
"(",
"'--application'",
",",
"'-a'",
",",
"dest... | Setup argument parser for command line arguments. | [
"Setup",
"argument",
"parser",
"for",
"command",
"line",
"arguments",
"."
] | python | train | 50.544715 |
raghakot/keras-vis | docs/md_autogen.py | https://github.com/raghakot/keras-vis/blob/668b0e11dab93f3487f23c17e07f40554a8939e9/docs/md_autogen.py#L71-L75 | def order_by_line_nos(objs, line_nos):
"""Orders the set of `objs` by `line_nos`
"""
ordering = sorted(range(len(line_nos)), key=line_nos.__getitem__)
return [objs[i] for i in ordering] | [
"def",
"order_by_line_nos",
"(",
"objs",
",",
"line_nos",
")",
":",
"ordering",
"=",
"sorted",
"(",
"range",
"(",
"len",
"(",
"line_nos",
")",
")",
",",
"key",
"=",
"line_nos",
".",
"__getitem__",
")",
"return",
"[",
"objs",
"[",
"i",
"]",
"for",
"i"... | Orders the set of `objs` by `line_nos` | [
"Orders",
"the",
"set",
"of",
"objs",
"by",
"line_nos"
] | python | train | 39.4 |
markokr/rarfile | rarfile.py | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L924-L932 | def has_header_encryption(self):
"""Returns True if headers are encrypted
"""
if self._hdrenc_main:
return True
if self._main:
if self._main.flags & RAR_MAIN_PASSWORD:
return True
return False | [
"def",
"has_header_encryption",
"(",
"self",
")",
":",
"if",
"self",
".",
"_hdrenc_main",
":",
"return",
"True",
"if",
"self",
".",
"_main",
":",
"if",
"self",
".",
"_main",
".",
"flags",
"&",
"RAR_MAIN_PASSWORD",
":",
"return",
"True",
"return",
"False"
] | Returns True if headers are encrypted | [
"Returns",
"True",
"if",
"headers",
"are",
"encrypted"
] | python | train | 29.333333 |
ciena/afkak | afkak/brokerclient.py | https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/brokerclient.py#L277-L292 | def handleResponse(self, response):
"""Handle the response string received by KafkaProtocol.
Ok, we've received the response from the broker. Find the requestId
in the message, lookup & fire the deferred with the response.
"""
requestId = KafkaCodec.get_response_correlation_id(r... | [
"def",
"handleResponse",
"(",
"self",
",",
"response",
")",
":",
"requestId",
"=",
"KafkaCodec",
".",
"get_response_correlation_id",
"(",
"response",
")",
"# Protect against responses coming back we didn't expect",
"tReq",
"=",
"self",
".",
"requests",
".",
"pop",
"("... | Handle the response string received by KafkaProtocol.
Ok, we've received the response from the broker. Find the requestId
in the message, lookup & fire the deferred with the response. | [
"Handle",
"the",
"response",
"string",
"received",
"by",
"KafkaProtocol",
"."
] | python | train | 49.5625 |
aio-libs/aiohttp | aiohttp/web_protocol.py | https://github.com/aio-libs/aiohttp/blob/9504fe2affaaff673fa4f3754c1c44221f8ba47d/aiohttp/web_protocol.py#L184-L213 | async def shutdown(self, timeout: Optional[float]=15.0) -> None:
"""Worker process is about to exit, we need cleanup everything and
stop accepting requests. It is especially important for keep-alive
connections."""
self._force_close = True
if self._keepalive_handle is not None:
... | [
"async",
"def",
"shutdown",
"(",
"self",
",",
"timeout",
":",
"Optional",
"[",
"float",
"]",
"=",
"15.0",
")",
"->",
"None",
":",
"self",
".",
"_force_close",
"=",
"True",
"if",
"self",
".",
"_keepalive_handle",
"is",
"not",
"None",
":",
"self",
".",
... | Worker process is about to exit, we need cleanup everything and
stop accepting requests. It is especially important for keep-alive
connections. | [
"Worker",
"process",
"is",
"about",
"to",
"exit",
"we",
"need",
"cleanup",
"everything",
"and",
"stop",
"accepting",
"requests",
".",
"It",
"is",
"especially",
"important",
"for",
"keep",
"-",
"alive",
"connections",
"."
] | python | train | 36.533333 |
materialsproject/pymatgen | pymatgen/core/structure.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/core/structure.py#L1778-L1830 | def from_str(cls, input_string, fmt, primitive=False, sort=False,
merge_tol=0.0):
"""
Reads a structure from a string.
Args:
input_string (str): String to parse.
fmt (str): A format specification.
primitive (bool): Whether to find a primitive... | [
"def",
"from_str",
"(",
"cls",
",",
"input_string",
",",
"fmt",
",",
"primitive",
"=",
"False",
",",
"sort",
"=",
"False",
",",
"merge_tol",
"=",
"0.0",
")",
":",
"from",
"pymatgen",
".",
"io",
".",
"cif",
"import",
"CifParser",
"from",
"pymatgen",
"."... | Reads a structure from a string.
Args:
input_string (str): String to parse.
fmt (str): A format specification.
primitive (bool): Whether to find a primitive cell. Defaults to
False.
sort (bool): Whether to sort the sites in accordance to the defau... | [
"Reads",
"a",
"structure",
"from",
"a",
"string",
"."
] | python | train | 38.735849 |
hyperledger-archives/indy-anoncreds | anoncreds/protocol/prover.py | https://github.com/hyperledger-archives/indy-anoncreds/blob/9d9cda3d505c312257d99a13d74d8f05dac3091a/anoncreds/protocol/prover.py#L102-L112 | async def presentProof(self, proofRequest: ProofRequest) -> FullProof:
"""
Presents a proof to the verifier.
:param proofRequest: description of a proof to be presented (revealed
attributes, predicates, timestamps for non-revocation)
:return: a proof (both primary and non-revoca... | [
"async",
"def",
"presentProof",
"(",
"self",
",",
"proofRequest",
":",
"ProofRequest",
")",
"->",
"FullProof",
":",
"claims",
",",
"requestedProof",
"=",
"await",
"self",
".",
"_findClaims",
"(",
"proofRequest",
")",
"proof",
"=",
"await",
"self",
".",
"_pre... | Presents a proof to the verifier.
:param proofRequest: description of a proof to be presented (revealed
attributes, predicates, timestamps for non-revocation)
:return: a proof (both primary and non-revocation) and revealed attributes (initial non-encoded values) | [
"Presents",
"a",
"proof",
"to",
"the",
"verifier",
"."
] | python | train | 50.545455 |
etal/biocma | biocma/cma.py | https://github.com/etal/biocma/blob/eac0c57eb83a9498e53ccdeb9cbc3fe21a5826a7/biocma/cma.py#L426-L495 | def collapse_to_consensus(seqrecords, strict=False, do_iron=True):
"""Opposite of realign_seqs.
Input sequences should all be the same length.
The first record must be the consensus.
"""
level = 0
name = seqrecords[0].id
# If this is a CMA alignment, extract additional info:
if hasattr... | [
"def",
"collapse_to_consensus",
"(",
"seqrecords",
",",
"strict",
"=",
"False",
",",
"do_iron",
"=",
"True",
")",
":",
"level",
"=",
"0",
"name",
"=",
"seqrecords",
"[",
"0",
"]",
".",
"id",
"# If this is a CMA alignment, extract additional info:",
"if",
"hasatt... | Opposite of realign_seqs.
Input sequences should all be the same length.
The first record must be the consensus. | [
"Opposite",
"of",
"realign_seqs",
"."
] | python | train | 37.457143 |
ishepard/pydriller | pydriller/git_repository.py | https://github.com/ishepard/pydriller/blob/71facb32afa085d5ddf0081beba34d00d57b8080/pydriller/git_repository.py#L122-L132 | def checkout(self, _hash: str) -> None:
"""
Checkout the repo at the speficied commit.
BE CAREFUL: this will change the state of the repo, hence it should
*not* be used with more than 1 thread.
:param _hash: commit hash to checkout
"""
with self.lock:
... | [
"def",
"checkout",
"(",
"self",
",",
"_hash",
":",
"str",
")",
"->",
"None",
":",
"with",
"self",
".",
"lock",
":",
"self",
".",
"_delete_tmp_branch",
"(",
")",
"self",
".",
"git",
".",
"checkout",
"(",
"'-f'",
",",
"_hash",
",",
"b",
"=",
"'_PD'",... | Checkout the repo at the speficied commit.
BE CAREFUL: this will change the state of the repo, hence it should
*not* be used with more than 1 thread.
:param _hash: commit hash to checkout | [
"Checkout",
"the",
"repo",
"at",
"the",
"speficied",
"commit",
".",
"BE",
"CAREFUL",
":",
"this",
"will",
"change",
"the",
"state",
"of",
"the",
"repo",
"hence",
"it",
"should",
"*",
"not",
"*",
"be",
"used",
"with",
"more",
"than",
"1",
"thread",
"."
... | python | train | 35.272727 |
ANTsX/ANTsPy | ants/utils/weingarten_image_curvature.py | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/weingarten_image_curvature.py#L11-L69 | def weingarten_image_curvature(image, sigma=1.0, opt='mean'):
"""
Uses the weingarten map to estimate image mean or gaussian curvature
ANTsR function: `weingartenImageCurvature`
Arguments
---------
image : ANTsImage
image from which curvature is calculated
sigma : scalar
... | [
"def",
"weingarten_image_curvature",
"(",
"image",
",",
"sigma",
"=",
"1.0",
",",
"opt",
"=",
"'mean'",
")",
":",
"if",
"image",
".",
"dimension",
"not",
"in",
"{",
"2",
",",
"3",
"}",
":",
"raise",
"ValueError",
"(",
"'image must be 2D or 3D'",
")",
"if... | Uses the weingarten map to estimate image mean or gaussian curvature
ANTsR function: `weingartenImageCurvature`
Arguments
---------
image : ANTsImage
image from which curvature is calculated
sigma : scalar
smoothing parameter
opt : string
mean by default, ... | [
"Uses",
"the",
"weingarten",
"map",
"to",
"estimate",
"image",
"mean",
"or",
"gaussian",
"curvature"
] | python | train | 28.355932 |
GoogleCloudPlatform/datastore-ndb-python | ndb/query.py | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/query.py#L1693-L1707 | def cursor_before(self):
"""Return the cursor before the current item.
You must pass a QueryOptions object with produce_cursors=True
for this to work.
If there is no cursor or no current item, raise BadArgumentError.
Before next() has returned there is no cursor. Once the loop is
exhausted, t... | [
"def",
"cursor_before",
"(",
"self",
")",
":",
"if",
"self",
".",
"_exhausted",
":",
"return",
"self",
".",
"cursor_after",
"(",
")",
"if",
"isinstance",
"(",
"self",
".",
"_cursor_before",
",",
"BaseException",
")",
":",
"raise",
"self",
".",
"_cursor_bef... | Return the cursor before the current item.
You must pass a QueryOptions object with produce_cursors=True
for this to work.
If there is no cursor or no current item, raise BadArgumentError.
Before next() has returned there is no cursor. Once the loop is
exhausted, this returns the cursor after the... | [
"Return",
"the",
"cursor",
"before",
"the",
"current",
"item",
"."
] | python | train | 35.466667 |
pgmpy/pgmpy | pgmpy/factors/discrete/JointProbabilityDistribution.py | https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/factors/discrete/JointProbabilityDistribution.py#L101-L133 | def marginal_distribution(self, variables, inplace=True):
"""
Returns the marginal distribution over variables.
Parameters
----------
variables: string, list, tuple, set, dict
Variable or list of variables over which marginal distribution needs
to... | [
"def",
"marginal_distribution",
"(",
"self",
",",
"variables",
",",
"inplace",
"=",
"True",
")",
":",
"return",
"self",
".",
"marginalize",
"(",
"list",
"(",
"set",
"(",
"list",
"(",
"self",
".",
"variables",
")",
")",
"-",
"set",
"(",
"variables",
"if... | Returns the marginal distribution over variables.
Parameters
----------
variables: string, list, tuple, set, dict
Variable or list of variables over which marginal distribution needs
to be calculated
inplace: Boolean (default True)
If Fals... | [
"Returns",
"the",
"marginal",
"distribution",
"over",
"variables",
"."
] | python | train | 40 |
majerteam/sqla_inspect | sqla_inspect/ods.py | https://github.com/majerteam/sqla_inspect/blob/67edb5541e6a56b0a657d3774d1e19c1110cd402/sqla_inspect/ods.py#L91-L101 | def _render_headers(self, sheet):
"""
Write the headers row
:param obj sheet: an odswriter Sheet object
"""
headers = getattr(self, 'headers', ())
labels = [header['label'] for header in headers]
extra_headers = getattr(self, "extra_headers", ())
labels.e... | [
"def",
"_render_headers",
"(",
"self",
",",
"sheet",
")",
":",
"headers",
"=",
"getattr",
"(",
"self",
",",
"'headers'",
",",
"(",
")",
")",
"labels",
"=",
"[",
"header",
"[",
"'label'",
"]",
"for",
"header",
"in",
"headers",
"]",
"extra_headers",
"=",... | Write the headers row
:param obj sheet: an odswriter Sheet object | [
"Write",
"the",
"headers",
"row"
] | python | train | 35.727273 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.