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 |
|---|---|---|---|---|---|---|---|---|---|
daler/gffutils | gffutils/helpers.py | https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/helpers.py#L415-L425 | def is_gff_db(db_fname):
"""
Return True if the given filename is a GFF database.
For now, rely on .db extension.
"""
if not os.path.isfile(db_fname):
return False
if db_fname.endswith(".db"):
return True
return False | [
"def",
"is_gff_db",
"(",
"db_fname",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"db_fname",
")",
":",
"return",
"False",
"if",
"db_fname",
".",
"endswith",
"(",
"\".db\"",
")",
":",
"return",
"True",
"return",
"False"
] | Return True if the given filename is a GFF database.
For now, rely on .db extension. | [
"Return",
"True",
"if",
"the",
"given",
"filename",
"is",
"a",
"GFF",
"database",
"."
] | python | train | 22.909091 |
quodlibet/mutagen | mutagen/id3/_frames.py | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/id3/_frames.py#L236-L292 | def _fromData(cls, header, tflags, data):
"""Construct this ID3 frame from raw string data.
Raises:
ID3JunkFrameError in case parsing failed
NotImplementedError in case parsing isn't implemented
ID3EncryptionUnsupportedError in case the frame is encrypted.
"""
... | [
"def",
"_fromData",
"(",
"cls",
",",
"header",
",",
"tflags",
",",
"data",
")",
":",
"if",
"header",
".",
"version",
">=",
"header",
".",
"_V24",
":",
"if",
"tflags",
"&",
"(",
"Frame",
".",
"FLAG24_COMPRESS",
"|",
"Frame",
".",
"FLAG24_DATALEN",
")",
... | Construct this ID3 frame from raw string data.
Raises:
ID3JunkFrameError in case parsing failed
NotImplementedError in case parsing isn't implemented
ID3EncryptionUnsupportedError in case the frame is encrypted. | [
"Construct",
"this",
"ID3",
"frame",
"from",
"raw",
"string",
"data",
"."
] | python | train | 43.157895 |
nfcpy/nfcpy | src/nfc/tag/tt3_sony.py | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt3_sony.py#L727-L748 | def write_without_mac(self, data, block):
"""Write a data block without integrity check.
This is the standard write method for a FeliCa Lite. The
16-byte string or bytearray *data* is written to the numbered
*block* in service 0x0009 (NDEF write service). ::
data = bytearra... | [
"def",
"write_without_mac",
"(",
"self",
",",
"data",
",",
"block",
")",
":",
"# Write a single data block without a mac. Write with mac is",
"# only supported by FeliCa Lite-S.",
"assert",
"len",
"(",
"data",
")",
"==",
"16",
"and",
"type",
"(",
"block",
")",
"is",
... | Write a data block without integrity check.
This is the standard write method for a FeliCa Lite. The
16-byte string or bytearray *data* is written to the numbered
*block* in service 0x0009 (NDEF write service). ::
data = bytearray(range(16)) # 0x00, 0x01, ... 0x0F
try: ... | [
"Write",
"a",
"data",
"block",
"without",
"integrity",
"check",
"."
] | python | train | 42.818182 |
Erotemic/ubelt | ubelt/util_path.py | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_path.py#L201-L237 | def truepath(path, real=False):
"""
Normalizes a string representation of a path and does shell-like expansion.
Args:
path (PathLike): string representation of a path
real (bool): if True, all symbolic links are followed. (default: False)
Returns:
PathLike : normalized path
... | [
"def",
"truepath",
"(",
"path",
",",
"real",
"=",
"False",
")",
":",
"path",
"=",
"expanduser",
"(",
"path",
")",
"path",
"=",
"expandvars",
"(",
"path",
")",
"if",
"real",
":",
"path",
"=",
"realpath",
"(",
"path",
")",
"else",
":",
"path",
"=",
... | Normalizes a string representation of a path and does shell-like expansion.
Args:
path (PathLike): string representation of a path
real (bool): if True, all symbolic links are followed. (default: False)
Returns:
PathLike : normalized path
Note:
This function is similar to ... | [
"Normalizes",
"a",
"string",
"representation",
"of",
"a",
"path",
"and",
"does",
"shell",
"-",
"like",
"expansion",
"."
] | python | valid | 32.891892 |
PyCQA/pylint | pylint/checkers/refactoring.py | https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/refactoring.py#L595-L608 | def _check_stop_iteration_inside_generator(self, node):
"""Check if an exception of type StopIteration is raised inside a generator"""
frame = node.frame()
if not isinstance(frame, astroid.FunctionDef) or not frame.is_generator():
return
if utils.node_ignores_exception(node, ... | [
"def",
"_check_stop_iteration_inside_generator",
"(",
"self",
",",
"node",
")",
":",
"frame",
"=",
"node",
".",
"frame",
"(",
")",
"if",
"not",
"isinstance",
"(",
"frame",
",",
"astroid",
".",
"FunctionDef",
")",
"or",
"not",
"frame",
".",
"is_generator",
... | Check if an exception of type StopIteration is raised inside a generator | [
"Check",
"if",
"an",
"exception",
"of",
"type",
"StopIteration",
"is",
"raised",
"inside",
"a",
"generator"
] | python | test | 45 |
project-ncl/pnc-cli | pnc_cli/products.py | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/products.py#L28-L34 | def create_product(name, abbreviation, **kwargs):
"""
Create a new Product
"""
data = create_product_raw(name, abbreviation, **kwargs)
if data:
return utils.format_json(data) | [
"def",
"create_product",
"(",
"name",
",",
"abbreviation",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"create_product_raw",
"(",
"name",
",",
"abbreviation",
",",
"*",
"*",
"kwargs",
")",
"if",
"data",
":",
"return",
"utils",
".",
"format_json",
"("... | Create a new Product | [
"Create",
"a",
"new",
"Product"
] | python | train | 28 |
aequitas/python-rflink | rflink/parser.py | https://github.com/aequitas/python-rflink/blob/46759ce8daf95cfc7cdb608ae17bc5501be9f6d8/rflink/parser.py#L225-L289 | def decode_packet(packet: str) -> dict:
"""Break packet down into primitives, and do basic interpretation.
>>> decode_packet('20;06;Kaku;ID=41;SWITCH=1;CMD=ON;') == {
... 'node': 'gateway',
... 'protocol': 'kaku',
... 'id': '000041',
... 'switch': '1',
... 'command': 'on... | [
"def",
"decode_packet",
"(",
"packet",
":",
"str",
")",
"->",
"dict",
":",
"node_id",
",",
"_",
",",
"protocol",
",",
"attrs",
"=",
"packet",
".",
"split",
"(",
"DELIM",
",",
"3",
")",
"data",
"=",
"cast",
"(",
"Dict",
"[",
"str",
",",
"Any",
"]"... | Break packet down into primitives, and do basic interpretation.
>>> decode_packet('20;06;Kaku;ID=41;SWITCH=1;CMD=ON;') == {
... 'node': 'gateway',
... 'protocol': 'kaku',
... 'id': '000041',
... 'switch': '1',
... 'command': 'on',
... }
True | [
"Break",
"packet",
"down",
"into",
"primitives",
"and",
"do",
"basic",
"interpretation",
"."
] | python | train | 27 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/core/api/user.py | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/user.py#L17-L31 | def get_user_token(login, password):
"""Retrieve user token from the API (via authentication)."""
client = get_user_api()
# Never use API key for the token endpoint
config = cloudsmith_api.Configuration()
set_api_key(config, None)
with catch_raise_api_exception():
data, _, headers = cl... | [
"def",
"get_user_token",
"(",
"login",
",",
"password",
")",
":",
"client",
"=",
"get_user_api",
"(",
")",
"# Never use API key for the token endpoint",
"config",
"=",
"cloudsmith_api",
".",
"Configuration",
"(",
")",
"set_api_key",
"(",
"config",
",",
"None",
")"... | Retrieve user token from the API (via authentication). | [
"Retrieve",
"user",
"token",
"from",
"the",
"API",
"(",
"via",
"authentication",
")",
"."
] | python | train | 32.133333 |
FNNDSC/med2image | med2image/systemMisc.py | https://github.com/FNNDSC/med2image/blob/638d5d230de47608af20f9764acf8e382c2bf2ff/med2image/systemMisc.py#L1034-L1047 | def shellne(command):
"""
Runs 'commands' on the underlying shell; any stderr is echo'd to the
console.
Raises a RuntimeException on any shell exec errors.
"""
child = os.popen(command)
data = child.read()
err = child.close()
if err:
raise RuntimeError('%s faile... | [
"def",
"shellne",
"(",
"command",
")",
":",
"child",
"=",
"os",
".",
"popen",
"(",
"command",
")",
"data",
"=",
"child",
".",
"read",
"(",
")",
"err",
"=",
"child",
".",
"close",
"(",
")",
"if",
"err",
":",
"raise",
"RuntimeError",
"(",
"'%s failed... | Runs 'commands' on the underlying shell; any stderr is echo'd to the
console.
Raises a RuntimeException on any shell exec errors. | [
"Runs",
"commands",
"on",
"the",
"underlying",
"shell",
";",
"any",
"stderr",
"is",
"echo",
"d",
"to",
"the",
"console",
"."
] | python | train | 25.642857 |
awslabs/sockeye | sockeye/init_embedding.py | https://github.com/awslabs/sockeye/blob/5d64a1ee1ef3cbba17c6d1d94bc061020c43f6ab/sockeye/init_embedding.py#L123-L136 | def main():
"""
Commandline interface to initialize Sockeye embedding weights with pretrained word representations.
"""
setup_main_logger(console=True, file_logging=False)
params = argparse.ArgumentParser(description='Quick usage: python3 -m sockeye.init_embedding '
... | [
"def",
"main",
"(",
")",
":",
"setup_main_logger",
"(",
"console",
"=",
"True",
",",
"file_logging",
"=",
"False",
")",
"params",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Quick usage: python3 -m sockeye.init_embedding '",
"'-w embed-in-src.np... | Commandline interface to initialize Sockeye embedding weights with pretrained word representations. | [
"Commandline",
"interface",
"to",
"initialize",
"Sockeye",
"embedding",
"weights",
"with",
"pretrained",
"word",
"representations",
"."
] | python | train | 57.928571 |
scrapinghub/exporters | exporters/iterio.py | https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/iterio.py#L158-L180 | def seek(self, offset, from_what=0):
"""
seek(offset, from_what=0) -> int. Change stream position.
Seek to byte offset pos relative to position indicated by whence:
0 Start of stream (the default). pos should be >= tell();
1 Current position - negative pos not impl... | [
"def",
"seek",
"(",
"self",
",",
"offset",
",",
"from_what",
"=",
"0",
")",
":",
"if",
"from_what",
"==",
"0",
":",
"# From the begining",
"if",
"offset",
">=",
"self",
".",
"tell",
"(",
")",
":",
"self",
".",
"seek",
"(",
"offset",
"-",
"self",
".... | seek(offset, from_what=0) -> int. Change stream position.
Seek to byte offset pos relative to position indicated by whence:
0 Start of stream (the default). pos should be >= tell();
1 Current position - negative pos not implemented;
2 End of stream - not implemented.... | [
"seek",
"(",
"offset",
"from_what",
"=",
"0",
")",
"-",
">",
"int",
".",
"Change",
"stream",
"position",
"."
] | python | train | 41.173913 |
DLR-RM/RAFCON | source/rafcon/gui/mygaphas/constraint.py | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/constraint.py#L134-L149 | def solve_for(self, var=None):
"""
Ensure that the children is within its parent
"""
margin = self.margin_method()
if self.parent_nw[0].value > self.child[0].value - margin:
_update(self.child[0], self.parent_nw[0].value + margin)
# Right edge (east)
i... | [
"def",
"solve_for",
"(",
"self",
",",
"var",
"=",
"None",
")",
":",
"margin",
"=",
"self",
".",
"margin_method",
"(",
")",
"if",
"self",
".",
"parent_nw",
"[",
"0",
"]",
".",
"value",
">",
"self",
".",
"child",
"[",
"0",
"]",
".",
"value",
"-",
... | Ensure that the children is within its parent | [
"Ensure",
"that",
"the",
"children",
"is",
"within",
"its",
"parent"
] | python | train | 47.5625 |
ramses-tech/nefertari | nefertari/view.py | https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/view.py#L136-L158 | def prepare_request_params(self, _query_params, _json_params):
""" Prepare query and update params. """
self._query_params = dictset(
_query_params or self.request.params.mixed())
self._json_params = dictset(_json_params)
ctype = self.request.content_type
if self.req... | [
"def",
"prepare_request_params",
"(",
"self",
",",
"_query_params",
",",
"_json_params",
")",
":",
"self",
".",
"_query_params",
"=",
"dictset",
"(",
"_query_params",
"or",
"self",
".",
"request",
".",
"params",
".",
"mixed",
"(",
")",
")",
"self",
".",
"_... | Prepare query and update params. | [
"Prepare",
"query",
"and",
"update",
"params",
"."
] | python | train | 44.434783 |
sebp/scikit-survival | sksurv/util.py | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/util.py#L28-L73 | def from_arrays(event, time, name_event=None, name_time=None):
"""Create structured array.
Parameters
----------
event : array-like
Event indicator. A boolean array or array with values 0/1.
time : array-like
Observed time.
name_event : str|None
... | [
"def",
"from_arrays",
"(",
"event",
",",
"time",
",",
"name_event",
"=",
"None",
",",
"name_time",
"=",
"None",
")",
":",
"name_event",
"=",
"name_event",
"or",
"'event'",
"name_time",
"=",
"name_time",
"or",
"'time'",
"if",
"name_time",
"==",
"name_event",
... | Create structured array.
Parameters
----------
event : array-like
Event indicator. A boolean array or array with values 0/1.
time : array-like
Observed time.
name_event : str|None
Name of event, optional, default: 'event'
name_time : s... | [
"Create",
"structured",
"array",
"."
] | python | train | 33.804348 |
brocade/pynos | pynos/versions/ver_7/ver_7_1_0/yang/brocade_lldp_ext.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_lldp_ext.py#L12-L25 | def get_lldp_neighbor_detail_input_request_type_get_request_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_lldp_neighbor_detail = ET.Element("get_lldp_neighbor_detail")
config = get_lldp_neighbor_detail
input = ET.SubElement(g... | [
"def",
"get_lldp_neighbor_detail_input_request_type_get_request_interface_type",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_lldp_neighbor_detail",
"=",
"ET",
".",
"Element",
"(",
"\"get_lldp_neighb... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 48.928571 |
google/grr | grr/core/grr_response_core/lib/util/collection.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/core/grr_response_core/lib/util/collection.py#L128-L154 | def Unzip(iterable):
"""Unzips specified iterable of pairs to pair of two iterables.
This function is an inversion of the standard `zip` function and the following
hold:
* ∀ l, r. l, r == unzip(zip(l, r))
* ∀ p. p == zip(unzip(p))
Examples:
>>> Unzip([("foo", 1), ("bar", 2), ("baz", 3)])
(["f... | [
"def",
"Unzip",
"(",
"iterable",
")",
":",
"lefts",
"=",
"[",
"]",
"rights",
"=",
"[",
"]",
"for",
"left",
",",
"right",
"in",
"iterable",
":",
"lefts",
".",
"append",
"(",
"left",
")",
"rights",
".",
"append",
"(",
"right",
")",
"return",
"lefts",... | Unzips specified iterable of pairs to pair of two iterables.
This function is an inversion of the standard `zip` function and the following
hold:
* ∀ l, r. l, r == unzip(zip(l, r))
* ∀ p. p == zip(unzip(p))
Examples:
>>> Unzip([("foo", 1), ("bar", 2), ("baz", 3)])
(["foo", "bar", "baz"], [1, 2,... | [
"Unzips",
"specified",
"iterable",
"of",
"pairs",
"to",
"pair",
"of",
"two",
"iterables",
"."
] | python | train | 21.037037 |
sprockets/sprockets.http | sprockets/http/app.py | https://github.com/sprockets/sprockets.http/blob/8baa4cdc1fa35a162ee226fd6cc4170a0ca0ecd3/sprockets/http/app.py#L106-L136 | def stop(self, io_loop):
"""
Asynchronously stop the application.
:param tornado.ioloop.IOLoop io_loop: loop to run until all
callbacks, timeouts, and queued calls are complete
Call this method to start the application shutdown process.
The IOLoop will be stopped on... | [
"def",
"stop",
"(",
"self",
",",
"io_loop",
")",
":",
"running_async",
"=",
"False",
"shutdown",
"=",
"_ShutdownHandler",
"(",
"io_loop",
")",
"for",
"callback",
"in",
"self",
".",
"on_shutdown_callbacks",
":",
"try",
":",
"maybe_future",
"=",
"callback",
"(... | Asynchronously stop the application.
:param tornado.ioloop.IOLoop io_loop: loop to run until all
callbacks, timeouts, and queued calls are complete
Call this method to start the application shutdown process.
The IOLoop will be stopped once the application is completely
shut... | [
"Asynchronously",
"stop",
"the",
"application",
"."
] | python | train | 37.064516 |
izacus/pysolarized | pysolarized/solr.py | https://github.com/izacus/pysolarized/blob/d820e20a45b63e5b88b0421eb703037a8d7ad4a3/pysolarized/solr.py#L158-L169 | def _get_shards(self):
"""
Returns comma separated list of configured Solr cores
"""
if self._shards is None:
endpoints = []
for endpoint in self.endpoints:
# We need to remove and http:// prefixes from URLs
url = urlparse.urlparse(... | [
"def",
"_get_shards",
"(",
"self",
")",
":",
"if",
"self",
".",
"_shards",
"is",
"None",
":",
"endpoints",
"=",
"[",
"]",
"for",
"endpoint",
"in",
"self",
".",
"endpoints",
":",
"# We need to remove and http:// prefixes from URLs",
"url",
"=",
"urlparse",
".",... | Returns comma separated list of configured Solr cores | [
"Returns",
"comma",
"separated",
"list",
"of",
"configured",
"Solr",
"cores"
] | python | train | 39.666667 |
pypa/pipenv | pipenv/vendor/pep517/envbuild.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pep517/envbuild.py#L117-L136 | def build_wheel(source_dir, wheel_dir, config_settings=None):
"""Build a wheel from a source directory using PEP 517 hooks.
:param str source_dir: Source directory containing pyproject.toml
:param str wheel_dir: Target directory to create wheel in
:param dict config_settings: Options to pass to build b... | [
"def",
"build_wheel",
"(",
"source_dir",
",",
"wheel_dir",
",",
"config_settings",
"=",
"None",
")",
":",
"if",
"config_settings",
"is",
"None",
":",
"config_settings",
"=",
"{",
"}",
"requires",
",",
"backend",
"=",
"_load_pyproject",
"(",
"source_dir",
")",
... | Build a wheel from a source directory using PEP 517 hooks.
:param str source_dir: Source directory containing pyproject.toml
:param str wheel_dir: Target directory to create wheel in
:param dict config_settings: Options to pass to build backend
This is a blocking function which will run pip in a subpr... | [
"Build",
"a",
"wheel",
"from",
"a",
"source",
"directory",
"using",
"PEP",
"517",
"hooks",
"."
] | python | train | 40.5 |
tensorpack/tensorpack | tensorpack/callbacks/monitor.py | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/monitor.py#L193-L203 | def put_event(self, evt):
"""
Put an :class:`tf.Event`.
`step` and `wall_time` fields of :class:`tf.Event` will be filled automatically.
Args:
evt (tf.Event):
"""
evt.step = self.global_step
evt.wall_time = time.time()
self._dispatch(lambda m:... | [
"def",
"put_event",
"(",
"self",
",",
"evt",
")",
":",
"evt",
".",
"step",
"=",
"self",
".",
"global_step",
"evt",
".",
"wall_time",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"_dispatch",
"(",
"lambda",
"m",
":",
"m",
".",
"process_event",
"... | Put an :class:`tf.Event`.
`step` and `wall_time` fields of :class:`tf.Event` will be filled automatically.
Args:
evt (tf.Event): | [
"Put",
"an",
":",
"class",
":",
"tf",
".",
"Event",
".",
"step",
"and",
"wall_time",
"fields",
"of",
":",
"class",
":",
"tf",
".",
"Event",
"will",
"be",
"filled",
"automatically",
"."
] | python | train | 30.181818 |
jaraco/keyrings.alt | keyrings/alt/file_base.py | https://github.com/jaraco/keyrings.alt/blob/5b71223d12bf9ac6abd05b1b395f1efccb5ea660/keyrings/alt/file_base.py#L96-L123 | def get_password(self, service, username):
"""
Read the password from the file.
"""
assoc = self._generate_assoc(service, username)
service = escape_for_ini(service)
username = escape_for_ini(username)
# load the passwords from the file
config = configpar... | [
"def",
"get_password",
"(",
"self",
",",
"service",
",",
"username",
")",
":",
"assoc",
"=",
"self",
".",
"_generate_assoc",
"(",
"service",
",",
"username",
")",
"service",
"=",
"escape_for_ini",
"(",
"service",
")",
"username",
"=",
"escape_for_ini",
"(",
... | Read the password from the file. | [
"Read",
"the",
"password",
"from",
"the",
"file",
"."
] | python | train | 38.464286 |
tensorflow/tensorboard | tensorboard/plugins/interactive_inference/utils/inference_utils.py | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/interactive_inference/utils/inference_utils.py#L225-L234 | def proto_value_for_feature(example, feature_name):
"""Get the value of a feature from Example regardless of feature type."""
feature = get_example_features(example)[feature_name]
if feature is None:
raise ValueError('Feature {} is not on example proto.'.format(feature_name))
feature_type = feature.WhichOne... | [
"def",
"proto_value_for_feature",
"(",
"example",
",",
"feature_name",
")",
":",
"feature",
"=",
"get_example_features",
"(",
"example",
")",
"[",
"feature_name",
"]",
"if",
"feature",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Feature {} is not on example pro... | Get the value of a feature from Example regardless of feature type. | [
"Get",
"the",
"value",
"of",
"a",
"feature",
"from",
"Example",
"regardless",
"of",
"feature",
"type",
"."
] | python | train | 49.8 |
spotify/docker_interface | docker_interface/util.py | https://github.com/spotify/docker_interface/blob/4df80e1fe072d958020080d32c16551ff7703d51/docker_interface/util.py#L139-L157 | def set_value(instance, path, value, ref=None):
"""
Set `value` on `instance` at the given `path` and create missing intermediate objects.
Parameters
----------
instance : dict or list
instance from which to retrieve a value
path : str
path to retrieve a value from
value :
... | [
"def",
"set_value",
"(",
"instance",
",",
"path",
",",
"value",
",",
"ref",
"=",
"None",
")",
":",
"",
"*",
"head",
",",
"tail",
"=",
"split_path",
"(",
"path",
",",
"ref",
")",
"for",
"part",
"in",
"head",
":",
"instance",
"=",
"instance",
".",
... | Set `value` on `instance` at the given `path` and create missing intermediate objects.
Parameters
----------
instance : dict or list
instance from which to retrieve a value
path : str
path to retrieve a value from
value :
value to set
ref : str or None
reference ... | [
"Set",
"value",
"on",
"instance",
"at",
"the",
"given",
"path",
"and",
"create",
"missing",
"intermediate",
"objects",
"."
] | python | train | 28.105263 |
numenta/nupic | src/nupic/encoders/coordinate.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/encoders/coordinate.py#L179-L189 | def _bitForCoordinate(cls, coordinate, n):
"""
Maps the coordinate to a bit in the SDR.
@param coordinate (numpy.array) Coordinate
@param n (int) The number of available bits in the SDR
@return (int) The index to a bit in the SDR
"""
seed = cls._hashCoordinate(coordinate)
rng = Random(s... | [
"def",
"_bitForCoordinate",
"(",
"cls",
",",
"coordinate",
",",
"n",
")",
":",
"seed",
"=",
"cls",
".",
"_hashCoordinate",
"(",
"coordinate",
")",
"rng",
"=",
"Random",
"(",
"seed",
")",
"return",
"rng",
".",
"getUInt32",
"(",
"n",
")"
] | Maps the coordinate to a bit in the SDR.
@param coordinate (numpy.array) Coordinate
@param n (int) The number of available bits in the SDR
@return (int) The index to a bit in the SDR | [
"Maps",
"the",
"coordinate",
"to",
"a",
"bit",
"in",
"the",
"SDR",
"."
] | python | valid | 31.090909 |
openai/baselines | baselines/common/plot_util.py | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/plot_util.py#L240-L375 | def plot_results(
allresults, *,
xy_fn=default_xy_fn,
split_fn=default_split_fn,
group_fn=default_split_fn,
average_group=False,
shaded_std=True,
shaded_err=True,
figsize=None,
legend_outside=False,
resample=0,
smooth_step=1.0
):
'''
Plot multiple Results objects
... | [
"def",
"plot_results",
"(",
"allresults",
",",
"*",
",",
"xy_fn",
"=",
"default_xy_fn",
",",
"split_fn",
"=",
"default_split_fn",
",",
"group_fn",
"=",
"default_split_fn",
",",
"average_group",
"=",
"False",
",",
"shaded_std",
"=",
"True",
",",
"shaded_err",
"... | Plot multiple Results objects
xy_fn: function Result -> x,y - function that converts results objects into tuple of x and y values.
By default, x is cumsum of episode lengths, and y is episode rewards
split_fn: function Result -> hashable - function tha... | [
"Plot",
"multiple",
"Results",
"objects"
] | python | valid | 50.198529 |
gccxml/pygccxml | pygccxml/declarations/pattern_parser.py | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/pattern_parser.py#L32-L46 | def has_pattern(self, decl_string):
"""
Implementation detail
"""
if self.__begin == "<":
# Cleanup parentheses blocks before checking for the pattern
# See also the args() method (in this file) for more explanations.
decl_string = re.sub("\\s\\(.*?\\... | [
"def",
"has_pattern",
"(",
"self",
",",
"decl_string",
")",
":",
"if",
"self",
".",
"__begin",
"==",
"\"<\"",
":",
"# Cleanup parentheses blocks before checking for the pattern",
"# See also the args() method (in this file) for more explanations.",
"decl_string",
"=",
"re",
"... | Implementation detail | [
"Implementation",
"detail"
] | python | train | 33.866667 |
spyder-ide/spyder | spyder/plugins/explorer/widgets.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/explorer/widgets.py#L218-L226 | def get_selected_filenames(self):
"""Return selected filenames"""
if self.selectionMode() == self.ExtendedSelection:
if self.selectionModel() is None:
return []
return [self.get_filename(idx) for idx in
self.selectionModel().selectedRows... | [
"def",
"get_selected_filenames",
"(",
"self",
")",
":",
"if",
"self",
".",
"selectionMode",
"(",
")",
"==",
"self",
".",
"ExtendedSelection",
":",
"if",
"self",
".",
"selectionModel",
"(",
")",
"is",
"None",
":",
"return",
"[",
"]",
"return",
"[",
"self"... | Return selected filenames | [
"Return",
"selected",
"filenames"
] | python | train | 43.444444 |
rosenbrockc/fortpy | fortpy/parsers/docstring.py | https://github.com/rosenbrockc/fortpy/blob/1ed0757c52d549e41d9d44bdea68cb89529293a5/fortpy/parsers/docstring.py#L356-L380 | def process_memberdocs(self, docs, codeEl, add=True):
"""Associates member type DocElements with their corresponding members
in the specified code element. The element must have a dictionary of
members already."""
#Now we need to associate the members with their docstrings
... | [
"def",
"process_memberdocs",
"(",
"self",
",",
"docs",
",",
"codeEl",
",",
"add",
"=",
"True",
")",
":",
"#Now we need to associate the members with their docstrings",
"#Some of the members may be buried inside a group tag and",
"#need to be handled separately.",
"remainingdocs",
... | Associates member type DocElements with their corresponding members
in the specified code element. The element must have a dictionary of
members already. | [
"Associates",
"member",
"type",
"DocElements",
"with",
"their",
"corresponding",
"members",
"in",
"the",
"specified",
"code",
"element",
".",
"The",
"element",
"must",
"have",
"a",
"dictionary",
"of",
"members",
"already",
"."
] | python | train | 44.64 |
craft-ai/craft-ai-client-python | craftai/client.py | https://github.com/craft-ai/craft-ai-client-python/blob/8bc1a9038511540930371aacfdde0f4040e08f24/craftai/client.py#L333-L368 | def _add_operations_bulk(self, chunked_data):
"""Tool for the function add_operations_bulk. It send the requests to
add the operations to the agents.
:param list chunked_data: list of list of the agents and their operations
to add. Each chunk can be requested at the same time.
:return: list of age... | [
"def",
"_add_operations_bulk",
"(",
"self",
",",
"chunked_data",
")",
":",
"url",
"=",
"\"{}/bulk/context\"",
".",
"format",
"(",
"self",
".",
"_base_url",
")",
"ct_header",
"=",
"{",
"\"Content-Type\"",
":",
"\"application/json; charset=utf-8\"",
"}",
"responses",
... | Tool for the function add_operations_bulk. It send the requests to
add the operations to the agents.
:param list chunked_data: list of list of the agents and their operations
to add. Each chunk can be requested at the same time.
:return: list of agents containing a message about the added
operatio... | [
"Tool",
"for",
"the",
"function",
"add_operations_bulk",
".",
"It",
"send",
"the",
"requests",
"to",
"add",
"the",
"operations",
"to",
"the",
"agents",
"."
] | python | train | 39.555556 |
openstack/networking-cisco | networking_cisco/apps/saf/agent/vdp/dfa_vdp_mgr.py | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/agent/vdp/dfa_vdp_mgr.py#L404-L413 | def _fill_topology_cfg(self, topo_dict):
"""Fills the extra configurations in the topology. """
cfg_dict = {}
if topo_dict.bond_member_ports is not None:
cfg_dict.update({'bond_member_ports':
topo_dict.bond_member_ports})
if topo_dict.bond_interfa... | [
"def",
"_fill_topology_cfg",
"(",
"self",
",",
"topo_dict",
")",
":",
"cfg_dict",
"=",
"{",
"}",
"if",
"topo_dict",
".",
"bond_member_ports",
"is",
"not",
"None",
":",
"cfg_dict",
".",
"update",
"(",
"{",
"'bond_member_ports'",
":",
"topo_dict",
".",
"bond_m... | Fills the extra configurations in the topology. | [
"Fills",
"the",
"extra",
"configurations",
"in",
"the",
"topology",
"."
] | python | train | 45.3 |
rbuffat/pyepw | pyepw/epw.py | https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L451-L476 | def export(self, top=True):
"""Exports object to its string representation.
Args:
top (bool): if True appends `internal_name` before values.
All non list objects should be exported with value top=True,
all list objects, that are embedded in as fields inlist ... | [
"def",
"export",
"(",
"self",
",",
"top",
"=",
"True",
")",
":",
"out",
"=",
"[",
"]",
"if",
"top",
":",
"out",
".",
"append",
"(",
"self",
".",
"_internal_name",
")",
"out",
".",
"append",
"(",
"self",
".",
"_to_str",
"(",
"self",
".",
"city",
... | Exports object to its string representation.
Args:
top (bool): if True appends `internal_name` before values.
All non list objects should be exported with value top=True,
all list objects, that are embedded in as fields inlist objects
should be expor... | [
"Exports",
"object",
"to",
"its",
"string",
"representation",
"."
] | python | train | 37.576923 |
MDAnalysis/GridDataFormats | gridData/core.py | https://github.com/MDAnalysis/GridDataFormats/blob/3eeb0432f8cf856912436e4f3e7aba99d3c916be/gridData/core.py#L396-L401 | def _load_dx(self, filename):
"""Initializes Grid from a OpenDX file."""
dx = OpenDX.field(0)
dx.read(filename)
grid, edges = dx.histogramdd()
self.__init__(grid=grid, edges=edges, metadata=self.metadata) | [
"def",
"_load_dx",
"(",
"self",
",",
"filename",
")",
":",
"dx",
"=",
"OpenDX",
".",
"field",
"(",
"0",
")",
"dx",
".",
"read",
"(",
"filename",
")",
"grid",
",",
"edges",
"=",
"dx",
".",
"histogramdd",
"(",
")",
"self",
".",
"__init__",
"(",
"gr... | Initializes Grid from a OpenDX file. | [
"Initializes",
"Grid",
"from",
"a",
"OpenDX",
"file",
"."
] | python | valid | 39.833333 |
senaite/senaite.core | bika/lims/workflow/analysisrequest/guards.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/workflow/analysisrequest/guards.py#L138-L155 | def guard_cancel(analysis_request):
"""Returns whether 'cancel' transition can be performed or not. Returns
True only if all analyses are in "unassigned" status
"""
# Ask to partitions
for partition in analysis_request.getDescendants(all_descendants=False):
if not isTransitionAllowed(partiti... | [
"def",
"guard_cancel",
"(",
"analysis_request",
")",
":",
"# Ask to partitions",
"for",
"partition",
"in",
"analysis_request",
".",
"getDescendants",
"(",
"all_descendants",
"=",
"False",
")",
":",
"if",
"not",
"isTransitionAllowed",
"(",
"partition",
",",
"\"cancel... | Returns whether 'cancel' transition can be performed or not. Returns
True only if all analyses are in "unassigned" status | [
"Returns",
"whether",
"cancel",
"transition",
"can",
"be",
"performed",
"or",
"not",
".",
"Returns",
"True",
"only",
"if",
"all",
"analyses",
"are",
"in",
"unassigned",
"status"
] | python | train | 44.277778 |
HazyResearch/fonduer | src/fonduer/supervision/labeler.py | https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/supervision/labeler.py#L77-L151 | def apply(
self,
docs=None,
split=0,
train=False,
lfs=None,
clear=True,
parallelism=None,
progress_bar=True,
):
"""Apply the labels of the specified candidates based on the provided LFs.
:param docs: If provided, apply the LFs to all t... | [
"def",
"apply",
"(",
"self",
",",
"docs",
"=",
"None",
",",
"split",
"=",
"0",
",",
"train",
"=",
"False",
",",
"lfs",
"=",
"None",
",",
"clear",
"=",
"True",
",",
"parallelism",
"=",
"None",
",",
"progress_bar",
"=",
"True",
",",
")",
":",
"if",... | Apply the labels of the specified candidates based on the provided LFs.
:param docs: If provided, apply the LFs to all the candidates in these
documents.
:param split: If docs is None, apply the LFs to the candidates in this
particular split.
:type split: int
:pa... | [
"Apply",
"the",
"labels",
"of",
"the",
"specified",
"candidates",
"based",
"on",
"the",
"provided",
"LFs",
"."
] | python | train | 36.026667 |
cslarsen/crianza | crianza/interpreter.py | https://github.com/cslarsen/crianza/blob/fa044f9d491f37cc06892bad14b2c80b8ac5a7cd/crianza/interpreter.py#L178-L197 | def run(self, steps=None):
"""Run threaded code in machine.
Args:
steps: If specified, run that many number of instructions before
stopping.
"""
try:
while self.instruction_pointer < len(self.code):
self.step()
if step... | [
"def",
"run",
"(",
"self",
",",
"steps",
"=",
"None",
")",
":",
"try",
":",
"while",
"self",
".",
"instruction_pointer",
"<",
"len",
"(",
"self",
".",
"code",
")",
":",
"self",
".",
"step",
"(",
")",
"if",
"steps",
"is",
"not",
"None",
":",
"step... | Run threaded code in machine.
Args:
steps: If specified, run that many number of instructions before
stopping. | [
"Run",
"threaded",
"code",
"in",
"machine",
"."
] | python | train | 26 |
esafak/mca | src/mca.py | https://github.com/esafak/mca/blob/f2b79ecbf37629902ccdbad2e1a556977c53d370/src/mca.py#L149-L157 | def cos_r(self, N=None): # percent=0.9
"""Return the squared cosines for each row."""
if not hasattr(self, 'F') or self.F.shape[1] < self.rank:
self.fs_r(N=self.rank) # generate F
self.dr = norm(self.F, axis=1)**2
# cheaper than diag(self.F.dot(self.F.T))?
return apply_along_axis(lambda _: _/self.dr, 0... | [
"def",
"cos_r",
"(",
"self",
",",
"N",
"=",
"None",
")",
":",
"# percent=0.9",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'F'",
")",
"or",
"self",
".",
"F",
".",
"shape",
"[",
"1",
"]",
"<",
"self",
".",
"rank",
":",
"self",
".",
"fs_r",
"(",
... | Return the squared cosines for each row. | [
"Return",
"the",
"squared",
"cosines",
"for",
"each",
"row",
"."
] | python | train | 36.777778 |
pylast/pylast | src/pylast/__init__.py | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2671-L2678 | def _retrieve_page(self, page_index):
"""Returns the node of matches to be processed"""
params = self._get_params()
params["page"] = str(page_index)
doc = self._request(self._ws_prefix + ".search", True, params)
return doc.getElementsByTagName(self._ws_prefix + "matches")[0] | [
"def",
"_retrieve_page",
"(",
"self",
",",
"page_index",
")",
":",
"params",
"=",
"self",
".",
"_get_params",
"(",
")",
"params",
"[",
"\"page\"",
"]",
"=",
"str",
"(",
"page_index",
")",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"_ws_pref... | Returns the node of matches to be processed | [
"Returns",
"the",
"node",
"of",
"matches",
"to",
"be",
"processed"
] | python | train | 38.75 |
awdeorio/mailmerge | mailmerge/api.py | https://github.com/awdeorio/mailmerge/blob/ff83f3b053ed6e182a98025873fcf3095d37b78b/mailmerge/api.py#L209-L278 | def create_sample_input_files(template_filename,
database_filename,
config_filename):
"""Create sample template email and database."""
print("Creating sample template email {}".format(template_filename))
if os.path.exists(template_filename):
... | [
"def",
"create_sample_input_files",
"(",
"template_filename",
",",
"database_filename",
",",
"config_filename",
")",
":",
"print",
"(",
"\"Creating sample template email {}\"",
".",
"format",
"(",
"template_filename",
")",
")",
"if",
"os",
".",
"path",
".",
"exists",
... | Create sample template email and database. | [
"Create",
"sample",
"template",
"email",
"and",
"database",
"."
] | python | valid | 39.342857 |
pyamg/pyamg | pyamg/aggregation/smooth.py | https://github.com/pyamg/pyamg/blob/89dc54aa27e278f65d2f54bdaf16ab97d7768fa6/pyamg/aggregation/smooth.py#L651-L877 | def gmres_prolongation_smoothing(A, T, B, BtBinv, Sparsity_Pattern, maxiter,
tol, weighting='local', Cpt_params=None):
"""Use GMRES to smooth T by solving A T = 0, subject to nullspace and sparsity constraints.
Parameters
----------
A : csr_matrix, bsr_matrix
SP... | [
"def",
"gmres_prolongation_smoothing",
"(",
"A",
",",
"T",
",",
"B",
",",
"BtBinv",
",",
"Sparsity_Pattern",
",",
"maxiter",
",",
"tol",
",",
"weighting",
"=",
"'local'",
",",
"Cpt_params",
"=",
"None",
")",
":",
"# For non-SPD system, apply GMRES with Diagonal Pr... | Use GMRES to smooth T by solving A T = 0, subject to nullspace and sparsity constraints.
Parameters
----------
A : csr_matrix, bsr_matrix
SPD sparse NxN matrix
Should be at least nonsymmetric or indefinite
T : bsr_matrix
Tentative prolongator, a NxM sparse matrix (M < N).
... | [
"Use",
"GMRES",
"to",
"smooth",
"T",
"by",
"solving",
"A",
"T",
"=",
"0",
"subject",
"to",
"nullspace",
"and",
"sparsity",
"constraints",
"."
] | python | train | 38.462555 |
carljm/django-adminfiles | adminfiles/flickr.py | https://github.com/carljm/django-adminfiles/blob/b01dc7be266305d575c11d5ff9a37ccac04a78c2/adminfiles/flickr.py#L656-L667 | def favorites_getPublicList(user_id, per_page='', page=''):
"""Returns list of Photo objects."""
method = 'flickr.favorites.getPublicList'
data = _doget(method, auth=False, user_id=user_id, per_page=per_page,\
page=page)
photos = []
if isinstance(data.rsp.photos.photo, list):
... | [
"def",
"favorites_getPublicList",
"(",
"user_id",
",",
"per_page",
"=",
"''",
",",
"page",
"=",
"''",
")",
":",
"method",
"=",
"'flickr.favorites.getPublicList'",
"data",
"=",
"_doget",
"(",
"method",
",",
"auth",
"=",
"False",
",",
"user_id",
"=",
"user_id"... | Returns list of Photo objects. | [
"Returns",
"list",
"of",
"Photo",
"objects",
"."
] | python | train | 39.75 |
sdispater/orator | orator/migrations/migrator.py | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/migrations/migrator.py#L194-L222 | def _pretend_to_run(self, migration, method):
"""
Pretend to run the migration.
:param migration: The migration
:type migration: orator.migrations.migration.Migration
:param method: The method to execute
:type method: str
"""
self._note("")
names... | [
"def",
"_pretend_to_run",
"(",
"self",
",",
"migration",
",",
"method",
")",
":",
"self",
".",
"_note",
"(",
"\"\"",
")",
"names",
"=",
"[",
"]",
"for",
"query",
"in",
"self",
".",
"_get_queries",
"(",
"migration",
",",
"method",
")",
":",
"name",
"=... | Pretend to run the migration.
:param migration: The migration
:type migration: orator.migrations.migration.Migration
:param method: The method to execute
:type method: str | [
"Pretend",
"to",
"run",
"the",
"migration",
"."
] | python | train | 28.344828 |
opinkerfi/nago | nago/core/__init__.py | https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/core/__init__.py#L151-L170 | def save(self):
""" Save this node (and all its attributes) to config """
cfg_file = "/etc/nago/nago.ini"
config = ConfigParser.ConfigParser()
config.read(cfg_file)
result = {}
token = self.data.pop("token", self.token)
if token != self._original_token:
... | [
"def",
"save",
"(",
"self",
")",
":",
"cfg_file",
"=",
"\"/etc/nago/nago.ini\"",
"config",
"=",
"ConfigParser",
".",
"ConfigParser",
"(",
")",
"config",
".",
"read",
"(",
"cfg_file",
")",
"result",
"=",
"{",
"}",
"token",
"=",
"self",
".",
"data",
".",
... | Save this node (and all its attributes) to config | [
"Save",
"this",
"node",
"(",
"and",
"all",
"its",
"attributes",
")",
"to",
"config"
] | python | train | 37.8 |
dgomes/pymediaroom | pymediaroom/remote.py | https://github.com/dgomes/pymediaroom/blob/f4f2686c8d5622dd5ae1bcdd76900ba35e148529/pymediaroom/remote.py#L113-L135 | def notify_callback(self, notify):
"""Process State from NOTIFY message."""
_LOGGER.debug(notify)
if notify.ip_address != self.stb_ip:
return
if notify.tune:
self._state = State.PLAYING_LIVE_TV
self.tune_src = notify.tune['@src']
try:
... | [
"def",
"notify_callback",
"(",
"self",
",",
"notify",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"notify",
")",
"if",
"notify",
".",
"ip_address",
"!=",
"self",
".",
"stb_ip",
":",
"return",
"if",
"notify",
".",
"tune",
":",
"self",
".",
"_state",
"=",
... | Process State from NOTIFY message. | [
"Process",
"State",
"from",
"NOTIFY",
"message",
"."
] | python | train | 37.73913 |
atlassian-api/atlassian-python-api | atlassian/bitbucket.py | https://github.com/atlassian-api/atlassian-python-api/blob/540d269905c3e7547b666fe30c647b2d512cf358/atlassian/bitbucket.py#L825-L836 | def set_branching_model(self, project, repository, data):
"""
Set branching model
:param project:
:param repository:
:param data:
:return:
"""
url = 'rest/branch-utils/1.0/projects/{project}/repos/{repository}/branchmodel/configuration'.format(
... | [
"def",
"set_branching_model",
"(",
"self",
",",
"project",
",",
"repository",
",",
"data",
")",
":",
"url",
"=",
"'rest/branch-utils/1.0/projects/{project}/repos/{repository}/branchmodel/configuration'",
".",
"format",
"(",
"project",
"=",
"project",
",",
"repository",
... | Set branching model
:param project:
:param repository:
:param data:
:return: | [
"Set",
"branching",
"model",
":",
"param",
"project",
":",
":",
"param",
"repository",
":",
":",
"param",
"data",
":",
":",
"return",
":"
] | python | train | 33.416667 |
andymccurdy/redis-py | redis/lock.py | https://github.com/andymccurdy/redis-py/blob/cdfe2befbe00db4a3c48c9ddd6d64dea15f6f0db/redis/lock.py#L207-L218 | def owned(self):
"""
Returns True if this key is locked by this lock, otherwise False.
"""
stored_token = self.redis.get(self.name)
# need to always compare bytes to bytes
# TODO: this can be simplified when the context manager is finished
if stored_token and not ... | [
"def",
"owned",
"(",
"self",
")",
":",
"stored_token",
"=",
"self",
".",
"redis",
".",
"get",
"(",
"self",
".",
"name",
")",
"# need to always compare bytes to bytes",
"# TODO: this can be simplified when the context manager is finished",
"if",
"stored_token",
"and",
"n... | Returns True if this key is locked by this lock, otherwise False. | [
"Returns",
"True",
"if",
"this",
"key",
"is",
"locked",
"by",
"this",
"lock",
"otherwise",
"False",
"."
] | python | train | 46.25 |
its-rigs/Trolly | trolly/client.py | https://github.com/its-rigs/Trolly/blob/483dc94c352df40dc05ead31820b059b2545cf82/trolly/client.py#L98-L110 | def create_organisation(self, organisation_json):
'''
Create an Organisation object from a JSON object
Returns:
Organisation: The organisation from the given `organisation_json`.
'''
return trolly.organisation.Organisation(
trello_client=self,
... | [
"def",
"create_organisation",
"(",
"self",
",",
"organisation_json",
")",
":",
"return",
"trolly",
".",
"organisation",
".",
"Organisation",
"(",
"trello_client",
"=",
"self",
",",
"organisation_id",
"=",
"organisation_json",
"[",
"'id'",
"]",
",",
"name",
"=",
... | Create an Organisation object from a JSON object
Returns:
Organisation: The organisation from the given `organisation_json`. | [
"Create",
"an",
"Organisation",
"object",
"from",
"a",
"JSON",
"object"
] | python | test | 33.769231 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsGenIncProcessModel.py | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsGenIncProcessModel.py#L1042-L1107 | def updatepLvlGrid(self):
'''
Update the grid of persistent income levels. Currently only works for
infinite horizon models (cycles=0) and lifecycle models (cycles=1). Not
clear what to do about cycles>1 because the distribution of persistent
income will be different within a p... | [
"def",
"updatepLvlGrid",
"(",
"self",
")",
":",
"orig_time",
"=",
"self",
".",
"time_flow",
"self",
".",
"timeFwd",
"(",
")",
"LivPrbAll",
"=",
"np",
".",
"array",
"(",
"self",
".",
"LivPrb",
")",
"# Simulate the distribution of persistent income levels by t_cycle... | Update the grid of persistent income levels. Currently only works for
infinite horizon models (cycles=0) and lifecycle models (cycles=1). Not
clear what to do about cycles>1 because the distribution of persistent
income will be different within a period depending on how many cycles
hav... | [
"Update",
"the",
"grid",
"of",
"persistent",
"income",
"levels",
".",
"Currently",
"only",
"works",
"for",
"infinite",
"horizon",
"models",
"(",
"cycles",
"=",
"0",
")",
"and",
"lifecycle",
"models",
"(",
"cycles",
"=",
"1",
")",
".",
"Not",
"clear",
"wh... | python | train | 51.242424 |
wonambi-python/wonambi | wonambi/widgets/notes.py | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/notes.py#L823-L842 | def delete_row(self):
"""Delete bookmarks or event from annotations, based on row."""
sel_model = self.idx_annot_list.selectionModel()
for row in sel_model.selectedRows():
i = row.row()
start = self.idx_annot_list.property('start')[i]
end = self.idx_annot_list... | [
"def",
"delete_row",
"(",
"self",
")",
":",
"sel_model",
"=",
"self",
".",
"idx_annot_list",
".",
"selectionModel",
"(",
")",
"for",
"row",
"in",
"sel_model",
".",
"selectedRows",
"(",
")",
":",
"i",
"=",
"row",
".",
"row",
"(",
")",
"start",
"=",
"s... | Delete bookmarks or event from annotations, based on row. | [
"Delete",
"bookmarks",
"or",
"event",
"from",
"annotations",
"based",
"on",
"row",
"."
] | python | train | 46.4 |
eventbrite/pysoa | pysoa/server/action/status.py | https://github.com/eventbrite/pysoa/blob/9c052cae2397d13de3df8ae2c790846a70b53f18/pysoa/server/action/status.py#L235-L253 | def StatusActionFactory(version, build=None, base_class=BaseStatusAction): # noqa
"""
A factory for creating a new status action class specific to a service.
:param version: The service version
:type version: union[str, unicode]
:param build: The optional service build identifier
:type build: ... | [
"def",
"StatusActionFactory",
"(",
"version",
",",
"build",
"=",
"None",
",",
"base_class",
"=",
"BaseStatusAction",
")",
":",
"# noqa",
"return",
"type",
"(",
"str",
"(",
"'StatusAction'",
")",
",",
"(",
"base_class",
",",
")",
",",
"{",
"str",
"(",
"'_... | A factory for creating a new status action class specific to a service.
:param version: The service version
:type version: union[str, unicode]
:param build: The optional service build identifier
:type build: union[str, unicode]
:param base_class: The optional base class, to override `BaseStatusActi... | [
"A",
"factory",
"for",
"creating",
"a",
"new",
"status",
"action",
"class",
"specific",
"to",
"a",
"service",
"."
] | python | train | 38.842105 |
python-useful-helpers/threaded | threaded/class_decorator.py | https://github.com/python-useful-helpers/threaded/blob/c1aa5a631ab3e2904b915ed6c6a8be03a9673a1a/threaded/class_decorator.py#L89-L94 | def _func(self) -> typing.Optional[typing.Callable[..., typing.Union["typing.Awaitable[typing.Any]", typing.Any]]]:
"""Get wrapped function.
:rtype: typing.Optional[typing.Callable[..., typing.Union[typing.Awaitable, typing.Any]]]
"""
return self.__func | [
"def",
"_func",
"(",
"self",
")",
"->",
"typing",
".",
"Optional",
"[",
"typing",
".",
"Callable",
"[",
"...",
",",
"typing",
".",
"Union",
"[",
"\"typing.Awaitable[typing.Any]\"",
",",
"typing",
".",
"Any",
"]",
"]",
"]",
":",
"return",
"self",
".",
"... | Get wrapped function.
:rtype: typing.Optional[typing.Callable[..., typing.Union[typing.Awaitable, typing.Any]]] | [
"Get",
"wrapped",
"function",
"."
] | python | train | 46.833333 |
Esri/ArcREST | src/arcrest/web/_base.py | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/web/_base.py#L346-L353 | def _mainType(self, resp):
""" gets the main type from the response object"""
if self.PY2:
return resp.headers.maintype
elif self.PY3:
return resp.headers.get_content_maintype()
else:
return None | [
"def",
"_mainType",
"(",
"self",
",",
"resp",
")",
":",
"if",
"self",
".",
"PY2",
":",
"return",
"resp",
".",
"headers",
".",
"maintype",
"elif",
"self",
".",
"PY3",
":",
"return",
"resp",
".",
"headers",
".",
"get_content_maintype",
"(",
")",
"else",
... | gets the main type from the response object | [
"gets",
"the",
"main",
"type",
"from",
"the",
"response",
"object"
] | python | train | 32 |
pyviz/param | param/__init__.py | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/__init__.py#L164-L208 | def guess_param_types(**kwargs):
"""
Given a set of keyword literals, promote to the appropriate
parameter type based on some simple heuristics.
"""
params = {}
for k, v in kwargs.items():
kws = dict(default=v, constant=True)
if isinstance(v, Parameter):
params[k] = v... | [
"def",
"guess_param_types",
"(",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"kws",
"=",
"dict",
"(",
"default",
"=",
"v",
",",
"constant",
"=",
"True",
")",
"if",
"i... | Given a set of keyword literals, promote to the appropriate
parameter type based on some simple heuristics. | [
"Given",
"a",
"set",
"of",
"keyword",
"literals",
"promote",
"to",
"the",
"appropriate",
"parameter",
"type",
"based",
"on",
"some",
"simple",
"heuristics",
"."
] | python | train | 34.088889 |
chaoss/grimoirelab-perceval | perceval/backends/core/gitlab.py | https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/gitlab.py#L293-L309 | def __get_merge_versions(self, merge_id):
"""Get merge versions"""
versions = []
group_versions = self.client.merge_versions(merge_id)
for raw_versions in group_versions:
for version in json.loads(raw_versions):
version_id = version['id']
ve... | [
"def",
"__get_merge_versions",
"(",
"self",
",",
"merge_id",
")",
":",
"versions",
"=",
"[",
"]",
"group_versions",
"=",
"self",
".",
"client",
".",
"merge_versions",
"(",
"merge_id",
")",
"for",
"raw_versions",
"in",
"group_versions",
":",
"for",
"version",
... | Get merge versions | [
"Get",
"merge",
"versions"
] | python | test | 32.235294 |
pydata/xarray | xarray/coding/cftime_offsets.py | https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/coding/cftime_offsets.py#L204-L212 | def _adjust_n_months(other_day, n, reference_day):
"""Adjust the number of times a monthly offset is applied based
on the day of a given date, and the reference day provided.
"""
if n > 0 and other_day < reference_day:
n = n - 1
elif n <= 0 and other_day > reference_day:
n = n + 1
... | [
"def",
"_adjust_n_months",
"(",
"other_day",
",",
"n",
",",
"reference_day",
")",
":",
"if",
"n",
">",
"0",
"and",
"other_day",
"<",
"reference_day",
":",
"n",
"=",
"n",
"-",
"1",
"elif",
"n",
"<=",
"0",
"and",
"other_day",
">",
"reference_day",
":",
... | Adjust the number of times a monthly offset is applied based
on the day of a given date, and the reference day provided. | [
"Adjust",
"the",
"number",
"of",
"times",
"a",
"monthly",
"offset",
"is",
"applied",
"based",
"on",
"the",
"day",
"of",
"a",
"given",
"date",
"and",
"the",
"reference",
"day",
"provided",
"."
] | python | train | 35.777778 |
deep-compute/basescript | basescript/log.py | https://github.com/deep-compute/basescript/blob/f7233963c5291530fcb2444a7f45b556e6407b90/basescript/log.py#L211-L229 | def _proxy_to_logger(self, method_name, event, *event_args,
**event_kw):
"""
Propagate a method call to the wrapped logger.
This is the same as the superclass implementation, except that
it also preserves positional arguments in the `event_dict` so
that ... | [
"def",
"_proxy_to_logger",
"(",
"self",
",",
"method_name",
",",
"event",
",",
"*",
"event_args",
",",
"*",
"*",
"event_kw",
")",
":",
"if",
"isinstance",
"(",
"event",
",",
"bytes",
")",
":",
"event",
"=",
"event",
".",
"decode",
"(",
"'utf-8'",
")",
... | Propagate a method call to the wrapped logger.
This is the same as the superclass implementation, except that
it also preserves positional arguments in the `event_dict` so
that the stdblib's support for format strings can be used. | [
"Propagate",
"a",
"method",
"call",
"to",
"the",
"wrapped",
"logger",
"."
] | python | train | 38.894737 |
grabbles/grabbit | grabbit/core.py | https://github.com/grabbles/grabbit/blob/83ff93df36019eaaee9d4e31f816a518e46cae07/grabbit/core.py#L630-L664 | def load_index(self, filename, reindex=False):
''' Load the Layout's index from a plaintext file.
Args:
filename (str): Path to the plaintext index file.
reindex (bool): If True, discards entity values provided in the
loaded index and instead re-indexes every fil... | [
"def",
"load_index",
"(",
"self",
",",
"filename",
",",
"reindex",
"=",
"False",
")",
":",
"self",
".",
"_reset_index",
"(",
")",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"fobj",
":",
"data",
"=",
"json",
".",
"load",
"(",
"fobj",
")... | Load the Layout's index from a plaintext file.
Args:
filename (str): Path to the plaintext index file.
reindex (bool): If True, discards entity values provided in the
loaded index and instead re-indexes every file in the loaded
index against the entities ... | [
"Load",
"the",
"Layout",
"s",
"index",
"from",
"a",
"plaintext",
"file",
"."
] | python | train | 41.8 |
labeneator/flask-cavage | flask_cavage.py | https://github.com/labeneator/flask-cavage/blob/7144841eaf289b469ba77507e19d9012284272d4/flask_cavage.py#L168-L175 | def secret_loader(self, callback):
"""
Decorate a method that receives a key id and returns a secret key
"""
if not callback or not callable(callback):
raise Exception("Please pass in a callable that loads secret keys")
self.secret_loader_callback = callback
r... | [
"def",
"secret_loader",
"(",
"self",
",",
"callback",
")",
":",
"if",
"not",
"callback",
"or",
"not",
"callable",
"(",
"callback",
")",
":",
"raise",
"Exception",
"(",
"\"Please pass in a callable that loads secret keys\"",
")",
"self",
".",
"secret_loader_callback"... | Decorate a method that receives a key id and returns a secret key | [
"Decorate",
"a",
"method",
"that",
"receives",
"a",
"key",
"id",
"and",
"returns",
"a",
"secret",
"key"
] | python | train | 40.875 |
gbowerman/azurerm | examples/create_vmss.py | https://github.com/gbowerman/azurerm/blob/79d40431d3b13f8a36aadbff5029888383d72674/examples/create_vmss.py#L10-L110 | def main():
'''Main routine.'''
# validate command line arguments
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('--name', '-n', required=True,
action='store', help='Name of vmss')
arg_parser.add_argument('--capacity', '-c', required=True, action='store',... | [
"def",
"main",
"(",
")",
":",
"# validate command line arguments",
"arg_parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"arg_parser",
".",
"add_argument",
"(",
"'--name'",
",",
"'-n'",
",",
"required",
"=",
"True",
",",
"action",
"=",
"'store'",
","... | Main routine. | [
"Main",
"routine",
"."
] | python | train | 39.980198 |
Rapptz/discord.py | discord/widget.py | https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/widget.py#L228-L250 | async def fetch_invite(self, *, with_counts=True):
"""|coro|
Retrieves an :class:`Invite` from a invite URL or ID.
This is the same as :meth:`Client.get_invite`; the invite
code is abstracted away.
Parameters
-----------
with_counts: :class:`bool`
Wh... | [
"async",
"def",
"fetch_invite",
"(",
"self",
",",
"*",
",",
"with_counts",
"=",
"True",
")",
":",
"if",
"self",
".",
"_invite",
":",
"invite_id",
"=",
"resolve_invite",
"(",
"self",
".",
"_invite",
")",
"data",
"=",
"await",
"self",
".",
"_state",
".",... | |coro|
Retrieves an :class:`Invite` from a invite URL or ID.
This is the same as :meth:`Client.get_invite`; the invite
code is abstracted away.
Parameters
-----------
with_counts: :class:`bool`
Whether to include count information in the invite. This fills t... | [
"|coro|"
] | python | train | 36.043478 |
cirruscluster/cirruscluster | cirruscluster/core.py | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/core.py#L586-L597 | def __WaitForVolume(volume, desired_state):
""" Blocks until EBS volume is in desired state. """
print 'Waiting for volume %s to be %s...' % (volume.id, desired_state)
while True:
volume.update()
sys.stdout.write('.')
sys.stdout.flush()
#print 'status is: %s' % volume.status
if volume.status =... | [
"def",
"__WaitForVolume",
"(",
"volume",
",",
"desired_state",
")",
":",
"print",
"'Waiting for volume %s to be %s...'",
"%",
"(",
"volume",
".",
"id",
",",
"desired_state",
")",
"while",
"True",
":",
"volume",
".",
"update",
"(",
")",
"sys",
".",
"stdout",
... | Blocks until EBS volume is in desired state. | [
"Blocks",
"until",
"EBS",
"volume",
"is",
"in",
"desired",
"state",
"."
] | python | train | 30.666667 |
gtaylor/django-athumb | athumb/fields.py | https://github.com/gtaylor/django-athumb/blob/69261ace0dff81e33156a54440874456a7b38dfb/athumb/fields.py#L94-L106 | def get_thumbnail_format(self):
"""
Determines the target thumbnail type either by looking for a format
override specified at the model level, or by using the format the
user uploaded.
"""
if self.field.thumbnail_format:
# Over-ride was given, use that instead... | [
"def",
"get_thumbnail_format",
"(",
"self",
")",
":",
"if",
"self",
".",
"field",
".",
"thumbnail_format",
":",
"# Over-ride was given, use that instead.",
"return",
"self",
".",
"field",
".",
"thumbnail_format",
".",
"lower",
"(",
")",
"else",
":",
"# Use the exi... | Determines the target thumbnail type either by looking for a format
override specified at the model level, or by using the format the
user uploaded. | [
"Determines",
"the",
"target",
"thumbnail",
"type",
"either",
"by",
"looking",
"for",
"a",
"format",
"override",
"specified",
"at",
"the",
"model",
"level",
"or",
"by",
"using",
"the",
"format",
"the",
"user",
"uploaded",
"."
] | python | train | 40.461538 |
FutunnOpen/futuquant | futuquant/examples/learn/get_realtime_data.py | https://github.com/FutunnOpen/futuquant/blob/1512b321845f92ec9c578ce2689aa4e8482669e4/futuquant/examples/learn/get_realtime_data.py#L8-L33 | def _example_stock_quote(quote_ctx):
"""
获取批量报价,输出 股票名称,时间,当前价,开盘价,最高价,最低价,昨天收盘价,成交量,成交额,换手率,振幅,股票状态
"""
stock_code_list = ["US.AAPL", "HK.00700"]
# subscribe "QUOTE"
ret_status, ret_data = quote_ctx.subscribe(stock_code_list, ft.SubType.QUOTE)
if ret_status != ft.RET_OK:
print("%s ... | [
"def",
"_example_stock_quote",
"(",
"quote_ctx",
")",
":",
"stock_code_list",
"=",
"[",
"\"US.AAPL\"",
",",
"\"HK.00700\"",
"]",
"# subscribe \"QUOTE\"",
"ret_status",
",",
"ret_data",
"=",
"quote_ctx",
".",
"subscribe",
"(",
"stock_code_list",
",",
"ft",
".",
"Su... | 获取批量报价,输出 股票名称,时间,当前价,开盘价,最高价,最低价,昨天收盘价,成交量,成交额,换手率,振幅,股票状态 | [
"获取批量报价,输出",
"股票名称,时间,当前价,开盘价,最高价,最低价,昨天收盘价,成交量,成交额,换手率,振幅,股票状态"
] | python | train | 27.961538 |
daviddrysdale/python-phonenumbers | python/phonenumbers/shortnumberinfo.py | https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/shortnumberinfo.py#L385-L404 | def is_carrier_specific(numobj):
"""Given a valid short number, determines whether it is carrier-specific
(however, nothing is implied about its validity). Carrier-specific numbers
may connect to a different end-point, or not connect at all, depending
on the user's carrier. If it is important that the ... | [
"def",
"is_carrier_specific",
"(",
"numobj",
")",
":",
"region_codes",
"=",
"region_codes_for_country_code",
"(",
"numobj",
".",
"country_code",
")",
"region_code",
"=",
"_region_code_for_short_number_from_region_list",
"(",
"numobj",
",",
"region_codes",
")",
"national_n... | Given a valid short number, determines whether it is carrier-specific
(however, nothing is implied about its validity). Carrier-specific numbers
may connect to a different end-point, or not connect at all, depending
on the user's carrier. If it is important that the number is valid, then
its validity m... | [
"Given",
"a",
"valid",
"short",
"number",
"determines",
"whether",
"it",
"is",
"carrier",
"-",
"specific",
"(",
"however",
"nothing",
"is",
"implied",
"about",
"its",
"validity",
")",
".",
"Carrier",
"-",
"specific",
"numbers",
"may",
"connect",
"to",
"a",
... | python | train | 51.5 |
bcbio/bcbio-nextgen | bcbio/structural/cnvkit.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/cnvkit.py#L490-L503 | def _add_seg_to_output(out, data, enumerate_chroms=False):
"""Export outputs to 'seg' format compatible with IGV and GenePattern.
"""
out_file = "%s.seg" % os.path.splitext(out["cns"])[0]
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
cmd = ... | [
"def",
"_add_seg_to_output",
"(",
"out",
",",
"data",
",",
"enumerate_chroms",
"=",
"False",
")",
":",
"out_file",
"=",
"\"%s.seg\"",
"%",
"os",
".",
"path",
".",
"splitext",
"(",
"out",
"[",
"\"cns\"",
"]",
")",
"[",
"0",
"]",
"if",
"not",
"utils",
... | Export outputs to 'seg' format compatible with IGV and GenePattern. | [
"Export",
"outputs",
"to",
"seg",
"format",
"compatible",
"with",
"IGV",
"and",
"GenePattern",
"."
] | python | train | 44.214286 |
kcolford/txt2boil | txt2boil/core/extractor.py | https://github.com/kcolford/txt2boil/blob/853a47bb8db27c0224531f24dfd02839c983d027/txt2boil/core/extractor.py#L93-L99 | def extractContent(self, text):
"""Extract the content of comment text.
"""
m = self.nextValidComment(text)
return '' if m is None else m.group(1) | [
"def",
"extractContent",
"(",
"self",
",",
"text",
")",
":",
"m",
"=",
"self",
".",
"nextValidComment",
"(",
"text",
")",
"return",
"''",
"if",
"m",
"is",
"None",
"else",
"m",
".",
"group",
"(",
"1",
")"
] | Extract the content of comment text. | [
"Extract",
"the",
"content",
"of",
"comment",
"text",
"."
] | python | train | 24.857143 |
cknoll/ipydex | ipydex/core.py | https://github.com/cknoll/ipydex/blob/ca528ce4c97ee934e48efbd5983c1b7cd88bec9d/ipydex/core.py#L529-L547 | def save_current_nb_as_html(info=False):
"""
Save the current notebook as html file in the same directory
"""
assert in_ipynb()
full_path = get_notebook_name()
path, filename = os.path.split(full_path)
wd_save = os.getcwd()
os.chdir(path)
cmd = 'jupyter nbconvert --to html "{}"'.fo... | [
"def",
"save_current_nb_as_html",
"(",
"info",
"=",
"False",
")",
":",
"assert",
"in_ipynb",
"(",
")",
"full_path",
"=",
"get_notebook_name",
"(",
")",
"path",
",",
"filename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"full_path",
")",
"wd_save",
"=",
... | Save the current notebook as html file in the same directory | [
"Save",
"the",
"current",
"notebook",
"as",
"html",
"file",
"in",
"the",
"same",
"directory"
] | python | train | 25 |
gawel/aiocron | aiocron/__init__.py | https://github.com/gawel/aiocron/blob/949870b2f7fe1e10e4220f3243c9d4237255d203/aiocron/__init__.py#L43-L47 | def start(self):
"""Start scheduling"""
self.stop()
self.initialize()
self.handle = self.loop.call_at(self.get_next(), self.call_next) | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"stop",
"(",
")",
"self",
".",
"initialize",
"(",
")",
"self",
".",
"handle",
"=",
"self",
".",
"loop",
".",
"call_at",
"(",
"self",
".",
"get_next",
"(",
")",
",",
"self",
".",
"call_next",
")"... | Start scheduling | [
"Start",
"scheduling"
] | python | train | 32.4 |
StackStorm/pybind | pybind/nos/v6_0_2f/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v6_0_2f/__init__.py#L6975-L6996 | def _set_tacacs_server(self, v, load=False):
"""
Setter method for tacacs_server, mapped from YANG variable /tacacs_server (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_tacacs_server is considered as a private
method. Backends looking to populate this v... | [
"def",
"_set_tacacs_server",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"... | Setter method for tacacs_server, mapped from YANG variable /tacacs_server (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_tacacs_server is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_tacacs_... | [
"Setter",
"method",
"for",
"tacacs_server",
"mapped",
"from",
"YANG",
"variable",
"/",
"tacacs_server",
"(",
"container",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
"in",
"the",
"source",
"YANG",
"file",
"th... | python | train | 78.590909 |
log2timeline/dfwinreg | dfwinreg/interface.py | https://github.com/log2timeline/dfwinreg/blob/9d488bb1db562197dbfb48de9613d6b29dea056e/dfwinreg/interface.py#L219-L228 | def RecurseKeys(self):
"""Recurses the subkeys starting with the key.
Yields:
WinRegistryKey: Windows Registry key.
"""
yield self
for subkey in self.GetSubkeys():
for key in subkey.RecurseKeys():
yield key | [
"def",
"RecurseKeys",
"(",
"self",
")",
":",
"yield",
"self",
"for",
"subkey",
"in",
"self",
".",
"GetSubkeys",
"(",
")",
":",
"for",
"key",
"in",
"subkey",
".",
"RecurseKeys",
"(",
")",
":",
"yield",
"key"
] | Recurses the subkeys starting with the key.
Yields:
WinRegistryKey: Windows Registry key. | [
"Recurses",
"the",
"subkeys",
"starting",
"with",
"the",
"key",
"."
] | python | train | 23.8 |
abnerjacobsen/tinydb-jsonorm | src/tinydb_jsonorm/cuid.py | https://github.com/abnerjacobsen/tinydb-jsonorm/blob/704d3f887cc8963769ffbb116eb7e6909deeaecd/src/tinydb_jsonorm/cuid.py#L51-L58 | def _random_block():
"""
Generate a random string of `BLOCK_SIZE` length.
"""
# TODO: Use a better RNG than random.randint
random_number = random.randint(0, DISCRETE_VALUES)
random_string = _to_base36(random_number)
return _pad(random_string, BLOCK_SIZE) | [
"def",
"_random_block",
"(",
")",
":",
"# TODO: Use a better RNG than random.randint",
"random_number",
"=",
"random",
".",
"randint",
"(",
"0",
",",
"DISCRETE_VALUES",
")",
"random_string",
"=",
"_to_base36",
"(",
"random_number",
")",
"return",
"_pad",
"(",
"rando... | Generate a random string of `BLOCK_SIZE` length. | [
"Generate",
"a",
"random",
"string",
"of",
"BLOCK_SIZE",
"length",
"."
] | python | train | 34.375 |
dailymuse/oz | oz/json_api/middleware.py | https://github.com/dailymuse/oz/blob/4329f6a207dc9d2a8fbeb4d16d415dbe4570b5bd/oz/json_api/middleware.py#L70-L88 | def body(self):
"""Gets the JSON body of the request"""
if self._decoded_body == None:
# Try to decode the JSON body. But raise an error if the
# content-type is unexpected, or the JSON is invalid.
raw_content_type = self.request.headers.get("content-type") or ""
... | [
"def",
"body",
"(",
"self",
")",
":",
"if",
"self",
".",
"_decoded_body",
"==",
"None",
":",
"# Try to decode the JSON body. But raise an error if the",
"# content-type is unexpected, or the JSON is invalid.",
"raw_content_type",
"=",
"self",
".",
"request",
".",
"headers",... | Gets the JSON body of the request | [
"Gets",
"the",
"JSON",
"body",
"of",
"the",
"request"
] | python | train | 38.473684 |
joyent/python-manta | manta/cmdln.py | https://github.com/joyent/python-manta/blob/f68ef142bdbac058c981e3b28e18d77612f5b7c6/manta/cmdln.py#L1472-L1503 | def argv2line(argv):
r"""Put together the given argument vector into a command line.
"argv" is the argument vector to process.
>>> from cmdln import argv2line
>>> argv2line(['foo'])
'foo'
>>> argv2line(['foo', 'bar'])
'foo bar'
>>> argv2line(['foo', 'bar baz'])
'foo "bar baz"'
... | [
"def",
"argv2line",
"(",
"argv",
")",
":",
"escapedArgs",
"=",
"[",
"]",
"for",
"arg",
"in",
"argv",
":",
"if",
"' '",
"in",
"arg",
"and",
"'\"'",
"not",
"in",
"arg",
":",
"arg",
"=",
"'\"'",
"+",
"arg",
"+",
"'\"'",
"elif",
"' '",
"in",
"arg",
... | r"""Put together the given argument vector into a command line.
"argv" is the argument vector to process.
>>> from cmdln import argv2line
>>> argv2line(['foo'])
'foo'
>>> argv2line(['foo', 'bar'])
'foo bar'
>>> argv2line(['foo', 'bar baz'])
'foo "bar baz"'
>>> argv2line(['foo"b... | [
"r",
"Put",
"together",
"the",
"given",
"argument",
"vector",
"into",
"a",
"command",
"line",
"."
] | python | train | 26.75 |
brechtm/rinohtype | src/rinoh/backend/pdf/xobject/purepng.py | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L2071-L2077 | def read(self, n):
"""Read `n` chars from buffer"""
r = self.buf[self.offset:self.offset + n]
if isinstance(r, array):
r = r.tostring()
self.offset += n
return r | [
"def",
"read",
"(",
"self",
",",
"n",
")",
":",
"r",
"=",
"self",
".",
"buf",
"[",
"self",
".",
"offset",
":",
"self",
".",
"offset",
"+",
"n",
"]",
"if",
"isinstance",
"(",
"r",
",",
"array",
")",
":",
"r",
"=",
"r",
".",
"tostring",
"(",
... | Read `n` chars from buffer | [
"Read",
"n",
"chars",
"from",
"buffer"
] | python | train | 29.571429 |
LonamiWebs/Telethon | telethon/client/users.py | https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/client/users.py#L398-L460 | async def _get_entity_from_string(self, string):
"""
Gets a full entity from the given string, which may be a phone or
a username, and processes all the found entities on the session.
The string may also be a user link, or a channel/chat invite link.
This method has the side eff... | [
"async",
"def",
"_get_entity_from_string",
"(",
"self",
",",
"string",
")",
":",
"phone",
"=",
"utils",
".",
"parse_phone",
"(",
"string",
")",
"if",
"phone",
":",
"try",
":",
"for",
"user",
"in",
"(",
"await",
"self",
"(",
"functions",
".",
"contacts",
... | Gets a full entity from the given string, which may be a phone or
a username, and processes all the found entities on the session.
The string may also be a user link, or a channel/chat invite link.
This method has the side effect of adding the found users to the
session database, so it ... | [
"Gets",
"a",
"full",
"entity",
"from",
"the",
"given",
"string",
"which",
"may",
"be",
"a",
"phone",
"or",
"a",
"username",
"and",
"processes",
"all",
"the",
"found",
"entities",
"on",
"the",
"session",
".",
"The",
"string",
"may",
"also",
"be",
"a",
"... | python | train | 43.888889 |
Parisson/TimeSide | timeside/plugins/grapher/spectrogram_lin.py | https://github.com/Parisson/TimeSide/blob/0618d75cd2f16021afcfd3d5b77f692adad76ea5/timeside/plugins/grapher/spectrogram_lin.py#L55-L67 | def set_scale(self):
"""generate the lookup which translates y-coordinate to fft-bin"""
f_min = float(self.lower_freq)
f_max = float(self.higher_freq)
y_min = f_min
y_max = f_max
for y in range(self.image_height):
freq = y_min + y / (self.image_height - 1.0) ... | [
"def",
"set_scale",
"(",
"self",
")",
":",
"f_min",
"=",
"float",
"(",
"self",
".",
"lower_freq",
")",
"f_max",
"=",
"float",
"(",
"self",
".",
"higher_freq",
")",
"y_min",
"=",
"f_min",
"y_max",
"=",
"f_max",
"for",
"y",
"in",
"range",
"(",
"self",
... | generate the lookup which translates y-coordinate to fft-bin | [
"generate",
"the",
"lookup",
"which",
"translates",
"y",
"-",
"coordinate",
"to",
"fft",
"-",
"bin"
] | python | train | 41.769231 |
googledatalab/pydatalab | google/datalab/utils/commands/_utils.py | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/commands/_utils.py#L165-L183 | def _get_data_from_dataframe(source, fields='*', first_row=0, count=-1, schema=None):
""" Helper function for _get_data that handles Pandas DataFrames. """
if schema is None:
schema = google.datalab.bigquery.Schema.from_data(source)
fields = get_field_list(fields, schema)
rows = []
if count < 0:
count... | [
"def",
"_get_data_from_dataframe",
"(",
"source",
",",
"fields",
"=",
"'*'",
",",
"first_row",
"=",
"0",
",",
"count",
"=",
"-",
"1",
",",
"schema",
"=",
"None",
")",
":",
"if",
"schema",
"is",
"None",
":",
"schema",
"=",
"google",
".",
"datalab",
".... | Helper function for _get_data that handles Pandas DataFrames. | [
"Helper",
"function",
"for",
"_get_data",
"that",
"handles",
"Pandas",
"DataFrames",
"."
] | python | train | 41.105263 |
trp07/messages | messages/telegram.py | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/telegram.py#L134-L144 | def _construct_message(self):
"""Build the message params."""
self.message["chat_id"] = self.chat_id
self.message["text"] = ""
if self.from_:
self.message["text"] += "From: " + self.from_ + "\n"
if self.subject:
self.message["text"] += "Subject: " + self.s... | [
"def",
"_construct_message",
"(",
"self",
")",
":",
"self",
".",
"message",
"[",
"\"chat_id\"",
"]",
"=",
"self",
".",
"chat_id",
"self",
".",
"message",
"[",
"\"text\"",
"]",
"=",
"\"\"",
"if",
"self",
".",
"from_",
":",
"self",
".",
"message",
"[",
... | Build the message params. | [
"Build",
"the",
"message",
"params",
"."
] | python | test | 37 |
wbond/asn1crypto | asn1crypto/algos.py | https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/algos.py#L728-L761 | def kdf_hmac(self):
"""
Returns the HMAC algorithm to use with the KDF.
:return:
A unicode string of one of the following: "md2", "md5", "sha1",
"sha224", "sha256", "sha384", "sha512"
"""
encryption_algo = self['algorithm'].native
if encryption_... | [
"def",
"kdf_hmac",
"(",
"self",
")",
":",
"encryption_algo",
"=",
"self",
"[",
"'algorithm'",
"]",
".",
"native",
"if",
"encryption_algo",
"==",
"'pbes2'",
":",
"return",
"self",
"[",
"'parameters'",
"]",
"[",
"'key_derivation_func'",
"]",
"[",
"'parameters'",... | Returns the HMAC algorithm to use with the KDF.
:return:
A unicode string of one of the following: "md2", "md5", "sha1",
"sha224", "sha256", "sha384", "sha512" | [
"Returns",
"the",
"HMAC",
"algorithm",
"to",
"use",
"with",
"the",
"KDF",
"."
] | python | train | 30.823529 |
bioasp/exdesi | src/query.py | https://github.com/bioasp/exdesi/blob/ccfa05657f14c49f7a873cb21804f43f81e2a0d1/src/query.py#L33-L54 | def get_best_single_experiments(nets,expvars):
'''
returns the experiments as a``TermSet`` object [instance].
'''
netsf = nets.to_file()
expvarsf = expvars.to_file()
i = 1 #single experiment
num_exp = String2TermSet('pexperiment('+str(i)+')')
num_expf = num_exp.to_file()
prg = [ netsf, e... | [
"def",
"get_best_single_experiments",
"(",
"nets",
",",
"expvars",
")",
":",
"netsf",
"=",
"nets",
".",
"to_file",
"(",
")",
"expvarsf",
"=",
"expvars",
".",
"to_file",
"(",
")",
"i",
"=",
"1",
"#single experiment",
"num_exp",
"=",
"String2TermSet",
"(",
"... | returns the experiments as a``TermSet`` object [instance]. | [
"returns",
"the",
"experiments",
"as",
"a",
"TermSet",
"object",
"[",
"instance",
"]",
"."
] | python | train | 29.636364 |
mdavidsaver/p4p | src/p4p/nt/scalar.py | https://github.com/mdavidsaver/p4p/blob/c5e45eac01edfdad9cc2857bc283c7f2695802b8/src/p4p/nt/scalar.py#L214-L226 | def unwrap(klass, value):
"""Unpack a Value into an augmented python type (selected from the 'value' field)
"""
assert isinstance(value, Value), value
V = value.value
try:
T = klass.typeMap[type(V)]
except KeyError:
raise ValueError("Can't unwrap v... | [
"def",
"unwrap",
"(",
"klass",
",",
"value",
")",
":",
"assert",
"isinstance",
"(",
"value",
",",
"Value",
")",
",",
"value",
"V",
"=",
"value",
".",
"value",
"try",
":",
"T",
"=",
"klass",
".",
"typeMap",
"[",
"type",
"(",
"V",
")",
"]",
"except... | Unpack a Value into an augmented python type (selected from the 'value' field) | [
"Unpack",
"a",
"Value",
"into",
"an",
"augmented",
"python",
"type",
"(",
"selected",
"from",
"the",
"value",
"field",
")"
] | python | train | 40.461538 |
DistrictDataLabs/yellowbrick | yellowbrick/features/manifold.py | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/features/manifold.py#L389-L407 | def finalize(self):
"""
Add title and modify axes to make the image ready for display.
"""
self.set_title(
'{} Manifold (fit in {:0.2f} seconds)'.format(
self._name, self.fit_time_.interval
)
)
self.ax.set_xticklabels([])
se... | [
"def",
"finalize",
"(",
"self",
")",
":",
"self",
".",
"set_title",
"(",
"'{} Manifold (fit in {:0.2f} seconds)'",
".",
"format",
"(",
"self",
".",
"_name",
",",
"self",
".",
"fit_time_",
".",
"interval",
")",
")",
"self",
".",
"ax",
".",
"set_xticklabels",
... | Add title and modify axes to make the image ready for display. | [
"Add",
"title",
"and",
"modify",
"axes",
"to",
"make",
"the",
"image",
"ready",
"for",
"display",
"."
] | python | train | 32.473684 |
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#L478-L498 | def get_fw_version(self):
'''
Queries Smoothieware for it's build version, and returns
the parsed response.
returns: str
Current version of attached Smoothi-driver. Versions are derived
from git branch-hash (eg: edge-66ec883NOMSD)
Example Smoothieware re... | [
"def",
"get_fw_version",
"(",
"self",
")",
":",
"version",
"=",
"'Virtual Smoothie'",
"if",
"not",
"self",
".",
"simulating",
":",
"version",
"=",
"self",
".",
"_send_command",
"(",
"'version'",
")",
"version",
"=",
"version",
".",
"split",
"(",
"','",
")"... | Queries Smoothieware for it's build version, and returns
the parsed response.
returns: str
Current version of attached Smoothi-driver. Versions are derived
from git branch-hash (eg: edge-66ec883NOMSD)
Example Smoothieware response:
Build version: edge-66ec883NO... | [
"Queries",
"Smoothieware",
"for",
"it",
"s",
"build",
"version",
"and",
"returns",
"the",
"parsed",
"response",
"."
] | python | train | 35.714286 |
ellmetha/django-machina | machina/apps/forum_member/views.py | https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_member/views.py#L49-L63 | def get_queryset(self):
""" Returns the list of items for this view. """
# Determines the forums that can be accessed by the current user
forums = self.request.forum_permission_handler.get_readable_forums(
Forum.objects.all(), self.request.user,
)
# Returns the posts... | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"# Determines the forums that can be accessed by the current user",
"forums",
"=",
"self",
".",
"request",
".",
"forum_permission_handler",
".",
"get_readable_forums",
"(",
"Forum",
".",
"objects",
".",
"all",
"(",
")",
",... | Returns the list of items for this view. | [
"Returns",
"the",
"list",
"of",
"items",
"for",
"this",
"view",
"."
] | python | train | 40.6 |
Vagrants/blackbird | blackbird/utils/logger.py | https://github.com/Vagrants/blackbird/blob/3b38cd5650caae362e0668dbd38bf8f88233e079/blackbird/utils/logger.py#L69-L91 | def get_handler_fp(logger):
"""
Get handler_fp.
This method is integrated to LoggerFactory Object in the future.
:param logging.Logger logger: Python logging.Logger. logger instance.
:rtype: logging.Logger.handlers.BaseRotatingHandler
:return: Handler or Handler's stream. We call it `handler_fp`... | [
"def",
"get_handler_fp",
"(",
"logger",
")",
":",
"if",
"not",
"hasattr",
"(",
"logger",
",",
"'handlers'",
")",
":",
"raise",
"blackbird",
".",
"utils",
".",
"error",
".",
"BlackbirdError",
"(",
"'Given logger is not logging.Logger instance!'",
")",
"if",
"len"... | Get handler_fp.
This method is integrated to LoggerFactory Object in the future.
:param logging.Logger logger: Python logging.Logger. logger instance.
:rtype: logging.Logger.handlers.BaseRotatingHandler
:return: Handler or Handler's stream. We call it `handler_fp`. | [
"Get",
"handler_fp",
".",
"This",
"method",
"is",
"integrated",
"to",
"LoggerFactory",
"Object",
"in",
"the",
"future",
".",
":",
"param",
"logging",
".",
"Logger",
"logger",
":",
"Python",
"logging",
".",
"Logger",
".",
"logger",
"instance",
".",
":",
"rt... | python | train | 34.391304 |
dls-controls/pymalcolm | malcolm/core/controller.py | https://github.com/dls-controls/pymalcolm/blob/80ea667e4da26365a6cebc0249f52fdc744bd983/malcolm/core/controller.py#L185-L210 | def _handle_put(self, request):
# type: (Put) -> CallbackResponses
"""Called with the lock taken"""
attribute_name = request.path[1]
attribute = self._block[attribute_name]
assert isinstance(attribute, AttributeModel), \
"Cannot Put to %s which is a %s" % (attribute.... | [
"def",
"_handle_put",
"(",
"self",
",",
"request",
")",
":",
"# type: (Put) -> CallbackResponses",
"attribute_name",
"=",
"request",
".",
"path",
"[",
"1",
"]",
"attribute",
"=",
"self",
".",
"_block",
"[",
"attribute_name",
"]",
"assert",
"isinstance",
"(",
"... | Called with the lock taken | [
"Called",
"with",
"the",
"lock",
"taken"
] | python | train | 40.730769 |
LionelAuroux/pyrser | pyrser/ast/state.py | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/ast/state.py#L288-L305 | def nextstate(self, newstate, treenode=None, user_data=None):
"""
Manage transition of state.
"""
if newstate is None:
return self
if isinstance(newstate, State) and id(newstate) != id(self):
return newstate
elif isinstance(newstate, StateEvent):
... | [
"def",
"nextstate",
"(",
"self",
",",
"newstate",
",",
"treenode",
"=",
"None",
",",
"user_data",
"=",
"None",
")",
":",
"if",
"newstate",
"is",
"None",
":",
"return",
"self",
"if",
"isinstance",
"(",
"newstate",
",",
"State",
")",
"and",
"id",
"(",
... | Manage transition of state. | [
"Manage",
"transition",
"of",
"state",
"."
] | python | test | 36.5 |
apache/incubator-mxnet | python/mxnet/contrib/onnx/onnx2mx/_op_translations.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/onnx2mx/_op_translations.py#L301-L305 | def softmax(attrs, inputs, proto_obj):
"""Softmax function."""
if 'axis' not in attrs:
attrs = translation_utils._add_extra_attributes(attrs, {'axis': 1})
return 'softmax', attrs, inputs | [
"def",
"softmax",
"(",
"attrs",
",",
"inputs",
",",
"proto_obj",
")",
":",
"if",
"'axis'",
"not",
"in",
"attrs",
":",
"attrs",
"=",
"translation_utils",
".",
"_add_extra_attributes",
"(",
"attrs",
",",
"{",
"'axis'",
":",
"1",
"}",
")",
"return",
"'softm... | Softmax function. | [
"Softmax",
"function",
"."
] | python | train | 40.4 |
polyaxon/polyaxon | polyaxon/db/models/pipelines.py | https://github.com/polyaxon/polyaxon/blob/e1724f0756b1a42f9e7aa08a976584a84ef7f016/polyaxon/db/models/pipelines.py#L578-L623 | def schedule_start(self) -> bool:
"""Schedule the task: check first if the task can start:
1. we check that the task is still in the CREATED state.
2. we check that the upstream dependency is met.
3. we check that pipeline can start a new task;
i.e. we check the... | [
"def",
"schedule_start",
"(",
"self",
")",
"->",
"bool",
":",
"if",
"self",
".",
"last_status",
"!=",
"self",
".",
"STATUSES",
".",
"CREATED",
":",
"return",
"False",
"upstream_trigger_check",
"=",
"self",
".",
"check_upstream_trigger",
"(",
")",
"if",
"not"... | Schedule the task: check first if the task can start:
1. we check that the task is still in the CREATED state.
2. we check that the upstream dependency is met.
3. we check that pipeline can start a new task;
i.e. we check the concurrency of the pipeline.
4. ... | [
"Schedule",
"the",
"task",
":",
"check",
"first",
"if",
"the",
"task",
"can",
"start",
":",
"1",
".",
"we",
"check",
"that",
"the",
"task",
"is",
"still",
"in",
"the",
"CREATED",
"state",
".",
"2",
".",
"we",
"check",
"that",
"the",
"upstream",
"depe... | python | train | 47.652174 |
googledatalab/pydatalab | solutionbox/structured_data/mltoolbox/_structured_data/trainer/util.py | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/trainer/util.py#L367-L445 | def get_estimator(output_dir, train_config, args):
"""Returns a tf learn estimator.
We only support {DNN, Linear}Regressor and {DNN, Linear}Classifier. This is
controlled by the values of model_type in the args.
Args:
output_dir: Modes are saved into outputdir/train
train_config: our training config
... | [
"def",
"get_estimator",
"(",
"output_dir",
",",
"train_config",
",",
"args",
")",
":",
"# Check the requested mode fits the preprocessed data.",
"target_name",
"=",
"train_config",
"[",
"'target_column'",
"]",
"if",
"is_classification_model",
"(",
"args",
".",
"model_type... | Returns a tf learn estimator.
We only support {DNN, Linear}Regressor and {DNN, Linear}Classifier. This is
controlled by the values of model_type in the args.
Args:
output_dir: Modes are saved into outputdir/train
train_config: our training config
args: command line parameters
Returns:
TF lean... | [
"Returns",
"a",
"tf",
"learn",
"estimator",
"."
] | python | train | 37.620253 |
tensorflow/datasets | tensorflow_datasets/core/features/text/text_encoder.py | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/features/text/text_encoder.py#L378-L397 | def tokenize(self, s):
"""Splits a string into tokens."""
s = tf.compat.as_text(s)
if self.reserved_tokens:
# First split out the reserved tokens
substrs = self._reserved_tokens_re.split(s)
else:
substrs = [s]
toks = []
for substr in substrs:
if substr in self.reserved_... | [
"def",
"tokenize",
"(",
"self",
",",
"s",
")",
":",
"s",
"=",
"tf",
".",
"compat",
".",
"as_text",
"(",
"s",
")",
"if",
"self",
".",
"reserved_tokens",
":",
"# First split out the reserved tokens",
"substrs",
"=",
"self",
".",
"_reserved_tokens_re",
".",
"... | Splits a string into tokens. | [
"Splits",
"a",
"string",
"into",
"tokens",
"."
] | python | train | 24.15 |
tensorflow/datasets | tensorflow_datasets/text/cnn_dailymail.py | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/text/cnn_dailymail.py#L163-L207 | def _get_art_abs(story_file):
"""Get abstract (highlights) and article from a story file path."""
# Based on https://github.com/abisee/cnn-dailymail/blob/master/
# make_datafiles.py
lines = _read_text_file(story_file)
# Lowercase everything
lines = [line.lower() for line in lines]
# Put periods on ... | [
"def",
"_get_art_abs",
"(",
"story_file",
")",
":",
"# Based on https://github.com/abisee/cnn-dailymail/blob/master/",
"# make_datafiles.py",
"lines",
"=",
"_read_text_file",
"(",
"story_file",
")",
"# Lowercase everything",
"lines",
"=",
"[",
"line",
".",
"lower",
"(",... | Get abstract (highlights) and article from a story file path. | [
"Get",
"abstract",
"(",
"highlights",
")",
"and",
"article",
"from",
"a",
"story",
"file",
"path",
"."
] | python | train | 32.288889 |
inveniosoftware/invenio-communities | invenio_communities/models.py | https://github.com/inveniosoftware/invenio-communities/blob/5c4de6783724d276ae1b6dd13a399a9e22fadc7a/invenio_communities/models.py#L343-L353 | def reject_record(self, record):
"""Reject a record for inclusion in the community.
:param record: Record object.
"""
with db.session.begin_nested():
req = InclusionRequest.get(self.id, record.id)
if req is None:
raise InclusionRequestMissingError... | [
"def",
"reject_record",
"(",
"self",
",",
"record",
")",
":",
"with",
"db",
".",
"session",
".",
"begin_nested",
"(",
")",
":",
"req",
"=",
"InclusionRequest",
".",
"get",
"(",
"self",
".",
"id",
",",
"record",
".",
"id",
")",
"if",
"req",
"is",
"N... | Reject a record for inclusion in the community.
:param record: Record object. | [
"Reject",
"a",
"record",
"for",
"inclusion",
"in",
"the",
"community",
"."
] | python | train | 37.909091 |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_xstp_ext.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_xstp_ext.py#L3943-L3955 | def get_stp_mst_detail_output_cist_cist_bridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist ... | [
"def",
"get_stp_mst_detail_output_cist_cist_bridge_id",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_stp_mst_detail",
"=",
"ET",
".",
"Element",
"(",
"\"get_stp_mst_detail\"",
")",
"config",
"=... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 42.461538 |
TkTech/PyNBT | pynbt/nbt.py | https://github.com/TkTech/PyNBT/blob/060fb0a2b58fc464a637fc108f05bd7274da8e5f/pynbt/nbt.py#L272-L277 | def update(self, *args, **kwargs):
"""See `__setitem__`."""
super(TAG_Compound, self).update(*args, **kwargs)
for key, item in self.items():
if item.name is None:
item.name = key | [
"def",
"update",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"TAG_Compound",
",",
"self",
")",
".",
"update",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"for",
"key",
",",
"item",
"in",
"self",
".",
"ite... | See `__setitem__`. | [
"See",
"__setitem__",
"."
] | python | train | 37.5 |
programa-stic/barf-project | barf/core/reil/emulator/emulator.py | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/emulator/emulator.py#L108-L117 | def execute_lite(self, instructions, context=None):
"""Execute a list of instructions. It does not support loops.
"""
if context:
self.__cpu.registers = dict(context)
for instr in instructions:
self.__execute_one(instr)
return dict(self.__cpu.registers),... | [
"def",
"execute_lite",
"(",
"self",
",",
"instructions",
",",
"context",
"=",
"None",
")",
":",
"if",
"context",
":",
"self",
".",
"__cpu",
".",
"registers",
"=",
"dict",
"(",
"context",
")",
"for",
"instr",
"in",
"instructions",
":",
"self",
".",
"__e... | Execute a list of instructions. It does not support loops. | [
"Execute",
"a",
"list",
"of",
"instructions",
".",
"It",
"does",
"not",
"support",
"loops",
"."
] | python | train | 32.2 |
keras-rl/keras-rl | rl/callbacks.py | https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L312-L336 | def on_episode_end(self, episode, logs):
""" Compute and print metrics at the end of each episode """
duration = timeit.default_timer() - self.starts[episode]
metrics = self.metrics[episode]
if np.isnan(metrics).all():
mean_metrics = np.array([np.nan for _ in self.metrics_n... | [
"def",
"on_episode_end",
"(",
"self",
",",
"episode",
",",
"logs",
")",
":",
"duration",
"=",
"timeit",
".",
"default_timer",
"(",
")",
"-",
"self",
".",
"starts",
"[",
"episode",
"]",
"metrics",
"=",
"self",
".",
"metrics",
"[",
"episode",
"]",
"if",
... | Compute and print metrics at the end of each episode | [
"Compute",
"and",
"print",
"metrics",
"at",
"the",
"end",
"of",
"each",
"episode"
] | python | train | 36.96 |
zomux/deepy | deepy/tensor/functions.py | https://github.com/zomux/deepy/blob/090fbad22a08a809b12951cd0d4984f5bd432698/deepy/tensor/functions.py#L38-L49 | def concatenate(vars, axis=-1):
"""
A utility function of concatenate.
"""
from deepy.core.neural_var import NeuralVariable
if isinstance(vars[0], NeuralVariable):
concat_var = Concatenate(axis=axis).compute(*vars)
if axis == -1 or axis == vars[0].tensor.ndim - 1:
concat_... | [
"def",
"concatenate",
"(",
"vars",
",",
"axis",
"=",
"-",
"1",
")",
":",
"from",
"deepy",
".",
"core",
".",
"neural_var",
"import",
"NeuralVariable",
"if",
"isinstance",
"(",
"vars",
"[",
"0",
"]",
",",
"NeuralVariable",
")",
":",
"concat_var",
"=",
"C... | A utility function of concatenate. | [
"A",
"utility",
"function",
"of",
"concatenate",
"."
] | python | test | 36.833333 |
saltstack/salt | salt/cli/daemons.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/daemons.py#L485-L510 | def start(self):
'''
Start the actual proxy minion.
If sub-classed, don't **ever** forget to run:
super(YourSubClass, self).start()
NOTE: Run any required code before calling `super()`.
'''
super(ProxyMinion, self).start()
try:
if check_... | [
"def",
"start",
"(",
"self",
")",
":",
"super",
"(",
"ProxyMinion",
",",
"self",
")",
".",
"start",
"(",
")",
"try",
":",
"if",
"check_user",
"(",
"self",
".",
"config",
"[",
"'user'",
"]",
")",
":",
"self",
".",
"action_log_info",
"(",
"'The Proxy M... | Start the actual proxy minion.
If sub-classed, don't **ever** forget to run:
super(YourSubClass, self).start()
NOTE: Run any required code before calling `super()`. | [
"Start",
"the",
"actual",
"proxy",
"minion",
"."
] | python | train | 35.961538 |
wummel/linkchecker | linkcheck/decorators.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/decorators.py#L135-L137 | def timed (log=sys.stderr, limit=2.0):
"""Decorator to run a function with timing info."""
return lambda func: timeit(func, log, limit) | [
"def",
"timed",
"(",
"log",
"=",
"sys",
".",
"stderr",
",",
"limit",
"=",
"2.0",
")",
":",
"return",
"lambda",
"func",
":",
"timeit",
"(",
"func",
",",
"log",
",",
"limit",
")"
] | Decorator to run a function with timing info. | [
"Decorator",
"to",
"run",
"a",
"function",
"with",
"timing",
"info",
"."
] | python | train | 47 |
log2timeline/dfvfs | dfvfs/path/path_spec.py | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/path/path_spec.py#L50-L70 | def _GetComparable(self, sub_comparable_string=''):
"""Retrieves the comparable representation.
This is a convenience function for constructing comparables.
Args:
sub_comparable_string (str): sub comparable string.
Returns:
str: comparable representation of the path specification.
"""... | [
"def",
"_GetComparable",
"(",
"self",
",",
"sub_comparable_string",
"=",
"''",
")",
":",
"string_parts",
"=",
"[",
"]",
"string_parts",
".",
"append",
"(",
"getattr",
"(",
"self",
".",
"parent",
",",
"'comparable'",
",",
"''",
")",
")",
"string_parts",
"."... | Retrieves the comparable representation.
This is a convenience function for constructing comparables.
Args:
sub_comparable_string (str): sub comparable string.
Returns:
str: comparable representation of the path specification. | [
"Retrieves",
"the",
"comparable",
"representation",
"."
] | python | train | 29.333333 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.