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 |
|---|---|---|---|---|---|---|---|---|---|
scrapinghub/exporters | exporters/readers/hubstorage_reader.py | https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/readers/hubstorage_reader.py#L81-L97 | def get_next_batch(self):
"""
This method is called from the manager. It must return a list or a generator
of BaseRecord objects.
When it has nothing else to read, it must set class variable "finished" to True.
"""
if self.collection_scanner.is_enabled:
batch ... | [
"def",
"get_next_batch",
"(",
"self",
")",
":",
"if",
"self",
".",
"collection_scanner",
".",
"is_enabled",
":",
"batch",
"=",
"self",
".",
"collection_scanner",
".",
"get_new_batch",
"(",
")",
"for",
"item",
"in",
"batch",
":",
"base_item",
"=",
"BaseRecord... | This method is called from the manager. It must return a list or a generator
of BaseRecord objects.
When it has nothing else to read, it must set class variable "finished" to True. | [
"This",
"method",
"is",
"called",
"from",
"the",
"manager",
".",
"It",
"must",
"return",
"a",
"list",
"or",
"a",
"generator",
"of",
"BaseRecord",
"objects",
".",
"When",
"it",
"has",
"nothing",
"else",
"to",
"read",
"it",
"must",
"set",
"class",
"variabl... | python | train | 41.176471 |
rochacbruno/dynaconf | dynaconf/loaders/env_loader.py | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/loaders/env_loader.py#L60-L63 | def write(settings_path, settings_data, **kwargs):
"""Write data to .env file"""
for key, value in settings_data.items():
dotenv_cli.set_key(str(settings_path), key.upper(), str(value)) | [
"def",
"write",
"(",
"settings_path",
",",
"settings_data",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"key",
",",
"value",
"in",
"settings_data",
".",
"items",
"(",
")",
":",
"dotenv_cli",
".",
"set_key",
"(",
"str",
"(",
"settings_path",
")",
",",
"ke... | Write data to .env file | [
"Write",
"data",
"to",
".",
"env",
"file"
] | python | train | 49.5 |
aestrivex/bctpy | bct/algorithms/generative.py | https://github.com/aestrivex/bctpy/blob/4cb0e759eb4a038750b07e23bd29958c400684b8/bct/algorithms/generative.py#L10-L527 | def generative_model(A, D, m, eta, gamma=None, model_type='matching',
model_var='powerlaw', epsilon=1e-6, copy=True, seed=None):
'''
Generates synthetic networks using the models described in
Betzel et al. (2016) Neuroimage. See this paper for more details.
Succinctly, the probability of forming a... | [
"def",
"generative_model",
"(",
"A",
",",
"D",
",",
"m",
",",
"eta",
",",
"gamma",
"=",
"None",
",",
"model_type",
"=",
"'matching'",
",",
"model_var",
"=",
"'powerlaw'",
",",
"epsilon",
"=",
"1e-6",
",",
"copy",
"=",
"True",
",",
"seed",
"=",
"None"... | Generates synthetic networks using the models described in
Betzel et al. (2016) Neuroimage. See this paper for more details.
Succinctly, the probability of forming a connection between nodes u and v is
P(u,v) = E(u,v)**eta * K(u,v)**gamma
where eta and gamma are hyperparameters, E(u,v) is the euclidean... | [
"Generates",
"synthetic",
"networks",
"using",
"the",
"models",
"described",
"in",
"Betzel",
"et",
"al",
".",
"(",
"2016",
")",
"Neuroimage",
".",
"See",
"this",
"paper",
"for",
"more",
"details",
"."
] | python | train | 32.625483 |
clalancette/pycdlib | pycdlib/pycdlib.py | https://github.com/clalancette/pycdlib/blob/1e7b77a809e905d67dc71e12d70e850be26b6233/pycdlib/pycdlib.py#L2587-L2661 | def _get_file_from_iso_fp(self, outfp, blocksize, iso_path, rr_path, joliet_path):
# type: (BinaryIO, int, Optional[bytes], Optional[bytes], Optional[bytes]) -> None
'''
An internal method to fetch a single file from the ISO and write it out
to the file object.
Parameters:
... | [
"def",
"_get_file_from_iso_fp",
"(",
"self",
",",
"outfp",
",",
"blocksize",
",",
"iso_path",
",",
"rr_path",
",",
"joliet_path",
")",
":",
"# type: (BinaryIO, int, Optional[bytes], Optional[bytes], Optional[bytes]) -> None",
"if",
"joliet_path",
"is",
"not",
"None",
":",... | An internal method to fetch a single file from the ISO and write it out
to the file object.
Parameters:
outfp - The file object to write data to.
blocksize - The number of bytes in each transfer.
iso_path - The absolute ISO9660 path to lookup on the ISO (exclusive
... | [
"An",
"internal",
"method",
"to",
"fetch",
"a",
"single",
"file",
"from",
"the",
"ISO",
"and",
"write",
"it",
"out",
"to",
"the",
"file",
"object",
"."
] | python | train | 54.64 |
BD2KGenomics/toil-scripts | src/toil_scripts/gatk_germline/germline.py | https://github.com/BD2KGenomics/toil-scripts/blob/f878d863defcdccaabb7fe06f991451b7a198fb7/src/toil_scripts/gatk_germline/germline.py#L752-L894 | def main():
"""
GATK germline pipeline with variant filtering and annotation.
"""
# Define Parser object and add to jobTree
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawTextHelpFormatter)
# Generate subparsers
subparsers = parser.add_subparsers(dest='com... | [
"def",
"main",
"(",
")",
":",
"# Define Parser object and add to jobTree",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"__doc__",
",",
"formatter_class",
"=",
"argparse",
".",
"RawTextHelpFormatter",
")",
"# Generate subparsers",
"subparse... | GATK germline pipeline with variant filtering and annotation. | [
"GATK",
"germline",
"pipeline",
"with",
"variant",
"filtering",
"and",
"annotation",
"."
] | python | train | 45.888112 |
jepegit/cellpy | cellpy/utils/batch_tools/dumpers.py | https://github.com/jepegit/cellpy/blob/9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370/cellpy/utils/batch_tools/dumpers.py#L78-L105 | def screen_dumper(**kwargs):
"""Dump data to screen."""
farms = kwargs["farms"]
engine = kwargs["engine"]
logging.info("dumping to screen")
print(f"\n[Screen dumper] ({engine})")
try:
if len(farms) == 1:
print(f"You have one farm with little pandas.")
else:
... | [
"def",
"screen_dumper",
"(",
"*",
"*",
"kwargs",
")",
":",
"farms",
"=",
"kwargs",
"[",
"\"farms\"",
"]",
"engine",
"=",
"kwargs",
"[",
"\"engine\"",
"]",
"logging",
".",
"info",
"(",
"\"dumping to screen\"",
")",
"print",
"(",
"f\"\\n[Screen dumper] ({engine}... | Dump data to screen. | [
"Dump",
"data",
"to",
"screen",
"."
] | python | train | 31.571429 |
openid/python-openid | openid/oidutil.py | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/oidutil.py#L55-L89 | def importElementTree(module_names=None):
"""Find a working ElementTree implementation, trying the standard
places that such a thing might show up.
>>> ElementTree = importElementTree()
@param module_names: The names of modules to try to use as
ElementTree. Defaults to C{L{elementtree_modules}... | [
"def",
"importElementTree",
"(",
"module_names",
"=",
"None",
")",
":",
"if",
"module_names",
"is",
"None",
":",
"module_names",
"=",
"elementtree_modules",
"for",
"mod_name",
"in",
"module_names",
":",
"try",
":",
"ElementTree",
"=",
"__import__",
"(",
"mod_nam... | Find a working ElementTree implementation, trying the standard
places that such a thing might show up.
>>> ElementTree = importElementTree()
@param module_names: The names of modules to try to use as
ElementTree. Defaults to C{L{elementtree_modules}}
@returns: An ElementTree module | [
"Find",
"a",
"working",
"ElementTree",
"implementation",
"trying",
"the",
"standard",
"places",
"that",
"such",
"a",
"thing",
"might",
"show",
"up",
"."
] | python | train | 35 |
Accelize/pycosio | pycosio/storage/swift.py | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/swift.py#L149-L163 | def _remove(self, client_kwargs):
"""
Remove an object.
args:
client_kwargs (dict): Client arguments.
"""
with _handle_client_exception():
# Object
if 'obj' in client_kwargs:
return self.client.delete_object(
... | [
"def",
"_remove",
"(",
"self",
",",
"client_kwargs",
")",
":",
"with",
"_handle_client_exception",
"(",
")",
":",
"# Object",
"if",
"'obj'",
"in",
"client_kwargs",
":",
"return",
"self",
".",
"client",
".",
"delete_object",
"(",
"client_kwargs",
"[",
"'contain... | Remove an object.
args:
client_kwargs (dict): Client arguments. | [
"Remove",
"an",
"object",
"."
] | python | train | 30.533333 |
mjirik/imcut | imcut/features.py | https://github.com/mjirik/imcut/blob/1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3/imcut/features.py#L39-L58 | def select_from_fv_by_seeds(fv, seeds, unique_cls):
"""
Tool to make simple feature functions take features from feature array by seeds.
:param fv: ndarray with lineariezed feature. It's shape is MxN, where M is number of image pixels and N is number
of features
:param seeds: ndarray with seeds. Doe... | [
"def",
"select_from_fv_by_seeds",
"(",
"fv",
",",
"seeds",
",",
"unique_cls",
")",
":",
"logger",
".",
"debug",
"(",
"\"seeds\"",
"+",
"str",
"(",
"seeds",
")",
")",
"# fvlin = fv.reshape(-1, int(fv.size/seeds.size))",
"expected_shape",
"=",
"[",
"seeds",
".",
"... | Tool to make simple feature functions take features from feature array by seeds.
:param fv: ndarray with lineariezed feature. It's shape is MxN, where M is number of image pixels and N is number
of features
:param seeds: ndarray with seeds. Does not to be linear.
:param unique_cls: number of used seeds ... | [
"Tool",
"to",
"make",
"simple",
"feature",
"functions",
"take",
"features",
"from",
"feature",
"array",
"by",
"seeds",
".",
":",
"param",
"fv",
":",
"ndarray",
"with",
"lineariezed",
"feature",
".",
"It",
"s",
"shape",
"is",
"MxN",
"where",
"M",
"is",
"n... | python | train | 50.6 |
numenta/nupic | src/nupic/database/client_jobs_dao.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/client_jobs_dao.py#L1851-L1887 | def jobSetCompleted(self, jobID, completionReason, completionMsg,
useConnectionID = True):
""" Change the status on the given job to completed
Parameters:
----------------------------------------------------------------
job: jobID of the job to mark as completed
... | [
"def",
"jobSetCompleted",
"(",
"self",
",",
"jobID",
",",
"completionReason",
",",
"completionMsg",
",",
"useConnectionID",
"=",
"True",
")",
":",
"# Get a database connection and cursor",
"with",
"ConnectionFactory",
".",
"get",
"(",
")",
"as",
"conn",
":",
"quer... | Change the status on the given job to completed
Parameters:
----------------------------------------------------------------
job: jobID of the job to mark as completed
completionReason: completionReason string
completionMsg: completionMsg string
useConnectionID: True i... | [
"Change",
"the",
"status",
"on",
"the",
"given",
"job",
"to",
"completed"
] | python | valid | 41.054054 |
python-beaver/python-beaver | beaver/utils.py | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/utils.py#L180-L210 | def multiline_merge(lines, current_event, re_after, re_before):
""" Merge multi-line events based.
Some event (like Python trackback or Java stracktrace) spawn
on multiple line. This method will merge them using two
regular expression: regex_after and regex_before.
If a line match ... | [
"def",
"multiline_merge",
"(",
"lines",
",",
"current_event",
",",
"re_after",
",",
"re_before",
")",
":",
"events",
"=",
"[",
"]",
"for",
"line",
"in",
"lines",
":",
"if",
"re_before",
"and",
"re_before",
".",
"match",
"(",
"line",
")",
":",
"current_ev... | Merge multi-line events based.
Some event (like Python trackback or Java stracktrace) spawn
on multiple line. This method will merge them using two
regular expression: regex_after and regex_before.
If a line match re_after, it will be merged with next line.
If a line match re_... | [
"Merge",
"multi",
"-",
"line",
"events",
"based",
"."
] | python | train | 40.032258 |
ns1/ns1-python | ns1/__init__.py | https://github.com/ns1/ns1-python/blob/f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e/ns1/__init__.py#L125-L132 | def notifylists(self):
"""
Return a new raw REST interface to notify list resources
:rtype: :py:class:`ns1.rest.monitoring.NotifyLists`
"""
import ns1.rest.monitoring
return ns1.rest.monitoring.NotifyLists(self.config) | [
"def",
"notifylists",
"(",
"self",
")",
":",
"import",
"ns1",
".",
"rest",
".",
"monitoring",
"return",
"ns1",
".",
"rest",
".",
"monitoring",
".",
"NotifyLists",
"(",
"self",
".",
"config",
")"
] | Return a new raw REST interface to notify list resources
:rtype: :py:class:`ns1.rest.monitoring.NotifyLists` | [
"Return",
"a",
"new",
"raw",
"REST",
"interface",
"to",
"notify",
"list",
"resources"
] | python | train | 32.5 |
pyviz/holoviews | holoviews/core/io.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/core/io.py#L132-L138 | def _merge_metadata(self_or_cls, obj, fn, *dicts):
"""
Returns a merged metadata info dictionary from the supplied
function and additional dictionaries
"""
merged = dict([(k,v) for d in dicts for (k,v) in d.items()])
return dict(merged, **fn(obj)) if fn else merged | [
"def",
"_merge_metadata",
"(",
"self_or_cls",
",",
"obj",
",",
"fn",
",",
"*",
"dicts",
")",
":",
"merged",
"=",
"dict",
"(",
"[",
"(",
"k",
",",
"v",
")",
"for",
"d",
"in",
"dicts",
"for",
"(",
"k",
",",
"v",
")",
"in",
"d",
".",
"items",
"(... | Returns a merged metadata info dictionary from the supplied
function and additional dictionaries | [
"Returns",
"a",
"merged",
"metadata",
"info",
"dictionary",
"from",
"the",
"supplied",
"function",
"and",
"additional",
"dictionaries"
] | python | train | 43.857143 |
noahbenson/neuropythy | neuropythy/hcp/files.py | https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/hcp/files.py#L1833-L1898 | def auto_download(status,
credentials=None, subjects_path=None, overwrite=False, release='HCP_1200',
database='hcp-openaccess', retinotopy_path=None, retinotopy_cache=True):
'''
auto_download(True) enables automatic downloading of HCP subject data when the subject ID
is... | [
"def",
"auto_download",
"(",
"status",
",",
"credentials",
"=",
"None",
",",
"subjects_path",
"=",
"None",
",",
"overwrite",
"=",
"False",
",",
"release",
"=",
"'HCP_1200'",
",",
"database",
"=",
"'hcp-openaccess'",
",",
"retinotopy_path",
"=",
"None",
",",
... | auto_download(True) enables automatic downloading of HCP subject data when the subject ID
is requested. The optional arguments are identical to those required for the function
download(), and they are passed to download() when auto-downloading occurs.
auto_download(False) disables automatic downloading.... | [
"auto_download",
"(",
"True",
")",
"enables",
"automatic",
"downloading",
"of",
"HCP",
"subject",
"data",
"when",
"the",
"subject",
"ID",
"is",
"requested",
".",
"The",
"optional",
"arguments",
"are",
"identical",
"to",
"those",
"required",
"for",
"the",
"func... | python | train | 60.318182 |
ajenhl/tacl | tacl/sequence.py | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/sequence.py#L151-L181 | def _generate_sequences(self, primary_label, secondary_label, ngrams):
"""Generates aligned sequences between each witness labelled
`primary_label` and each witness labelled `secondary_label`,
based around `ngrams`.
:param primary_label: label for one side of the pairs of
... | [
"def",
"_generate_sequences",
"(",
"self",
",",
"primary_label",
",",
"secondary_label",
",",
"ngrams",
")",
":",
"cols",
"=",
"[",
"constants",
".",
"WORK_FIELDNAME",
",",
"constants",
".",
"SIGLUM_FIELDNAME",
"]",
"primary_works",
"=",
"self",
".",
"_matches",... | Generates aligned sequences between each witness labelled
`primary_label` and each witness labelled `secondary_label`,
based around `ngrams`.
:param primary_label: label for one side of the pairs of
witnesses to align
:type primary_label: `str`
:par... | [
"Generates",
"aligned",
"sequences",
"between",
"each",
"witness",
"labelled",
"primary_label",
"and",
"each",
"witness",
"labelled",
"secondary_label",
"based",
"around",
"ngrams",
"."
] | python | train | 50.419355 |
foxx/python-helpful | helpful.py | https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L408-L423 | def default(*args, **kwargs):
"""
Return first argument which is "truthy"
>>> default(None, None, 1)
1
>>> default(None, None, 123)
123
>>> print(default(None, None))
None
"""
default = kwargs.get('default', None)
for arg in args:
if arg:
return arg
r... | [
"def",
"default",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"default",
"=",
"kwargs",
".",
"get",
"(",
"'default'",
",",
"None",
")",
"for",
"arg",
"in",
"args",
":",
"if",
"arg",
":",
"return",
"arg",
"return",
"default"
] | Return first argument which is "truthy"
>>> default(None, None, 1)
1
>>> default(None, None, 123)
123
>>> print(default(None, None))
None | [
"Return",
"first",
"argument",
"which",
"is",
"truthy"
] | python | train | 19.875 |
dmwm/DBS | Server/Python/src/dbs/business/DBSBlock.py | https://github.com/dmwm/DBS/blob/9619bafce3783b3e77f0415f8f9a258e33dd1e6f/Server/Python/src/dbs/business/DBSBlock.py#L219-L231 | def listBlockChildren(self, block_name=""):
"""
list parents of a block
"""
if (not block_name) or re.search("['%','*']", block_name):
dbsExceptionHandler("dbsException-invalid-input", "DBSBlock/listBlockChildren. Block_name must be provided." )
conn = self.dbi.connec... | [
"def",
"listBlockChildren",
"(",
"self",
",",
"block_name",
"=",
"\"\"",
")",
":",
"if",
"(",
"not",
"block_name",
")",
"or",
"re",
".",
"search",
"(",
"\"['%','*']\"",
",",
"block_name",
")",
":",
"dbsExceptionHandler",
"(",
"\"dbsException-invalid-input\"",
... | list parents of a block | [
"list",
"parents",
"of",
"a",
"block"
] | python | train | 37.615385 |
trailofbits/manticore | examples/script/concolic.py | https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/examples/script/concolic.py#L97-L123 | def perm(lst, func):
''' Produce permutations of `lst`, where permutations are mutated by `func`. Used for flipping constraints. highly
possible that returned constraints can be unsat this does it blindly, without any attention to the constraints
themselves
Considering lst as a list of constraints, e.g... | [
"def",
"perm",
"(",
"lst",
",",
"func",
")",
":",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"2",
"**",
"len",
"(",
"lst",
")",
")",
":",
"yield",
"[",
"func",
"(",
"item",
")",
"if",
"(",
"1",
"<<",
"j",
")",
"&",
"i",
"else",
"item",
"fo... | Produce permutations of `lst`, where permutations are mutated by `func`. Used for flipping constraints. highly
possible that returned constraints can be unsat this does it blindly, without any attention to the constraints
themselves
Considering lst as a list of constraints, e.g.
[ C1, C2, C3 ]
... | [
"Produce",
"permutations",
"of",
"lst",
"where",
"permutations",
"are",
"mutated",
"by",
"func",
".",
"Used",
"for",
"flipping",
"constraints",
".",
"highly",
"possible",
"that",
"returned",
"constraints",
"can",
"be",
"unsat",
"this",
"does",
"it",
"blindly",
... | python | valid | 40.62963 |
saltstack/salt | salt/engines/webhook.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/webhook.py#L17-L88 | def start(address=None, port=5000, ssl_crt=None, ssl_key=None):
'''
Api to listen for webhooks to send to the reactor.
Implement the webhook behavior in an engine.
:py:class:`rest_cherrypy Webhook docs <salt.netapi.rest_cherrypy.app.Webhook>`
Unlike the rest_cherrypy Webhook, this is only an unaut... | [
"def",
"start",
"(",
"address",
"=",
"None",
",",
"port",
"=",
"5000",
",",
"ssl_crt",
"=",
"None",
",",
"ssl_key",
"=",
"None",
")",
":",
"if",
"__opts__",
".",
"get",
"(",
"'__role'",
")",
"==",
"'master'",
":",
"fire_master",
"=",
"salt",
".",
"... | Api to listen for webhooks to send to the reactor.
Implement the webhook behavior in an engine.
:py:class:`rest_cherrypy Webhook docs <salt.netapi.rest_cherrypy.app.Webhook>`
Unlike the rest_cherrypy Webhook, this is only an unauthenticated webhook
endpoint. If an authenticated webhook endpoint is ne... | [
"Api",
"to",
"listen",
"for",
"webhooks",
"to",
"send",
"to",
"the",
"reactor",
"."
] | python | train | 35.611111 |
tensorflow/tensor2tensor | tensor2tensor/data_generators/text_encoder.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_encoder.py#L400-L422 | def _escape_token(token, alphabet):
"""Escape away underscores and OOV characters and append '_'.
This allows the token to be expressed as the concatenation of a list
of subtokens from the vocabulary. The underscore acts as a sentinel
which allows us to invertibly concatenate multiple such lists.
Args:
... | [
"def",
"_escape_token",
"(",
"token",
",",
"alphabet",
")",
":",
"if",
"not",
"isinstance",
"(",
"token",
",",
"six",
".",
"text_type",
")",
":",
"raise",
"ValueError",
"(",
"\"Expected string type for token, got %s\"",
"%",
"type",
"(",
"token",
")",
")",
"... | Escape away underscores and OOV characters and append '_'.
This allows the token to be expressed as the concatenation of a list
of subtokens from the vocabulary. The underscore acts as a sentinel
which allows us to invertibly concatenate multiple such lists.
Args:
token: A unicode string to be escaped.
... | [
"Escape",
"away",
"underscores",
"and",
"OOV",
"characters",
"and",
"append",
"_",
"."
] | python | train | 35.913043 |
wmayner/pyphi | pyphi/conf.py | https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/conf.py#L275-L282 | def load_file(self, filename):
"""Load config from a YAML file."""
filename = os.path.abspath(filename)
with open(filename) as f:
self.load_dict(yaml.load(f))
self._loaded_files.append(filename) | [
"def",
"load_file",
"(",
"self",
",",
"filename",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"filename",
")",
"with",
"open",
"(",
"filename",
")",
"as",
"f",
":",
"self",
".",
"load_dict",
"(",
"yaml",
".",
"load",
"(",
"f"... | Load config from a YAML file. | [
"Load",
"config",
"from",
"a",
"YAML",
"file",
"."
] | python | train | 29.125 |
fbcotter/py3nvml | py3nvml/py3nvml.py | https://github.com/fbcotter/py3nvml/blob/47f0f2c0eee56dec4e4beebec26b734e01d357b7/py3nvml/py3nvml.py#L2183-L2213 | def nvmlDeviceGetSerial(handle):
r"""
/**
* Retrieves the globally unique board serial number associated with this device's board.
*
* For all products with an inforom.
*
* The serial number is an alphanumeric string that will not exceed 30 characters (including the NULL terminator).
... | [
"def",
"nvmlDeviceGetSerial",
"(",
"handle",
")",
":",
"c_serial",
"=",
"create_string_buffer",
"(",
"NVML_DEVICE_SERIAL_BUFFER_SIZE",
")",
"fn",
"=",
"_nvmlGetFunctionPointer",
"(",
"\"nvmlDeviceGetSerial\"",
")",
"ret",
"=",
"fn",
"(",
"handle",
",",
"c_serial",
"... | r"""
/**
* Retrieves the globally unique board serial number associated with this device's board.
*
* For all products with an inforom.
*
* The serial number is an alphanumeric string that will not exceed 30 characters (including the NULL terminator).
* This number matches the serial n... | [
"r",
"/",
"**",
"*",
"Retrieves",
"the",
"globally",
"unique",
"board",
"serial",
"number",
"associated",
"with",
"this",
"device",
"s",
"board",
".",
"*",
"*",
"For",
"all",
"products",
"with",
"an",
"inforom",
".",
"*",
"*",
"The",
"serial",
"number",
... | python | train | 56.483871 |
asottile/git-code-debt | git_code_debt/discovery.py | https://github.com/asottile/git-code-debt/blob/31b41e2510063e9739de7987cdca95eaccaecbd6/git_code_debt/discovery.py#L22-L40 | def get_metric_parsers(metric_packages=tuple(), include_defaults=True):
"""Gets all of the metric parsers.
Args:
metric_packages - Defaults to no extra packages. An iterable of
metric containing packages. A metric inherits DiffParserBase
and does not have __metric__ = False
... | [
"def",
"get_metric_parsers",
"(",
"metric_packages",
"=",
"tuple",
"(",
")",
",",
"include_defaults",
"=",
"True",
")",
":",
"metric_parsers",
"=",
"set",
"(",
")",
"if",
"include_defaults",
":",
"import",
"git_code_debt",
".",
"metrics",
"metric_parsers",
".",
... | Gets all of the metric parsers.
Args:
metric_packages - Defaults to no extra packages. An iterable of
metric containing packages. A metric inherits DiffParserBase
and does not have __metric__ = False
A metric package must be imported using import a.b.c
include_d... | [
"Gets",
"all",
"of",
"the",
"metric",
"parsers",
"."
] | python | train | 39.631579 |
brocade/pynos | pynos/versions/ver_7/ver_7_1_0/yang/brocade_vswitch.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_vswitch.py#L833-L844 | def get_vnetwork_portgroups_input_last_rcvd_instance(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vnetwork_portgroups = ET.Element("get_vnetwork_portgroups")
config = get_vnetwork_portgroups
input = ET.SubElement(get_vnetwork_portgroups, "... | [
"def",
"get_vnetwork_portgroups_input_last_rcvd_instance",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_vnetwork_portgroups",
"=",
"ET",
".",
"Element",
"(",
"\"get_vnetwork_portgroups\"",
")",
"... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 45.5 |
intel-analytics/BigDL | pyspark/bigdl/util/common.py | https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/util/common.py#L576-L592 | def callBigDlFunc(bigdl_type, name, *args):
""" Call API in PythonBigDL """
gateway = _get_gateway()
error = Exception("Cannot find function: %s" % name)
for jinvoker in JavaCreator.instance(bigdl_type, gateway).value:
# hasattr(jinvoker, name) always return true here,
# so you need to i... | [
"def",
"callBigDlFunc",
"(",
"bigdl_type",
",",
"name",
",",
"*",
"args",
")",
":",
"gateway",
"=",
"_get_gateway",
"(",
")",
"error",
"=",
"Exception",
"(",
"\"Cannot find function: %s\"",
"%",
"name",
")",
"for",
"jinvoker",
"in",
"JavaCreator",
".",
"inst... | Call API in PythonBigDL | [
"Call",
"API",
"in",
"PythonBigDL"
] | python | test | 37 |
gmichaeljaison/cv-utils | cv_utils/img_utils.py | https://github.com/gmichaeljaison/cv-utils/blob/a8251c870165a7428d8c468a6436aa41d0cf7c09/cv_utils/img_utils.py#L200-L220 | def imshow(*imgs, **options):
"""
Plots multiple images using matplotlib
by dynamically finding the required number of rows and cols.
:param imgs: Images as any number of arguments
:param options: Dict of options
- cmap: Color map for gray scale images
- vmin: Minimum value to be... | [
"def",
"imshow",
"(",
"*",
"imgs",
",",
"*",
"*",
"options",
")",
":",
"n",
"=",
"len",
"(",
"imgs",
")",
"nrows",
"=",
"int",
"(",
"math",
".",
"ceil",
"(",
"math",
".",
"sqrt",
"(",
"n",
")",
")",
")",
"ncols",
"=",
"int",
"(",
"math",
".... | Plots multiple images using matplotlib
by dynamically finding the required number of rows and cols.
:param imgs: Images as any number of arguments
:param options: Dict of options
- cmap: Color map for gray scale images
- vmin: Minimum value to be used in color map
- vmax: Maximum... | [
"Plots",
"multiple",
"images",
"using",
"matplotlib",
"by",
"dynamically",
"finding",
"the",
"required",
"number",
"of",
"rows",
"and",
"cols",
".",
":",
"param",
"imgs",
":",
"Images",
"as",
"any",
"number",
"of",
"arguments",
":",
"param",
"options",
":",
... | python | train | 34.047619 |
nicolargo/glances | glances/outputs/glances_bottle.py | https://github.com/nicolargo/glances/blob/5bd4d587a736e0d2b03170b56926841d2a3eb7ee/glances/outputs/glances_bottle.py#L583-L603 | def _api_args_item(self, item):
"""Glances API RESTful implementation.
Return the JSON representation of the Glances command line arguments item
HTTP/200 if OK
HTTP/400 if item is not found
HTTP/404 if others error
"""
response.content_type = 'application/json; c... | [
"def",
"_api_args_item",
"(",
"self",
",",
"item",
")",
":",
"response",
".",
"content_type",
"=",
"'application/json; charset=utf-8'",
"if",
"item",
"not",
"in",
"self",
".",
"args",
":",
"abort",
"(",
"400",
",",
"\"Unknown argument item %s\"",
"%",
"item",
... | Glances API RESTful implementation.
Return the JSON representation of the Glances command line arguments item
HTTP/200 if OK
HTTP/400 if item is not found
HTTP/404 if others error | [
"Glances",
"API",
"RESTful",
"implementation",
"."
] | python | train | 36.904762 |
pandas-dev/pandas | pandas/core/panel.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/panel.py#L1451-L1456 | def _extract_axes_for_slice(self, axes):
"""
Return the slice dictionary for these axes.
"""
return {self._AXIS_SLICEMAP[i]: a for i, a in
zip(self._AXIS_ORDERS[self._AXIS_LEN - len(axes):], axes)} | [
"def",
"_extract_axes_for_slice",
"(",
"self",
",",
"axes",
")",
":",
"return",
"{",
"self",
".",
"_AXIS_SLICEMAP",
"[",
"i",
"]",
":",
"a",
"for",
"i",
",",
"a",
"in",
"zip",
"(",
"self",
".",
"_AXIS_ORDERS",
"[",
"self",
".",
"_AXIS_LEN",
"-",
"len... | Return the slice dictionary for these axes. | [
"Return",
"the",
"slice",
"dictionary",
"for",
"these",
"axes",
"."
] | python | train | 40 |
adamziel/python_translate | python_translate/translations.py | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/translations.py#L73-L81 | def set(self, id, translation, domain='messages'):
"""
Sets a message translation.
"""
assert isinstance(id, (str, unicode))
assert isinstance(translation, (str, unicode))
assert isinstance(domain, (str, unicode))
self.add({id: translation}, domain) | [
"def",
"set",
"(",
"self",
",",
"id",
",",
"translation",
",",
"domain",
"=",
"'messages'",
")",
":",
"assert",
"isinstance",
"(",
"id",
",",
"(",
"str",
",",
"unicode",
")",
")",
"assert",
"isinstance",
"(",
"translation",
",",
"(",
"str",
",",
"uni... | Sets a message translation. | [
"Sets",
"a",
"message",
"translation",
"."
] | python | train | 33.111111 |
pyparsing/pyparsing | examples/pymicko.py | https://github.com/pyparsing/pyparsing/blob/f0264bd8d1a548a50b3e5f7d99cfefd577942d14/examples/pymicko.py#L1030-L1040 | def lookup_id_action(self, text, loc, var):
"""Code executed after recognising an identificator in expression"""
exshared.setpos(loc, text)
if DEBUG > 0:
print("EXP_VAR:",var)
if DEBUG == 2: self.symtab.display()
if DEBUG > 2: return
var_index =... | [
"def",
"lookup_id_action",
"(",
"self",
",",
"text",
",",
"loc",
",",
"var",
")",
":",
"exshared",
".",
"setpos",
"(",
"loc",
",",
"text",
")",
"if",
"DEBUG",
">",
"0",
":",
"print",
"(",
"\"EXP_VAR:\"",
",",
"var",
")",
"if",
"DEBUG",
"==",
"2",
... | Code executed after recognising an identificator in expression | [
"Code",
"executed",
"after",
"recognising",
"an",
"identificator",
"in",
"expression"
] | python | train | 50.545455 |
Unidata/MetPy | metpy/calc/basic.py | https://github.com/Unidata/MetPy/blob/16f68a94919b9a82dcf9cada2169cf039129e67b/metpy/calc/basic.py#L393-L426 | def height_to_geopotential(height):
r"""Compute geopotential for a given height.
Parameters
----------
height : `pint.Quantity`
Height above sea level (array_like)
Returns
-------
`pint.Quantity`
The corresponding geopotential value(s)
Examples
--------
>>> fro... | [
"def",
"height_to_geopotential",
"(",
"height",
")",
":",
"# Calculate geopotential",
"geopot",
"=",
"mpconsts",
".",
"G",
"*",
"mpconsts",
".",
"me",
"*",
"(",
"(",
"1",
"/",
"mpconsts",
".",
"Re",
")",
"-",
"(",
"1",
"/",
"(",
"mpconsts",
".",
"Re",
... | r"""Compute geopotential for a given height.
Parameters
----------
height : `pint.Quantity`
Height above sea level (array_like)
Returns
-------
`pint.Quantity`
The corresponding geopotential value(s)
Examples
--------
>>> from metpy.constants import g, G, me, Re
... | [
"r",
"Compute",
"geopotential",
"for",
"a",
"given",
"height",
"."
] | python | train | 29.147059 |
saltstack/salt | salt/beacons/__init__.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/__init__.py#L194-L207 | def _update_enabled(self, name, enabled_value):
'''
Update whether an individual beacon is enabled
'''
if isinstance(self.opts['beacons'][name], dict):
# Backwards compatibility
self.opts['beacons'][name]['enabled'] = enabled_value
else:
enabl... | [
"def",
"_update_enabled",
"(",
"self",
",",
"name",
",",
"enabled_value",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"opts",
"[",
"'beacons'",
"]",
"[",
"name",
"]",
",",
"dict",
")",
":",
"# Backwards compatibility",
"self",
".",
"opts",
"[",
"'bea... | Update whether an individual beacon is enabled | [
"Update",
"whether",
"an",
"individual",
"beacon",
"is",
"enabled"
] | python | train | 42 |
Microsoft/LightGBM | python-package/lightgbm/callback.py | https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/callback.py#L108-L150 | def reset_parameter(**kwargs):
"""Create a callback that resets the parameter after the first iteration.
Note
----
The initial parameter will still take in-effect on first iteration.
Parameters
----------
**kwargs : value should be list or function
List of parameters for each boost... | [
"def",
"reset_parameter",
"(",
"*",
"*",
"kwargs",
")",
":",
"def",
"_callback",
"(",
"env",
")",
":",
"new_parameters",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"key",
"in",
"[",
"'num_class'",
... | Create a callback that resets the parameter after the first iteration.
Note
----
The initial parameter will still take in-effect on first iteration.
Parameters
----------
**kwargs : value should be list or function
List of parameters for each boosting round
or a customized func... | [
"Create",
"a",
"callback",
"that",
"resets",
"the",
"parameter",
"after",
"the",
"first",
"iteration",
"."
] | python | train | 41.023256 |
deepmipt/DeepPavlov | deeppavlov/models/morpho_tagger/network.py | https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/morpho_tagger/network.py#L234-L244 | def train_on_batch(self, data: List[Iterable], labels: Iterable[list]) -> None:
"""Trains model on a single batch
Args:
data: a batch of word sequences
labels: a batch of correct tag sequences
Returns:
the trained model
"""
X, Y = self._transf... | [
"def",
"train_on_batch",
"(",
"self",
",",
"data",
":",
"List",
"[",
"Iterable",
"]",
",",
"labels",
":",
"Iterable",
"[",
"list",
"]",
")",
"->",
"None",
":",
"X",
",",
"Y",
"=",
"self",
".",
"_transform_batch",
"(",
"data",
",",
"labels",
")",
"s... | Trains model on a single batch
Args:
data: a batch of word sequences
labels: a batch of correct tag sequences
Returns:
the trained model | [
"Trains",
"model",
"on",
"a",
"single",
"batch"
] | python | test | 34 |
bitesofcode/projexui | projexui/widgets/xtreewidget/xtreewidget.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtreewidget/xtreewidget.py#L445-L461 | def column(self, name):
"""
Returns the index of the column at the given name.
:param name | <str>
:return <int> (-1 if not found)
"""
columns = self.columns()
if name in columns:
return columns.index(name)
... | [
"def",
"column",
"(",
"self",
",",
"name",
")",
":",
"columns",
"=",
"self",
".",
"columns",
"(",
")",
"if",
"name",
"in",
"columns",
":",
"return",
"columns",
".",
"index",
"(",
"name",
")",
"else",
":",
"check",
"=",
"projex",
".",
"text",
".",
... | Returns the index of the column at the given name.
:param name | <str>
:return <int> (-1 if not found) | [
"Returns",
"the",
"index",
"of",
"the",
"column",
"at",
"the",
"given",
"name",
".",
":",
"param",
"name",
"|",
"<str",
">",
":",
"return",
"<int",
">",
"(",
"-",
"1",
"if",
"not",
"found",
")"
] | python | train | 30.588235 |
openstack/networking-cisco | networking_cisco/apps/saf/server/dfa_openstack_helper.py | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/dfa_openstack_helper.py#L215-L227 | def get_rtr_by_name(self, rtr_name):
"""Search a router by its name. """
upd_rtr_list = []
try:
rtr_list = self.neutronclient.list_routers()
for rtr in rtr_list.get('routers'):
if rtr_name == rtr['name']:
upd_rtr_list.append(rtr)
... | [
"def",
"get_rtr_by_name",
"(",
"self",
",",
"rtr_name",
")",
":",
"upd_rtr_list",
"=",
"[",
"]",
"try",
":",
"rtr_list",
"=",
"self",
".",
"neutronclient",
".",
"list_routers",
"(",
")",
"for",
"rtr",
"in",
"rtr_list",
".",
"get",
"(",
"'routers'",
")",
... | Search a router by its name. | [
"Search",
"a",
"router",
"by",
"its",
"name",
"."
] | python | train | 40.153846 |
monarch-initiative/dipper | dipper/sources/MGI.py | https://github.com/monarch-initiative/dipper/blob/24cc80db355bbe15776edc5c7b41e0886959ba41/dipper/sources/MGI.py#L1343-L1429 | def _process_mrk_marker_view(self, limit):
"""
This is the definition of markers
(as in genes, but other genomic loci types as well).
It looks up the identifiers in the hashmap
This includes their labels, specific class, and identifiers
TODO should we use the mrk_mouse_vi... | [
"def",
"_process_mrk_marker_view",
"(",
"self",
",",
"limit",
")",
":",
"if",
"self",
".",
"test_mode",
":",
"graph",
"=",
"self",
".",
"testgraph",
"else",
":",
"graph",
"=",
"self",
".",
"graph",
"model",
"=",
"Model",
"(",
"graph",
")",
"geno",
"=",... | This is the definition of markers
(as in genes, but other genomic loci types as well).
It looks up the identifiers in the hashmap
This includes their labels, specific class, and identifiers
TODO should we use the mrk_mouse_view instead?
Triples:
<marker_id> a owl:Class O... | [
"This",
"is",
"the",
"definition",
"of",
"markers",
"(",
"as",
"in",
"genes",
"but",
"other",
"genomic",
"loci",
"types",
"as",
"well",
")",
".",
"It",
"looks",
"up",
"the",
"identifiers",
"in",
"the",
"hashmap",
"This",
"includes",
"their",
"labels",
"s... | python | train | 39.724138 |
mkouhei/tonicdnscli | src/tonicdnscli/command.py | https://github.com/mkouhei/tonicdnscli/blob/df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c/src/tonicdnscli/command.py#L587-L601 | def parse_get(prs, conn):
"""Retrieve records.
Arguments:
prs: parser object of argparse
conn: dictionary of connection information
"""
prs_get = prs.add_parser(
'get', help='retrieve all zones or records with a specific zone')
prs_get.add_argument('--domain', action='stor... | [
"def",
"parse_get",
"(",
"prs",
",",
"conn",
")",
":",
"prs_get",
"=",
"prs",
".",
"add_parser",
"(",
"'get'",
",",
"help",
"=",
"'retrieve all zones or records with a specific zone'",
")",
"prs_get",
".",
"add_argument",
"(",
"'--domain'",
",",
"action",
"=",
... | Retrieve records.
Arguments:
prs: parser object of argparse
conn: dictionary of connection information | [
"Retrieve",
"records",
"."
] | python | train | 30.866667 |
theosysbio/means | src/means/inference/results.py | https://github.com/theosysbio/means/blob/fe164916a1d84ab2a4fa039871d38ccdf638b1db/src/means/inference/results.py#L399-L420 | def solutions_as_2d_trajectories(self, x_axis, y_axis):
"""
Returns the :attr:`InferenceResult.solutions` as a plottable 2d trajectory.
:param x_axis: the variable to be on the x axis of projection
:param y_axis: the variable to be on the y axis of preojection
:return: a tuple x... | [
"def",
"solutions_as_2d_trajectories",
"(",
"self",
",",
"x_axis",
",",
"y_axis",
")",
":",
"if",
"not",
"self",
".",
"solutions",
":",
"raise",
"Exception",
"(",
"'No intermediate solutions returned. '",
"'Re-run inference with return_intermediate_solutions=True'",
")",
... | Returns the :attr:`InferenceResult.solutions` as a plottable 2d trajectory.
:param x_axis: the variable to be on the x axis of projection
:param y_axis: the variable to be on the y axis of preojection
:return: a tuple x, y specifying lists of x and y coordinates of projection | [
"Returns",
"the",
":",
"attr",
":",
"InferenceResult",
".",
"solutions",
"as",
"a",
"plottable",
"2d",
"trajectory",
"."
] | python | train | 40.727273 |
tschaume/ccsgp_get_started | ccsgp_get_started/examples/gp_background.py | https://github.com/tschaume/ccsgp_get_started/blob/e4e29844a3e6fc7574e9b4b8cd84131f28ddc3f2/ccsgp_get_started/examples/gp_background.py#L201-L245 | def gp_norm(infile):
"""indentify normalization region"""
inDir, outDir = getWorkDirs()
data, titles = [], []
for eidx,energy in enumerate(['19', '27', '39', '62']):
file_url = os.path.realpath(os.path.join(
inDir, 'rawdata', energy, 'pt-integrated', infile+'.dat'
))
... | [
"def",
"gp_norm",
"(",
"infile",
")",
":",
"inDir",
",",
"outDir",
"=",
"getWorkDirs",
"(",
")",
"data",
",",
"titles",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"eidx",
",",
"energy",
"in",
"enumerate",
"(",
"[",
"'19'",
",",
"'27'",
",",
"'39'",
","... | indentify normalization region | [
"indentify",
"normalization",
"region"
] | python | train | 40.555556 |
cloudbase/python-hnvclient | hnv/common/model.py | https://github.com/cloudbase/python-hnvclient/blob/b019452af01db22629809b8930357a2ebf6494be/hnv/common/model.py#L168-L175 | def remove_field(self, field_name):
"""Remove the field with the received field name from model."""
field = self._fields.pop(field_name, None)
if field is not None and field.default is not None:
if six.callable(field.default):
self._default_callables.pop(field.key, No... | [
"def",
"remove_field",
"(",
"self",
",",
"field_name",
")",
":",
"field",
"=",
"self",
".",
"_fields",
".",
"pop",
"(",
"field_name",
",",
"None",
")",
"if",
"field",
"is",
"not",
"None",
"and",
"field",
".",
"default",
"is",
"not",
"None",
":",
"if"... | Remove the field with the received field name from model. | [
"Remove",
"the",
"field",
"with",
"the",
"received",
"field",
"name",
"from",
"model",
"."
] | python | train | 48.25 |
Microsoft/nni | examples/trials/kaggle-tgs-salt/lovasz_losses.py | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/kaggle-tgs-salt/lovasz_losses.py#L234-L252 | def mean(l, ignore_nan=False, empty=0):
"""
nanmean compatible with generators.
"""
l = iter(l)
if ignore_nan:
l = ifilterfalse(np.isnan, l)
try:
n = 1
acc = next(l)
except StopIteration:
if empty == 'raise':
raise ValueError('Empty mean')
... | [
"def",
"mean",
"(",
"l",
",",
"ignore_nan",
"=",
"False",
",",
"empty",
"=",
"0",
")",
":",
"l",
"=",
"iter",
"(",
"l",
")",
"if",
"ignore_nan",
":",
"l",
"=",
"ifilterfalse",
"(",
"np",
".",
"isnan",
",",
"l",
")",
"try",
":",
"n",
"=",
"1",... | nanmean compatible with generators. | [
"nanmean",
"compatible",
"with",
"generators",
"."
] | python | train | 21.947368 |
quora/qcore | qcore/asserts.py | https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/asserts.py#L244-L260 | def assert_not_in(obj, seq, message=None, extra=None):
"""Raises an AssertionError if obj is in iter."""
# for very long strings, provide a truncated error
if isinstance(seq, six.string_types) and obj in seq and len(seq) > 200:
index = seq.find(obj)
start_index = index - 50
if start_... | [
"def",
"assert_not_in",
"(",
"obj",
",",
"seq",
",",
"message",
"=",
"None",
",",
"extra",
"=",
"None",
")",
":",
"# for very long strings, provide a truncated error",
"if",
"isinstance",
"(",
"seq",
",",
"six",
".",
"string_types",
")",
"and",
"obj",
"in",
... | Raises an AssertionError if obj is in iter. | [
"Raises",
"an",
"AssertionError",
"if",
"obj",
"is",
"in",
"iter",
"."
] | python | train | 44.588235 |
liamw9534/bt-manager | bt_manager/codecs.py | https://github.com/liamw9534/bt-manager/blob/51be2919394ce8134c698359649bfad09eedf4ec/bt_manager/codecs.py#L183-L205 | def decode(self, fd, mtu, max_len=2560):
"""
Read the media transport descriptor, depay
the RTP payload and decode the SBC frames into
a byte array. The maximum number of bytes to
be returned may be passed as an argument and all
available bytes are returned to the caller... | [
"def",
"decode",
"(",
"self",
",",
"fd",
",",
"mtu",
",",
"max_len",
"=",
"2560",
")",
":",
"output_buffer",
"=",
"ffi",
".",
"new",
"(",
"'char[]'",
",",
"max_len",
")",
"sz",
"=",
"self",
".",
"codec",
".",
"rtp_sbc_decode_from_fd",
"(",
"self",
".... | Read the media transport descriptor, depay
the RTP payload and decode the SBC frames into
a byte array. The maximum number of bytes to
be returned may be passed as an argument and all
available bytes are returned to the caller.
:param int fd: Media transport file descriptor
... | [
"Read",
"the",
"media",
"transport",
"descriptor",
"depay",
"the",
"RTP",
"payload",
"and",
"decode",
"the",
"SBC",
"frames",
"into",
"a",
"byte",
"array",
".",
"The",
"maximum",
"number",
"of",
"bytes",
"to",
"be",
"returned",
"may",
"be",
"passed",
"as",... | python | train | 44.695652 |
numenta/nupic | src/nupic/frameworks/opf/model_factory.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/model_factory.py#L88-L99 | def loadFromCheckpoint(savedModelDir, newSerialization=False):
""" Load saved model.
:param savedModelDir: (string)
Directory of where the experiment is to be or was saved
:returns: (:class:`nupic.frameworks.opf.model.Model`) The loaded model
instance.
"""
if newSerializati... | [
"def",
"loadFromCheckpoint",
"(",
"savedModelDir",
",",
"newSerialization",
"=",
"False",
")",
":",
"if",
"newSerialization",
":",
"return",
"HTMPredictionModel",
".",
"readFromCheckpoint",
"(",
"savedModelDir",
")",
"else",
":",
"return",
"Model",
".",
"load",
"(... | Load saved model.
:param savedModelDir: (string)
Directory of where the experiment is to be or was saved
:returns: (:class:`nupic.frameworks.opf.model.Model`) The loaded model
instance. | [
"Load",
"saved",
"model",
"."
] | python | valid | 35.583333 |
Kozea/pygal | pygal/graph/graph.py | https://github.com/Kozea/pygal/blob/5e25c98a59a0642eecd9fcc5dbfeeb2190fbb5e7/pygal/graph/graph.py#L71-L140 | def _make_graph(self):
"""Init common graph svg structure"""
self.nodes['graph'] = self.svg.node(
class_='graph %s-graph %s' % (
self.__class__.__name__.lower(),
'horizontal' if self.horizontal else 'vertical'
)
)
self.svg.node(
... | [
"def",
"_make_graph",
"(",
"self",
")",
":",
"self",
".",
"nodes",
"[",
"'graph'",
"]",
"=",
"self",
".",
"svg",
".",
"node",
"(",
"class_",
"=",
"'graph %s-graph %s'",
"%",
"(",
"self",
".",
"__class__",
".",
"__name__",
".",
"lower",
"(",
")",
",",... | Init common graph svg structure | [
"Init",
"common",
"graph",
"svg",
"structure"
] | python | train | 31.557143 |
Kunstmord/datalib | src/dataset.py | https://github.com/Kunstmord/datalib/blob/9d7db3e7c3a5feeeb5d19eb0dbee858bd2b50886/src/dataset.py#L676-L702 | def extract_feature_dependent_feature(self, extractor, force_extraction=False, verbose=0, add_args=None,
custom_name=None):
"""
Extracts a feature which may be dependent on other features and stores it in the database
Parameters
----------
... | [
"def",
"extract_feature_dependent_feature",
"(",
"self",
",",
"extractor",
",",
"force_extraction",
"=",
"False",
",",
"verbose",
"=",
"0",
",",
"add_args",
"=",
"None",
",",
"custom_name",
"=",
"None",
")",
":",
"if",
"self",
".",
"_prepopulated",
"is",
"Fa... | Extracts a feature which may be dependent on other features and stores it in the database
Parameters
----------
extractor : function, which takes the path of a data point, a dictionary of all other features and *args as
parameters and returns a feature
force_extraction : boolean... | [
"Extracts",
"a",
"feature",
"which",
"may",
"be",
"dependent",
"on",
"other",
"features",
"and",
"stores",
"it",
"in",
"the",
"database"
] | python | train | 60.185185 |
CZ-NIC/yangson | yangson/schemadata.py | https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/schemadata.py#L350-L365 | def sni2route(self, sni: SchemaNodeId, sctx: SchemaContext) -> SchemaRoute:
"""Translate schema node identifier to a schema route.
Args:
sni: Schema node identifier (absolute or relative).
sctx: Schema context.
Raises:
ModuleNotRegistered: If `mid` is not re... | [
"def",
"sni2route",
"(",
"self",
",",
"sni",
":",
"SchemaNodeId",
",",
"sctx",
":",
"SchemaContext",
")",
"->",
"SchemaRoute",
":",
"nlist",
"=",
"sni",
".",
"split",
"(",
"\"/\"",
")",
"res",
"=",
"[",
"]",
"for",
"qn",
"in",
"(",
"nlist",
"[",
"1... | Translate schema node identifier to a schema route.
Args:
sni: Schema node identifier (absolute or relative).
sctx: Schema context.
Raises:
ModuleNotRegistered: If `mid` is not registered in the data model.
UnknownPrefix: If a prefix specified in `sni` i... | [
"Translate",
"schema",
"node",
"identifier",
"to",
"a",
"schema",
"route",
"."
] | python | train | 37.625 |
ihmeuw/vivarium | src/vivarium/interface/cli.py | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/interface/cli.py#L39-L63 | def run(model_specification, results_directory, verbose, log, with_debugger):
"""Run a simulation from the command line.
The simulation itself is defined by the given MODEL_SPECIFICATION yaml file.
Within the results directory, which defaults to ~/vivarium_results if none
is provided, a subdirectory w... | [
"def",
"run",
"(",
"model_specification",
",",
"results_directory",
",",
"verbose",
",",
"log",
",",
"with_debugger",
")",
":",
"log_level",
"=",
"logging",
".",
"DEBUG",
"if",
"verbose",
"else",
"logging",
".",
"ERROR",
"logging",
".",
"basicConfig",
"(",
"... | Run a simulation from the command line.
The simulation itself is defined by the given MODEL_SPECIFICATION yaml file.
Within the results directory, which defaults to ~/vivarium_results if none
is provided, a subdirectory will be created with the same name as the
MODEL_SPECIFICATION if one does not exis... | [
"Run",
"a",
"simulation",
"from",
"the",
"command",
"line",
"."
] | python | train | 39.96 |
mitsei/dlkit | dlkit/json_/logging_/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/logging_/sessions.py#L2407-L2423 | def get_parent_log_ids(self, log_id):
"""Gets the parent ``Ids`` of the given log.
arg: log_id (osid.id.Id): the ``Id`` of a log
return: (osid.id.IdList) - the parent ``Ids`` of the log
raise: NotFound - ``log_id`` is not found
raise: NullArgument - ``log_id`` is ``null``
... | [
"def",
"get_parent_log_ids",
"(",
"self",
",",
"log_id",
")",
":",
"# Implemented from template for",
"# osid.resource.BinHierarchySession.get_parent_bin_ids",
"if",
"self",
".",
"_catalog_session",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_catalog_session",
".",... | Gets the parent ``Ids`` of the given log.
arg: log_id (osid.id.Id): the ``Id`` of a log
return: (osid.id.IdList) - the parent ``Ids`` of the log
raise: NotFound - ``log_id`` is not found
raise: NullArgument - ``log_id`` is ``null``
raise: OperationFailed - unable to comple... | [
"Gets",
"the",
"parent",
"Ids",
"of",
"the",
"given",
"log",
"."
] | python | train | 46.823529 |
vadimk2016/v-vk-api | v_vk_api/session.py | https://github.com/vadimk2016/v-vk-api/blob/ef5656e09944b5319a1f573cfb7b022f3d31c0cf/v_vk_api/session.py#L108-L133 | def auth_oauth2(self) -> dict:
"""
Authorizes a user by OAuth2 to get access token
"""
oauth_data = {
'client_id': self._app_id,
'display': 'mobile',
'response_type': 'token',
'scope': '+66560',
'v': self.API_VERSION
}
... | [
"def",
"auth_oauth2",
"(",
"self",
")",
"->",
"dict",
":",
"oauth_data",
"=",
"{",
"'client_id'",
":",
"self",
".",
"_app_id",
",",
"'display'",
":",
"'mobile'",
",",
"'response_type'",
":",
"'token'",
",",
"'scope'",
":",
"'+66560'",
",",
"'v'",
":",
"s... | Authorizes a user by OAuth2 to get access token | [
"Authorizes",
"a",
"user",
"by",
"OAuth2",
"to",
"get",
"access",
"token"
] | python | train | 36 |
carpyncho/feets | feets/libs/ls_fap.py | https://github.com/carpyncho/feets/blob/53bdfb73b53845561914fc1f756e0c2377b9b76b/feets/libs/ls_fap.py#L218-L225 | def fap_baluev(Z, fmax, t, y, dy, normalization='standard'):
"""Alias-free approximation to false alarm probability
(Eqn 6 of Baluev 2008)
"""
cdf = cdf_single(Z, len(t), normalization)
tau = tau_davies(Z, fmax, t, y, dy, normalization=normalization)
return 1 - cdf * np.exp(-tau) | [
"def",
"fap_baluev",
"(",
"Z",
",",
"fmax",
",",
"t",
",",
"y",
",",
"dy",
",",
"normalization",
"=",
"'standard'",
")",
":",
"cdf",
"=",
"cdf_single",
"(",
"Z",
",",
"len",
"(",
"t",
")",
",",
"normalization",
")",
"tau",
"=",
"tau_davies",
"(",
... | Alias-free approximation to false alarm probability
(Eqn 6 of Baluev 2008) | [
"Alias",
"-",
"free",
"approximation",
"to",
"false",
"alarm",
"probability"
] | python | train | 37.25 |
Nic30/hwt | hwt/serializer/verilog/serializer.py | https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/serializer/verilog/serializer.py#L98-L121 | def Architecture_var(cls, v, serializerVars, extraTypes,
extraTypes_serialized, ctx, childCtx):
"""
:return: list of extra discovered processes
"""
t = v._dtype
# if type requires extra definition
if isinstance(t, HArray) and v.defVal.vldMask:
... | [
"def",
"Architecture_var",
"(",
"cls",
",",
"v",
",",
"serializerVars",
",",
"extraTypes",
",",
"extraTypes_serialized",
",",
"ctx",
",",
"childCtx",
")",
":",
"t",
"=",
"v",
".",
"_dtype",
"# if type requires extra definition",
"if",
"isinstance",
"(",
"t",
"... | :return: list of extra discovered processes | [
":",
"return",
":",
"list",
"of",
"extra",
"discovered",
"processes"
] | python | test | 41.916667 |
JnyJny/Geometry | Geometry/line.py | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/line.py#L198-L223 | def t(self, point):
'''
:point: Point subclass
:return: float
If :point: is collinear, determine the 't' coefficient of
the parametric equation:
xyz = A<xyz> + t ( B<xyz> - A<xyz> )
if t < 0, point is less than A and B on the line
if t >= 0 and <= 1, po... | [
"def",
"t",
"(",
"self",
",",
"point",
")",
":",
"# XXX could use for an ordering on points?",
"if",
"point",
"not",
"in",
"self",
":",
"msg",
"=",
"\"'{p}' is not collinear with '{l}'\"",
"raise",
"CollinearPoints",
"(",
"msg",
".",
"format",
"(",
"p",
"=",
"po... | :point: Point subclass
:return: float
If :point: is collinear, determine the 't' coefficient of
the parametric equation:
xyz = A<xyz> + t ( B<xyz> - A<xyz> )
if t < 0, point is less than A and B on the line
if t >= 0 and <= 1, point is between A and B
if t > 1 ... | [
":",
"point",
":",
"Point",
"subclass",
":",
"return",
":",
"float"
] | python | train | 26.923077 |
google/transitfeed | transitfeed/shapelib.py | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/shapelib.py#L128-L143 | def LargestComponent(self):
"""
Returns (i, val) where i is the component index (0 - 2)
which has largest absolute value and val is the value
of the component.
"""
if abs(self.x) > abs(self.y):
if abs(self.x) > abs(self.z):
return (0, self.x)
else:
return (2, self.z)
... | [
"def",
"LargestComponent",
"(",
"self",
")",
":",
"if",
"abs",
"(",
"self",
".",
"x",
")",
">",
"abs",
"(",
"self",
".",
"y",
")",
":",
"if",
"abs",
"(",
"self",
".",
"x",
")",
">",
"abs",
"(",
"self",
".",
"z",
")",
":",
"return",
"(",
"0"... | Returns (i, val) where i is the component index (0 - 2)
which has largest absolute value and val is the value
of the component. | [
"Returns",
"(",
"i",
"val",
")",
"where",
"i",
"is",
"the",
"component",
"index",
"(",
"0",
"-",
"2",
")",
"which",
"has",
"largest",
"absolute",
"value",
"and",
"val",
"is",
"the",
"value",
"of",
"the",
"component",
"."
] | python | train | 26 |
serge-sans-paille/pythran | pythran/utils.py | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/utils.py#L26-L43 | def path_to_attr(path):
"""
Transform path to ast.Attribute.
>>> import gast as ast
>>> path = ('__builtin__', 'my', 'constant')
>>> value = path_to_attr(path)
>>> ref = ast.Attribute(
... value=ast.Attribute(value=ast.Name(id="__builtin__",
... ... | [
"def",
"path_to_attr",
"(",
"path",
")",
":",
"return",
"reduce",
"(",
"lambda",
"hpath",
",",
"last",
":",
"ast",
".",
"Attribute",
"(",
"hpath",
",",
"last",
",",
"ast",
".",
"Load",
"(",
")",
")",
",",
"path",
"[",
"1",
":",
"]",
",",
"ast",
... | Transform path to ast.Attribute.
>>> import gast as ast
>>> path = ('__builtin__', 'my', 'constant')
>>> value = path_to_attr(path)
>>> ref = ast.Attribute(
... value=ast.Attribute(value=ast.Name(id="__builtin__",
... ctx=ast.Load(),
... ... | [
"Transform",
"path",
"to",
"ast",
".",
"Attribute",
"."
] | python | train | 38.833333 |
log2timeline/plaso | plaso/parsers/dpkg.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/parsers/dpkg.py#L167-L185 | def VerifyStructure(self, parser_mediator, line):
"""Verifies if a line from a text file is in the expected format.
Args:
parser_mediator (ParserMediator): parser mediator.
line (str): line from a text file.
Returns:
bool: True if the line is in the expected format, False if not.
"""... | [
"def",
"VerifyStructure",
"(",
"self",
",",
"parser_mediator",
",",
"line",
")",
":",
"try",
":",
"structure",
"=",
"self",
".",
"_DPKG_LOG_LINE",
".",
"parseString",
"(",
"line",
")",
"except",
"pyparsing",
".",
"ParseException",
"as",
"exception",
":",
"lo... | Verifies if a line from a text file is in the expected format.
Args:
parser_mediator (ParserMediator): parser mediator.
line (str): line from a text file.
Returns:
bool: True if the line is in the expected format, False if not. | [
"Verifies",
"if",
"a",
"line",
"from",
"a",
"text",
"file",
"is",
"in",
"the",
"expected",
"format",
"."
] | python | train | 32.526316 |
Dallinger/Dallinger | dallinger/experiment_server/experiment_server.py | https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment_server/experiment_server.py#L814-L831 | def assign_properties(thing):
"""Assign properties to an object.
When creating something via a post request (e.g. a node), you can pass the
properties of the object in the request. This function gets those values
from the request and fills in the relevant columns of the table.
"""
details = req... | [
"def",
"assign_properties",
"(",
"thing",
")",
":",
"details",
"=",
"request_parameter",
"(",
"parameter",
"=",
"\"details\"",
",",
"optional",
"=",
"True",
")",
"if",
"details",
":",
"setattr",
"(",
"thing",
",",
"\"details\"",
",",
"loads",
"(",
"details",... | Assign properties to an object.
When creating something via a post request (e.g. a node), you can pass the
properties of the object in the request. This function gets those values
from the request and fills in the relevant columns of the table. | [
"Assign",
"properties",
"to",
"an",
"object",
"."
] | python | train | 36.833333 |
django-danceschool/django-danceschool | danceschool/core/mixins.py | https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/mixins.py#L487-L490 | def get_return_page(self,prior=False):
''' This is just a wrapper for the getReturnPage helper function. '''
siteHistory = self.request.session.get('SITE_HISTORY',{})
return getReturnPage(siteHistory,prior=prior) | [
"def",
"get_return_page",
"(",
"self",
",",
"prior",
"=",
"False",
")",
":",
"siteHistory",
"=",
"self",
".",
"request",
".",
"session",
".",
"get",
"(",
"'SITE_HISTORY'",
",",
"{",
"}",
")",
"return",
"getReturnPage",
"(",
"siteHistory",
",",
"prior",
"... | This is just a wrapper for the getReturnPage helper function. | [
"This",
"is",
"just",
"a",
"wrapper",
"for",
"the",
"getReturnPage",
"helper",
"function",
"."
] | python | train | 59 |
poppy-project/pypot | pypot/vrep/remoteApiBindings/vrep.py | https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/vrep/remoteApiBindings/vrep.py#L735-L740 | def simxReadCollision(clientID, collisionObjectHandle, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
collisionState = ct.c_ubyte()
return c_ReadCollision(clientID, collisionObjectHandle, ct.byref(collisionState), operationMode), bool(co... | [
"def",
"simxReadCollision",
"(",
"clientID",
",",
"collisionObjectHandle",
",",
"operationMode",
")",
":",
"collisionState",
"=",
"ct",
".",
"c_ubyte",
"(",
")",
"return",
"c_ReadCollision",
"(",
"clientID",
",",
"collisionObjectHandle",
",",
"ct",
".",
"byref",
... | Please have a look at the function description/documentation in the V-REP user manual | [
"Please",
"have",
"a",
"look",
"at",
"the",
"function",
"description",
"/",
"documentation",
"in",
"the",
"V",
"-",
"REP",
"user",
"manual"
] | python | train | 56.166667 |
googleapis/google-cloud-python | core/google/cloud/operation.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/core/google/cloud/operation.py#L252-L266 | def poll(self):
"""Check if the operation has finished.
:rtype: bool
:returns: A boolean indicating if the current operation has completed.
:raises ValueError: if the operation
has already completed.
"""
if self.complete:
raise ValueError("Th... | [
"def",
"poll",
"(",
"self",
")",
":",
"if",
"self",
".",
"complete",
":",
"raise",
"ValueError",
"(",
"\"The operation has completed.\"",
")",
"operation_pb",
"=",
"self",
".",
"_get_operation",
"(",
")",
"self",
".",
"_update_state",
"(",
"operation_pb",
")",... | Check if the operation has finished.
:rtype: bool
:returns: A boolean indicating if the current operation has completed.
:raises ValueError: if the operation
has already completed. | [
"Check",
"if",
"the",
"operation",
"has",
"finished",
"."
] | python | train | 30.066667 |
theislab/anndata | anndata/base.py | https://github.com/theislab/anndata/blob/34f4eb63710628fbc15e7050e5efcac1d7806062/anndata/base.py#L2014-L2030 | def write_csvs(self, dirname: PathLike, skip_data: bool = True, sep: str = ','):
"""Write annotation to ``.csv`` files.
It is not possible to recover the full :class:`~anndata.AnnData` from the
output of this function. Use :meth:`~anndata.AnnData.write` for this.
Parameters
---... | [
"def",
"write_csvs",
"(",
"self",
",",
"dirname",
":",
"PathLike",
",",
"skip_data",
":",
"bool",
"=",
"True",
",",
"sep",
":",
"str",
"=",
"','",
")",
":",
"from",
".",
"readwrite",
".",
"write",
"import",
"write_csvs",
"write_csvs",
"(",
"dirname",
"... | Write annotation to ``.csv`` files.
It is not possible to recover the full :class:`~anndata.AnnData` from the
output of this function. Use :meth:`~anndata.AnnData.write` for this.
Parameters
----------
dirname
Name of directory to which to export.
skip_data
... | [
"Write",
"annotation",
"to",
".",
"csv",
"files",
"."
] | python | train | 36.058824 |
biolink/biolink-model | metamodel/generators/pythongen.py | https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/generators/pythongen.py#L233-L240 | def primary_keys_for(self, cls: ClassDefinition) -> List[SlotDefinitionName]:
""" Return all primary keys / identifiers for cls
@param cls: class to get keys for
@return: List of primary keys
"""
return [slot_name for slot_name in self.all_slots_for(cls)
if self.... | [
"def",
"primary_keys_for",
"(",
"self",
",",
"cls",
":",
"ClassDefinition",
")",
"->",
"List",
"[",
"SlotDefinitionName",
"]",
":",
"return",
"[",
"slot_name",
"for",
"slot_name",
"in",
"self",
".",
"all_slots_for",
"(",
"cls",
")",
"if",
"self",
".",
"sch... | Return all primary keys / identifiers for cls
@param cls: class to get keys for
@return: List of primary keys | [
"Return",
"all",
"primary",
"keys",
"/",
"identifiers",
"for",
"cls"
] | python | train | 49 |
lucapinello/Haystack | haystack/external.py | https://github.com/lucapinello/Haystack/blob/cc080d741f36cd77b07c0b59d08ea6a4cf0ef2f7/haystack/external.py#L654-L666 | def _print_p(self):
"""
m._print_p() -- Print probability (frequency) matrix
"""
print "# ",
for i in range(self.width):
print " %4d "%i,
print
for L in ['A', 'C', 'T', 'G']:
print "#%s "%L,
for i in range(self.width):
... | [
"def",
"_print_p",
"(",
"self",
")",
":",
"print",
"\"# \"",
",",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"width",
")",
":",
"print",
"\" %4d \"",
"%",
"i",
",",
"print",
"for",
"L",
"in",
"[",
"'A'",
",",
"'C'",
",",
"'T'",
",",
"'G'",
... | m._print_p() -- Print probability (frequency) matrix | [
"m",
".",
"_print_p",
"()",
"--",
"Print",
"probability",
"(",
"frequency",
")",
"matrix"
] | python | train | 29.307692 |
frnsys/broca | broca/knowledge/tf.py | https://github.com/frnsys/broca/blob/7236dcf54edc0a4a54a55eb93be30800910667e7/broca/knowledge/tf.py#L7-L21 | def train_tf(tokens_stream, out=None, **kwargs):
"""
Train a map of term frequencies on a list of files (parallelized).
"""
print('Counting terms...')
results = parallel(count_tf, tokens_stream, n_jobs=-1)
print('Merging...')
tf = merge(results)
if out is not None:
with open(ou... | [
"def",
"train_tf",
"(",
"tokens_stream",
",",
"out",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"print",
"(",
"'Counting terms...'",
")",
"results",
"=",
"parallel",
"(",
"count_tf",
",",
"tokens_stream",
",",
"n_jobs",
"=",
"-",
"1",
")",
"print",
... | Train a map of term frequencies on a list of files (parallelized). | [
"Train",
"a",
"map",
"of",
"term",
"frequencies",
"on",
"a",
"list",
"of",
"files",
"(",
"parallelized",
")",
"."
] | python | train | 24.2 |
hydraplatform/hydra-base | hydra_base/lib/units.py | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/units.py#L463-L476 | def delete_unit(unit_id, **kwargs):
"""
Delete a unit from the DB.
Raises and exception if the unit does not exist
"""
try:
db_unit = db.DBSession.query(Unit).filter(Unit.id==unit_id).one()
db.DBSession.delete(db_unit)
db.DBSession.flush()
return True
ex... | [
"def",
"delete_unit",
"(",
"unit_id",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"db_unit",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"Unit",
")",
".",
"filter",
"(",
"Unit",
".",
"id",
"==",
"unit_id",
")",
".",
"one",
"(",
")",
"db",
... | Delete a unit from the DB.
Raises and exception if the unit does not exist | [
"Delete",
"a",
"unit",
"from",
"the",
"DB",
".",
"Raises",
"and",
"exception",
"if",
"the",
"unit",
"does",
"not",
"exist"
] | python | train | 28.785714 |
awslabs/sockeye | sockeye/encoder.py | https://github.com/awslabs/sockeye/blob/5d64a1ee1ef3cbba17c6d1d94bc061020c43f6ab/sockeye/encoder.py#L830-L844 | def encode(self,
data: mx.sym.Symbol,
data_length: Optional[mx.sym.Symbol],
seq_len: int) -> Tuple[mx.sym.Symbol, mx.sym.Symbol, int]:
"""
Encodes data given sequence lengths of individual examples and maximum sequence length.
:param data: Input data... | [
"def",
"encode",
"(",
"self",
",",
"data",
":",
"mx",
".",
"sym",
".",
"Symbol",
",",
"data_length",
":",
"Optional",
"[",
"mx",
".",
"sym",
".",
"Symbol",
"]",
",",
"seq_len",
":",
"int",
")",
"->",
"Tuple",
"[",
"mx",
".",
"sym",
".",
"Symbol",... | Encodes data given sequence lengths of individual examples and maximum sequence length.
:param data: Input data.
:param data_length: Vector with sequence lengths.
:param seq_len: Maximum sequence length.
:return: Encoded versions of input data (data, data_length, seq_len). | [
"Encodes",
"data",
"given",
"sequence",
"lengths",
"of",
"individual",
"examples",
"and",
"maximum",
"sequence",
"length",
"."
] | python | train | 43.266667 |
GhostofGoes/getmac | getmac/getmac.py | https://github.com/GhostofGoes/getmac/blob/553846d6b8b8873ea874ea8cfb35a07ae523569a/getmac/getmac.py#L497-L536 | def _try_methods(methods, to_find=None):
# type: (list, Optional[str]) -> Optional[str]
"""Runs the methods specified by _hunt_for_mac().
We try every method and see if it returned a MAC address. If it returns
None or raises an exception, we continue and try the next method.
"""
found = None
... | [
"def",
"_try_methods",
"(",
"methods",
",",
"to_find",
"=",
"None",
")",
":",
"# type: (list, Optional[str]) -> Optional[str]",
"found",
"=",
"None",
"for",
"m",
"in",
"methods",
":",
"try",
":",
"if",
"isinstance",
"(",
"m",
",",
"tuple",
")",
":",
"for",
... | Runs the methods specified by _hunt_for_mac().
We try every method and see if it returned a MAC address. If it returns
None or raises an exception, we continue and try the next method. | [
"Runs",
"the",
"methods",
"specified",
"by",
"_hunt_for_mac",
"()",
"."
] | python | train | 39.125 |
saltstack/salt | salt/cloud/clouds/ec2.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/ec2.py#L3209-L3250 | def get_tags(name=None,
instance_id=None,
call=None,
location=None,
kwargs=None,
resource_id=None): # pylint: disable=W0613
'''
Retrieve tags for a resource. Normally a VM name or instance_id is passed
in, but a resource_id may be passed inst... | [
"def",
"get_tags",
"(",
"name",
"=",
"None",
",",
"instance_id",
"=",
"None",
",",
"call",
"=",
"None",
",",
"location",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"resource_id",
"=",
"None",
")",
":",
"# pylint: disable=W0613",
"if",
"location",
"is"... | Retrieve tags for a resource. Normally a VM name or instance_id is passed
in, but a resource_id may be passed instead. If both are passed in, the
instance_id will be used.
CLI Examples:
.. code-block:: bash
salt-cloud -a get_tags mymachine
salt-cloud -a get_tags resource_id=vol-3267ab... | [
"Retrieve",
"tags",
"for",
"a",
"resource",
".",
"Normally",
"a",
"VM",
"name",
"or",
"instance_id",
"is",
"passed",
"in",
"but",
"a",
"resource_id",
"may",
"be",
"passed",
"instead",
".",
"If",
"both",
"are",
"passed",
"in",
"the",
"instance_id",
"will",
... | python | train | 30.666667 |
mikedh/trimesh | trimesh/transformations.py | https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/transformations.py#L632-L685 | def clip_matrix(left, right, bottom, top, near, far, perspective=False):
"""Return matrix to obtain normalized device coordinates from frustum.
The frustum bounds are axis-aligned along x (left, right),
y (bottom, top) and z (near, far).
Normalized device coordinates are in range [-1, 1] if coordinate... | [
"def",
"clip_matrix",
"(",
"left",
",",
"right",
",",
"bottom",
",",
"top",
",",
"near",
",",
"far",
",",
"perspective",
"=",
"False",
")",
":",
"if",
"left",
">=",
"right",
"or",
"bottom",
">=",
"top",
"or",
"near",
">=",
"far",
":",
"raise",
"Val... | Return matrix to obtain normalized device coordinates from frustum.
The frustum bounds are axis-aligned along x (left, right),
y (bottom, top) and z (near, far).
Normalized device coordinates are in range [-1, 1] if coordinates are
inside the frustum.
If perspective is True the frustum is a trunc... | [
"Return",
"matrix",
"to",
"obtain",
"normalized",
"device",
"coordinates",
"from",
"frustum",
"."
] | python | train | 40.259259 |
joanvila/aioredlock | aioredlock/redis.py | https://github.com/joanvila/aioredlock/blob/6c62f0895c93b26b87ca8e3fe36bc024c81be421/aioredlock/redis.py#L127-L162 | async def set_lock(self, resource, lock_identifier, lock_timeout):
"""
Lock this instance and set lock expiration time to lock_timeout
:param resource: redis key to set
:param lock_identifier: uniquie id of lock
:param lock_timeout: timeout for lock in seconds
:raises: Lo... | [
"async",
"def",
"set_lock",
"(",
"self",
",",
"resource",
",",
"lock_identifier",
",",
"lock_timeout",
")",
":",
"lock_timeout_ms",
"=",
"int",
"(",
"lock_timeout",
"*",
"1000",
")",
"try",
":",
"with",
"await",
"self",
".",
"connect",
"(",
")",
"as",
"r... | Lock this instance and set lock expiration time to lock_timeout
:param resource: redis key to set
:param lock_identifier: uniquie id of lock
:param lock_timeout: timeout for lock in seconds
:raises: LockError if lock is not acquired | [
"Lock",
"this",
"instance",
"and",
"set",
"lock",
"expiration",
"time",
"to",
"lock_timeout",
":",
"param",
"resource",
":",
"redis",
"key",
"to",
"set",
":",
"param",
"lock_identifier",
":",
"uniquie",
"id",
"of",
"lock",
":",
"param",
"lock_timeout",
":",
... | python | train | 42.305556 |
odlgroup/odl | odl/discr/partition.py | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/discr/partition.py#L661-L706 | def squeeze(self, axis=None):
"""Return the partition with removed degenerate (length 1) dimensions.
Parameters
----------
axis : None or index expression, optional
Subset of the axes to squeeze. Default: All axes.
Returns
-------
squeezed : `RectPar... | [
"def",
"squeeze",
"(",
"self",
",",
"axis",
"=",
"None",
")",
":",
"if",
"axis",
"is",
"None",
":",
"rng",
"=",
"range",
"(",
"self",
".",
"ndim",
")",
"else",
":",
"rng",
"=",
"list",
"(",
"np",
".",
"atleast_1d",
"(",
"np",
".",
"arange",
"("... | Return the partition with removed degenerate (length 1) dimensions.
Parameters
----------
axis : None or index expression, optional
Subset of the axes to squeeze. Default: All axes.
Returns
-------
squeezed : `RectPartition`
Squeezed partition.
... | [
"Return",
"the",
"partition",
"with",
"removed",
"degenerate",
"(",
"length",
"1",
")",
"dimensions",
"."
] | python | train | 31.804348 |
lpantano/seqcluster | seqcluster/libs/thinkbayes.py | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L747-L761 | def MakePmfFromList(t, name=''):
"""Makes a PMF from an unsorted sequence of values.
Args:
t: sequence of numbers
name: string name for this PMF
Returns:
Pmf object
"""
hist = MakeHistFromList(t)
d = hist.GetDict()
pmf = Pmf(d, name)
pmf.Normalize()
return p... | [
"def",
"MakePmfFromList",
"(",
"t",
",",
"name",
"=",
"''",
")",
":",
"hist",
"=",
"MakeHistFromList",
"(",
"t",
")",
"d",
"=",
"hist",
".",
"GetDict",
"(",
")",
"pmf",
"=",
"Pmf",
"(",
"d",
",",
"name",
")",
"pmf",
".",
"Normalize",
"(",
")",
... | Makes a PMF from an unsorted sequence of values.
Args:
t: sequence of numbers
name: string name for this PMF
Returns:
Pmf object | [
"Makes",
"a",
"PMF",
"from",
"an",
"unsorted",
"sequence",
"of",
"values",
"."
] | python | train | 20.533333 |
bcbio/bcbio-nextgen | bcbio/pipeline/region.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/region.py#L40-L65 | def _split_by_regions(dirname, out_ext, in_key):
"""Split a BAM file data analysis into chromosomal regions.
"""
def _do_work(data):
# XXX Need to move retrieval of regions into preparation to avoid
# need for files when running in non-shared filesystems
regions = _get_parallel_regio... | [
"def",
"_split_by_regions",
"(",
"dirname",
",",
"out_ext",
",",
"in_key",
")",
":",
"def",
"_do_work",
"(",
"data",
")",
":",
"# XXX Need to move retrieval of regions into preparation to avoid",
"# need for files when running in non-shared filesystems",
"regions",
"=",
"_get... | Split a BAM file data analysis into chromosomal regions. | [
"Split",
"a",
"BAM",
"file",
"data",
"analysis",
"into",
"chromosomal",
"regions",
"."
] | python | train | 48.884615 |
benmack/eo-box | eobox/raster/rasterprocessing.py | https://github.com/benmack/eo-box/blob/a291450c766bf50ea06adcdeb5729a4aad790ed5/eobox/raster/rasterprocessing.py#L133-L146 | def ji_windows(self, ij_win): # what can be given to ij_win NOT intuitive/right name by now!!!
"""For a given specific window, i.e. an element of :attr:`windows`, get the windows of all resolutions.
Arguments:
ij_win {int} -- The index specifying the window for which to return the resoluti... | [
"def",
"ji_windows",
"(",
"self",
",",
"ij_win",
")",
":",
"# what can be given to ij_win NOT intuitive/right name by now!!!",
"ji_windows",
"=",
"{",
"}",
"transform_src",
"=",
"self",
".",
"_layer_meta",
"[",
"self",
".",
"_res_indices",
"[",
"self",
".",
"_window... | For a given specific window, i.e. an element of :attr:`windows`, get the windows of all resolutions.
Arguments:
ij_win {int} -- The index specifying the window for which to return the resolution-windows. | [
"For",
"a",
"given",
"specific",
"window",
"i",
".",
"e",
".",
"an",
"element",
"of",
":",
"attr",
":",
"windows",
"get",
"the",
"windows",
"of",
"all",
"resolutions",
"."
] | python | train | 59.714286 |
samluescher/django-media-tree | media_tree/utils/filenode.py | https://github.com/samluescher/django-media-tree/blob/3eb6345faaf57e2fbe35ca431d4d133f950f2b5f/media_tree/utils/filenode.py#L134-L177 | def get_file_link(node, use_metadata=False, include_size=False, include_extension=False, include_icon=False, href=None, extra_class='', extra=''):
"""
Returns a formatted HTML link tag to the FileNode's file, optionally including some meta information about the file.
"""
link_text = None
if use_meta... | [
"def",
"get_file_link",
"(",
"node",
",",
"use_metadata",
"=",
"False",
",",
"include_size",
"=",
"False",
",",
"include_extension",
"=",
"False",
",",
"include_icon",
"=",
"False",
",",
"href",
"=",
"None",
",",
"extra_class",
"=",
"''",
",",
"extra",
"="... | Returns a formatted HTML link tag to the FileNode's file, optionally including some meta information about the file. | [
"Returns",
"a",
"formatted",
"HTML",
"link",
"tag",
"to",
"the",
"FileNode",
"s",
"file",
"optionally",
"including",
"some",
"meta",
"information",
"about",
"the",
"file",
"."
] | python | train | 36.568182 |
fumitoh/modelx | modelx/core/base.py | https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/base.py#L854-L877 | def _update_data(self):
"""Update altfunc"""
func = self.owner.formula.func
codeobj = func.__code__
name = func.__name__ # self.cells.name # func.__name__
namespace_impl = self.owner._namespace_impl.get_updated()
namespace = namespace_impl.interfaces
selfnode ... | [
"def",
"_update_data",
"(",
"self",
")",
":",
"func",
"=",
"self",
".",
"owner",
".",
"formula",
".",
"func",
"codeobj",
"=",
"func",
".",
"__code__",
"name",
"=",
"func",
".",
"__name__",
"# self.cells.name # func.__name__",
"namespace_impl",
"=",
"self",
... | Update altfunc | [
"Update",
"altfunc"
] | python | valid | 38.458333 |
datastax/python-driver | cassandra/cqlengine/models.py | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cqlengine/models.py#L800-L810 | def delete(self):
"""
Deletes the object from the database
"""
self.__dmlquery__(self.__class__, self,
batch=self._batch,
timestamp=self._timestamp,
consistency=self.__consistency__,
t... | [
"def",
"delete",
"(",
"self",
")",
":",
"self",
".",
"__dmlquery__",
"(",
"self",
".",
"__class__",
",",
"self",
",",
"batch",
"=",
"self",
".",
"_batch",
",",
"timestamp",
"=",
"self",
".",
"_timestamp",
",",
"consistency",
"=",
"self",
".",
"__consis... | Deletes the object from the database | [
"Deletes",
"the",
"object",
"from",
"the",
"database"
] | python | train | 40.909091 |
apache/airflow | airflow/contrib/hooks/mongo_hook.py | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/mongo_hook.py#L144-L163 | def update_one(self, mongo_collection, filter_doc, update_doc,
mongo_db=None, **kwargs):
"""
Updates a single document in a mongo collection.
https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.update_one
:param mongo_colle... | [
"def",
"update_one",
"(",
"self",
",",
"mongo_collection",
",",
"filter_doc",
",",
"update_doc",
",",
"mongo_db",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"collection",
"=",
"self",
".",
"get_collection",
"(",
"mongo_collection",
",",
"mongo_db",
"=",... | Updates a single document in a mongo collection.
https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.update_one
:param mongo_collection: The name of the collection to update.
:type mongo_collection: str
:param filter_doc: A query that matches... | [
"Updates",
"a",
"single",
"document",
"in",
"a",
"mongo",
"collection",
".",
"https",
":",
"//",
"api",
".",
"mongodb",
".",
"com",
"/",
"python",
"/",
"current",
"/",
"api",
"/",
"pymongo",
"/",
"collection",
".",
"html#pymongo",
".",
"collection",
".",... | python | test | 45.1 |
trendels/rhino | rhino/http.py | https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/http.py#L31-L57 | def parse_etag_header(header):
"""Parse a header containing one or more ETags or a wildcard ('*').
Returns the string '*' or a list of ETags as (weak, etag) tuples.
`weak` is the prefix designating a weak ETag, or the empty string.
`etag` is the ETag (including quotes) with the weak prefix stripped
... | [
"def",
"parse_etag_header",
"(",
"header",
")",
":",
"m",
"=",
"etag_header_re",
".",
"match",
"(",
"header",
".",
"strip",
"(",
")",
")",
"if",
"not",
"m",
":",
"return",
"[",
"]",
"if",
"m",
".",
"group",
"(",
"1",
")",
":",
"# star",
"return",
... | Parse a header containing one or more ETags or a wildcard ('*').
Returns the string '*' or a list of ETags as (weak, etag) tuples.
`weak` is the prefix designating a weak ETag, or the empty string.
`etag` is the ETag (including quotes) with the weak prefix stripped
off. Returns an empty list if the hea... | [
"Parse",
"a",
"header",
"containing",
"one",
"or",
"more",
"ETags",
"or",
"a",
"wildcard",
"(",
"*",
")",
"."
] | python | train | 30.703704 |
planetlabs/planet-client-python | planet/scripts/util.py | https://github.com/planetlabs/planet-client-python/blob/1c62ce7d416819951dddee0c22068fef6d40b027/planet/scripts/util.py#L136-L164 | def echo_json_response(response, pretty, limit=None, ndjson=False):
'''Wrapper to echo JSON with optional 'pretty' printing. If pretty is not
provided explicity and stdout is a terminal (and not redirected or piped),
the default will be to indent and sort keys'''
indent = None
sort_keys = False
... | [
"def",
"echo_json_response",
"(",
"response",
",",
"pretty",
",",
"limit",
"=",
"None",
",",
"ndjson",
"=",
"False",
")",
":",
"indent",
"=",
"None",
"sort_keys",
"=",
"False",
"nl",
"=",
"False",
"if",
"not",
"ndjson",
"and",
"(",
"pretty",
"or",
"(",... | Wrapper to echo JSON with optional 'pretty' printing. If pretty is not
provided explicity and stdout is a terminal (and not redirected or piped),
the default will be to indent and sort keys | [
"Wrapper",
"to",
"echo",
"JSON",
"with",
"optional",
"pretty",
"printing",
".",
"If",
"pretty",
"is",
"not",
"provided",
"explicity",
"and",
"stdout",
"is",
"a",
"terminal",
"(",
"and",
"not",
"redirected",
"or",
"piped",
")",
"the",
"default",
"will",
"be... | python | train | 41.137931 |
tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L1018-L1049 | def attention_bias_batch(batch_coordinates_q,
batch_coordinates_k=None,
condition_fn=None):
"""Generate a mask to prevent the batch to attend to each others.
Args:
batch_coordinates_q: Int-like Tensor of shape [length_q, 1] containing the
coordinates of t... | [
"def",
"attention_bias_batch",
"(",
"batch_coordinates_q",
",",
"batch_coordinates_k",
"=",
"None",
",",
"condition_fn",
"=",
"None",
")",
":",
"if",
"batch_coordinates_k",
"is",
"None",
":",
"batch_coordinates_k",
"=",
"batch_coordinates_q",
"# Convert to float first bec... | Generate a mask to prevent the batch to attend to each others.
Args:
batch_coordinates_q: Int-like Tensor of shape [length_q, 1] containing the
coordinates of the batches
batch_coordinates_k: Int-like Tensor of shape [length_k, 1] containing the
coordinates of the batches. If None, do self-attent... | [
"Generate",
"a",
"mask",
"to",
"prevent",
"the",
"batch",
"to",
"attend",
"to",
"each",
"others",
"."
] | python | train | 34.5 |
majerteam/sqla_inspect | sqla_inspect/py3o.py | https://github.com/majerteam/sqla_inspect/blob/67edb5541e6a56b0a657d3774d1e19c1110cd402/sqla_inspect/py3o.py#L329-L345 | def compile_obj(self, obj):
"""
generate a context based on the given obj
:param obj: an instance of the model
"""
res = {}
for column in self.columns:
if isinstance(column['__col__'], ColumnProperty):
value = self._get_column_value(obj, colum... | [
"def",
"compile_obj",
"(",
"self",
",",
"obj",
")",
":",
"res",
"=",
"{",
"}",
"for",
"column",
"in",
"self",
".",
"columns",
":",
"if",
"isinstance",
"(",
"column",
"[",
"'__col__'",
"]",
",",
"ColumnProperty",
")",
":",
"value",
"=",
"self",
".",
... | generate a context based on the given obj
:param obj: an instance of the model | [
"generate",
"a",
"context",
"based",
"on",
"the",
"given",
"obj"
] | python | train | 29.647059 |
tchellomello/raincloudy | raincloudy/faucet.py | https://github.com/tchellomello/raincloudy/blob/1847fa913e5ba79645d51bf23637860d68c67dbf/raincloudy/faucet.py#L347-L386 | def preupdate(self, force_refresh=True):
"""Return a dict with all current options prior submitting request."""
ddata = MANUAL_OP_DATA.copy()
# force update to make sure status is accurate
if force_refresh:
self.update()
# select current controller and faucet
... | [
"def",
"preupdate",
"(",
"self",
",",
"force_refresh",
"=",
"True",
")",
":",
"ddata",
"=",
"MANUAL_OP_DATA",
".",
"copy",
"(",
")",
"# force update to make sure status is accurate",
"if",
"force_refresh",
":",
"self",
".",
"update",
"(",
")",
"# select current co... | Return a dict with all current options prior submitting request. | [
"Return",
"a",
"dict",
"with",
"all",
"current",
"options",
"prior",
"submitting",
"request",
"."
] | python | train | 39.975 |
monarch-initiative/dipper | dipper/sources/Bgee.py | https://github.com/monarch-initiative/dipper/blob/24cc80db355bbe15776edc5c7b41e0886959ba41/dipper/sources/Bgee.py#L176-L207 | def _parse_gene_anatomy(self, fh, limit):
"""
Process anat_entity files with columns:
Ensembl gene ID,gene name, anatomical entity ID,
anatomical entity name, rank score, XRefs to BTO
:param fh: filehandle
:param limit: int, limit per group
:return: None
... | [
"def",
"_parse_gene_anatomy",
"(",
"self",
",",
"fh",
",",
"limit",
")",
":",
"dataframe",
"=",
"pd",
".",
"read_csv",
"(",
"fh",
",",
"sep",
"=",
"'\\t'",
")",
"col",
"=",
"self",
".",
"files",
"[",
"'anat_entity'",
"]",
"[",
"'columns'",
"]",
"if",... | Process anat_entity files with columns:
Ensembl gene ID,gene name, anatomical entity ID,
anatomical entity name, rank score, XRefs to BTO
:param fh: filehandle
:param limit: int, limit per group
:return: None | [
"Process",
"anat_entity",
"files",
"with",
"columns",
":",
"Ensembl",
"gene",
"ID",
"gene",
"name",
"anatomical",
"entity",
"ID",
"anatomical",
"entity",
"name",
"rank",
"score",
"XRefs",
"to",
"BTO"
] | python | train | 35.71875 |
bcbio/bcbio-nextgen | bcbio/variation/vcfanno.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/vcfanno.py#L47-L66 | def _combine_files(orig_files, base_out_file, data, fill_paths=True):
"""Combine multiple input files, fixing file paths if needed.
We fill in full paths from files in the data dictionary if we're
not using basepath (old style GEMINI).
"""
orig_files = [x for x in orig_files if x and utils.file_exi... | [
"def",
"_combine_files",
"(",
"orig_files",
",",
"base_out_file",
",",
"data",
",",
"fill_paths",
"=",
"True",
")",
":",
"orig_files",
"=",
"[",
"x",
"for",
"x",
"in",
"orig_files",
"if",
"x",
"and",
"utils",
".",
"file_exists",
"(",
"x",
")",
"]",
"if... | Combine multiple input files, fixing file paths if needed.
We fill in full paths from files in the data dictionary if we're
not using basepath (old style GEMINI). | [
"Combine",
"multiple",
"input",
"files",
"fixing",
"file",
"paths",
"if",
"needed",
"."
] | python | train | 44.4 |
ThePlasmaRailgun/py-rolldice | rolldice/rolldice.py | https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L55-L64 | def safe_power(a, b):
"""
Same power of a ^ b
:param a: Number a
:param b: Number b
:return: a ^ b
"""
if abs(a) > MAX_POWER or abs(b) > MAX_POWER:
raise ValueError('Number too high!')
return a ** b | [
"def",
"safe_power",
"(",
"a",
",",
"b",
")",
":",
"if",
"abs",
"(",
"a",
")",
">",
"MAX_POWER",
"or",
"abs",
"(",
"b",
")",
">",
"MAX_POWER",
":",
"raise",
"ValueError",
"(",
"'Number too high!'",
")",
"return",
"a",
"**",
"b"
] | Same power of a ^ b
:param a: Number a
:param b: Number b
:return: a ^ b | [
"Same",
"power",
"of",
"a",
"^",
"b",
":",
"param",
"a",
":",
"Number",
"a",
":",
"param",
"b",
":",
"Number",
"b",
":",
"return",
":",
"a",
"^",
"b"
] | python | train | 22.9 |
apple/turicreate | src/unity/python/turicreate/toolkits/_feature_engineering/_autovectorizer.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_feature_engineering/_autovectorizer.py#L645-L671 | def fit_transform(self, data):
"""
Fits and transforms the SFrame `data` using a fitted model.
Parameters
----------
data : SFrame
The data to be transformed.
Returns
-------
A transformed SFrame.
Returns
-------
out... | [
"def",
"fit_transform",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_setup_from_data",
"(",
"data",
")",
"ret",
"=",
"self",
".",
"transform_chain",
".",
"fit_transform",
"(",
"data",
")",
"self",
".",
"__proxy__",
".",
"update",
"(",
"{",
"\"fitte... | Fits and transforms the SFrame `data` using a fitted model.
Parameters
----------
data : SFrame
The data to be transformed.
Returns
-------
A transformed SFrame.
Returns
-------
out: SFrame
A transformed SFrame.
... | [
"Fits",
"and",
"transforms",
"the",
"SFrame",
"data",
"using",
"a",
"fitted",
"model",
"."
] | python | train | 20.962963 |
gem/oq-engine | openquake/hazardlib/gsim/campbell_bozorgnia_2014.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/campbell_bozorgnia_2014.py#L234-L241 | def _get_hanging_wall_coeffs_rrup(self, dists):
"""
Returns the hanging wall rrup term defined in equation 13
"""
fhngrrup = np.ones(len(dists.rrup))
idx = dists.rrup > 0.0
fhngrrup[idx] = (dists.rrup[idx] - dists.rjb[idx]) / dists.rrup[idx]
return fhngrrup | [
"def",
"_get_hanging_wall_coeffs_rrup",
"(",
"self",
",",
"dists",
")",
":",
"fhngrrup",
"=",
"np",
".",
"ones",
"(",
"len",
"(",
"dists",
".",
"rrup",
")",
")",
"idx",
"=",
"dists",
".",
"rrup",
">",
"0.0",
"fhngrrup",
"[",
"idx",
"]",
"=",
"(",
"... | Returns the hanging wall rrup term defined in equation 13 | [
"Returns",
"the",
"hanging",
"wall",
"rrup",
"term",
"defined",
"in",
"equation",
"13"
] | python | train | 38.25 |
konstantint/matplotlib-venn | matplotlib_venn/_venn3.py | https://github.com/konstantint/matplotlib-venn/blob/c26796c9925bdac512edf48387452fbd1848c791/matplotlib_venn/_venn3.py#L268-L296 | def venn3_circles(subsets, normalize_to=1.0, alpha=1.0, color='black', linestyle='solid', linewidth=2.0, ax=None, **kwargs):
'''
Plots only the three circles for the corresponding Venn diagram.
Useful for debugging or enhancing the basic venn diagram.
parameters ``subsets``, ``normalize_to`` and ``ax`` ... | [
"def",
"venn3_circles",
"(",
"subsets",
",",
"normalize_to",
"=",
"1.0",
",",
"alpha",
"=",
"1.0",
",",
"color",
"=",
"'black'",
",",
"linestyle",
"=",
"'solid'",
",",
"linewidth",
"=",
"2.0",
",",
"ax",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":"... | Plots only the three circles for the corresponding Venn diagram.
Useful for debugging or enhancing the basic venn diagram.
parameters ``subsets``, ``normalize_to`` and ``ax`` are the same as in venn3()
kwargs are passed as-is to matplotlib.patches.Circle.
returns a list of three Circle patches.
... | [
"Plots",
"only",
"the",
"three",
"circles",
"for",
"the",
"corresponding",
"Venn",
"diagram",
".",
"Useful",
"for",
"debugging",
"or",
"enhancing",
"the",
"basic",
"venn",
"diagram",
".",
"parameters",
"subsets",
"normalize_to",
"and",
"ax",
"are",
"the",
"sam... | python | train | 44.793103 |
ethereum/pyethereum | ethereum/tools/_solidity.py | https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/tools/_solidity.py#L133-L194 | def solidity_names(code): # pylint: disable=too-many-branches
""" Return the library and contract names in order of appearence. """
names = []
in_string = None
backslash = False
comment = None
# "parse" the code by hand to handle the corner cases:
# - the contract or library can be inside... | [
"def",
"solidity_names",
"(",
"code",
")",
":",
"# pylint: disable=too-many-branches",
"names",
"=",
"[",
"]",
"in_string",
"=",
"None",
"backslash",
"=",
"False",
"comment",
"=",
"None",
"# \"parse\" the code by hand to handle the corner cases:",
"# - the contract or libr... | Return the library and contract names in order of appearence. | [
"Return",
"the",
"library",
"and",
"contract",
"names",
"in",
"order",
"of",
"appearence",
"."
] | python | train | 33.33871 |
pymupdf/PyMuPDF | fitz/fitz.py | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L171-L175 | def preTranslate(self, tx, ty):
"""Calculate pre translation and replace current matrix."""
self.e += tx * self.a + ty * self.c
self.f += tx * self.b + ty * self.d
return self | [
"def",
"preTranslate",
"(",
"self",
",",
"tx",
",",
"ty",
")",
":",
"self",
".",
"e",
"+=",
"tx",
"*",
"self",
".",
"a",
"+",
"ty",
"*",
"self",
".",
"c",
"self",
".",
"f",
"+=",
"tx",
"*",
"self",
".",
"b",
"+",
"ty",
"*",
"self",
".",
"... | Calculate pre translation and replace current matrix. | [
"Calculate",
"pre",
"translation",
"and",
"replace",
"current",
"matrix",
"."
] | python | train | 40.6 |
isogeo/isogeo-api-py-minsdk | isogeo_pysdk/isogeo_sdk.py | https://github.com/isogeo/isogeo-api-py-minsdk/blob/57a604be92c7767b26abd247012cc1a584b386a0/isogeo_pysdk/isogeo_sdk.py#L593-L620 | def license(self, license_id: str, token: dict = None, prot: str = "https") -> dict:
"""Get details about a specific license.
:param str token: API auth token
:param str license_id: license UUID
:param str prot: https [DEFAULT] or http
(use it only for dev and tracking needs).
... | [
"def",
"license",
"(",
"self",
",",
"license_id",
":",
"str",
",",
"token",
":",
"dict",
"=",
"None",
",",
"prot",
":",
"str",
"=",
"\"https\"",
")",
"->",
"dict",
":",
"# handling request parameters",
"payload",
"=",
"{",
"\"lid\"",
":",
"license_id",
"... | Get details about a specific license.
:param str token: API auth token
:param str license_id: license UUID
:param str prot: https [DEFAULT] or http
(use it only for dev and tracking needs). | [
"Get",
"details",
"about",
"a",
"specific",
"license",
"."
] | python | train | 30.428571 |
systemd/python-systemd | systemd/journal.py | https://github.com/systemd/python-systemd/blob/c06c5d401d60ae9175367be0797a6c2b562ac5ba/systemd/journal.py#L295-L306 | def wait(self, timeout=None):
"""Wait for a change in the journal.
`timeout` is the maximum time in seconds to wait, or None which
means to wait forever.
Returns one of NOP (no change), APPEND (new entries have been added to
the end of the journal), or INVALIDATE (journal files... | [
"def",
"wait",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"us",
"=",
"-",
"1",
"if",
"timeout",
"is",
"None",
"else",
"int",
"(",
"timeout",
"*",
"1000000",
")",
"return",
"super",
"(",
"Reader",
",",
"self",
")",
".",
"wait",
"(",
"us",... | Wait for a change in the journal.
`timeout` is the maximum time in seconds to wait, or None which
means to wait forever.
Returns one of NOP (no change), APPEND (new entries have been added to
the end of the journal), or INVALIDATE (journal files have been added or
removed). | [
"Wait",
"for",
"a",
"change",
"in",
"the",
"journal",
"."
] | python | train | 38.75 |
pypa/setuptools | pkg_resources/__init__.py | https://github.com/pypa/setuptools/blob/83c667e0b2a98193851c07115d1af65011ed0fb6/pkg_resources/__init__.py#L2739-L2754 | def _get_metadata_path_for_display(self, name):
"""
Return the path to the given metadata file, if available.
"""
try:
# We need to access _get_metadata_path() on the provider object
# directly rather than through this class's __getattr__()
# since _ge... | [
"def",
"_get_metadata_path_for_display",
"(",
"self",
",",
"name",
")",
":",
"try",
":",
"# We need to access _get_metadata_path() on the provider object",
"# directly rather than through this class's __getattr__()",
"# since _get_metadata_path() is marked private.",
"path",
"=",
"self... | Return the path to the given metadata file, if available. | [
"Return",
"the",
"path",
"to",
"the",
"given",
"metadata",
"file",
"if",
"available",
"."
] | python | train | 38.375 |
LeonardMH/namealizer | namealizer/namealizer.py | https://github.com/LeonardMH/namealizer/blob/ef09492fb4565b692fda329dc02b8c4364f1cc0a/namealizer/namealizer.py#L257-L288 | def create_parser():
"""Creates the Namespace object to be used by the rest of the tool"""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-d', '--dictionary',
nargs='?',
default='dictionaries/all_en_US.dict',
... | [
"def",
"create_parser",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"__doc__",
")",
"parser",
".",
"add_argument",
"(",
"'-d'",
",",
"'--dictionary'",
",",
"nargs",
"=",
"'?'",
",",
"default",
"=",
"'dictionaries... | Creates the Namespace object to be used by the rest of the tool | [
"Creates",
"the",
"Namespace",
"object",
"to",
"be",
"used",
"by",
"the",
"rest",
"of",
"the",
"tool"
] | python | train | 46.4375 |
ioam/lancet | lancet/core.py | https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/core.py#L907-L918 | def load(self, val, **kwargs):
"""
Load the file contents into the supplied pandas dataframe or
HoloViews Table. This allows a selection to be made over the
metadata before loading the file contents (may be slow).
"""
if Table and isinstance(val, Table):
retur... | [
"def",
"load",
"(",
"self",
",",
"val",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"Table",
"and",
"isinstance",
"(",
"val",
",",
"Table",
")",
":",
"return",
"self",
".",
"load_table",
"(",
"val",
",",
"*",
"*",
"kwargs",
")",
"elif",
"DataFrame",
... | Load the file contents into the supplied pandas dataframe or
HoloViews Table. This allows a selection to be made over the
metadata before loading the file contents (may be slow). | [
"Load",
"the",
"file",
"contents",
"into",
"the",
"supplied",
"pandas",
"dataframe",
"or",
"HoloViews",
"Table",
".",
"This",
"allows",
"a",
"selection",
"to",
"be",
"made",
"over",
"the",
"metadata",
"before",
"loading",
"the",
"file",
"contents",
"(",
"may... | python | valid | 44.833333 |
neurosynth/neurosynth | neurosynth/analysis/decode.py | https://github.com/neurosynth/neurosynth/blob/948ce7edce15d7df693446e76834e0c23bfe8f11/neurosynth/analysis/decode.py#L221-L238 | def _roi_association(self, imgs_to_decode, value='z', binarize=None):
""" Computes the strength of association between activation in a mask
and presence/absence of a semantic feature. This is essentially a
generalization of the voxel-wise reverse inference z-score to the
multivoxel case.... | [
"def",
"_roi_association",
"(",
"self",
",",
"imgs_to_decode",
",",
"value",
"=",
"'z'",
",",
"binarize",
"=",
"None",
")",
":",
"imgs_to_decode",
"=",
"imgs_to_decode",
".",
"squeeze",
"(",
")",
"x",
"=",
"average_within_regions",
"(",
"self",
".",
"dataset... | Computes the strength of association between activation in a mask
and presence/absence of a semantic feature. This is essentially a
generalization of the voxel-wise reverse inference z-score to the
multivoxel case. | [
"Computes",
"the",
"strength",
"of",
"association",
"between",
"activation",
"in",
"a",
"mask",
"and",
"presence",
"/",
"absence",
"of",
"a",
"semantic",
"feature",
".",
"This",
"is",
"essentially",
"a",
"generalization",
"of",
"the",
"voxel",
"-",
"wise",
"... | python | test | 44.222222 |
daviddrysdale/python-phonenumbers | python/phonenumbers/shortnumberinfo.py | https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/shortnumberinfo.py#L137-L156 | def is_valid_short_number(numobj):
"""Tests whether a short number matches a valid pattern.
If a country calling code is shared by multiple regions, this returns True
if it's valid in any of them. Note that this doesn't verify the number is
actually in use, which is impossible to tell by just looking a... | [
"def",
"is_valid_short_number",
"(",
"numobj",
")",
":",
"region_codes",
"=",
"region_codes_for_country_code",
"(",
"numobj",
".",
"country_code",
")",
"region_code",
"=",
"_region_code_for_short_number_from_region_list",
"(",
"numobj",
",",
"region_codes",
")",
"if",
"... | Tests whether a short number matches a valid pattern.
If a country calling code is shared by multiple regions, this returns True
if it's valid in any of them. Note that this doesn't verify the number is
actually in use, which is impossible to tell by just looking at the number
itself. See is_valid_shor... | [
"Tests",
"whether",
"a",
"short",
"number",
"matches",
"a",
"valid",
"pattern",
"."
] | python | train | 50.45 |
kurtbrose/faststat | faststat/faststat.py | https://github.com/kurtbrose/faststat/blob/5060c0e10acaafd4a48de3f16869bfccc1deb44a/faststat/faststat.py#L133-L143 | def lag_avgs(self):
'''
same data as expo_avgs, but with keys as the average age
of the data -- assuming evenly spaced data points -- rather
than decay rates
'''
if not self.interval:
return
interval = self.interval.mean
return dict([(... | [
"def",
"lag_avgs",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"interval",
":",
"return",
"interval",
"=",
"self",
".",
"interval",
".",
"mean",
"return",
"dict",
"(",
"[",
"(",
"interval",
"/",
"alpha",
",",
"val",
")",
"for",
"alpha",
",",
"... | same data as expo_avgs, but with keys as the average age
of the data -- assuming evenly spaced data points -- rather
than decay rates | [
"same",
"data",
"as",
"expo_avgs",
"but",
"with",
"keys",
"as",
"the",
"average",
"age",
"of",
"the",
"data",
"--",
"assuming",
"evenly",
"spaced",
"data",
"points",
"--",
"rather",
"than",
"decay",
"rates"
] | python | train | 35.727273 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.