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 |
|---|---|---|---|---|---|---|---|---|---|
ajenhl/tacl | tacl/results.py | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L875-L880 | def reciprocal_remove(self):
"""Removes results rows for which the n-gram is not present in
at least one text in each labelled set of texts."""
self._logger.info(
'Removing n-grams that are not attested in all labels')
self._matches = self._reciprocal_remove(self._matches) | [
"def",
"reciprocal_remove",
"(",
"self",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'Removing n-grams that are not attested in all labels'",
")",
"self",
".",
"_matches",
"=",
"self",
".",
"_reciprocal_remove",
"(",
"self",
".",
"_matches",
")"
] | Removes results rows for which the n-gram is not present in
at least one text in each labelled set of texts. | [
"Removes",
"results",
"rows",
"for",
"which",
"the",
"n",
"-",
"gram",
"is",
"not",
"present",
"in",
"at",
"least",
"one",
"text",
"in",
"each",
"labelled",
"set",
"of",
"texts",
"."
] | python | train | 52 |
agile-geoscience/welly | welly/utils.py | https://github.com/agile-geoscience/welly/blob/ed4c991011d6290938fef365553041026ba29f42/welly/utils.py#L54-L62 | def sharey(axes):
"""
Shared axes limits without shared locators, ticks, etc.
By Joe Kington
"""
linker = Linker(axes)
for ax in axes:
ax._linker = linker | [
"def",
"sharey",
"(",
"axes",
")",
":",
"linker",
"=",
"Linker",
"(",
"axes",
")",
"for",
"ax",
"in",
"axes",
":",
"ax",
".",
"_linker",
"=",
"linker"
] | Shared axes limits without shared locators, ticks, etc.
By Joe Kington | [
"Shared",
"axes",
"limits",
"without",
"shared",
"locators",
"ticks",
"etc",
"."
] | python | train | 19.888889 |
zwischenloesung/ardu-report-lib | libardurep/datareporter.py | https://github.com/zwischenloesung/ardu-report-lib/blob/51bd4a07e036065aafcb1273b151bea3fdfa50fa/libardurep/datareporter.py#L68-L87 | def log_post(self, url=None, credentials=None, do_verify_certificate=True):
"""
Write to a remote host via HTTP POST
"""
if url is None:
url = self.url
if credentials is None:
credentials = self.credentials
if do_verify_certificate is None:
... | [
"def",
"log_post",
"(",
"self",
",",
"url",
"=",
"None",
",",
"credentials",
"=",
"None",
",",
"do_verify_certificate",
"=",
"True",
")",
":",
"if",
"url",
"is",
"None",
":",
"url",
"=",
"self",
".",
"url",
"if",
"credentials",
"is",
"None",
":",
"cr... | Write to a remote host via HTTP POST | [
"Write",
"to",
"a",
"remote",
"host",
"via",
"HTTP",
"POST"
] | python | valid | 42.3 |
evhub/coconut | coconut/main.py | https://github.com/evhub/coconut/blob/ff97177344e7604e89a0a98a977a87ed2a56fc6d/coconut/main.py#L24-L29 | def add_coconut_to_path():
"""Adds coconut to sys.path if it isn't there already."""
try:
import coconut # NOQA
except ImportError:
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | [
"def",
"add_coconut_to_path",
"(",
")",
":",
"try",
":",
"import",
"coconut",
"# NOQA",
"except",
"ImportError",
":",
"sys",
".",
"path",
".",
"insert",
"(",
"0",
",",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"o... | Adds coconut to sys.path if it isn't there already. | [
"Adds",
"coconut",
"to",
"sys",
".",
"path",
"if",
"it",
"isn",
"t",
"there",
"already",
"."
] | python | train | 39.166667 |
tensorflow/tensor2tensor | tensor2tensor/layers/modalities.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/modalities.py#L128-L173 | def audio_bottom(x, model_hparams, vocab_size):
"""Transform input from data space to model space.
Args:
x: A Tensor with shape [batch, ...]
model_hparams: HParams, model hyperparmeters.
vocab_size: int, vocabulary size.
Returns:
body_input: A Tensor with shape [batch, ?, ?,
model_hparams.... | [
"def",
"audio_bottom",
"(",
"x",
",",
"model_hparams",
",",
"vocab_size",
")",
":",
"del",
"vocab_size",
"# unused arg",
"inputs",
"=",
"x",
"with",
"tf",
".",
"variable_scope",
"(",
"\"audio_modality\"",
")",
":",
"# TODO(aidangomez): Will need to sort out a better a... | Transform input from data space to model space.
Args:
x: A Tensor with shape [batch, ...]
model_hparams: HParams, model hyperparmeters.
vocab_size: int, vocabulary size.
Returns:
body_input: A Tensor with shape [batch, ?, ?,
model_hparams.hidden_size]. | [
"Transform",
"input",
"from",
"data",
"space",
"to",
"model",
"space",
"."
] | python | train | 35.586957 |
googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/transaction.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/transaction.py#L164-L181 | def _rollback(self):
"""Roll back the transaction.
Raises:
ValueError: If no transaction is in progress.
"""
if not self.in_progress:
raise ValueError(_CANT_ROLLBACK)
try:
# NOTE: The response is just ``google.protobuf.Empty``.
se... | [
"def",
"_rollback",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"in_progress",
":",
"raise",
"ValueError",
"(",
"_CANT_ROLLBACK",
")",
"try",
":",
"# NOTE: The response is just ``google.protobuf.Empty``.",
"self",
".",
"_client",
".",
"_firestore_api",
".",
"... | Roll back the transaction.
Raises:
ValueError: If no transaction is in progress. | [
"Roll",
"back",
"the",
"transaction",
"."
] | python | train | 29.111111 |
osrg/ryu | ryu/services/protocols/zebra/client/zclient.py | https://github.com/osrg/ryu/blob/6f906e72c92e10bd0264c9b91a2f7bb85b97780c/ryu/services/protocols/zebra/client/zclient.py#L38-L65 | def create_connection(address):
"""
Wrapper for socket.create_connection() function.
If *address* (a 2-tuple ``(host, port)``) contains a valid IPv4/v6
address, passes *address* to socket.create_connection().
If *host* is valid path to Unix Domain socket, tries to connect to
the server listenin... | [
"def",
"create_connection",
"(",
"address",
")",
":",
"host",
",",
"_port",
"=",
"address",
"if",
"ip",
".",
"valid_ipv4",
"(",
"host",
")",
"or",
"ip",
".",
"valid_ipv6",
"(",
"host",
")",
":",
"return",
"socket",
".",
"create_connection",
"(",
"address... | Wrapper for socket.create_connection() function.
If *address* (a 2-tuple ``(host, port)``) contains a valid IPv4/v6
address, passes *address* to socket.create_connection().
If *host* is valid path to Unix Domain socket, tries to connect to
the server listening on the given socket.
:param address: ... | [
"Wrapper",
"for",
"socket",
".",
"create_connection",
"()",
"function",
"."
] | python | train | 33.071429 |
lk-geimfari/mimesis | mimesis/providers/person.py | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/person.py#L439-L455 | def telephone(self, mask: str = '', placeholder: str = '#') -> str:
"""Generate a random phone number.
:param mask: Mask for formatting number.
:param placeholder: A placeholder for a mask (default is #).
:return: Phone number.
:Example:
+7-(963)-409-11-22.
... | [
"def",
"telephone",
"(",
"self",
",",
"mask",
":",
"str",
"=",
"''",
",",
"placeholder",
":",
"str",
"=",
"'#'",
")",
"->",
"str",
":",
"if",
"not",
"mask",
":",
"code",
"=",
"self",
".",
"random",
".",
"choice",
"(",
"CALLING_CODES",
")",
"default... | Generate a random phone number.
:param mask: Mask for formatting number.
:param placeholder: A placeholder for a mask (default is #).
:return: Phone number.
:Example:
+7-(963)-409-11-22. | [
"Generate",
"a",
"random",
"phone",
"number",
"."
] | python | train | 36.117647 |
tnkteja/myhelp | virtualEnvironment/lib/python2.7/site-packages/coverage/html.py | https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/html.py#L23-L41 | def data_filename(fname, pkgdir=""):
"""Return the path to a data file of ours.
The file is searched for on `STATIC_PATH`, and the first place it's found,
is returned.
Each directory in `STATIC_PATH` is searched as-is, and also, if `pkgdir`
is provided, at that subdirectory.
"""
for stati... | [
"def",
"data_filename",
"(",
"fname",
",",
"pkgdir",
"=",
"\"\"",
")",
":",
"for",
"static_dir",
"in",
"STATIC_PATH",
":",
"static_filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"static_dir",
",",
"fname",
")",
"if",
"os",
".",
"path",
".",
"exis... | Return the path to a data file of ours.
The file is searched for on `STATIC_PATH`, and the first place it's found,
is returned.
Each directory in `STATIC_PATH` is searched as-is, and also, if `pkgdir`
is provided, at that subdirectory. | [
"Return",
"the",
"path",
"to",
"a",
"data",
"file",
"of",
"ours",
"."
] | python | test | 37.052632 |
tanghaibao/goatools | goatools/go_enrichment.py | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/go_enrichment.py#L160-L164 | def get_prtflds_default(self):
"""Get default fields."""
return self._fldsdefprt[:-1] + \
["p_{M}".format(M=m.fieldname) for m in self.method_flds] + \
[self._fldsdefprt[-1]] | [
"def",
"get_prtflds_default",
"(",
"self",
")",
":",
"return",
"self",
".",
"_fldsdefprt",
"[",
":",
"-",
"1",
"]",
"+",
"[",
"\"p_{M}\"",
".",
"format",
"(",
"M",
"=",
"m",
".",
"fieldname",
")",
"for",
"m",
"in",
"self",
".",
"method_flds",
"]",
... | Get default fields. | [
"Get",
"default",
"fields",
"."
] | python | train | 43.2 |
joelfrederico/SciSalt | scisalt/matplotlib/axesfontsize.py | https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/matplotlib/axesfontsize.py#L1-L7 | def axesfontsize(ax, fontsize):
"""
Change the font size for the title, x and y labels, and x and y tick labels for axis *ax* to *fontsize*.
"""
items = ([ax.title, ax.xaxis.label, ax.yaxis.label] + ax.get_xticklabels() + ax.get_yticklabels())
for item in items:
item.set_fontsize(fontsize) | [
"def",
"axesfontsize",
"(",
"ax",
",",
"fontsize",
")",
":",
"items",
"=",
"(",
"[",
"ax",
".",
"title",
",",
"ax",
".",
"xaxis",
".",
"label",
",",
"ax",
".",
"yaxis",
".",
"label",
"]",
"+",
"ax",
".",
"get_xticklabels",
"(",
")",
"+",
"ax",
... | Change the font size for the title, x and y labels, and x and y tick labels for axis *ax* to *fontsize*. | [
"Change",
"the",
"font",
"size",
"for",
"the",
"title",
"x",
"and",
"y",
"labels",
"and",
"x",
"and",
"y",
"tick",
"labels",
"for",
"axis",
"*",
"ax",
"*",
"to",
"*",
"fontsize",
"*",
"."
] | python | valid | 44.571429 |
Duke-GCB/DukeDSClient | ddsc/core/util.py | https://github.com/Duke-GCB/DukeDSClient/blob/117f68fb9bae82e4c81ea487ad5d61ac350f3726/ddsc/core/util.py#L350-L360 | def verify_file_private(filename):
"""
Raises ValueError the file permissions allow group/other
On windows this never raises due to the implementation of stat.
"""
if platform.system().upper() != 'WINDOWS':
filename = os.path.expanduser(filename)
if os.path.exists(filename):
... | [
"def",
"verify_file_private",
"(",
"filename",
")",
":",
"if",
"platform",
".",
"system",
"(",
")",
".",
"upper",
"(",
")",
"!=",
"'WINDOWS'",
":",
"filename",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"filename",
")",
"if",
"os",
".",
"path",
... | Raises ValueError the file permissions allow group/other
On windows this never raises due to the implementation of stat. | [
"Raises",
"ValueError",
"the",
"file",
"permissions",
"allow",
"group",
"/",
"other",
"On",
"windows",
"this",
"never",
"raises",
"due",
"to",
"the",
"implementation",
"of",
"stat",
"."
] | python | train | 42.636364 |
textbook/aslack | aslack/slack_bot/handler.py | https://github.com/textbook/aslack/blob/9ac6a44e4464180109fa4be130ad7a980a9d1acc/aslack/slack_bot/handler.py#L22-L40 | def description(self):
"""A user-friendly description of the handler.
Returns:
:py:class:`str`: The handler's description.
"""
if self._description is None:
text = '\n'.join(self.__doc__.splitlines()[1:]).strip()
lines = []
for line in map(... | [
"def",
"description",
"(",
"self",
")",
":",
"if",
"self",
".",
"_description",
"is",
"None",
":",
"text",
"=",
"'\\n'",
".",
"join",
"(",
"self",
".",
"__doc__",
".",
"splitlines",
"(",
")",
"[",
"1",
":",
"]",
")",
".",
"strip",
"(",
")",
"line... | A user-friendly description of the handler.
Returns:
:py:class:`str`: The handler's description. | [
"A",
"user",
"-",
"friendly",
"description",
"of",
"the",
"handler",
"."
] | python | valid | 33.368421 |
coursera-dl/coursera-dl | coursera/cookies.py | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/cookies.py#L258-L276 | def find_cookies_for_class(cookies_file, class_name):
"""
Return a RequestsCookieJar containing the cookies for
.coursera.org and class.coursera.org found in the given cookies_file.
"""
path = "/" + class_name
def cookies_filter(c):
return c.domain == ".coursera.org" \
or (... | [
"def",
"find_cookies_for_class",
"(",
"cookies_file",
",",
"class_name",
")",
":",
"path",
"=",
"\"/\"",
"+",
"class_name",
"def",
"cookies_filter",
"(",
"c",
")",
":",
"return",
"c",
".",
"domain",
"==",
"\".coursera.org\"",
"or",
"(",
"c",
".",
"domain",
... | Return a RequestsCookieJar containing the cookies for
.coursera.org and class.coursera.org found in the given cookies_file. | [
"Return",
"a",
"RequestsCookieJar",
"containing",
"the",
"cookies",
"for",
".",
"coursera",
".",
"org",
"and",
"class",
".",
"coursera",
".",
"org",
"found",
"in",
"the",
"given",
"cookies_file",
"."
] | python | train | 28.052632 |
apache/incubator-mxnet | example/capsnet/capsulenet.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/capsnet/capsulenet.py#L39-L100 | def capsnet(batch_size, n_class, num_routing, recon_loss_weight):
"""Create CapsNet"""
# data.shape = [batch_size, 1, 28, 28]
data = mx.sym.Variable('data')
input_shape = (1, 28, 28)
# Conv2D layer
# net.shape = [batch_size, 256, 20, 20]
conv1 = mx.sym.Convolution(data=data,
... | [
"def",
"capsnet",
"(",
"batch_size",
",",
"n_class",
",",
"num_routing",
",",
"recon_loss_weight",
")",
":",
"# data.shape = [batch_size, 1, 28, 28]",
"data",
"=",
"mx",
".",
"sym",
".",
"Variable",
"(",
"'data'",
")",
"input_shape",
"=",
"(",
"1",
",",
"28",
... | Create CapsNet | [
"Create",
"CapsNet"
] | python | train | 48.758065 |
pandas-dev/pandas | pandas/io/sql.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/sql.py#L982-L1029 | def read_table(self, table_name, index_col=None, coerce_float=True,
parse_dates=None, columns=None, schema=None,
chunksize=None):
"""Read SQL database table into a DataFrame.
Parameters
----------
table_name : string
Name of SQL table in... | [
"def",
"read_table",
"(",
"self",
",",
"table_name",
",",
"index_col",
"=",
"None",
",",
"coerce_float",
"=",
"True",
",",
"parse_dates",
"=",
"None",
",",
"columns",
"=",
"None",
",",
"schema",
"=",
"None",
",",
"chunksize",
"=",
"None",
")",
":",
"ta... | Read SQL database table into a DataFrame.
Parameters
----------
table_name : string
Name of SQL table in database.
index_col : string, optional, default: None
Column to set as index.
coerce_float : boolean, default True
Attempts to convert val... | [
"Read",
"SQL",
"database",
"table",
"into",
"a",
"DataFrame",
"."
] | python | train | 43.104167 |
shakefu/pyconfig | pyconfig/scripts.py | https://github.com/shakefu/pyconfig/blob/000cb127db51e03cb4070aae6943e956193cbad5/pyconfig/scripts.py#L124-L136 | def as_live(self):
"""
Return this call as if it were being assigned in a pyconfig namespace,
but load the actual value currently available in pyconfig.
"""
key = self.get_key()
default = pyconfig.get(key)
if default:
default = repr(default)
e... | [
"def",
"as_live",
"(",
"self",
")",
":",
"key",
"=",
"self",
".",
"get_key",
"(",
")",
"default",
"=",
"pyconfig",
".",
"get",
"(",
"key",
")",
"if",
"default",
":",
"default",
"=",
"repr",
"(",
"default",
")",
"else",
":",
"default",
"=",
"self",
... | Return this call as if it were being assigned in a pyconfig namespace,
but load the actual value currently available in pyconfig. | [
"Return",
"this",
"call",
"as",
"if",
"it",
"were",
"being",
"assigned",
"in",
"a",
"pyconfig",
"namespace",
"but",
"load",
"the",
"actual",
"value",
"currently",
"available",
"in",
"pyconfig",
"."
] | python | valid | 31.076923 |
welbornprod/colr | colr/trans.py | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/trans.py#L552-L556 | def _init_hex(self, hexval: str) -> None:
""" Initialize from a hex value string. """
self.hexval = hex2termhex(fix_hex(hexval))
self.code = hex2term(self.hexval)
self.rgb = hex2rgb(self.hexval) | [
"def",
"_init_hex",
"(",
"self",
",",
"hexval",
":",
"str",
")",
"->",
"None",
":",
"self",
".",
"hexval",
"=",
"hex2termhex",
"(",
"fix_hex",
"(",
"hexval",
")",
")",
"self",
".",
"code",
"=",
"hex2term",
"(",
"self",
".",
"hexval",
")",
"self",
"... | Initialize from a hex value string. | [
"Initialize",
"from",
"a",
"hex",
"value",
"string",
"."
] | python | train | 44.4 |
cgearhart/Resound | identify.py | https://github.com/cgearhart/Resound/blob/83a15be0ce2dc13003574c6039f8a1ad87734bc2/identify.py#L38-L63 | def main(input_filename, format):
"""
Calculate the fingerprint hashses of the referenced audio file and save
to disk as a pickle file
"""
# open the file & convert to wav
song_data = AudioSegment.from_file(input_filename, format=format)
song_data = song_data.set_channels(1) # convert to m... | [
"def",
"main",
"(",
"input_filename",
",",
"format",
")",
":",
"# open the file & convert to wav",
"song_data",
"=",
"AudioSegment",
".",
"from_file",
"(",
"input_filename",
",",
"format",
"=",
"format",
")",
"song_data",
"=",
"song_data",
".",
"set_channels",
"("... | Calculate the fingerprint hashses of the referenced audio file and save
to disk as a pickle file | [
"Calculate",
"the",
"fingerprint",
"hashses",
"of",
"the",
"referenced",
"audio",
"file",
"and",
"save",
"to",
"disk",
"as",
"a",
"pickle",
"file"
] | python | train | 39.346154 |
mitsei/dlkit | dlkit/records/assessment/basic/wrong_answers.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/records/assessment/basic/wrong_answers.py#L63-L68 | def get_wrong_answer_ids(self):
"""provide this method to return only wrong answer ids"""
id_list = []
for answer in self.get_wrong_answers():
id_list.append(answer.get_id())
return IdList(id_list) | [
"def",
"get_wrong_answer_ids",
"(",
"self",
")",
":",
"id_list",
"=",
"[",
"]",
"for",
"answer",
"in",
"self",
".",
"get_wrong_answers",
"(",
")",
":",
"id_list",
".",
"append",
"(",
"answer",
".",
"get_id",
"(",
")",
")",
"return",
"IdList",
"(",
"id_... | provide this method to return only wrong answer ids | [
"provide",
"this",
"method",
"to",
"return",
"only",
"wrong",
"answer",
"ids"
] | python | train | 39.333333 |
DistrictDataLabs/yellowbrick | yellowbrick/utils/helpers.py | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/utils/helpers.py#L76-L99 | def is_monotonic(a, increasing=True):
"""
Tests whether a vector a has monotonicity.
Parameters
----------
a : array-like
Array that should be tested for monotonicity
increasing : bool, default: True
Test if the array is montonically increasing, otherwise test if the
ar... | [
"def",
"is_monotonic",
"(",
"a",
",",
"increasing",
"=",
"True",
")",
":",
"a",
"=",
"np",
".",
"asarray",
"(",
"a",
")",
"# ensure a is array-like",
"if",
"a",
".",
"ndim",
">",
"1",
":",
"raise",
"ValueError",
"(",
"\"not supported for multi-dimensonal arr... | Tests whether a vector a has monotonicity.
Parameters
----------
a : array-like
Array that should be tested for monotonicity
increasing : bool, default: True
Test if the array is montonically increasing, otherwise test if the
array is montonically decreasing. | [
"Tests",
"whether",
"a",
"vector",
"a",
"has",
"monotonicity",
"."
] | python | train | 26 |
pytorch/text | torchtext/data/iterator.py | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/data/iterator.py#L109-L125 | def init_epoch(self):
"""Set up the batch generator for a new epoch."""
if self._restored_from_state:
self.random_shuffler.random_state = self._random_state_this_epoch
else:
self._random_state_this_epoch = self.random_shuffler.random_state
self.create_batches()
... | [
"def",
"init_epoch",
"(",
"self",
")",
":",
"if",
"self",
".",
"_restored_from_state",
":",
"self",
".",
"random_shuffler",
".",
"random_state",
"=",
"self",
".",
"_random_state_this_epoch",
"else",
":",
"self",
".",
"_random_state_this_epoch",
"=",
"self",
".",... | Set up the batch generator for a new epoch. | [
"Set",
"up",
"the",
"batch",
"generator",
"for",
"a",
"new",
"epoch",
"."
] | python | train | 29.823529 |
timothydmorton/VESPA | vespa/stars/populations.py | https://github.com/timothydmorton/VESPA/blob/0446b54d48009f3655cfd1a3957ceea21d3adcaa/vespa/stars/populations.py#L685-L693 | def hidden_constraints(self):
"""
Constraints applied to the population, but temporarily removed.
"""
try:
return self._hidden_constraints
except AttributeError:
self._hidden_constraints = ConstraintDict()
return self._hidden_constraints | [
"def",
"hidden_constraints",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_hidden_constraints",
"except",
"AttributeError",
":",
"self",
".",
"_hidden_constraints",
"=",
"ConstraintDict",
"(",
")",
"return",
"self",
".",
"_hidden_constraints"
] | Constraints applied to the population, but temporarily removed. | [
"Constraints",
"applied",
"to",
"the",
"population",
"but",
"temporarily",
"removed",
"."
] | python | train | 33.888889 |
google/grr | grr/client/grr_response_client/vfs_handlers/registry.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/client/grr_response_client/vfs_handlers/registry.py#L258-L273 | def _Reg2Py(data, size, data_type):
"""Converts a Windows Registry value to the corresponding Python data type."""
if data_type == winreg.REG_DWORD:
if size == 0:
return 0
# DWORD is an unsigned 32-bit integer, see:
# https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-dtyp/262627d8-34... | [
"def",
"_Reg2Py",
"(",
"data",
",",
"size",
",",
"data_type",
")",
":",
"if",
"data_type",
"==",
"winreg",
".",
"REG_DWORD",
":",
"if",
"size",
"==",
"0",
":",
"return",
"0",
"# DWORD is an unsigned 32-bit integer, see:",
"# https://docs.microsoft.com/en-us/openspec... | Converts a Windows Registry value to the corresponding Python data type. | [
"Converts",
"a",
"Windows",
"Registry",
"value",
"to",
"the",
"corresponding",
"Python",
"data",
"type",
"."
] | python | train | 46.4375 |
petl-developers/petl | petl/transform/joins.py | https://github.com/petl-developers/petl/blob/1d33ca055f7e04e0d28a772041c9fd30c8d415d6/petl/transform/joins.py#L643-L682 | def lookupjoin(left, right, key=None, lkey=None, rkey=None, missing=None,
presorted=False, buffersize=None, tempdir=None, cache=True,
lprefix=None, rprefix=None):
"""
Perform a left join, but where the key is not unique in the right-hand
table, arbitrarily choose the first row ... | [
"def",
"lookupjoin",
"(",
"left",
",",
"right",
",",
"key",
"=",
"None",
",",
"lkey",
"=",
"None",
",",
"rkey",
"=",
"None",
",",
"missing",
"=",
"None",
",",
"presorted",
"=",
"False",
",",
"buffersize",
"=",
"None",
",",
"tempdir",
"=",
"None",
"... | Perform a left join, but where the key is not unique in the right-hand
table, arbitrarily choose the first row and ignore others. E.g.::
>>> import petl as etl
>>> table1 = [['id', 'color', 'cost'],
... [1, 'blue', 12],
... [2, 'red', 8],
... [3... | [
"Perform",
"a",
"left",
"join",
"but",
"where",
"the",
"key",
"is",
"not",
"unique",
"in",
"the",
"right",
"-",
"hand",
"table",
"arbitrarily",
"choose",
"the",
"first",
"row",
"and",
"ignore",
"others",
".",
"E",
".",
"g",
".",
"::"
] | python | train | 44.375 |
google/grumpy | third_party/stdlib/traceback.py | https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/traceback.py#L205-L212 | def _format_final_exc_line(etype, value):
"""Return a list of a single line -- normal case for format_exception_only"""
valuestr = _some_str(value)
if value is None or not valuestr:
line = "%s\n" % etype
else:
line = "%s: %s\n" % (etype, valuestr)
return line | [
"def",
"_format_final_exc_line",
"(",
"etype",
",",
"value",
")",
":",
"valuestr",
"=",
"_some_str",
"(",
"value",
")",
"if",
"value",
"is",
"None",
"or",
"not",
"valuestr",
":",
"line",
"=",
"\"%s\\n\"",
"%",
"etype",
"else",
":",
"line",
"=",
"\"%s: %s... | Return a list of a single line -- normal case for format_exception_only | [
"Return",
"a",
"list",
"of",
"a",
"single",
"line",
"--",
"normal",
"case",
"for",
"format_exception_only"
] | python | valid | 36 |
dschep/lambda-decorators | lambda_decorators.py | https://github.com/dschep/lambda-decorators/blob/9195914c8afe26843de9968d96dae6a89f061e8a/lambda_decorators.py#L324-L351 | def async_handler(handler):
"""
This decorator allows for use of async handlers by automatically running
them in an event loop. The loop is added to the context object for if the
handler needs it.
Usage::
>>> from lambda_decorators import async_handler
>>> async def foobar():
... | [
"def",
"async_handler",
"(",
"handler",
")",
":",
"@",
"wraps",
"(",
"handler",
")",
"def",
"wrapper",
"(",
"event",
",",
"context",
")",
":",
"context",
".",
"loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"return",
"context",
".",
"loop",
".... | This decorator allows for use of async handlers by automatically running
them in an event loop. The loop is added to the context object for if the
handler needs it.
Usage::
>>> from lambda_decorators import async_handler
>>> async def foobar():
... return 'foobar'
>>> @... | [
"This",
"decorator",
"allows",
"for",
"use",
"of",
"async",
"handlers",
"by",
"automatically",
"running",
"them",
"in",
"an",
"event",
"loop",
".",
"The",
"loop",
"is",
"added",
"to",
"the",
"context",
"object",
"for",
"if",
"the",
"handler",
"needs",
"it"... | python | train | 27.142857 |
pypa/pipenv | pipenv/vendor/distlib/database.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L407-L439 | def matches_requirement(self, req):
"""
Say if this instance matches (fulfills) a requirement.
:param req: The requirement to match.
:rtype req: str
:return: True if it matches, else False.
"""
# Requirement may contain extras - parse to lose those
# from ... | [
"def",
"matches_requirement",
"(",
"self",
",",
"req",
")",
":",
"# Requirement may contain extras - parse to lose those",
"# from what's passed to the matcher",
"r",
"=",
"parse_requirement",
"(",
"req",
")",
"scheme",
"=",
"get_scheme",
"(",
"self",
".",
"metadata",
"... | Say if this instance matches (fulfills) a requirement.
:param req: The requirement to match.
:rtype req: str
:return: True if it matches, else False. | [
"Say",
"if",
"this",
"instance",
"matches",
"(",
"fulfills",
")",
"a",
"requirement",
".",
":",
"param",
"req",
":",
"The",
"requirement",
"to",
"match",
".",
":",
"rtype",
"req",
":",
"str",
":",
"return",
":",
"True",
"if",
"it",
"matches",
"else",
... | python | train | 34.333333 |
twilio/twilio-python | twilio/jwt/client/__init__.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/jwt/client/__init__.py#L44-L55 | def allow_client_outgoing(self, application_sid, **kwargs):
"""
Allow the user of this token to make outgoing connections. Keyword arguments are passed
to the application.
:param str application_sid: Application to contact
"""
scope = ScopeURI('client', 'outgoing', {'app... | [
"def",
"allow_client_outgoing",
"(",
"self",
",",
"application_sid",
",",
"*",
"*",
"kwargs",
")",
":",
"scope",
"=",
"ScopeURI",
"(",
"'client'",
",",
"'outgoing'",
",",
"{",
"'appSid'",
":",
"application_sid",
"}",
")",
"if",
"kwargs",
":",
"scope",
".",... | Allow the user of this token to make outgoing connections. Keyword arguments are passed
to the application.
:param str application_sid: Application to contact | [
"Allow",
"the",
"user",
"of",
"this",
"token",
"to",
"make",
"outgoing",
"connections",
".",
"Keyword",
"arguments",
"are",
"passed",
"to",
"the",
"application",
"."
] | python | train | 39.166667 |
googledatalab/pydatalab | solutionbox/ml_workbench/xgboost/trainer/feature_transforms.py | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/xgboost/trainer/feature_transforms.py#L252-L314 | def make_preprocessing_fn(output_dir, features, keep_target):
"""Makes a preprocessing function.
Args:
output_dir: folder path that contains the vocab and stats files.
features: the features dict
Returns:
a function that takes a dict of input tensors
"""
def preprocessing_fn(inputs):
"""Prep... | [
"def",
"make_preprocessing_fn",
"(",
"output_dir",
",",
"features",
",",
"keep_target",
")",
":",
"def",
"preprocessing_fn",
"(",
"inputs",
")",
":",
"\"\"\"Preprocessing function.\n\n Args:\n inputs: dictionary of raw input tensors\n\n Returns:\n A dictionary of tran... | Makes a preprocessing function.
Args:
output_dir: folder path that contains the vocab and stats files.
features: the features dict
Returns:
a function that takes a dict of input tensors | [
"Makes",
"a",
"preprocessing",
"function",
"."
] | python | train | 35.52381 |
numenta/nupic | src/nupic/algorithms/knn_classifier.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/knn_classifier.py#L840-L870 | def getPattern(self, idx, sparseBinaryForm=False, cat=None):
"""Gets a training pattern either by index or category number.
:param idx: Index of the training pattern
:param sparseBinaryForm: If true, returns a list of the indices of the
non-zero bits in the training pattern
:param cat: If not... | [
"def",
"getPattern",
"(",
"self",
",",
"idx",
",",
"sparseBinaryForm",
"=",
"False",
",",
"cat",
"=",
"None",
")",
":",
"if",
"cat",
"is",
"not",
"None",
":",
"assert",
"idx",
"is",
"None",
"idx",
"=",
"self",
".",
"_categoryList",
".",
"index",
"(",... | Gets a training pattern either by index or category number.
:param idx: Index of the training pattern
:param sparseBinaryForm: If true, returns a list of the indices of the
non-zero bits in the training pattern
:param cat: If not None, get the first pattern belonging to category cat. If
t... | [
"Gets",
"a",
"training",
"pattern",
"either",
"by",
"index",
"or",
"category",
"number",
"."
] | python | valid | 29.516129 |
tanghaibao/goatools | goatools/cli/find_enrichment.py | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/cli/find_enrichment.py#L201-L214 | def _init_itemid2name(self):
"""Print gene symbols instead of gene IDs, if provided."""
if not hasattr(self.args, 'id2sym'):
return None
fin_id2sym = self.args.id2sym
if fin_id2sym is not None and os.path.exists(fin_id2sym):
id2sym = {}
cmpl = re.compi... | [
"def",
"_init_itemid2name",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
".",
"args",
",",
"'id2sym'",
")",
":",
"return",
"None",
"fin_id2sym",
"=",
"self",
".",
"args",
".",
"id2sym",
"if",
"fin_id2sym",
"is",
"not",
"None",
"and",
"os... | Print gene symbols instead of gene IDs, if provided. | [
"Print",
"gene",
"symbols",
"instead",
"of",
"gene",
"IDs",
"if",
"provided",
"."
] | python | train | 41.285714 |
robertchase/ergaleia | ergaleia/normalize_path.py | https://github.com/robertchase/ergaleia/blob/df8e9a4b18c563022a503faa27e822c9a5755490/ergaleia/normalize_path.py#L17-L65 | def normalize_path(path, filetype=None, has_filetype=True):
""" Convert dot-separated paths to directory paths
Allows non-python files to be placed in the PYTHONPATH and be referenced
using dot-notation instead of absolute or relative file-system paths.
If a text file, named test.txt was placed in a p... | [
"def",
"normalize_path",
"(",
"path",
",",
"filetype",
"=",
"None",
",",
"has_filetype",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"path",
",",
"str",
")",
":",
"return",
"path",
"if",
"'.'",
"in",
"path",
"and",
"os",
".",
"path",
".",
... | Convert dot-separated paths to directory paths
Allows non-python files to be placed in the PYTHONPATH and be referenced
using dot-notation instead of absolute or relative file-system paths.
If a text file, named test.txt was placed in a python repo named myprog in
the module named util, then:
... | [
"Convert",
"dot",
"-",
"separated",
"paths",
"to",
"directory",
"paths"
] | python | train | 40.102041 |
BlueBrain/hpcbench | hpcbench/toolbox/process.py | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/toolbox/process.py#L57-L74 | def physical_cpus():
"""Get cpus identifiers, for instance set(["0", "1", "2", "3"])
:return Number of physical CPUs available
:rtype: int
"""
if platform.system() == 'Darwin':
ncores = subprocess.check_output(
['/usr/sbin/sysctl', '-n', 'hw.ncpu'], shell=False
)
... | [
"def",
"physical_cpus",
"(",
")",
":",
"if",
"platform",
".",
"system",
"(",
")",
"==",
"'Darwin'",
":",
"ncores",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'/usr/sbin/sysctl'",
",",
"'-n'",
",",
"'hw.ncpu'",
"]",
",",
"shell",
"=",
"False",
")"... | Get cpus identifiers, for instance set(["0", "1", "2", "3"])
:return Number of physical CPUs available
:rtype: int | [
"Get",
"cpus",
"identifiers",
"for",
"instance",
"set",
"(",
"[",
"0",
"1",
"2",
"3",
"]",
")"
] | python | train | 30.277778 |
swistakm/graceful | src/graceful/validators.py | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/validators.py#L14-L28 | def min_validator(min_value):
"""Return validator function that ensures lower bound of a number.
Result validation function will validate the internal value of resource
instance field with the ``value >= min_value`` check
Args:
min_value: minimal value for new validator
"""
def valida... | [
"def",
"min_validator",
"(",
"min_value",
")",
":",
"def",
"validator",
"(",
"value",
")",
":",
"if",
"value",
"<",
"min_value",
":",
"raise",
"ValidationError",
"(",
"\"{} is not >= {}\"",
".",
"format",
"(",
"value",
",",
"min_value",
")",
")",
"return",
... | Return validator function that ensures lower bound of a number.
Result validation function will validate the internal value of resource
instance field with the ``value >= min_value`` check
Args:
min_value: minimal value for new validator | [
"Return",
"validator",
"function",
"that",
"ensures",
"lower",
"bound",
"of",
"a",
"number",
"."
] | python | train | 29.8 |
gem/oq-engine | openquake/hazardlib/geo/utils.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L214-L250 | def line_intersects_itself(lons, lats, closed_shape=False):
"""
Return ``True`` if line of points intersects itself.
Line with the last point repeating the first one considered
intersecting itself.
The line is defined by lists (or numpy arrays) of points'
longitudes and latitudes (depth is not ... | [
"def",
"line_intersects_itself",
"(",
"lons",
",",
"lats",
",",
"closed_shape",
"=",
"False",
")",
":",
"assert",
"len",
"(",
"lons",
")",
"==",
"len",
"(",
"lats",
")",
"if",
"len",
"(",
"lons",
")",
"<=",
"3",
":",
"# line can not intersect itself unless... | Return ``True`` if line of points intersects itself.
Line with the last point repeating the first one considered
intersecting itself.
The line is defined by lists (or numpy arrays) of points'
longitudes and latitudes (depth is not taken into account).
:param closed_shape:
If ``True`` the l... | [
"Return",
"True",
"if",
"line",
"of",
"points",
"intersects",
"itself",
".",
"Line",
"with",
"the",
"last",
"point",
"repeating",
"the",
"first",
"one",
"considered",
"intersecting",
"itself",
"."
] | python | train | 36.243243 |
reingart/gui2py | gui/windows/window.py | https://github.com/reingart/gui2py/blob/aca0a05f6fcde55c94ad7cc058671a06608b01a4/gui/windows/window.py#L124-L139 | def show(self, value=True, modal=None):
"Display or hide the window, optionally disabling all other windows"
self.wx_obj.Show(value)
if modal:
# disable all top level windows of this application (MakeModal)
disabler = wx.WindowDisabler(self.wx_obj)
# cre... | [
"def",
"show",
"(",
"self",
",",
"value",
"=",
"True",
",",
"modal",
"=",
"None",
")",
":",
"self",
".",
"wx_obj",
".",
"Show",
"(",
"value",
")",
"if",
"modal",
":",
"# disable all top level windows of this application (MakeModal)\r",
"disabler",
"=",
"wx",
... | Display or hide the window, optionally disabling all other windows | [
"Display",
"or",
"hide",
"the",
"window",
"optionally",
"disabling",
"all",
"other",
"windows"
] | python | test | 46 |
anchor/elasticsearchadmin | esadmin/elasticsearchadmin.py | https://github.com/anchor/elasticsearchadmin/blob/80b5adf79ead341ce0ded34119b087a343425983/esadmin/elasticsearchadmin.py#L239-L270 | def nontruncating_zip(*seqs):
"""Return a list of tuples, where each tuple contains the i-th
element from each of the argument sequences.
The returned list is as long as the longest argument sequence.
Shorter argument sequences will be represented in the output as
None paddi... | [
"def",
"nontruncating_zip",
"(",
"*",
"seqs",
")",
":",
"n_seqs",
"=",
"len",
"(",
"seqs",
")",
"tups",
"=",
"[",
"]",
"idx",
"=",
"0",
"while",
"True",
":",
"empties",
"=",
"0",
"tup",
"=",
"[",
"]",
"for",
"seq",
"in",
"seqs",
":",
"try",
":"... | Return a list of tuples, where each tuple contains the i-th
element from each of the argument sequences.
The returned list is as long as the longest argument sequence.
Shorter argument sequences will be represented in the output as
None padding elements:
nontruncating_z... | [
"Return",
"a",
"list",
"of",
"tuples",
"where",
"each",
"tuple",
"contains",
"the",
"i",
"-",
"th",
"element",
"from",
"each",
"of",
"the",
"argument",
"sequences",
"."
] | python | train | 27.9375 |
peterjc/flake8-rst-docstrings | flake8_rst_docstrings.py | https://github.com/peterjc/flake8-rst-docstrings/blob/b8b17d0317fc6728d5586553ab29a7d97e6417fd/flake8_rst_docstrings.py#L587-L599 | def parse(self, filelike, filename):
"""Parse the given file-like object and return its Module object."""
self.log = log
self.source = filelike.readlines()
src = "".join(self.source)
# This may raise a SyntaxError:
compile(src, filename, "exec")
self.stream = Toke... | [
"def",
"parse",
"(",
"self",
",",
"filelike",
",",
"filename",
")",
":",
"self",
".",
"log",
"=",
"log",
"self",
".",
"source",
"=",
"filelike",
".",
"readlines",
"(",
")",
"src",
"=",
"\"\"",
".",
"join",
"(",
"self",
".",
"source",
")",
"# This m... | Parse the given file-like object and return its Module object. | [
"Parse",
"the",
"given",
"file",
"-",
"like",
"object",
"and",
"return",
"its",
"Module",
"object",
"."
] | python | valid | 38.461538 |
earlye/nephele | nephele/AwsStack.py | https://github.com/earlye/nephele/blob/a7dadc68f4124671457f09119419978c4d22013e/nephele/AwsStack.py#L152-L165 | def do_asg(self,args):
"""Go to the specified auto scaling group. asg -h for detailed help"""
parser = CommandArgumentParser("asg")
parser.add_argument(dest='asg',help='asg index or name');
args = vars(parser.parse_args(args))
print "loading auto scaling group {}".format(args['a... | [
"def",
"do_asg",
"(",
"self",
",",
"args",
")",
":",
"parser",
"=",
"CommandArgumentParser",
"(",
"\"asg\"",
")",
"parser",
".",
"add_argument",
"(",
"dest",
"=",
"'asg'",
",",
"help",
"=",
"'asg index or name'",
")",
"args",
"=",
"vars",
"(",
"parser",
... | Go to the specified auto scaling group. asg -h for detailed help | [
"Go",
"to",
"the",
"specified",
"auto",
"scaling",
"group",
".",
"asg",
"-",
"h",
"for",
"detailed",
"help"
] | python | train | 48.571429 |
SiLab-Bonn/pyBAR | pybar/analysis/analysis.py | https://github.com/SiLab-Bonn/pyBAR/blob/5ad95bbcd41cd358825823fb78f396cfce23593e/pybar/analysis/analysis.py#L428-L482 | def histogram_cluster_table(analyzed_data_file, output_file, chunk_size=10000000):
'''Reads in the cluster info table in chunks and histograms the seed pixels into one occupancy array.
The 3rd dimension of the occupancy array is the number of different scan parameters used
Parameters
----------
ana... | [
"def",
"histogram_cluster_table",
"(",
"analyzed_data_file",
",",
"output_file",
",",
"chunk_size",
"=",
"10000000",
")",
":",
"with",
"tb",
".",
"open_file",
"(",
"analyzed_data_file",
",",
"mode",
"=",
"\"r\"",
")",
"as",
"in_file_h5",
":",
"with",
"tb",
"."... | Reads in the cluster info table in chunks and histograms the seed pixels into one occupancy array.
The 3rd dimension of the occupancy array is the number of different scan parameters used
Parameters
----------
analyzed_data_file : string
HDF5 filename of the file containing the cluster table. I... | [
"Reads",
"in",
"the",
"cluster",
"info",
"table",
"in",
"chunks",
"and",
"histograms",
"the",
"seed",
"pixels",
"into",
"one",
"occupancy",
"array",
".",
"The",
"3rd",
"dimension",
"of",
"the",
"occupancy",
"array",
"is",
"the",
"number",
"of",
"different",
... | python | train | 60.781818 |
SHDShim/pytheos | pytheos/eqn_anharmonic.py | https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_anharmonic.py#L6-L29 | def zharkov_panh(v, temp, v0, a0, m, n, z, t_ref=300.,
three_r=3. * constants.R):
"""
calculate pressure from anharmonicity for Zharkov equation
the equation is from Dorogokupets 2015
:param v: unit-cell volume in A^3
:param temp: temperature in K
:param v0: unit-cell volume in... | [
"def",
"zharkov_panh",
"(",
"v",
",",
"temp",
",",
"v0",
",",
"a0",
",",
"m",
",",
"n",
",",
"z",
",",
"t_ref",
"=",
"300.",
",",
"three_r",
"=",
"3.",
"*",
"constants",
".",
"R",
")",
":",
"v_mol",
"=",
"vol_uc2mol",
"(",
"v",
",",
"z",
")",... | calculate pressure from anharmonicity for Zharkov equation
the equation is from Dorogokupets 2015
:param v: unit-cell volume in A^3
:param temp: temperature in K
:param v0: unit-cell volume in A^3 at 1 bar
:param a0: parameter in K-1 for the Zharkov equation
:param m: parameter for the Zharkov ... | [
"calculate",
"pressure",
"from",
"anharmonicity",
"for",
"Zharkov",
"equation",
"the",
"equation",
"is",
"from",
"Dorogokupets",
"2015"
] | python | train | 34.208333 |
datascopeanalytics/traces | traces/timeseries.py | https://github.com/datascopeanalytics/traces/blob/420611151a05fea88a07bc5200fefffdc37cc95b/traces/timeseries.py#L206-L224 | def set_interval(self, start, end, value, compact=False):
"""Set the value for the time series on an interval. If compact is
True, only set the value if it's different from what it would
be anyway.
"""
# for each interval to render
for i, (s, e, v) in enumerate(self.iter... | [
"def",
"set_interval",
"(",
"self",
",",
"start",
",",
"end",
",",
"value",
",",
"compact",
"=",
"False",
")",
":",
"# for each interval to render",
"for",
"i",
",",
"(",
"s",
",",
"e",
",",
"v",
")",
"in",
"enumerate",
"(",
"self",
".",
"iterperiods",... | Set the value for the time series on an interval. If compact is
True, only set the value if it's different from what it would
be anyway. | [
"Set",
"the",
"value",
"for",
"the",
"time",
"series",
"on",
"an",
"interval",
".",
"If",
"compact",
"is",
"True",
"only",
"set",
"the",
"value",
"if",
"it",
"s",
"different",
"from",
"what",
"it",
"would",
"be",
"anyway",
"."
] | python | train | 40.684211 |
merll/docker-map | dockermap/client/cli.py | https://github.com/merll/docker-map/blob/e14fe86a6ff5c33d121eb2f9157e9359cb80dd02/dockermap/client/cli.py#L258-L270 | def parse_volumes_output(out):
"""
Parses the output of the Docker CLI 'docker volume ls' and returns it in the format similar to the Docker API.
:param out: CLI output.
:type out: unicode | str
:return: Parsed result.
:rtype: list[dict]
"""
if not out:
return []
line_iter =... | [
"def",
"parse_volumes_output",
"(",
"out",
")",
":",
"if",
"not",
"out",
":",
"return",
"[",
"]",
"line_iter",
"=",
"islice",
"(",
"out",
".",
"splitlines",
"(",
")",
",",
"1",
",",
"None",
")",
"# Skip header",
"return",
"list",
"(",
"map",
"(",
"_v... | Parses the output of the Docker CLI 'docker volume ls' and returns it in the format similar to the Docker API.
:param out: CLI output.
:type out: unicode | str
:return: Parsed result.
:rtype: list[dict] | [
"Parses",
"the",
"output",
"of",
"the",
"Docker",
"CLI",
"docker",
"volume",
"ls",
"and",
"returns",
"it",
"in",
"the",
"format",
"similar",
"to",
"the",
"Docker",
"API",
"."
] | python | train | 31 |
saltstack/salt | salt/state.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L3487-L3536 | def verify_tops(self, tops):
'''
Verify the contents of the top file data
'''
errors = []
if not isinstance(tops, dict):
errors.append('Top data was not formed as a dict')
# No further checks will work, bail out
return errors
for salten... | [
"def",
"verify_tops",
"(",
"self",
",",
"tops",
")",
":",
"errors",
"=",
"[",
"]",
"if",
"not",
"isinstance",
"(",
"tops",
",",
"dict",
")",
":",
"errors",
".",
"append",
"(",
"'Top data was not formed as a dict'",
")",
"# No further checks will work, bail out",... | Verify the contents of the top file data | [
"Verify",
"the",
"contents",
"of",
"the",
"top",
"file",
"data"
] | python | train | 42.98 |
Qiskit/qiskit-terra | qiskit/tools/qi/qi.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/qi/qi.py#L95-L123 | def __partial_trace_vec(vec, trace_systems, dimensions, reverse=True):
"""
Partial trace over subsystems of multi-partite vector.
Args:
vec (vector_like): complex vector N
trace_systems (list(int)): a list of subsystems (starting from 0) to
trace over.
... | [
"def",
"__partial_trace_vec",
"(",
"vec",
",",
"trace_systems",
",",
"dimensions",
",",
"reverse",
"=",
"True",
")",
":",
"# trace sys positions",
"if",
"reverse",
":",
"dimensions",
"=",
"dimensions",
"[",
":",
":",
"-",
"1",
"]",
"trace_systems",
"=",
"len... | Partial trace over subsystems of multi-partite vector.
Args:
vec (vector_like): complex vector N
trace_systems (list(int)): a list of subsystems (starting from 0) to
trace over.
dimensions (list(int)): a list of the dimensions of the subsystems.
... | [
"Partial",
"trace",
"over",
"subsystems",
"of",
"multi",
"-",
"partite",
"vector",
"."
] | python | test | 38.931034 |
mardix/Mocha | mocha/contrib/auth/models.py | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/auth/models.py#L166-L170 | def get_by_username(cls, username):
"""
Return a User by email address
"""
return cls.query().filter(cls.username == username).first() | [
"def",
"get_by_username",
"(",
"cls",
",",
"username",
")",
":",
"return",
"cls",
".",
"query",
"(",
")",
".",
"filter",
"(",
"cls",
".",
"username",
"==",
"username",
")",
".",
"first",
"(",
")"
] | Return a User by email address | [
"Return",
"a",
"User",
"by",
"email",
"address"
] | python | train | 32.4 |
gem/oq-engine | openquake/hazardlib/site.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/site.py#L183-L230 | def from_points(cls, lons, lats, depths=None, sitemodel=None,
req_site_params=()):
"""
Build the site collection from
:param lons:
a sequence of longitudes
:param lats:
a sequence of latitudes
:param depths:
a sequence of d... | [
"def",
"from_points",
"(",
"cls",
",",
"lons",
",",
"lats",
",",
"depths",
"=",
"None",
",",
"sitemodel",
"=",
"None",
",",
"req_site_params",
"=",
"(",
")",
")",
":",
"assert",
"len",
"(",
"lons",
")",
"<",
"U32LIMIT",
",",
"len",
"(",
"lons",
")"... | Build the site collection from
:param lons:
a sequence of longitudes
:param lats:
a sequence of latitudes
:param depths:
a sequence of depths (or None)
:param sitemodel:
None or an object containing site parameters as attributes
:p... | [
"Build",
"the",
"site",
"collection",
"from"
] | python | train | 43.791667 |
tensorflow/tensor2tensor | tensor2tensor/models/video/savp_params.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/savp_params.py#L81-L92 | def next_frame_savp_gan():
"""SAVP - GAN only model."""
hparams = next_frame_savp()
hparams.use_gan = True
hparams.use_vae = False
hparams.gan_loss_multiplier = 0.001
hparams.optimizer_adam_beta1 = 0.5
hparams.learning_rate_constant = 2e-4
hparams.gan_loss = "cross_entropy"
hparams.learning_rate_decay... | [
"def",
"next_frame_savp_gan",
"(",
")",
":",
"hparams",
"=",
"next_frame_savp",
"(",
")",
"hparams",
".",
"use_gan",
"=",
"True",
"hparams",
".",
"use_vae",
"=",
"False",
"hparams",
".",
"gan_loss_multiplier",
"=",
"0.001",
"hparams",
".",
"optimizer_adam_beta1"... | SAVP - GAN only model. | [
"SAVP",
"-",
"GAN",
"only",
"model",
"."
] | python | train | 33.333333 |
ajk8/hatchery | hatchery/config.py | https://github.com/ajk8/hatchery/blob/e068c9f5366d2c98225babb03d4cde36c710194f/hatchery/config.py#L87-L93 | def pypirc_temp(index_url):
""" Create a temporary pypirc file for interaction with twine """
pypirc_file = tempfile.NamedTemporaryFile(suffix='.pypirc', delete=False)
print(pypirc_file.name)
with open(pypirc_file.name, 'w') as fh:
fh.write(PYPIRC_TEMPLATE.format(index_name=PYPIRC_TEMP_INDEX_NAM... | [
"def",
"pypirc_temp",
"(",
"index_url",
")",
":",
"pypirc_file",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"suffix",
"=",
"'.pypirc'",
",",
"delete",
"=",
"False",
")",
"print",
"(",
"pypirc_file",
".",
"name",
")",
"with",
"open",
"(",
"pypirc_file",... | Create a temporary pypirc file for interaction with twine | [
"Create",
"a",
"temporary",
"pypirc",
"file",
"for",
"interaction",
"with",
"twine"
] | python | train | 52.285714 |
synw/dataswim | dataswim/charts/__init__.py | https://github.com/synw/dataswim/blob/4a4a53f80daa7cd8e8409d76a19ce07296269da2/dataswim/charts/__init__.py#L51-L71 | def _chart(self, x, y, chart_type, opts, style, label, options, **kwargs):
"""
Initialize chart options
"""
if opts is not None:
self.chart_opts = opts
if style is not None:
self.chart_style = style
if label is not None:
self.label = label
self.x = x
self.y = y
if chart_type is None:
retur... | [
"def",
"_chart",
"(",
"self",
",",
"x",
",",
"y",
",",
"chart_type",
",",
"opts",
",",
"style",
",",
"label",
",",
"options",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"opts",
"is",
"not",
"None",
":",
"self",
".",
"chart_opts",
"=",
"opts",
"if",... | Initialize chart options | [
"Initialize",
"chart",
"options"
] | python | train | 23.857143 |
suds-community/suds | suds/transport/http.py | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/transport/http.py#L130-L140 | def u2opener(self):
"""
Create a urllib opener.
@return: An opener.
@rtype: I{OpenerDirector}
"""
if self.urlopener is None:
return urllib2.build_opener(*self.u2handlers())
return self.urlopener | [
"def",
"u2opener",
"(",
"self",
")",
":",
"if",
"self",
".",
"urlopener",
"is",
"None",
":",
"return",
"urllib2",
".",
"build_opener",
"(",
"*",
"self",
".",
"u2handlers",
"(",
")",
")",
"return",
"self",
".",
"urlopener"
] | Create a urllib opener.
@return: An opener.
@rtype: I{OpenerDirector} | [
"Create",
"a",
"urllib",
"opener",
"."
] | python | train | 23.090909 |
daviddrysdale/python-phonenumbers | tools/python/buildmetadatafromxml.py | https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/tools/python/buildmetadatafromxml.py#L189-L201 | def _expand_formatting_rule(rule, national_prefix):
"""Formatting rules can include terms "$NP" and "$FG",
These get replaced with:
"$NP" => the national prefix
"$FG" => the first group, i.e. "$1"
"""
if rule is None:
return None
if national_prefix is None:
national_prefix ... | [
"def",
"_expand_formatting_rule",
"(",
"rule",
",",
"national_prefix",
")",
":",
"if",
"rule",
"is",
"None",
":",
"return",
"None",
"if",
"national_prefix",
"is",
"None",
":",
"national_prefix",
"=",
"u",
"(",
"\"\"",
")",
"rule",
"=",
"re",
".",
"sub",
... | Formatting rules can include terms "$NP" and "$FG",
These get replaced with:
"$NP" => the national prefix
"$FG" => the first group, i.e. "$1" | [
"Formatting",
"rules",
"can",
"include",
"terms",
"$NP",
"and",
"$FG",
"These",
"get",
"replaced",
"with",
":",
"$NP",
"=",
">",
"the",
"national",
"prefix",
"$FG",
"=",
">",
"the",
"first",
"group",
"i",
".",
"e",
".",
"$1"
] | python | train | 33 |
hhatto/autopep8 | autopep8.py | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L3479-L3489 | def global_fixes():
"""Yield multiple (code, function) tuples."""
for function in list(globals().values()):
if inspect.isfunction(function):
arguments = _get_parameters(function)
if arguments[:1] != ['source']:
continue
code = extract_code_from_functi... | [
"def",
"global_fixes",
"(",
")",
":",
"for",
"function",
"in",
"list",
"(",
"globals",
"(",
")",
".",
"values",
"(",
")",
")",
":",
"if",
"inspect",
".",
"isfunction",
"(",
"function",
")",
":",
"arguments",
"=",
"_get_parameters",
"(",
"function",
")"... | Yield multiple (code, function) tuples. | [
"Yield",
"multiple",
"(",
"code",
"function",
")",
"tuples",
"."
] | python | train | 34.727273 |
ansible/molecule | molecule/provisioner/ansible.py | https://github.com/ansible/molecule/blob/766dc35b0b0ce498cd5e3a62b40f828742d0d08c/molecule/provisioner/ansible.py#L794-L805 | def _remove_vars(self):
"""
Remove hosts/host_vars/group_vars and returns None.
:returns: None
"""
for name in ("hosts", "group_vars", "host_vars"):
d = os.path.join(self.inventory_directory, name)
if os.path.islink(d) or os.path.isfile(d):
... | [
"def",
"_remove_vars",
"(",
"self",
")",
":",
"for",
"name",
"in",
"(",
"\"hosts\"",
",",
"\"group_vars\"",
",",
"\"host_vars\"",
")",
":",
"d",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"inventory_directory",
",",
"name",
")",
"if",
"os",... | Remove hosts/host_vars/group_vars and returns None.
:returns: None | [
"Remove",
"hosts",
"/",
"host_vars",
"/",
"group_vars",
"and",
"returns",
"None",
"."
] | python | train | 32.583333 |
dw/mitogen | mitogen/parent.py | https://github.com/dw/mitogen/blob/a7fdb55e1300a7e0a5e404b09eb730cf9a525da7/mitogen/parent.py#L1988-L2022 | def _on_del_route(self, msg):
"""
Respond to :data:`mitogen.core.DEL_ROUTE` by validating the source of
the message, updating the local table, propagating the message
upwards, and downwards towards any stream that every had a message
forwarded from it towards the disconnecting co... | [
"def",
"_on_del_route",
"(",
"self",
",",
"msg",
")",
":",
"if",
"msg",
".",
"is_dead",
":",
"return",
"target_id",
"=",
"int",
"(",
"msg",
".",
"data",
")",
"registered_stream",
"=",
"self",
".",
"router",
".",
"stream_by_id",
"(",
"target_id",
")",
"... | Respond to :data:`mitogen.core.DEL_ROUTE` by validating the source of
the message, updating the local table, propagating the message
upwards, and downwards towards any stream that every had a message
forwarded from it towards the disconnecting context. | [
"Respond",
"to",
":",
"data",
":",
"mitogen",
".",
"core",
".",
"DEL_ROUTE",
"by",
"validating",
"the",
"source",
"of",
"the",
"message",
"updating",
"the",
"local",
"table",
"propagating",
"the",
"message",
"upwards",
"and",
"downwards",
"towards",
"any",
"... | python | train | 39.657143 |
log2timeline/dfvfs | dfvfs/file_io/data_range_io.py | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/file_io/data_range_io.py#L127-L170 | def read(self, size=None):
"""Reads a byte string from the file-like object at the current offset.
The function will read a byte string of the specified size or
all of the remaining data if no size was specified.
Args:
size (Optional[int]): number of bytes to read, where None is all
re... | [
"def",
"read",
"(",
"self",
",",
"size",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_is_open",
":",
"raise",
"IOError",
"(",
"'Not opened.'",
")",
"if",
"self",
".",
"_range_offset",
"<",
"0",
"or",
"self",
".",
"_range_size",
"<",
"0",
":",
... | Reads a byte string from the file-like object at the current offset.
The function will read a byte string of the specified size or
all of the remaining data if no size was specified.
Args:
size (Optional[int]): number of bytes to read, where None is all
remaining data.
Returns:
... | [
"Reads",
"a",
"byte",
"string",
"from",
"the",
"file",
"-",
"like",
"object",
"at",
"the",
"current",
"offset",
"."
] | python | train | 26.363636 |
apple/turicreate | deps/src/cmake-3.13.4/Source/cmConvertMSBuildXMLToJSON.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/cmake-3.13.4/Source/cmConvertMSBuildXMLToJSON.py#L173-L198 | def __merge_json_values(current, previous):
"""Merges the values between the current and previous run of the script."""
for value in current:
name = value['name']
# Find the previous value
previous_value = __find_and_remove_value(previous, value)
if previous_value is not None:
... | [
"def",
"__merge_json_values",
"(",
"current",
",",
"previous",
")",
":",
"for",
"value",
"in",
"current",
":",
"name",
"=",
"value",
"[",
"'name'",
"]",
"# Find the previous value",
"previous_value",
"=",
"__find_and_remove_value",
"(",
"previous",
",",
"value",
... | Merges the values between the current and previous run of the script. | [
"Merges",
"the",
"values",
"between",
"the",
"current",
"and",
"previous",
"run",
"of",
"the",
"script",
"."
] | python | train | 32.576923 |
CodeReclaimers/neat-python | neat/reproduction.py | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/reproduction.py#L84-L188 | def reproduce(self, config, species, pop_size, generation):
"""
Handles creation of genomes, either from scratch or by sexual or
asexual reproduction from parents.
"""
# TODO: I don't like this modification of the species and stagnation objects,
# because it requires inte... | [
"def",
"reproduce",
"(",
"self",
",",
"config",
",",
"species",
",",
"pop_size",
",",
"generation",
")",
":",
"# TODO: I don't like this modification of the species and stagnation objects,",
"# because it requires internal knowledge of the objects.",
"# Filter out stagnated species, ... | Handles creation of genomes, either from scratch or by sexual or
asexual reproduction from parents. | [
"Handles",
"creation",
"of",
"genomes",
"either",
"from",
"scratch",
"or",
"by",
"sexual",
"or",
"asexual",
"reproduction",
"from",
"parents",
"."
] | python | train | 48.371429 |
polysquare/cmake-ast | cmakeast/ast.py | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L891-L902 | def parse(contents, tokens=None):
"""Parse a string called contents for an AST and return it."""
# Shortcut for users who are interested in tokens
if tokens is None:
tokens = [t for t in tokenize(contents)]
token_index, body = _ast_worker(tokens, len(tokens), 0, None)
assert token_index ==... | [
"def",
"parse",
"(",
"contents",
",",
"tokens",
"=",
"None",
")",
":",
"# Shortcut for users who are interested in tokens",
"if",
"tokens",
"is",
"None",
":",
"tokens",
"=",
"[",
"t",
"for",
"t",
"in",
"tokenize",
"(",
"contents",
")",
"]",
"token_index",
",... | Parse a string called contents for an AST and return it. | [
"Parse",
"a",
"string",
"called",
"contents",
"for",
"an",
"AST",
"and",
"return",
"it",
"."
] | python | train | 33.833333 |
quiltdata/quilt | compiler/quilt/tools/command.py | https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/tools/command.py#L502-L533 | def build(package, path=None, dry_run=False, env='default', force=False, build_file=False):
"""
Compile a Quilt data package, either from a build file or an existing package node.
:param package: short package specifier, i.e. 'team:user/pkg'
:param path: file path, git url, or existing package node
... | [
"def",
"build",
"(",
"package",
",",
"path",
"=",
"None",
",",
"dry_run",
"=",
"False",
",",
"env",
"=",
"'default'",
",",
"force",
"=",
"False",
",",
"build_file",
"=",
"False",
")",
":",
"# TODO: rename 'path' param to 'target'?",
"team",
",",
"_",
",",
... | Compile a Quilt data package, either from a build file or an existing package node.
:param package: short package specifier, i.e. 'team:user/pkg'
:param path: file path, git url, or existing package node | [
"Compile",
"a",
"Quilt",
"data",
"package",
"either",
"from",
"a",
"build",
"file",
"or",
"an",
"existing",
"package",
"node",
"."
] | python | train | 48 |
joke2k/django-environ | environ/environ.py | https://github.com/joke2k/django-environ/blob/c2620021614557abe197578f99deeef42af3e082/environ/environ.py#L169-L173 | def json(self, var, default=NOTSET):
"""
:returns: Json parsed
"""
return self.get_value(var, cast=json.loads, default=default) | [
"def",
"json",
"(",
"self",
",",
"var",
",",
"default",
"=",
"NOTSET",
")",
":",
"return",
"self",
".",
"get_value",
"(",
"var",
",",
"cast",
"=",
"json",
".",
"loads",
",",
"default",
"=",
"default",
")"
] | :returns: Json parsed | [
":",
"returns",
":",
"Json",
"parsed"
] | python | train | 31 |
CalebBell/thermo | thermo/electrochem.py | https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/electrochem.py#L826-L865 | def ionic_strength(mis, zis):
r'''Calculate the ionic strength of a solution in one of two ways,
depending on the inputs only. For Pitzer and Bromley models,
`mis` should be molalities of each component. For eNRTL models,
`mis` should be mole fractions of each electrolyte in the solution.
This will ... | [
"def",
"ionic_strength",
"(",
"mis",
",",
"zis",
")",
":",
"return",
"0.5",
"*",
"sum",
"(",
"[",
"mi",
"*",
"zi",
"*",
"zi",
"for",
"mi",
",",
"zi",
"in",
"zip",
"(",
"mis",
",",
"zis",
")",
"]",
")"
] | r'''Calculate the ionic strength of a solution in one of two ways,
depending on the inputs only. For Pitzer and Bromley models,
`mis` should be molalities of each component. For eNRTL models,
`mis` should be mole fractions of each electrolyte in the solution.
This will sum to be much less than 1.
.... | [
"r",
"Calculate",
"the",
"ionic",
"strength",
"of",
"a",
"solution",
"in",
"one",
"of",
"two",
"ways",
"depending",
"on",
"the",
"inputs",
"only",
".",
"For",
"Pitzer",
"and",
"Bromley",
"models",
"mis",
"should",
"be",
"molalities",
"of",
"each",
"compone... | python | valid | 31.725 |
UCBerkeleySETI/blimpy | blimpy/utils.py | https://github.com/UCBerkeleySETI/blimpy/blob/b8822d3e3e911944370d84371a91fa0c29e9772e/blimpy/utils.py#L133-L156 | def unpack_4to8(data):
""" Promote 2-bit unisgned data into 8-bit unsigned data.
Args:
data: Numpy array with dtype == uint8
Notes:
# The process is this:
# ABCDEFGH [Bits of one 4+4-bit value]
# 00000000ABCDEFGH [astype(uint16)]
# 0000ABCDEFGH0000 [<< 4]
# ... | [
"def",
"unpack_4to8",
"(",
"data",
")",
":",
"tmpdata",
"=",
"data",
".",
"astype",
"(",
"np",
".",
"int16",
")",
"# np.empty(upshape, dtype=np.int16)",
"tmpdata",
"=",
"(",
"tmpdata",
"|",
"(",
"tmpdata",
"<<",
"4",
")",
")",
"&",
"0x0F0F",
"# tmpdata = t... | Promote 2-bit unisgned data into 8-bit unsigned data.
Args:
data: Numpy array with dtype == uint8
Notes:
# The process is this:
# ABCDEFGH [Bits of one 4+4-bit value]
# 00000000ABCDEFGH [astype(uint16)]
# 0000ABCDEFGH0000 [<< 4]
# 0000ABCDXXXXEFGH [bitwise 'or' ... | [
"Promote",
"2",
"-",
"bit",
"unisgned",
"data",
"into",
"8",
"-",
"bit",
"unsigned",
"data",
"."
] | python | test | 37.666667 |
jupyterhub/kubespawner | kubespawner/utils.py | https://github.com/jupyterhub/kubespawner/blob/46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13/kubespawner/utils.py#L32-L73 | def update_k8s_model(target, changes, logger=None, target_name=None, changes_name=None):
"""
Takes a model instance such as V1PodSpec() and updates it with another
model, which is allowed to be a dict or another model instance of the same
type. The logger is used to warn if any truthy value in the targe... | [
"def",
"update_k8s_model",
"(",
"target",
",",
"changes",
",",
"logger",
"=",
"None",
",",
"target_name",
"=",
"None",
",",
"changes_name",
"=",
"None",
")",
":",
"model_type",
"=",
"type",
"(",
"target",
")",
"if",
"not",
"hasattr",
"(",
"target",
",",
... | Takes a model instance such as V1PodSpec() and updates it with another
model, which is allowed to be a dict or another model instance of the same
type. The logger is used to warn if any truthy value in the target is is
overridden. The target_name parameter can for example be "pod.spec", and
changes_name... | [
"Takes",
"a",
"model",
"instance",
"such",
"as",
"V1PodSpec",
"()",
"and",
"updates",
"it",
"with",
"another",
"model",
"which",
"is",
"allowed",
"to",
"be",
"a",
"dict",
"or",
"another",
"model",
"instance",
"of",
"the",
"same",
"type",
".",
"The",
"log... | python | train | 55.666667 |
JamesRitchie/django-rest-framework-expiring-tokens | rest_framework_expiring_authtoken/views.py | https://github.com/JamesRitchie/django-rest-framework-expiring-tokens/blob/e62f1f92a621575174172e970da624d367ac0cf6/rest_framework_expiring_authtoken/views.py#L20-L39 | def post(self, request):
"""Respond to POSTed username/password with token."""
serializer = AuthTokenSerializer(data=request.data)
if serializer.is_valid():
token, _ = ExpiringToken.objects.get_or_create(
user=serializer.validated_data['user']
)
... | [
"def",
"post",
"(",
"self",
",",
"request",
")",
":",
"serializer",
"=",
"AuthTokenSerializer",
"(",
"data",
"=",
"request",
".",
"data",
")",
"if",
"serializer",
".",
"is_valid",
"(",
")",
":",
"token",
",",
"_",
"=",
"ExpiringToken",
".",
"objects",
... | Respond to POSTed username/password with token. | [
"Respond",
"to",
"POSTed",
"username",
"/",
"password",
"with",
"token",
"."
] | python | train | 34.85 |
AmanoTeam/amanobot | amanobot/__init__.py | https://github.com/AmanoTeam/amanobot/blob/fe546e2e294eec88e637da0b2567c7e7e8662437/amanobot/__init__.py#L564-L577 | def sendDocument(self, chat_id, document,
thumb=None,
caption=None,
parse_mode=None,
disable_notification=None,
reply_to_message_id=None,
reply_markup=None):
"""
See: https://cor... | [
"def",
"sendDocument",
"(",
"self",
",",
"chat_id",
",",
"document",
",",
"thumb",
"=",
"None",
",",
"caption",
"=",
"None",
",",
"parse_mode",
"=",
"None",
",",
"disable_notification",
"=",
"None",
",",
"reply_to_message_id",
"=",
"None",
",",
"reply_markup... | See: https://core.telegram.org/bots/api#senddocument
:param document: Same as ``photo`` in :meth:`amanobot.Bot.sendPhoto` | [
"See",
":",
"https",
":",
"//",
"core",
".",
"telegram",
".",
"org",
"/",
"bots",
"/",
"api#senddocument"
] | python | train | 41.071429 |
Erotemic/utool | utool/util_cache.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_cache.py#L989-L993 | def delete_global_cache(appname='default'):
""" Reads cache files to a safe place in each operating system """
#close_global_shelf(appname)
shelf_fpath = get_global_shelf_fpath(appname)
util_path.remove_file(shelf_fpath, verbose=True, dryrun=False) | [
"def",
"delete_global_cache",
"(",
"appname",
"=",
"'default'",
")",
":",
"#close_global_shelf(appname)",
"shelf_fpath",
"=",
"get_global_shelf_fpath",
"(",
"appname",
")",
"util_path",
".",
"remove_file",
"(",
"shelf_fpath",
",",
"verbose",
"=",
"True",
",",
"dryru... | Reads cache files to a safe place in each operating system | [
"Reads",
"cache",
"files",
"to",
"a",
"safe",
"place",
"in",
"each",
"operating",
"system"
] | python | train | 52 |
klahnakoski/pyLibrary | pyLibrary/env/elasticsearch.py | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/pyLibrary/env/elasticsearch.py#L175-L187 | def delete_all_but_self(self):
"""
DELETE ALL INDEXES WITH GIVEN PREFIX, EXCEPT name
"""
prefix = self.settings.alias
name = self.settings.index
if prefix == name:
Log.note("{{index_name}} will not be deleted", index_name= prefix)
for a in self.clust... | [
"def",
"delete_all_but_self",
"(",
"self",
")",
":",
"prefix",
"=",
"self",
".",
"settings",
".",
"alias",
"name",
"=",
"self",
".",
"settings",
".",
"index",
"if",
"prefix",
"==",
"name",
":",
"Log",
".",
"note",
"(",
"\"{{index_name}} will not be deleted\"... | DELETE ALL INDEXES WITH GIVEN PREFIX, EXCEPT name | [
"DELETE",
"ALL",
"INDEXES",
"WITH",
"GIVEN",
"PREFIX",
"EXCEPT",
"name"
] | python | train | 39.692308 |
Falkonry/falkonry-python-client | falkonryclient/service/falkonry.py | https://github.com/Falkonry/falkonry-python-client/blob/0aeb2b00293ee94944f1634e9667401b03da29c1/falkonryclient/service/falkonry.py#L37-L45 | def get_datastreams(self):
"""
To get list of Datastream
"""
datastreams = []
response = self.http.get('/Datastream')
for datastream in response:
datastreams.append(Schemas.Datastream(datastream=datastream))
return datastreams | [
"def",
"get_datastreams",
"(",
"self",
")",
":",
"datastreams",
"=",
"[",
"]",
"response",
"=",
"self",
".",
"http",
".",
"get",
"(",
"'/Datastream'",
")",
"for",
"datastream",
"in",
"response",
":",
"datastreams",
".",
"append",
"(",
"Schemas",
".",
"Da... | To get list of Datastream | [
"To",
"get",
"list",
"of",
"Datastream"
] | python | train | 31.777778 |
seung-lab/cloud-volume | cloudvolume/storage.py | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/storage.py#L818-L832 | def _radix_sort(L, i=0):
"""
Most significant char radix sort
"""
if len(L) <= 1:
return L
done_bucket = []
buckets = [ [] for x in range(255) ]
for s in L:
if i >= len(s):
done_bucket.append(s)
else:
buckets[ ord(s[i]) ].append(s)
buckets = [ _radix_sort(b, i + 1) for b in buck... | [
"def",
"_radix_sort",
"(",
"L",
",",
"i",
"=",
"0",
")",
":",
"if",
"len",
"(",
"L",
")",
"<=",
"1",
":",
"return",
"L",
"done_bucket",
"=",
"[",
"]",
"buckets",
"=",
"[",
"[",
"]",
"for",
"x",
"in",
"range",
"(",
"255",
")",
"]",
"for",
"s... | Most significant char radix sort | [
"Most",
"significant",
"char",
"radix",
"sort"
] | python | train | 25.066667 |
GNS3/gns3-server | gns3server/compute/virtualbox/virtualbox_vm.py | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/virtualbox/virtualbox_vm.py#L300-L345 | def stop(self):
"""
Stops this VirtualBox VM.
"""
self._hw_virtualization = False
yield from self._stop_ubridge()
yield from self._stop_remote_console()
vm_state = yield from self._get_vm_state()
if vm_state == "running" or vm_state == "paused" or vm_stat... | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"_hw_virtualization",
"=",
"False",
"yield",
"from",
"self",
".",
"_stop_ubridge",
"(",
")",
"yield",
"from",
"self",
".",
"_stop_remote_console",
"(",
")",
"vm_state",
"=",
"yield",
"from",
"self",
".",
... | Stops this VirtualBox VM. | [
"Stops",
"this",
"VirtualBox",
"VM",
"."
] | python | train | 45.434783 |
soravux/scoop | scoop/_comm/scooptcp.py | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/_comm/scooptcp.py#L315-L332 | def sendResult(self, future):
"""Send a terminated future back to its parent."""
future = copy.copy(future)
# Remove the (now) extraneous elements from future class
future.callable = future.args = future.kargs = future.greenlet = None
if not future.sendResultBack:
... | [
"def",
"sendResult",
"(",
"self",
",",
"future",
")",
":",
"future",
"=",
"copy",
".",
"copy",
"(",
"future",
")",
"# Remove the (now) extraneous elements from future class\r",
"future",
".",
"callable",
"=",
"future",
".",
"args",
"=",
"future",
".",
"kargs",
... | Send a terminated future back to its parent. | [
"Send",
"a",
"terminated",
"future",
"back",
"to",
"its",
"parent",
"."
] | python | train | 32 |
abhinav/reversible | reversible/tornado/generator.py | https://github.com/abhinav/reversible/blob/7e28aaf0390f7d4b889c6ac14d7b340f8f314e89/reversible/tornado/generator.py#L76-L144 | def gen(function, io_loop=None):
"""Allows using a generator to chain together reversible actions.
This function is very similar to :py:func:`reversible.gen` except that it
may be used with actions whose ``forwards`` and/or ``backwards`` methods
are couroutines. Specifically, if either of those methods... | [
"def",
"gen",
"(",
"function",
",",
"io_loop",
"=",
"None",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"function",
")",
"# TODO: use wrapt instead?",
"def",
"new_function",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"value",
"... | Allows using a generator to chain together reversible actions.
This function is very similar to :py:func:`reversible.gen` except that it
may be used with actions whose ``forwards`` and/or ``backwards`` methods
are couroutines. Specifically, if either of those methods return futures
the generated action... | [
"Allows",
"using",
"a",
"generator",
"to",
"chain",
"together",
"reversible",
"actions",
"."
] | python | train | 35.333333 |
dmbee/seglearn | seglearn/transform.py | https://github.com/dmbee/seglearn/blob/d8d7039e92c4c6571a70350c03298aceab8dbeec/seglearn/transform.py#L1301-L1319 | def _retrieve_indices(cols):
'''
Retrieve a list of indices corresponding to the provided column specification.
'''
if isinstance(cols, int):
return [cols]
elif isinstance(cols, slice):
start = cols.start if cols.start else 0
stop = cols.stop
... | [
"def",
"_retrieve_indices",
"(",
"cols",
")",
":",
"if",
"isinstance",
"(",
"cols",
",",
"int",
")",
":",
"return",
"[",
"cols",
"]",
"elif",
"isinstance",
"(",
"cols",
",",
"slice",
")",
":",
"start",
"=",
"cols",
".",
"start",
"if",
"cols",
".",
... | Retrieve a list of indices corresponding to the provided column specification. | [
"Retrieve",
"a",
"list",
"of",
"indices",
"corresponding",
"to",
"the",
"provided",
"column",
"specification",
"."
] | python | train | 41.684211 |
gwpy/gwpy | gwpy/types/series.py | https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/types/series.py#L209-L228 | def _set_index(self, key, index):
"""Set a new index array for this series
"""
axis = key[0]
origin = "{}0".format(axis)
delta = "d{}".format(axis)
if index is None:
return delattr(self, key)
if not isinstance(index, Index):
try:
... | [
"def",
"_set_index",
"(",
"self",
",",
"key",
",",
"index",
")",
":",
"axis",
"=",
"key",
"[",
"0",
"]",
"origin",
"=",
"\"{}0\"",
".",
"format",
"(",
"axis",
")",
"delta",
"=",
"\"d{}\"",
".",
"format",
"(",
"axis",
")",
"if",
"index",
"is",
"No... | Set a new index array for this series | [
"Set",
"a",
"new",
"index",
"array",
"for",
"this",
"series"
] | python | train | 34.95 |
blink1073/oct2py | oct2py/core.py | https://github.com/blink1073/oct2py/blob/bfc69d2168ae3d98258f95bbc55a858c21836b58/oct2py/core.py#L689-L693 | def _get_function_ptr(self, name):
"""Get or create a function pointer of the given name."""
func = _make_function_ptr_instance
self._function_ptrs.setdefault(name, func(self, name))
return self._function_ptrs[name] | [
"def",
"_get_function_ptr",
"(",
"self",
",",
"name",
")",
":",
"func",
"=",
"_make_function_ptr_instance",
"self",
".",
"_function_ptrs",
".",
"setdefault",
"(",
"name",
",",
"func",
"(",
"self",
",",
"name",
")",
")",
"return",
"self",
".",
"_function_ptrs... | Get or create a function pointer of the given name. | [
"Get",
"or",
"create",
"a",
"function",
"pointer",
"of",
"the",
"given",
"name",
"."
] | python | valid | 49.4 |
sdispater/orator | orator/orm/factory.py | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/factory.py#L98-L111 | def register_as(self, klass, name, callback):
"""
Register a class with a function.
:param klass: The class
:type klass: class
:param callback: The callable
:type callback: callable
:param name: The short name
:type name: str
"""
return ... | [
"def",
"register_as",
"(",
"self",
",",
"klass",
",",
"name",
",",
"callback",
")",
":",
"return",
"self",
".",
"register",
"(",
"klass",
",",
"callback",
",",
"name",
")"
] | Register a class with a function.
:param klass: The class
:type klass: class
:param callback: The callable
:type callback: callable
:param name: The short name
:type name: str | [
"Register",
"a",
"class",
"with",
"a",
"function",
"."
] | python | train | 24.5 |
yero13/na3x | na3x/validation/validator.py | https://github.com/yero13/na3x/blob/b31ef801ea574081125020a7d0f9c4242f8f8b02/na3x/validation/validator.py#L221-L241 | def aggregate(input, **params):
"""
Returns aggregate
:param input:
:param params:
:return:
"""
PARAM_CFG_EXTRACT = 'extract'
PARAM_CFG_SUBSTITUTE = 'substitute'
PARAM_CFG_AGGREGATE = 'aggregate'
AGGR_FIELD = 'field'
AGGR_FUNC = 'func'
extract_params = params.get(PARAM_C... | [
"def",
"aggregate",
"(",
"input",
",",
"*",
"*",
"params",
")",
":",
"PARAM_CFG_EXTRACT",
"=",
"'extract'",
"PARAM_CFG_SUBSTITUTE",
"=",
"'substitute'",
"PARAM_CFG_AGGREGATE",
"=",
"'aggregate'",
"AGGR_FIELD",
"=",
"'field'",
"AGGR_FUNC",
"=",
"'func'",
"extract_par... | Returns aggregate
:param input:
:param params:
:return: | [
"Returns",
"aggregate",
":",
"param",
"input",
":",
":",
"param",
"params",
":",
":",
"return",
":"
] | python | train | 32.857143 |
Skyscanner/pages | pages/ui_component.py | https://github.com/Skyscanner/pages/blob/f80471ef01f84b11e4d751dff1e6398ae1e230b8/pages/ui_component.py#L44-L54 | def from_web_element(self, web_element):
"""
Store reference to a WebElement instance representing the element on the DOM.
Use it when an instance of WebElement has already been created (e.g. as the result of find_element) and
you want to create a UIComponent out of it withou... | [
"def",
"from_web_element",
"(",
"self",
",",
"web_element",
")",
":",
"if",
"isinstance",
"(",
"web_element",
",",
"WebElement",
")",
"is",
"not",
"True",
":",
"raise",
"TypeError",
"(",
"\"web_element parameter is not of type WebElement.\"",
")",
"self",
".",
"_w... | Store reference to a WebElement instance representing the element on the DOM.
Use it when an instance of WebElement has already been created (e.g. as the result of find_element) and
you want to create a UIComponent out of it without evaluating it from the locator again.
Returns an in... | [
"Store",
"reference",
"to",
"a",
"WebElement",
"instance",
"representing",
"the",
"element",
"on",
"the",
"DOM",
".",
"Use",
"it",
"when",
"an",
"instance",
"of",
"WebElement",
"has",
"already",
"been",
"created",
"(",
"e",
".",
"g",
".",
"as",
"the",
"r... | python | test | 55.181818 |
sorgerlab/indra | indra/sources/trips/processor.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/trips/processor.py#L717-L821 | def get_modifications_indirect(self):
"""Extract indirect Modification INDRA Statements."""
# Get all the specific mod types
mod_event_types = list(ont_to_mod_type.keys())
# Add ONT::PTMs as a special case
mod_event_types += ['ONT::PTM']
def get_increase_events(mod_event... | [
"def",
"get_modifications_indirect",
"(",
"self",
")",
":",
"# Get all the specific mod types",
"mod_event_types",
"=",
"list",
"(",
"ont_to_mod_type",
".",
"keys",
"(",
")",
")",
"# Add ONT::PTMs as a special case",
"mod_event_types",
"+=",
"[",
"'ONT::PTM'",
"]",
"def... | Extract indirect Modification INDRA Statements. | [
"Extract",
"indirect",
"Modification",
"INDRA",
"Statements",
"."
] | python | train | 42.914286 |
alefnula/tea | tea/console/color.py | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/console/color.py#L171-L184 | def set_color(
fg=Color.normal,
bg=Color.normal,
fg_dark=False,
bg_dark=False,
underlined=False,
):
"""Set the console color.
>>> set_color(Color.red, Color.blue)
>>> set_color('red', 'blue')
>>> set_color() # returns back to normal
"""
_set_color(fg, bg, fg_dar... | [
"def",
"set_color",
"(",
"fg",
"=",
"Color",
".",
"normal",
",",
"bg",
"=",
"Color",
".",
"normal",
",",
"fg_dark",
"=",
"False",
",",
"bg_dark",
"=",
"False",
",",
"underlined",
"=",
"False",
",",
")",
":",
"_set_color",
"(",
"fg",
",",
"bg",
",",... | Set the console color.
>>> set_color(Color.red, Color.blue)
>>> set_color('red', 'blue')
>>> set_color() # returns back to normal | [
"Set",
"the",
"console",
"color",
".",
">>>",
"set_color",
"(",
"Color",
".",
"red",
"Color",
".",
"blue",
")",
">>>",
"set_color",
"(",
"red",
"blue",
")",
">>>",
"set_color",
"()",
"#",
"returns",
"back",
"to",
"normal"
] | python | train | 23.571429 |
ktbyers/netmiko | netmiko/scp_handler.py | https://github.com/ktbyers/netmiko/blob/54e6116c0b4664de2123081937e0a9a27bdfdfea/netmiko/scp_handler.py#L277-L284 | def compare_md5(self):
"""Compare md5 of file on network device to md5 of local file."""
if self.direction == "put":
remote_md5 = self.remote_md5()
return self.source_md5 == remote_md5
elif self.direction == "get":
local_md5 = self.file_md5(self.dest_file)
... | [
"def",
"compare_md5",
"(",
"self",
")",
":",
"if",
"self",
".",
"direction",
"==",
"\"put\"",
":",
"remote_md5",
"=",
"self",
".",
"remote_md5",
"(",
")",
"return",
"self",
".",
"source_md5",
"==",
"remote_md5",
"elif",
"self",
".",
"direction",
"==",
"\... | Compare md5 of file on network device to md5 of local file. | [
"Compare",
"md5",
"of",
"file",
"on",
"network",
"device",
"to",
"md5",
"of",
"local",
"file",
"."
] | python | train | 44.625 |
foxx/python-helpful | helpful.py | https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L455-L478 | def is_int(value):
"""
Check if value is an int
:type value: int, str, bytes, float, Decimal
>>> is_int(123), is_int('123'), is_int(Decimal('10'))
(True, True, True)
>>> is_int(1.1), is_int('1.1'), is_int(Decimal('10.1'))
(False, False, False)
>>> is_int(object)
Traceback (most rec... | [
"def",
"is_int",
"(",
"value",
")",
":",
"ensure_instance",
"(",
"value",
",",
"(",
"int",
",",
"str",
",",
"bytes",
",",
"float",
",",
"Decimal",
")",
")",
"if",
"isinstance",
"(",
"value",
",",
"int",
")",
":",
"return",
"True",
"elif",
"isinstance... | Check if value is an int
:type value: int, str, bytes, float, Decimal
>>> is_int(123), is_int('123'), is_int(Decimal('10'))
(True, True, True)
>>> is_int(1.1), is_int('1.1'), is_int(Decimal('10.1'))
(False, False, False)
>>> is_int(object)
Traceback (most recent call last):
TypeError: | [
"Check",
"if",
"value",
"is",
"an",
"int"
] | python | train | 28.041667 |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/property.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/property.py#L313-L336 | def translate_paths (properties, path):
""" Interpret all path properties in 'properties' as relative to 'path'
The property values are assumed to be in system-specific form, and
will be translated into normalized form.
"""
assert is_iterable_typed(properties, Property)
result = []
... | [
"def",
"translate_paths",
"(",
"properties",
",",
"path",
")",
":",
"assert",
"is_iterable_typed",
"(",
"properties",
",",
"Property",
")",
"result",
"=",
"[",
"]",
"for",
"p",
"in",
"properties",
":",
"if",
"p",
".",
"feature",
".",
"path",
":",
"values... | Interpret all path properties in 'properties' as relative to 'path'
The property values are assumed to be in system-specific form, and
will be translated into normalized form. | [
"Interpret",
"all",
"path",
"properties",
"in",
"properties",
"as",
"relative",
"to",
"path",
"The",
"property",
"values",
"are",
"assumed",
"to",
"be",
"in",
"system",
"-",
"specific",
"form",
"and",
"will",
"be",
"translated",
"into",
"normalized",
"form",
... | python | train | 30.208333 |
gwpy/gwpy | gwpy/io/gwf.py | https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/io/gwf.py#L356-L385 | def _gwf_channel_segments(path, channel, warn=True):
"""Yields the segments containing data for ``channel`` in this GWF path
"""
stream = open_gwf(path)
# get segments for frames
toc = stream.GetTOC()
secs = toc.GetGTimeS()
nano = toc.GetGTimeN()
dur = toc.GetDt()
readers = [getattr... | [
"def",
"_gwf_channel_segments",
"(",
"path",
",",
"channel",
",",
"warn",
"=",
"True",
")",
":",
"stream",
"=",
"open_gwf",
"(",
"path",
")",
"# get segments for frames",
"toc",
"=",
"stream",
".",
"GetTOC",
"(",
")",
"secs",
"=",
"toc",
".",
"GetGTimeS",
... | Yields the segments containing data for ``channel`` in this GWF path | [
"Yields",
"the",
"segments",
"containing",
"data",
"for",
"channel",
"in",
"this",
"GWF",
"path"
] | python | train | 35.566667 |
rdireen/spherepy | spherepy/ops.py | https://github.com/rdireen/spherepy/blob/241521401d4d76851d4a1a564a365cfab8e98496/spherepy/ops.py#L55-L66 | def fix_even_row_data_fc(fdata):
"""When the number of rows in fdata is even, there is a subtlety that must
be taken care of if fdata is to satisfy the symmetry required for further
processing. For an array length of 6,the data is align as [0 1 2 -3 -2 -1]
this routine simply sets the row corresponding... | [
"def",
"fix_even_row_data_fc",
"(",
"fdata",
")",
":",
"L",
"=",
"fdata",
".",
"shape",
"[",
"0",
"]",
"if",
"np",
".",
"mod",
"(",
"L",
",",
"2",
")",
"==",
"0",
":",
"fdata",
"[",
"int",
"(",
"L",
"/",
"2",
")",
",",
":",
"]",
"=",
"0"
] | When the number of rows in fdata is even, there is a subtlety that must
be taken care of if fdata is to satisfy the symmetry required for further
processing. For an array length of 6,the data is align as [0 1 2 -3 -2 -1]
this routine simply sets the row corresponding to the -3 index equal to
zero. It ... | [
"When",
"the",
"number",
"of",
"rows",
"in",
"fdata",
"is",
"even",
"there",
"is",
"a",
"subtlety",
"that",
"must",
"be",
"taken",
"care",
"of",
"if",
"fdata",
"is",
"to",
"satisfy",
"the",
"symmetry",
"required",
"for",
"further",
"processing",
".",
"Fo... | python | train | 52.916667 |
portfors-lab/sparkle | sparkle/gui/stim/stimulusview.py | https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/stim/stimulusview.py#L474-L485 | def visualRegionForSelection(self, selection):
"""Gets the region of all of the components in selection
:param selection: a selection model for this view
:type selection: :qtdoc:`QItemSelectionModel`
:returns: :qtdoc:`QRegion` -- union of rects of the selected components
"""
... | [
"def",
"visualRegionForSelection",
"(",
"self",
",",
"selection",
")",
":",
"region",
"=",
"QtGui",
".",
"QRegion",
"(",
")",
"for",
"index",
"in",
"selection",
".",
"indexes",
"(",
")",
":",
"region",
"=",
"region",
".",
"united",
"(",
"self",
".",
"_... | Gets the region of all of the components in selection
:param selection: a selection model for this view
:type selection: :qtdoc:`QItemSelectionModel`
:returns: :qtdoc:`QRegion` -- union of rects of the selected components | [
"Gets",
"the",
"region",
"of",
"all",
"of",
"the",
"components",
"in",
"selection"
] | python | train | 40 |
PyGithub/PyGithub | github/AuthenticatedUser.py | https://github.com/PyGithub/PyGithub/blob/f716df86bbe7dc276c6596699fa9712b61ef974c/github/AuthenticatedUser.py#L369-L381 | def add_to_emails(self, *emails):
"""
:calls: `POST /user/emails <http://developer.github.com/v3/users/emails>`_
:param email: string
:rtype: None
"""
assert all(isinstance(element, (str, unicode)) for element in emails), emails
post_parameters = emails
he... | [
"def",
"add_to_emails",
"(",
"self",
",",
"*",
"emails",
")",
":",
"assert",
"all",
"(",
"isinstance",
"(",
"element",
",",
"(",
"str",
",",
"unicode",
")",
")",
"for",
"element",
"in",
"emails",
")",
",",
"emails",
"post_parameters",
"=",
"emails",
"h... | :calls: `POST /user/emails <http://developer.github.com/v3/users/emails>`_
:param email: string
:rtype: None | [
":",
"calls",
":",
"POST",
"/",
"user",
"/",
"emails",
"<http",
":",
"//",
"developer",
".",
"github",
".",
"com",
"/",
"v3",
"/",
"users",
"/",
"emails",
">",
"_",
":",
"param",
"email",
":",
"string",
":",
"rtype",
":",
"None"
] | python | train | 34.615385 |
3DLIRIOUS/MeshLabXML | meshlabxml/transfer.py | https://github.com/3DLIRIOUS/MeshLabXML/blob/177cce21e92baca500f56a932d66bd9a33257af8/meshlabxml/transfer.py#L196-L289 | def vert_attr2tex_2_meshes(script, source_mesh=0, target_mesh=1, attribute=0,
max_distance=0.5, tex_name='TEMP3D_texture.png',
tex_width=1024, tex_height=1024,
overwrite_tex=True, assign_tex=False,
fill_tex=True)... | [
"def",
"vert_attr2tex_2_meshes",
"(",
"script",
",",
"source_mesh",
"=",
"0",
",",
"target_mesh",
"=",
"1",
",",
"attribute",
"=",
"0",
",",
"max_distance",
"=",
"0.5",
",",
"tex_name",
"=",
"'TEMP3D_texture.png'",
",",
"tex_width",
"=",
"1024",
",",
"tex_he... | Transfer Vertex Attributes to Texture (between 2 meshes)
Args:
script: the FilterScript object or script filename to write
the filter to.
source_mesh (int): The mesh that contains the source data that we want to transfer
target_mesh (int): The mesh whose texture will be filled a... | [
"Transfer",
"Vertex",
"Attributes",
"to",
"Texture",
"(",
"between",
"2",
"meshes",
")"
] | python | test | 40.361702 |
bwohlberg/sporco | sporco/prox/_nuclear.py | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/prox/_nuclear.py#L21-L41 | def norm_nuclear(X):
r"""Compute the nuclear norm
.. math::
\| X \|_* = \sum_i \sigma_i
where :math:`\sigma_i` are the singular values of matrix :math:`X`.
Parameters
----------
X : array_like
Input array :math:`X`
Returns
-------
nncl : float
Nuclear norm of `... | [
"def",
"norm_nuclear",
"(",
"X",
")",
":",
"return",
"np",
".",
"sum",
"(",
"np",
".",
"linalg",
".",
"svd",
"(",
"sl",
".",
"promote16",
"(",
"X",
")",
",",
"compute_uv",
"=",
"False",
")",
")"
] | r"""Compute the nuclear norm
.. math::
\| X \|_* = \sum_i \sigma_i
where :math:`\sigma_i` are the singular values of matrix :math:`X`.
Parameters
----------
X : array_like
Input array :math:`X`
Returns
-------
nncl : float
Nuclear norm of `X` | [
"r",
"Compute",
"the",
"nuclear",
"norm"
] | python | train | 18.047619 |
fake-name/ChromeController | ChromeController/Generator/Generated.py | https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L427-L451 | def Page_deleteCookie(self, cookieName, url):
"""
Function path: Page.deleteCookie
Domain: Page
Method name: deleteCookie
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'cookieName' (type: string) -> Name of the cookie to remove.
'url' (type: string)... | [
"def",
"Page_deleteCookie",
"(",
"self",
",",
"cookieName",
",",
"url",
")",
":",
"assert",
"isinstance",
"(",
"cookieName",
",",
"(",
"str",
",",
")",
")",
",",
"\"Argument 'cookieName' must be of type '['str']'. Received type: '%s'\"",
"%",
"type",
"(",
"cookieNam... | Function path: Page.deleteCookie
Domain: Page
Method name: deleteCookie
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'cookieName' (type: string) -> Name of the cookie to remove.
'url' (type: string) -> URL to match cooke domain and path.
No return v... | [
"Function",
"path",
":",
"Page",
".",
"deleteCookie",
"Domain",
":",
"Page",
"Method",
"name",
":",
"deleteCookie",
"WARNING",
":",
"This",
"function",
"is",
"marked",
"Experimental",
"!",
"Parameters",
":",
"Required",
"arguments",
":",
"cookieName",
"(",
"ty... | python | train | 33.2 |
gwastro/pycbc | pycbc/types/array.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/types/array.py#L944-L959 | def lal(self):
""" Returns a LAL Object that contains this data """
lal_data = None
if self._data.dtype == float32:
lal_data = _lal.CreateREAL4Vector(len(self))
elif self._data.dtype == float64:
lal_data = _lal.CreateREAL8Vector(len(self))
elif self._data... | [
"def",
"lal",
"(",
"self",
")",
":",
"lal_data",
"=",
"None",
"if",
"self",
".",
"_data",
".",
"dtype",
"==",
"float32",
":",
"lal_data",
"=",
"_lal",
".",
"CreateREAL4Vector",
"(",
"len",
"(",
"self",
")",
")",
"elif",
"self",
".",
"_data",
".",
"... | Returns a LAL Object that contains this data | [
"Returns",
"a",
"LAL",
"Object",
"that",
"contains",
"this",
"data"
] | python | train | 34.8125 |
ioos/pyoos | pyoos/parsers/hads.py | https://github.com/ioos/pyoos/blob/908660385029ecd8eccda8ab3a6b20b47b915c77/pyoos/parsers/hads.py#L160-L246 | def _parse_metadata(self, metadata):
"""
Transforms raw HADS metadata into a dictionary (station code -> props)
"""
retval = {}
# these are the first keys, afterwards follows a var-len list of variables/props
# first key always blank so skip it
field_keys = [
... | [
"def",
"_parse_metadata",
"(",
"self",
",",
"metadata",
")",
":",
"retval",
"=",
"{",
"}",
"# these are the first keys, afterwards follows a var-len list of variables/props",
"# first key always blank so skip it",
"field_keys",
"=",
"[",
"\"nesdis_id\"",
",",
"\"nwsli\"",
","... | Transforms raw HADS metadata into a dictionary (station code -> props) | [
"Transforms",
"raw",
"HADS",
"metadata",
"into",
"a",
"dictionary",
"(",
"station",
"code",
"-",
">",
"props",
")"
] | python | train | 30.862069 |
Opentrons/opentrons | api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py#L1438-L1488 | async def update_firmware(self,
filename: str,
loop: asyncio.AbstractEventLoop = None,
explicit_modeset: bool = True) -> str:
"""
Program the smoothie board with a given hex file.
If explicit_modeset is Tr... | [
"async",
"def",
"update_firmware",
"(",
"self",
",",
"filename",
":",
"str",
",",
"loop",
":",
"asyncio",
".",
"AbstractEventLoop",
"=",
"None",
",",
"explicit_modeset",
":",
"bool",
"=",
"True",
")",
"->",
"str",
":",
"# ensure there is a reference to the port"... | Program the smoothie board with a given hex file.
If explicit_modeset is True (default), explicitly place the smoothie in
programming mode.
If explicit_modeset is False, assume the smoothie is already in
programming mode. | [
"Program",
"the",
"smoothie",
"board",
"with",
"a",
"given",
"hex",
"file",
"."
] | python | train | 33.784314 |
hoh/Hereby | hereby.py | https://github.com/hoh/Hereby/blob/a5f8bcdcb667e1fe1e64f542162e15ec31741505/hereby.py#L33-L36 | def open(self, path, mode='r', *args, **kwargs):
"""Proxy to function `open` with path to the current file."""
return open(os.path.join(os.path.dirname(self.path), path),
mode=mode, *args, **kwargs) | [
"def",
"open",
"(",
"self",
",",
"path",
",",
"mode",
"=",
"'r'",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"path",
")... | Proxy to function `open` with path to the current file. | [
"Proxy",
"to",
"function",
"open",
"with",
"path",
"to",
"the",
"current",
"file",
"."
] | python | train | 57.75 |
EmbodiedCognition/pagoda | pagoda/physics.py | https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/physics.py#L1012-L1015 | def axes(self):
'''A list of axes of rotation for this joint.'''
return [np.array(self.ode_obj.getAxis1()),
np.array(self.ode_obj.getAxis2())] | [
"def",
"axes",
"(",
"self",
")",
":",
"return",
"[",
"np",
".",
"array",
"(",
"self",
".",
"ode_obj",
".",
"getAxis1",
"(",
")",
")",
",",
"np",
".",
"array",
"(",
"self",
".",
"ode_obj",
".",
"getAxis2",
"(",
")",
")",
"]"
] | A list of axes of rotation for this joint. | [
"A",
"list",
"of",
"axes",
"of",
"rotation",
"for",
"this",
"joint",
"."
] | python | valid | 42.75 |
T-002/pycast | pycast/common/decorators.py | https://github.com/T-002/pycast/blob/8a53505c6d8367e0ea572e8af768e80b29e1cc41/pycast/common/decorators.py#L25-L68 | def optimized(fn):
"""Decorator that will call the optimized c++ version
of a pycast function if available rather than theo
original pycast function
:param function fn: original pycast function
:return: return the wrapped function
:rtype: function
"""
def _optimized(self, *args, **kwa... | [
"def",
"optimized",
"(",
"fn",
")",
":",
"def",
"_optimized",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\" This method calls the pycastC function if\n optimization is enabled and the pycastC function\n is available.\n\n :param: ... | Decorator that will call the optimized c++ version
of a pycast function if available rather than theo
original pycast function
:param function fn: original pycast function
:return: return the wrapped function
:rtype: function | [
"Decorator",
"that",
"will",
"call",
"the",
"optimized",
"c",
"++",
"version",
"of",
"a",
"pycast",
"function",
"if",
"available",
"rather",
"than",
"theo",
"original",
"pycast",
"function"
] | python | train | 40.681818 |
3ll3d00d/vibe | backend/src/analyser/common/targetcontroller.py | https://github.com/3ll3d00d/vibe/blob/124b029f13ac746723e92cb47e9cb56edd2e54b5/backend/src/analyser/common/targetcontroller.py#L140-L152 | def log_interp1d(self, xx, yy, kind='linear'):
"""
Performs a log space 1d interpolation.
:param xx: the x values.
:param yy: the y values.
:param kind: the type of interpolation to apply (as per scipy interp1d)
:return: the interpolation function.
"""
log... | [
"def",
"log_interp1d",
"(",
"self",
",",
"xx",
",",
"yy",
",",
"kind",
"=",
"'linear'",
")",
":",
"logx",
"=",
"np",
".",
"log10",
"(",
"xx",
")",
"logy",
"=",
"np",
".",
"log10",
"(",
"yy",
")",
"lin_interp",
"=",
"interp1d",
"(",
"logx",
",",
... | Performs a log space 1d interpolation.
:param xx: the x values.
:param yy: the y values.
:param kind: the type of interpolation to apply (as per scipy interp1d)
:return: the interpolation function. | [
"Performs",
"a",
"log",
"space",
"1d",
"interpolation",
".",
":",
"param",
"xx",
":",
"the",
"x",
"values",
".",
":",
"param",
"yy",
":",
"the",
"y",
"values",
".",
":",
"param",
"kind",
":",
"the",
"type",
"of",
"interpolation",
"to",
"apply",
"(",
... | python | train | 38.769231 |
worldcompany/djangoembed | oembed/utils.py | https://github.com/worldcompany/djangoembed/blob/f3f2be283441d91d1f89db780444dc75f7b51902/oembed/utils.py#L124-L132 | def load_class(path):
"""
dynamically load a class given a string of the format
package.Class
"""
package, klass = path.rsplit('.', 1)
module = import_module(package)
return getattr(module, klass) | [
"def",
"load_class",
"(",
"path",
")",
":",
"package",
",",
"klass",
"=",
"path",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"module",
"=",
"import_module",
"(",
"package",
")",
"return",
"getattr",
"(",
"module",
",",
"klass",
")"
] | dynamically load a class given a string of the format
package.Class | [
"dynamically",
"load",
"a",
"class",
"given",
"a",
"string",
"of",
"the",
"format",
"package",
".",
"Class"
] | python | valid | 24.555556 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.