repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
openid/JWTConnect-Python-CryptoJWT | src/cryptojwt/jwe/jwe_ec.py | https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwe/jwe_ec.py#L181-L214 | def encrypt(self, key=None, iv="", cek="", **kwargs):
"""
Produces a JWE as defined in RFC7516 using an Elliptic curve key
:param key: *Not used>, only there to present the same API as
JWE_RSA and JWE_SYM
:param iv: Initialization vector
:param cek: Content master ke... | [
"def",
"encrypt",
"(",
"self",
",",
"key",
"=",
"None",
",",
"iv",
"=",
"\"\"",
",",
"cek",
"=",
"\"\"",
",",
"*",
"*",
"kwargs",
")",
":",
"_msg",
"=",
"as_bytes",
"(",
"self",
".",
"msg",
")",
"_args",
"=",
"self",
".",
"_dict",
"try",
":",
... | Produces a JWE as defined in RFC7516 using an Elliptic curve key
:param key: *Not used>, only there to present the same API as
JWE_RSA and JWE_SYM
:param iv: Initialization vector
:param cek: Content master key
:param kwargs: Extra keyword arguments
:return: An encry... | [
"Produces",
"a",
"JWE",
"as",
"defined",
"in",
"RFC7516",
"using",
"an",
"Elliptic",
"curve",
"key"
] | python | train |
kubernetes-client/python | kubernetes/client/apis/apps_v1_api.py | https://github.com/kubernetes-client/python/blob/5e512ff564c244c50cab780d821542ed56aa965a/kubernetes/client/apis/apps_v1_api.py#L869-L896 | def delete_collection_namespaced_deployment(self, namespace, **kwargs):
"""
delete collection of Deployment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_collection_namespaced_depl... | [
"def",
"delete_collection_namespaced_deployment",
"(",
"self",
",",
"namespace",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
... | delete collection of Deployment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_collection_namespaced_deployment(namespace, async_req=True)
>>> result = thread.get()
:param async_re... | [
"delete",
"collection",
"of",
"Deployment",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"pass",
"async_req",
"=",
"True",
">>>",
"thread",
"=",
"api",
... | python | train |
echinopsii/net.echinopsii.ariane.community.cli.python3 | ariane_clip3/directory.py | https://github.com/echinopsii/net.echinopsii.ariane.community.cli.python3/blob/0a7feddebf66fee4bef38d64f456d93a7e9fcd68/ariane_clip3/directory.py#L3512-L3523 | def json_2_company(json_obj):
"""
transform JSON obj coming from Ariane to ariane_clip3 object
:param json_obj: the JSON obj coming from Ariane
:return: ariane_clip3 Company object
"""
LOGGER.debug("Company.json_2_company")
return Company(cmpid=json_obj['companyID... | [
"def",
"json_2_company",
"(",
"json_obj",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"Company.json_2_company\"",
")",
"return",
"Company",
"(",
"cmpid",
"=",
"json_obj",
"[",
"'companyID'",
"]",
",",
"name",
"=",
"json_obj",
"[",
"'companyName'",
"]",
",",
"de... | transform JSON obj coming from Ariane to ariane_clip3 object
:param json_obj: the JSON obj coming from Ariane
:return: ariane_clip3 Company object | [
"transform",
"JSON",
"obj",
"coming",
"from",
"Ariane",
"to",
"ariane_clip3",
"object",
":",
"param",
"json_obj",
":",
"the",
"JSON",
"obj",
"coming",
"from",
"Ariane",
":",
"return",
":",
"ariane_clip3",
"Company",
"object"
] | python | train |
django-fluent/django-fluent-blogs | fluent_blogs/managers.py | https://github.com/django-fluent/django-fluent-blogs/blob/86b148549a010eaca9a2ea987fe43be250e06c50/fluent_blogs/managers.py#L48-L56 | def authors(self, *usernames):
"""
Return the entries written by the given usernames
When multiple tags are provided, they operate as "OR" query.
"""
if len(usernames) == 1:
return self.filter(**{"author__{}".format(User.USERNAME_FIELD): usernames[0]})
else:
... | [
"def",
"authors",
"(",
"self",
",",
"*",
"usernames",
")",
":",
"if",
"len",
"(",
"usernames",
")",
"==",
"1",
":",
"return",
"self",
".",
"filter",
"(",
"*",
"*",
"{",
"\"author__{}\"",
".",
"format",
"(",
"User",
".",
"USERNAME_FIELD",
")",
":",
... | Return the entries written by the given usernames
When multiple tags are provided, they operate as "OR" query. | [
"Return",
"the",
"entries",
"written",
"by",
"the",
"given",
"usernames",
"When",
"multiple",
"tags",
"are",
"provided",
"they",
"operate",
"as",
"OR",
"query",
"."
] | python | train |
ultrabug/py3status | py3status/modules/group.py | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/group.py#L152-L160 | def _urgent_function(self, module_list):
"""
A contained module has become urgent.
We want to display it to the user.
"""
for module in module_list:
if module in self.items:
self.active = self.items.index(module)
self.urgent = True | [
"def",
"_urgent_function",
"(",
"self",
",",
"module_list",
")",
":",
"for",
"module",
"in",
"module_list",
":",
"if",
"module",
"in",
"self",
".",
"items",
":",
"self",
".",
"active",
"=",
"self",
".",
"items",
".",
"index",
"(",
"module",
")",
"self"... | A contained module has become urgent.
We want to display it to the user. | [
"A",
"contained",
"module",
"has",
"become",
"urgent",
".",
"We",
"want",
"to",
"display",
"it",
"to",
"the",
"user",
"."
] | python | train |
UCL-INGI/INGInious | inginious/client/client_sync.py | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/client/client_sync.py#L16-L34 | def new_job(self, task, inputdata, launcher_name="Unknown", debug=False):
"""
Runs a new job.
It works exactly like the Client class, instead that there is no callback and directly returns result, in the form of a tuple
(result, grade, problems, tests, custom, archive).
... | [
"def",
"new_job",
"(",
"self",
",",
"task",
",",
"inputdata",
",",
"launcher_name",
"=",
"\"Unknown\"",
",",
"debug",
"=",
"False",
")",
":",
"job_semaphore",
"=",
"threading",
".",
"Semaphore",
"(",
"0",
")",
"def",
"manage_output",
"(",
"result",
",",
... | Runs a new job.
It works exactly like the Client class, instead that there is no callback and directly returns result, in the form of a tuple
(result, grade, problems, tests, custom, archive). | [
"Runs",
"a",
"new",
"job",
".",
"It",
"works",
"exactly",
"like",
"the",
"Client",
"class",
"instead",
"that",
"there",
"is",
"no",
"callback",
"and",
"directly",
"returns",
"result",
"in",
"the",
"form",
"of",
"a",
"tuple",
"(",
"result",
"grade",
"prob... | python | train |
EntilZha/PyFunctional | functional/transformations.py | https://github.com/EntilZha/PyFunctional/blob/ac04e4a8552b0c464a7f492f7c9862424867b63e/functional/transformations.py#L23-L32 | def name(function):
"""
Retrieve a pretty name for the function
:param function: function to get name from
:return: pretty name
"""
if isinstance(function, types.FunctionType):
return function.__name__
else:
return str(function) | [
"def",
"name",
"(",
"function",
")",
":",
"if",
"isinstance",
"(",
"function",
",",
"types",
".",
"FunctionType",
")",
":",
"return",
"function",
".",
"__name__",
"else",
":",
"return",
"str",
"(",
"function",
")"
] | Retrieve a pretty name for the function
:param function: function to get name from
:return: pretty name | [
"Retrieve",
"a",
"pretty",
"name",
"for",
"the",
"function",
":",
"param",
"function",
":",
"function",
"to",
"get",
"name",
"from",
":",
"return",
":",
"pretty",
"name"
] | python | train |
mathiasertl/django-ca | ca/django_ca/utils.py | https://github.com/mathiasertl/django-ca/blob/976d7ea05276320f20daed2a6d59c8f5660fe976/ca/django_ca/utils.py#L304-L317 | def x509_name(name):
"""Parses a subject into a :py:class:`x509.Name <cg:cryptography.x509.Name>`.
If ``name`` is a string, :py:func:`parse_name` is used to parse it.
>>> x509_name('/C=AT/CN=example.com')
<Name(C=AT,CN=example.com)>
>>> x509_name([('C', 'AT'), ('CN', 'example.com')])
<Name(C=A... | [
"def",
"x509_name",
"(",
"name",
")",
":",
"if",
"isinstance",
"(",
"name",
",",
"six",
".",
"string_types",
")",
":",
"name",
"=",
"parse_name",
"(",
"name",
")",
"return",
"x509",
".",
"Name",
"(",
"[",
"x509",
".",
"NameAttribute",
"(",
"NAME_OID_MA... | Parses a subject into a :py:class:`x509.Name <cg:cryptography.x509.Name>`.
If ``name`` is a string, :py:func:`parse_name` is used to parse it.
>>> x509_name('/C=AT/CN=example.com')
<Name(C=AT,CN=example.com)>
>>> x509_name([('C', 'AT'), ('CN', 'example.com')])
<Name(C=AT,CN=example.com)> | [
"Parses",
"a",
"subject",
"into",
"a",
":",
"py",
":",
"class",
":",
"x509",
".",
"Name",
"<cg",
":",
"cryptography",
".",
"x509",
".",
"Name",
">",
"."
] | python | train |
lmcinnes/umap | umap/utils.py | https://github.com/lmcinnes/umap/blob/bbb01c03ba49f7bff8f77fd662d00e50d6686c77/umap/utils.py#L326-L366 | def deheap_sort(heap):
"""Given an array of heaps (of indices and weights), unpack the heap
out to give and array of sorted lists of indices and weights by increasing
weight. This is effectively just the second half of heap sort (the first
half not being required since we already have the data in a heap... | [
"def",
"deheap_sort",
"(",
"heap",
")",
":",
"indices",
"=",
"heap",
"[",
"0",
"]",
"weights",
"=",
"heap",
"[",
"1",
"]",
"for",
"i",
"in",
"range",
"(",
"indices",
".",
"shape",
"[",
"0",
"]",
")",
":",
"ind_heap",
"=",
"indices",
"[",
"i",
"... | Given an array of heaps (of indices and weights), unpack the heap
out to give and array of sorted lists of indices and weights by increasing
weight. This is effectively just the second half of heap sort (the first
half not being required since we already have the data in a heap).
Parameters
-------... | [
"Given",
"an",
"array",
"of",
"heaps",
"(",
"of",
"indices",
"and",
"weights",
")",
"unpack",
"the",
"heap",
"out",
"to",
"give",
"and",
"array",
"of",
"sorted",
"lists",
"of",
"indices",
"and",
"weights",
"by",
"increasing",
"weight",
".",
"This",
"is",... | python | train |
roamanalytics/mittens | mittens/tf_mittens.py | https://github.com/roamanalytics/mittens/blob/dbf0c3f8d18651475cf7e21ab1ceb824c5f89150/mittens/tf_mittens.py#L156-L177 | def _get_cost_function(self):
"""Compute the cost of the Mittens objective function.
If self.mittens = 0, this is the same as the cost of GloVe.
"""
self.weights = tf.placeholder(
tf.float32, shape=[self.n_words, self.n_words])
self.log_coincidence = tf.placeholder(
... | [
"def",
"_get_cost_function",
"(",
"self",
")",
":",
"self",
".",
"weights",
"=",
"tf",
".",
"placeholder",
"(",
"tf",
".",
"float32",
",",
"shape",
"=",
"[",
"self",
".",
"n_words",
",",
"self",
".",
"n_words",
"]",
")",
"self",
".",
"log_coincidence",... | Compute the cost of the Mittens objective function.
If self.mittens = 0, this is the same as the cost of GloVe. | [
"Compute",
"the",
"cost",
"of",
"the",
"Mittens",
"objective",
"function",
"."
] | python | train |
tensorflow/cleverhans | cleverhans/attacks/spsa.py | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/spsa.py#L444-L473 | def margin_logit_loss(model_logits, label, nb_classes=10, num_classes=None):
"""Computes difference between logit for `label` and next highest logit.
The loss is high when `label` is unlikely (targeted by default).
This follows the same interface as `loss_fn` for TensorOptimizer and
projected_optimization, i.e... | [
"def",
"margin_logit_loss",
"(",
"model_logits",
",",
"label",
",",
"nb_classes",
"=",
"10",
",",
"num_classes",
"=",
"None",
")",
":",
"if",
"num_classes",
"is",
"not",
"None",
":",
"warnings",
".",
"warn",
"(",
"\"`num_classes` is depreciated. Switch to `nb_clas... | Computes difference between logit for `label` and next highest logit.
The loss is high when `label` is unlikely (targeted by default).
This follows the same interface as `loss_fn` for TensorOptimizer and
projected_optimization, i.e. it returns a batch of loss values. | [
"Computes",
"difference",
"between",
"logit",
"for",
"label",
"and",
"next",
"highest",
"logit",
"."
] | python | train |
notifiers/notifiers | notifiers_cli/utils/dynamic_click.py | https://github.com/notifiers/notifiers/blob/6dd8aafff86935dbb4763db9c56f9cdd7fc08b65/notifiers_cli/utils/dynamic_click.py#L148-L161 | def schema_to_command(
p, name: str, callback: callable, add_message: bool
) -> click.Command:
"""
Generates a ``notify`` :class:`click.Command` for :class:`~notifiers.core.Provider`
:param p: Relevant Provider
:param name: Command name
:return: A ``notify`` :class:`click.Command`
"""
p... | [
"def",
"schema_to_command",
"(",
"p",
",",
"name",
":",
"str",
",",
"callback",
":",
"callable",
",",
"add_message",
":",
"bool",
")",
"->",
"click",
".",
"Command",
":",
"params",
"=",
"params_factory",
"(",
"p",
".",
"schema",
"[",
"\"properties\"",
"]... | Generates a ``notify`` :class:`click.Command` for :class:`~notifiers.core.Provider`
:param p: Relevant Provider
:param name: Command name
:return: A ``notify`` :class:`click.Command` | [
"Generates",
"a",
"notify",
":",
"class",
":",
"click",
".",
"Command",
"for",
":",
"class",
":",
"~notifiers",
".",
"core",
".",
"Provider"
] | python | train |
twoolie/NBT | nbt/region.py | https://github.com/twoolie/NBT/blob/b06dd6cc8117d2788da1d8416e642d58bad45762/nbt/region.py#L517-L583 | def get_blockdata(self, x, z):
"""
Return the decompressed binary data representing a chunk.
May raise a RegionFileFormatError().
If decompression of the data succeeds, all available data is returned,
even if it is shorter than what is specified in the header (e.g. in c... | [
"def",
"get_blockdata",
"(",
"self",
",",
"x",
",",
"z",
")",
":",
"# read metadata block",
"m",
"=",
"self",
".",
"metadata",
"[",
"x",
",",
"z",
"]",
"if",
"m",
".",
"status",
"==",
"STATUS_CHUNK_NOT_CREATED",
":",
"raise",
"InconceivedChunk",
"(",
"\"... | Return the decompressed binary data representing a chunk.
May raise a RegionFileFormatError().
If decompression of the data succeeds, all available data is returned,
even if it is shorter than what is specified in the header (e.g. in case
of a truncated while and non-compressed... | [
"Return",
"the",
"decompressed",
"binary",
"data",
"representing",
"a",
"chunk",
".",
"May",
"raise",
"a",
"RegionFileFormatError",
"()",
".",
"If",
"decompression",
"of",
"the",
"data",
"succeeds",
"all",
"available",
"data",
"is",
"returned",
"even",
"if",
"... | python | train |
secynic/ipwhois | ipwhois/scripts/ipwhois_cli.py | https://github.com/secynic/ipwhois/blob/b5d634d36b0b942d538d38d77b3bdcd815f155a0/ipwhois/scripts/ipwhois_cli.py#L448-L487 | def generate_output_asn(self, json_data=None, hr=True, show_name=False,
colorize=True):
"""
The function for generating CLI output ASN results.
Args:
json_data (:obj:`dict`): The data to process. Defaults to None.
hr (:obj:`bool`): Enable huma... | [
"def",
"generate_output_asn",
"(",
"self",
",",
"json_data",
"=",
"None",
",",
"hr",
"=",
"True",
",",
"show_name",
"=",
"False",
",",
"colorize",
"=",
"True",
")",
":",
"if",
"json_data",
"is",
"None",
":",
"json_data",
"=",
"{",
"}",
"keys",
"=",
"... | The function for generating CLI output ASN results.
Args:
json_data (:obj:`dict`): The data to process. Defaults to None.
hr (:obj:`bool`): Enable human readable key translations. Defaults
to True.
show_name (:obj:`bool`): Show human readable name (default is... | [
"The",
"function",
"for",
"generating",
"CLI",
"output",
"ASN",
"results",
"."
] | python | train |
tehmaze/natural | natural/bank.py | https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/bank.py#L21-L34 | def bban_base10(number):
'''
Printable Basic Bank Account Number in base-10.
:param number: string
>>> bban_base10('01234567')
'45670123'
>>> bban_base10('ABCD')
'10111213'
'''
number = bban_compact(number)
number = number[4:] + number[:4]
return ''.join([str(IBAN_ALPHABET.... | [
"def",
"bban_base10",
"(",
"number",
")",
":",
"number",
"=",
"bban_compact",
"(",
"number",
")",
"number",
"=",
"number",
"[",
"4",
":",
"]",
"+",
"number",
"[",
":",
"4",
"]",
"return",
"''",
".",
"join",
"(",
"[",
"str",
"(",
"IBAN_ALPHABET",
".... | Printable Basic Bank Account Number in base-10.
:param number: string
>>> bban_base10('01234567')
'45670123'
>>> bban_base10('ABCD')
'10111213' | [
"Printable",
"Basic",
"Bank",
"Account",
"Number",
"in",
"base",
"-",
"10",
"."
] | python | train |
bcbio/bcbio-nextgen | bcbio/structural/__init__.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/__init__.py#L64-L85 | def _handle_multiple_svcallers(data, stage):
"""Retrieve configured structural variation caller, handling multiple.
"""
svs = get_svcallers(data)
# special cases -- prioritization
if stage == "ensemble" and dd.get_svprioritize(data):
svs.append("prioritize")
out = []
for svcaller in ... | [
"def",
"_handle_multiple_svcallers",
"(",
"data",
",",
"stage",
")",
":",
"svs",
"=",
"get_svcallers",
"(",
"data",
")",
"# special cases -- prioritization",
"if",
"stage",
"==",
"\"ensemble\"",
"and",
"dd",
".",
"get_svprioritize",
"(",
"data",
")",
":",
"svs",... | Retrieve configured structural variation caller, handling multiple. | [
"Retrieve",
"configured",
"structural",
"variation",
"caller",
"handling",
"multiple",
"."
] | python | train |
hasgeek/coaster | coaster/manage.py | https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/manage.py#L54-L75 | def set_alembic_revision(path=None):
"""Create/Update alembic table to latest revision number"""
config = Config()
try:
config.set_main_option("script_location", path or "migrations")
script = ScriptDirectory.from_config(config)
head = script.get_current_head()
# create alemb... | [
"def",
"set_alembic_revision",
"(",
"path",
"=",
"None",
")",
":",
"config",
"=",
"Config",
"(",
")",
"try",
":",
"config",
".",
"set_main_option",
"(",
"\"script_location\"",
",",
"path",
"or",
"\"migrations\"",
")",
"script",
"=",
"ScriptDirectory",
".",
"... | Create/Update alembic table to latest revision number | [
"Create",
"/",
"Update",
"alembic",
"table",
"to",
"latest",
"revision",
"number"
] | python | train |
openstack/horizon | openstack_auth/utils.py | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/utils.py#L75-L101 | def is_token_valid(token, margin=None):
"""Timezone-aware checking of the auth token's expiration timestamp.
Returns ``True`` if the token has not yet expired, otherwise ``False``.
:param token: The openstack_auth.user.Token instance to check
:param margin:
A time margin in seconds to subtract... | [
"def",
"is_token_valid",
"(",
"token",
",",
"margin",
"=",
"None",
")",
":",
"expiration",
"=",
"token",
".",
"expires",
"# In case we get an unparseable expiration timestamp, return False",
"# so you can't have a \"forever\" token just by breaking the expires param.",
"if",
"exp... | Timezone-aware checking of the auth token's expiration timestamp.
Returns ``True`` if the token has not yet expired, otherwise ``False``.
:param token: The openstack_auth.user.Token instance to check
:param margin:
A time margin in seconds to subtract from the real token's validity.
An exam... | [
"Timezone",
"-",
"aware",
"checking",
"of",
"the",
"auth",
"token",
"s",
"expiration",
"timestamp",
"."
] | python | train |
StackStorm/pybind | pybind/slxos/v17s_1_02/isis_state/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/isis_state/__init__.py#L258-L281 | def _set_ipv6_routes(self, v, load=False):
"""
Setter method for ipv6_routes, mapped from YANG variable /isis_state/ipv6_routes (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_ipv6_routes is considered as a private
method. Backends looking to populate thi... | [
"def",
"_set_ipv6_routes",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"ba... | Setter method for ipv6_routes, mapped from YANG variable /isis_state/ipv6_routes (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_ipv6_routes is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_ip... | [
"Setter",
"method",
"for",
"ipv6_routes",
"mapped",
"from",
"YANG",
"variable",
"/",
"isis_state",
"/",
"ipv6_routes",
"(",
"container",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
"in",
"the",
"source",
"YAN... | python | train |
craffel/mir_eval | mir_eval/sonify.py | https://github.com/craffel/mir_eval/blob/f41c8dafaea04b411252a516d1965af43c7d531b/mir_eval/sonify.py#L14-L60 | def clicks(times, fs, click=None, length=None):
"""Returns a signal with the signal 'click' placed at each specified time
Parameters
----------
times : np.ndarray
times to place clicks, in seconds
fs : int
desired sampling rate of the output signal
click : np.ndarray
cli... | [
"def",
"clicks",
"(",
"times",
",",
"fs",
",",
"click",
"=",
"None",
",",
"length",
"=",
"None",
")",
":",
"# Create default click signal",
"if",
"click",
"is",
"None",
":",
"# 1 kHz tone, 100ms",
"click",
"=",
"np",
".",
"sin",
"(",
"2",
"*",
"np",
".... | Returns a signal with the signal 'click' placed at each specified time
Parameters
----------
times : np.ndarray
times to place clicks, in seconds
fs : int
desired sampling rate of the output signal
click : np.ndarray
click signal, defaults to a 1 kHz blip
length : int
... | [
"Returns",
"a",
"signal",
"with",
"the",
"signal",
"click",
"placed",
"at",
"each",
"specified",
"time"
] | python | train |
ARMmbed/mbed-cloud-sdk-python | src/mbed_cloud/device_directory/device_directory.py | https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/device_directory/device_directory.py#L80-L88 | def get_device(self, device_id):
"""Get device details from catalog.
:param str device_id: the ID of the device to retrieve (Required)
:returns: device object matching the `device_id`.
:rtype: Device
"""
api = self._get_api(device_directory.DefaultApi)
return Dev... | [
"def",
"get_device",
"(",
"self",
",",
"device_id",
")",
":",
"api",
"=",
"self",
".",
"_get_api",
"(",
"device_directory",
".",
"DefaultApi",
")",
"return",
"Device",
"(",
"api",
".",
"device_retrieve",
"(",
"device_id",
")",
")"
] | Get device details from catalog.
:param str device_id: the ID of the device to retrieve (Required)
:returns: device object matching the `device_id`.
:rtype: Device | [
"Get",
"device",
"details",
"from",
"catalog",
"."
] | python | train |
websauna/pyramid_notebook | pyramid_notebook/server/comm.py | https://github.com/websauna/pyramid_notebook/blob/8a7ecfa0259810de1a818e4b415a62811a7b077a/pyramid_notebook/server/comm.py#L31-L35 | def get_context_file_name(pid_file):
"""When the daemon is started write out the information which port it was using."""
root = os.path.dirname(pid_file)
port_file = os.path.join(root, "context.json")
return port_file | [
"def",
"get_context_file_name",
"(",
"pid_file",
")",
":",
"root",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"pid_file",
")",
"port_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"\"context.json\"",
")",
"return",
"port_file"
] | When the daemon is started write out the information which port it was using. | [
"When",
"the",
"daemon",
"is",
"started",
"write",
"out",
"the",
"information",
"which",
"port",
"it",
"was",
"using",
"."
] | python | train |
christophertbrown/bioscripts | ctbBio/genome_variation.py | https://github.com/christophertbrown/bioscripts/blob/83b2566b3a5745437ec651cd6cafddd056846240/ctbBio/genome_variation.py#L158-L172 | def parse_codons(ref, start, end, strand):
"""
parse codon nucleotide positions in range start -> end, wrt strand
"""
codon = []
c = cycle([1, 2, 3])
ref = ref[start - 1:end]
if strand == -1:
ref = rc_stats(ref)
for pos in ref:
n = next(c)
codon.append(pos)
... | [
"def",
"parse_codons",
"(",
"ref",
",",
"start",
",",
"end",
",",
"strand",
")",
":",
"codon",
"=",
"[",
"]",
"c",
"=",
"cycle",
"(",
"[",
"1",
",",
"2",
",",
"3",
"]",
")",
"ref",
"=",
"ref",
"[",
"start",
"-",
"1",
":",
"end",
"]",
"if",
... | parse codon nucleotide positions in range start -> end, wrt strand | [
"parse",
"codon",
"nucleotide",
"positions",
"in",
"range",
"start",
"-",
">",
"end",
"wrt",
"strand"
] | python | train |
monarch-initiative/dipper | dipper/sources/CTD.py | https://github.com/monarch-initiative/dipper/blob/24cc80db355bbe15776edc5c7b41e0886959ba41/dipper/sources/CTD.py#L123-L158 | def parse(self, limit=None):
"""
Override Source.parse()
Parses version and interaction information from CTD
Args:
:param limit (int, optional) limit the number of rows processed
Returns:
:return None
"""
if limit is not None:
LOG.info(... | [
"def",
"parse",
"(",
"self",
",",
"limit",
"=",
"None",
")",
":",
"if",
"limit",
"is",
"not",
"None",
":",
"LOG",
".",
"info",
"(",
"\"Only parsing first %d rows\"",
",",
"limit",
")",
"LOG",
".",
"info",
"(",
"\"Parsing files...\"",
")",
"# pub_map = dict... | Override Source.parse()
Parses version and interaction information from CTD
Args:
:param limit (int, optional) limit the number of rows processed
Returns:
:return None | [
"Override",
"Source",
".",
"parse",
"()",
"Parses",
"version",
"and",
"interaction",
"information",
"from",
"CTD",
"Args",
":",
":",
"param",
"limit",
"(",
"int",
"optional",
")",
"limit",
"the",
"number",
"of",
"rows",
"processed",
"Returns",
":",
":",
"r... | python | train |
sorgerlab/indra | indra/tools/reading/readers.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/readers.py#L131-L141 | def change_format(self, new_format):
"""Change the format label of this content.
Note that this does NOT actually alter the format of the content, only
the label.
"""
self._load_raw_content()
self._format = new_format
self.get_filename(renew=True)
self.ge... | [
"def",
"change_format",
"(",
"self",
",",
"new_format",
")",
":",
"self",
".",
"_load_raw_content",
"(",
")",
"self",
".",
"_format",
"=",
"new_format",
"self",
".",
"get_filename",
"(",
"renew",
"=",
"True",
")",
"self",
".",
"get_filepath",
"(",
"renew",... | Change the format label of this content.
Note that this does NOT actually alter the format of the content, only
the label. | [
"Change",
"the",
"format",
"label",
"of",
"this",
"content",
"."
] | python | train |
cedrus-opensource/pyxid | pyxid/pyxid_impl.py | https://github.com/cedrus-opensource/pyxid/blob/02dba3a825f0d4f4c0bfa044c6a361492e4c25b6/pyxid/pyxid_impl.py#L223-L287 | def activate_line(self, lines=None, bitmask=None,
leave_remaining_lines=False):
"""
Triggers an output line on StimTracker.
There are 8 output lines on StimTracker that can be raised in any
combination. To raise lines 1 and 7, for example, you pass in
the ... | [
"def",
"activate_line",
"(",
"self",
",",
"lines",
"=",
"None",
",",
"bitmask",
"=",
"None",
",",
"leave_remaining_lines",
"=",
"False",
")",
":",
"if",
"lines",
"is",
"None",
"and",
"bitmask",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Must set one ... | Triggers an output line on StimTracker.
There are 8 output lines on StimTracker that can be raised in any
combination. To raise lines 1 and 7, for example, you pass in
the list: activate_line(lines=[1, 7]).
To raise a single line, pass in just an integer, or a list with a
sing... | [
"Triggers",
"an",
"output",
"line",
"on",
"StimTracker",
"."
] | python | train |
michael-lazar/rtv | rtv/packages/praw/__init__.py | https://github.com/michael-lazar/rtv/blob/ccef2af042566ad384977028cf0bde01bc524dda/rtv/packages/praw/__init__.py#L2623-L2668 | def hide(self, thing_id, _unhide=False):
"""Hide one or multiple objects in the context of the logged in user.
:param thing_id: A single fullname or list of fullnames,
representing objects which will be hidden.
:param _unhide: If True, unhide the object(s) instead. Use
:... | [
"def",
"hide",
"(",
"self",
",",
"thing_id",
",",
"_unhide",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"thing_id",
",",
"six",
".",
"string_types",
")",
":",
"thing_id",
"=",
"[",
"thing_id",
"]",
"else",
":",
"# Guarantee a subscriptable type.",
"t... | Hide one or multiple objects in the context of the logged in user.
:param thing_id: A single fullname or list of fullnames,
representing objects which will be hidden.
:param _unhide: If True, unhide the object(s) instead. Use
:meth:`~praw.__init__.ReportMixin.unhide` rather than... | [
"Hide",
"one",
"or",
"multiple",
"objects",
"in",
"the",
"context",
"of",
"the",
"logged",
"in",
"user",
"."
] | python | train |
cokelaer/spectrum | src/spectrum/linear_prediction.py | https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/linear_prediction.py#L286-L341 | def poly2lsf(a):
"""Prediction polynomial to line spectral frequencies.
converts the prediction polynomial specified by A,
into the corresponding line spectral frequencies, LSF.
normalizes the prediction polynomial by A(1).
.. doctest::
>>> from spectrum import poly2lsf
>>> a = [1... | [
"def",
"poly2lsf",
"(",
"a",
")",
":",
"#Line spectral frequencies are not defined for complex polynomials.",
"# Normalize the polynomial",
"a",
"=",
"numpy",
".",
"array",
"(",
"a",
")",
"if",
"a",
"[",
"0",
"]",
"!=",
"1",
":",
"a",
"/=",
"a",
"[",
"0",
"]... | Prediction polynomial to line spectral frequencies.
converts the prediction polynomial specified by A,
into the corresponding line spectral frequencies, LSF.
normalizes the prediction polynomial by A(1).
.. doctest::
>>> from spectrum import poly2lsf
>>> a = [1.0000, 0.6149, 0.9899, ... | [
"Prediction",
"polynomial",
"to",
"line",
"spectral",
"frequencies",
"."
] | python | valid |
scanny/python-pptx | pptx/chart/data.py | https://github.com/scanny/python-pptx/blob/d6ab8234f8b03953d2f831ff9394b1852db34130/pptx/chart/data.py#L281-L293 | def add_series(self, name, values=(), number_format=None):
"""
Add a series to this data set entitled *name* and having the data
points specified by *values*, an iterable of numeric values.
*number_format* specifies how the series values will be displayed,
and may be a string, e.... | [
"def",
"add_series",
"(",
"self",
",",
"name",
",",
"values",
"=",
"(",
")",
",",
"number_format",
"=",
"None",
")",
":",
"series_data",
"=",
"CategorySeriesData",
"(",
"self",
",",
"name",
",",
"number_format",
")",
"self",
".",
"append",
"(",
"series_d... | Add a series to this data set entitled *name* and having the data
points specified by *values*, an iterable of numeric values.
*number_format* specifies how the series values will be displayed,
and may be a string, e.g. '#,##0' corresponding to an Excel number
format. | [
"Add",
"a",
"series",
"to",
"this",
"data",
"set",
"entitled",
"*",
"name",
"*",
"and",
"having",
"the",
"data",
"points",
"specified",
"by",
"*",
"values",
"*",
"an",
"iterable",
"of",
"numeric",
"values",
".",
"*",
"number_format",
"*",
"specifies",
"h... | python | train |
spacetelescope/stsci.tools | lib/stsci/tools/editpar.py | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/editpar.py#L1332-L1383 | def _showAnyHelp(self, kind, tag=None):
""" Invoke task/epar/etc. help and put the page in a window.
This same logic is used for GUI help, task help, log msgs, etc. """
# sanity check
assert kind in ('epar', 'task', 'log'), 'Unknown help kind: '+str(kind)
#---------------------... | [
"def",
"_showAnyHelp",
"(",
"self",
",",
"kind",
",",
"tag",
"=",
"None",
")",
":",
"# sanity check",
"assert",
"kind",
"in",
"(",
"'epar'",
",",
"'task'",
",",
"'log'",
")",
",",
"'Unknown help kind: '",
"+",
"str",
"(",
"kind",
")",
"#-------------------... | Invoke task/epar/etc. help and put the page in a window.
This same logic is used for GUI help, task help, log msgs, etc. | [
"Invoke",
"task",
"/",
"epar",
"/",
"etc",
".",
"help",
"and",
"put",
"the",
"page",
"in",
"a",
"window",
".",
"This",
"same",
"logic",
"is",
"used",
"for",
"GUI",
"help",
"task",
"help",
"log",
"msgs",
"etc",
"."
] | python | train |
WebarchivCZ/WA-KAT | src/wa_kat/templates/static/js/Lib/site-packages/components/author_picker.py | https://github.com/WebarchivCZ/WA-KAT/blob/16d064a3a775dc1d2713debda7847ded52dd2a06/src/wa_kat/templates/static/js/Lib/site-packages/components/author_picker.py#L222-L243 | def start(cls, ev):
"""
Event handler which starts the request to REST API.
"""
# somehow the first call doesn't stop the propagation
ev.stopPropagation()
ev.preventDefault()
# make sure, that `author` was filled
author = cls.input_el.value.strip()
... | [
"def",
"start",
"(",
"cls",
",",
"ev",
")",
":",
"# somehow the first call doesn't stop the propagation",
"ev",
".",
"stopPropagation",
"(",
")",
"ev",
".",
"preventDefault",
"(",
")",
"# make sure, that `author` was filled",
"author",
"=",
"cls",
".",
"input_el",
"... | Event handler which starts the request to REST API. | [
"Event",
"handler",
"which",
"starts",
"the",
"request",
"to",
"REST",
"API",
"."
] | python | train |
aio-libs/yarl | yarl/__init__.py | https://github.com/aio-libs/yarl/blob/e47da02c00ad764e030ca7647a9565548c97d362/yarl/__init__.py#L332-L345 | def is_default_port(self):
"""A check for default port.
Return True if port is default for specified scheme,
e.g. 'http://python.org' or 'http://python.org:80', False
otherwise.
"""
if self.port is None:
return False
default = DEFAULT_PORTS.get(self.... | [
"def",
"is_default_port",
"(",
"self",
")",
":",
"if",
"self",
".",
"port",
"is",
"None",
":",
"return",
"False",
"default",
"=",
"DEFAULT_PORTS",
".",
"get",
"(",
"self",
".",
"scheme",
")",
"if",
"default",
"is",
"None",
":",
"return",
"False",
"retu... | A check for default port.
Return True if port is default for specified scheme,
e.g. 'http://python.org' or 'http://python.org:80', False
otherwise. | [
"A",
"check",
"for",
"default",
"port",
"."
] | python | train |
josiah-wolf-oberholtzer/uqbar | uqbar/apis/InheritanceGraph.py | https://github.com/josiah-wolf-oberholtzer/uqbar/blob/eca7fefebbbee1e2ae13bf5d6baa838be66b1db6/uqbar/apis/InheritanceGraph.py#L347-L385 | def _build_mappings(
self, classes: Sequence[type]
) -> Tuple[Mapping[type, Sequence[type]], Mapping[type, Sequence[type]]]:
"""
Collect all bases and organize into parent/child mappings.
"""
parents_to_children: MutableMapping[type, Set[type]] = {}
children_to_parent... | [
"def",
"_build_mappings",
"(",
"self",
",",
"classes",
":",
"Sequence",
"[",
"type",
"]",
")",
"->",
"Tuple",
"[",
"Mapping",
"[",
"type",
",",
"Sequence",
"[",
"type",
"]",
"]",
",",
"Mapping",
"[",
"type",
",",
"Sequence",
"[",
"type",
"]",
"]",
... | Collect all bases and organize into parent/child mappings. | [
"Collect",
"all",
"bases",
"and",
"organize",
"into",
"parent",
"/",
"child",
"mappings",
"."
] | python | train |
XuShaohua/bcloud | bcloud/CloudPage.py | https://github.com/XuShaohua/bcloud/blob/4b54e0fdccf2b3013285fef05c97354cfa31697b/bcloud/CloudPage.py#L179-L215 | def load(self):
'''获取当前的离线任务列表'''
def on_list_task(info, error=None):
self.loading_spin.stop()
self.loading_spin.hide()
if not info:
self.app.toast(_('Network error, info is empty'))
if error or not info:
logger.error('Cloud... | [
"def",
"load",
"(",
"self",
")",
":",
"def",
"on_list_task",
"(",
"info",
",",
"error",
"=",
"None",
")",
":",
"self",
".",
"loading_spin",
".",
"stop",
"(",
")",
"self",
".",
"loading_spin",
".",
"hide",
"(",
")",
"if",
"not",
"info",
":",
"self",... | 获取当前的离线任务列表 | [
"获取当前的离线任务列表"
] | python | train |
LordDarkula/chess_py | chess_py/pieces/piece_const.py | https://github.com/LordDarkula/chess_py/blob/14bebc2f8c49ae25c59375cc83d0b38d8ff7281d/chess_py/pieces/piece_const.py#L27-L44 | def init_manual(cls, pawn_value, knight_value, bishop_value, rook_value, queen_value, king_value):
"""
Manual init method for external piece values
:type: PAWN_VALUE: int
:type: KNIGHT_VALUE: int
:type: BISHOP_VALUE: int
:type: ROOK_VALUE: int
:type: QUEEN_VALUE:... | [
"def",
"init_manual",
"(",
"cls",
",",
"pawn_value",
",",
"knight_value",
",",
"bishop_value",
",",
"rook_value",
",",
"queen_value",
",",
"king_value",
")",
":",
"piece_values",
"=",
"cls",
"(",
")",
"piece_values",
".",
"PAWN_VALUE",
"=",
"pawn_value",
"piec... | Manual init method for external piece values
:type: PAWN_VALUE: int
:type: KNIGHT_VALUE: int
:type: BISHOP_VALUE: int
:type: ROOK_VALUE: int
:type: QUEEN_VALUE: int | [
"Manual",
"init",
"method",
"for",
"external",
"piece",
"values"
] | python | train |
scrapinghub/dateparser | dateparser/utils/strptime.py | https://github.com/scrapinghub/dateparser/blob/11a761c99d3ee522a3c63756b70c106a579e8b5c/dateparser/utils/strptime.py#L17-L52 | def patch_strptime():
"""Monkey patching _strptime to avoid problems related with non-english
locale changes on the system.
For example, if system's locale is set to fr_FR. Parser won't recognize
any date since all languages are translated to english dates.
"""
_strptime = imp.load_module(
... | [
"def",
"patch_strptime",
"(",
")",
":",
"_strptime",
"=",
"imp",
".",
"load_module",
"(",
"'strptime_patched'",
",",
"*",
"imp",
".",
"find_module",
"(",
"'_strptime'",
")",
")",
"_calendar",
"=",
"imp",
".",
"load_module",
"(",
"'calendar_patched'",
",",
"*... | Monkey patching _strptime to avoid problems related with non-english
locale changes on the system.
For example, if system's locale is set to fr_FR. Parser won't recognize
any date since all languages are translated to english dates. | [
"Monkey",
"patching",
"_strptime",
"to",
"avoid",
"problems",
"related",
"with",
"non",
"-",
"english",
"locale",
"changes",
"on",
"the",
"system",
"."
] | python | test |
sassoo/goldman | goldman/queryparams/page.py | https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/queryparams/page.py#L124-L133 | def to_dict(self):
""" Convert the Paginator into a dict """
return {
'current': self.current,
'first': self.first,
'last': self.last,
'next': self.more,
'prev': self.prev,
} | [
"def",
"to_dict",
"(",
"self",
")",
":",
"return",
"{",
"'current'",
":",
"self",
".",
"current",
",",
"'first'",
":",
"self",
".",
"first",
",",
"'last'",
":",
"self",
".",
"last",
",",
"'next'",
":",
"self",
".",
"more",
",",
"'prev'",
":",
"self... | Convert the Paginator into a dict | [
"Convert",
"the",
"Paginator",
"into",
"a",
"dict"
] | python | train |
dswah/pyGAM | pygam/core.py | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/core.py#L156-L179 | def set_params(self, deep=False, force=False, **parameters):
"""
sets an object's paramters
Parameters
----------
deep : boolean, default: False
when True, also sets non-user-facing paramters
force : boolean, default: False
when True, also sets pa... | [
"def",
"set_params",
"(",
"self",
",",
"deep",
"=",
"False",
",",
"force",
"=",
"False",
",",
"*",
"*",
"parameters",
")",
":",
"param_names",
"=",
"self",
".",
"get_params",
"(",
"deep",
"=",
"deep",
")",
".",
"keys",
"(",
")",
"for",
"parameter",
... | sets an object's paramters
Parameters
----------
deep : boolean, default: False
when True, also sets non-user-facing paramters
force : boolean, default: False
when True, also sets parameters that the object does not already
have
**parameters :... | [
"sets",
"an",
"object",
"s",
"paramters"
] | python | train |
F5Networks/f5-common-python | f5/bigip/tm/gtm/monitor.py | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/gtm/monitor.py#L625-L645 | def update(self, **kwargs):
"""Change the configuration of the resource on the device.
This method uses Http PUT alter the service state on the device.
The attributes of the instance will be packaged as a dictionary. That
dictionary will be updated with kwargs. It is then submitted a... | [
"def",
"update",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"__dict__",
".",
"pop",
"(",
"'agent'",
",",
"''",
")",
"self",
".",
"__dict__",
".",
"pop",
"(",
"'post'",
",",
"''",
")",
"self",
".",
"__dict__",
".",
"pop",
"(",
... | Change the configuration of the resource on the device.
This method uses Http PUT alter the service state on the device.
The attributes of the instance will be packaged as a dictionary. That
dictionary will be updated with kwargs. It is then submitted as JSON
to the device. Various ... | [
"Change",
"the",
"configuration",
"of",
"the",
"resource",
"on",
"the",
"device",
"."
] | python | train |
apache/spark | python/pyspark/ml/image.py | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/ml/image.py#L119-L130 | def undefinedImageType(self):
"""
Returns the name of undefined image type for the invalid image.
.. versionadded:: 2.3.0
"""
if self._undefinedImageType is None:
ctx = SparkContext._active_spark_context
self._undefinedImageType = \
ctx._... | [
"def",
"undefinedImageType",
"(",
"self",
")",
":",
"if",
"self",
".",
"_undefinedImageType",
"is",
"None",
":",
"ctx",
"=",
"SparkContext",
".",
"_active_spark_context",
"self",
".",
"_undefinedImageType",
"=",
"ctx",
".",
"_jvm",
".",
"org",
".",
"apache",
... | Returns the name of undefined image type for the invalid image.
.. versionadded:: 2.3.0 | [
"Returns",
"the",
"name",
"of",
"undefined",
"image",
"type",
"for",
"the",
"invalid",
"image",
"."
] | python | train |
Julius2342/pyvlx | pyvlx/frame_creation.py | https://github.com/Julius2342/pyvlx/blob/ee78e1324bcb1be5b8d1a9d05ab5496b72eae848/pyvlx/frame_creation.py#L32-L41 | def frame_from_raw(raw):
"""Create and return frame from raw bytes."""
command, payload = extract_from_frame(raw)
frame = create_frame(command)
if frame is None:
PYVLXLOG.warning("Command %s not implemented, raw: %s", command, ":".join("{:02x}".format(c) for c in raw))
return None
fr... | [
"def",
"frame_from_raw",
"(",
"raw",
")",
":",
"command",
",",
"payload",
"=",
"extract_from_frame",
"(",
"raw",
")",
"frame",
"=",
"create_frame",
"(",
"command",
")",
"if",
"frame",
"is",
"None",
":",
"PYVLXLOG",
".",
"warning",
"(",
"\"Command %s not impl... | Create and return frame from raw bytes. | [
"Create",
"and",
"return",
"frame",
"from",
"raw",
"bytes",
"."
] | python | train |
hollenstein/maspy | maspy/writer.py | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/writer.py#L227-L239 | def _writeMzmlChecksum(xmlWriter, outputFile):
""" #TODO: docstring
:param xmlWriter: #TODO: docstring
:param outputFile: #TODO: docstring
"""
sha = hashlib.sha1(outputFile.getvalue())
sha.update('<fileChecksum>')
xmlChecksumElement = ETREE.Element('fileChecksum')
xmlChecksumElement.te... | [
"def",
"_writeMzmlChecksum",
"(",
"xmlWriter",
",",
"outputFile",
")",
":",
"sha",
"=",
"hashlib",
".",
"sha1",
"(",
"outputFile",
".",
"getvalue",
"(",
")",
")",
"sha",
".",
"update",
"(",
"'<fileChecksum>'",
")",
"xmlChecksumElement",
"=",
"ETREE",
".",
... | #TODO: docstring
:param xmlWriter: #TODO: docstring
:param outputFile: #TODO: docstring | [
"#TODO",
":",
"docstring"
] | python | train |
ralphje/imagemounter | imagemounter/dependencies.py | https://github.com/ralphje/imagemounter/blob/86213781c366cad65096447d91f522f0a3fb4b93/imagemounter/dependencies.py#L8-L28 | def require(*requirements, **kwargs):
"""Decorator that can be used to require requirements.
:param requirements: List of requirements that should be verified
:param none_on_failure: If true, does not raise a PrerequisiteFailedError, but instead returns None
"""
# TODO: require(*requirements, none_... | [
"def",
"require",
"(",
"*",
"requirements",
",",
"*",
"*",
"kwargs",
")",
":",
"# TODO: require(*requirements, none_on_failure=False) is not supported by Python 2",
"none_on_failure",
"=",
"kwargs",
".",
"get",
"(",
"'none_on_failure'",
",",
"False",
")",
"def",
"inner"... | Decorator that can be used to require requirements.
:param requirements: List of requirements that should be verified
:param none_on_failure: If true, does not raise a PrerequisiteFailedError, but instead returns None | [
"Decorator",
"that",
"can",
"be",
"used",
"to",
"require",
"requirements",
"."
] | python | train |
scanny/python-pptx | pptx/chart/chart.py | https://github.com/scanny/python-pptx/blob/d6ab8234f8b03953d2f831ff9394b1852db34130/pptx/chart/chart.py#L144-L152 | def legend(self):
"""
A |Legend| object providing access to the properties of the legend
for this chart.
"""
legend_elm = self._chartSpace.chart.legend
if legend_elm is None:
return None
return Legend(legend_elm) | [
"def",
"legend",
"(",
"self",
")",
":",
"legend_elm",
"=",
"self",
".",
"_chartSpace",
".",
"chart",
".",
"legend",
"if",
"legend_elm",
"is",
"None",
":",
"return",
"None",
"return",
"Legend",
"(",
"legend_elm",
")"
] | A |Legend| object providing access to the properties of the legend
for this chart. | [
"A",
"|Legend|",
"object",
"providing",
"access",
"to",
"the",
"properties",
"of",
"the",
"legend",
"for",
"this",
"chart",
"."
] | python | train |
twitterdev/twitter-python-ads-sdk | twitter_ads/http.py | https://github.com/twitterdev/twitter-python-ads-sdk/blob/b4488333ac2a794b85b7f16ded71e98b60e51c74/twitter_ads/http.py#L226-L240 | def content_type(self):
"""Returns the content-type value determined by file extension."""
if hasattr(self, '_content_type'):
return self._content_type
filename, extension = os.path.splitext(self._file_path)
if extension == '.csv':
self._content_type = 'text/csv... | [
"def",
"content_type",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_content_type'",
")",
":",
"return",
"self",
".",
"_content_type",
"filename",
",",
"extension",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"self",
".",
"_file_path",
"... | Returns the content-type value determined by file extension. | [
"Returns",
"the",
"content",
"-",
"type",
"value",
"determined",
"by",
"file",
"extension",
"."
] | python | train |
nchopin/particles | particles/resampling.py | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/resampling.py#L162-L184 | def essl(lw):
"""ESS (Effective sample size) computed from log-weights.
Parameters
----------
lw: (N,) ndarray
log-weights
Returns
-------
float
the ESS of weights w = exp(lw), i.e. the quantity
sum(w**2) / (sum(w))**2
Note
----
The ESS is a popula... | [
"def",
"essl",
"(",
"lw",
")",
":",
"w",
"=",
"np",
".",
"exp",
"(",
"lw",
"-",
"lw",
".",
"max",
"(",
")",
")",
"return",
"(",
"w",
".",
"sum",
"(",
")",
")",
"**",
"2",
"/",
"np",
".",
"sum",
"(",
"w",
"**",
"2",
")"
] | ESS (Effective sample size) computed from log-weights.
Parameters
----------
lw: (N,) ndarray
log-weights
Returns
-------
float
the ESS of weights w = exp(lw), i.e. the quantity
sum(w**2) / (sum(w))**2
Note
----
The ESS is a popular criterion to determ... | [
"ESS",
"(",
"Effective",
"sample",
"size",
")",
"computed",
"from",
"log",
"-",
"weights",
"."
] | python | train |
SBRG/ssbio | ssbio/core/protein.py | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/core/protein.py#L937-L1008 | def map_uniprot_to_pdb(self, seq_ident_cutoff=0.0, outdir=None, force_rerun=False):
"""Map the representative sequence's UniProt ID to PDB IDs using the PDBe "Best Structures" API.
Will save a JSON file of the results to the protein sequences folder.
The "Best structures" API is available at ht... | [
"def",
"map_uniprot_to_pdb",
"(",
"self",
",",
"seq_ident_cutoff",
"=",
"0.0",
",",
"outdir",
"=",
"None",
",",
"force_rerun",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"representative_sequence",
":",
"log",
".",
"error",
"(",
"'{}: no representative s... | Map the representative sequence's UniProt ID to PDB IDs using the PDBe "Best Structures" API.
Will save a JSON file of the results to the protein sequences folder.
The "Best structures" API is available at https://www.ebi.ac.uk/pdbe/api/doc/sifts.html
The list of PDB structures mapping to a Uni... | [
"Map",
"the",
"representative",
"sequence",
"s",
"UniProt",
"ID",
"to",
"PDB",
"IDs",
"using",
"the",
"PDBe",
"Best",
"Structures",
"API",
".",
"Will",
"save",
"a",
"JSON",
"file",
"of",
"the",
"results",
"to",
"the",
"protein",
"sequences",
"folder",
"."
... | python | train |
nerdvegas/rez | src/rez/vendor/memcache/memcache.py | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/memcache/memcache.py#L256-L290 | def get_stats(self, stat_args = None):
'''Get statistics from each of the servers.
@param stat_args: Additional arguments to pass to the memcache
"stats" command.
@return: A list of tuples ( server_identifier, stats_dictionary ).
The dictionary contains a number of name... | [
"def",
"get_stats",
"(",
"self",
",",
"stat_args",
"=",
"None",
")",
":",
"data",
"=",
"[",
"]",
"for",
"s",
"in",
"self",
".",
"servers",
":",
"if",
"not",
"s",
".",
"connect",
"(",
")",
":",
"continue",
"if",
"s",
".",
"family",
"==",
"socket",... | Get statistics from each of the servers.
@param stat_args: Additional arguments to pass to the memcache
"stats" command.
@return: A list of tuples ( server_identifier, stats_dictionary ).
The dictionary contains a number of name/value pairs specifying
the name of th... | [
"Get",
"statistics",
"from",
"each",
"of",
"the",
"servers",
"."
] | python | train |
openstack/os-refresh-config | os_refresh_config/os_refresh_config.py | https://github.com/openstack/os-refresh-config/blob/39c1df66510ffd9a528a783208661217242dbd9e/os_refresh_config/os_refresh_config.py#L32-L50 | def default_base_dir():
"""Determine the default base directory path
If the OS_REFRESH_CONFIG_BASE_DIR environment variable is set,
use its value.
Otherwise, prefer the new default path, but still allow the old one for
backwards compatibility.
"""
base_dir = os.environ.get('OS_REFRESH_CONFI... | [
"def",
"default_base_dir",
"(",
")",
":",
"base_dir",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'OS_REFRESH_CONFIG_BASE_DIR'",
")",
"if",
"base_dir",
"is",
"None",
":",
"# NOTE(bnemec): Prefer the new location, but still allow the old one.",
"if",
"os",
".",
"path"... | Determine the default base directory path
If the OS_REFRESH_CONFIG_BASE_DIR environment variable is set,
use its value.
Otherwise, prefer the new default path, but still allow the old one for
backwards compatibility. | [
"Determine",
"the",
"default",
"base",
"directory",
"path"
] | python | train |
pyBookshelf/bookshelf | bookshelf/api_v1.py | https://github.com/pyBookshelf/bookshelf/blob/a6770678e735de95b194f6e6989223970db5f654/bookshelf/api_v1.py#L874-L883 | def down_ec2(instance_id, region, access_key_id, secret_access_key):
""" shutdown of an existing EC2 instance """
conn = connect_to_ec2(region, access_key_id, secret_access_key)
# get the instance_id from the state file, and stop the instance
instance = conn.stop_instances(instance_ids=instance_id)[0]
... | [
"def",
"down_ec2",
"(",
"instance_id",
",",
"region",
",",
"access_key_id",
",",
"secret_access_key",
")",
":",
"conn",
"=",
"connect_to_ec2",
"(",
"region",
",",
"access_key_id",
",",
"secret_access_key",
")",
"# get the instance_id from the state file, and stop the inst... | shutdown of an existing EC2 instance | [
"shutdown",
"of",
"an",
"existing",
"EC2",
"instance"
] | python | train |
marcharper/python-ternary | examples/scatter_colorbar.py | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/examples/scatter_colorbar.py#L95-L130 | def _read_data(fname):
"""Reads data from file.
Reads the data in 'fname' into a list where each list entry contains
[energy predicted, energy calculated, list of concentrations].
Parameters
----------
fname : str
The name and path to the data file.
Returns
-------
en... | [
"def",
"_read_data",
"(",
"fname",
")",
":",
"energy",
"=",
"[",
"]",
"with",
"open",
"(",
"fname",
",",
"'r'",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"CE",
"=",
"abs",
"(",
"float",
"(",
"line",
".",
"strip",
"(",
")",
".",
"spl... | Reads data from file.
Reads the data in 'fname' into a list where each list entry contains
[energy predicted, energy calculated, list of concentrations].
Parameters
----------
fname : str
The name and path to the data file.
Returns
-------
energy : list of lists of floats... | [
"Reads",
"data",
"from",
"file",
"."
] | python | train |
pyviz/holoviews | holoviews/core/ndmapping.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/core/ndmapping.py#L513-L518 | def keys(self):
" Returns the keys of all the elements."
if self.ndims == 1:
return [k[0] for k in self.data.keys()]
else:
return list(self.data.keys()) | [
"def",
"keys",
"(",
"self",
")",
":",
"if",
"self",
".",
"ndims",
"==",
"1",
":",
"return",
"[",
"k",
"[",
"0",
"]",
"for",
"k",
"in",
"self",
".",
"data",
".",
"keys",
"(",
")",
"]",
"else",
":",
"return",
"list",
"(",
"self",
".",
"data",
... | Returns the keys of all the elements. | [
"Returns",
"the",
"keys",
"of",
"all",
"the",
"elements",
"."
] | python | train |
saltstack/salt | salt/modules/solrcloud.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solrcloud.py#L445-L473 | def collection_get_options(collection_name, **kwargs):
'''
Get collection options
Additional parameters (kwargs) may be passed, they will be proxied to http.query
CLI Example:
.. code-block:: bash
salt '*' solrcloud.collection_get_options collection_name
'''
cluster = cluster_st... | [
"def",
"collection_get_options",
"(",
"collection_name",
",",
"*",
"*",
"kwargs",
")",
":",
"cluster",
"=",
"cluster_status",
"(",
"*",
"*",
"kwargs",
")",
"options",
"=",
"{",
"\"collection.configName\"",
":",
"cluster",
"[",
"\"collections\"",
"]",
"[",
"col... | Get collection options
Additional parameters (kwargs) may be passed, they will be proxied to http.query
CLI Example:
.. code-block:: bash
salt '*' solrcloud.collection_get_options collection_name | [
"Get",
"collection",
"options"
] | python | train |
googleapis/google-cloud-python | storage/google/cloud/storage/bucket.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/bucket.py#L1493-L1508 | def retention_period(self, value):
"""Set the retention period for items in the bucket.
:type value: int
:param value:
number of seconds to retain items after upload or release from
event-based lock.
:raises ValueError: if the bucket's retention policy is locked... | [
"def",
"retention_period",
"(",
"self",
",",
"value",
")",
":",
"policy",
"=",
"self",
".",
"_properties",
".",
"setdefault",
"(",
"\"retentionPolicy\"",
",",
"{",
"}",
")",
"if",
"value",
"is",
"not",
"None",
":",
"policy",
"[",
"\"retentionPeriod\"",
"]"... | Set the retention period for items in the bucket.
:type value: int
:param value:
number of seconds to retain items after upload or release from
event-based lock.
:raises ValueError: if the bucket's retention policy is locked. | [
"Set",
"the",
"retention",
"period",
"for",
"items",
"in",
"the",
"bucket",
"."
] | python | train |
ml4ai/delphi | delphi/translators/for2py/format.py | https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/format.py#L73-L87 | def init_read_line(self):
"""init_read_line() initializes fields relevant to input matching"""
format_list = self._format_list
self._re_cvt = self.match_input_fmt(format_list)
regexp0_str = "".join([subs[0] for subs in self._re_cvt])
self._regexp_str = regexp0_str
self._r... | [
"def",
"init_read_line",
"(",
"self",
")",
":",
"format_list",
"=",
"self",
".",
"_format_list",
"self",
".",
"_re_cvt",
"=",
"self",
".",
"match_input_fmt",
"(",
"format_list",
")",
"regexp0_str",
"=",
"\"\"",
".",
"join",
"(",
"[",
"subs",
"[",
"0",
"]... | init_read_line() initializes fields relevant to input matching | [
"init_read_line",
"()",
"initializes",
"fields",
"relevant",
"to",
"input",
"matching"
] | python | train |
rq/Flask-RQ2 | src/flask_rq2/app.py | https://github.com/rq/Flask-RQ2/blob/58eedf6f0cd7bcde4ccd787074762ea08f531337/src/flask_rq2/app.py#L367-L390 | def get_worker(self, *queues):
"""
Returns an RQ worker instance for the given queue names, e.g.::
configured_worker = rq.get_worker()
default_worker = rq.get_worker('default')
default_low_worker = rq.get_worker('default', 'low')
:param \\*queues: Names of q... | [
"def",
"get_worker",
"(",
"self",
",",
"*",
"queues",
")",
":",
"if",
"not",
"queues",
":",
"queues",
"=",
"self",
".",
"queues",
"queues",
"=",
"[",
"self",
".",
"get_queue",
"(",
"name",
")",
"for",
"name",
"in",
"queues",
"]",
"worker_cls",
"=",
... | Returns an RQ worker instance for the given queue names, e.g.::
configured_worker = rq.get_worker()
default_worker = rq.get_worker('default')
default_low_worker = rq.get_worker('default', 'low')
:param \\*queues: Names of queues the worker should act on, falls back
... | [
"Returns",
"an",
"RQ",
"worker",
"instance",
"for",
"the",
"given",
"queue",
"names",
"e",
".",
"g",
".",
"::"
] | python | train |
saltstack/salt | salt/states/win_system.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_system.py#L364-L449 | def shutdown(name, message=None, timeout=5, force_close=True, reboot=False,
in_seconds=False, only_on_pending_reboot=False):
'''
Shutdown the computer
:param str message:
An optional message to display to users. It will also be used as a
comment in the event log entry.
... | [
"def",
"shutdown",
"(",
"name",
",",
"message",
"=",
"None",
",",
"timeout",
"=",
"5",
",",
"force_close",
"=",
"True",
",",
"reboot",
"=",
"False",
",",
"in_seconds",
"=",
"False",
",",
"only_on_pending_reboot",
"=",
"False",
")",
":",
"ret",
"=",
"{"... | Shutdown the computer
:param str message:
An optional message to display to users. It will also be used as a
comment in the event log entry.
The default value is None.
:param int timeout:
The number of minutes or seconds before a shutdown will occur. Whether
this numbe... | [
"Shutdown",
"the",
"computer"
] | python | train |
bcbio/bcbio-nextgen | bcbio/variation/freebayes.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/freebayes.py#L275-L330 | def call_somatic(tumor_name, normal_name):
"""Call SOMATIC variants from tumor/normal calls, adding REJECT filters and SOMATIC flag.
Works from stdin and writes to stdout, finding positions of tumor and normal samples.
Uses MuTect like somatic filter based on implementation in speedseq:
https://github... | [
"def",
"call_somatic",
"(",
"tumor_name",
",",
"normal_name",
")",
":",
"# Thresholds are like phred scores, so 3.5 = phred35",
"tumor_thresh",
",",
"normal_thresh",
"=",
"3.5",
",",
"3.5",
"new_headers",
"=",
"[",
"'##INFO=<ID=SOMATIC,Number=0,Type=Flag,Description=\"Somatic e... | Call SOMATIC variants from tumor/normal calls, adding REJECT filters and SOMATIC flag.
Works from stdin and writes to stdout, finding positions of tumor and normal samples.
Uses MuTect like somatic filter based on implementation in speedseq:
https://github.com/cc2qe/speedseq/blob/e6729aa2589eca4e3a946f398... | [
"Call",
"SOMATIC",
"variants",
"from",
"tumor",
"/",
"normal",
"calls",
"adding",
"REJECT",
"filters",
"and",
"SOMATIC",
"flag",
"."
] | python | train |
RedisJSON/rejson-py | rejson/client.py | https://github.com/RedisJSON/rejson-py/blob/55f0adf3adc40f5a769e28e541dbbf5377b90ec6/rejson/client.py#L166-L171 | def jsonnummultby(self, name, path, number):
"""
Multiplies the numeric (integer or floating point) JSON value under
``path`` at key ``name`` with the provided ``number``
"""
return self.execute_command('JSON.NUMMULTBY', name, str_path(path), self._encode(number)) | [
"def",
"jsonnummultby",
"(",
"self",
",",
"name",
",",
"path",
",",
"number",
")",
":",
"return",
"self",
".",
"execute_command",
"(",
"'JSON.NUMMULTBY'",
",",
"name",
",",
"str_path",
"(",
"path",
")",
",",
"self",
".",
"_encode",
"(",
"number",
")",
... | Multiplies the numeric (integer or floating point) JSON value under
``path`` at key ``name`` with the provided ``number`` | [
"Multiplies",
"the",
"numeric",
"(",
"integer",
"or",
"floating",
"point",
")",
"JSON",
"value",
"under",
"path",
"at",
"key",
"name",
"with",
"the",
"provided",
"number"
] | python | train |
ThreatResponse/aws_ir_plugins | aws_ir_plugins/revokests_key.py | https://github.com/ThreatResponse/aws_ir_plugins/blob/b5128ef5cbd91fc0b5d55615f1c14cb036ae7c73/aws_ir_plugins/revokests_key.py#L86-L97 | def _attach_inline_policy(self, username, policy_document):
"""Attaches the policy to the user"""
response = self.client.put_user_policy(
UserName=username,
PolicyName="threatresponse-temporal-key-revocation",
PolicyDocument=policy_document
)
logger.in... | [
"def",
"_attach_inline_policy",
"(",
"self",
",",
"username",
",",
"policy_document",
")",
":",
"response",
"=",
"self",
".",
"client",
".",
"put_user_policy",
"(",
"UserName",
"=",
"username",
",",
"PolicyName",
"=",
"\"threatresponse-temporal-key-revocation\"",
",... | Attaches the policy to the user | [
"Attaches",
"the",
"policy",
"to",
"the",
"user"
] | python | train |
willkg/everett | everett/sphinxext.py | https://github.com/willkg/everett/blob/5653134af59f439d2b33f3939fab2b8544428f11/everett/sphinxext.py#L329-L412 | def generate_docs(self, clspath, more_content):
"""Generate documentation for this configman class"""
obj = import_class(clspath)
sourcename = 'docstring of %s' % clspath
all_options = []
indent = ' '
config = obj.get_required_config()
if config.options:
... | [
"def",
"generate_docs",
"(",
"self",
",",
"clspath",
",",
"more_content",
")",
":",
"obj",
"=",
"import_class",
"(",
"clspath",
")",
"sourcename",
"=",
"'docstring of %s'",
"%",
"clspath",
"all_options",
"=",
"[",
"]",
"indent",
"=",
"' '",
"config",
"=",... | Generate documentation for this configman class | [
"Generate",
"documentation",
"for",
"this",
"configman",
"class"
] | python | train |
gwastro/pycbc-glue | pycbc_glue/ldbd.py | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ldbd.py#L427-L469 | def insert(self):
"""Insert the object into the database"""
if not self.curs:
raise LIGOLwDBError, "Database connection not initalized"
if len(self.table) == 0:
raise LIGOLwDBError, 'attempt to insert empty table'
for tab in self.table.keys():
# find and add any missing unique ids
... | [
"def",
"insert",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"curs",
":",
"raise",
"LIGOLwDBError",
",",
"\"Database connection not initalized\"",
"if",
"len",
"(",
"self",
".",
"table",
")",
"==",
"0",
":",
"raise",
"LIGOLwDBError",
",",
"'attempt to i... | Insert the object into the database | [
"Insert",
"the",
"object",
"into",
"the",
"database"
] | python | train |
common-workflow-language/cwltool | cwltool/load_tool.py | https://github.com/common-workflow-language/cwltool/blob/cb81b22abc52838823da9945f04d06739ab32fda/cwltool/load_tool.py#L194-L320 | def resolve_and_validate_document(loadingContext,
workflowobj,
uri,
preprocess_only=False, # type: bool
skip_schemas=None, # type: bool
):
# type: (...) -> Tuple[LoadingContext, Text]
"""Vali... | [
"def",
"resolve_and_validate_document",
"(",
"loadingContext",
",",
"workflowobj",
",",
"uri",
",",
"preprocess_only",
"=",
"False",
",",
"# type: bool",
"skip_schemas",
"=",
"None",
",",
"# type: bool",
")",
":",
"# type: (...) -> Tuple[LoadingContext, Text]",
"loadingCo... | Validate a CWL document. | [
"Validate",
"a",
"CWL",
"document",
"."
] | python | train |
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#L522-L534 | def get_vnetwork_dvs_output_vnetwork_dvs_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vnetwork_dvs = ET.Element("get_vnetwork_dvs")
config = get_vnetwork_dvs
output = ET.SubElement(get_vnetwork_dvs, "output")
vnetwork_dvs = ET... | [
"def",
"get_vnetwork_dvs_output_vnetwork_dvs_name",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_vnetwork_dvs",
"=",
"ET",
".",
"Element",
"(",
"\"get_vnetwork_dvs\"",
")",
"config",
"=",
"ge... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
JukeboxPipeline/jukebox-core | src/jukeboxcore/reftrack.py | https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L1193-L1216 | def import_file(self, taskfileinfo):
"""Import the file for the given taskfileinfo
This will also update the status to :data:`Reftrack.IMPORTED`. This will also call
:meth:`fetch_new_children`. Because after the import, we might have new children.
:param taskfileinfo: the taskfileinfo ... | [
"def",
"import_file",
"(",
"self",
",",
"taskfileinfo",
")",
":",
"assert",
"self",
".",
"status",
"(",
")",
"is",
"None",
",",
"\"Entity is already in scene. Use replace instead.\"",
"refobjinter",
"=",
"self",
".",
"get_refobjinter",
"(",
")",
"refobj",
"=",
"... | Import the file for the given taskfileinfo
This will also update the status to :data:`Reftrack.IMPORTED`. This will also call
:meth:`fetch_new_children`. Because after the import, we might have new children.
:param taskfileinfo: the taskfileinfo to import. If None is given, try to import
... | [
"Import",
"the",
"file",
"for",
"the",
"given",
"taskfileinfo"
] | python | train |
miguelgrinberg/Flask-SocketIO | flask_socketio/__init__.py | https://github.com/miguelgrinberg/Flask-SocketIO/blob/4bef800d5e7ba7d98a6f4cd94191ff0b4496c334/flask_socketio/__init__.py#L235-L266 | def on(self, message, namespace=None):
"""Decorator to register a SocketIO event handler.
This decorator must be applied to SocketIO event handlers. Example::
@socketio.on('my event', namespace='/chat')
def handle_my_custom_event(json):
print('received json: ' +... | [
"def",
"on",
"(",
"self",
",",
"message",
",",
"namespace",
"=",
"None",
")",
":",
"namespace",
"=",
"namespace",
"or",
"'/'",
"def",
"decorator",
"(",
"handler",
")",
":",
"def",
"_handler",
"(",
"sid",
",",
"*",
"args",
")",
":",
"return",
"self",
... | Decorator to register a SocketIO event handler.
This decorator must be applied to SocketIO event handlers. Example::
@socketio.on('my event', namespace='/chat')
def handle_my_custom_event(json):
print('received json: ' + str(json))
:param message: The name of t... | [
"Decorator",
"to",
"register",
"a",
"SocketIO",
"event",
"handler",
"."
] | python | train |
tensorpack/tensorpack | examples/DeepQNetwork/atari.py | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/DeepQNetwork/atari.py#L103-L108 | def _grab_raw_image(self):
"""
:returns: the current 3-channel image
"""
m = self.ale.getScreenRGB()
return m.reshape((self.height, self.width, 3)) | [
"def",
"_grab_raw_image",
"(",
"self",
")",
":",
"m",
"=",
"self",
".",
"ale",
".",
"getScreenRGB",
"(",
")",
"return",
"m",
".",
"reshape",
"(",
"(",
"self",
".",
"height",
",",
"self",
".",
"width",
",",
"3",
")",
")"
] | :returns: the current 3-channel image | [
":",
"returns",
":",
"the",
"current",
"3",
"-",
"channel",
"image"
] | python | train |
raamana/mrivis | mrivis/workflow.py | https://github.com/raamana/mrivis/blob/199ad096b8a1d825f69109e7218a81b2f1cec756/mrivis/workflow.py#L597-L632 | def _generic_mixer(slice1, slice2, mixer_name, **kwargs):
"""
Generic mixer to process two slices with appropriate mixer
and return the composite to be displayed.
"""
mixer_name = mixer_name.lower()
if mixer_name in ['color_mix', 'rgb']:
mixed = _mix_color(slice1, slice2, **kwargs)
... | [
"def",
"_generic_mixer",
"(",
"slice1",
",",
"slice2",
",",
"mixer_name",
",",
"*",
"*",
"kwargs",
")",
":",
"mixer_name",
"=",
"mixer_name",
".",
"lower",
"(",
")",
"if",
"mixer_name",
"in",
"[",
"'color_mix'",
",",
"'rgb'",
"]",
":",
"mixed",
"=",
"_... | Generic mixer to process two slices with appropriate mixer
and return the composite to be displayed. | [
"Generic",
"mixer",
"to",
"process",
"two",
"slices",
"with",
"appropriate",
"mixer",
"and",
"return",
"the",
"composite",
"to",
"be",
"displayed",
"."
] | python | train |
bokeh/bokeh | bokeh/models/plots.py | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/plots.py#L300-L315 | def add_tile(self, tile_source, **kw):
''' Adds new ``TileRenderer`` into ``Plot.renderers``
Args:
tile_source (TileSource) : a tile source instance which contain tileset configuration
Keyword Arguments:
Additional keyword arguments are passed on as-is to the tile rende... | [
"def",
"add_tile",
"(",
"self",
",",
"tile_source",
",",
"*",
"*",
"kw",
")",
":",
"tile_renderer",
"=",
"TileRenderer",
"(",
"tile_source",
"=",
"tile_source",
",",
"*",
"*",
"kw",
")",
"self",
".",
"renderers",
".",
"append",
"(",
"tile_renderer",
")",... | Adds new ``TileRenderer`` into ``Plot.renderers``
Args:
tile_source (TileSource) : a tile source instance which contain tileset configuration
Keyword Arguments:
Additional keyword arguments are passed on as-is to the tile renderer
Returns:
TileRenderer : Ti... | [
"Adds",
"new",
"TileRenderer",
"into",
"Plot",
".",
"renderers"
] | python | train |
ManiacalLabs/BiblioPixel | bibliopixel/layout/matrix_drawing.py | https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/layout/matrix_drawing.py#L258-L270 | def draw_round_rect(setter, x, y, w, h, r, color=None, aa=False):
"""Draw rectangle with top-left corner at x,y, width w, height h,
and corner radius r.
"""
_draw_fast_hline(setter, x + r, y, w - 2 * r, color, aa) # Top
_draw_fast_hline(setter, x + r, y + h - 1, w - 2 * r, color, aa) # Bottom
... | [
"def",
"draw_round_rect",
"(",
"setter",
",",
"x",
",",
"y",
",",
"w",
",",
"h",
",",
"r",
",",
"color",
"=",
"None",
",",
"aa",
"=",
"False",
")",
":",
"_draw_fast_hline",
"(",
"setter",
",",
"x",
"+",
"r",
",",
"y",
",",
"w",
"-",
"2",
"*",... | Draw rectangle with top-left corner at x,y, width w, height h,
and corner radius r. | [
"Draw",
"rectangle",
"with",
"top",
"-",
"left",
"corner",
"at",
"x",
"y",
"width",
"w",
"height",
"h",
"and",
"corner",
"radius",
"r",
"."
] | python | valid |
minio/minio-py | minio/api.py | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L978-L1012 | def stat_object(self, bucket_name, object_name, sse=None):
"""
Check if an object exists.
:param bucket_name: Bucket of object.
:param object_name: Name of object
:return: Object metadata if object exists
"""
headers = {}
if sse:
is_valid_sse... | [
"def",
"stat_object",
"(",
"self",
",",
"bucket_name",
",",
"object_name",
",",
"sse",
"=",
"None",
")",
":",
"headers",
"=",
"{",
"}",
"if",
"sse",
":",
"is_valid_sse_c_object",
"(",
"sse",
"=",
"sse",
")",
"headers",
".",
"update",
"(",
"sse",
".",
... | Check if an object exists.
:param bucket_name: Bucket of object.
:param object_name: Name of object
:return: Object metadata if object exists | [
"Check",
"if",
"an",
"object",
"exists",
"."
] | python | train |
aio-libs/aioodbc | aioodbc/cursor.py | https://github.com/aio-libs/aioodbc/blob/01245560828d4adce0d7d16930fa566102322a0a/aioodbc/cursor.py#L212-L223 | def columns(self, **kw):
"""Creates a results set of column names in specified tables by
executing the ODBC SQLColumns function. Each row fetched has the
following columns.
:param table: the table tname
:param catalog: the catalog name
:param schema: the schmea name
... | [
"def",
"columns",
"(",
"self",
",",
"*",
"*",
"kw",
")",
":",
"fut",
"=",
"self",
".",
"_run_operation",
"(",
"self",
".",
"_impl",
".",
"columns",
",",
"*",
"*",
"kw",
")",
"return",
"fut"
] | Creates a results set of column names in specified tables by
executing the ODBC SQLColumns function. Each row fetched has the
following columns.
:param table: the table tname
:param catalog: the catalog name
:param schema: the schmea name
:param column: string search pat... | [
"Creates",
"a",
"results",
"set",
"of",
"column",
"names",
"in",
"specified",
"tables",
"by",
"executing",
"the",
"ODBC",
"SQLColumns",
"function",
".",
"Each",
"row",
"fetched",
"has",
"the",
"following",
"columns",
"."
] | python | train |
sorend/sshconf | sshconf.py | https://github.com/sorend/sshconf/blob/59f3fc165b1ba9e76ba23444b1205d88462938f3/sshconf.py#L237-L250 | def unset(self, host, *args):
"""
Removes settings for a host.
Parameters
----------
host : the host to remove settings from.
*args : list of settings to removes.
"""
self.__check_host_args(host, args)
remove_idx = [idx for idx, x in enumerate(sel... | [
"def",
"unset",
"(",
"self",
",",
"host",
",",
"*",
"args",
")",
":",
"self",
".",
"__check_host_args",
"(",
"host",
",",
"args",
")",
"remove_idx",
"=",
"[",
"idx",
"for",
"idx",
",",
"x",
"in",
"enumerate",
"(",
"self",
".",
"lines_",
")",
"if",
... | Removes settings for a host.
Parameters
----------
host : the host to remove settings from.
*args : list of settings to removes. | [
"Removes",
"settings",
"for",
"a",
"host",
"."
] | python | train |
googleapis/google-cloud-python | oslogin/google/cloud/oslogin_v1/gapic/os_login_service_client.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/oslogin/google/cloud/oslogin_v1/gapic/os_login_service_client.py#L81-L85 | def project_path(cls, user, project):
"""Return a fully-qualified project string."""
return google.api_core.path_template.expand(
"users/{user}/projects/{project}", user=user, project=project
) | [
"def",
"project_path",
"(",
"cls",
",",
"user",
",",
"project",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"users/{user}/projects/{project}\"",
",",
"user",
"=",
"user",
",",
"project",
"=",
"project",
")"
] | Return a fully-qualified project string. | [
"Return",
"a",
"fully",
"-",
"qualified",
"project",
"string",
"."
] | python | train |
nerdvegas/rez | src/rez/vendor/amqp/channel.py | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/channel.py#L1677-L1798 | def basic_consume(self, queue='', consumer_tag='', no_local=False,
no_ack=False, exclusive=False, nowait=False,
callback=None, arguments=None, on_cancel=None):
"""Start a queue consumer
This method asks the server to start a "consumer", which is a
tra... | [
"def",
"basic_consume",
"(",
"self",
",",
"queue",
"=",
"''",
",",
"consumer_tag",
"=",
"''",
",",
"no_local",
"=",
"False",
",",
"no_ack",
"=",
"False",
",",
"exclusive",
"=",
"False",
",",
"nowait",
"=",
"False",
",",
"callback",
"=",
"None",
",",
... | Start a queue consumer
This method asks the server to start a "consumer", which is a
transient request for messages from a specific queue.
Consumers last as long as the channel they were created on, or
until the client cancels them.
RULE:
The server SHOULD support ... | [
"Start",
"a",
"queue",
"consumer"
] | python | train |
fermiPy/fermipy | fermipy/wcs_utils.py | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/wcs_utils.py#L185-L212 | def wcs_add_energy_axis(wcs, energies):
"""Copy a WCS object, and add on the energy axis.
Parameters
----------
wcs : `~astropy.wcs.WCS`
WCS
energies : array-like
Array of energies.
"""
if wcs.naxis != 2:
raise Exception(
'wcs_add_energy_axis, input WCS na... | [
"def",
"wcs_add_energy_axis",
"(",
"wcs",
",",
"energies",
")",
":",
"if",
"wcs",
".",
"naxis",
"!=",
"2",
":",
"raise",
"Exception",
"(",
"'wcs_add_energy_axis, input WCS naxis != 2 %i'",
"%",
"wcs",
".",
"naxis",
")",
"w",
"=",
"WCS",
"(",
"naxis",
"=",
... | Copy a WCS object, and add on the energy axis.
Parameters
----------
wcs : `~astropy.wcs.WCS`
WCS
energies : array-like
Array of energies. | [
"Copy",
"a",
"WCS",
"object",
"and",
"add",
"on",
"the",
"energy",
"axis",
"."
] | python | train |
hvac/hvac | hvac/api/auth_methods/gcp.py | https://github.com/hvac/hvac/blob/cce5b86889193f622c2a72a4a1b7e1c9c8aff1ce/hvac/api/auth_methods/gcp.py#L366-L398 | def login(self, role, jwt, use_token=True, mount_point=DEFAULT_MOUNT_POINT):
"""Login to retrieve a Vault token via the GCP auth method.
This endpoint takes a signed JSON Web Token (JWT) and a role name for some entity. It verifies the JWT
signature with Google Cloud to authenticate that en... | [
"def",
"login",
"(",
"self",
",",
"role",
",",
"jwt",
",",
"use_token",
"=",
"True",
",",
"mount_point",
"=",
"DEFAULT_MOUNT_POINT",
")",
":",
"params",
"=",
"{",
"'role'",
":",
"role",
",",
"'jwt'",
":",
"jwt",
",",
"}",
"api_path",
"=",
"'/v1/auth/{m... | Login to retrieve a Vault token via the GCP auth method.
This endpoint takes a signed JSON Web Token (JWT) and a role name for some entity. It verifies the JWT
signature with Google Cloud to authenticate that entity and then authorizes the entity for the given role.
Supported methods:
... | [
"Login",
"to",
"retrieve",
"a",
"Vault",
"token",
"via",
"the",
"GCP",
"auth",
"method",
"."
] | python | train |
delph-in/pydelphin | delphin/derivation.py | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/derivation.py#L138-L162 | def to_dict(self, fields=_all_fields, labels=None):
"""
Encode the node as a dictionary suitable for JSON serialization.
Args:
fields: if given, this is a whitelist of fields to include
on nodes (`daughters` and `form` are always shown)
labels: optional l... | [
"def",
"to_dict",
"(",
"self",
",",
"fields",
"=",
"_all_fields",
",",
"labels",
"=",
"None",
")",
":",
"fields",
"=",
"set",
"(",
"fields",
")",
"diff",
"=",
"fields",
".",
"difference",
"(",
"_all_fields",
")",
"if",
"isinstance",
"(",
"labels",
",",... | Encode the node as a dictionary suitable for JSON serialization.
Args:
fields: if given, this is a whitelist of fields to include
on nodes (`daughters` and `form` are always shown)
labels: optional label annotations to embed in the
derivation dict; the va... | [
"Encode",
"the",
"node",
"as",
"a",
"dictionary",
"suitable",
"for",
"JSON",
"serialization",
"."
] | python | train |
zhanglab/psamm | psamm/lpsolver/gurobi.py | https://github.com/zhanglab/psamm/blob/dc427848c4f9d109ca590f0afa024c63b685b3f4/psamm/lpsolver/gurobi.py#L333-L336 | def success(self):
"""Return boolean indicating whether a solution was found."""
self._check_valid()
return self._problem._p.Status == gurobipy.GRB.OPTIMAL | [
"def",
"success",
"(",
"self",
")",
":",
"self",
".",
"_check_valid",
"(",
")",
"return",
"self",
".",
"_problem",
".",
"_p",
".",
"Status",
"==",
"gurobipy",
".",
"GRB",
".",
"OPTIMAL"
] | Return boolean indicating whether a solution was found. | [
"Return",
"boolean",
"indicating",
"whether",
"a",
"solution",
"was",
"found",
"."
] | python | train |
androguard/androguard | androguard/decompiler/dad/graph.py | https://github.com/androguard/androguard/blob/984c0d981be2950cf0451e484f7b0d4d53bc4911/androguard/decompiler/dad/graph.py#L212-L272 | def split_if_nodes(graph):
"""
Split IfNodes in two nodes, the first node is the header node, the
second one is only composed of the jump condition.
"""
node_map = {n: n for n in graph}
to_update = set()
for node in graph.nodes[:]:
if node.type.is_cond:
if len(node.get_in... | [
"def",
"split_if_nodes",
"(",
"graph",
")",
":",
"node_map",
"=",
"{",
"n",
":",
"n",
"for",
"n",
"in",
"graph",
"}",
"to_update",
"=",
"set",
"(",
")",
"for",
"node",
"in",
"graph",
".",
"nodes",
"[",
":",
"]",
":",
"if",
"node",
".",
"type",
... | Split IfNodes in two nodes, the first node is the header node, the
second one is only composed of the jump condition. | [
"Split",
"IfNodes",
"in",
"two",
"nodes",
"the",
"first",
"node",
"is",
"the",
"header",
"node",
"the",
"second",
"one",
"is",
"only",
"composed",
"of",
"the",
"jump",
"condition",
"."
] | python | train |
pyvisa/pyvisa-sim | pyvisa-sim/channels.py | https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/channels.py#L30-L35 | def init_value(self, string_value):
"""Create an empty defaultdict holding the default value.
"""
value = self.validate_value(string_value)
self._value = defaultdict(lambda: value) | [
"def",
"init_value",
"(",
"self",
",",
"string_value",
")",
":",
"value",
"=",
"self",
".",
"validate_value",
"(",
"string_value",
")",
"self",
".",
"_value",
"=",
"defaultdict",
"(",
"lambda",
":",
"value",
")"
] | Create an empty defaultdict holding the default value. | [
"Create",
"an",
"empty",
"defaultdict",
"holding",
"the",
"default",
"value",
"."
] | python | train |
google/transitfeed | transitfeed/trip.py | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/trip.py#L227-L256 | def GetStopTimes(self, problems=None):
"""Return a sorted list of StopTime objects for this trip."""
# In theory problems=None should be safe because data from database has been
# validated. See comment in _LoadStopTimes for why this isn't always true.
cursor = self._schedule._connection.cursor()
cu... | [
"def",
"GetStopTimes",
"(",
"self",
",",
"problems",
"=",
"None",
")",
":",
"# In theory problems=None should be safe because data from database has been",
"# validated. See comment in _LoadStopTimes for why this isn't always true.",
"cursor",
"=",
"self",
".",
"_schedule",
".",
... | Return a sorted list of StopTime objects for this trip. | [
"Return",
"a",
"sorted",
"list",
"of",
"StopTime",
"objects",
"for",
"this",
"trip",
"."
] | python | train |
inspirehep/inspire-query-parser | inspire_query_parser/parser.py | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/parser.py#L534-L543 | def parse(cls, parser, text, pos):
"""Using our own parse to enable the flag below."""
try:
parser._parsing_parenthesized_simple_values_expression = True
remaining_text, recognized_tokens = parser.parse(text, cls.grammar)
return remaining_text, recognized_tokens
... | [
"def",
"parse",
"(",
"cls",
",",
"parser",
",",
"text",
",",
"pos",
")",
":",
"try",
":",
"parser",
".",
"_parsing_parenthesized_simple_values_expression",
"=",
"True",
"remaining_text",
",",
"recognized_tokens",
"=",
"parser",
".",
"parse",
"(",
"text",
",",
... | Using our own parse to enable the flag below. | [
"Using",
"our",
"own",
"parse",
"to",
"enable",
"the",
"flag",
"below",
"."
] | python | train |
geertj/pyskiplist | pyskiplist/skiplist.py | https://github.com/geertj/pyskiplist/blob/c5f94cf135d42bb277255150d3f570ed807468b2/pyskiplist/skiplist.py#L279-L290 | def replace(self, key, value):
"""Replace the value of the first key-value pair with key *key*.
If the key was not found, the pair is inserted.
"""
self._find_lt(key)
node = self._path[0][2]
if node is self._tail or key < node[0]:
node = self._create_node(key... | [
"def",
"replace",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"self",
".",
"_find_lt",
"(",
"key",
")",
"node",
"=",
"self",
".",
"_path",
"[",
"0",
"]",
"[",
"2",
"]",
"if",
"node",
"is",
"self",
".",
"_tail",
"or",
"key",
"<",
"node",
... | Replace the value of the first key-value pair with key *key*.
If the key was not found, the pair is inserted. | [
"Replace",
"the",
"value",
"of",
"the",
"first",
"key",
"-",
"value",
"pair",
"with",
"key",
"*",
"key",
"*",
"."
] | python | train |
armstrong/armstrong.hatband | armstrong/hatband/views/search.py | https://github.com/armstrong/armstrong.hatband/blob/b34027c85a8ccfe2ee37aa9348d98e143d300082/armstrong/hatband/views/search.py#L88-L102 | def generic_key_modelsearch(self, request, app_label, model_name):
"""
Find instances for the requested model and return them as JSON.
# TODO: add test coverage for this
We don't have to worry about invalid app_label/model_name parameters
because the URLs are pre-built with the ... | [
"def",
"generic_key_modelsearch",
"(",
"self",
",",
"request",
",",
"app_label",
",",
"model_name",
")",
":",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get",
"(",
"app_label",
"=",
"app_label",
",",
"model",
"=",
"model_name",
")",
"model",
"... | Find instances for the requested model and return them as JSON.
# TODO: add test coverage for this
We don't have to worry about invalid app_label/model_name parameters
because the URLs are pre-built with the kwargs in `get_urls()`. | [
"Find",
"instances",
"for",
"the",
"requested",
"model",
"and",
"return",
"them",
"as",
"JSON",
".",
"#",
"TODO",
":",
"add",
"test",
"coverage",
"for",
"this"
] | python | train |
CalebBell/thermo | thermo/utils.py | https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/utils.py#L2113-L2139 | def calculate_derivative(self, T, method, order=1):
r'''Method to calculate a derivative of a property with respect to
temperature, of a given order using a specified method. Uses SciPy's
derivative function, with a delta of 1E-6 K and a number of points
equal to 2*order + 1.
... | [
"def",
"calculate_derivative",
"(",
"self",
",",
"T",
",",
"method",
",",
"order",
"=",
"1",
")",
":",
"return",
"derivative",
"(",
"self",
".",
"calculate",
",",
"T",
",",
"dx",
"=",
"1e-6",
",",
"args",
"=",
"[",
"method",
"]",
",",
"n",
"=",
"... | r'''Method to calculate a derivative of a property with respect to
temperature, of a given order using a specified method. Uses SciPy's
derivative function, with a delta of 1E-6 K and a number of points
equal to 2*order + 1.
This method can be overwritten by subclasses who may perfe... | [
"r",
"Method",
"to",
"calculate",
"a",
"derivative",
"of",
"a",
"property",
"with",
"respect",
"to",
"temperature",
"of",
"a",
"given",
"order",
"using",
"a",
"specified",
"method",
".",
"Uses",
"SciPy",
"s",
"derivative",
"function",
"with",
"a",
"delta",
... | python | valid |
Duke-GCB/DukeDSClient | ddsc/config.py | https://github.com/Duke-GCB/DukeDSClient/blob/117f68fb9bae82e4c81ea487ad5d61ac350f3726/ddsc/config.py#L188-L201 | def parse_bytes_str(value):
"""
Given a value return the integer number of bytes it represents.
Trailing "MB" causes the value multiplied by 1024*1024
:param value:
:return: int number of bytes represented by value.
"""
if type(value) == str:
if "MB" i... | [
"def",
"parse_bytes_str",
"(",
"value",
")",
":",
"if",
"type",
"(",
"value",
")",
"==",
"str",
":",
"if",
"\"MB\"",
"in",
"value",
":",
"return",
"int",
"(",
"value",
".",
"replace",
"(",
"\"MB\"",
",",
"\"\"",
")",
")",
"*",
"MB_TO_BYTES",
"else",
... | Given a value return the integer number of bytes it represents.
Trailing "MB" causes the value multiplied by 1024*1024
:param value:
:return: int number of bytes represented by value. | [
"Given",
"a",
"value",
"return",
"the",
"integer",
"number",
"of",
"bytes",
"it",
"represents",
".",
"Trailing",
"MB",
"causes",
"the",
"value",
"multiplied",
"by",
"1024",
"*",
"1024",
":",
"param",
"value",
":",
":",
"return",
":",
"int",
"number",
"of... | python | train |
oceanprotocol/aquarius | aquarius/app/assets.py | https://github.com/oceanprotocol/aquarius/blob/9fb094b1ac01f0604d0c854166dd324e476a010e/aquarius/app/assets.py#L26-L41 | def get_assets():
"""Get all asset IDs.
---
tags:
- ddo
responses:
200:
description: successful action
"""
args = []
query = dict()
args.append(query)
asset_with_id = dao.get_all_listed_assets()
asset_ids = [a['id'] for a in asset_with_id]
resp_body = dict... | [
"def",
"get_assets",
"(",
")",
":",
"args",
"=",
"[",
"]",
"query",
"=",
"dict",
"(",
")",
"args",
".",
"append",
"(",
"query",
")",
"asset_with_id",
"=",
"dao",
".",
"get_all_listed_assets",
"(",
")",
"asset_ids",
"=",
"[",
"a",
"[",
"'id'",
"]",
... | Get all asset IDs.
---
tags:
- ddo
responses:
200:
description: successful action | [
"Get",
"all",
"asset",
"IDs",
".",
"---",
"tags",
":",
"-",
"ddo",
"responses",
":",
"200",
":",
"description",
":",
"successful",
"action"
] | python | train |
HydraChain/hydrachain | hydrachain/consensus/base.py | https://github.com/HydraChain/hydrachain/blob/6c0919b0575dc8aa481f3a8c703e1a7f0575ecc3/hydrachain/consensus/base.py#L393-L395 | def to_block(self, env, parent=None):
"""Convert the transient block to a :class:`ethereum.blocks.Block`"""
return Block(self.header, self.transaction_list, self.uncles, env=env, parent=parent) | [
"def",
"to_block",
"(",
"self",
",",
"env",
",",
"parent",
"=",
"None",
")",
":",
"return",
"Block",
"(",
"self",
".",
"header",
",",
"self",
".",
"transaction_list",
",",
"self",
".",
"uncles",
",",
"env",
"=",
"env",
",",
"parent",
"=",
"parent",
... | Convert the transient block to a :class:`ethereum.blocks.Block` | [
"Convert",
"the",
"transient",
"block",
"to",
"a",
":",
"class",
":",
"ethereum",
".",
"blocks",
".",
"Block"
] | python | test |
dgketchum/satellite_image | sat_image/fmask.py | https://github.com/dgketchum/satellite_image/blob/0207fbb7b2bbf14f4307db65489bb4d4c5b92f52/sat_image/fmask.py#L365-L395 | def variability_prob(self, whiteness):
"""Use the probability of the spectral variability
to identify clouds over land.
Equation 15 (Zhu and Woodcock, 2012)
Parameters
----------
ndvi: ndarray
ndsi: ndarray
whiteness: ndarray
Output
------
... | [
"def",
"variability_prob",
"(",
"self",
",",
"whiteness",
")",
":",
"if",
"self",
".",
"sat",
"in",
"[",
"'LT5'",
",",
"'LE7'",
"]",
":",
"# check for green and red saturation",
"# if red is saturated and less than nir, ndvi = LE07_clip_L1TP_039027_20150529_20160902_01_T1_B1.... | Use the probability of the spectral variability
to identify clouds over land.
Equation 15 (Zhu and Woodcock, 2012)
Parameters
----------
ndvi: ndarray
ndsi: ndarray
whiteness: ndarray
Output
------
ndarray :
probability of cloud... | [
"Use",
"the",
"probability",
"of",
"the",
"spectral",
"variability",
"to",
"identify",
"clouds",
"over",
"land",
".",
"Equation",
"15",
"(",
"Zhu",
"and",
"Woodcock",
"2012",
")",
"Parameters",
"----------",
"ndvi",
":",
"ndarray",
"ndsi",
":",
"ndarray",
"w... | python | train |
mdiener/grace | grace/py27/pyjsdoc.py | https://github.com/mdiener/grace/blob/2dab13a2cf636da5da989904c5885166fc94d36d/grace/py27/pyjsdoc.py#L140-L153 | def save_file(path, text):
"""
Save a string to a file. If the containing directory(ies) doesn't exist,
this creates it.
"""
dir = os.path.dirname(path)
if not os.path.exists(dir):
os.makedirs(dir)
fd = open(path, 'w')
try:
fd.write(text)
finally:
fd.close() | [
"def",
"save_file",
"(",
"path",
",",
"text",
")",
":",
"dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dir",
")",
":",
"os",
".",
"makedirs",
"(",
"dir",
")",
"fd",
"=",
"... | Save a string to a file. If the containing directory(ies) doesn't exist,
this creates it. | [
"Save",
"a",
"string",
"to",
"a",
"file",
".",
"If",
"the",
"containing",
"directory",
"(",
"ies",
")",
"doesn",
"t",
"exist",
"this",
"creates",
"it",
"."
] | python | train |
rauenzi/discordbot.py | discordbot/cogs/botadmin.py | https://github.com/rauenzi/discordbot.py/blob/39bb98dae4e49487e6c6c597f85fc41c74b62bb8/discordbot/cogs/botadmin.py#L197-L208 | async def ignore(self, ctx):
"""Handles the bot's ignore lists.
To use these commands, you must have the Bot Admin role or have
Manage Channels permissions. These commands are not allowed to be used
in a private message context.
Users with Manage Roles or Bot Admin role can sti... | [
"async",
"def",
"ignore",
"(",
"self",
",",
"ctx",
")",
":",
"if",
"ctx",
".",
"invoked_subcommand",
"is",
"None",
":",
"await",
"self",
".",
"bot",
".",
"say",
"(",
"'Invalid subcommand passed: {0.subcommand_passed}'",
".",
"format",
"(",
"ctx",
")",
")"
] | Handles the bot's ignore lists.
To use these commands, you must have the Bot Admin role or have
Manage Channels permissions. These commands are not allowed to be used
in a private message context.
Users with Manage Roles or Bot Admin role can still invoke the bot
in ignored cha... | [
"Handles",
"the",
"bot",
"s",
"ignore",
"lists",
"."
] | python | train |
sorgerlab/indra | indra/sources/eidos/cli.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/eidos/cli.py#L41-L58 | def extract_from_directory(path_in, path_out):
"""Run Eidos on a set of text files in a folder.
The output is produced in the specified output folder but
the output files aren't processed by this function.
Parameters
----------
path_in : str
Path to an input folder with some text files... | [
"def",
"extract_from_directory",
"(",
"path_in",
",",
"path_out",
")",
":",
"path_in",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"path_in",
")",
")",
"path_out",
"=",
"os",
".",
"path",
".",
"realpath",
"(... | Run Eidos on a set of text files in a folder.
The output is produced in the specified output folder but
the output files aren't processed by this function.
Parameters
----------
path_in : str
Path to an input folder with some text files
path_out : str
Path to an output folder i... | [
"Run",
"Eidos",
"on",
"a",
"set",
"of",
"text",
"files",
"in",
"a",
"folder",
"."
] | python | train |
RudolfCardinal/pythonlib | cardinal_pythonlib/tools/merge_csv.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tools/merge_csv.py#L45-L94 | def merge_csv(filenames: List[str],
outfile: TextIO = sys.stdout,
input_dialect: str = 'excel',
output_dialect: str = 'excel',
debug: bool = False,
headers: bool = True) -> None:
"""
Amalgamate multiple CSV/TSV/similar files into one.
Ar... | [
"def",
"merge_csv",
"(",
"filenames",
":",
"List",
"[",
"str",
"]",
",",
"outfile",
":",
"TextIO",
"=",
"sys",
".",
"stdout",
",",
"input_dialect",
":",
"str",
"=",
"'excel'",
",",
"output_dialect",
":",
"str",
"=",
"'excel'",
",",
"debug",
":",
"bool"... | Amalgamate multiple CSV/TSV/similar files into one.
Args:
filenames: list of filenames to process
outfile: file-like object to write output to
input_dialect: dialect of input files, as passed to ``csv.reader``
output_dialect: dialect to write, as passed to ``csv.writer``
deb... | [
"Amalgamate",
"multiple",
"CSV",
"/",
"TSV",
"/",
"similar",
"files",
"into",
"one",
"."
] | python | train |
secdev/scapy | scapy/layers/inet6.py | https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/layers/inet6.py#L299-L329 | def extract_padding(self, data):
"""Extract the IPv6 payload"""
if self.plen == 0 and self.nh == 0 and len(data) >= 8:
# Extract Hop-by-Hop extension length
hbh_len = orb(data[1])
hbh_len = 8 + hbh_len * 8
# Extract length from the Jumbogram option
... | [
"def",
"extract_padding",
"(",
"self",
",",
"data",
")",
":",
"if",
"self",
".",
"plen",
"==",
"0",
"and",
"self",
".",
"nh",
"==",
"0",
"and",
"len",
"(",
"data",
")",
">=",
"8",
":",
"# Extract Hop-by-Hop extension length",
"hbh_len",
"=",
"orb",
"("... | Extract the IPv6 payload | [
"Extract",
"the",
"IPv6",
"payload"
] | python | train |
tornadoweb/tornado | tornado/ioloop.py | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/ioloop.py#L735-L763 | def _run_callback(self, callback: Callable[[], Any]) -> None:
"""Runs a callback with error handling.
.. versionchanged:: 6.0
CancelledErrors are no longer logged.
"""
try:
ret = callback()
if ret is not None:
from tornado import gen
... | [
"def",
"_run_callback",
"(",
"self",
",",
"callback",
":",
"Callable",
"[",
"[",
"]",
",",
"Any",
"]",
")",
"->",
"None",
":",
"try",
":",
"ret",
"=",
"callback",
"(",
")",
"if",
"ret",
"is",
"not",
"None",
":",
"from",
"tornado",
"import",
"gen",
... | Runs a callback with error handling.
.. versionchanged:: 6.0
CancelledErrors are no longer logged. | [
"Runs",
"a",
"callback",
"with",
"error",
"handling",
"."
] | python | train |
pyviz/holoviews | holoviews/core/data/__init__.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/core/data/__init__.py#L219-L247 | def closest(self, coords=[], **kwargs):
"""Snaps coordinate(s) to closest coordinate in Dataset
Args:
coords: List of coordinates expressed as tuples
**kwargs: Coordinates defined as keyword pairs
Returns:
List of tuples of the snapped coordinates
R... | [
"def",
"closest",
"(",
"self",
",",
"coords",
"=",
"[",
"]",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"ndims",
">",
"1",
":",
"raise",
"NotImplementedError",
"(",
"\"Closest method currently only \"",
"\"implemented for 1D Elements\"",
")",
"if",
... | Snaps coordinate(s) to closest coordinate in Dataset
Args:
coords: List of coordinates expressed as tuples
**kwargs: Coordinates defined as keyword pairs
Returns:
List of tuples of the snapped coordinates
Raises:
NotImplementedError: Raised if s... | [
"Snaps",
"coordinate",
"(",
"s",
")",
"to",
"closest",
"coordinate",
"in",
"Dataset"
] | python | train |
freelawproject/reporters-db | reporters_db/utils.py | https://github.com/freelawproject/reporters-db/blob/ee17ee38a4e39de8d83beb78d84d146cd7e8afbc/reporters_db/utils.py#L7-L34 | def suck_out_variations_only(reporters):
"""Builds a dictionary of variations to canonical reporters.
The dictionary takes the form of:
{
"A. 2d": ["A.2d"],
...
"P.R.": ["Pen. & W.", "P.R.R.", "P."],
}
In other words, it's a dictionary that maps each variation to... | [
"def",
"suck_out_variations_only",
"(",
"reporters",
")",
":",
"variations_out",
"=",
"{",
"}",
"for",
"reporter_key",
",",
"data_list",
"in",
"reporters",
".",
"items",
"(",
")",
":",
"# For each reporter key...",
"for",
"data",
"in",
"data_list",
":",
"# For e... | Builds a dictionary of variations to canonical reporters.
The dictionary takes the form of:
{
"A. 2d": ["A.2d"],
...
"P.R.": ["Pen. & W.", "P.R.R.", "P."],
}
In other words, it's a dictionary that maps each variation to a list of
reporters that it could be possib... | [
"Builds",
"a",
"dictionary",
"of",
"variations",
"to",
"canonical",
"reporters",
"."
] | python | train |
inspirehep/inspire-dojson | inspire_dojson/hep/rules/bd7xx.py | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hep/rules/bd7xx.py#L49-L63 | def collaborations(self, key, value):
"""Populate the ``collaborations`` key."""
result = []
for g_value in force_list(value.get('g')):
collaborations = normalize_collaboration(g_value)
if len(collaborations) == 1:
result.append({
'record': get_record_ref(maybe_i... | [
"def",
"collaborations",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"result",
"=",
"[",
"]",
"for",
"g_value",
"in",
"force_list",
"(",
"value",
".",
"get",
"(",
"'g'",
")",
")",
":",
"collaborations",
"=",
"normalize_collaboration",
"(",
"g_value"... | Populate the ``collaborations`` key. | [
"Populate",
"the",
"collaborations",
"key",
"."
] | python | train |
materialsproject/pymatgen | pymatgen/io/abinit/flows.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/flows.py#L648-L658 | def iflat_tasks(self, status=None, op="==", nids=None):
"""
Generator to iterate over all the tasks of the :class:`Flow`.
If status is not None, only the tasks whose status satisfies
the condition (task.status op status) are selected
status can be either one of the flags defined... | [
"def",
"iflat_tasks",
"(",
"self",
",",
"status",
"=",
"None",
",",
"op",
"=",
"\"==\"",
",",
"nids",
"=",
"None",
")",
":",
"return",
"self",
".",
"_iflat_tasks_wti",
"(",
"status",
"=",
"status",
",",
"op",
"=",
"op",
",",
"nids",
"=",
"nids",
",... | Generator to iterate over all the tasks of the :class:`Flow`.
If status is not None, only the tasks whose status satisfies
the condition (task.status op status) are selected
status can be either one of the flags defined in the :class:`Task` class
(e.g Task.S_OK) or a string e.g "S_OK"
... | [
"Generator",
"to",
"iterate",
"over",
"all",
"the",
"tasks",
"of",
"the",
":",
"class",
":",
"Flow",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.