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 |
|---|---|---|---|---|---|---|---|---|---|
econ-ark/HARK | HARK/ConsumptionSaving/ConsAggShockModel.py | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsAggShockModel.py#L241-L255 | def getRfree(self):
'''
Returns an array of size self.AgentCount with self.RfreeNow in every entry.
Parameters
----------
None
Returns
-------
RfreeNow : np.array
Array of size self.AgentCount with risk free interest rate for each agent.
... | [
"def",
"getRfree",
"(",
"self",
")",
":",
"RfreeNow",
"=",
"self",
".",
"RfreeNow",
"*",
"np",
".",
"ones",
"(",
"self",
".",
"AgentCount",
")",
"return",
"RfreeNow"
] | Returns an array of size self.AgentCount with self.RfreeNow in every entry.
Parameters
----------
None
Returns
-------
RfreeNow : np.array
Array of size self.AgentCount with risk free interest rate for each agent. | [
"Returns",
"an",
"array",
"of",
"size",
"self",
".",
"AgentCount",
"with",
"self",
".",
"RfreeNow",
"in",
"every",
"entry",
"."
] | python | train | 26.4 |
mitsei/dlkit | dlkit/json_/resource/managers.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/resource/managers.py#L1329-L1344 | def get_bin_query_session(self, proxy):
"""Gets the bin query session.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.resource.BinQuerySession) - a ``BinQuerySession``
raise: NullArgument - ``proxy`` is ``null``
raise: OperationFailed - unable to complete request
... | [
"def",
"get_bin_query_session",
"(",
"self",
",",
"proxy",
")",
":",
"if",
"not",
"self",
".",
"supports_bin_query",
"(",
")",
":",
"raise",
"errors",
".",
"Unimplemented",
"(",
")",
"# pylint: disable=no-member",
"return",
"sessions",
".",
"BinQuerySession",
"(... | Gets the bin query session.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.resource.BinQuerySession) - a ``BinQuerySession``
raise: NullArgument - ``proxy`` is ``null``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``supports_bin_query()`... | [
"Gets",
"the",
"bin",
"query",
"session",
"."
] | python | train | 43.3125 |
serkanyersen/underscore.py | src/underscore.py | https://github.com/serkanyersen/underscore.py/blob/07c25c3f0f789536e4ad47aa315faccc0da9602f/src/underscore.py#L1592-L1614 | def makeStatic():
""" Provide static access to underscore class
"""
p = lambda value: inspect.ismethod(value) or inspect.isfunction(value)
for eachMethod in inspect.getmembers(underscore,
predicate=p):
m = eachMethod[0]
... | [
"def",
"makeStatic",
"(",
")",
":",
"p",
"=",
"lambda",
"value",
":",
"inspect",
".",
"ismethod",
"(",
"value",
")",
"or",
"inspect",
".",
"isfunction",
"(",
"value",
")",
"for",
"eachMethod",
"in",
"inspect",
".",
"getmembers",
"(",
"underscore",
",",
... | Provide static access to underscore class | [
"Provide",
"static",
"access",
"to",
"underscore",
"class"
] | python | train | 44.478261 |
spulec/moto | scripts/scaffold.py | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/scripts/scaffold.py#L279-L301 | def get_function_in_models(service, operation):
"""refers to definition of API in botocore, and autogenerates function
You can see example of elbv2 from link below.
https://github.com/boto/botocore/blob/develop/botocore/data/elbv2/2015-12-01/service-2.json
"""
client = boto3.client(service)
aw... | [
"def",
"get_function_in_models",
"(",
"service",
",",
"operation",
")",
":",
"client",
"=",
"boto3",
".",
"client",
"(",
"service",
")",
"aws_operation_name",
"=",
"to_upper_camel_case",
"(",
"operation",
")",
"op_model",
"=",
"client",
".",
"_service_model",
".... | refers to definition of API in botocore, and autogenerates function
You can see example of elbv2 from link below.
https://github.com/boto/botocore/blob/develop/botocore/data/elbv2/2015-12-01/service-2.json | [
"refers",
"to",
"definition",
"of",
"API",
"in",
"botocore",
"and",
"autogenerates",
"function",
"You",
"can",
"see",
"example",
"of",
"elbv2",
"from",
"link",
"below",
".",
"https",
":",
"//",
"github",
".",
"com",
"/",
"boto",
"/",
"botocore",
"/",
"bl... | python | train | 45.695652 |
molmod/molmod | molmod/pairff.py | https://github.com/molmod/molmod/blob/a7b5b4364ed514ad4c465856c05b5eda1cb561e0/molmod/pairff.py#L202-L219 | def yield_pair_energies(self, index1, index2):
"""Yields pairs ((s(r_ij), v(bar{r}_ij))"""
d_1 = 1/self.distances[index1, index2]
if self.charges is not None:
c1 = self.charges[index1]
c2 = self.charges[index2]
yield c1*c2*d_1, 1
if self.dipoles is not... | [
"def",
"yield_pair_energies",
"(",
"self",
",",
"index1",
",",
"index2",
")",
":",
"d_1",
"=",
"1",
"/",
"self",
".",
"distances",
"[",
"index1",
",",
"index2",
"]",
"if",
"self",
".",
"charges",
"is",
"not",
"None",
":",
"c1",
"=",
"self",
".",
"c... | Yields pairs ((s(r_ij), v(bar{r}_ij)) | [
"Yields",
"pairs",
"((",
"s",
"(",
"r_ij",
")",
"v",
"(",
"bar",
"{",
"r",
"}",
"_ij",
"))"
] | python | train | 40.166667 |
ThreatConnect-Inc/tcex | tcex/tcex_ti/mappings/tcex_ti_mappings.py | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/mappings/tcex_ti_mappings.py#L644-L678 | def attribute(self, attribute_id, action='GET', params=None):
"""
Gets the attribute from a Group/Indicator or Victim
Args:
action:
params:
attribute_id:
Returns: attribute json
"""
if params is None:
params = {}
... | [
"def",
"attribute",
"(",
"self",
",",
"attribute_id",
",",
"action",
"=",
"'GET'",
",",
"params",
"=",
"None",
")",
":",
"if",
"params",
"is",
"None",
":",
"params",
"=",
"{",
"}",
"if",
"not",
"self",
".",
"can_update",
"(",
")",
":",
"self",
".",... | Gets the attribute from a Group/Indicator or Victim
Args:
action:
params:
attribute_id:
Returns: attribute json | [
"Gets",
"the",
"attribute",
"from",
"a",
"Group",
"/",
"Indicator",
"or",
"Victim"
] | python | train | 27.457143 |
learningequality/ricecooker | ricecooker/managers/tree.py | https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/managers/tree.py#L148-L170 | def upload_tree(self):
""" upload_tree: sends processed channel data to server to create tree
Args: None
Returns: link to uploadedchannel
"""
from datetime import datetime
start_time = datetime.now()
root, channel_id = self.add_channel()
self.node_... | [
"def",
"upload_tree",
"(",
"self",
")",
":",
"from",
"datetime",
"import",
"datetime",
"start_time",
"=",
"datetime",
".",
"now",
"(",
")",
"root",
",",
"channel_id",
"=",
"self",
".",
"add_channel",
"(",
")",
"self",
".",
"node_count_dict",
"=",
"{",
"\... | upload_tree: sends processed channel data to server to create tree
Args: None
Returns: link to uploadedchannel | [
"upload_tree",
":",
"sends",
"processed",
"channel",
"data",
"to",
"server",
"to",
"create",
"tree",
"Args",
":",
"None",
"Returns",
":",
"link",
"to",
"uploadedchannel"
] | python | train | 41.869565 |
tdryer/hangups | hangups/auth.py | https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/auth.py#L220-L235 | def get_auth_stdin(refresh_token_filename, manual_login=False):
"""Simple wrapper for :func:`get_auth` that prompts the user using stdin.
Args:
refresh_token_filename (str): Path to file where refresh token will be
cached.
manual_login (bool): If true, prompt user to log in through ... | [
"def",
"get_auth_stdin",
"(",
"refresh_token_filename",
",",
"manual_login",
"=",
"False",
")",
":",
"refresh_token_cache",
"=",
"RefreshTokenCache",
"(",
"refresh_token_filename",
")",
"return",
"get_auth",
"(",
"CredentialsPrompt",
"(",
")",
",",
"refresh_token_cache"... | Simple wrapper for :func:`get_auth` that prompts the user using stdin.
Args:
refresh_token_filename (str): Path to file where refresh token will be
cached.
manual_login (bool): If true, prompt user to log in through a browser
and enter authorization code manually. Defaults t... | [
"Simple",
"wrapper",
"for",
":",
"func",
":",
"get_auth",
"that",
"prompts",
"the",
"user",
"using",
"stdin",
"."
] | python | valid | 39.875 |
explosion/thinc | thinc/api.py | https://github.com/explosion/thinc/blob/90129be5f0d6c665344245a7c37dbe1b8afceea2/thinc/api.py#L367-L407 | def foreach(layer, drop_factor=1.0):
"""Map a layer across list items"""
def foreach_fwd(docs, drop=0.0):
sents = []
lengths = []
for doc in docs:
doc_sents = [sent for sent in doc if len(sent)]
subset = [
s for s in doc_sents if numpy.random.rand... | [
"def",
"foreach",
"(",
"layer",
",",
"drop_factor",
"=",
"1.0",
")",
":",
"def",
"foreach_fwd",
"(",
"docs",
",",
"drop",
"=",
"0.0",
")",
":",
"sents",
"=",
"[",
"]",
"lengths",
"=",
"[",
"]",
"for",
"doc",
"in",
"docs",
":",
"doc_sents",
"=",
"... | Map a layer across list items | [
"Map",
"a",
"layer",
"across",
"list",
"items"
] | python | train | 31.170732 |
tensorflow/tensor2tensor | tensor2tensor/utils/decoding.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/decoding.py#L782-L795 | def save_video(video, save_path_template):
"""Save frames of the videos into files."""
try:
from PIL import Image # pylint: disable=g-import-not-at-top
except ImportError as e:
tf.logging.warning(
"Showing and saving an image requires PIL library to be "
"installed: %s", e)
raise NotI... | [
"def",
"save_video",
"(",
"video",
",",
"save_path_template",
")",
":",
"try",
":",
"from",
"PIL",
"import",
"Image",
"# pylint: disable=g-import-not-at-top",
"except",
"ImportError",
"as",
"e",
":",
"tf",
".",
"logging",
".",
"warning",
"(",
"\"Showing and saving... | Save frames of the videos into files. | [
"Save",
"frames",
"of",
"the",
"videos",
"into",
"files",
"."
] | python | train | 38.714286 |
ForensicArtifacts/artifacts | artifacts/writer.py | https://github.com/ForensicArtifacts/artifacts/blob/044a63bfb4448af33d085c69066c80f9505ae7ca/artifacts/writer.py#L72-L83 | def FormatArtifacts(self, artifacts):
"""Formats artifacts to desired output format.
Args:
artifacts (list[ArtifactDefinition]): artifact definitions.
Returns:
str: formatted string of artifact definition.
"""
artifact_definitions = [artifact.AsDict() for artifact in artifacts]
jso... | [
"def",
"FormatArtifacts",
"(",
"self",
",",
"artifacts",
")",
":",
"artifact_definitions",
"=",
"[",
"artifact",
".",
"AsDict",
"(",
")",
"for",
"artifact",
"in",
"artifacts",
"]",
"json_data",
"=",
"json",
".",
"dumps",
"(",
"artifact_definitions",
")",
"re... | Formats artifacts to desired output format.
Args:
artifacts (list[ArtifactDefinition]): artifact definitions.
Returns:
str: formatted string of artifact definition. | [
"Formats",
"artifacts",
"to",
"desired",
"output",
"format",
"."
] | python | train | 30.916667 |
boriel/zxbasic | zxbpp.py | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbpp.py#L118-L136 | def search_filename(fname, lineno, local_first):
""" Search a filename into the list of the include path.
If local_first is true, it will try first in the current directory of
the file being analyzed.
"""
fname = api.utils.sanitize_filename(fname)
i_path = [CURRENT_DIR] + INCLUDEPATH if local_fi... | [
"def",
"search_filename",
"(",
"fname",
",",
"lineno",
",",
"local_first",
")",
":",
"fname",
"=",
"api",
".",
"utils",
".",
"sanitize_filename",
"(",
"fname",
")",
"i_path",
"=",
"[",
"CURRENT_DIR",
"]",
"+",
"INCLUDEPATH",
"if",
"local_first",
"else",
"l... | Search a filename into the list of the include path.
If local_first is true, it will try first in the current directory of
the file being analyzed. | [
"Search",
"a",
"filename",
"into",
"the",
"list",
"of",
"the",
"include",
"path",
".",
"If",
"local_first",
"is",
"true",
"it",
"will",
"try",
"first",
"in",
"the",
"current",
"directory",
"of",
"the",
"file",
"being",
"analyzed",
"."
] | python | train | 39.578947 |
ungarj/mapchete | mapchete/io/raster.py | https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/io/raster.py#L290-L324 | def read_raster_no_crs(input_file, indexes=None, gdal_opts=None):
"""
Wrapper function around rasterio.open().read().
Parameters
----------
input_file : str
Path to file
indexes : int or list
Band index or list of band indexes to be read.
Returns
-------
MaskedArray... | [
"def",
"read_raster_no_crs",
"(",
"input_file",
",",
"indexes",
"=",
"None",
",",
"gdal_opts",
"=",
"None",
")",
":",
"with",
"warnings",
".",
"catch_warnings",
"(",
")",
":",
"warnings",
".",
"simplefilter",
"(",
"\"ignore\"",
")",
"try",
":",
"with",
"ra... | Wrapper function around rasterio.open().read().
Parameters
----------
input_file : str
Path to file
indexes : int or list
Band index or list of band indexes to be read.
Returns
-------
MaskedArray
Raises
------
FileNotFoundError if file cannot be found. | [
"Wrapper",
"function",
"around",
"rasterio",
".",
"open",
"()",
".",
"read",
"()",
"."
] | python | valid | 29.342857 |
econ-ark/HARK | HARK/core.py | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/core.py#L721-L801 | def solveAgent(agent,verbose):
'''
Solve the dynamic model for one agent type. This function iterates on "cycles"
of an agent's model either a given number of times or until solution convergence
if an infinite horizon model is used (with agent.cycles = 0).
Parameters
----------
agent : Age... | [
"def",
"solveAgent",
"(",
"agent",
",",
"verbose",
")",
":",
"# Record the flow of time when the Agent began the process, and make sure time is flowing backwards",
"original_time_flow",
"=",
"agent",
".",
"time_flow",
"agent",
".",
"timeRev",
"(",
")",
"# Check to see whether t... | Solve the dynamic model for one agent type. This function iterates on "cycles"
of an agent's model either a given number of times or until solution convergence
if an infinite horizon model is used (with agent.cycles = 0).
Parameters
----------
agent : AgentType
The microeconomic AgentType ... | [
"Solve",
"the",
"dynamic",
"model",
"for",
"one",
"agent",
"type",
".",
"This",
"function",
"iterates",
"on",
"cycles",
"of",
"an",
"agent",
"s",
"model",
"either",
"a",
"given",
"number",
"of",
"times",
"or",
"until",
"solution",
"convergence",
"if",
"an"... | python | train | 39.074074 |
echonest/pyechonest | examples/try_new_things.py | https://github.com/echonest/pyechonest/blob/d8c7af6c1da699b50b2f4b1bd3c0febe72e7f1ee/examples/try_new_things.py#L95-L109 | def write_xspf(f, tuples):
"""send me a list of (artist,title,mp3_url)"""
xml = XmlWriter(f, indentAmount=' ')
xml.prolog()
xml.start('playlist', { 'xmlns': 'http://xspf.org/ns/0/', 'version': '1' })
xml.start('trackList')
for tupe in tuples:
xml.start('track')
xml.elem('creator... | [
"def",
"write_xspf",
"(",
"f",
",",
"tuples",
")",
":",
"xml",
"=",
"XmlWriter",
"(",
"f",
",",
"indentAmount",
"=",
"' '",
")",
"xml",
".",
"prolog",
"(",
")",
"xml",
".",
"start",
"(",
"'playlist'",
",",
"{",
"'xmlns'",
":",
"'http://xspf.org/ns/0/'... | send me a list of (artist,title,mp3_url) | [
"send",
"me",
"a",
"list",
"of",
"(",
"artist",
"title",
"mp3_url",
")"
] | python | train | 29.866667 |
chemlab/chemlab | chemlab/graphics/renderers/sphere.py | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/renderers/sphere.py#L86-L93 | def update_positions(self, positions):
'''Update the sphere positions.
'''
sphs_verts = self.sphs_verts_radii.copy()
sphs_verts += positions.reshape(self.n_spheres, 1, 3)
self.tr.update_vertices(sphs_verts)
self.poslist = positions | [
"def",
"update_positions",
"(",
"self",
",",
"positions",
")",
":",
"sphs_verts",
"=",
"self",
".",
"sphs_verts_radii",
".",
"copy",
"(",
")",
"sphs_verts",
"+=",
"positions",
".",
"reshape",
"(",
"self",
".",
"n_spheres",
",",
"1",
",",
"3",
")",
"self"... | Update the sphere positions. | [
"Update",
"the",
"sphere",
"positions",
"."
] | python | train | 34.125 |
cfobel/si-prefix | si_prefix/__init__.py | https://github.com/cfobel/si-prefix/blob/274fdf47f65d87d0b7a2e3c80f267db63d042c59/si_prefix/__init__.py#L224-L263 | def si_parse(value):
'''
Parse a value expressed using SI prefix units to a floating point number.
Parameters
----------
value : str or unicode
Value expressed using SI prefix units (as returned by :func:`si_format`
function).
.. versionchanged:: 1.0
Use unicode string... | [
"def",
"si_parse",
"(",
"value",
")",
":",
"CRE_10E_NUMBER",
"=",
"re",
".",
"compile",
"(",
"r'^\\s*(?P<integer>[\\+\\-]?\\d+)?'",
"r'(?P<fraction>.\\d+)?\\s*([eE]\\s*'",
"r'(?P<expof10>[\\+\\-]?\\d+))?$'",
")",
"CRE_SI_NUMBER",
"=",
"re",
".",
"compile",
"(",
"r'^\\s*(?... | Parse a value expressed using SI prefix units to a floating point number.
Parameters
----------
value : str or unicode
Value expressed using SI prefix units (as returned by :func:`si_format`
function).
.. versionchanged:: 1.0
Use unicode string for SI unit to support micro (i.... | [
"Parse",
"a",
"value",
"expressed",
"using",
"SI",
"prefix",
"units",
"to",
"a",
"floating",
"point",
"number",
"."
] | python | train | 36.4 |
tomplus/kubernetes_asyncio | kubernetes_asyncio/client/api/storage_v1_api.py | https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/client/api/storage_v1_api.py#L1531-L1554 | def read_volume_attachment(self, name, **kwargs): # noqa: E501
"""read_volume_attachment # noqa: E501
read the specified VolumeAttachment # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>>... | [
"def",
"read_volume_attachment",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"rea... | read_volume_attachment # noqa: E501
read the specified VolumeAttachment # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_volume_attachment(name, async_req=True)
>>> resu... | [
"read_volume_attachment",
"#",
"noqa",
":",
"E501"
] | python | train | 51.958333 |
SHDShim/pytheos | pytheos/eqn_bm3.py | https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_bm3.py#L96-L107 | def bm3_k(p, v0, k0, k0p):
"""
calculate bulk modulus, wrapper for cal_k_bm3
cannot handle uncertainties
:param p: pressure
:param v0: volume at reference conditions
:param k0: bulk modulus at reference conditions
:param k0p: pressure derivative of bulk modulus at different conditions
:... | [
"def",
"bm3_k",
"(",
"p",
",",
"v0",
",",
"k0",
",",
"k0p",
")",
":",
"return",
"cal_k_bm3",
"(",
"p",
",",
"[",
"v0",
",",
"k0",
",",
"k0p",
"]",
")"
] | calculate bulk modulus, wrapper for cal_k_bm3
cannot handle uncertainties
:param p: pressure
:param v0: volume at reference conditions
:param k0: bulk modulus at reference conditions
:param k0p: pressure derivative of bulk modulus at different conditions
:return: bulk modulus at high pressure | [
"calculate",
"bulk",
"modulus",
"wrapper",
"for",
"cal_k_bm3",
"cannot",
"handle",
"uncertainties"
] | python | train | 32.75 |
pysathq/pysat | pysat/formula.py | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/formula.py#L1239-L1291 | def from_fp(self, file_pointer, comment_lead=['c']):
"""
Read a CNF+ formula from a file pointer. A file pointer should be
specified as an argument. The only default argument is
``comment_lead``, which can be used for parsing specific comment
lines.
:... | [
"def",
"from_fp",
"(",
"self",
",",
"file_pointer",
",",
"comment_lead",
"=",
"[",
"'c'",
"]",
")",
":",
"self",
".",
"nv",
"=",
"0",
"self",
".",
"clauses",
"=",
"[",
"]",
"self",
".",
"atmosts",
"=",
"[",
"]",
"self",
".",
"comments",
"=",
"[",... | Read a CNF+ formula from a file pointer. A file pointer should be
specified as an argument. The only default argument is
``comment_lead``, which can be used for parsing specific comment
lines.
:param file_pointer: a file pointer to read the formula from.
:par... | [
"Read",
"a",
"CNF",
"+",
"formula",
"from",
"a",
"file",
"pointer",
".",
"A",
"file",
"pointer",
"should",
"be",
"specified",
"as",
"an",
"argument",
".",
"The",
"only",
"default",
"argument",
"is",
"comment_lead",
"which",
"can",
"be",
"used",
"for",
"p... | python | train | 37.622642 |
nccgroup/opinel | opinel/services/cloudformation.py | https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/services/cloudformation.py#L154-L176 | def get_stackset_ready_accounts(credentials, account_ids, quiet=True):
"""
Verify which AWS accounts have been configured for CloudFormation stack set by attempting to assume the stack set execution role
:param credentials: AWS credentials to use when calling sts:assumerole
:param org_a... | [
"def",
"get_stackset_ready_accounts",
"(",
"credentials",
",",
"account_ids",
",",
"quiet",
"=",
"True",
")",
":",
"api_client",
"=",
"connect_service",
"(",
"'sts'",
",",
"credentials",
",",
"silent",
"=",
"True",
")",
"configured_account_ids",
"=",
"[",
"]",
... | Verify which AWS accounts have been configured for CloudFormation stack set by attempting to assume the stack set execution role
:param credentials: AWS credentials to use when calling sts:assumerole
:param org_account_ids: List of AWS accounts to check for Stackset configuration
... | [
"Verify",
"which",
"AWS",
"accounts",
"have",
"been",
"configured",
"for",
"CloudFormation",
"stack",
"set",
"by",
"attempting",
"to",
"assume",
"the",
"stack",
"set",
"execution",
"role"
] | python | train | 53.391304 |
rdo-management/python-rdomanager-oscplugin | rdomanager_oscplugin/utils.py | https://github.com/rdo-management/python-rdomanager-oscplugin/blob/165a166fb2e5a2598380779b35812b8b8478c4fb/rdomanager_oscplugin/utils.py#L162-L199 | def wait_for_provision_state(baremetal_client, node_uuid, provision_state,
loops=10, sleep=1):
"""Wait for a given Provisioning state in Ironic Discoverd
Updating the provisioning state is an async operation, we
need to wait for it to be completed.
:param baremetal_client:... | [
"def",
"wait_for_provision_state",
"(",
"baremetal_client",
",",
"node_uuid",
",",
"provision_state",
",",
"loops",
"=",
"10",
",",
"sleep",
"=",
"1",
")",
":",
"for",
"_",
"in",
"range",
"(",
"0",
",",
"loops",
")",
":",
"node",
"=",
"baremetal_client",
... | Wait for a given Provisioning state in Ironic Discoverd
Updating the provisioning state is an async operation, we
need to wait for it to be completed.
:param baremetal_client: Instance of Ironic client
:type baremetal_client: ironicclient.v1.client.Client
:param node_uuid: The Ironic node UUID
... | [
"Wait",
"for",
"a",
"given",
"Provisioning",
"state",
"in",
"Ironic",
"Discoverd"
] | python | train | 27.631579 |
PixelwarStudio/PyTree | Tree/draw.py | https://github.com/PixelwarStudio/PyTree/blob/f14b25ea145da6b00d836e34251d2a4c823766dc/Tree/draw.py#L42-L62 | def _get_color(self, age):
"""Get the fill color depending on age.
Args:
age (int): The age of the branch/es
Returns:
tuple: (r, g, b)
"""
if age == self.tree.age:
return self.leaf_color
color = self.stem_color
tree = self.tre... | [
"def",
"_get_color",
"(",
"self",
",",
"age",
")",
":",
"if",
"age",
"==",
"self",
".",
"tree",
".",
"age",
":",
"return",
"self",
".",
"leaf_color",
"color",
"=",
"self",
".",
"stem_color",
"tree",
"=",
"self",
".",
"tree",
"if",
"len",
"(",
"colo... | Get the fill color depending on age.
Args:
age (int): The age of the branch/es
Returns:
tuple: (r, g, b) | [
"Get",
"the",
"fill",
"color",
"depending",
"on",
"age",
"."
] | python | train | 25.809524 |
google/grumpy | third_party/pypy/datetime.py | https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pypy/datetime.py#L1354-L1368 | def replace(self, hour=None, minute=None, second=None, microsecond=None,
tzinfo=True):
"""Return a new time with new values for the specified fields."""
if hour is None:
hour = self.hour
if minute is None:
minute = self.minute
if second is None:
... | [
"def",
"replace",
"(",
"self",
",",
"hour",
"=",
"None",
",",
"minute",
"=",
"None",
",",
"second",
"=",
"None",
",",
"microsecond",
"=",
"None",
",",
"tzinfo",
"=",
"True",
")",
":",
"if",
"hour",
"is",
"None",
":",
"hour",
"=",
"self",
".",
"ho... | Return a new time with new values for the specified fields. | [
"Return",
"a",
"new",
"time",
"with",
"new",
"values",
"for",
"the",
"specified",
"fields",
"."
] | python | valid | 38.8 |
yyuu/botornado | boto/ec2/connection.py | https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/ec2/connection.py#L286-L313 | def deregister_image(self, image_id, delete_snapshot=False):
"""
Unregister an AMI.
:type image_id: string
:param image_id: the ID of the Image to unregister
:type delete_snapshot: bool
:param delete_snapshot: Set to True if we should delete the
... | [
"def",
"deregister_image",
"(",
"self",
",",
"image_id",
",",
"delete_snapshot",
"=",
"False",
")",
":",
"snapshot_id",
"=",
"None",
"if",
"delete_snapshot",
":",
"image",
"=",
"self",
".",
"get_image",
"(",
"image_id",
")",
"for",
"key",
"in",
"image",
".... | Unregister an AMI.
:type image_id: string
:param image_id: the ID of the Image to unregister
:type delete_snapshot: bool
:param delete_snapshot: Set to True if we should delete the
snapshot associated with an EBS volume
mo... | [
"Unregister",
"an",
"AMI",
"."
] | python | train | 35.642857 |
mseclab/PyJFuzz | pyjfuzz/core/pjf_process_monitor.py | https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/pyjfuzz/core/pjf_process_monitor.py#L101-L127 | def start_monitor(self, standalone=True):
"""
Run command in a loop and check exit status plus restart process when needed
"""
try:
self.start()
cmdline = shlex.split(self.config.process_to_monitor)
if standalone:
signal.signal(signal.S... | [
"def",
"start_monitor",
"(",
"self",
",",
"standalone",
"=",
"True",
")",
":",
"try",
":",
"self",
".",
"start",
"(",
")",
"cmdline",
"=",
"shlex",
".",
"split",
"(",
"self",
".",
"config",
".",
"process_to_monitor",
")",
"if",
"standalone",
":",
"sign... | Run command in a loop and check exit status plus restart process when needed | [
"Run",
"command",
"in",
"a",
"loop",
"and",
"check",
"exit",
"status",
"plus",
"restart",
"process",
"when",
"needed"
] | python | test | 50.407407 |
cmutel/constructive_geometries | constructive_geometries/cg.py | https://github.com/cmutel/constructive_geometries/blob/d38d7e8d5bf943a6499f3000004f1953af5970de/constructive_geometries/cg.py#L143-L182 | def construct_rest_of_worlds_mapping(self, excluded, fp=None):
"""Construct topo mapping file for ``excluded``.
``excluded`` must be a **dictionary** of {"rest-of-world label": ["names", "of", "excluded", "locations"]}``.
Topo mapping has the data format:
.. code-block:: python
... | [
"def",
"construct_rest_of_worlds_mapping",
"(",
"self",
",",
"excluded",
",",
"fp",
"=",
"None",
")",
":",
"metadata",
"=",
"{",
"'filename'",
":",
"'faces.gpkg'",
",",
"'field'",
":",
"'id'",
",",
"'sha256'",
":",
"sha256",
"(",
"self",
".",
"faces_fp",
"... | Construct topo mapping file for ``excluded``.
``excluded`` must be a **dictionary** of {"rest-of-world label": ["names", "of", "excluded", "locations"]}``.
Topo mapping has the data format:
.. code-block:: python
{
'data': [
['location label', ... | [
"Construct",
"topo",
"mapping",
"file",
"for",
"excluded",
"."
] | python | train | 34.95 |
morpframework/morpfw | morpfw/interfaces.py | https://github.com/morpframework/morpfw/blob/803fbf29714e6f29456482f1cfbdbd4922b020b0/morpfw/interfaces.py#L168-L172 | def aggregate(self, query: Optional[dict] = None,
group: Optional[dict] = None,
order_by: Union[None, list, tuple] = None) -> list:
"""return aggregation result based on specified rulez query and group"""
raise NotImplementedError | [
"def",
"aggregate",
"(",
"self",
",",
"query",
":",
"Optional",
"[",
"dict",
"]",
"=",
"None",
",",
"group",
":",
"Optional",
"[",
"dict",
"]",
"=",
"None",
",",
"order_by",
":",
"Union",
"[",
"None",
",",
"list",
",",
"tuple",
"]",
"=",
"None",
... | return aggregation result based on specified rulez query and group | [
"return",
"aggregation",
"result",
"based",
"on",
"specified",
"rulez",
"query",
"and",
"group"
] | python | train | 55.6 |
cloudendpoints/endpoints-python | endpoints/endpoints_dispatcher.py | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/endpoints_dispatcher.py#L149-L172 | def dispatch(self, request, start_response):
"""Handles dispatch to apiserver handlers.
This typically ends up calling start_response and returning the entire
body of the response.
Args:
request: An ApiRequest, the request from the user.
start_response: A function with semantics defined ... | [
"def",
"dispatch",
"(",
"self",
",",
"request",
",",
"start_response",
")",
":",
"# Check if this matches any of our special handlers.",
"dispatched_response",
"=",
"self",
".",
"dispatch_non_api_requests",
"(",
"request",
",",
"start_response",
")",
"if",
"dispatched_res... | Handles dispatch to apiserver handlers.
This typically ends up calling start_response and returning the entire
body of the response.
Args:
request: An ApiRequest, the request from the user.
start_response: A function with semantics defined in PEP-333.
Returns:
A string, the body o... | [
"Handles",
"dispatch",
"to",
"apiserver",
"handlers",
"."
] | python | train | 35.166667 |
deathbeds/importnb | src/importnb/remote.py | https://github.com/deathbeds/importnb/blob/ec870d1f8ab99fd5b363267f89787a3e442a779f/src/importnb/remote.py#L88-L96 | def Remote(path=None, loader=Notebook, **globals):
"""A remote notebook finder. Place a `*` into a url
to generalize the finder. It returns a context manager
"""
class Remote(RemoteMixin, loader):
...
return Remote(path=path, **globals) | [
"def",
"Remote",
"(",
"path",
"=",
"None",
",",
"loader",
"=",
"Notebook",
",",
"*",
"*",
"globals",
")",
":",
"class",
"Remote",
"(",
"RemoteMixin",
",",
"loader",
")",
":",
"...",
"return",
"Remote",
"(",
"path",
"=",
"path",
",",
"*",
"*",
"glob... | A remote notebook finder. Place a `*` into a url
to generalize the finder. It returns a context manager | [
"A",
"remote",
"notebook",
"finder",
".",
"Place",
"a",
"*",
"into",
"a",
"url",
"to",
"generalize",
"the",
"finder",
".",
"It",
"returns",
"a",
"context",
"manager"
] | python | train | 28.888889 |
UCL-INGI/INGInious | inginious/common/task_factory.py | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/task_factory.py#L95-L120 | def update_task_descriptor_content(self, courseid, taskid, content, force_extension=None):
"""
Update the task descriptor with the dict in content
:param courseid: the course id of the course
:param taskid: the task id of the task
:param content: the content to put in the task fi... | [
"def",
"update_task_descriptor_content",
"(",
"self",
",",
"courseid",
",",
"taskid",
",",
"content",
",",
"force_extension",
"=",
"None",
")",
":",
"if",
"not",
"id_checker",
"(",
"courseid",
")",
":",
"raise",
"InvalidNameException",
"(",
"\"Course with invalid ... | Update the task descriptor with the dict in content
:param courseid: the course id of the course
:param taskid: the task id of the task
:param content: the content to put in the task file
:param force_extension: If None, save it the same format. Else, save with the given extension
... | [
"Update",
"the",
"task",
"descriptor",
"with",
"the",
"dict",
"in",
"content",
":",
"param",
"courseid",
":",
"the",
"course",
"id",
"of",
"the",
"course",
":",
"param",
"taskid",
":",
"the",
"task",
"id",
"of",
"the",
"task",
":",
"param",
"content",
... | python | train | 50.384615 |
saltstack/salt | salt/modules/ssh.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ssh.py#L52-L80 | def _refine_enc(enc):
'''
Return the properly formatted ssh value for the authorized encryption key
type. ecdsa defaults to 256 bits, must give full ecdsa enc schema string
if using higher enc. If the type is not found, raise CommandExecutionError.
'''
rsa = ['r', 'rsa', 'ssh-rsa']
dss = ['... | [
"def",
"_refine_enc",
"(",
"enc",
")",
":",
"rsa",
"=",
"[",
"'r'",
",",
"'rsa'",
",",
"'ssh-rsa'",
"]",
"dss",
"=",
"[",
"'d'",
",",
"'dsa'",
",",
"'dss'",
",",
"'ssh-dss'",
"]",
"ecdsa",
"=",
"[",
"'e'",
",",
"'ecdsa'",
",",
"'ecdsa-sha2-nistp521'"... | Return the properly formatted ssh value for the authorized encryption key
type. ecdsa defaults to 256 bits, must give full ecdsa enc schema string
if using higher enc. If the type is not found, raise CommandExecutionError. | [
"Return",
"the",
"properly",
"formatted",
"ssh",
"value",
"for",
"the",
"authorized",
"encryption",
"key",
"type",
".",
"ecdsa",
"defaults",
"to",
"256",
"bits",
"must",
"give",
"full",
"ecdsa",
"enc",
"schema",
"string",
"if",
"using",
"higher",
"enc",
".",... | python | train | 33.068966 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/funcs.py | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/funcs.py#L199-L216 | def rank(keys, axis=semantics.axis_default):
"""where each item is in the pecking order.
Parameters
----------
keys : indexable object
Returns
-------
ndarray, [keys.size], int
unique integers, ranking the sorting order
Notes
-----
we should have that index.sorted[inde... | [
"def",
"rank",
"(",
"keys",
",",
"axis",
"=",
"semantics",
".",
"axis_default",
")",
":",
"index",
"=",
"as_index",
"(",
"keys",
",",
"axis",
")",
"return",
"index",
".",
"rank"
] | where each item is in the pecking order.
Parameters
----------
keys : indexable object
Returns
-------
ndarray, [keys.size], int
unique integers, ranking the sorting order
Notes
-----
we should have that index.sorted[index.rank] == keys | [
"where",
"each",
"item",
"is",
"in",
"the",
"pecking",
"order",
"."
] | python | train | 21.166667 |
sorgerlab/indra | indra/sources/trips/analyze_ekbs.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/trips/analyze_ekbs.py#L20-L47 | def get_args(node):
"""Return the arguments of a node in the event graph."""
arg_roles = {}
args = node.findall('arg') + \
[node.find('arg1'), node.find('arg2'), node.find('arg3')]
for arg in args:
if arg is not None:
id = arg.attrib.get('id')
if id is not None:
... | [
"def",
"get_args",
"(",
"node",
")",
":",
"arg_roles",
"=",
"{",
"}",
"args",
"=",
"node",
".",
"findall",
"(",
"'arg'",
")",
"+",
"[",
"node",
".",
"find",
"(",
"'arg1'",
")",
",",
"node",
".",
"find",
"(",
"'arg2'",
")",
",",
"node",
".",
"fi... | Return the arguments of a node in the event graph. | [
"Return",
"the",
"arguments",
"of",
"a",
"node",
"in",
"the",
"event",
"graph",
"."
] | python | train | 37.285714 |
apragacz/django-rest-registration | rest_registration/api/views/register_email.py | https://github.com/apragacz/django-rest-registration/blob/7373571264dd567c2a73a97ff4c45b64f113605b/rest_registration/api/views/register_email.py#L33-L58 | def register_email(request):
'''
Register new email.
'''
user = request.user
serializer = RegisterEmailSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
email = serializer.validated_data['email']
template_config = (
registration_settings.REGISTER_EMAIL_VE... | [
"def",
"register_email",
"(",
"request",
")",
":",
"user",
"=",
"request",
".",
"user",
"serializer",
"=",
"RegisterEmailSerializer",
"(",
"data",
"=",
"request",
".",
"data",
")",
"serializer",
".",
"is_valid",
"(",
"raise_exception",
"=",
"True",
")",
"ema... | Register new email. | [
"Register",
"new",
"email",
"."
] | python | train | 30.730769 |
rodricios/eatiht | eatiht/v2.py | https://github.com/rodricios/eatiht/blob/7341c46327cfe7e0c9f226ef5e9808975c4d43da/eatiht/v2.py#L113-L158 | def get_html_tree(filename_url_or_filelike):
"""From some file path, input stream, or URL, construct and return
an HTML tree.
"""
try:
handler = (
HTTPSHandler
if filename_url_or_filelike.lower().startswith('https')
else HTTPHandler
)
... | [
"def",
"get_html_tree",
"(",
"filename_url_or_filelike",
")",
":",
"try",
":",
"handler",
"=",
"(",
"HTTPSHandler",
"if",
"filename_url_or_filelike",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"'https'",
")",
"else",
"HTTPHandler",
")",
"cj",
"=",
"Cookie... | From some file path, input stream, or URL, construct and return
an HTML tree. | [
"From",
"some",
"file",
"path",
"input",
"stream",
"or",
"URL",
"construct",
"and",
"return",
"an",
"HTML",
"tree",
"."
] | python | train | 32.847826 |
aio-libs/aiohttp | aiohttp/streams.py | https://github.com/aio-libs/aiohttp/blob/9504fe2affaaff673fa4f3754c1c44221f8ba47d/aiohttp/streams.py#L472-L484 | def _read_nowait(self, n: int) -> bytes:
""" Read not more than n bytes, or whole buffer is n == -1 """
chunks = []
while self._buffer:
chunk = self._read_nowait_chunk(n)
chunks.append(chunk)
if n != -1:
n -= len(chunk)
if n ==... | [
"def",
"_read_nowait",
"(",
"self",
",",
"n",
":",
"int",
")",
"->",
"bytes",
":",
"chunks",
"=",
"[",
"]",
"while",
"self",
".",
"_buffer",
":",
"chunk",
"=",
"self",
".",
"_read_nowait_chunk",
"(",
"n",
")",
"chunks",
".",
"append",
"(",
"chunk",
... | Read not more than n bytes, or whole buffer is n == -1 | [
"Read",
"not",
"more",
"than",
"n",
"bytes",
"or",
"whole",
"buffer",
"is",
"n",
"==",
"-",
"1"
] | python | train | 29.923077 |
theislab/scanpy | scanpy/tools/_sim.py | https://github.com/theislab/scanpy/blob/9e4e5ee02e04cf618872d9b098e24f0542e8b227/scanpy/tools/_sim.py#L675-L683 | def coupl_model8(self):
""" Variant of toggle switch.
"""
self.Coupl = 0.5*self.Adj_signed
# reduce the value of the coupling of the repressing genes
# otherwise completely unstable solutions are obtained
for x in np.nditer(self.Coupl,op_flags=['readwrite']):
... | [
"def",
"coupl_model8",
"(",
"self",
")",
":",
"self",
".",
"Coupl",
"=",
"0.5",
"*",
"self",
".",
"Adj_signed",
"# reduce the value of the coupling of the repressing genes",
"# otherwise completely unstable solutions are obtained",
"for",
"x",
"in",
"np",
".",
"nditer",
... | Variant of toggle switch. | [
"Variant",
"of",
"toggle",
"switch",
"."
] | python | train | 39.444444 |
rene-aguirre/pywinusb | examples/mute_led.py | https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/examples/mute_led.py#L13-L49 | def set_mute(mute_value):
"Browse for mute usages and set value"
all_mutes = ( \
(0x8, 0x9), # LED page
(0x1, 0xA7), # desktop page
(0xb, 0x2f),
)
all_target_usages = [hid.get_full_usage_id(u[0], u[1]) for u in all_mutes]
# usually you'll find and open the target... | [
"def",
"set_mute",
"(",
"mute_value",
")",
":",
"all_mutes",
"=",
"(",
"(",
"0x8",
",",
"0x9",
")",
",",
"# LED page",
"(",
"0x1",
",",
"0xA7",
")",
",",
"# desktop page",
"(",
"0xb",
",",
"0x2f",
")",
",",
")",
"all_target_usages",
"=",
"[",
"hid",
... | Browse for mute usages and set value | [
"Browse",
"for",
"mute",
"usages",
"and",
"set",
"value"
] | python | train | 35.351351 |
cloudtools/stacker | stacker/actions/base.py | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/actions/base.py#L100-L113 | def stack_template_key_name(blueprint):
"""Given a blueprint, produce an appropriate key name.
Args:
blueprint (:class:`stacker.blueprints.base.Blueprint`): The blueprint
object to create the key from.
Returns:
string: Key name resulting from blueprint.
"""
name = bluep... | [
"def",
"stack_template_key_name",
"(",
"blueprint",
")",
":",
"name",
"=",
"blueprint",
".",
"name",
"return",
"\"stack_templates/%s/%s-%s.json\"",
"%",
"(",
"blueprint",
".",
"context",
".",
"get_fqn",
"(",
"name",
")",
",",
"name",
",",
"blueprint",
".",
"ve... | Given a blueprint, produce an appropriate key name.
Args:
blueprint (:class:`stacker.blueprints.base.Blueprint`): The blueprint
object to create the key from.
Returns:
string: Key name resulting from blueprint. | [
"Given",
"a",
"blueprint",
"produce",
"an",
"appropriate",
"key",
"name",
"."
] | python | train | 36.571429 |
pybel/pybel | src/pybel/struct/graph.py | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/graph.py#L413-L416 | def _add_two_way_unqualified_edge(self, u: BaseEntity, v: BaseEntity, relation: str) -> str:
"""Add an unqualified edge both ways."""
self.add_unqualified_edge(v, u, relation)
return self.add_unqualified_edge(u, v, relation) | [
"def",
"_add_two_way_unqualified_edge",
"(",
"self",
",",
"u",
":",
"BaseEntity",
",",
"v",
":",
"BaseEntity",
",",
"relation",
":",
"str",
")",
"->",
"str",
":",
"self",
".",
"add_unqualified_edge",
"(",
"v",
",",
"u",
",",
"relation",
")",
"return",
"s... | Add an unqualified edge both ways. | [
"Add",
"an",
"unqualified",
"edge",
"both",
"ways",
"."
] | python | train | 61.25 |
prthkms/alex | alex/handler.py | https://github.com/prthkms/alex/blob/79d3167c877e94cc07db0aab55a35857fac67ef7/alex/handler.py#L43-L50 | def make_executable(query):
"""make_executable(query) -- give executable permissions to a given file
"""
filename = support.get_file_name(query)
if(os.path.isfile(filename)):
os.system('chmod +x '+filename)
else:
print 'file not found' | [
"def",
"make_executable",
"(",
"query",
")",
":",
"filename",
"=",
"support",
".",
"get_file_name",
"(",
"query",
")",
"if",
"(",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
")",
":",
"os",
".",
"system",
"(",
"'chmod +x '",
"+",
"filename"... | make_executable(query) -- give executable permissions to a given file | [
"make_executable",
"(",
"query",
")",
"--",
"give",
"executable",
"permissions",
"to",
"a",
"given",
"file"
] | python | train | 29.625 |
saltstack/salt | salt/modules/postgres.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L291-L316 | def version(user=None, host=None, port=None, maintenance_db=None,
password=None, runas=None):
'''
Return the version of a Postgres server.
CLI Example:
.. code-block:: bash
salt '*' postgres.version
'''
query = 'SELECT setting FROM pg_catalog.pg_settings ' \
'W... | [
"def",
"version",
"(",
"user",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"maintenance_db",
"=",
"None",
",",
"password",
"=",
"None",
",",
"runas",
"=",
"None",
")",
":",
"query",
"=",
"'SELECT setting FROM pg_catalog.pg_setting... | Return the version of a Postgres server.
CLI Example:
.. code-block:: bash
salt '*' postgres.version | [
"Return",
"the",
"version",
"of",
"a",
"Postgres",
"server",
"."
] | python | train | 30.384615 |
albahnsen/CostSensitiveClassification | costcla/models/cost_tree.py | https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/cost_tree.py#L654-L676 | def pruning(self, X, y, cost_mat):
""" Function that prune the decision tree.
Parameters
----------
X : array-like of shape = [n_samples, n_features]
The input samples.
y_true : array indicator matrix
Ground truth (correct) labels.
cost_mat : a... | [
"def",
"pruning",
"(",
"self",
",",
"X",
",",
"y",
",",
"cost_mat",
")",
":",
"self",
".",
"tree_",
".",
"tree_pruned",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"tree_",
".",
"tree",
")",
"if",
"self",
".",
"tree_",
".",
"n_nodes",
">",
"0... | Function that prune the decision tree.
Parameters
----------
X : array-like of shape = [n_samples, n_features]
The input samples.
y_true : array indicator matrix
Ground truth (correct) labels.
cost_mat : array-like of shape = [n_samples, 4]
... | [
"Function",
"that",
"prune",
"the",
"decision",
"tree",
"."
] | python | train | 35.478261 |
reingart/pyafipws | wsremcarne.py | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wsremcarne.py#L143-L148 | def __analizar_evento(self, ret):
"Comprueba y extrae el wvento informativo si existen en la respuesta XML"
evt = ret.get('evento')
if evt:
self.Eventos = [evt]
self.Evento = "%(codigo)s: %(descripcion)s" % evt | [
"def",
"__analizar_evento",
"(",
"self",
",",
"ret",
")",
":",
"evt",
"=",
"ret",
".",
"get",
"(",
"'evento'",
")",
"if",
"evt",
":",
"self",
".",
"Eventos",
"=",
"[",
"evt",
"]",
"self",
".",
"Evento",
"=",
"\"%(codigo)s: %(descripcion)s\"",
"%",
"evt... | Comprueba y extrae el wvento informativo si existen en la respuesta XML | [
"Comprueba",
"y",
"extrae",
"el",
"wvento",
"informativo",
"si",
"existen",
"en",
"la",
"respuesta",
"XML"
] | python | train | 42.166667 |
draios/python-sdc-client | sdcclient/_monitor.py | https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_monitor.py#L811-L866 | def convert_scope_string_to_expression(scope):
'''**Description**
Internal function to convert a filter string to a filter object to be used with dashboards.
'''
#
# NOTE: The supported grammar is not perfectly aligned with the grammar supported by the Sysdig backend.
... | [
"def",
"convert_scope_string_to_expression",
"(",
"scope",
")",
":",
"#",
"# NOTE: The supported grammar is not perfectly aligned with the grammar supported by the Sysdig backend.",
"# Proper grammar implementation will happen soon.",
"# For practical purposes, the parsing will have equivalent res... | **Description**
Internal function to convert a filter string to a filter object to be used with dashboards. | [
"**",
"Description",
"**",
"Internal",
"function",
"to",
"convert",
"a",
"filter",
"string",
"to",
"a",
"filter",
"object",
"to",
"be",
"used",
"with",
"dashboards",
"."
] | python | test | 41.410714 |
saltstack/salt | salt/states/pkg.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pkg.py#L840-L884 | def _verify_install(desired, new_pkgs, ignore_epoch=False, new_caps=None):
'''
Determine whether or not the installed packages match what was requested in
the SLS file.
'''
ok = []
failed = []
if not new_caps:
new_caps = dict()
for pkgname, pkgver in desired.items():
# Fr... | [
"def",
"_verify_install",
"(",
"desired",
",",
"new_pkgs",
",",
"ignore_epoch",
"=",
"False",
",",
"new_caps",
"=",
"None",
")",
":",
"ok",
"=",
"[",
"]",
"failed",
"=",
"[",
"]",
"if",
"not",
"new_caps",
":",
"new_caps",
"=",
"dict",
"(",
")",
"for"... | Determine whether or not the installed packages match what was requested in
the SLS file. | [
"Determine",
"whether",
"or",
"not",
"the",
"installed",
"packages",
"match",
"what",
"was",
"requested",
"in",
"the",
"SLS",
"file",
"."
] | python | train | 38.555556 |
ReadabilityHoldings/python-readability-api | readability/clients.py | https://github.com/ReadabilityHoldings/python-readability-api/blob/4b746166877d5a8dc29222aedccb18c2506a5385/readability/clients.py#L350-L360 | def post(self, url, post_params=None):
"""
Make an HTTP POST request to the Parser API.
:param url: url to which to make the request
:param post_params: POST data to send along. Expected to be a dict.
"""
post_params['token'] = self.token
params = urlencode(post_... | [
"def",
"post",
"(",
"self",
",",
"url",
",",
"post_params",
"=",
"None",
")",
":",
"post_params",
"[",
"'token'",
"]",
"=",
"self",
".",
"token",
"params",
"=",
"urlencode",
"(",
"post_params",
")",
"logger",
".",
"debug",
"(",
"'Making POST request to %s ... | Make an HTTP POST request to the Parser API.
:param url: url to which to make the request
:param post_params: POST data to send along. Expected to be a dict. | [
"Make",
"an",
"HTTP",
"POST",
"request",
"to",
"the",
"Parser",
"API",
"."
] | python | train | 40 |
tensorflow/tensor2tensor | tensor2tensor/envs/rendered_env_problem.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/rendered_env_problem.py#L66-L85 | def example_reading_spec(self):
"""Return a mix of env and video data fields and decoders."""
video_fields, video_decoders = (
video_utils.VideoProblem.example_reading_spec(self))
env_fields, env_decoders = env_problem.EnvProblem.example_reading_spec(self)
# Remove raw observations field since ... | [
"def",
"example_reading_spec",
"(",
"self",
")",
":",
"video_fields",
",",
"video_decoders",
"=",
"(",
"video_utils",
".",
"VideoProblem",
".",
"example_reading_spec",
"(",
"self",
")",
")",
"env_fields",
",",
"env_decoders",
"=",
"env_problem",
".",
"EnvProblem",... | Return a mix of env and video data fields and decoders. | [
"Return",
"a",
"mix",
"of",
"env",
"and",
"video",
"data",
"fields",
"and",
"decoders",
"."
] | python | train | 41.25 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/module.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/module.py#L952-L1005 | def get_module_by_name(self, modName):
"""
@type modName: int
@param modName:
Name of the module to look for, as returned by L{Module.get_name}.
If two or more modules with the same name are loaded, only one
of the matching modules is returned.
Y... | [
"def",
"get_module_by_name",
"(",
"self",
",",
"modName",
")",
":",
"# Convert modName to lowercase.",
"# This helps make case insensitive string comparisons.",
"modName",
"=",
"modName",
".",
"lower",
"(",
")",
"# modName is an absolute pathname.",
"if",
"PathOperations",
".... | @type modName: int
@param modName:
Name of the module to look for, as returned by L{Module.get_name}.
If two or more modules with the same name are loaded, only one
of the matching modules is returned.
You can also pass a full pathname to the DLL file.
... | [
"@type",
"modName",
":",
"int",
"@param",
"modName",
":",
"Name",
"of",
"the",
"module",
"to",
"look",
"for",
"as",
"returned",
"by",
"L",
"{",
"Module",
".",
"get_name",
"}",
".",
"If",
"two",
"or",
"more",
"modules",
"with",
"the",
"same",
"name",
... | python | train | 35.185185 |
MacHu-GWU/angora-project | angora/crawler/simplecrawler.py | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/crawler/simplecrawler.py#L194-L219 | def html(self, url, timeout=None):
"""High level method to get http request response in text.
smartly handle the encoding problem.
"""
response = self.get_response(url, timeout=timeout)
if response:
domain = self.get_domain(url)
if domain in self.domain_en... | [
"def",
"html",
"(",
"self",
",",
"url",
",",
"timeout",
"=",
"None",
")",
":",
"response",
"=",
"self",
".",
"get_response",
"(",
"url",
",",
"timeout",
"=",
"timeout",
")",
"if",
"response",
":",
"domain",
"=",
"self",
".",
"get_domain",
"(",
"url",... | High level method to get http request response in text.
smartly handle the encoding problem. | [
"High",
"level",
"method",
"to",
"get",
"http",
"request",
"response",
"in",
"text",
".",
"smartly",
"handle",
"the",
"encoding",
"problem",
"."
] | python | train | 42 |
gem/oq-engine | openquake/hazardlib/probability_map.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/probability_map.py#L187-L191 | def array(self):
"""
The underlying array of shape (N, L, I)
"""
return numpy.array([self[sid].array for sid in sorted(self)]) | [
"def",
"array",
"(",
"self",
")",
":",
"return",
"numpy",
".",
"array",
"(",
"[",
"self",
"[",
"sid",
"]",
".",
"array",
"for",
"sid",
"in",
"sorted",
"(",
"self",
")",
"]",
")"
] | The underlying array of shape (N, L, I) | [
"The",
"underlying",
"array",
"of",
"shape",
"(",
"N",
"L",
"I",
")"
] | python | train | 30.8 |
unixsurfer/anycast_healthchecker | anycast_healthchecker/utils.py | https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/utils.py#L558-L595 | def create_bird_config_files(bird_configuration):
"""Create bird configuration files per IP version.
Creates bird configuration files if they don't exist. It also creates the
directories where we store the history of changes, if this functionality is
enabled.
Arguments:
bird_configuration ... | [
"def",
"create_bird_config_files",
"(",
"bird_configuration",
")",
":",
"for",
"ip_version",
"in",
"bird_configuration",
":",
"# This creates the file if it doesn't exist.",
"config_file",
"=",
"bird_configuration",
"[",
"ip_version",
"]",
"[",
"'config_file'",
"]",
"try",
... | Create bird configuration files per IP version.
Creates bird configuration files if they don't exist. It also creates the
directories where we store the history of changes, if this functionality is
enabled.
Arguments:
bird_configuration (dict): A dictionary with settings for bird.
Returns... | [
"Create",
"bird",
"configuration",
"files",
"per",
"IP",
"version",
"."
] | python | train | 38.631579 |
rsinger86/drf-flex-fields | rest_flex_fields/serializers.py | https://github.com/rsinger86/drf-flex-fields/blob/56495f15977d76697972acac571792e8fd67003d/rest_flex_fields/serializers.py#L50-L75 | def _make_expanded_field_serializer(
self, name, nested_expand, nested_fields, nested_omit
):
"""
Returns an instance of the dynamically created nested serializer.
"""
field_options = self.expandable_fields[name]
serializer_class = field_options[0]
serializer_... | [
"def",
"_make_expanded_field_serializer",
"(",
"self",
",",
"name",
",",
"nested_expand",
",",
"nested_fields",
",",
"nested_omit",
")",
":",
"field_options",
"=",
"self",
".",
"expandable_fields",
"[",
"name",
"]",
"serializer_class",
"=",
"field_options",
"[",
"... | Returns an instance of the dynamically created nested serializer. | [
"Returns",
"an",
"instance",
"of",
"the",
"dynamically",
"created",
"nested",
"serializer",
"."
] | python | train | 34.884615 |
gamechanger/dusty | dusty/commands/run.py | https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/commands/run.py#L113-L131 | def restart_apps_or_services(app_or_service_names=None):
"""Restart any containers associated with Dusty, or associated with
the provided app_or_service_names."""
if app_or_service_names:
log_to_client("Restarting the following apps or services: {}".format(', '.join(app_or_service_names)))
else:... | [
"def",
"restart_apps_or_services",
"(",
"app_or_service_names",
"=",
"None",
")",
":",
"if",
"app_or_service_names",
":",
"log_to_client",
"(",
"\"Restarting the following apps or services: {}\"",
".",
"format",
"(",
"', '",
".",
"join",
"(",
"app_or_service_names",
")",
... | Restart any containers associated with Dusty, or associated with
the provided app_or_service_names. | [
"Restart",
"any",
"containers",
"associated",
"with",
"Dusty",
"or",
"associated",
"with",
"the",
"provided",
"app_or_service_names",
"."
] | python | valid | 51.157895 |
innogames/polysh | polysh/console.py | https://github.com/innogames/polysh/blob/fbea36f3bc9f47a62d72040c48dad1776124dae3/polysh/console.py#L40-L56 | def console_output(msg, logging_msg=None):
"""Use instead of print, to clear the status information before printing"""
assert isinstance(msg, bytes)
assert isinstance(logging_msg, bytes) or logging_msg is None
from polysh import remote_dispatcher
remote_dispatcher.log(logging_msg or msg)
if re... | [
"def",
"console_output",
"(",
"msg",
",",
"logging_msg",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"msg",
",",
"bytes",
")",
"assert",
"isinstance",
"(",
"logging_msg",
",",
"bytes",
")",
"or",
"logging_msg",
"is",
"None",
"from",
"polysh",
"impo... | Use instead of print, to clear the status information before printing | [
"Use",
"instead",
"of",
"print",
"to",
"clear",
"the",
"status",
"information",
"before",
"printing"
] | python | train | 37.764706 |
eternnoir/pyTelegramBotAPI | telebot/__init__.py | https://github.com/eternnoir/pyTelegramBotAPI/blob/47b53b88123097f1b9562a6cd5d4e080b86185d1/telebot/__init__.py#L674-L688 | def send_document(self, chat_id, data, reply_to_message_id=None, caption=None, reply_markup=None,
parse_mode=None, disable_notification=None, timeout=None):
"""
Use this method to send general files.
:param chat_id:
:param data:
:param reply_to_message_id:
... | [
"def",
"send_document",
"(",
"self",
",",
"chat_id",
",",
"data",
",",
"reply_to_message_id",
"=",
"None",
",",
"caption",
"=",
"None",
",",
"reply_markup",
"=",
"None",
",",
"parse_mode",
"=",
"None",
",",
"disable_notification",
"=",
"None",
",",
"timeout"... | Use this method to send general files.
:param chat_id:
:param data:
:param reply_to_message_id:
:param reply_markup:
:param parse_mode:
:param disable_notification:
:return: API reply. | [
"Use",
"this",
"method",
"to",
"send",
"general",
"files",
".",
":",
"param",
"chat_id",
":",
":",
"param",
"data",
":",
":",
"param",
"reply_to_message_id",
":",
":",
"param",
"reply_markup",
":",
":",
"param",
"parse_mode",
":",
":",
"param",
"disable_no... | python | train | 44.933333 |
MartinThoma/hwrt | hwrt/datasets/crohme_eval.py | https://github.com/MartinThoma/hwrt/blob/725c21a3d0f5a30b8492cbc184b3688ceb364e1c/hwrt/datasets/crohme_eval.py#L21-L41 | def evaluate_dir(sample_dir):
"""Evaluate all recordings in `sample_dir`.
Parameters
----------
sample_dir : string
The path to a directory with *.inkml files.
Returns
-------
list of dictionaries
Each dictionary contains the keys 'filename' and 'results', where
're... | [
"def",
"evaluate_dir",
"(",
"sample_dir",
")",
":",
"results",
"=",
"[",
"]",
"if",
"sample_dir",
"[",
"-",
"1",
"]",
"==",
"\"/\"",
":",
"sample_dir",
"=",
"sample_dir",
"[",
":",
"-",
"1",
"]",
"for",
"filename",
"in",
"glob",
".",
"glob",
"(",
"... | Evaluate all recordings in `sample_dir`.
Parameters
----------
sample_dir : string
The path to a directory with *.inkml files.
Returns
-------
list of dictionaries
Each dictionary contains the keys 'filename' and 'results', where
'results' itself is a list of dictionari... | [
"Evaluate",
"all",
"recordings",
"in",
"sample_dir",
"."
] | python | train | 29.761905 |
RJT1990/pyflux | pyflux/gas/gasllt.py | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/gas/gasllt.py#L389-L448 | def _sim_prediction(self, theta, theta_t, Y, scores, h, t_params, simulations):
""" Simulates a h-step ahead mean prediction
Parameters
----------
theta : np.array
The past predicted values
theta_t : np.array
The past local linear trend
Y : np.a... | [
"def",
"_sim_prediction",
"(",
"self",
",",
"theta",
",",
"theta_t",
",",
"Y",
",",
"scores",
",",
"h",
",",
"t_params",
",",
"simulations",
")",
":",
"model_scale",
",",
"model_shape",
",",
"model_skewness",
"=",
"self",
".",
"_get_scale_and_shape",
"(",
... | Simulates a h-step ahead mean prediction
Parameters
----------
theta : np.array
The past predicted values
theta_t : np.array
The past local linear trend
Y : np.array
The past data
scores : np.array
The past scores
... | [
"Simulates",
"a",
"h",
"-",
"step",
"ahead",
"mean",
"prediction"
] | python | train | 33.083333 |
pinterest/pymemcache | pymemcache/client/base.py | https://github.com/pinterest/pymemcache/blob/f3a348f4ce2248cce8b398e93e08d984fb9100e5/pymemcache/client/base.py#L258-L261 | def check_key(self, key):
"""Checks key and add key_prefix."""
return _check_key(key, allow_unicode_keys=self.allow_unicode_keys,
key_prefix=self.key_prefix) | [
"def",
"check_key",
"(",
"self",
",",
"key",
")",
":",
"return",
"_check_key",
"(",
"key",
",",
"allow_unicode_keys",
"=",
"self",
".",
"allow_unicode_keys",
",",
"key_prefix",
"=",
"self",
".",
"key_prefix",
")"
] | Checks key and add key_prefix. | [
"Checks",
"key",
"and",
"add",
"key_prefix",
"."
] | python | train | 49 |
rodluger/everest | everest/detrender.py | https://github.com/rodluger/everest/blob/6779591f9f8b3556847e2fbf761bdfac7520eaea/everest/detrender.py#L375-L397 | def cv_compute(self, b, A, B, C, mK, f, m1, m2):
'''
Compute the model (cross-validation step only) for chunk :py:obj:`b`.
'''
A = np.sum([l * a for l, a in zip(self.lam[b], A)
if l is not None], axis=0)
B = np.sum([l * b for l, b in zip(self.lam[b], B)
... | [
"def",
"cv_compute",
"(",
"self",
",",
"b",
",",
"A",
",",
"B",
",",
"C",
",",
"mK",
",",
"f",
",",
"m1",
",",
"m2",
")",
":",
"A",
"=",
"np",
".",
"sum",
"(",
"[",
"l",
"*",
"a",
"for",
"l",
",",
"a",
"in",
"zip",
"(",
"self",
".",
"... | Compute the model (cross-validation step only) for chunk :py:obj:`b`. | [
"Compute",
"the",
"model",
"(",
"cross",
"-",
"validation",
"step",
"only",
")",
"for",
"chunk",
":",
"py",
":",
"obj",
":",
"b",
"."
] | python | train | 37.782609 |
apache/spark | python/pyspark/sql/functions.py | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/functions.py#L314-L329 | def approx_count_distinct(col, rsd=None):
"""Aggregate function: returns a new :class:`Column` for approximate distinct count of
column `col`.
:param rsd: maximum estimation error allowed (default = 0.05). For rsd < 0.01, it is more
efficient to use :func:`countDistinct`
>>> df.agg(approx_coun... | [
"def",
"approx_count_distinct",
"(",
"col",
",",
"rsd",
"=",
"None",
")",
":",
"sc",
"=",
"SparkContext",
".",
"_active_spark_context",
"if",
"rsd",
"is",
"None",
":",
"jc",
"=",
"sc",
".",
"_jvm",
".",
"functions",
".",
"approx_count_distinct",
"(",
"_to_... | Aggregate function: returns a new :class:`Column` for approximate distinct count of
column `col`.
:param rsd: maximum estimation error allowed (default = 0.05). For rsd < 0.01, it is more
efficient to use :func:`countDistinct`
>>> df.agg(approx_count_distinct(df.age).alias('distinct_ages')).collec... | [
"Aggregate",
"function",
":",
"returns",
"a",
"new",
":",
"class",
":",
"Column",
"for",
"approximate",
"distinct",
"count",
"of",
"column",
"col",
"."
] | python | train | 40.1875 |
deschler/django-modeltranslation | modeltranslation/widgets.py | https://github.com/deschler/django-modeltranslation/blob/18fec04a5105cbd83fc3759f4fda20135b3a848c/modeltranslation/widgets.py#L53-L58 | def media(self):
"""
Combines media of both components and adds a small script that unchecks
the clear box, when a value in any wrapped input is modified.
"""
return self.widget.media + self.checkbox.media + Media(self.Media) | [
"def",
"media",
"(",
"self",
")",
":",
"return",
"self",
".",
"widget",
".",
"media",
"+",
"self",
".",
"checkbox",
".",
"media",
"+",
"Media",
"(",
"self",
".",
"Media",
")"
] | Combines media of both components and adds a small script that unchecks
the clear box, when a value in any wrapped input is modified. | [
"Combines",
"media",
"of",
"both",
"components",
"and",
"adds",
"a",
"small",
"script",
"that",
"unchecks",
"the",
"clear",
"box",
"when",
"a",
"value",
"in",
"any",
"wrapped",
"input",
"is",
"modified",
"."
] | python | train | 43.333333 |
BeyondTheClouds/enoslib | docs/tutorials/using-tasks/step2.py | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/docs/tutorials/using-tasks/step2.py#L32-L40 | def up(force=True, env=None, **kwargs):
"Starts a new experiment"
inventory = os.path.join(os.getcwd(), "hosts")
conf = Configuration.from_dictionnary(provider_conf)
provider = Enos_vagrant(conf)
roles, networks = provider.init()
check_networks(roles, networks)
env["roles"] = roles
env["... | [
"def",
"up",
"(",
"force",
"=",
"True",
",",
"env",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"inventory",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"\"hosts\"",
")",
"conf",
"=",
"Configuration",
".",
... | Starts a new experiment | [
"Starts",
"a",
"new",
"experiment"
] | python | train | 37 |
Clinical-Genomics/scout | scout/adapter/mongo/index.py | https://github.com/Clinical-Genomics/scout/blob/90a551e2e1653a319e654c2405c2866f93d0ebb9/scout/adapter/mongo/index.py#L74-L79 | def drop_indexes(self):
"""Delete all indexes for the database"""
LOG.warning("Dropping all indexe")
for collection_name in INDEXES:
LOG.warning("Dropping all indexes for collection name %s", collection_name)
self.db[collection_name].drop_indexes() | [
"def",
"drop_indexes",
"(",
"self",
")",
":",
"LOG",
".",
"warning",
"(",
"\"Dropping all indexe\"",
")",
"for",
"collection_name",
"in",
"INDEXES",
":",
"LOG",
".",
"warning",
"(",
"\"Dropping all indexes for collection name %s\"",
",",
"collection_name",
")",
"sel... | Delete all indexes for the database | [
"Delete",
"all",
"indexes",
"for",
"the",
"database"
] | python | test | 48.5 |
pandas-dev/pandas | pandas/core/indexes/base.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L1022-L1046 | def to_native_types(self, slicer=None, **kwargs):
"""
Format specified values of `self` and return them.
Parameters
----------
slicer : int, array-like
An indexer into `self` that specifies which values
are used in the formatting process.
kwargs :... | [
"def",
"to_native_types",
"(",
"self",
",",
"slicer",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"values",
"=",
"self",
"if",
"slicer",
"is",
"not",
"None",
":",
"values",
"=",
"values",
"[",
"slicer",
"]",
"return",
"values",
".",
"_format_native... | Format specified values of `self` and return them.
Parameters
----------
slicer : int, array-like
An indexer into `self` that specifies which values
are used in the formatting process.
kwargs : dict
Options for specifying how the values should be form... | [
"Format",
"specified",
"values",
"of",
"self",
"and",
"return",
"them",
"."
] | python | train | 34.96 |
lemieuxl/pyGenClean | pyGenClean/DupSNPs/duplicated_snps.py | https://github.com/lemieuxl/pyGenClean/blob/6173a48ccc0cf3a3bd711b1f2a1fa16248b8bf55/pyGenClean/DupSNPs/duplicated_snps.py#L933-L1063 | def computeStatistics(tped, tfam, snps):
"""Computes the completion and concordance of each SNPs.
:param tped: a representation of the ``tped``.
:param tfam: a representation of the ``tfam``
:param snps: the position of the duplicated markers in the ``tped``.
:type tped: numpy.array
:type tfam... | [
"def",
"computeStatistics",
"(",
"tped",
",",
"tfam",
",",
"snps",
")",
":",
"# The completion data type",
"completion",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"0",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"tped",
")",
")",
"]",
",",
"[",
"0",
... | Computes the completion and concordance of each SNPs.
:param tped: a representation of the ``tped``.
:param tfam: a representation of the ``tfam``
:param snps: the position of the duplicated markers in the ``tped``.
:type tped: numpy.array
:type tfam: list
:type snps: dict
:returns: a tup... | [
"Computes",
"the",
"completion",
"and",
"concordance",
"of",
"each",
"SNPs",
"."
] | python | train | 38.839695 |
Jajcus/pyxmpp2 | pyxmpp2/ext/muc/muc.py | https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muc.py#L494-L504 | def send_message(self,body):
"""
Send a message to the room.
:Parameters:
- `body`: the message body.
:Types:
- `body`: `unicode`
"""
m=Message(to_jid=self.room_jid.bare(),stanza_type="groupchat",body=body)
self.manager.stream.send(m) | [
"def",
"send_message",
"(",
"self",
",",
"body",
")",
":",
"m",
"=",
"Message",
"(",
"to_jid",
"=",
"self",
".",
"room_jid",
".",
"bare",
"(",
")",
",",
"stanza_type",
"=",
"\"groupchat\"",
",",
"body",
"=",
"body",
")",
"self",
".",
"manager",
".",
... | Send a message to the room.
:Parameters:
- `body`: the message body.
:Types:
- `body`: `unicode` | [
"Send",
"a",
"message",
"to",
"the",
"room",
"."
] | python | valid | 27.727273 |
DataBiosphere/toil | src/toil/wdl/wdl_analysis.py | https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/wdl/wdl_analysis.py#L883-L927 | def parse_declaration_expressn_fncall(self, name, params, es):
"""
Parses out cromwell's built-in function calls.
Some of these are special
and need minor adjustments, for example length(), which is equivalent to
python's len() function. Or sub, which is equivalent to re.sub(),... | [
"def",
"parse_declaration_expressn_fncall",
"(",
"self",
",",
"name",
",",
"params",
",",
"es",
")",
":",
"# name of the function",
"if",
"isinstance",
"(",
"name",
",",
"wdl_parser",
".",
"Terminal",
")",
":",
"if",
"name",
".",
"str",
":",
"# use python's bu... | Parses out cromwell's built-in function calls.
Some of these are special
and need minor adjustments, for example length(), which is equivalent to
python's len() function. Or sub, which is equivalent to re.sub(), but
needs a rearrangement of input variables.
Known to be support... | [
"Parses",
"out",
"cromwell",
"s",
"built",
"-",
"in",
"function",
"calls",
"."
] | python | train | 36.911111 |
d0c-s4vage/pfp | pfp/interp.py | https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L281-L293 | def push(self, new_scope=None):
"""Create a new scope
:returns: TODO
"""
if new_scope is None:
new_scope = {
"types": {},
"vars": {}
}
self._curr_scope = new_scope
self._dlog("pushing new scope, scope level = {}".fo... | [
"def",
"push",
"(",
"self",
",",
"new_scope",
"=",
"None",
")",
":",
"if",
"new_scope",
"is",
"None",
":",
"new_scope",
"=",
"{",
"\"types\"",
":",
"{",
"}",
",",
"\"vars\"",
":",
"{",
"}",
"}",
"self",
".",
"_curr_scope",
"=",
"new_scope",
"self",
... | Create a new scope
:returns: TODO | [
"Create",
"a",
"new",
"scope",
":",
"returns",
":",
"TODO"
] | python | train | 29.076923 |
pymc-devs/pymc | pymc/StepMethods.py | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/StepMethods.py#L292-L300 | def loglike(self):
'''
The summed log-probability of all stochastic variables that depend on
self.stochastics, with self.stochastics removed.
'''
sum = logp_of_set(self.children)
if self.verbose > 2:
print_('\t' + self._id + ' Current log-likelihood ', sum)
... | [
"def",
"loglike",
"(",
"self",
")",
":",
"sum",
"=",
"logp_of_set",
"(",
"self",
".",
"children",
")",
"if",
"self",
".",
"verbose",
">",
"2",
":",
"print_",
"(",
"'\\t'",
"+",
"self",
".",
"_id",
"+",
"' Current log-likelihood '",
",",
"sum",
")",
"... | The summed log-probability of all stochastic variables that depend on
self.stochastics, with self.stochastics removed. | [
"The",
"summed",
"log",
"-",
"probability",
"of",
"all",
"stochastic",
"variables",
"that",
"depend",
"on",
"self",
".",
"stochastics",
"with",
"self",
".",
"stochastics",
"removed",
"."
] | python | train | 36.444444 |
yunojuno/elasticsearch-django | elasticsearch_django/apps.py | https://github.com/yunojuno/elasticsearch-django/blob/e8d98d32bcd77f1bedb8f1a22b6523ca44ffd489/elasticsearch_django/apps.py#L112-L137 | def _update_search_index(*, instance, index, update_fields):
"""Process index / update search index update actions."""
if not _in_search_queryset(instance=instance, index=index):
logger.debug(
"Object (%r) is not in search queryset, ignoring update.", instance
)
return
t... | [
"def",
"_update_search_index",
"(",
"*",
",",
"instance",
",",
"index",
",",
"update_fields",
")",
":",
"if",
"not",
"_in_search_queryset",
"(",
"instance",
"=",
"instance",
",",
"index",
"=",
"index",
")",
":",
"logger",
".",
"debug",
"(",
"\"Object (%r) is... | Process index / update search index update actions. | [
"Process",
"index",
"/",
"update",
"search",
"index",
"update",
"actions",
"."
] | python | train | 38.384615 |
havardgulldahl/jottalib | src/jottalib/JFS.py | https://github.com/havardgulldahl/jottalib/blob/4d015e4309b1d9055e561ec757363fb2632b4eb7/src/jottalib/JFS.py#L1103-L1180 | def up(self, path, fileobject, upload_callback=None, resume_offset=None):
"Upload a fileobject to path, HTTP POST-ing to up.jottacloud.com, using the JottaCloud API"
"""
*** WHAT DID I DO?: created file
***
POST https://up.jottacloud.com/jfs/**USERNAME**/Jotta/Sync/testFolder/t... | [
"def",
"up",
"(",
"self",
",",
"path",
",",
"fileobject",
",",
"upload_callback",
"=",
"None",
",",
"resume_offset",
"=",
"None",
")",
":",
"\"\"\"\n\n *** WHAT DID I DO?: created file\n ***\n\n POST https://up.jottacloud.com/jfs/**USERNAME**/Jotta/Sync/testF... | Upload a fileobject to path, HTTP POST-ing to up.jottacloud.com, using the JottaCloud API | [
"Upload",
"a",
"fileobject",
"to",
"path",
"HTTP",
"POST",
"-",
"ing",
"to",
"up",
".",
"jottacloud",
".",
"com",
"using",
"the",
"JottaCloud",
"API"
] | python | train | 46 |
tensorflow/datasets | tensorflow_datasets/image/cifar.py | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/cifar.py#L110-L127 | def _generate_examples(self, filepaths):
"""Generate CIFAR examples as dicts.
Shared across CIFAR-{10, 100}. Uses self._cifar_info as
configuration.
Args:
filepaths (list[str]): The files to use to generate the data.
Yields:
The cifar examples, as defined in the dataset info features.... | [
"def",
"_generate_examples",
"(",
"self",
",",
"filepaths",
")",
":",
"label_keys",
"=",
"self",
".",
"_cifar_info",
".",
"label_keys",
"for",
"path",
"in",
"filepaths",
":",
"for",
"labels",
",",
"np_image",
"in",
"_load_data",
"(",
"path",
",",
"len",
"(... | Generate CIFAR examples as dicts.
Shared across CIFAR-{10, 100}. Uses self._cifar_info as
configuration.
Args:
filepaths (list[str]): The files to use to generate the data.
Yields:
The cifar examples, as defined in the dataset info features. | [
"Generate",
"CIFAR",
"examples",
"as",
"dicts",
"."
] | python | train | 30.111111 |
pgmpy/pgmpy | pgmpy/readwrite/BIF.py | https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/readwrite/BIF.py#L69-L85 | def get_variable_grammar(self):
"""
A method that returns variable grammar
"""
# Defining a expression for valid word
word_expr = Word(alphanums + '_' + '-')
word_expr2 = Word(initChars=printables, excludeChars=['{', '}', ',', ' '])
name_expr = Suppress('variable... | [
"def",
"get_variable_grammar",
"(",
"self",
")",
":",
"# Defining a expression for valid word",
"word_expr",
"=",
"Word",
"(",
"alphanums",
"+",
"'_'",
"+",
"'-'",
")",
"word_expr2",
"=",
"Word",
"(",
"initChars",
"=",
"printables",
",",
"excludeChars",
"=",
"["... | A method that returns variable grammar | [
"A",
"method",
"that",
"returns",
"variable",
"grammar"
] | python | train | 55.882353 |
jtambasco/modesolverpy | modesolverpy/structure_base.py | https://github.com/jtambasco/modesolverpy/blob/85254a13b5aed2404187c52ac93b9b3ce99ee3a3/modesolverpy/structure_base.py#L142-L151 | def y(self):
'''
np.array: The grid points in y.
'''
if None not in (self.y_min, self.y_max, self.y_step) and \
self.y_min != self.y_max:
y = np.arange(self.y_min, self.y_max-self.y_step*0.1, self.y_step)
else:
y = np.array([])
retu... | [
"def",
"y",
"(",
"self",
")",
":",
"if",
"None",
"not",
"in",
"(",
"self",
".",
"y_min",
",",
"self",
".",
"y_max",
",",
"self",
".",
"y_step",
")",
"and",
"self",
".",
"y_min",
"!=",
"self",
".",
"y_max",
":",
"y",
"=",
"np",
".",
"arange",
... | np.array: The grid points in y. | [
"np",
".",
"array",
":",
"The",
"grid",
"points",
"in",
"y",
"."
] | python | train | 31.5 |
scanny/python-pptx | pptx/oxml/shapes/autoshape.py | https://github.com/scanny/python-pptx/blob/d6ab8234f8b03953d2f831ff9394b1852db34130/pptx/oxml/shapes/autoshape.py#L89-L97 | def add_moveTo(self, x, y):
"""Return a newly created `a:moveTo` subtree with point *(x, y)*.
The new `a:moveTo` element is appended to this `a:path` element.
"""
moveTo = self._add_moveTo()
pt = moveTo._add_pt()
pt.x, pt.y = x, y
return moveTo | [
"def",
"add_moveTo",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"moveTo",
"=",
"self",
".",
"_add_moveTo",
"(",
")",
"pt",
"=",
"moveTo",
".",
"_add_pt",
"(",
")",
"pt",
".",
"x",
",",
"pt",
".",
"y",
"=",
"x",
",",
"y",
"return",
"moveTo"
] | Return a newly created `a:moveTo` subtree with point *(x, y)*.
The new `a:moveTo` element is appended to this `a:path` element. | [
"Return",
"a",
"newly",
"created",
"a",
":",
"moveTo",
"subtree",
"with",
"point",
"*",
"(",
"x",
"y",
")",
"*",
"."
] | python | train | 32.555556 |
rakanalh/pocket-api | pocket/__init__.py | https://github.com/rakanalh/pocket-api/blob/d8222dd34e3aa5e545f9b8ba407fa277c734ab82/pocket/__init__.py#L61-L76 | def bulk_add(self, item_id, ref_id=None, tags=None,
time=None, title=None, url=None):
"""
Add an item to list
See: https://getpocket.com/developer/docs/v3/modify
:param item_id: int
:param ref_id: tweet_id
:param tags: list of tags
:param time: ti... | [
"def",
"bulk_add",
"(",
"self",
",",
"item_id",
",",
"ref_id",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"time",
"=",
"None",
",",
"title",
"=",
"None",
",",
"url",
"=",
"None",
")",
":",
"self",
".",
"_add_action",
"(",
"'add'",
")",
"return",
... | Add an item to list
See: https://getpocket.com/developer/docs/v3/modify
:param item_id: int
:param ref_id: tweet_id
:param tags: list of tags
:param time: time of action
:param title: given title
:param url: item url
:return: self for chaining
:rty... | [
"Add",
"an",
"item",
"to",
"list",
"See",
":",
"https",
":",
"//",
"getpocket",
".",
"com",
"/",
"developer",
"/",
"docs",
"/",
"v3",
"/",
"modify",
":",
"param",
"item_id",
":",
"int",
":",
"param",
"ref_id",
":",
"tweet_id",
":",
"param",
"tags",
... | python | train | 31.375 |
ccubed/Shosetsu | Shosetsu/Parsing.py | https://github.com/ccubed/Shosetsu/blob/eba01c058100ec8806129b11a2859f3126a1b101/Shosetsu/Parsing.py#L16-L35 | async def parse_release_results(soup):
"""
Parse Releases search pages.
:param soup: The BS4 class object
:return: A list of dictionaries containing a release dictionary. This is the same as the one returned in get_novel.
It contains a Date released, Platform, Ages group and Name.
"""
... | [
"async",
"def",
"parse_release_results",
"(",
"soup",
")",
":",
"soup",
"=",
"list",
"(",
"soup",
".",
"find_all",
"(",
"'table'",
",",
"class_",
"=",
"'stripe'",
")",
"[",
"0",
"]",
".",
"children",
")",
"[",
"1",
":",
"]",
"releases",
"=",
"[",
"... | Parse Releases search pages.
:param soup: The BS4 class object
:return: A list of dictionaries containing a release dictionary. This is the same as the one returned in get_novel.
It contains a Date released, Platform, Ages group and Name. | [
"Parse",
"Releases",
"search",
"pages",
"."
] | python | test | 39.65 |
Microsoft/azure-devops-python-api | azure-devops/azure/devops/v5_1/task_agent/task_agent_client.py | https://github.com/Microsoft/azure-devops-python-api/blob/4777ffda2f5052fabbaddb2abe9cb434e0cf1aa8/azure-devops/azure/devops/v5_1/task_agent/task_agent_client.py#L41-L54 | def delete_agent_cloud(self, agent_cloud_id):
"""DeleteAgentCloud.
[Preview API]
:param int agent_cloud_id:
:rtype: :class:`<TaskAgentCloud> <azure.devops.v5_1.task-agent.models.TaskAgentCloud>`
"""
route_values = {}
if agent_cloud_id is not None:
rout... | [
"def",
"delete_agent_cloud",
"(",
"self",
",",
"agent_cloud_id",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"agent_cloud_id",
"is",
"not",
"None",
":",
"route_values",
"[",
"'agentCloudId'",
"]",
"=",
"self",
".",
"_serialize",
".",
"url",
"(",
"'agent_c... | DeleteAgentCloud.
[Preview API]
:param int agent_cloud_id:
:rtype: :class:`<TaskAgentCloud> <azure.devops.v5_1.task-agent.models.TaskAgentCloud>` | [
"DeleteAgentCloud",
".",
"[",
"Preview",
"API",
"]",
":",
"param",
"int",
"agent_cloud_id",
":",
":",
"rtype",
":",
":",
"class",
":",
"<TaskAgentCloud",
">",
"<azure",
".",
"devops",
".",
"v5_1",
".",
"task",
"-",
"agent",
".",
"models",
".",
"TaskAgent... | python | train | 50.071429 |
spyder-ide/spyder | spyder/plugins/editor/panels/scrollflag.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/scrollflag.py#L185-L188 | def get_scrollbar_value_height(self):
"""Return the value span height of the scrollbar"""
vsb = self.editor.verticalScrollBar()
return vsb.maximum()-vsb.minimum()+vsb.pageStep() | [
"def",
"get_scrollbar_value_height",
"(",
"self",
")",
":",
"vsb",
"=",
"self",
".",
"editor",
".",
"verticalScrollBar",
"(",
")",
"return",
"vsb",
".",
"maximum",
"(",
")",
"-",
"vsb",
".",
"minimum",
"(",
")",
"+",
"vsb",
".",
"pageStep",
"(",
")"
] | Return the value span height of the scrollbar | [
"Return",
"the",
"value",
"span",
"height",
"of",
"the",
"scrollbar"
] | python | train | 49.5 |
dagster-io/dagster | python_modules/libraries/dagster-gcp/dagster_gcp/types.py | https://github.com/dagster-io/dagster/blob/4119f8c773089de64831b1dfb9e168e353d401dc/python_modules/libraries/dagster-gcp/dagster_gcp/types.py#L86-L93 | def _is_valid_dataset(config_value):
'''Datasets must be of form "project.dataset" or "dataset"
'''
return re.match(
# regex matches: project.table -- OR -- table
r'^' + RE_PROJECT + r'\.' + RE_DS_TABLE + r'$|^' + RE_DS_TABLE + r'$',
config_value,
) | [
"def",
"_is_valid_dataset",
"(",
"config_value",
")",
":",
"return",
"re",
".",
"match",
"(",
"# regex matches: project.table -- OR -- table",
"r'^'",
"+",
"RE_PROJECT",
"+",
"r'\\.'",
"+",
"RE_DS_TABLE",
"+",
"r'$|^'",
"+",
"RE_DS_TABLE",
"+",
"r'$'",
",",
"confi... | Datasets must be of form "project.dataset" or "dataset" | [
"Datasets",
"must",
"be",
"of",
"form",
"project",
".",
"dataset",
"or",
"dataset"
] | python | test | 35.25 |
openstack/networking-cisco | networking_cisco/db/migration/alembic_migrations/versions/mitaka/expand/9148d96f9b39_rename_tenantid_to_projectid.py | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/db/migration/alembic_migrations/versions/mitaka/expand/9148d96f9b39_rename_tenantid_to_projectid.py#L35-L47 | def get_inspector():
"""Reuse inspector"""
global _INSPECTOR
if _INSPECTOR:
return _INSPECTOR
else:
bind = op.get_bind()
_INSPECTOR = sa.engine.reflection.Inspector.from_engine(bind)
return _INSPECTOR | [
"def",
"get_inspector",
"(",
")",
":",
"global",
"_INSPECTOR",
"if",
"_INSPECTOR",
":",
"return",
"_INSPECTOR",
"else",
":",
"bind",
"=",
"op",
".",
"get_bind",
"(",
")",
"_INSPECTOR",
"=",
"sa",
".",
"engine",
".",
"reflection",
".",
"Inspector",
".",
"... | Reuse inspector | [
"Reuse",
"inspector"
] | python | train | 18.153846 |
carsonyl/pypac | pypac/os_settings.py | https://github.com/carsonyl/pypac/blob/9e14a9e84a1ec5513a4fa819573073942fed0980/pypac/os_settings.py#L53-L76 | def autoconfig_url_from_preferences():
"""
Get the PAC ``AutoConfigURL`` value from the macOS System Preferences.
This setting is visible as the "URL" field in
System Preferences > Network > Advanced... > Proxies > Automatic Proxy Configuration.
:return: The value from the registry, or None i... | [
"def",
"autoconfig_url_from_preferences",
"(",
")",
":",
"if",
"not",
"ON_DARWIN",
":",
"raise",
"NotDarwinError",
"(",
")",
"try",
":",
"config",
"=",
"SystemConfiguration",
".",
"SCDynamicStoreCopyProxies",
"(",
"None",
")",
"except",
"AttributeError",
":",
"ret... | Get the PAC ``AutoConfigURL`` value from the macOS System Preferences.
This setting is visible as the "URL" field in
System Preferences > Network > Advanced... > Proxies > Automatic Proxy Configuration.
:return: The value from the registry, or None if the value isn't configured or available.
N... | [
"Get",
"the",
"PAC",
"AutoConfigURL",
"value",
"from",
"the",
"macOS",
"System",
"Preferences",
".",
"This",
"setting",
"is",
"visible",
"as",
"the",
"URL",
"field",
"in",
"System",
"Preferences",
">",
"Network",
">",
"Advanced",
"...",
">",
"Proxies",
">",
... | python | train | 42.75 |
google/flatbuffers | python/flatbuffers/table.py | https://github.com/google/flatbuffers/blob/6cc30b3272d79c85db7d4871ac0aa69541dc89de/python/flatbuffers/table.py#L66-L75 | def Vector(self, off):
"""Vector retrieves the start of data of the vector whose offset is
stored at "off" in this object."""
N.enforce_number(off, N.UOffsetTFlags)
off += self.Pos
x = off + self.Get(N.UOffsetTFlags, off)
# data starts after metadata containing the ve... | [
"def",
"Vector",
"(",
"self",
",",
"off",
")",
":",
"N",
".",
"enforce_number",
"(",
"off",
",",
"N",
".",
"UOffsetTFlags",
")",
"off",
"+=",
"self",
".",
"Pos",
"x",
"=",
"off",
"+",
"self",
".",
"Get",
"(",
"N",
".",
"UOffsetTFlags",
",",
"off"... | Vector retrieves the start of data of the vector whose offset is
stored at "off" in this object. | [
"Vector",
"retrieves",
"the",
"start",
"of",
"data",
"of",
"the",
"vector",
"whose",
"offset",
"is",
"stored",
"at",
"off",
"in",
"this",
"object",
"."
] | python | train | 37.8 |
biolink/ontobio | ontobio/io/parsereport.py | https://github.com/biolink/ontobio/blob/4e512a7831cfe6bc1b32f2c3be2ba41bc5cf7345/ontobio/io/parsereport.py#L26-L39 | def message(self, message: Message, rule: Optional[int]) -> None:
"""
Add a message to the appropriate list of messages. If `rule` refers
to a valid id range for a go rule, the message is entered in a list
keyed by the full gorule-{id}. Otherwise, if `rule` is None, or
outside th... | [
"def",
"message",
"(",
"self",
",",
"message",
":",
"Message",
",",
"rule",
":",
"Optional",
"[",
"int",
"]",
")",
"->",
"None",
":",
"rule_id",
"=",
"self",
".",
"_rule_id",
"(",
"rule",
")",
"if",
"rule_id",
"not",
"in",
"self",
".",
"messages",
... | Add a message to the appropriate list of messages. If `rule` refers
to a valid id range for a go rule, the message is entered in a list
keyed by the full gorule-{id}. Otherwise, if `rule` is None, or
outside the id range, then we put this in the catch-all "other"
keyed list of messages. | [
"Add",
"a",
"message",
"to",
"the",
"appropriate",
"list",
"of",
"messages",
".",
"If",
"rule",
"refers",
"to",
"a",
"valid",
"id",
"range",
"for",
"a",
"go",
"rule",
"the",
"message",
"is",
"entered",
"in",
"a",
"list",
"keyed",
"by",
"the",
"full",
... | python | train | 45.714286 |
aleju/imgaug | imgaug/external/poly_point_isect_py2py3.py | https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/external/poly_point_isect_py2py3.py#L1042-L1053 | def iter_items(self, start_key=None, end_key=None, reverse=False):
"""Iterates over the (key, value) items of the associated tree,
in ascending order if reverse is True, iterate in descending order,
reverse defaults to False"""
# optimized iterator (reduced method calls) - faster on CPy... | [
"def",
"iter_items",
"(",
"self",
",",
"start_key",
"=",
"None",
",",
"end_key",
"=",
"None",
",",
"reverse",
"=",
"False",
")",
":",
"# optimized iterator (reduced method calls) - faster on CPython but slower on pypy",
"if",
"self",
".",
"is_empty",
"(",
")",
":",
... | Iterates over the (key, value) items of the associated tree,
in ascending order if reverse is True, iterate in descending order,
reverse defaults to False | [
"Iterates",
"over",
"the",
"(",
"key",
"value",
")",
"items",
"of",
"the",
"associated",
"tree",
"in",
"ascending",
"order",
"if",
"reverse",
"is",
"True",
"iterate",
"in",
"descending",
"order",
"reverse",
"defaults",
"to",
"False"
] | python | valid | 45.5 |
quantopian/zipline | zipline/lib/labelarray.py | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/lib/labelarray.py#L303-L312 | def as_int_array(self):
"""
Convert self into a regular ndarray of ints.
This is an O(1) operation. It does not copy the underlying data.
"""
return self.view(
type=ndarray,
dtype=unsigned_int_dtype_with_size_in_bytes(self.itemsize),
) | [
"def",
"as_int_array",
"(",
"self",
")",
":",
"return",
"self",
".",
"view",
"(",
"type",
"=",
"ndarray",
",",
"dtype",
"=",
"unsigned_int_dtype_with_size_in_bytes",
"(",
"self",
".",
"itemsize",
")",
",",
")"
] | Convert self into a regular ndarray of ints.
This is an O(1) operation. It does not copy the underlying data. | [
"Convert",
"self",
"into",
"a",
"regular",
"ndarray",
"of",
"ints",
"."
] | python | train | 29.9 |
simon-anders/htseq | python2/HTSeq/__init__.py | https://github.com/simon-anders/htseq/blob/6f7d66e757e610228c33ebf2bb5dc8cc5051c7f0/python2/HTSeq/__init__.py#L144-L175 | def parse_GFF_attribute_string(attrStr, extra_return_first_value=False):
"""Parses a GFF attribute string and returns it as a dictionary.
If 'extra_return_first_value' is set, a pair is returned: the dictionary
and the value of the first attribute. This might be useful if this is the
ID.
"""
if... | [
"def",
"parse_GFF_attribute_string",
"(",
"attrStr",
",",
"extra_return_first_value",
"=",
"False",
")",
":",
"if",
"attrStr",
".",
"endswith",
"(",
"\"\\n\"",
")",
":",
"attrStr",
"=",
"attrStr",
"[",
":",
"-",
"1",
"]",
"d",
"=",
"{",
"}",
"first_val",
... | Parses a GFF attribute string and returns it as a dictionary.
If 'extra_return_first_value' is set, a pair is returned: the dictionary
and the value of the first attribute. This might be useful if this is the
ID. | [
"Parses",
"a",
"GFF",
"attribute",
"string",
"and",
"returns",
"it",
"as",
"a",
"dictionary",
"."
] | python | train | 35.90625 |
ewels/MultiQC | multiqc/modules/hicpro/hicpro.py | https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/hicpro/hicpro.py#L301-L320 | def hicpro_pairing_chart (self):
""" Generate Pairing chart """
# Specify the order of the different possible categories
keys = OrderedDict()
keys['Unique_paired_alignments'] = { 'color': '#005ce6', 'name': 'Uniquely Aligned' }
keys['Low_qual_pairs'] = { 'color': '#b97b35', 'nam... | [
"def",
"hicpro_pairing_chart",
"(",
"self",
")",
":",
"# Specify the order of the different possible categories",
"keys",
"=",
"OrderedDict",
"(",
")",
"keys",
"[",
"'Unique_paired_alignments'",
"]",
"=",
"{",
"'color'",
":",
"'#005ce6'",
",",
"'name'",
":",
"'Uniquel... | Generate Pairing chart | [
"Generate",
"Pairing",
"chart"
] | python | train | 44.4 |
knipknap/exscript | Exscript/protocols/telnetlib.py | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/protocols/telnetlib.py#L379-L391 | def read_very_lazy(self):
"""Return any data available in the cooked queue (very lazy).
Raise EOFError if connection closed and no data available.
Return '' if no cooked data available otherwise. Don't block.
"""
buf = self.cookedq.getvalue()
self.cookedq.seek(0)
... | [
"def",
"read_very_lazy",
"(",
"self",
")",
":",
"buf",
"=",
"self",
".",
"cookedq",
".",
"getvalue",
"(",
")",
"self",
".",
"cookedq",
".",
"seek",
"(",
"0",
")",
"self",
".",
"cookedq",
".",
"truncate",
"(",
")",
"if",
"not",
"buf",
"and",
"self",... | Return any data available in the cooked queue (very lazy).
Raise EOFError if connection closed and no data available.
Return '' if no cooked data available otherwise. Don't block. | [
"Return",
"any",
"data",
"available",
"in",
"the",
"cooked",
"queue",
"(",
"very",
"lazy",
")",
"."
] | python | train | 35.307692 |
gwastro/pycbc | pycbc/waveform/ringdown.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/waveform/ringdown.py#L202-L218 | def lm_ffinal(freqs, damping_times, modes):
"""Return the maximum f_final of the modes given, with f_final the frequency
at which the amplitude falls to 1/1000 of the peak amplitude
"""
f_max = {}
for lmn in modes:
l, m, nmodes = int(lmn[0]), int(lmn[1]), int(lmn[2])
for n in range(... | [
"def",
"lm_ffinal",
"(",
"freqs",
",",
"damping_times",
",",
"modes",
")",
":",
"f_max",
"=",
"{",
"}",
"for",
"lmn",
"in",
"modes",
":",
"l",
",",
"m",
",",
"nmodes",
"=",
"int",
"(",
"lmn",
"[",
"0",
"]",
")",
",",
"int",
"(",
"lmn",
"[",
"... | Return the maximum f_final of the modes given, with f_final the frequency
at which the amplitude falls to 1/1000 of the peak amplitude | [
"Return",
"the",
"maximum",
"f_final",
"of",
"the",
"modes",
"given",
"with",
"f_final",
"the",
"frequency",
"at",
"which",
"the",
"amplitude",
"falls",
"to",
"1",
"/",
"1000",
"of",
"the",
"peak",
"amplitude"
] | python | train | 34.235294 |
ansible/molecule | molecule/provisioner/lint/ansible_lint.py | https://github.com/ansible/molecule/blob/766dc35b0b0ce498cd5e3a62b40f828742d0d08c/molecule/provisioner/lint/ansible_lint.py#L64-L86 | def bake(self):
"""
Bake an `ansible-lint` command so it's ready to execute and returns
None.
:return: None
"""
options = self.options
default_exclude_list = options.pop('default_exclude')
options_exclude_list = options.pop('exclude')
excludes = d... | [
"def",
"bake",
"(",
"self",
")",
":",
"options",
"=",
"self",
".",
"options",
"default_exclude_list",
"=",
"options",
".",
"pop",
"(",
"'default_exclude'",
")",
"options_exclude_list",
"=",
"options",
".",
"pop",
"(",
"'exclude'",
")",
"excludes",
"=",
"defa... | Bake an `ansible-lint` command so it's ready to execute and returns
None.
:return: None | [
"Bake",
"an",
"ansible",
"-",
"lint",
"command",
"so",
"it",
"s",
"ready",
"to",
"execute",
"and",
"returns",
"None",
"."
] | python | train | 32.565217 |
tisimst/mcerp | mcerp/umath.py | https://github.com/tisimst/mcerp/blob/2bb8260c9ad2d58a806847f1b627b6451e407de1/mcerp/umath.py#L161-L169 | def fabs(x):
"""
Absolute value function
"""
if isinstance(x, UncertainFunction):
mcpts = np.fabs(x._mcpts)
return UncertainFunction(mcpts)
else:
return np.fabs(x) | [
"def",
"fabs",
"(",
"x",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"UncertainFunction",
")",
":",
"mcpts",
"=",
"np",
".",
"fabs",
"(",
"x",
".",
"_mcpts",
")",
"return",
"UncertainFunction",
"(",
"mcpts",
")",
"else",
":",
"return",
"np",
".",
... | Absolute value function | [
"Absolute",
"value",
"function"
] | python | train | 22.111111 |
h2oai/h2o-3 | h2o-py/h2o/model/regression.py | https://github.com/h2oai/h2o-3/blob/dd62aaa1e7f680a8b16ee14bc66b0fb5195c2ad8/h2o-py/h2o/model/regression.py#L69-L78 | def h2o_median_absolute_error(y_actual, y_predicted):
"""
Median absolute error regression loss
:param y_actual: H2OFrame of actual response.
:param y_predicted: H2OFrame of predicted response.
:returns: median absolute error loss (best is 0.0)
"""
ModelBase._check_targets(y_actual, y_predi... | [
"def",
"h2o_median_absolute_error",
"(",
"y_actual",
",",
"y_predicted",
")",
":",
"ModelBase",
".",
"_check_targets",
"(",
"y_actual",
",",
"y_predicted",
")",
"return",
"(",
"y_predicted",
"-",
"y_actual",
")",
".",
"abs",
"(",
")",
".",
"median",
"(",
")"... | Median absolute error regression loss
:param y_actual: H2OFrame of actual response.
:param y_predicted: H2OFrame of predicted response.
:returns: median absolute error loss (best is 0.0) | [
"Median",
"absolute",
"error",
"regression",
"loss"
] | python | test | 36.7 |
tomasbasham/dominos | dominos/api.py | https://github.com/tomasbasham/dominos/blob/59729a8bdca0ae30a84115a0e93e9b1f259faf0e/dominos/api.py#L224-L236 | def process_payment(self):
'''
Proceed with payment using the payment method selected earlier.
:return: A response having processes the payment.
:rtype: requests.Response
'''
params = {
'__RequestVerificationToken': self.session.cookies,
'method':... | [
"def",
"process_payment",
"(",
"self",
")",
":",
"params",
"=",
"{",
"'__RequestVerificationToken'",
":",
"self",
".",
"session",
".",
"cookies",
",",
"'method'",
":",
"'submit'",
"}",
"return",
"self",
".",
"__post",
"(",
"'/PaymentOptions/Proceed'",
",",
"js... | Proceed with payment using the payment method selected earlier.
:return: A response having processes the payment.
:rtype: requests.Response | [
"Proceed",
"with",
"payment",
"using",
"the",
"payment",
"method",
"selected",
"earlier",
"."
] | python | test | 30.384615 |
chimera0/accel-brain-code | Generative-Adversarial-Networks/pygan/generativemodel/autoencodermodel/encoder_decoder_model.py | https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Generative-Adversarial-Networks/pygan/generativemodel/autoencodermodel/encoder_decoder_model.py#L68-L78 | def draw(self):
'''
Draws samples from the `fake` distribution.
Returns:
`np.ndarray` of samples.
'''
observed_arr = self.noise_sampler.generate()
_ = self.__encoder_decoder_controller.encoder.inference(observed_arr)
arr = self.__encoder_deco... | [
"def",
"draw",
"(",
"self",
")",
":",
"observed_arr",
"=",
"self",
".",
"noise_sampler",
".",
"generate",
"(",
")",
"_",
"=",
"self",
".",
"__encoder_decoder_controller",
".",
"encoder",
".",
"inference",
"(",
"observed_arr",
")",
"arr",
"=",
"self",
".",
... | Draws samples from the `fake` distribution.
Returns:
`np.ndarray` of samples. | [
"Draws",
"samples",
"from",
"the",
"fake",
"distribution",
".",
"Returns",
":",
"np",
".",
"ndarray",
"of",
"samples",
"."
] | python | train | 33.909091 |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L1887-L1902 | def set_default_unit_all(self, twig=None, unit=None, **kwargs):
"""
TODO: add documentation
"""
if twig is not None and unit is None:
# then try to support value as the first argument if no matches with twigs
if isinstance(unit, u.Unit) or not isinstance(twig, str... | [
"def",
"set_default_unit_all",
"(",
"self",
",",
"twig",
"=",
"None",
",",
"unit",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"twig",
"is",
"not",
"None",
"and",
"unit",
"is",
"None",
":",
"# then try to support value as the first argument if no mat... | TODO: add documentation | [
"TODO",
":",
"add",
"documentation"
] | python | train | 38.5 |
keras-rl/keras-rl | rl/callbacks.py | https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L81-L89 | def on_step_end(self, step, logs={}):
""" Called at end of each step for each callback in callbackList"""
for callback in self.callbacks:
# Check if callback supports the more appropriate `on_step_end` callback.
# If not, fall back to `on_batch_end` to be compatible with built-in... | [
"def",
"on_step_end",
"(",
"self",
",",
"step",
",",
"logs",
"=",
"{",
"}",
")",
":",
"for",
"callback",
"in",
"self",
".",
"callbacks",
":",
"# Check if callback supports the more appropriate `on_step_end` callback.",
"# If not, fall back to `on_batch_end` to be compatible... | Called at end of each step for each callback in callbackList | [
"Called",
"at",
"end",
"of",
"each",
"step",
"for",
"each",
"callback",
"in",
"callbackList"
] | python | train | 57.888889 |
mlperf/training | rnn_translator/pytorch/seq2seq/inference/inference.py | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/inference/inference.py#L87-L145 | def run(self, calc_bleu=True, epoch=None, iteration=None, eval_path=None,
summary=False, reference_path=None):
"""
Runs translation on test dataset.
:param calc_bleu: if True compares results with reference and computes
BLEU score
:param epoch: index of the curre... | [
"def",
"run",
"(",
"self",
",",
"calc_bleu",
"=",
"True",
",",
"epoch",
"=",
"None",
",",
"iteration",
"=",
"None",
",",
"eval_path",
"=",
"None",
",",
"summary",
"=",
"False",
",",
"reference_path",
"=",
"None",
")",
":",
"if",
"self",
".",
"cuda",
... | Runs translation on test dataset.
:param calc_bleu: if True compares results with reference and computes
BLEU score
:param epoch: index of the current epoch
:param iteration: index of the current iteration
:param eval_path: path to the file for saving results
:param ... | [
"Runs",
"translation",
"on",
"test",
"dataset",
"."
] | python | train | 37.033898 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.