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 key
:param kwargs: Extra keyword arguments
:return: An encrypted JWT
"""
_msg = as_bytes(self.msg)
_args = self._dict
try:
_args["kid"] = kwargs["kid"]
except KeyError:
pass
if 'params' in kwargs:
if 'apu' in kwargs['params']:
_args['apu'] = kwargs['params']['apu']
if 'apv' in kwargs['params']:
_args['apv'] = kwargs['params']['apv']
if 'epk' in kwargs['params']:
_args['epk'] = kwargs['params']['epk']
jwe = JWEnc(**_args)
ctxt, tag, cek = super(JWE_EC, self).enc_setup(
self["enc"], _msg, auth_data=jwe.b64_encode_header(), key=cek,
iv=iv)
if 'encrypted_key' in kwargs:
return jwe.pack(parts=[kwargs['encrypted_key'], iv, ctxt, tag])
return jwe.pack(parts=[iv, ctxt, tag]) | [
"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 encrypted JWT | [
"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_deployment(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.delete_collection_namespaced_deployment_with_http_info(namespace, **kwargs)
else:
(data) = self.delete_collection_namespaced_deployment_with_http_info(namespace, **kwargs)
return data | [
"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_req bool
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:return: V1Status
If the method is called asynchronously,
returns the request thread. | [
"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'],
name=json_obj['companyName'],
description=json_obj['companyDescription'],
application_ids=json_obj['companyApplicationsID'],
ost_ids=json_obj['companyOSTypesID']) | [
"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:
return self.filter(**{"author__{}__in".format(User.USERNAME_FIELD): usernames}) | [
"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).
"""
job_semaphore = threading.Semaphore(0)
def manage_output(result, grade, problems, tests, custom, state, archive, stdout, stderr):
""" Manages the output of this job """
manage_output.job_return = (result, grade, problems, tests, custom, state, archive, stdout, stderr)
job_semaphore.release()
manage_output.job_return = None
self._client.new_job(task, inputdata, manage_output, launcher_name, debug)
job_semaphore.acquire()
job_return = manage_output.job_return
return job_return | [
"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=AT,CN=example.com)>
"""
if isinstance(name, six.string_types):
name = parse_name(name)
return x509.Name([x509.NameAttribute(NAME_OID_MAPPINGS[typ], force_text(value)) for typ, value in name]) | [
"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).
Parameters
----------
heap : array of shape (3, n_samples, n_neighbors)
The heap to turn into sorted lists.
Returns
-------
indices, weights: arrays of shape (n_samples, n_neighbors)
The indices and weights sorted by increasing weight.
"""
indices = heap[0]
weights = heap[1]
for i in range(indices.shape[0]):
ind_heap = indices[i]
dist_heap = weights[i]
for j in range(ind_heap.shape[0] - 1):
ind_heap[0], ind_heap[ind_heap.shape[0] - j - 1] = (
ind_heap[ind_heap.shape[0] - j - 1],
ind_heap[0],
)
dist_heap[0], dist_heap[dist_heap.shape[0] - j - 1] = (
dist_heap[dist_heap.shape[0] - j - 1],
dist_heap[0],
)
siftdown(
dist_heap[: dist_heap.shape[0] - j - 1],
ind_heap[: ind_heap.shape[0] - j - 1],
0,
)
return indices.astype(np.int64), weights | [
"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
----------
heap : array of shape (3, n_samples, n_neighbors)
The heap to turn into sorted lists.
Returns
-------
indices, weights: arrays of shape (n_samples, n_neighbors)
The indices and weights sorted by increasing weight. | [
"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(
tf.float32, shape=[self.n_words, self.n_words])
self.diffs = tf.subtract(self.model, self.log_coincidence)
cost = tf.reduce_sum(
0.5 * tf.multiply(self.weights, tf.square(self.diffs)))
if self.mittens > 0:
self.mittens = tf.constant(self.mittens, tf.float32)
cost += self.mittens * tf.reduce_sum(
tf.multiply(
self.has_embedding,
self._tf_squared_euclidean(
tf.add(self.W, self.C),
self.original_embedding)))
tf.summary.scalar("cost", cost)
return cost | [
"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. it returns a batch of loss values.
"""
if num_classes is not None:
warnings.warn("`num_classes` is depreciated. Switch to `nb_classes`."
" `num_classes` may be removed on or after 2019-04-23.")
nb_classes = num_classes
del num_classes
if 'int' in str(label.dtype):
logit_mask = tf.one_hot(label, depth=nb_classes, axis=-1)
else:
logit_mask = label
if 'int' in str(logit_mask.dtype):
logit_mask = tf.to_float(logit_mask)
try:
label_logits = reduce_sum(logit_mask * model_logits, axis=-1)
except TypeError:
raise TypeError("Could not take row-wise dot product between "
"logit mask, of dtype " + str(logit_mask.dtype)
+ " and model_logits, of dtype "
+ str(model_logits.dtype))
logits_with_target_label_neg_inf = model_logits - logit_mask * 99999
highest_nonlabel_logits = reduce_max(
logits_with_target_label_neg_inf, axis=-1)
loss = highest_nonlabel_logits - label_logits
return loss | [
"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`
"""
params = params_factory(p.schema["properties"], add_message=add_message)
help = p.__doc__
cmd = click.Command(name=name, callback=callback, params=params, help=help)
return cmd | [
"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 case
of a truncated while and non-compressed data).
"""
# read metadata block
m = self.metadata[x, z]
if m.status == STATUS_CHUNK_NOT_CREATED:
raise InconceivedChunk("Chunk %d,%d is not present in region" % (x,z))
elif m.status == STATUS_CHUNK_IN_HEADER:
raise RegionHeaderError('Chunk %d,%d is in the region header' % (x,z))
elif m.status == STATUS_CHUNK_OUT_OF_FILE and (m.length <= 1 or m.compression == None):
# Chunk header is outside of the file.
raise RegionHeaderError('Chunk %d,%d is partially/completely outside the file' % (x,z))
elif m.status == STATUS_CHUNK_ZERO_LENGTH:
if m.blocklength == 0:
raise RegionHeaderError('Chunk %d,%d has zero length' % (x,z))
else:
raise ChunkHeaderError('Chunk %d,%d has zero length' % (x,z))
elif m.blockstart * SECTOR_LENGTH + 5 >= self.size:
raise RegionHeaderError('Chunk %d,%d is partially/completely outside the file' % (x,z))
# status is STATUS_CHUNK_OK, STATUS_CHUNK_MISMATCHED_LENGTHS, STATUS_CHUNK_OVERLAPPING
# or STATUS_CHUNK_OUT_OF_FILE.
# The chunk is always read, but in case of an error, the exception may be different
# based on the status.
err = None
try:
# offset comes in sectors of 4096 bytes + length bytes + compression byte
self.file.seek(m.blockstart * SECTOR_LENGTH + 5)
# Do not read past the length of the file.
# The length in the file includes the compression byte, hence the -1.
length = min(m.length - 1, self.size - (m.blockstart * SECTOR_LENGTH + 5))
chunk = self.file.read(length)
if (m.compression == COMPRESSION_GZIP):
# Python 3.1 and earlier do not yet support gzip.decompress(chunk)
f = gzip.GzipFile(fileobj=BytesIO(chunk))
chunk = bytes(f.read())
f.close()
elif (m.compression == COMPRESSION_ZLIB):
chunk = zlib.decompress(chunk)
elif m.compression != COMPRESSION_NONE:
raise ChunkDataError('Unknown chunk compression/format (%s)' % m.compression)
return chunk
except RegionFileFormatError:
raise
except Exception as e:
# Deliberately catch the Exception and re-raise.
# The details in gzip/zlib/nbt are irrelevant, just that the data is garbled.
err = '%s' % e # avoid str(e) due to Unicode issues in Python 2.
if err:
# don't raise during exception handling to avoid the warning
# "During handling of the above exception, another exception occurred".
# Python 3.3 solution (see PEP 409 & 415): "raise ChunkDataError(str(e)) from None"
if m.status == STATUS_CHUNK_MISMATCHED_LENGTHS:
raise ChunkHeaderError('The length in region header and the length in the header of chunk %d,%d are incompatible' % (x,z))
elif m.status == STATUS_CHUNK_OVERLAPPING:
raise ChunkHeaderError('Chunk %d,%d is overlapping with another chunk' % (x,z))
else:
raise ChunkDataError(err) | [
"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 data). | [
"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 human readable key translations. Defaults
to True.
show_name (:obj:`bool`): Show human readable name (default is to
only show short). Defaults to False.
colorize (:obj:`bool`): Colorize the console output with ANSI
colors. Defaults to True.
Returns:
str: The generated output.
"""
if json_data is None:
json_data = {}
keys = {'asn', 'asn_cidr', 'asn_country_code', 'asn_date',
'asn_registry', 'asn_description'}.intersection(json_data)
output = ''
for key in keys:
output += generate_output(
line='0',
short=HR_ASN[key]['_short'] if hr else key,
name=HR_ASN[key]['_name'] if (hr and show_name) else None,
value=(json_data[key] if (
json_data[key] is not None and
len(json_data[key]) > 0 and
json_data[key] != 'NA') else 'None'),
colorize=colorize
)
return output | [
"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 to
only show short). Defaults to False.
colorize (:obj:`bool`): Colorize the console output with ANSI
colors. Defaults to True.
Returns:
str: The generated output. | [
"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.index(char)) for char in number]) | [
"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 svs:
if svcaller in _get_callers([data], stage):
base = copy.deepcopy(data)
# clean SV callers present in multiple rounds and not this caller
final_svs = []
for sv in data.get("sv", []):
if (stage == "ensemble" or sv["variantcaller"] == svcaller or sv["variantcaller"] not in svs
or svcaller not in _get_callers([data], stage, special_cases=True)):
final_svs.append(sv)
base["sv"] = final_svs
base["config"]["algorithm"]["svcaller"] = svcaller
base["config"]["algorithm"]["svcaller_orig"] = svs
out.append(base)
return out | [
"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 alembic table
metadata, alembic_version = alembic_table_metadata()
metadata.create_all()
item = manager.db.session.query(alembic_version).first()
if item and item.version_num != head:
item.version_num = head
else:
item = alembic_version.insert().values(version_num=head)
item.compile()
conn = manager.db.engine.connect()
conn.execute(item)
manager.db.session.commit()
stdout.write("alembic head is set to %s \n" % head)
except CommandError as e:
stdout.write(e.message) | [
"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 from the real token's validity.
An example usage is that the token can be valid once the middleware
passed, and invalid (timed-out) during a view rendering and this
generates authorization errors during the view rendering.
A default margin can be set by the TOKEN_TIMEOUT_MARGIN in the
django settings.
"""
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 expiration is None:
return False
if margin is None:
margin = getattr(settings, 'TOKEN_TIMEOUT_MARGIN', 0)
expiration = expiration - datetime.timedelta(seconds=margin)
if settings.USE_TZ and timezone.is_naive(expiration):
# Presumes that the Keystone is using UTC.
expiration = timezone.make_aware(expiration, timezone.utc)
return expiration > timezone.now() | [
"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 example usage is that the token can be valid once the middleware
passed, and invalid (timed-out) during a view rendering and this
generates authorization errors during the view rendering.
A default margin can be set by the TOKEN_TIMEOUT_MARGIN in the
django settings. | [
"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 this variable should
do so via calling thisObj._set_ipv6_routes() directly.
YANG Description: ISIS IPv6 Route Table
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=ipv6_routes.ipv6_routes, is_container='container', presence=False, yang_name="ipv6-routes", rest_name="ipv6-routes", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'callpoint': u'isis-ipv6-route-table', u'cli-suppress-show-path': None}}, namespace='urn:brocade.com:mgmt:brocade-isis-operational', defining_module='brocade-isis-operational', yang_type='container', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """ipv6_routes must be of a type compatible with container""",
'defined-type': "container",
'generated-type': """YANGDynClass(base=ipv6_routes.ipv6_routes, is_container='container', presence=False, yang_name="ipv6-routes", rest_name="ipv6-routes", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'callpoint': u'isis-ipv6-route-table', u'cli-suppress-show-path': None}}, namespace='urn:brocade.com:mgmt:brocade-isis-operational', defining_module='brocade-isis-operational', yang_type='container', is_config=False)""",
})
self.__ipv6_routes = t
if hasattr(self, '_set'):
self._set() | [
"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_ipv6_routes() directly.
YANG Description: ISIS IPv6 Route Table | [
"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
click signal, defaults to a 1 kHz blip
length : int
desired number of samples in the output signal,
defaults to ``times.max()*fs + click.shape[0] + 1``
Returns
-------
click_signal : np.ndarray
Synthesized click signal
"""
# Create default click signal
if click is None:
# 1 kHz tone, 100ms
click = np.sin(2*np.pi*np.arange(fs*.1)*1000/(1.*fs))
# Exponential decay
click *= np.exp(-np.arange(fs*.1)/(fs*.01))
# Set default length
if length is None:
length = int(times.max()*fs + click.shape[0] + 1)
# Pre-allocate click signal
click_signal = np.zeros(length)
# Place clicks
for time in times:
# Compute the boundaries of the click
start = int(time*fs)
end = start + click.shape[0]
# Make sure we don't try to output past the end of the signal
if start >= length:
break
if end >= length:
click_signal[start:] = click[:length - start]
break
# Normally, just add a click here
click_signal[start:end] = click
return click_signal | [
"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
desired number of samples in the output signal,
defaults to ``times.max()*fs + click.shape[0] + 1``
Returns
-------
click_signal : np.ndarray
Synthesized click signal | [
"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 Device(api.device_retrieve(device_id)) | [
"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)
if n == 3:
yield codon
codon = [] | [
"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("Only parsing first %d rows", limit)
LOG.info("Parsing files...")
# pub_map = dict()
# file_path = '/'.join((self.rawdir,
# self.static_files['publications']['file']))
# if os.path.exists(file_path) is True:
# pub_map = self._parse_publication_file(
# self.static_files['publications']['file']
# )
if self.test_only:
self.test_mode = True
self.geno = Genotype(self.graph)
self.pathway = Pathway(self.graph)
self._parse_ctd_file(
limit, self.files['chemical_disease_interactions']['file'])
self._parse_ctd_file(limit, self.files['gene_pathway']['file'])
self._parse_ctd_file(limit, self.files['gene_disease']['file'])
self._parse_curated_chem_disease(limit)
LOG.info("Done parsing files.")
return | [
"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.get_filepath(renew=True)
return | [
"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 list: activate_line(lines=[1, 7]).
To raise a single line, pass in just an integer, or a list with a
single element to the lines keyword argument:
activate_line(lines=3)
or
activate_line(lines=[3])
The `lines` argument must either be an Integer, list of Integers, or
None.
If you'd rather specify a bitmask for setting the lines, you can use
the bitmask keyword argument. Bitmask must be a Integer value between
0 and 255 where 0 specifies no lines, and 255 is all lines. For a
mapping between lines and their bit values, see the `_lines` class
variable.
To use this, call the function as so to activate lines 1 and 6:
activate_line(bitmask=33)
leave_remaining_lines tells the function to only operate on the lines
specified. For example, if lines 1 and 8 are active, and you make
the following function call:
activate_line(lines=4, leave_remaining_lines=True)
This will result in lines 1, 4 and 8 being active.
If you call activate_line(lines=4) with leave_remaining_lines=False
(the default), if lines 1 and 8 were previously active, only line 4
will be active after the call.
"""
if lines is None and bitmask is None:
raise ValueError('Must set one of lines or bitmask')
if lines is not None and bitmask is not None:
raise ValueError('Can only set one of lines or bitmask')
if bitmask is not None:
if bitmask not in range(0, 256):
raise ValueError('bitmask must be an integer between '
'0 and 255')
if lines is not None:
if not isinstance(lines, list):
lines = [lines]
bitmask = 0
for l in lines:
if l < 1 or l > 8:
raise ValueError('Line numbers must be between 1 and 8 '
'(inclusive)')
bitmask |= self._lines[l]
self.con.set_digital_output_lines(bitmask, leave_remaining_lines) | [
"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
single element to the lines keyword argument:
activate_line(lines=3)
or
activate_line(lines=[3])
The `lines` argument must either be an Integer, list of Integers, or
None.
If you'd rather specify a bitmask for setting the lines, you can use
the bitmask keyword argument. Bitmask must be a Integer value between
0 and 255 where 0 specifies no lines, and 255 is all lines. For a
mapping between lines and their bit values, see the `_lines` class
variable.
To use this, call the function as so to activate lines 1 and 6:
activate_line(bitmask=33)
leave_remaining_lines tells the function to only operate on the lines
specified. For example, if lines 1 and 8 are active, and you make
the following function call:
activate_line(lines=4, leave_remaining_lines=True)
This will result in lines 1, 4 and 8 being active.
If you call activate_line(lines=4) with leave_remaining_lines=False
(the default), if lines 1 and 8 were previously active, only line 4
will be active after the call. | [
"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
:meth:`~praw.__init__.ReportMixin.unhide` rather than setting this
manually.
:returns: The json response from the server.
"""
if isinstance(thing_id, six.string_types):
thing_id = [thing_id]
else:
# Guarantee a subscriptable type.
thing_id = list(thing_id)
if len(thing_id) == 0:
raise ValueError('No fullnames provided')
# Will we return a list of server responses, or just one?
# TODO: In future versions, change the threshold to 1 to get
# list-in-list-out, single-in-single-out behavior. Threshold of 50
# is to avoid a breaking change at this time.
return_list = len(thing_id) > 50
id_chunks = chunk_sequence(thing_id, 50)
responses = []
for id_chunk in id_chunks:
id_chunk = ','.join(id_chunk)
method = 'unhide' if _unhide else 'hide'
data = {'id': id_chunk,
'executed': method}
response = self.request_json(self.config[method], data=data)
responses.append(response)
if self.user is not None:
self.evict(urljoin(self.user._url, # pylint: disable=W0212
'hidden'))
if return_list:
return responses
else:
return responses[0] | [
"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 setting this
manually.
:returns: The json response from the server. | [
"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.0000, 0.6149, 0.9899, 0.0000 ,0.0031, -0.0082]
>>> lsf = poly2lsf(a)
>>> lsf = array([0.7842, 1.5605, 1.8776, 1.8984, 2.3593])
.. seealso:: lsf2poly, poly2rc, poly2qc, rc2is
"""
#Line spectral frequencies are not defined for complex polynomials.
# Normalize the polynomial
a = numpy.array(a)
if a[0] != 1:
a/=a[0]
if max(numpy.abs(numpy.roots(a))) >= 1.0:
error('The polynomial must have all roots inside of the unit circle.');
# Form the sum and differnce filters
p = len(a)-1 # The leading one in the polynomial is not used
a1 = numpy.concatenate((a, numpy.array([0])))
a2 = a1[-1::-1]
P1 = a1 - a2 # Difference filter
Q1 = a1 + a2 # Sum Filter
# If order is even, remove the known root at z = 1 for P1 and z = -1 for Q1
# If odd, remove both the roots from P1
if p%2: # Odd order
P, r = deconvolve(P1,[1, 0 ,-1])
Q = Q1
else: # Even order
P, r = deconvolve(P1, [1, -1])
Q, r = deconvolve(Q1, [1, 1])
rP = numpy.roots(P)
rQ = numpy.roots(Q)
aP = numpy.angle(rP[1::2])
aQ = numpy.angle(rQ[1::2])
lsf = sorted(numpy.concatenate((-aP,-aQ)))
return lsf | [
"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, 0.0000 ,0.0031, -0.0082]
>>> lsf = poly2lsf(a)
>>> lsf = array([0.7842, 1.5605, 1.8776, 1.8984, 2.3593])
.. seealso:: lsf2poly, poly2rc, poly2qc, rc2is | [
"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.g. '#,##0' corresponding to an Excel number
format.
"""
series_data = CategorySeriesData(self, name, number_format)
self.append(series_data)
for value in values:
series_data.add_data_point(value)
return series_data | [
"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)
#-----------------------------------------
# See if they'd like to view in a browser
#-----------------------------------------
if self._showHelpInBrowser or (kind == 'task' and
self._knowTaskHelpIsHtml):
if kind == 'epar':
self.htmlHelp(helpString=self._appHelpString,
title='Parameter Editor Help')
if kind == 'task':
self.htmlHelp(istask=True, tag=tag)
if kind == 'log':
self.htmlHelp(helpString='\n'.join(self._msgHistory),
title=self._appName+' Event Log')
return
#-----------------------------------------
# Now try to pop up the regular Tk window
#-----------------------------------------
wins = {'epar':self.eparHelpWin,
'task':self.irafHelpWin,
'log': self.logHistWin, }
window = wins[kind]
try:
if window.state() != NORMAL:
window.deiconify()
window.tkraise()
return
except (AttributeError, TclError):
pass
#---------------------------------------------------------
# That didn't succeed (window is still None), so build it
#---------------------------------------------------------
if kind == 'epar':
self.eparHelpWin = self.makeHelpWin(self._appHelpString,
title='Parameter Editor Help')
if kind == 'task':
# Acquire the task help as a string
# Need to include the package name for the task to
# avoid name conflicts with tasks from other packages. WJH
self.irafHelpWin = self.makeHelpWin(self.getHelpString(
self.pkgName+'.'+self.taskName))
if kind == 'log':
self.logHistWin = self.makeHelpWin('\n'.join(self._msgHistory),
title=self._appName+' Event Log') | [
"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()
if not author:
cls.input_el.style.border = "2px solid red"
return
cls.hide_errors()
AuthorBar.show(50)
make_request(
url=join(settings.API_PATH, "aleph/authors_by_name"),
data={"name": author},
on_complete=cls.on_complete
) | [
"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.scheme)
if default is None:
return False
return self.port == default | [
"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_parents: MutableMapping[type, Set[type]] = {}
visited_classes: Set[type] = set()
class_stack = list(classes)
while class_stack:
class_ = class_stack.pop()
if class_ in visited_classes:
continue
visited_classes.add(class_)
for base in class_.__bases__:
if base not in visited_classes:
class_stack.append(base)
parents_to_children.setdefault(base, set()).add(class_)
children_to_parents.setdefault(class_, set()).add(base)
sorted_parents_to_children: MutableMapping[
type, List[type]
] = collections.OrderedDict()
for parent, children in sorted(
parents_to_children.items(), key=lambda x: (x[0].__module__, x[0].__name__)
):
sorted_parents_to_children[parent] = sorted(
children, key=lambda x: (x.__module__, x.__name__)
)
sorted_children_to_parents: MutableMapping[
type, List[type]
] = collections.OrderedDict()
for child, parents in sorted(
children_to_parents.items(), key=lambda x: (x[0].__module__, x[0].__name__)
):
sorted_children_to_parents[child] = sorted(
parents, key=lambda x: (x.__module__, x.__name__)
)
return sorted_parents_to_children, sorted_children_to_parents | [
"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('CloudPage.load: %s, %s' % (info, error))
return
tasks = info['task_info']
for task in tasks:
self.liststore.append([
task['task_id'],
task['task_name'],
task['save_path'],
task['source_url'],
0,
0,
int(task['status']),
0,
'0',
gutil.escape(task['save_path'])
])
self.scan_tasks()
nonlocal start
start = start + len(tasks)
if info['total'] > start:
gutil.async_call(pcs.cloud_list_task, self.app.cookie,
self.app.tokens, start, callback=on_list_task)
self.loading_spin.start()
self.loading_spin.show_all()
start = 0
gutil.async_call(pcs.cloud_list_task, self.app.cookie, self.app.tokens,
start, callback=on_list_task) | [
"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: int
"""
piece_values = cls()
piece_values.PAWN_VALUE = pawn_value
piece_values.KNIGHT_VALUE = knight_value
piece_values.BISHOP_VALUE = bishop_value
piece_values.ROOK_VALUE = rook_value
piece_values.QUEEN_VALUE = queen_value
piece_values.KING_VALUE = king_value
return piece_values | [
"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(
'strptime_patched', *imp.find_module('_strptime')
)
_calendar = imp.load_module(
'calendar_patched', *imp.find_module('_strptime')
)
_strptime._getlang = lambda: ('en_US', 'UTF-8')
_strptime.calendar = _calendar
_strptime.calendar.day_abbr = [
'mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'
]
_strptime.calendar.day_name = [
'monday', 'tuesday', 'wednesday', 'thursday',
'friday', 'saturday', 'sunday'
]
_strptime.calendar.month_abbr = [
'', 'jan', 'feb', 'mar', 'apr', 'may', 'jun',
'jul', 'aug', 'sep', 'oct', 'nov', 'dec'
]
_strptime.calendar.month_name = [
'', 'january', 'february', 'march', 'april',
'may', 'june', 'july', 'august', 'september',
'october', 'november', 'december'
]
return _strptime._strptime_time | [
"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 parameters that the object does not already
have
**parameters : paramters to set
Returns
------
self
"""
param_names = self.get_params(deep=deep).keys()
for parameter, value in parameters.items():
if (parameter in param_names
or force
or (hasattr(self, parameter) and parameter == parameter.strip('_'))):
setattr(self, parameter, value)
return self | [
"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 : paramters to set
Returns
------
self | [
"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 as JSON
to the device. Various edge cases are handled:
* read-only attributes that are unchangeable are removed
* ``agent`` attribute removed prior to PUT
* ``post`` attribute removed prior to PUT
* ``method`` attribute removed prior to PUT
:param kwargs: keys and associated values to alter on the device
"""
self.__dict__.pop('agent', '')
self.__dict__.pop('post', '')
self.__dict__.pop('method', '')
super(Wmi, self).update(**kwargs) | [
"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 edge cases are handled:
* read-only attributes that are unchangeable are removed
* ``agent`` attribute removed prior to PUT
* ``post`` attribute removed prior to PUT
* ``method`` attribute removed prior to PUT
:param kwargs: keys and associated values to alter on the device | [
"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._jvm.org.apache.spark.ml.image.ImageSchema.undefinedImageType()
return self._undefinedImageType | [
"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
frame.validate_payload_len(payload)
frame.from_payload(payload)
return frame | [
"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.text = sha.hexdigest()
xmlWriter.write(xmlChecksumElement, pretty_print=True) | [
"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_on_failure=False) is not supported by Python 2
none_on_failure = kwargs.get('none_on_failure', False)
def inner(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
for req in requirements:
if none_on_failure:
if not getattr(req, 'is_available'):
return None
else:
getattr(req, 'require')()
return f(*args, **kwargs)
return wrapper
return inner | [
"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'
elif extension == '.tsv':
self._content_type = 'text/tab-separated-values'
else:
self._content_type = 'text/plain'
return self._content_type | [
"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 popular criterion to determine how *uneven* are the weights.
Its value is in the range [1, N], it equals N when weights are constant,
and 1 if all weights but one are zero.
"""
w = np.exp(lw - lw.max())
return (w.sum())**2 / np.sum(w**2) | [
"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 determine how *uneven* are the weights.
Its value is in the range [1, N], it equals N when weights are constant,
and 1 if all weights but one are zero. | [
"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 https://www.ebi.ac.uk/pdbe/api/doc/sifts.html
The list of PDB structures mapping to a UniProt accession sorted by coverage of the protein and,
if the same, resolution.
Args:
seq_ident_cutoff (float): Sequence identity cutoff in decimal form
outdir (str): Output directory to cache JSON results of search
force_rerun (bool): Force re-downloading of JSON results if they already exist
Returns:
list: A rank-ordered list of PDBProp objects that map to the UniProt ID
"""
if not self.representative_sequence:
log.error('{}: no representative sequence set, cannot use best structures API'.format(self.id))
return None
# Check if a UniProt ID is attached to the representative sequence
uniprot_id = self.representative_sequence.uniprot
if not uniprot_id:
log.error('{}: no representative UniProt ID set, cannot use best structures API'.format(self.id))
return None
if '-' in uniprot_id:
log.debug('{}: "-" detected in UniProt ID, isoform specific sequences are ignored with best structures API'.format(self.id))
uniprot_id = uniprot_id.split('-')[0]
if not outdir:
outdir = self.sequence_dir
if not outdir:
raise ValueError('Output directory must be specified')
best_structures = ssbio.databases.pdb.best_structures(uniprot_id,
outname='{}_best_structures'.format(custom_slugify(uniprot_id)),
outdir=outdir,
seq_ident_cutoff=seq_ident_cutoff,
force_rerun=force_rerun)
new_pdbs = []
if best_structures:
rank = 1
for best_structure in best_structures:
currpdb = str(best_structure['pdb_id'].lower())
new_pdbs.append(currpdb)
currchain = str(best_structure['chain_id'])
# load_pdb will append this protein to the list
new_pdb = self.load_pdb(pdb_id=currpdb, mapped_chains=currchain)
# Also add this chain to the chains attribute so we can save the
# info we get from best_structures
new_pdb.add_chain_ids(currchain)
pdb_specific_keys = ['experimental_method', 'resolution']
chain_specific_keys = ['coverage', 'start', 'end', 'unp_start', 'unp_end']
new_pdb.update(best_structure, only_keys=pdb_specific_keys)
new_chain = new_pdb.chains.get_by_id(currchain)
new_chain.update(best_structure, only_keys=chain_specific_keys)
new_chain.update({'rank': rank})
rank += 1
log.debug('{}, {}: {} PDB/chain pairs mapped'.format(self.id, uniprot_id, len(best_structures)))
else:
log.debug('{}, {}: no PDB/chain pairs mapped'.format(self.id, uniprot_id))
return new_pdbs | [
"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 UniProt accession sorted by coverage of the protein and,
if the same, resolution.
Args:
seq_ident_cutoff (float): Sequence identity cutoff in decimal form
outdir (str): Output directory to cache JSON results of search
force_rerun (bool): Force re-downloading of JSON results if they already exist
Returns:
list: A rank-ordered list of PDBProp objects that map to the UniProt ID | [
"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/value pairs specifying
the name of the status field and the string value associated with
it. The values are not converted from strings.
'''
data = []
for s in self.servers:
if not s.connect(): continue
if s.family == socket.AF_INET:
name = '%s:%s (%s)' % ( s.ip, s.port, s.weight )
elif s.family == socket.AF_INET6:
name = '[%s]:%s (%s)' % ( s.ip, s.port, s.weight )
else:
name = 'unix:%s (%s)' % ( s.address, s.weight )
if not stat_args:
s.send_cmd('stats')
else:
s.send_cmd('stats ' + stat_args)
serverData = {}
data.append(( name, serverData ))
readline = s.readline
while 1:
line = readline()
if not line or line.strip() in ('END', 'RESET'):
break
stats = line.split(' ', 2)
serverData[stats[1]] = stats[2]
return(data) | [
"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 the status field and the string value associated with
it. The values are not converted from strings. | [
"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_CONFIG_BASE_DIR')
if base_dir is None:
# NOTE(bnemec): Prefer the new location, but still allow the old one.
if os.path.isdir(OLD_BASE_DIR) and not os.path.isdir(DEFAULT_BASE_DIR):
logging.warning('Base directory %s is deprecated. The recommended '
'base directory is %s',
OLD_BASE_DIR, DEFAULT_BASE_DIR)
base_dir = OLD_BASE_DIR
else:
base_dir = DEFAULT_BASE_DIR
return base_dir | [
"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]
while instance.state != "stopped":
log_yellow("Instance state: %s" % instance.state)
sleep(10)
instance.update()
log_green('Instance state: %s' % instance.state) | [
"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
-------
energy : list of lists of floats
A list of the energies and the concentrations.
"""
energy = []
with open(fname,'r') as f:
for line in f:
CE = abs(float(line.strip().split()[0]))
VASP = abs(float(line.strip().split()[1]))
conc = [i for i in line.strip().split()[2:]]
conc_f = []
for c in conc:
if '[' in c and ']' in c:
conc_f.append(int(c[1:-1]))
elif '[' in c:
conc_f.append(int(c[1:-1]))
elif ']' in c or ',' in c:
conc_f.append(int(c[:-1]))
else:
conc_f.append(int(c))
energy.append([CE,VASP,conc_f])
return energy | [
"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
A list of the energies and the concentrations. | [
"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_status(**kwargs)
options = {
"collection.configName": cluster["collections"][collection_name]["configName"],
"router.name": cluster["collections"][collection_name]["router"]["name"],
"replicationFactor": int(cluster["collections"][collection_name]["replicationFactor"]),
"maxShardsPerNode": int(cluster["collections"][collection_name]["maxShardsPerNode"]),
"autoAddReplicas": cluster["collections"][collection_name]["autoAddReplicas"] is True
}
if 'rule' in cluster["collections"][collection_name]:
options['rule'] = cluster["collections"][collection_name]['rule']
if 'snitch' in cluster["collections"][collection_name]:
options['snitch'] = cluster["collections"][collection_name]['rule']
return options | [
"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.
"""
policy = self._properties.setdefault("retentionPolicy", {})
if value is not None:
policy["retentionPeriod"] = str(value)
else:
policy = None
self._patch_property("retentionPolicy", policy) | [
"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._re = re.compile(regexp0_str)
self._match_exps = [
subs[1] for subs in self._re_cvt if subs[1] is not None
]
self._divisors = [subs[2] for subs in self._re_cvt if subs[2] is not None]
self._in_cvt_fns = [
subs[3] for subs in self._re_cvt if subs[3] is not None
]
self._read_line_init = True | [
"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 queues the worker should act on, falls back
to the configured queues.
"""
if not queues:
queues = self.queues
queues = [self.get_queue(name) for name in queues]
worker_cls = import_attribute(self.worker_class)
worker = worker_cls(
queues,
connection=self.connection,
job_class=self.job_class,
queue_class=self.queue_class,
)
for exception_handler in self._exception_handlers:
worker.push_exc_handler(import_attribute(exception_handler))
return worker | [
"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
to the configured queues. | [
"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.
The default value is None.
:param int timeout:
The number of minutes or seconds before a shutdown will occur. Whether
this number represents minutes or seconds depends on the value of
``in_seconds``.
The default value is 5.
:param bool in_seconds:
If this is True, the value of ``timeout`` will be treated as a number
of seconds. If this is False, the value of ``timeout`` will be treated
as a number of minutes.
The default value is False.
:param bool force_close:
If this is True, running applications will be forced to close without
warning. If this is False, running applications will not get the
opportunity to prompt users about unsaved data.
The default value is True.
:param bool reboot:
If this is True, the computer will restart immediately after shutting
down. If False the system flushes all caches to disk and safely powers
down the system.
The default value is False.
:param bool only_on_pending_reboot:
If this is True, the shutdown will only occur if the system reports a
pending reboot. If this is False, the shutdown will always occur.
The default value is False.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if reboot:
action = 'reboot'
else:
action = 'shutdown'
if only_on_pending_reboot and not __salt__['system.get_pending_reboot']():
if __opts__['test']:
ret['comment'] = ('System {0} will be skipped because '
'no reboot is pending').format(action)
else:
ret['comment'] = ('System {0} has been skipped because '
'no reboot was pending').format(action)
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Will attempt to schedule a {0}'.format(action)
return ret
ret['result'] = __salt__['system.shutdown'](message=message,
timeout=timeout,
force_close=force_close,
reboot=reboot,
in_seconds=in_seconds,
only_on_pending_reboot=False)
if ret['result']:
ret['changes'] = {'old': 'No reboot or shutdown was scheduled',
'new': 'A {0} has been scheduled'.format(action)}
ret['comment'] = 'Request to {0} was successful'.format(action)
else:
ret['comment'] = 'Request to {0} failed'.format(action)
return ret | [
"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 number represents minutes or seconds depends on the value of
``in_seconds``.
The default value is 5.
:param bool in_seconds:
If this is True, the value of ``timeout`` will be treated as a number
of seconds. If this is False, the value of ``timeout`` will be treated
as a number of minutes.
The default value is False.
:param bool force_close:
If this is True, running applications will be forced to close without
warning. If this is False, running applications will not get the
opportunity to prompt users about unsaved data.
The default value is True.
:param bool reboot:
If this is True, the computer will restart immediately after shutting
down. If False the system flushes all caches to disk and safely powers
down the system.
The default value is False.
:param bool only_on_pending_reboot:
If this is True, the shutdown will only occur if the system reports a
pending reboot. If this is False, the shutdown will always occur.
The default value is False. | [
"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.com/cc2qe/speedseq/blob/e6729aa2589eca4e3a946f398c1a2bdc15a7300d/bin/speedseq#L62
Extracts the genotype likelihoods (GLs) from FreeBayes, which are like phred scores
except not multiplied by 10.0 (https://en.wikipedia.org/wiki/Phred_quality_score).
For tumors, we retrieve the best likelihood to not be reference (the first GL) and
for normal, the best likelhood to be reference.
After calculating the likelihoods, we compare these to thresholds to pass variants
at tuned sensitivity/precision. Tuning done on DREAM synthetic 3 dataset evaluations.
We also check that the frequency of the tumor exceeds the frequency of the normal by
a threshold to avoid calls that are low frequency in both tumor and normal. This supports
both FreeBayes and VarDict output frequencies.
"""
# 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 event">\n',
('##FILTER=<ID=REJECT,Description="Not somatic due to normal call frequency '
'or phred likelihoods: tumor: %s, normal %s.">\n')
% (int(tumor_thresh * 10), int(normal_thresh * 10))]
def _output_filter_line(line, indexes):
parts = line.split("\t")
if _check_lods(parts, tumor_thresh, normal_thresh, indexes) and _check_freqs(parts, indexes):
parts[7] = parts[7] + ";SOMATIC"
else:
if parts[6] in set([".", "PASS"]):
parts[6] = "REJECT"
else:
parts[6] += ";REJECT"
line = "\t".join(parts)
sys.stdout.write(line)
def _write_header(header):
for hline in header[:-1] + new_headers + [header[-1]]:
sys.stdout.write(hline)
header = []
indexes = None
for line in sys.stdin:
if not indexes:
if line.startswith("#"):
header.append(line)
else:
parts = header[-1].rstrip().split("\t")
indexes = {"tumor": parts.index(tumor_name), "normal": parts.index(normal_name)}
_write_header(header)
_output_filter_line(line, indexes)
else:
_output_filter_line(line, indexes)
# no calls, only output the header
if not indexes:
_write_header(header) | [
"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/e6729aa2589eca4e3a946f398c1a2bdc15a7300d/bin/speedseq#L62
Extracts the genotype likelihoods (GLs) from FreeBayes, which are like phred scores
except not multiplied by 10.0 (https://en.wikipedia.org/wiki/Phred_quality_score).
For tumors, we retrieve the best likelihood to not be reference (the first GL) and
for normal, the best likelhood to be reference.
After calculating the likelihoods, we compare these to thresholds to pass variants
at tuned sensitivity/precision. Tuning done on DREAM synthetic 3 dataset evaluations.
We also check that the frequency of the tumor exceeds the frequency of the normal by
a threshold to avoid calls that are low frequency in both tumor and normal. This supports
both FreeBayes and VarDict output frequencies. | [
"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.info(
'An inline policy has been attached for'
' {u} revoking sts tokens.'.format(u=username)
)
return response | [
"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:
# Go through options and figure out relevant information
for option in config:
if 'namespace' in self.options:
namespaced_key = self.options['namespace'] + '_' + option.key
else:
namespaced_key = option.key
if 'case' in self.options:
if self.options['case'] == 'upper':
namespaced_key = namespaced_key.upper()
elif self.options['case'] == 'lower':
namespaced_key = namespaced_key.lower()
all_options.append({
'key': namespaced_key,
'parser': qualname(option.parser),
'doc': option.doc,
'default': option.default,
})
if 'hide-classname' not in self.options:
modname, clsname = split_clspath(clspath)
component_name = clspath
component_index = clsname
else:
component_name = 'Configuration'
component_index = 'Configuration'
if all_options:
# Add index entries for options first so they link to the right
# place; we do it this way so that we don't have to make options a
# real object type and then we don't get to use TypedField
# formatting
self.add_line('.. index::', sourcename)
for option in all_options:
self.add_line(' single: %s; (%s)' % (option['key'], component_index), sourcename)
self.add_line('', '')
# Add the classname or 'Configuration'
self.add_line('.. everett:component:: %s' % component_name, sourcename)
self.add_line('', sourcename)
# Add the docstring if there is one and if show-docstring
if 'show-docstring' in self.options:
docstring_attr = self.options['show-docstring'] or '__doc__'
docstring = getattr(obj, docstring_attr, None)
if docstring:
docstringlines = prepare_docstring(docstring, ignore=1)
for i, line in enumerate(docstringlines):
self.add_line(indent + line, sourcename, i)
self.add_line('', '')
# Add content from the directive if there was any
if more_content:
for line, src in zip(more_content.data, more_content.items):
self.add_line(indent + line, src[0], src[1])
self.add_line('', '')
if all_options:
# Now list the options
sourcename = 'class definition'
for option in all_options:
self.add_line(
'%s:option %s %s:' % (indent, option['parser'], option['key']),
sourcename
)
self.add_line('%s %s' % (indent, option['doc']), sourcename)
if option['default'] is not NO_VALUE:
self.add_line('', '')
self.add_line(
'%s Defaults to ``%r``.' % (indent, option['default']),
sourcename
)
self.add_line('', '') | [
"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
generate = []
missingcols = [k for k in self.ldb.uniqueids[tab]
if k not in self.table[tab]['column']]
for m in missingcols:
generate.append(',BLOB(GENERATE_UNIQUE())')
self.table[tab]['orderedcol'].append(m)
# and construct the sql query
self.table[tab]['query'] = ' '.join(
['INSERT INTO', tab, '(', ','.join(self.table[tab]['orderedcol']),
') VALUES (', ','.join(['?' for x in self.table[tab]['column']]) ,
''.join(generate), ')'])
for tabtup in self.ldb.tables:
tab = tabtup[0].lower()
try:
try:
self.curs.executemany(self.table[tab]['query'],
self.table[tab]['stream'])
rowcount = self.curs.rowcount
except DB2.Error, e:
self.curs.execute('rollback')
msg = e[2]
msg += self.xml() + '\n'
msg += str(self.table[tab]['query']) + '\n'
msg += str(self.table[tab]['stream']) + '\n'
raise LIGOLwDBError, msg
except DB2.Warning, e:
self.curs.execute('rollback')
raise LIGOLwDBError, e[2]
#except Exception, e:
# self.curs.execute('rollback')
# raise LIGOLwDBError, e[2]
except KeyError:
pass
self.curs.execute('commit')
return rowcount | [
"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]
"""Validate a CWL document."""
loadingContext = loadingContext.copy()
if not isinstance(workflowobj, MutableMapping):
raise ValueError("workflowjobj must be a dict, got '{}': {}".format(
type(workflowobj), workflowobj))
jobobj = None
if "cwl:tool" in workflowobj:
jobobj, _ = loadingContext.loader.resolve_all(workflowobj, uri, checklinks=loadingContext.do_validate)
uri = urllib.parse.urljoin(uri, workflowobj["https://w3id.org/cwl/cwl#tool"])
del cast(dict, jobobj)["https://w3id.org/cwl/cwl#tool"]
workflowobj = fetch_document(uri, loadingContext)[1]
fileuri = urllib.parse.urldefrag(uri)[0]
cwlVersion = loadingContext.metadata.get("cwlVersion")
if not cwlVersion:
cwlVersion = workflowobj.get("cwlVersion")
if not cwlVersion:
raise ValidationException(
"No cwlVersion found. "
"Use the following syntax in your CWL document to declare "
"the version: cwlVersion: <version>.\n"
"Note: if this is a CWL draft-2 (pre v1.0) document then it "
"will need to be upgraded first.")
if not isinstance(cwlVersion, string_types):
with SourceLine(workflowobj, "cwlVersion", ValidationException):
raise ValidationException("'cwlVersion' must be a string, "
"got {}".format(
type(cwlVersion)))
# strip out version
cwlVersion = re.sub(
r"^(?:cwl:|https://w3id.org/cwl/cwl#)", "",
cwlVersion)
if cwlVersion not in list(ALLUPDATES):
# print out all the Supported Versions of cwlVersion
versions = []
for version in list(ALLUPDATES):
if "dev" in version:
version += " (with --enable-dev flag only)"
versions.append(version)
versions.sort()
raise ValidationException(
"The CWL reference runner no longer supports pre CWL v1.0 "
"documents. Supported versions are: "
"\n{}".format("\n".join(versions)))
if isinstance(jobobj, CommentedMap) and "http://commonwl.org/cwltool#overrides" in jobobj:
loadingContext.overrides_list.extend(resolve_overrides(jobobj, uri, uri))
del jobobj["http://commonwl.org/cwltool#overrides"]
if isinstance(jobobj, CommentedMap) and "https://w3id.org/cwl/cwl#requirements" in jobobj:
if cwlVersion not in ("v1.1.0-dev1",):
raise ValidationException(
"`cwl:requirements` in the input object is not part of CWL "
"v1.0. You can adjust to use `cwltool:overrides` instead; or you "
"can set the cwlVersion to v1.1.0-dev1 or greater and re-run with "
"--enable-dev.")
loadingContext.overrides_list.append({"overrideTarget": uri,
"requirements": jobobj["https://w3id.org/cwl/cwl#requirements"]})
del jobobj["https://w3id.org/cwl/cwl#requirements"]
(sch_document_loader, avsc_names) = \
process.get_schema(cwlVersion)[:2]
if isinstance(avsc_names, Exception):
raise avsc_names
processobj = None # type: Union[CommentedMap, CommentedSeq, Text, None]
document_loader = Loader(sch_document_loader.ctx,
schemagraph=sch_document_loader.graph,
idx=loadingContext.loader.idx,
cache=sch_document_loader.cache,
fetcher_constructor=loadingContext.fetcher_constructor,
skip_schemas=skip_schemas)
if cwlVersion == "v1.0":
_add_blank_ids(workflowobj)
workflowobj["id"] = fileuri
processobj, metadata = document_loader.resolve_all(
workflowobj, fileuri, checklinks=loadingContext.do_validate)
if loadingContext.metadata:
metadata = loadingContext.metadata
if not isinstance(processobj, (CommentedMap, CommentedSeq)):
raise ValidationException("Workflow must be a CommentedMap or CommentedSeq.")
if not isinstance(metadata, CommentedMap):
raise ValidationException("metadata must be a CommentedMap, was %s" % type(metadata))
_convert_stdstreams_to_files(workflowobj)
if preprocess_only:
return loadingContext, uri
if loadingContext.do_validate:
schema.validate_doc(avsc_names, processobj, document_loader, loadingContext.strict)
# None means default behavior (do update)
if loadingContext.do_update in (True, None):
processobj = cast(CommentedMap, cmap(update.update(
processobj, document_loader, fileuri, loadingContext.enable_dev, metadata)))
if isinstance(processobj, MutableMapping):
document_loader.idx[processobj["id"]] = processobj
elif isinstance(processobj, MutableSequence):
document_loader.idx[metadata["id"]] = metadata
for po in processobj:
document_loader.idx[po["id"]] = po
if jobobj is not None:
loadingContext.jobdefaults = jobobj
loadingContext.loader = document_loader
loadingContext.avsc_names = avsc_names
loadingContext.metadata = metadata
return loadingContext, uri | [
"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.SubElement(output, "vnetwork-dvs")
name = ET.SubElement(vnetwork_dvs, "name")
name.text = kwargs.pop('name')
callback = kwargs.pop('callback', self._callback)
return callback(config) | [
"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 to import. If None is given, try to import
the current reference
:type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo` | None
:returns: None
:rtype: None
:raises: :class:`ReftrackIntegrityError`
"""
assert self.status() is None,\
"Entity is already in scene. Use replace instead."
refobjinter = self.get_refobjinter()
refobj = self.create_refobject()
with self.set_parent_on_new(refobj):
refobjinter.import_taskfile(refobj, taskfileinfo)
self.set_refobj(refobj)
self.set_status(self.IMPORTED)
self.fetch_new_children()
self.update_restrictions()
self.emit_data_changed() | [
"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
the current reference
:type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo` | None
:returns: None
:rtype: None
:raises: :class:`ReftrackIntegrityError` | [
"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: ' + str(json))
:param message: The name of the event. This is normally a user defined
string, but a few event names are already defined. Use
``'message'`` to define a handler that takes a string
payload, ``'json'`` to define a handler that takes a
JSON blob payload, ``'connect'`` or ``'disconnect'``
to create handlers for connection and disconnection
events.
:param namespace: The namespace on which the handler is to be
registered. Defaults to the global namespace.
"""
namespace = namespace or '/'
def decorator(handler):
def _handler(sid, *args):
return self._handle_event(handler, message, namespace, sid,
*args)
if self.server:
self.server.on(message, _handler, namespace=namespace)
else:
self.handlers.append((message, _handler, namespace))
return handler
return decorator | [
"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 the event. This is normally a user defined
string, but a few event names are already defined. Use
``'message'`` to define a handler that takes a string
payload, ``'json'`` to define a handler that takes a
JSON blob payload, ``'connect'`` or ``'disconnect'``
to create handlers for connection and disconnection
events.
:param namespace: The namespace on which the handler is to be
registered. Defaults to the global namespace. | [
"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)
cmap = None # data is already RGB-ed
elif mixer_name in ['checkerboard', 'checker', 'cb', 'checker_board']:
checkers = _get_checkers(slice1.shape, **kwargs)
mixed = _checker_mixer(slice1, slice2, checkers)
cmap = 'gray'
elif mixer_name in ['diff', 'voxelwise_diff', 'vdiff']:
mixed, cmap = _diff_image(slice1, slice2, **kwargs)
# if kwargs['overlay_image'] is True:
# diff_cmap = diff_colormap()
# plt.imshow(slice1, alpha=kwargs['overlay_alpha'], **display_params)
# plt.hold(True)
# plt.imshow(mixed,
# cmap=diff_cmap,
# vmin=min_value, vmax=max_value,
# **display_params)
# else:
# plt.imshow(mixed, cmap=cmap,
# vmin=min_value, vmax=max_value,
# **display_params)
else:
raise ValueError('Invalid mixer name chosen.')
disp_params = dict(cmap=cmap)
return mixed, disp_params | [
"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 renderer
Returns:
TileRenderer : TileRenderer
'''
tile_renderer = TileRenderer(tile_source=tile_source, **kw)
self.renderers.append(tile_renderer)
return tile_renderer | [
"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 : TileRenderer | [
"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
_draw_fast_vline(setter, x, y + r, h - 2 * r, color, aa) # Left
_draw_fast_vline(setter, x + w - 1, y + r, h - 2 * r, color, aa) # Right
# draw four corners
_draw_circle_helper(setter, x + r, y + r, r, 1, color, aa)
_draw_circle_helper(setter, x + w - r - 1, y + r, r, 2, color, aa)
_draw_circle_helper(setter, x + w - r - 1, y + h - r - 1, r, 4, color, aa)
_draw_circle_helper(setter, x + r, y + h - r - 1, r, 8, color, aa) | [
"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_c_object(sse=sse)
headers.update(sse.marshal())
is_valid_bucket_name(bucket_name)
is_non_empty_string(object_name)
response = self._url_open('HEAD', bucket_name=bucket_name,
object_name=object_name, headers=headers)
etag = response.headers.get('etag', '').replace('"', '')
size = int(response.headers.get('content-length', '0'))
content_type = response.headers.get('content-type', '')
last_modified = response.headers.get('last-modified')
## Capture only custom metadata.
custom_metadata = dict()
for k in response.headers:
if is_supported_header(k) or is_amz_header(k):
custom_metadata[k] = response.headers.get(k)
if last_modified:
last_modified = dateutil.parser.parse(last_modified).timetuple()
return Object(bucket_name, object_name, last_modified, etag, size,
content_type=content_type, metadata=custom_metadata) | [
"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
:param column: string search pattern for column names.
"""
fut = self._run_operation(self._impl.columns, **kw)
return fut | [
"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 pattern for column names. | [
"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(self.lines_)
if x.host == host and x.key.lower() in args]
for idx in reversed(sorted(remove_idx)):
del self.lines_[idx] | [
"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
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 at least 16 consumers per queue,
unless the queue was declared as private, and ideally,
impose no limit except as defined by available resources.
PARAMETERS:
queue: shortstr
Specifies the name of the queue to consume from. If
the queue name is null, refers to the current queue
for the channel, which is the last declared queue.
RULE:
If the client did not previously declare a queue,
and the queue name in this method is empty, the
server MUST raise a connection exception with
reply code 530 (not allowed).
consumer_tag: shortstr
Specifies the identifier for the consumer. The
consumer tag is local to a connection, so two clients
can use the same consumer tags. If this field is empty
the server will generate a unique tag.
RULE:
The tag MUST NOT refer to an existing consumer. If
the client attempts to create two consumers with
the same non-empty tag the server MUST raise a
connection exception with reply code 530 (not
allowed).
no_local: boolean
do not deliver own messages
If the no-local field is set the server will not send
messages to the client that published them.
no_ack: boolean
no acknowledgement needed
If this field is set the server does not expect
acknowledgments for messages. That is, when a message
is delivered to the client the server automatically and
silently acknowledges it on behalf of the client. This
functionality increases performance but at the cost of
reliability. Messages can get lost if a client dies
before it can deliver them to the application.
exclusive: boolean
request exclusive access
Request exclusive consumer access, meaning only this
consumer can access the queue.
RULE:
If the server cannot grant exclusive access to the
queue when asked, - because there are other
consumers active - it MUST raise a channel
exception with return code 403 (access refused).
nowait: boolean
do not send a reply method
If set, the server will not respond to the method. The
client should not wait for a reply method. If the
server could not complete the method it will raise a
channel or connection exception.
callback: Python callable
function/method called with each delivered message
For each message delivered by the broker, the
callable will be called with a Message object
as the single argument. If no callable is specified,
messages are quietly discarded, no_ack should probably
be set to True in that case.
"""
args = AMQPWriter()
args.write_short(0)
args.write_shortstr(queue)
args.write_shortstr(consumer_tag)
args.write_bit(no_local)
args.write_bit(no_ack)
args.write_bit(exclusive)
args.write_bit(nowait)
args.write_table(arguments or {})
self._send_method((60, 20), args)
if not nowait:
consumer_tag = self.wait(allowed_methods=[
(60, 21), # Channel.basic_consume_ok
])
self.callbacks[consumer_tag] = callback
if on_cancel:
self.cancel_callbacks[consumer_tag] = on_cancel
if no_ack:
self.no_ack_consumers.add(consumer_tag)
return consumer_tag | [
"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 at least 16 consumers per queue,
unless the queue was declared as private, and ideally,
impose no limit except as defined by available resources.
PARAMETERS:
queue: shortstr
Specifies the name of the queue to consume from. If
the queue name is null, refers to the current queue
for the channel, which is the last declared queue.
RULE:
If the client did not previously declare a queue,
and the queue name in this method is empty, the
server MUST raise a connection exception with
reply code 530 (not allowed).
consumer_tag: shortstr
Specifies the identifier for the consumer. The
consumer tag is local to a connection, so two clients
can use the same consumer tags. If this field is empty
the server will generate a unique tag.
RULE:
The tag MUST NOT refer to an existing consumer. If
the client attempts to create two consumers with
the same non-empty tag the server MUST raise a
connection exception with reply code 530 (not
allowed).
no_local: boolean
do not deliver own messages
If the no-local field is set the server will not send
messages to the client that published them.
no_ack: boolean
no acknowledgement needed
If this field is set the server does not expect
acknowledgments for messages. That is, when a message
is delivered to the client the server automatically and
silently acknowledges it on behalf of the client. This
functionality increases performance but at the cost of
reliability. Messages can get lost if a client dies
before it can deliver them to the application.
exclusive: boolean
request exclusive access
Request exclusive consumer access, meaning only this
consumer can access the queue.
RULE:
If the server cannot grant exclusive access to the
queue when asked, - because there are other
consumers active - it MUST raise a channel
exception with return code 403 (access refused).
nowait: boolean
do not send a reply method
If set, the server will not respond to the method. The
client should not wait for a reply method. If the
server could not complete the method it will raise a
channel or connection exception.
callback: Python callable
function/method called with each delivered message
For each message delivered by the broker, the
callable will be called with a Message object
as the single argument. If no callable is specified,
messages are quietly discarded, no_ack should probably
be set to True in that case. | [
"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 naxis != 2 %i' % wcs.naxis)
w = WCS(naxis=3)
w.wcs.crpix[0] = wcs.wcs.crpix[0]
w.wcs.crpix[1] = wcs.wcs.crpix[1]
w.wcs.ctype[0] = wcs.wcs.ctype[0]
w.wcs.ctype[1] = wcs.wcs.ctype[1]
w.wcs.crval[0] = wcs.wcs.crval[0]
w.wcs.crval[1] = wcs.wcs.crval[1]
w.wcs.cdelt[0] = wcs.wcs.cdelt[0]
w.wcs.cdelt[1] = wcs.wcs.cdelt[1]
w = WCS(w.to_header())
w.wcs.crpix[2] = 1
w.wcs.crval[2] = energies[0]
w.wcs.cdelt[2] = energies[1] - energies[0]
w.wcs.ctype[2] = 'Energy'
return w | [
"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 entity and then authorizes the entity for the given role.
Supported methods:
POST: /auth/{mount_point}/login. Produces: 200 application/json
:param role: The name of the role against which the login is being attempted.
:type role: str | unicode
:param jwt: A signed JSON web token
:type jwt: str | unicode
:param use_token: if True, uses the token in the response received from the auth request to set the "token"
attribute on the the :py:meth:`hvac.adapters.Adapter` instance under the _adapater Client attribute.
:type use_token: bool
:param mount_point: The "path" the method/backend was mounted on.
:type mount_point: str | unicode
:return: The JSON response of the request.
:rtype: dict
"""
params = {
'role': role,
'jwt': jwt,
}
api_path = '/v1/auth/{mount_point}/login'.format(mount_point=mount_point)
response = self._adapter.login(
url=api_path,
use_token=use_token,
json=params,
)
return response | [
"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:
POST: /auth/{mount_point}/login. Produces: 200 application/json
:param role: The name of the role against which the login is being attempted.
:type role: str | unicode
:param jwt: A signed JSON web token
:type jwt: str | unicode
:param use_token: if True, uses the token in the response received from the auth request to set the "token"
attribute on the the :py:meth:`hvac.adapters.Adapter` instance under the _adapater Client attribute.
:type use_token: bool
:param mount_point: The "path" the method/backend was mounted on.
:type mount_point: str | unicode
:return: The JSON response of the request.
:rtype: dict | [
"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 label annotations to embed in the
derivation dict; the value is a list of lists matching
the structure of the derivation (e.g.,
`["S" ["NP" ["NNS" ["Dogs"]]] ["VP" ["VBZ" ["bark"]]]]`)
Returns:
dict: the dictionary representation of the structure
"""
fields = set(fields)
diff = fields.difference(_all_fields)
if isinstance(labels, Sequence):
labels = _map_labels(self, labels)
elif labels is None:
labels = {}
if diff:
raise ValueError(
'Invalid field(s): {}'.format(', '.join(diff))
)
return _to_dict(self, fields, labels) | [
"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 value is a list of lists matching
the structure of the derivation (e.g.,
`["S" ["NP" ["NNS" ["Dogs"]]] ["VP" ["VBZ" ["bark"]]]]`)
Returns:
dict: the dictionary representation of the structure | [
"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_ins()) > 1:
pre_ins = node.get_ins()[:-1]
last_ins = node.get_ins()[-1]
pre_node = StatementBlock('%s-pre' % node.name, pre_ins)
cond_node = CondBlock('%s-cond' % node.name, [last_ins])
node_map[node] = pre_node
node_map[pre_node] = pre_node
node_map[cond_node] = cond_node
pre_node.copy_from(node)
cond_node.copy_from(node)
for var in node.var_to_declare:
pre_node.add_variable_declaration(var)
pre_node.type.is_stmt = True
cond_node.true = node.true
cond_node.false = node.false
for pred in graph.all_preds(node):
pred_node = node_map[pred]
# Verify that the link is not an exception link
if node not in graph.sucs(pred):
graph.add_catch_edge(pred_node, pre_node)
continue
if pred is node:
pred_node = cond_node
if pred.type.is_cond: # and not (pred is node):
if pred.true is node:
pred_node.true = pre_node
if pred.false is node:
pred_node.false = pre_node
graph.add_edge(pred_node, pre_node)
for suc in graph.sucs(node):
graph.add_edge(cond_node, node_map[suc])
# We link all the exceptions to the pre node instead of the
# condition node, which should not trigger any of them.
for suc in graph.catch_edges.get(node, []):
graph.add_catch_edge(pre_node, node_map[suc])
if node is graph.entry:
graph.entry = pre_node
graph.add_node(pre_node)
graph.add_node(cond_node)
graph.add_edge(pre_node, cond_node)
pre_node.update_attribute_with(node_map)
cond_node.update_attribute_with(node_map)
graph.remove_node(node)
else:
to_update.add(node)
for node in to_update:
node.update_attribute_with(node_map) | [
"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()
cursor.execute(
'SELECT arrival_secs,departure_secs,stop_headsign,pickup_type,'
'drop_off_type,shape_dist_traveled,stop_id,stop_sequence,timepoint '
'FROM stop_times '
'WHERE trip_id=? '
'ORDER BY stop_sequence', (self.trip_id,))
stop_times = []
stoptime_class = self.GetGtfsFactory().StopTime
if problems is None:
# TODO: delete this branch when StopTime.__init__ doesn't need a
# ProblemReporter
problems = problems_module.default_problem_reporter
for row in cursor.fetchall():
stop = self._schedule.GetStop(row[6])
stop_times.append(stoptime_class(problems=problems,
stop=stop,
arrival_secs=row[0],
departure_secs=row[1],
stop_headsign=row[2],
pickup_type=row[3],
drop_off_type=row[4],
shape_dist_traveled=row[5],
stop_sequence=row[7],
timepoint=row[8]))
return stop_times | [
"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
except SyntaxError as e:
return text, e
finally:
parser._parsing_parenthesized_simple_values_expression = False | [
"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, value)
self._insert(node)
else:
node[1] = value | [
"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 kwargs in `get_urls()`.
"""
content_type = ContentType.objects.get(app_label=app_label,
model=model_name)
model = content_type.model_class()
model_admin = self._registry[model].__class__(model, self)
model_admin.change_list_template = "admin/hatband/change_list.json"
return model_admin.changelist_view(request) | [
"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.
This method can be overwritten by subclasses who may perfer to add
analytical methods for some or all methods as this is much faster.
If the calculation does not succeed, returns the actual error
encountered.
Parameters
----------
T : float
Temperature at which to calculate the derivative, [K]
method : str
Method for which to find the derivative
order : int
Order of the derivative, >= 1
Returns
-------
derivative : float
Calculated derivative property, [`units/K^order`]
'''
return derivative(self.calculate, T, dx=1e-6, args=[method], n=order, order=1+order*2) | [
"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 perfer to add
analytical methods for some or all methods as this is much faster.
If the calculation does not succeed, returns the actual error
encountered.
Parameters
----------
T : float
Temperature at which to calculate the derivative, [K]
method : str
Method for which to find the derivative
order : int
Order of the derivative, >= 1
Returns
-------
derivative : float
Calculated derivative property, [`units/K^order`] | [
"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" in value:
return int(value.replace("MB", "")) * MB_TO_BYTES
else:
return int(value)
else:
return value | [
"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({'ids': asset_ids})
return Response(_sanitize_record(resp_body), 200, content_type='application/json') | [
"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
------
ndarray :
probability of cloud over land based on variability
"""
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.TIF
mod_ndvi = np.where(self.red_saturated & (self.nir > self.red), 0, self.ndvi)
# if green is saturated and less than swir1, ndsi = LE07_clip_L1TP_039027_20150529_20160902_01_T1_B1.TIF
mod_ndsi = np.where(self.green_saturated & (self.swir1 > self.green), 0, self.ndsi)
ndi_max = np.fmax(np.absolute(mod_ndvi), np.absolute(mod_ndsi))
else:
ndi_max = np.fmax(np.absolute(self.ndvi), np.absolute(self.ndsi))
f_max = 1.0 - np.fmax(ndi_max, whiteness)
return f_max | [
"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 over land based on variability | [
"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 still invoke the bot
in ignored channels.
"""
if ctx.invoked_subcommand is None:
await self.bot.say('Invalid subcommand passed: {0.subcommand_passed}'.format(ctx)) | [
"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 channels. | [
"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
path_out : str
Path to an output folder in which Eidos places the output
JSON-LD files
"""
path_in = os.path.realpath(os.path.expanduser(path_in))
path_out = os.path.realpath(os.path.expanduser(path_out))
logger.info('Running Eidos on input folder %s' % path_in)
run_eidos('apps.ExtractFromDirectory', path_in, path_out) | [
"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 in which Eidos places the output
JSON-LD files | [
"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.
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``
debug: be verbose?
headers: do the files have header lines?
"""
writer = csv.writer(outfile, dialect=output_dialect)
written_header = False
header_items = [] # type: List[str]
for filename in filenames:
log.info("Processing file " + repr(filename))
with open(filename, 'r') as f:
reader = csv.reader(f, dialect=input_dialect)
if headers:
if not written_header:
header_items = next(reader)
if debug:
log.debug("Header row: {!r}", header_items)
writer.writerow(header_items)
written_header = True
else:
new_headers = next(reader)
if new_headers != header_items:
raise ValueError(
"Header line in file {filename} doesn't match - "
"it was {new} but previous was {old}".format(
filename=repr(filename),
new=repr(new_headers),
old=repr(header_items),
))
if debug:
log.debug("Header row matches previous")
else:
if debug:
log.debug("No headers in use")
for row in reader:
if debug:
log.debug("Data row: {!r}", row)
writer.writerow(row) | [
"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``
debug: be verbose?
headers: do the files have header lines? | [
"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
# Note: the following algorithm take advantage of the Jumbo option
# mandatory alignment (4n + 2, RFC2675 Section 2)
jumbo_len = None
idx = 0
offset = 4 * idx + 2
while offset <= len(data):
opt_type = orb(data[offset])
if opt_type == 0xc2: # Jumbo option
jumbo_len = struct.unpack("I", data[offset + 2:offset + 2 + 4])[0] # noqa: E501
break
offset = 4 * idx + 2
idx += 1
if jumbo_len is None:
warning("Scapy did not find a Jumbo option")
jumbo_len = 0
tmp_len = hbh_len + jumbo_len
else:
tmp_len = self.plen
return data[:tmp_len], data[tmp_len:] | [
"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
# Functions that return Futures typically swallow all
# exceptions and store them in the Future. If a Future
# makes it out to the IOLoop, ensure its exception (if any)
# gets logged too.
try:
ret = gen.convert_yielded(ret)
except gen.BadYieldError:
# It's not unusual for add_callback to be used with
# methods returning a non-None and non-yieldable
# result, which should just be ignored.
pass
else:
self.add_future(ret, self._discard_future_result)
except asyncio.CancelledError:
pass
except Exception:
app_log.error("Exception in callback %r", callback, exc_info=True) | [
"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
Raises:
NotImplementedError: Raised if snapping is not supported
"""
if self.ndims > 1:
raise NotImplementedError("Closest method currently only "
"implemented for 1D Elements")
if kwargs:
if len(kwargs) > 1:
raise NotImplementedError("Closest method currently only "
"supports 1D indexes")
samples = list(kwargs.values())[0]
coords = samples if isinstance(samples, list) else [samples]
xs = self.dimension_values(0)
if xs.dtype.kind in 'SO':
raise NotImplementedError("Closest only supported for numeric types")
idxs = [np.argmin(np.abs(xs-coord)) for coord in coords]
return [xs[idx] for idx in idxs] | [
"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 snapping is not supported | [
"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 a list of
reporters that it could be possibly referring to.
"""
variations_out = {}
for reporter_key, data_list in reporters.items():
# For each reporter key...
for data in data_list:
# For each book it maps to...
for variation_key, variation_value in data["variations"].items():
try:
variations_list = variations_out[variation_key]
if variation_value not in variations_list:
variations_list.append(variation_value)
except KeyError:
# The item wasn't there; add it.
variations_out[variation_key] = [variation_value]
return variations_out | [
"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 possibly referring to. | [
"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_int(value.get('0')), 'experiments'),
'value': collaborations[0],
})
else:
result.extend({'value': collaboration} for collaboration in collaborations)
return result | [
"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 in the :class:`Task` class
(e.g Task.S_OK) or a string e.g "S_OK"
nids is an optional list of node identifiers used to filter the tasks.
"""
return self._iflat_tasks_wti(status=status, op=op, nids=nids, with_wti=False) | [
"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"
nids is an optional list of node identifiers used to filter the tasks. | [
"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.