repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
inveniosoftware/invenio-access | invenio_access/models.py | get_action_cache_key | def get_action_cache_key(name, argument):
"""Get an action cache key string."""
tokens = [str(name)]
if argument:
tokens.append(str(argument))
return '::'.join(tokens) | python | def get_action_cache_key(name, argument):
"""Get an action cache key string."""
tokens = [str(name)]
if argument:
tokens.append(str(argument))
return '::'.join(tokens) | [
"def",
"get_action_cache_key",
"(",
"name",
",",
"argument",
")",
":",
"tokens",
"=",
"[",
"str",
"(",
"name",
")",
"]",
"if",
"argument",
":",
"tokens",
".",
"append",
"(",
"str",
"(",
"argument",
")",
")",
"return",
"'::'",
".",
"join",
"(",
"tokens",
")"
] | Get an action cache key string. | [
"Get",
"an",
"action",
"cache",
"key",
"string",
"."
] | 3b033a4bdc110eb2f7e9f08f0744a780884bfc80 | https://github.com/inveniosoftware/invenio-access/blob/3b033a4bdc110eb2f7e9f08f0744a780884bfc80/invenio_access/models.py#L200-L205 | train |
inveniosoftware/invenio-access | invenio_access/models.py | removed_or_inserted_action | def removed_or_inserted_action(mapper, connection, target):
"""Remove the action from cache when an item is inserted or deleted."""
current_access.delete_action_cache(get_action_cache_key(target.action,
target.argument)) | python | def removed_or_inserted_action(mapper, connection, target):
"""Remove the action from cache when an item is inserted or deleted."""
current_access.delete_action_cache(get_action_cache_key(target.action,
target.argument)) | [
"def",
"removed_or_inserted_action",
"(",
"mapper",
",",
"connection",
",",
"target",
")",
":",
"current_access",
".",
"delete_action_cache",
"(",
"get_action_cache_key",
"(",
"target",
".",
"action",
",",
"target",
".",
"argument",
")",
")"
] | Remove the action from cache when an item is inserted or deleted. | [
"Remove",
"the",
"action",
"from",
"cache",
"when",
"an",
"item",
"is",
"inserted",
"or",
"deleted",
"."
] | 3b033a4bdc110eb2f7e9f08f0744a780884bfc80 | https://github.com/inveniosoftware/invenio-access/blob/3b033a4bdc110eb2f7e9f08f0744a780884bfc80/invenio_access/models.py#L208-L211 | train |
inveniosoftware/invenio-access | invenio_access/models.py | changed_action | def changed_action(mapper, connection, target):
"""Remove the action from cache when an item is updated."""
action_history = get_history(target, 'action')
argument_history = get_history(target, 'argument')
owner_history = get_history(
target,
'user' if isinstance(target, ActionUsers) else
'role' if isinstance(target, ActionRoles) else 'role_name')
if action_history.has_changes() or argument_history.has_changes() \
or owner_history.has_changes():
current_access.delete_action_cache(
get_action_cache_key(target.action, target.argument))
current_access.delete_action_cache(
get_action_cache_key(
action_history.deleted[0] if action_history.deleted
else target.action,
argument_history.deleted[0] if argument_history.deleted
else target.argument)
) | python | def changed_action(mapper, connection, target):
"""Remove the action from cache when an item is updated."""
action_history = get_history(target, 'action')
argument_history = get_history(target, 'argument')
owner_history = get_history(
target,
'user' if isinstance(target, ActionUsers) else
'role' if isinstance(target, ActionRoles) else 'role_name')
if action_history.has_changes() or argument_history.has_changes() \
or owner_history.has_changes():
current_access.delete_action_cache(
get_action_cache_key(target.action, target.argument))
current_access.delete_action_cache(
get_action_cache_key(
action_history.deleted[0] if action_history.deleted
else target.action,
argument_history.deleted[0] if argument_history.deleted
else target.argument)
) | [
"def",
"changed_action",
"(",
"mapper",
",",
"connection",
",",
"target",
")",
":",
"action_history",
"=",
"get_history",
"(",
"target",
",",
"'action'",
")",
"argument_history",
"=",
"get_history",
"(",
"target",
",",
"'argument'",
")",
"owner_history",
"=",
"get_history",
"(",
"target",
",",
"'user'",
"if",
"isinstance",
"(",
"target",
",",
"ActionUsers",
")",
"else",
"'role'",
"if",
"isinstance",
"(",
"target",
",",
"ActionRoles",
")",
"else",
"'role_name'",
")",
"if",
"action_history",
".",
"has_changes",
"(",
")",
"or",
"argument_history",
".",
"has_changes",
"(",
")",
"or",
"owner_history",
".",
"has_changes",
"(",
")",
":",
"current_access",
".",
"delete_action_cache",
"(",
"get_action_cache_key",
"(",
"target",
".",
"action",
",",
"target",
".",
"argument",
")",
")",
"current_access",
".",
"delete_action_cache",
"(",
"get_action_cache_key",
"(",
"action_history",
".",
"deleted",
"[",
"0",
"]",
"if",
"action_history",
".",
"deleted",
"else",
"target",
".",
"action",
",",
"argument_history",
".",
"deleted",
"[",
"0",
"]",
"if",
"argument_history",
".",
"deleted",
"else",
"target",
".",
"argument",
")",
")"
] | Remove the action from cache when an item is updated. | [
"Remove",
"the",
"action",
"from",
"cache",
"when",
"an",
"item",
"is",
"updated",
"."
] | 3b033a4bdc110eb2f7e9f08f0744a780884bfc80 | https://github.com/inveniosoftware/invenio-access/blob/3b033a4bdc110eb2f7e9f08f0744a780884bfc80/invenio_access/models.py#L214-L233 | train |
inveniosoftware/invenio-access | invenio_access/models.py | ActionNeedMixin.allow | def allow(cls, action, **kwargs):
"""Allow the given action need.
:param action: The action to allow.
:returns: A :class:`invenio_access.models.ActionNeedMixin` instance.
"""
return cls.create(action, exclude=False, **kwargs) | python | def allow(cls, action, **kwargs):
"""Allow the given action need.
:param action: The action to allow.
:returns: A :class:`invenio_access.models.ActionNeedMixin` instance.
"""
return cls.create(action, exclude=False, **kwargs) | [
"def",
"allow",
"(",
"cls",
",",
"action",
",",
"**",
"kwargs",
")",
":",
"return",
"cls",
".",
"create",
"(",
"action",
",",
"exclude",
"=",
"False",
",",
"**",
"kwargs",
")"
] | Allow the given action need.
:param action: The action to allow.
:returns: A :class:`invenio_access.models.ActionNeedMixin` instance. | [
"Allow",
"the",
"given",
"action",
"need",
"."
] | 3b033a4bdc110eb2f7e9f08f0744a780884bfc80 | https://github.com/inveniosoftware/invenio-access/blob/3b033a4bdc110eb2f7e9f08f0744a780884bfc80/invenio_access/models.py#L62-L68 | train |
inveniosoftware/invenio-access | invenio_access/models.py | ActionNeedMixin.deny | def deny(cls, action, **kwargs):
"""Deny the given action need.
:param action: The action to deny.
:returns: A :class:`invenio_access.models.ActionNeedMixin` instance.
"""
return cls.create(action, exclude=True, **kwargs) | python | def deny(cls, action, **kwargs):
"""Deny the given action need.
:param action: The action to deny.
:returns: A :class:`invenio_access.models.ActionNeedMixin` instance.
"""
return cls.create(action, exclude=True, **kwargs) | [
"def",
"deny",
"(",
"cls",
",",
"action",
",",
"**",
"kwargs",
")",
":",
"return",
"cls",
".",
"create",
"(",
"action",
",",
"exclude",
"=",
"True",
",",
"**",
"kwargs",
")"
] | Deny the given action need.
:param action: The action to deny.
:returns: A :class:`invenio_access.models.ActionNeedMixin` instance. | [
"Deny",
"the",
"given",
"action",
"need",
"."
] | 3b033a4bdc110eb2f7e9f08f0744a780884bfc80 | https://github.com/inveniosoftware/invenio-access/blob/3b033a4bdc110eb2f7e9f08f0744a780884bfc80/invenio_access/models.py#L71-L77 | train |
inveniosoftware/invenio-access | invenio_access/models.py | ActionNeedMixin.query_by_action | def query_by_action(cls, action, argument=None):
"""Prepare query object with filtered action.
:param action: The action to deny.
:param argument: The action argument. If it's ``None`` then, if exists,
the ``action.argument`` will be taken. In the worst case will be
set as ``None``. (Default: ``None``)
:returns: A query object.
"""
query = cls.query.filter_by(action=action.value)
argument = argument or getattr(action, 'argument', None)
if argument is not None:
query = query.filter(db.or_(
cls.argument == str(argument),
cls.argument.is_(None),
))
else:
query = query.filter(cls.argument.is_(None))
return query | python | def query_by_action(cls, action, argument=None):
"""Prepare query object with filtered action.
:param action: The action to deny.
:param argument: The action argument. If it's ``None`` then, if exists,
the ``action.argument`` will be taken. In the worst case will be
set as ``None``. (Default: ``None``)
:returns: A query object.
"""
query = cls.query.filter_by(action=action.value)
argument = argument or getattr(action, 'argument', None)
if argument is not None:
query = query.filter(db.or_(
cls.argument == str(argument),
cls.argument.is_(None),
))
else:
query = query.filter(cls.argument.is_(None))
return query | [
"def",
"query_by_action",
"(",
"cls",
",",
"action",
",",
"argument",
"=",
"None",
")",
":",
"query",
"=",
"cls",
".",
"query",
".",
"filter_by",
"(",
"action",
"=",
"action",
".",
"value",
")",
"argument",
"=",
"argument",
"or",
"getattr",
"(",
"action",
",",
"'argument'",
",",
"None",
")",
"if",
"argument",
"is",
"not",
"None",
":",
"query",
"=",
"query",
".",
"filter",
"(",
"db",
".",
"or_",
"(",
"cls",
".",
"argument",
"==",
"str",
"(",
"argument",
")",
",",
"cls",
".",
"argument",
".",
"is_",
"(",
"None",
")",
",",
")",
")",
"else",
":",
"query",
"=",
"query",
".",
"filter",
"(",
"cls",
".",
"argument",
".",
"is_",
"(",
"None",
")",
")",
"return",
"query"
] | Prepare query object with filtered action.
:param action: The action to deny.
:param argument: The action argument. If it's ``None`` then, if exists,
the ``action.argument`` will be taken. In the worst case will be
set as ``None``. (Default: ``None``)
:returns: A query object. | [
"Prepare",
"query",
"object",
"with",
"filtered",
"action",
"."
] | 3b033a4bdc110eb2f7e9f08f0744a780884bfc80 | https://github.com/inveniosoftware/invenio-access/blob/3b033a4bdc110eb2f7e9f08f0744a780884bfc80/invenio_access/models.py#L80-L98 | train |
BD2KGenomics/protect | src/protect/binding_prediction/mhci.py | predict_mhci_binding | def predict_mhci_binding(job, peptfile, allele, peplen, univ_options, mhci_options):
"""
Predict binding for each peptide in `peptfile` to `allele` using the IEDB mhci binding
prediction tool.
:param toil.fileStore.FileID peptfile: The input peptide fasta
:param str allele: Allele to predict binding against
:param str peplen: Length of peptides to process
:param dict univ_options: Dict of universal options used by almost all tools
:param dict mhci_options: Options specific to mhci binding prediction
:return: fsID for file containing the predictions
:rtype: toil.fileStore.FileID
"""
work_dir = os.getcwd()
input_files = {
'peptfile.faa': peptfile}
input_files = get_files_from_filestore(job, input_files, work_dir, docker=True)
peptides = read_peptide_file(os.path.join(os.getcwd(), 'peptfile.faa'))
if not peptides:
return job.fileStore.writeGlobalFile(job.fileStore.getLocalTempFile())
parameters = [mhci_options['pred'],
allele,
peplen,
input_files['peptfile.faa']]
with open('/'.join([work_dir, 'predictions.tsv']), 'w') as predfile:
docker_call(tool='mhci', tool_parameters=parameters, work_dir=work_dir,
dockerhub=univ_options['dockerhub'], outfile=predfile, interactive=True,
tool_version=mhci_options['version'])
output_file = job.fileStore.writeGlobalFile(predfile.name)
job.fileStore.logToMaster('Ran mhci on %s:%s:%s successfully'
% (univ_options['patient'], allele, peplen))
return output_file | python | def predict_mhci_binding(job, peptfile, allele, peplen, univ_options, mhci_options):
"""
Predict binding for each peptide in `peptfile` to `allele` using the IEDB mhci binding
prediction tool.
:param toil.fileStore.FileID peptfile: The input peptide fasta
:param str allele: Allele to predict binding against
:param str peplen: Length of peptides to process
:param dict univ_options: Dict of universal options used by almost all tools
:param dict mhci_options: Options specific to mhci binding prediction
:return: fsID for file containing the predictions
:rtype: toil.fileStore.FileID
"""
work_dir = os.getcwd()
input_files = {
'peptfile.faa': peptfile}
input_files = get_files_from_filestore(job, input_files, work_dir, docker=True)
peptides = read_peptide_file(os.path.join(os.getcwd(), 'peptfile.faa'))
if not peptides:
return job.fileStore.writeGlobalFile(job.fileStore.getLocalTempFile())
parameters = [mhci_options['pred'],
allele,
peplen,
input_files['peptfile.faa']]
with open('/'.join([work_dir, 'predictions.tsv']), 'w') as predfile:
docker_call(tool='mhci', tool_parameters=parameters, work_dir=work_dir,
dockerhub=univ_options['dockerhub'], outfile=predfile, interactive=True,
tool_version=mhci_options['version'])
output_file = job.fileStore.writeGlobalFile(predfile.name)
job.fileStore.logToMaster('Ran mhci on %s:%s:%s successfully'
% (univ_options['patient'], allele, peplen))
return output_file | [
"def",
"predict_mhci_binding",
"(",
"job",
",",
"peptfile",
",",
"allele",
",",
"peplen",
",",
"univ_options",
",",
"mhci_options",
")",
":",
"work_dir",
"=",
"os",
".",
"getcwd",
"(",
")",
"input_files",
"=",
"{",
"'peptfile.faa'",
":",
"peptfile",
"}",
"input_files",
"=",
"get_files_from_filestore",
"(",
"job",
",",
"input_files",
",",
"work_dir",
",",
"docker",
"=",
"True",
")",
"peptides",
"=",
"read_peptide_file",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"'peptfile.faa'",
")",
")",
"if",
"not",
"peptides",
":",
"return",
"job",
".",
"fileStore",
".",
"writeGlobalFile",
"(",
"job",
".",
"fileStore",
".",
"getLocalTempFile",
"(",
")",
")",
"parameters",
"=",
"[",
"mhci_options",
"[",
"'pred'",
"]",
",",
"allele",
",",
"peplen",
",",
"input_files",
"[",
"'peptfile.faa'",
"]",
"]",
"with",
"open",
"(",
"'/'",
".",
"join",
"(",
"[",
"work_dir",
",",
"'predictions.tsv'",
"]",
")",
",",
"'w'",
")",
"as",
"predfile",
":",
"docker_call",
"(",
"tool",
"=",
"'mhci'",
",",
"tool_parameters",
"=",
"parameters",
",",
"work_dir",
"=",
"work_dir",
",",
"dockerhub",
"=",
"univ_options",
"[",
"'dockerhub'",
"]",
",",
"outfile",
"=",
"predfile",
",",
"interactive",
"=",
"True",
",",
"tool_version",
"=",
"mhci_options",
"[",
"'version'",
"]",
")",
"output_file",
"=",
"job",
".",
"fileStore",
".",
"writeGlobalFile",
"(",
"predfile",
".",
"name",
")",
"job",
".",
"fileStore",
".",
"logToMaster",
"(",
"'Ran mhci on %s:%s:%s successfully'",
"%",
"(",
"univ_options",
"[",
"'patient'",
"]",
",",
"allele",
",",
"peplen",
")",
")",
"return",
"output_file"
] | Predict binding for each peptide in `peptfile` to `allele` using the IEDB mhci binding
prediction tool.
:param toil.fileStore.FileID peptfile: The input peptide fasta
:param str allele: Allele to predict binding against
:param str peplen: Length of peptides to process
:param dict univ_options: Dict of universal options used by almost all tools
:param dict mhci_options: Options specific to mhci binding prediction
:return: fsID for file containing the predictions
:rtype: toil.fileStore.FileID | [
"Predict",
"binding",
"for",
"each",
"peptide",
"in",
"peptfile",
"to",
"allele",
"using",
"the",
"IEDB",
"mhci",
"binding",
"prediction",
"tool",
"."
] | 06310682c50dcf8917b912c8e551299ff7ee41ce | https://github.com/BD2KGenomics/protect/blob/06310682c50dcf8917b912c8e551299ff7ee41ce/src/protect/binding_prediction/mhci.py#L23-L54 | train |
rmohr/static3 | static.py | iter_and_close | def iter_and_close(file_like, block_size):
"""Yield file contents by block then close the file."""
while 1:
try:
block = file_like.read(block_size)
if block:
yield block
else:
raise StopIteration
except StopIteration:
file_like.close()
return | python | def iter_and_close(file_like, block_size):
"""Yield file contents by block then close the file."""
while 1:
try:
block = file_like.read(block_size)
if block:
yield block
else:
raise StopIteration
except StopIteration:
file_like.close()
return | [
"def",
"iter_and_close",
"(",
"file_like",
",",
"block_size",
")",
":",
"while",
"1",
":",
"try",
":",
"block",
"=",
"file_like",
".",
"read",
"(",
"block_size",
")",
"if",
"block",
":",
"yield",
"block",
"else",
":",
"raise",
"StopIteration",
"except",
"StopIteration",
":",
"file_like",
".",
"close",
"(",
")",
"return"
] | Yield file contents by block then close the file. | [
"Yield",
"file",
"contents",
"by",
"block",
"then",
"close",
"the",
"file",
"."
] | e5f88c5e91789bd4db7fde0cf59e4a15c3326f11 | https://github.com/rmohr/static3/blob/e5f88c5e91789bd4db7fde0cf59e4a15c3326f11/static.py#L239-L250 | train |
rmohr/static3 | static.py | cling_wrap | def cling_wrap(package_name, dir_name, **kw):
"""Return a Cling that serves from the given package and dir_name.
This uses pkg_resources.resource_filename which is not the
recommended way, since it extracts the files.
I think this works fine unless you have some _very_ serious
requirements for static content, in which case you probably
shouldn't be serving it through a WSGI app, IMHO. YMMV.
"""
resource = Requirement.parse(package_name)
return Cling(resource_filename(resource, dir_name), **kw) | python | def cling_wrap(package_name, dir_name, **kw):
"""Return a Cling that serves from the given package and dir_name.
This uses pkg_resources.resource_filename which is not the
recommended way, since it extracts the files.
I think this works fine unless you have some _very_ serious
requirements for static content, in which case you probably
shouldn't be serving it through a WSGI app, IMHO. YMMV.
"""
resource = Requirement.parse(package_name)
return Cling(resource_filename(resource, dir_name), **kw) | [
"def",
"cling_wrap",
"(",
"package_name",
",",
"dir_name",
",",
"**",
"kw",
")",
":",
"resource",
"=",
"Requirement",
".",
"parse",
"(",
"package_name",
")",
"return",
"Cling",
"(",
"resource_filename",
"(",
"resource",
",",
"dir_name",
")",
",",
"**",
"kw",
")"
] | Return a Cling that serves from the given package and dir_name.
This uses pkg_resources.resource_filename which is not the
recommended way, since it extracts the files.
I think this works fine unless you have some _very_ serious
requirements for static content, in which case you probably
shouldn't be serving it through a WSGI app, IMHO. YMMV. | [
"Return",
"a",
"Cling",
"that",
"serves",
"from",
"the",
"given",
"package",
"and",
"dir_name",
"."
] | e5f88c5e91789bd4db7fde0cf59e4a15c3326f11 | https://github.com/rmohr/static3/blob/e5f88c5e91789bd4db7fde0cf59e4a15c3326f11/static.py#L253-L264 | train |
rmohr/static3 | static.py | Cling._is_under_root | def _is_under_root(self, full_path):
"""Guard against arbitrary file retrieval."""
if (path.abspath(full_path) + path.sep)\
.startswith(path.abspath(self.root) + path.sep):
return True
else:
return False | python | def _is_under_root(self, full_path):
"""Guard against arbitrary file retrieval."""
if (path.abspath(full_path) + path.sep)\
.startswith(path.abspath(self.root) + path.sep):
return True
else:
return False | [
"def",
"_is_under_root",
"(",
"self",
",",
"full_path",
")",
":",
"if",
"(",
"path",
".",
"abspath",
"(",
"full_path",
")",
"+",
"path",
".",
"sep",
")",
".",
"startswith",
"(",
"path",
".",
"abspath",
"(",
"self",
".",
"root",
")",
"+",
"path",
".",
"sep",
")",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | Guard against arbitrary file retrieval. | [
"Guard",
"against",
"arbitrary",
"file",
"retrieval",
"."
] | e5f88c5e91789bd4db7fde0cf59e4a15c3326f11 | https://github.com/rmohr/static3/blob/e5f88c5e91789bd4db7fde0cf59e4a15c3326f11/static.py#L200-L206 | train |
rmohr/static3 | static.py | Shock._match_magic | def _match_magic(self, full_path):
"""Return the first magic that matches this path or None."""
for magic in self.magics:
if magic.matches(full_path):
return magic | python | def _match_magic(self, full_path):
"""Return the first magic that matches this path or None."""
for magic in self.magics:
if magic.matches(full_path):
return magic | [
"def",
"_match_magic",
"(",
"self",
",",
"full_path",
")",
":",
"for",
"magic",
"in",
"self",
".",
"magics",
":",
"if",
"magic",
".",
"matches",
"(",
"full_path",
")",
":",
"return",
"magic"
] | Return the first magic that matches this path or None. | [
"Return",
"the",
"first",
"magic",
"that",
"matches",
"this",
"path",
"or",
"None",
"."
] | e5f88c5e91789bd4db7fde0cf59e4a15c3326f11 | https://github.com/rmohr/static3/blob/e5f88c5e91789bd4db7fde0cf59e4a15c3326f11/static.py#L296-L300 | train |
rmohr/static3 | static.py | Shock._full_path | def _full_path(self, path_info):
"""Return the full path from which to read."""
full_path = self.root + path_info
if path.exists(full_path):
return full_path
else:
for magic in self.magics:
if path.exists(magic.new_path(full_path)):
return magic.new_path(full_path)
else:
return full_path | python | def _full_path(self, path_info):
"""Return the full path from which to read."""
full_path = self.root + path_info
if path.exists(full_path):
return full_path
else:
for magic in self.magics:
if path.exists(magic.new_path(full_path)):
return magic.new_path(full_path)
else:
return full_path | [
"def",
"_full_path",
"(",
"self",
",",
"path_info",
")",
":",
"full_path",
"=",
"self",
".",
"root",
"+",
"path_info",
"if",
"path",
".",
"exists",
"(",
"full_path",
")",
":",
"return",
"full_path",
"else",
":",
"for",
"magic",
"in",
"self",
".",
"magics",
":",
"if",
"path",
".",
"exists",
"(",
"magic",
".",
"new_path",
"(",
"full_path",
")",
")",
":",
"return",
"magic",
".",
"new_path",
"(",
"full_path",
")",
"else",
":",
"return",
"full_path"
] | Return the full path from which to read. | [
"Return",
"the",
"full",
"path",
"from",
"which",
"to",
"read",
"."
] | e5f88c5e91789bd4db7fde0cf59e4a15c3326f11 | https://github.com/rmohr/static3/blob/e5f88c5e91789bd4db7fde0cf59e4a15c3326f11/static.py#L302-L312 | train |
rmohr/static3 | static.py | Shock._guess_type | def _guess_type(self, full_path):
"""Guess the mime type magically or using the mimetypes module."""
magic = self._match_magic(full_path)
if magic is not None:
return (mimetypes.guess_type(magic.old_path(full_path))[0]
or 'text/plain')
else:
return mimetypes.guess_type(full_path)[0] or 'text/plain' | python | def _guess_type(self, full_path):
"""Guess the mime type magically or using the mimetypes module."""
magic = self._match_magic(full_path)
if magic is not None:
return (mimetypes.guess_type(magic.old_path(full_path))[0]
or 'text/plain')
else:
return mimetypes.guess_type(full_path)[0] or 'text/plain' | [
"def",
"_guess_type",
"(",
"self",
",",
"full_path",
")",
":",
"magic",
"=",
"self",
".",
"_match_magic",
"(",
"full_path",
")",
"if",
"magic",
"is",
"not",
"None",
":",
"return",
"(",
"mimetypes",
".",
"guess_type",
"(",
"magic",
".",
"old_path",
"(",
"full_path",
")",
")",
"[",
"0",
"]",
"or",
"'text/plain'",
")",
"else",
":",
"return",
"mimetypes",
".",
"guess_type",
"(",
"full_path",
")",
"[",
"0",
"]",
"or",
"'text/plain'"
] | Guess the mime type magically or using the mimetypes module. | [
"Guess",
"the",
"mime",
"type",
"magically",
"or",
"using",
"the",
"mimetypes",
"module",
"."
] | e5f88c5e91789bd4db7fde0cf59e4a15c3326f11 | https://github.com/rmohr/static3/blob/e5f88c5e91789bd4db7fde0cf59e4a15c3326f11/static.py#L314-L321 | train |
rmohr/static3 | static.py | Shock._conditions | def _conditions(self, full_path, environ):
"""Return Etag and Last-Modified values defaults to now for both."""
magic = self._match_magic(full_path)
if magic is not None:
return magic.conditions(full_path, environ)
else:
mtime = stat(full_path).st_mtime
return str(mtime), rfc822.formatdate(mtime) | python | def _conditions(self, full_path, environ):
"""Return Etag and Last-Modified values defaults to now for both."""
magic = self._match_magic(full_path)
if magic is not None:
return magic.conditions(full_path, environ)
else:
mtime = stat(full_path).st_mtime
return str(mtime), rfc822.formatdate(mtime) | [
"def",
"_conditions",
"(",
"self",
",",
"full_path",
",",
"environ",
")",
":",
"magic",
"=",
"self",
".",
"_match_magic",
"(",
"full_path",
")",
"if",
"magic",
"is",
"not",
"None",
":",
"return",
"magic",
".",
"conditions",
"(",
"full_path",
",",
"environ",
")",
"else",
":",
"mtime",
"=",
"stat",
"(",
"full_path",
")",
".",
"st_mtime",
"return",
"str",
"(",
"mtime",
")",
",",
"rfc822",
".",
"formatdate",
"(",
"mtime",
")"
] | Return Etag and Last-Modified values defaults to now for both. | [
"Return",
"Etag",
"and",
"Last",
"-",
"Modified",
"values",
"defaults",
"to",
"now",
"for",
"both",
"."
] | e5f88c5e91789bd4db7fde0cf59e4a15c3326f11 | https://github.com/rmohr/static3/blob/e5f88c5e91789bd4db7fde0cf59e4a15c3326f11/static.py#L323-L330 | train |
rmohr/static3 | static.py | Shock._file_like | def _file_like(self, full_path):
"""Return the appropriate file object."""
magic = self._match_magic(full_path)
if magic is not None:
return magic.file_like(full_path, self.encoding)
else:
return open(full_path, 'rb') | python | def _file_like(self, full_path):
"""Return the appropriate file object."""
magic = self._match_magic(full_path)
if magic is not None:
return magic.file_like(full_path, self.encoding)
else:
return open(full_path, 'rb') | [
"def",
"_file_like",
"(",
"self",
",",
"full_path",
")",
":",
"magic",
"=",
"self",
".",
"_match_magic",
"(",
"full_path",
")",
"if",
"magic",
"is",
"not",
"None",
":",
"return",
"magic",
".",
"file_like",
"(",
"full_path",
",",
"self",
".",
"encoding",
")",
"else",
":",
"return",
"open",
"(",
"full_path",
",",
"'rb'",
")"
] | Return the appropriate file object. | [
"Return",
"the",
"appropriate",
"file",
"object",
"."
] | e5f88c5e91789bd4db7fde0cf59e4a15c3326f11 | https://github.com/rmohr/static3/blob/e5f88c5e91789bd4db7fde0cf59e4a15c3326f11/static.py#L332-L338 | train |
rmohr/static3 | static.py | BaseMagic.old_path | def old_path(self, full_path):
"""Remove self.extension from path or raise MagicError."""
if self.matches(full_path):
return full_path[:-len(self.extension)]
else:
raise MagicError("Path does not match this magic.") | python | def old_path(self, full_path):
"""Remove self.extension from path or raise MagicError."""
if self.matches(full_path):
return full_path[:-len(self.extension)]
else:
raise MagicError("Path does not match this magic.") | [
"def",
"old_path",
"(",
"self",
",",
"full_path",
")",
":",
"if",
"self",
".",
"matches",
"(",
"full_path",
")",
":",
"return",
"full_path",
"[",
":",
"-",
"len",
"(",
"self",
".",
"extension",
")",
"]",
"else",
":",
"raise",
"MagicError",
"(",
"\"Path does not match this magic.\"",
")"
] | Remove self.extension from path or raise MagicError. | [
"Remove",
"self",
".",
"extension",
"from",
"path",
"or",
"raise",
"MagicError",
"."
] | e5f88c5e91789bd4db7fde0cf59e4a15c3326f11 | https://github.com/rmohr/static3/blob/e5f88c5e91789bd4db7fde0cf59e4a15c3326f11/static.py#L374-L379 | train |
rmohr/static3 | static.py | StringMagic.body | def body(self, environ, file_like):
"""Pass environ and self.variables in to template.
self.variables overrides environ so that suprises in environ don't
cause unexpected output if you are passing a value in explicitly.
"""
variables = environ.copy()
variables.update(self.variables)
template = string.Template(file_like.read())
if self.safe is True:
return [template.safe_substitute(variables)]
else:
return [template.substitute(variables)] | python | def body(self, environ, file_like):
"""Pass environ and self.variables in to template.
self.variables overrides environ so that suprises in environ don't
cause unexpected output if you are passing a value in explicitly.
"""
variables = environ.copy()
variables.update(self.variables)
template = string.Template(file_like.read())
if self.safe is True:
return [template.safe_substitute(variables)]
else:
return [template.substitute(variables)] | [
"def",
"body",
"(",
"self",
",",
"environ",
",",
"file_like",
")",
":",
"variables",
"=",
"environ",
".",
"copy",
"(",
")",
"variables",
".",
"update",
"(",
"self",
".",
"variables",
")",
"template",
"=",
"string",
".",
"Template",
"(",
"file_like",
".",
"read",
"(",
")",
")",
"if",
"self",
".",
"safe",
"is",
"True",
":",
"return",
"[",
"template",
".",
"safe_substitute",
"(",
"variables",
")",
"]",
"else",
":",
"return",
"[",
"template",
".",
"substitute",
"(",
"variables",
")",
"]"
] | Pass environ and self.variables in to template.
self.variables overrides environ so that suprises in environ don't
cause unexpected output if you are passing a value in explicitly. | [
"Pass",
"environ",
"and",
"self",
".",
"variables",
"in",
"to",
"template",
"."
] | e5f88c5e91789bd4db7fde0cf59e4a15c3326f11 | https://github.com/rmohr/static3/blob/e5f88c5e91789bd4db7fde0cf59e4a15c3326f11/static.py#L414-L426 | train |
budacom/trading-bots | trading_bots/contrib/converters/base.py | Converter.get_rate_for | def get_rate_for(self, currency: str, to: str, reverse: bool=False) -> Number:
"""Get current market rate for currency"""
# Return 1 when currencies match
if currency.upper() == to.upper():
return self._format_number('1.0')
# Set base and quote currencies
base, quote = currency, to
if reverse:
base, quote = to, currency
try: # Get rate from source
rate = self._get_rate(base, quote)
except Exception as e:
raise ConverterRateError(self.name) from e
# Convert rate to number
rate = self._format_number(rate)
try: # Validate rate value
assert isinstance(rate, (float, Decimal))
assert rate > 0
except AssertionError as e:
raise ConverterValidationError(self.name, rate) from e
# Return market rate
if reverse:
return self._format_number('1.0') / rate
return rate | python | def get_rate_for(self, currency: str, to: str, reverse: bool=False) -> Number:
"""Get current market rate for currency"""
# Return 1 when currencies match
if currency.upper() == to.upper():
return self._format_number('1.0')
# Set base and quote currencies
base, quote = currency, to
if reverse:
base, quote = to, currency
try: # Get rate from source
rate = self._get_rate(base, quote)
except Exception as e:
raise ConverterRateError(self.name) from e
# Convert rate to number
rate = self._format_number(rate)
try: # Validate rate value
assert isinstance(rate, (float, Decimal))
assert rate > 0
except AssertionError as e:
raise ConverterValidationError(self.name, rate) from e
# Return market rate
if reverse:
return self._format_number('1.0') / rate
return rate | [
"def",
"get_rate_for",
"(",
"self",
",",
"currency",
":",
"str",
",",
"to",
":",
"str",
",",
"reverse",
":",
"bool",
"=",
"False",
")",
"->",
"Number",
":",
"if",
"currency",
".",
"upper",
"(",
")",
"==",
"to",
".",
"upper",
"(",
")",
":",
"return",
"self",
".",
"_format_number",
"(",
"'1.0'",
")",
"base",
",",
"quote",
"=",
"currency",
",",
"to",
"if",
"reverse",
":",
"base",
",",
"quote",
"=",
"to",
",",
"currency",
"try",
":",
"rate",
"=",
"self",
".",
"_get_rate",
"(",
"base",
",",
"quote",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"ConverterRateError",
"(",
"self",
".",
"name",
")",
"from",
"e",
"rate",
"=",
"self",
".",
"_format_number",
"(",
"rate",
")",
"try",
":",
"assert",
"isinstance",
"(",
"rate",
",",
"(",
"float",
",",
"Decimal",
")",
")",
"assert",
"rate",
">",
"0",
"except",
"AssertionError",
"as",
"e",
":",
"raise",
"ConverterValidationError",
"(",
"self",
".",
"name",
",",
"rate",
")",
"from",
"e",
"if",
"reverse",
":",
"return",
"self",
".",
"_format_number",
"(",
"'1.0'",
")",
"/",
"rate",
"return",
"rate"
] | Get current market rate for currency | [
"Get",
"current",
"market",
"rate",
"for",
"currency"
] | 8cb68bb8d0b5f822108db1cc5dae336e3d3c3452 | https://github.com/budacom/trading-bots/blob/8cb68bb8d0b5f822108db1cc5dae336e3d3c3452/trading_bots/contrib/converters/base.py#L45-L74 | train |
budacom/trading-bots | trading_bots/contrib/converters/base.py | Converter.convert | def convert(self, amount: Number, currency: str, to: str, reverse: bool=False) -> Number:
"""Convert amount to another currency"""
rate = self.get_rate_for(currency, to, reverse)
if self.return_decimal:
amount = Decimal(amount)
return amount * rate | python | def convert(self, amount: Number, currency: str, to: str, reverse: bool=False) -> Number:
"""Convert amount to another currency"""
rate = self.get_rate_for(currency, to, reverse)
if self.return_decimal:
amount = Decimal(amount)
return amount * rate | [
"def",
"convert",
"(",
"self",
",",
"amount",
":",
"Number",
",",
"currency",
":",
"str",
",",
"to",
":",
"str",
",",
"reverse",
":",
"bool",
"=",
"False",
")",
"->",
"Number",
":",
"rate",
"=",
"self",
".",
"get_rate_for",
"(",
"currency",
",",
"to",
",",
"reverse",
")",
"if",
"self",
".",
"return_decimal",
":",
"amount",
"=",
"Decimal",
"(",
"amount",
")",
"return",
"amount",
"*",
"rate"
] | Convert amount to another currency | [
"Convert",
"amount",
"to",
"another",
"currency"
] | 8cb68bb8d0b5f822108db1cc5dae336e3d3c3452 | https://github.com/budacom/trading-bots/blob/8cb68bb8d0b5f822108db1cc5dae336e3d3c3452/trading_bots/contrib/converters/base.py#L76-L81 | train |
budacom/trading-bots | trading_bots/contrib/converters/base.py | Converter.convert_money | def convert_money(self, money: Money, to: str, reverse: bool=False) -> Money:
"""Convert money to another currency"""
converted = self.convert(money.amount, money.currency, to, reverse)
return Money(converted, to) | python | def convert_money(self, money: Money, to: str, reverse: bool=False) -> Money:
"""Convert money to another currency"""
converted = self.convert(money.amount, money.currency, to, reverse)
return Money(converted, to) | [
"def",
"convert_money",
"(",
"self",
",",
"money",
":",
"Money",
",",
"to",
":",
"str",
",",
"reverse",
":",
"bool",
"=",
"False",
")",
"->",
"Money",
":",
"converted",
"=",
"self",
".",
"convert",
"(",
"money",
".",
"amount",
",",
"money",
".",
"currency",
",",
"to",
",",
"reverse",
")",
"return",
"Money",
"(",
"converted",
",",
"to",
")"
] | Convert money to another currency | [
"Convert",
"money",
"to",
"another",
"currency"
] | 8cb68bb8d0b5f822108db1cc5dae336e3d3c3452 | https://github.com/budacom/trading-bots/blob/8cb68bb8d0b5f822108db1cc5dae336e3d3c3452/trading_bots/contrib/converters/base.py#L83-L86 | train |
jinglemansweep/lcdproc | lcdproc/screen.py | Screen.add_icon_widget | def add_icon_widget(self, ref, x=1, y=1, name="heart"):
""" Add Icon Widget """
if ref not in self.widgets:
widget = IconWidget(screen=self, ref=ref, x=x, y=y, name=name)
self.widgets[ref] = widget
return self.widgets[ref] | python | def add_icon_widget(self, ref, x=1, y=1, name="heart"):
""" Add Icon Widget """
if ref not in self.widgets:
widget = IconWidget(screen=self, ref=ref, x=x, y=y, name=name)
self.widgets[ref] = widget
return self.widgets[ref] | [
"def",
"add_icon_widget",
"(",
"self",
",",
"ref",
",",
"x",
"=",
"1",
",",
"y",
"=",
"1",
",",
"name",
"=",
"\"heart\"",
")",
":",
"if",
"ref",
"not",
"in",
"self",
".",
"widgets",
":",
"widget",
"=",
"IconWidget",
"(",
"screen",
"=",
"self",
",",
"ref",
"=",
"ref",
",",
"x",
"=",
"x",
",",
"y",
"=",
"y",
",",
"name",
"=",
"name",
")",
"self",
".",
"widgets",
"[",
"ref",
"]",
"=",
"widget",
"return",
"self",
".",
"widgets",
"[",
"ref",
"]"
] | Add Icon Widget | [
"Add",
"Icon",
"Widget"
] | 973628fc326177c9deaf3f2e1a435159eb565ae0 | https://github.com/jinglemansweep/lcdproc/blob/973628fc326177c9deaf3f2e1a435159eb565ae0/lcdproc/screen.py#L179-L186 | train |
jinglemansweep/lcdproc | lcdproc/screen.py | Screen.add_scroller_widget | def add_scroller_widget(self, ref, left=1, top=1, right=20, bottom=1, direction="h", speed=1, text="Message"):
""" Add Scroller Widget """
if ref not in self.widgets:
widget = ScrollerWidget(screen=self, ref=ref, left=left, top=top, right=right, bottom=bottom, direction=direction, speed=speed, text=text)
self.widgets[ref] = widget
return self.widgets[ref] | python | def add_scroller_widget(self, ref, left=1, top=1, right=20, bottom=1, direction="h", speed=1, text="Message"):
""" Add Scroller Widget """
if ref not in self.widgets:
widget = ScrollerWidget(screen=self, ref=ref, left=left, top=top, right=right, bottom=bottom, direction=direction, speed=speed, text=text)
self.widgets[ref] = widget
return self.widgets[ref] | [
"def",
"add_scroller_widget",
"(",
"self",
",",
"ref",
",",
"left",
"=",
"1",
",",
"top",
"=",
"1",
",",
"right",
"=",
"20",
",",
"bottom",
"=",
"1",
",",
"direction",
"=",
"\"h\"",
",",
"speed",
"=",
"1",
",",
"text",
"=",
"\"Message\"",
")",
":",
"if",
"ref",
"not",
"in",
"self",
".",
"widgets",
":",
"widget",
"=",
"ScrollerWidget",
"(",
"screen",
"=",
"self",
",",
"ref",
"=",
"ref",
",",
"left",
"=",
"left",
",",
"top",
"=",
"top",
",",
"right",
"=",
"right",
",",
"bottom",
"=",
"bottom",
",",
"direction",
"=",
"direction",
",",
"speed",
"=",
"speed",
",",
"text",
"=",
"text",
")",
"self",
".",
"widgets",
"[",
"ref",
"]",
"=",
"widget",
"return",
"self",
".",
"widgets",
"[",
"ref",
"]"
] | Add Scroller Widget | [
"Add",
"Scroller",
"Widget"
] | 973628fc326177c9deaf3f2e1a435159eb565ae0 | https://github.com/jinglemansweep/lcdproc/blob/973628fc326177c9deaf3f2e1a435159eb565ae0/lcdproc/screen.py#L189-L196 | train |
idlesign/steampak | steampak/libsteam/resources/apps.py | Application.install_dir | def install_dir(self):
"""Returns application installation path.
.. note::
If fails this falls back to a restricted interface, which can only be used by approved apps.
:rtype: str
"""
max_len = 500
directory = self._get_str(self._iface.get_install_dir, [self.app_id], max_len=max_len)
if not directory:
# Fallback to restricted interface (can only be used by approved apps).
directory = self._get_str(self._iface_list.get_install_dir, [self.app_id], max_len=max_len)
return directory | python | def install_dir(self):
"""Returns application installation path.
.. note::
If fails this falls back to a restricted interface, which can only be used by approved apps.
:rtype: str
"""
max_len = 500
directory = self._get_str(self._iface.get_install_dir, [self.app_id], max_len=max_len)
if not directory:
# Fallback to restricted interface (can only be used by approved apps).
directory = self._get_str(self._iface_list.get_install_dir, [self.app_id], max_len=max_len)
return directory | [
"def",
"install_dir",
"(",
"self",
")",
":",
"max_len",
"=",
"500",
"directory",
"=",
"self",
".",
"_get_str",
"(",
"self",
".",
"_iface",
".",
"get_install_dir",
",",
"[",
"self",
".",
"app_id",
"]",
",",
"max_len",
"=",
"max_len",
")",
"if",
"not",
"directory",
":",
"directory",
"=",
"self",
".",
"_get_str",
"(",
"self",
".",
"_iface_list",
".",
"get_install_dir",
",",
"[",
"self",
".",
"app_id",
"]",
",",
"max_len",
"=",
"max_len",
")",
"return",
"directory"
] | Returns application installation path.
.. note::
If fails this falls back to a restricted interface, which can only be used by approved apps.
:rtype: str | [
"Returns",
"application",
"installation",
"path",
"."
] | cb3f2c737e272b0360802d947e388df7e34f50f3 | https://github.com/idlesign/steampak/blob/cb3f2c737e272b0360802d947e388df7e34f50f3/steampak/libsteam/resources/apps.py#L73-L90 | train |
idlesign/steampak | steampak/libsteam/resources/apps.py | Application.purchase_time | def purchase_time(self):
"""Date and time of app purchase.
:rtype: datetime
"""
ts = self._iface.get_purchase_time(self.app_id)
return datetime.utcfromtimestamp(ts) | python | def purchase_time(self):
"""Date and time of app purchase.
:rtype: datetime
"""
ts = self._iface.get_purchase_time(self.app_id)
return datetime.utcfromtimestamp(ts) | [
"def",
"purchase_time",
"(",
"self",
")",
":",
"ts",
"=",
"self",
".",
"_iface",
".",
"get_purchase_time",
"(",
"self",
".",
"app_id",
")",
"return",
"datetime",
".",
"utcfromtimestamp",
"(",
"ts",
")"
] | Date and time of app purchase.
:rtype: datetime | [
"Date",
"and",
"time",
"of",
"app",
"purchase",
"."
] | cb3f2c737e272b0360802d947e388df7e34f50f3 | https://github.com/idlesign/steampak/blob/cb3f2c737e272b0360802d947e388df7e34f50f3/steampak/libsteam/resources/apps.py#L93-L99 | train |
BD2KGenomics/protect | docker/pipelineWrapper.py | PipelineWrapperBuilder.get_args | def get_args(self):
"""
Use this context manager to add arguments to an argparse object with the add_argument
method. Arguments must be defined before the command is defined. Note that
no-clean and resume are added upon exit and should not be added in the context manager. For
more info about these default arguments see below.
"""
parser = argparse.ArgumentParser(description=self._desc,
formatter_class=MyUniversalHelpFormatter)
# default args
if self._no_clean:
parser.add_argument('--no-clean', action='store_true',
help='If this flag is used, temporary work directory is not '
'cleaned.')
if self._resume:
parser.add_argument('--resume', action='store_true',
help='If this flag is used, a previously uncleaned workflow in the'
' same directory will be resumed')
return parser | python | def get_args(self):
"""
Use this context manager to add arguments to an argparse object with the add_argument
method. Arguments must be defined before the command is defined. Note that
no-clean and resume are added upon exit and should not be added in the context manager. For
more info about these default arguments see below.
"""
parser = argparse.ArgumentParser(description=self._desc,
formatter_class=MyUniversalHelpFormatter)
# default args
if self._no_clean:
parser.add_argument('--no-clean', action='store_true',
help='If this flag is used, temporary work directory is not '
'cleaned.')
if self._resume:
parser.add_argument('--resume', action='store_true',
help='If this flag is used, a previously uncleaned workflow in the'
' same directory will be resumed')
return parser | [
"def",
"get_args",
"(",
"self",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"self",
".",
"_desc",
",",
"formatter_class",
"=",
"MyUniversalHelpFormatter",
")",
"if",
"self",
".",
"_no_clean",
":",
"parser",
".",
"add_argument",
"(",
"'--no-clean'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'If this flag is used, temporary work directory is not '",
"'cleaned.'",
")",
"if",
"self",
".",
"_resume",
":",
"parser",
".",
"add_argument",
"(",
"'--resume'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'If this flag is used, a previously uncleaned workflow in the'",
"' same directory will be resumed'",
")",
"return",
"parser"
] | Use this context manager to add arguments to an argparse object with the add_argument
method. Arguments must be defined before the command is defined. Note that
no-clean and resume are added upon exit and should not be added in the context manager. For
more info about these default arguments see below. | [
"Use",
"this",
"context",
"manager",
"to",
"add",
"arguments",
"to",
"an",
"argparse",
"object",
"with",
"the",
"add_argument",
"method",
".",
"Arguments",
"must",
"be",
"defined",
"before",
"the",
"command",
"is",
"defined",
".",
"Note",
"that",
"no",
"-",
"clean",
"and",
"resume",
"are",
"added",
"upon",
"exit",
"and",
"should",
"not",
"be",
"added",
"in",
"the",
"context",
"manager",
".",
"For",
"more",
"info",
"about",
"these",
"default",
"arguments",
"see",
"below",
"."
] | 06310682c50dcf8917b912c8e551299ff7ee41ce | https://github.com/BD2KGenomics/protect/blob/06310682c50dcf8917b912c8e551299ff7ee41ce/docker/pipelineWrapper.py#L170-L188 | train |
BD2KGenomics/protect | src/protect/rankboost.py | wrap_rankboost | def wrap_rankboost(job, rsem_files, merged_mhc_calls, transgene_out, univ_options,
rankboost_options):
"""
A wrapper for boost_ranks.
:param dict rsem_files: Dict of results from rsem
:param dict merged_mhc_calls: Dict of results from merging mhc peptide binding predictions
:param dict transgene_out: Dict of results from running Transgene
:param dict univ_options: Dict of universal options used by almost all tools
:param dict rankboost_options: Options specific to rankboost
:return: Dict of concise and detailed results for mhci and mhcii
output_files:
|- 'mhcii_rankboost_concise_results.tsv': fsID
|- 'mhcii_rankboost_detailed_results.txt': fsID
|- 'mhci_rankboost_concise_results.tsv': fsID
+- 'mhci_rankboost_detailed_results.txt': fsID
:rtype: dict
"""
rankboost = job.addChildJobFn(boost_ranks, rsem_files['rsem.isoforms.results'],
merged_mhc_calls, transgene_out, univ_options, rankboost_options)
return rankboost.rv() | python | def wrap_rankboost(job, rsem_files, merged_mhc_calls, transgene_out, univ_options,
rankboost_options):
"""
A wrapper for boost_ranks.
:param dict rsem_files: Dict of results from rsem
:param dict merged_mhc_calls: Dict of results from merging mhc peptide binding predictions
:param dict transgene_out: Dict of results from running Transgene
:param dict univ_options: Dict of universal options used by almost all tools
:param dict rankboost_options: Options specific to rankboost
:return: Dict of concise and detailed results for mhci and mhcii
output_files:
|- 'mhcii_rankboost_concise_results.tsv': fsID
|- 'mhcii_rankboost_detailed_results.txt': fsID
|- 'mhci_rankboost_concise_results.tsv': fsID
+- 'mhci_rankboost_detailed_results.txt': fsID
:rtype: dict
"""
rankboost = job.addChildJobFn(boost_ranks, rsem_files['rsem.isoforms.results'],
merged_mhc_calls, transgene_out, univ_options, rankboost_options)
return rankboost.rv() | [
"def",
"wrap_rankboost",
"(",
"job",
",",
"rsem_files",
",",
"merged_mhc_calls",
",",
"transgene_out",
",",
"univ_options",
",",
"rankboost_options",
")",
":",
"rankboost",
"=",
"job",
".",
"addChildJobFn",
"(",
"boost_ranks",
",",
"rsem_files",
"[",
"'rsem.isoforms.results'",
"]",
",",
"merged_mhc_calls",
",",
"transgene_out",
",",
"univ_options",
",",
"rankboost_options",
")",
"return",
"rankboost",
".",
"rv",
"(",
")"
] | A wrapper for boost_ranks.
:param dict rsem_files: Dict of results from rsem
:param dict merged_mhc_calls: Dict of results from merging mhc peptide binding predictions
:param dict transgene_out: Dict of results from running Transgene
:param dict univ_options: Dict of universal options used by almost all tools
:param dict rankboost_options: Options specific to rankboost
:return: Dict of concise and detailed results for mhci and mhcii
output_files:
|- 'mhcii_rankboost_concise_results.tsv': fsID
|- 'mhcii_rankboost_detailed_results.txt': fsID
|- 'mhci_rankboost_concise_results.tsv': fsID
+- 'mhci_rankboost_detailed_results.txt': fsID
:rtype: dict | [
"A",
"wrapper",
"for",
"boost_ranks",
"."
] | 06310682c50dcf8917b912c8e551299ff7ee41ce | https://github.com/BD2KGenomics/protect/blob/06310682c50dcf8917b912c8e551299ff7ee41ce/src/protect/rankboost.py#L21-L42 | train |
budacom/trading-bots | trading_bots/bots/registry.py | BotRegistry._path_from_module | def _path_from_module(module):
"""Attempt to determine bot's filesystem path from its module."""
# Convert paths to list because Python's _NamespacePath doesn't support
# indexing.
paths = list(getattr(module, '__path__', []))
if len(paths) != 1:
filename = getattr(module, '__file__', None)
if filename is not None:
paths = [os.path.dirname(filename)]
else:
# For unknown reasons, sometimes the list returned by __path__
# contains duplicates that must be removed.
paths = list(set(paths))
if len(paths) > 1:
raise ImproperlyConfigured(
"The bot module %r has multiple filesystem locations (%r); "
"you must configure this bot with an AppConfig subclass "
"with a 'path' class attribute." % (module, paths))
elif not paths:
raise ImproperlyConfigured(
"The bot module %r has no filesystem location, "
"you must configure this bot with an AppConfig subclass "
"with a 'path' class attribute." % (module,))
return paths[0] | python | def _path_from_module(module):
"""Attempt to determine bot's filesystem path from its module."""
# Convert paths to list because Python's _NamespacePath doesn't support
# indexing.
paths = list(getattr(module, '__path__', []))
if len(paths) != 1:
filename = getattr(module, '__file__', None)
if filename is not None:
paths = [os.path.dirname(filename)]
else:
# For unknown reasons, sometimes the list returned by __path__
# contains duplicates that must be removed.
paths = list(set(paths))
if len(paths) > 1:
raise ImproperlyConfigured(
"The bot module %r has multiple filesystem locations (%r); "
"you must configure this bot with an AppConfig subclass "
"with a 'path' class attribute." % (module, paths))
elif not paths:
raise ImproperlyConfigured(
"The bot module %r has no filesystem location, "
"you must configure this bot with an AppConfig subclass "
"with a 'path' class attribute." % (module,))
return paths[0] | [
"def",
"_path_from_module",
"(",
"module",
")",
":",
"paths",
"=",
"list",
"(",
"getattr",
"(",
"module",
",",
"'__path__'",
",",
"[",
"]",
")",
")",
"if",
"len",
"(",
"paths",
")",
"!=",
"1",
":",
"filename",
"=",
"getattr",
"(",
"module",
",",
"'__file__'",
",",
"None",
")",
"if",
"filename",
"is",
"not",
"None",
":",
"paths",
"=",
"[",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
")",
"]",
"else",
":",
"paths",
"=",
"list",
"(",
"set",
"(",
"paths",
")",
")",
"if",
"len",
"(",
"paths",
")",
">",
"1",
":",
"raise",
"ImproperlyConfigured",
"(",
"\"The bot module %r has multiple filesystem locations (%r); \"",
"\"you must configure this bot with an AppConfig subclass \"",
"\"with a 'path' class attribute.\"",
"%",
"(",
"module",
",",
"paths",
")",
")",
"elif",
"not",
"paths",
":",
"raise",
"ImproperlyConfigured",
"(",
"\"The bot module %r has no filesystem location, \"",
"\"you must configure this bot with an AppConfig subclass \"",
"\"with a 'path' class attribute.\"",
"%",
"(",
"module",
",",
")",
")",
"return",
"paths",
"[",
"0",
"]"
] | Attempt to determine bot's filesystem path from its module. | [
"Attempt",
"to",
"determine",
"bot",
"s",
"filesystem",
"path",
"from",
"its",
"module",
"."
] | 8cb68bb8d0b5f822108db1cc5dae336e3d3c3452 | https://github.com/budacom/trading-bots/blob/8cb68bb8d0b5f822108db1cc5dae336e3d3c3452/trading_bots/bots/registry.py#L58-L81 | train |
budacom/trading-bots | trading_bots/bots/registry.py | BotRegistry.create | def create(cls, entry):
"""
Factory that creates an bot config from an entry in INSTALLED_APPS.
"""
# trading_bots.example.bot.ExampleBot
try:
# If import_module succeeds, entry is a path to a bot module,
# which may specify a bot class with a default_bot attribute.
# Otherwise, entry is a path to a bot class or an error.
module = import_module(entry)
except ImportError:
# Track that importing as a bot module failed. If importing as a
# bot class fails too, we'll trigger the ImportError again.
module = None
mod_path, _, cls_name = entry.rpartition('.')
# Raise the original exception when entry cannot be a path to an
# bot config class.
if not mod_path:
raise
else:
try:
# If this works, the bot module specifies a bot class.
entry = module.default_bot
except AttributeError:
# Otherwise, it simply uses the default bot registry class.
return cls(f'{entry}.Bot', module)
else:
mod_path, _, cls_name = entry.rpartition('.')
# If we're reaching this point, we must attempt to load the bot
# class located at <mod_path>.<cls_name>
mod = import_module(mod_path)
try:
bot_cls = getattr(mod, cls_name)
except AttributeError:
if module is None:
# If importing as an bot module failed, that error probably
# contains the most informative traceback. Trigger it again.
import_module(entry)
raise
# Check for obvious errors. (This check prevents duck typing, but
# it could be removed if it became a problem in practice.)
if not issubclass(bot_cls, Bot):
raise ImproperlyConfigured(
"'%s' isn't a subclass of Bot." % entry)
# Entry is a path to an bot config class.
return cls(entry, mod, bot_cls.label) | python | def create(cls, entry):
"""
Factory that creates an bot config from an entry in INSTALLED_APPS.
"""
# trading_bots.example.bot.ExampleBot
try:
# If import_module succeeds, entry is a path to a bot module,
# which may specify a bot class with a default_bot attribute.
# Otherwise, entry is a path to a bot class or an error.
module = import_module(entry)
except ImportError:
# Track that importing as a bot module failed. If importing as a
# bot class fails too, we'll trigger the ImportError again.
module = None
mod_path, _, cls_name = entry.rpartition('.')
# Raise the original exception when entry cannot be a path to an
# bot config class.
if not mod_path:
raise
else:
try:
# If this works, the bot module specifies a bot class.
entry = module.default_bot
except AttributeError:
# Otherwise, it simply uses the default bot registry class.
return cls(f'{entry}.Bot', module)
else:
mod_path, _, cls_name = entry.rpartition('.')
# If we're reaching this point, we must attempt to load the bot
# class located at <mod_path>.<cls_name>
mod = import_module(mod_path)
try:
bot_cls = getattr(mod, cls_name)
except AttributeError:
if module is None:
# If importing as an bot module failed, that error probably
# contains the most informative traceback. Trigger it again.
import_module(entry)
raise
# Check for obvious errors. (This check prevents duck typing, but
# it could be removed if it became a problem in practice.)
if not issubclass(bot_cls, Bot):
raise ImproperlyConfigured(
"'%s' isn't a subclass of Bot." % entry)
# Entry is a path to an bot config class.
return cls(entry, mod, bot_cls.label) | [
"def",
"create",
"(",
"cls",
",",
"entry",
")",
":",
"try",
":",
"module",
"=",
"import_module",
"(",
"entry",
")",
"except",
"ImportError",
":",
"module",
"=",
"None",
"mod_path",
",",
"_",
",",
"cls_name",
"=",
"entry",
".",
"rpartition",
"(",
"'.'",
")",
"if",
"not",
"mod_path",
":",
"raise",
"else",
":",
"try",
":",
"entry",
"=",
"module",
".",
"default_bot",
"except",
"AttributeError",
":",
"return",
"cls",
"(",
"f'{entry}.Bot'",
",",
"module",
")",
"else",
":",
"mod_path",
",",
"_",
",",
"cls_name",
"=",
"entry",
".",
"rpartition",
"(",
"'.'",
")",
"mod",
"=",
"import_module",
"(",
"mod_path",
")",
"try",
":",
"bot_cls",
"=",
"getattr",
"(",
"mod",
",",
"cls_name",
")",
"except",
"AttributeError",
":",
"if",
"module",
"is",
"None",
":",
"import_module",
"(",
"entry",
")",
"raise",
"if",
"not",
"issubclass",
"(",
"bot_cls",
",",
"Bot",
")",
":",
"raise",
"ImproperlyConfigured",
"(",
"\"'%s' isn't a subclass of Bot.\"",
"%",
"entry",
")",
"return",
"cls",
"(",
"entry",
",",
"mod",
",",
"bot_cls",
".",
"label",
")"
] | Factory that creates an bot config from an entry in INSTALLED_APPS. | [
"Factory",
"that",
"creates",
"an",
"bot",
"config",
"from",
"an",
"entry",
"in",
"INSTALLED_APPS",
"."
] | 8cb68bb8d0b5f822108db1cc5dae336e3d3c3452 | https://github.com/budacom/trading-bots/blob/8cb68bb8d0b5f822108db1cc5dae336e3d3c3452/trading_bots/bots/registry.py#L84-L136 | train |
budacom/trading-bots | trading_bots/bots/registry.py | BotRegistry.get_config | def get_config(self, config_name, require_ready=True):
"""
Return the config with the given case-insensitive config_name.
Raise LookupError if no config exists with this name.
"""
if require_ready:
self.bots.check_configs_ready()
else:
self.bots.check_bots_ready()
return self.configs.get(config_name.lower(), {}) | python | def get_config(self, config_name, require_ready=True):
"""
Return the config with the given case-insensitive config_name.
Raise LookupError if no config exists with this name.
"""
if require_ready:
self.bots.check_configs_ready()
else:
self.bots.check_bots_ready()
return self.configs.get(config_name.lower(), {}) | [
"def",
"get_config",
"(",
"self",
",",
"config_name",
",",
"require_ready",
"=",
"True",
")",
":",
"if",
"require_ready",
":",
"self",
".",
"bots",
".",
"check_configs_ready",
"(",
")",
"else",
":",
"self",
".",
"bots",
".",
"check_bots_ready",
"(",
")",
"return",
"self",
".",
"configs",
".",
"get",
"(",
"config_name",
".",
"lower",
"(",
")",
",",
"{",
"}",
")"
] | Return the config with the given case-insensitive config_name.
Raise LookupError if no config exists with this name. | [
"Return",
"the",
"config",
"with",
"the",
"given",
"case",
"-",
"insensitive",
"config_name",
".",
"Raise",
"LookupError",
"if",
"no",
"config",
"exists",
"with",
"this",
"name",
"."
] | 8cb68bb8d0b5f822108db1cc5dae336e3d3c3452 | https://github.com/budacom/trading-bots/blob/8cb68bb8d0b5f822108db1cc5dae336e3d3c3452/trading_bots/bots/registry.py#L138-L148 | train |
budacom/trading-bots | trading_bots/bots/registry.py | BotRegistry.get_configs | def get_configs(self):
"""
Return an iterable of models.
"""
self.bots.check_models_ready()
for config in self.configs.values():
yield config | python | def get_configs(self):
"""
Return an iterable of models.
"""
self.bots.check_models_ready()
for config in self.configs.values():
yield config | [
"def",
"get_configs",
"(",
"self",
")",
":",
"self",
".",
"bots",
".",
"check_models_ready",
"(",
")",
"for",
"config",
"in",
"self",
".",
"configs",
".",
"values",
"(",
")",
":",
"yield",
"config"
] | Return an iterable of models. | [
"Return",
"an",
"iterable",
"of",
"models",
"."
] | 8cb68bb8d0b5f822108db1cc5dae336e3d3c3452 | https://github.com/budacom/trading-bots/blob/8cb68bb8d0b5f822108db1cc5dae336e3d3c3452/trading_bots/bots/registry.py#L150-L156 | train |
budacom/trading-bots | trading_bots/bots/registry.py | Bots.populate | def populate(self, installed_bots=None):
"""
Load bots.
Import each bot module.
It is thread-safe and idempotent, but not re-entrant.
"""
if self.ready:
return
# populate() might be called by two threads in parallel on servers
# that create threads before initializing the WSGI callable.
with self._lock:
if self.ready:
return
# An RLock prevents other threads from entering this section. The
# compare and set operation below is atomic.
if self.loading:
# Prevent re-entrant calls to avoid running AppConfig.ready()
# methods twice.
raise RuntimeError("populate() isn't re-entrant")
self.loading = True
# Phase 1: Initialize bots
for entry in installed_bots or {}:
if isinstance(entry, Bot):
cls = entry
entry = '.'.join([cls.__module__, cls.__name__])
bot_reg = BotRegistry.create(entry)
if bot_reg.label in self.bots:
raise ImproperlyConfigured(
"Bot labels aren't unique, "
"duplicates: %s" % bot_reg.label)
self.bots[bot_reg.label] = bot_reg
bot_reg.bots = self
# Check for duplicate bot names.
counts = Counter(
bot_reg.name for bot_reg in self.bots.values())
duplicates = [
name for name, count in counts.most_common() if count > 1]
if duplicates:
raise ImproperlyConfigured(
"Bot names aren't unique, "
"duplicates: %s" % ", ".join(duplicates))
self.bots_ready = True
# Phase 2: import config files
for bot in self.bots.values():
bot.import_configs()
self.configs_ready = True
self.ready = True | python | def populate(self, installed_bots=None):
"""
Load bots.
Import each bot module.
It is thread-safe and idempotent, but not re-entrant.
"""
if self.ready:
return
# populate() might be called by two threads in parallel on servers
# that create threads before initializing the WSGI callable.
with self._lock:
if self.ready:
return
# An RLock prevents other threads from entering this section. The
# compare and set operation below is atomic.
if self.loading:
# Prevent re-entrant calls to avoid running AppConfig.ready()
# methods twice.
raise RuntimeError("populate() isn't re-entrant")
self.loading = True
# Phase 1: Initialize bots
for entry in installed_bots or {}:
if isinstance(entry, Bot):
cls = entry
entry = '.'.join([cls.__module__, cls.__name__])
bot_reg = BotRegistry.create(entry)
if bot_reg.label in self.bots:
raise ImproperlyConfigured(
"Bot labels aren't unique, "
"duplicates: %s" % bot_reg.label)
self.bots[bot_reg.label] = bot_reg
bot_reg.bots = self
# Check for duplicate bot names.
counts = Counter(
bot_reg.name for bot_reg in self.bots.values())
duplicates = [
name for name, count in counts.most_common() if count > 1]
if duplicates:
raise ImproperlyConfigured(
"Bot names aren't unique, "
"duplicates: %s" % ", ".join(duplicates))
self.bots_ready = True
# Phase 2: import config files
for bot in self.bots.values():
bot.import_configs()
self.configs_ready = True
self.ready = True | [
"def",
"populate",
"(",
"self",
",",
"installed_bots",
"=",
"None",
")",
":",
"if",
"self",
".",
"ready",
":",
"return",
"with",
"self",
".",
"_lock",
":",
"if",
"self",
".",
"ready",
":",
"return",
"if",
"self",
".",
"loading",
":",
"raise",
"RuntimeError",
"(",
"\"populate() isn't re-entrant\"",
")",
"self",
".",
"loading",
"=",
"True",
"for",
"entry",
"in",
"installed_bots",
"or",
"{",
"}",
":",
"if",
"isinstance",
"(",
"entry",
",",
"Bot",
")",
":",
"cls",
"=",
"entry",
"entry",
"=",
"'.'",
".",
"join",
"(",
"[",
"cls",
".",
"__module__",
",",
"cls",
".",
"__name__",
"]",
")",
"bot_reg",
"=",
"BotRegistry",
".",
"create",
"(",
"entry",
")",
"if",
"bot_reg",
".",
"label",
"in",
"self",
".",
"bots",
":",
"raise",
"ImproperlyConfigured",
"(",
"\"Bot labels aren't unique, \"",
"\"duplicates: %s\"",
"%",
"bot_reg",
".",
"label",
")",
"self",
".",
"bots",
"[",
"bot_reg",
".",
"label",
"]",
"=",
"bot_reg",
"bot_reg",
".",
"bots",
"=",
"self",
"counts",
"=",
"Counter",
"(",
"bot_reg",
".",
"name",
"for",
"bot_reg",
"in",
"self",
".",
"bots",
".",
"values",
"(",
")",
")",
"duplicates",
"=",
"[",
"name",
"for",
"name",
",",
"count",
"in",
"counts",
".",
"most_common",
"(",
")",
"if",
"count",
">",
"1",
"]",
"if",
"duplicates",
":",
"raise",
"ImproperlyConfigured",
"(",
"\"Bot names aren't unique, \"",
"\"duplicates: %s\"",
"%",
"\", \"",
".",
"join",
"(",
"duplicates",
")",
")",
"self",
".",
"bots_ready",
"=",
"True",
"for",
"bot",
"in",
"self",
".",
"bots",
".",
"values",
"(",
")",
":",
"bot",
".",
"import_configs",
"(",
")",
"self",
".",
"configs_ready",
"=",
"True",
"self",
".",
"ready",
"=",
"True"
] | Load bots.
Import each bot module.
It is thread-safe and idempotent, but not re-entrant. | [
"Load",
"bots",
".",
"Import",
"each",
"bot",
"module",
".",
"It",
"is",
"thread",
"-",
"safe",
"and",
"idempotent",
"but",
"not",
"re",
"-",
"entrant",
"."
] | 8cb68bb8d0b5f822108db1cc5dae336e3d3c3452 | https://github.com/budacom/trading-bots/blob/8cb68bb8d0b5f822108db1cc5dae336e3d3c3452/trading_bots/bots/registry.py#L199-L254 | train |
budacom/trading-bots | trading_bots/bots/registry.py | Bots.get_bot | def get_bot(self, bot_label):
"""
Import all bots and returns a bot class for the given label.
Raise LookupError if no bot exists with this label.
"""
self.check_bots_ready()
try:
return self.bots[bot_label]
except KeyError:
message = "No installed bot with label '%s'." % bot_label
for bot_cls in self.get_bots():
if bot_cls.name == bot_label:
message += " Did you mean '%s'?" % bot_cls.label
break
raise LookupError(message) | python | def get_bot(self, bot_label):
"""
Import all bots and returns a bot class for the given label.
Raise LookupError if no bot exists with this label.
"""
self.check_bots_ready()
try:
return self.bots[bot_label]
except KeyError:
message = "No installed bot with label '%s'." % bot_label
for bot_cls in self.get_bots():
if bot_cls.name == bot_label:
message += " Did you mean '%s'?" % bot_cls.label
break
raise LookupError(message) | [
"def",
"get_bot",
"(",
"self",
",",
"bot_label",
")",
":",
"self",
".",
"check_bots_ready",
"(",
")",
"try",
":",
"return",
"self",
".",
"bots",
"[",
"bot_label",
"]",
"except",
"KeyError",
":",
"message",
"=",
"\"No installed bot with label '%s'.\"",
"%",
"bot_label",
"for",
"bot_cls",
"in",
"self",
".",
"get_bots",
"(",
")",
":",
"if",
"bot_cls",
".",
"name",
"==",
"bot_label",
":",
"message",
"+=",
"\" Did you mean '%s'?\"",
"%",
"bot_cls",
".",
"label",
"break",
"raise",
"LookupError",
"(",
"message",
")"
] | Import all bots and returns a bot class for the given label.
Raise LookupError if no bot exists with this label. | [
"Import",
"all",
"bots",
"and",
"returns",
"a",
"bot",
"class",
"for",
"the",
"given",
"label",
".",
"Raise",
"LookupError",
"if",
"no",
"bot",
"exists",
"with",
"this",
"label",
"."
] | 8cb68bb8d0b5f822108db1cc5dae336e3d3c3452 | https://github.com/budacom/trading-bots/blob/8cb68bb8d0b5f822108db1cc5dae336e3d3c3452/trading_bots/bots/registry.py#L271-L285 | train |
budacom/trading-bots | trading_bots/bots/registry.py | Bots.get_configs | def get_configs(self):
"""
Return a list of all installed configs.
"""
self.check_configs_ready()
result = []
for bot in self.bots.values():
result.extend(list(bot.get_models()))
return result | python | def get_configs(self):
"""
Return a list of all installed configs.
"""
self.check_configs_ready()
result = []
for bot in self.bots.values():
result.extend(list(bot.get_models()))
return result | [
"def",
"get_configs",
"(",
"self",
")",
":",
"self",
".",
"check_configs_ready",
"(",
")",
"result",
"=",
"[",
"]",
"for",
"bot",
"in",
"self",
".",
"bots",
".",
"values",
"(",
")",
":",
"result",
".",
"extend",
"(",
"list",
"(",
"bot",
".",
"get_models",
"(",
")",
")",
")",
"return",
"result"
] | Return a list of all installed configs. | [
"Return",
"a",
"list",
"of",
"all",
"installed",
"configs",
"."
] | 8cb68bb8d0b5f822108db1cc5dae336e3d3c3452 | https://github.com/budacom/trading-bots/blob/8cb68bb8d0b5f822108db1cc5dae336e3d3c3452/trading_bots/bots/registry.py#L287-L296 | train |
budacom/trading-bots | trading_bots/bots/registry.py | Bots.get_config | def get_config(self, bot_label, config_name=None, require_ready=True):
"""
Return the config matching the given bot_label and config_name.
config_name is case-insensitive.
Raise LookupError if no bot exists with this label, or no config
exists with this name in the bot. Raise ValueError if called with a
single argument that doesn't contain exactly one dot.
"""
if require_ready:
self.check_configs_ready()
else:
self.check_bots_ready()
if config_name is None:
config_name = defaults.BOT_CONFIG
bot = self.get_bot(bot_label)
if not require_ready and bot.configs is None:
bot.import_configs()
return bot.get_config(config_name, require_ready=require_ready) | python | def get_config(self, bot_label, config_name=None, require_ready=True):
"""
Return the config matching the given bot_label and config_name.
config_name is case-insensitive.
Raise LookupError if no bot exists with this label, or no config
exists with this name in the bot. Raise ValueError if called with a
single argument that doesn't contain exactly one dot.
"""
if require_ready:
self.check_configs_ready()
else:
self.check_bots_ready()
if config_name is None:
config_name = defaults.BOT_CONFIG
bot = self.get_bot(bot_label)
if not require_ready and bot.configs is None:
bot.import_configs()
return bot.get_config(config_name, require_ready=require_ready) | [
"def",
"get_config",
"(",
"self",
",",
"bot_label",
",",
"config_name",
"=",
"None",
",",
"require_ready",
"=",
"True",
")",
":",
"if",
"require_ready",
":",
"self",
".",
"check_configs_ready",
"(",
")",
"else",
":",
"self",
".",
"check_bots_ready",
"(",
")",
"if",
"config_name",
"is",
"None",
":",
"config_name",
"=",
"defaults",
".",
"BOT_CONFIG",
"bot",
"=",
"self",
".",
"get_bot",
"(",
"bot_label",
")",
"if",
"not",
"require_ready",
"and",
"bot",
".",
"configs",
"is",
"None",
":",
"bot",
".",
"import_configs",
"(",
")",
"return",
"bot",
".",
"get_config",
"(",
"config_name",
",",
"require_ready",
"=",
"require_ready",
")"
] | Return the config matching the given bot_label and config_name.
config_name is case-insensitive.
Raise LookupError if no bot exists with this label, or no config
exists with this name in the bot. Raise ValueError if called with a
single argument that doesn't contain exactly one dot. | [
"Return",
"the",
"config",
"matching",
"the",
"given",
"bot_label",
"and",
"config_name",
".",
"config_name",
"is",
"case",
"-",
"insensitive",
".",
"Raise",
"LookupError",
"if",
"no",
"bot",
"exists",
"with",
"this",
"label",
"or",
"no",
"config",
"exists",
"with",
"this",
"name",
"in",
"the",
"bot",
".",
"Raise",
"ValueError",
"if",
"called",
"with",
"a",
"single",
"argument",
"that",
"doesn",
"t",
"contain",
"exactly",
"one",
"dot",
"."
] | 8cb68bb8d0b5f822108db1cc5dae336e3d3c3452 | https://github.com/budacom/trading-bots/blob/8cb68bb8d0b5f822108db1cc5dae336e3d3c3452/trading_bots/bots/registry.py#L298-L319 | train |
mjj4791/python-buienradar | buienradar/buienradar_json.py | __to_float | def __to_float(val, digits):
"""Convert val into float with digits decimal."""
try:
return round(float(val), digits)
except (ValueError, TypeError):
return float(0) | python | def __to_float(val, digits):
"""Convert val into float with digits decimal."""
try:
return round(float(val), digits)
except (ValueError, TypeError):
return float(0) | [
"def",
"__to_float",
"(",
"val",
",",
"digits",
")",
":",
"try",
":",
"return",
"round",
"(",
"float",
"(",
"val",
")",
",",
"digits",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"return",
"float",
"(",
"0",
")"
] | Convert val into float with digits decimal. | [
"Convert",
"val",
"into",
"float",
"with",
"digits",
"decimal",
"."
] | a70436f54e007ce921d5210cb296cf3e4adf9d09 | https://github.com/mjj4791/python-buienradar/blob/a70436f54e007ce921d5210cb296cf3e4adf9d09/buienradar/buienradar_json.py#L97-L102 | train |
mjj4791/python-buienradar | buienradar/buienradar_json.py | get_json_data | def get_json_data(latitude=52.091579, longitude=5.119734):
"""Get buienradar json data and return results."""
final_result = {SUCCESS: False,
MESSAGE: None,
CONTENT: None,
RAINCONTENT: None}
log.info("Getting buienradar json data for latitude=%s, longitude=%s",
latitude, longitude)
result = __get_ws_data()
if result[SUCCESS]:
# store json data:
final_result[CONTENT] = result[CONTENT]
final_result[SUCCESS] = True
else:
if STATUS_CODE in result and MESSAGE in result:
msg = "Status: %d, Msg: %s" % (result[STATUS_CODE],
result[MESSAGE])
elif MESSAGE in result:
msg = "Msg: %s" % (result[MESSAGE])
else:
msg = "Something went wrong (reason unknown)."
log.warning(msg)
final_result[MESSAGE] = msg
# load forecasted precipitation:
result = __get_precipfc_data(latitude,
longitude)
if result[SUCCESS]:
final_result[RAINCONTENT] = result[CONTENT]
else:
if STATUS_CODE in result and MESSAGE in result:
msg = "Status: %d, Msg: %s" % (result[STATUS_CODE],
result[MESSAGE])
elif MESSAGE in result:
msg = "Msg: %s" % (result[MESSAGE])
else:
msg = "Something went wrong (reason unknown)."
log.warning(msg)
final_result[MESSAGE] = msg
return final_result | python | def get_json_data(latitude=52.091579, longitude=5.119734):
"""Get buienradar json data and return results."""
final_result = {SUCCESS: False,
MESSAGE: None,
CONTENT: None,
RAINCONTENT: None}
log.info("Getting buienradar json data for latitude=%s, longitude=%s",
latitude, longitude)
result = __get_ws_data()
if result[SUCCESS]:
# store json data:
final_result[CONTENT] = result[CONTENT]
final_result[SUCCESS] = True
else:
if STATUS_CODE in result and MESSAGE in result:
msg = "Status: %d, Msg: %s" % (result[STATUS_CODE],
result[MESSAGE])
elif MESSAGE in result:
msg = "Msg: %s" % (result[MESSAGE])
else:
msg = "Something went wrong (reason unknown)."
log.warning(msg)
final_result[MESSAGE] = msg
# load forecasted precipitation:
result = __get_precipfc_data(latitude,
longitude)
if result[SUCCESS]:
final_result[RAINCONTENT] = result[CONTENT]
else:
if STATUS_CODE in result and MESSAGE in result:
msg = "Status: %d, Msg: %s" % (result[STATUS_CODE],
result[MESSAGE])
elif MESSAGE in result:
msg = "Msg: %s" % (result[MESSAGE])
else:
msg = "Something went wrong (reason unknown)."
log.warning(msg)
final_result[MESSAGE] = msg
return final_result | [
"def",
"get_json_data",
"(",
"latitude",
"=",
"52.091579",
",",
"longitude",
"=",
"5.119734",
")",
":",
"final_result",
"=",
"{",
"SUCCESS",
":",
"False",
",",
"MESSAGE",
":",
"None",
",",
"CONTENT",
":",
"None",
",",
"RAINCONTENT",
":",
"None",
"}",
"log",
".",
"info",
"(",
"\"Getting buienradar json data for latitude=%s, longitude=%s\"",
",",
"latitude",
",",
"longitude",
")",
"result",
"=",
"__get_ws_data",
"(",
")",
"if",
"result",
"[",
"SUCCESS",
"]",
":",
"final_result",
"[",
"CONTENT",
"]",
"=",
"result",
"[",
"CONTENT",
"]",
"final_result",
"[",
"SUCCESS",
"]",
"=",
"True",
"else",
":",
"if",
"STATUS_CODE",
"in",
"result",
"and",
"MESSAGE",
"in",
"result",
":",
"msg",
"=",
"\"Status: %d, Msg: %s\"",
"%",
"(",
"result",
"[",
"STATUS_CODE",
"]",
",",
"result",
"[",
"MESSAGE",
"]",
")",
"elif",
"MESSAGE",
"in",
"result",
":",
"msg",
"=",
"\"Msg: %s\"",
"%",
"(",
"result",
"[",
"MESSAGE",
"]",
")",
"else",
":",
"msg",
"=",
"\"Something went wrong (reason unknown).\"",
"log",
".",
"warning",
"(",
"msg",
")",
"final_result",
"[",
"MESSAGE",
"]",
"=",
"msg",
"result",
"=",
"__get_precipfc_data",
"(",
"latitude",
",",
"longitude",
")",
"if",
"result",
"[",
"SUCCESS",
"]",
":",
"final_result",
"[",
"RAINCONTENT",
"]",
"=",
"result",
"[",
"CONTENT",
"]",
"else",
":",
"if",
"STATUS_CODE",
"in",
"result",
"and",
"MESSAGE",
"in",
"result",
":",
"msg",
"=",
"\"Status: %d, Msg: %s\"",
"%",
"(",
"result",
"[",
"STATUS_CODE",
"]",
",",
"result",
"[",
"MESSAGE",
"]",
")",
"elif",
"MESSAGE",
"in",
"result",
":",
"msg",
"=",
"\"Msg: %s\"",
"%",
"(",
"result",
"[",
"MESSAGE",
"]",
")",
"else",
":",
"msg",
"=",
"\"Something went wrong (reason unknown).\"",
"log",
".",
"warning",
"(",
"msg",
")",
"final_result",
"[",
"MESSAGE",
"]",
"=",
"msg",
"return",
"final_result"
] | Get buienradar json data and return results. | [
"Get",
"buienradar",
"json",
"data",
"and",
"return",
"results",
"."
] | a70436f54e007ce921d5210cb296cf3e4adf9d09 | https://github.com/mjj4791/python-buienradar/blob/a70436f54e007ce921d5210cb296cf3e4adf9d09/buienradar/buienradar_json.py#L194-L238 | train |
mjj4791/python-buienradar | buienradar/buienradar_json.py | __get_precipfc_data | def __get_precipfc_data(latitude, longitude):
"""Get buienradar forecasted precipitation."""
url = 'https://gpsgadget.buienradar.nl/data/raintext?lat={}&lon={}'
# rounding coordinates prevents unnecessary redirects/calls
url = url.format(
round(latitude, 2),
round(longitude, 2)
)
result = __get_url(url)
return result | python | def __get_precipfc_data(latitude, longitude):
"""Get buienradar forecasted precipitation."""
url = 'https://gpsgadget.buienradar.nl/data/raintext?lat={}&lon={}'
# rounding coordinates prevents unnecessary redirects/calls
url = url.format(
round(latitude, 2),
round(longitude, 2)
)
result = __get_url(url)
return result | [
"def",
"__get_precipfc_data",
"(",
"latitude",
",",
"longitude",
")",
":",
"url",
"=",
"'https://gpsgadget.buienradar.nl/data/raintext?lat={}&lon={}'",
"url",
"=",
"url",
".",
"format",
"(",
"round",
"(",
"latitude",
",",
"2",
")",
",",
"round",
"(",
"longitude",
",",
"2",
")",
")",
"result",
"=",
"__get_url",
"(",
"url",
")",
"return",
"result"
] | Get buienradar forecasted precipitation. | [
"Get",
"buienradar",
"forecasted",
"precipitation",
"."
] | a70436f54e007ce921d5210cb296cf3e4adf9d09 | https://github.com/mjj4791/python-buienradar/blob/a70436f54e007ce921d5210cb296cf3e4adf9d09/buienradar/buienradar_json.py#L276-L285 | train |
mjj4791/python-buienradar | buienradar/buienradar_json.py | __get_url | def __get_url(url):
"""Load json data from url and return result."""
log.info("Retrieving weather data (%s)...", url)
result = {SUCCESS: False, MESSAGE: None}
try:
r = requests.get(url)
result[STATUS_CODE] = r.status_code
result[HEADERS] = r.headers
result[CONTENT] = r.text
if (200 == r.status_code):
result[SUCCESS] = True
else:
result[MESSAGE] = "Got http statuscode: %d." % (r.status_code)
return result
except requests.RequestException as ose:
result[MESSAGE] = 'Error getting url data. %s' % ose
log.error(result[MESSAGE])
return result | python | def __get_url(url):
"""Load json data from url and return result."""
log.info("Retrieving weather data (%s)...", url)
result = {SUCCESS: False, MESSAGE: None}
try:
r = requests.get(url)
result[STATUS_CODE] = r.status_code
result[HEADERS] = r.headers
result[CONTENT] = r.text
if (200 == r.status_code):
result[SUCCESS] = True
else:
result[MESSAGE] = "Got http statuscode: %d." % (r.status_code)
return result
except requests.RequestException as ose:
result[MESSAGE] = 'Error getting url data. %s' % ose
log.error(result[MESSAGE])
return result | [
"def",
"__get_url",
"(",
"url",
")",
":",
"log",
".",
"info",
"(",
"\"Retrieving weather data (%s)...\"",
",",
"url",
")",
"result",
"=",
"{",
"SUCCESS",
":",
"False",
",",
"MESSAGE",
":",
"None",
"}",
"try",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"url",
")",
"result",
"[",
"STATUS_CODE",
"]",
"=",
"r",
".",
"status_code",
"result",
"[",
"HEADERS",
"]",
"=",
"r",
".",
"headers",
"result",
"[",
"CONTENT",
"]",
"=",
"r",
".",
"text",
"if",
"(",
"200",
"==",
"r",
".",
"status_code",
")",
":",
"result",
"[",
"SUCCESS",
"]",
"=",
"True",
"else",
":",
"result",
"[",
"MESSAGE",
"]",
"=",
"\"Got http statuscode: %d.\"",
"%",
"(",
"r",
".",
"status_code",
")",
"return",
"result",
"except",
"requests",
".",
"RequestException",
"as",
"ose",
":",
"result",
"[",
"MESSAGE",
"]",
"=",
"'Error getting url data. %s'",
"%",
"ose",
"log",
".",
"error",
"(",
"result",
"[",
"MESSAGE",
"]",
")",
"return",
"result"
] | Load json data from url and return result. | [
"Load",
"json",
"data",
"from",
"url",
"and",
"return",
"result",
"."
] | a70436f54e007ce921d5210cb296cf3e4adf9d09 | https://github.com/mjj4791/python-buienradar/blob/a70436f54e007ce921d5210cb296cf3e4adf9d09/buienradar/buienradar_json.py#L288-L306 | train |
mjj4791/python-buienradar | buienradar/buienradar_json.py | __parse_ws_data | def __parse_ws_data(jsondata, latitude=52.091579, longitude=5.119734):
"""Parse the buienradar json and rain data."""
log.info("Parse ws data: latitude: %s, longitude: %s", latitude, longitude)
result = {SUCCESS: False, MESSAGE: None, DATA: None}
# select the nearest weather station
loc_data = __select_nearest_ws(jsondata, latitude, longitude)
# process current weather data from selected weatherstation
if not loc_data:
result[MESSAGE] = 'No location selected.'
return result
if not __is_valid(loc_data):
result[MESSAGE] = 'Location data is invalid.'
return result
# add distance to weatherstation
log.debug("Raw location data: %s", loc_data)
result[DISTANCE] = __get_ws_distance(loc_data, latitude, longitude)
result = __parse_loc_data(loc_data, result)
# extract weather forecast
try:
fc_data = jsondata[__FORECAST][__FIVEDAYFORECAST]
except (json.JSONDecodeError, KeyError):
result[MESSAGE] = 'Unable to extract forecast data.'
log.exception(result[MESSAGE])
return result
if fc_data:
# result = __parse_fc_data(fc_data, result)
log.debug("Raw forecast data: %s", fc_data)
# pylint: disable=unsupported-assignment-operation
result[DATA][FORECAST] = __parse_fc_data(fc_data)
return result | python | def __parse_ws_data(jsondata, latitude=52.091579, longitude=5.119734):
"""Parse the buienradar json and rain data."""
log.info("Parse ws data: latitude: %s, longitude: %s", latitude, longitude)
result = {SUCCESS: False, MESSAGE: None, DATA: None}
# select the nearest weather station
loc_data = __select_nearest_ws(jsondata, latitude, longitude)
# process current weather data from selected weatherstation
if not loc_data:
result[MESSAGE] = 'No location selected.'
return result
if not __is_valid(loc_data):
result[MESSAGE] = 'Location data is invalid.'
return result
# add distance to weatherstation
log.debug("Raw location data: %s", loc_data)
result[DISTANCE] = __get_ws_distance(loc_data, latitude, longitude)
result = __parse_loc_data(loc_data, result)
# extract weather forecast
try:
fc_data = jsondata[__FORECAST][__FIVEDAYFORECAST]
except (json.JSONDecodeError, KeyError):
result[MESSAGE] = 'Unable to extract forecast data.'
log.exception(result[MESSAGE])
return result
if fc_data:
# result = __parse_fc_data(fc_data, result)
log.debug("Raw forecast data: %s", fc_data)
# pylint: disable=unsupported-assignment-operation
result[DATA][FORECAST] = __parse_fc_data(fc_data)
return result | [
"def",
"__parse_ws_data",
"(",
"jsondata",
",",
"latitude",
"=",
"52.091579",
",",
"longitude",
"=",
"5.119734",
")",
":",
"log",
".",
"info",
"(",
"\"Parse ws data: latitude: %s, longitude: %s\"",
",",
"latitude",
",",
"longitude",
")",
"result",
"=",
"{",
"SUCCESS",
":",
"False",
",",
"MESSAGE",
":",
"None",
",",
"DATA",
":",
"None",
"}",
"loc_data",
"=",
"__select_nearest_ws",
"(",
"jsondata",
",",
"latitude",
",",
"longitude",
")",
"if",
"not",
"loc_data",
":",
"result",
"[",
"MESSAGE",
"]",
"=",
"'No location selected.'",
"return",
"result",
"if",
"not",
"__is_valid",
"(",
"loc_data",
")",
":",
"result",
"[",
"MESSAGE",
"]",
"=",
"'Location data is invalid.'",
"return",
"result",
"log",
".",
"debug",
"(",
"\"Raw location data: %s\"",
",",
"loc_data",
")",
"result",
"[",
"DISTANCE",
"]",
"=",
"__get_ws_distance",
"(",
"loc_data",
",",
"latitude",
",",
"longitude",
")",
"result",
"=",
"__parse_loc_data",
"(",
"loc_data",
",",
"result",
")",
"try",
":",
"fc_data",
"=",
"jsondata",
"[",
"__FORECAST",
"]",
"[",
"__FIVEDAYFORECAST",
"]",
"except",
"(",
"json",
".",
"JSONDecodeError",
",",
"KeyError",
")",
":",
"result",
"[",
"MESSAGE",
"]",
"=",
"'Unable to extract forecast data.'",
"log",
".",
"exception",
"(",
"result",
"[",
"MESSAGE",
"]",
")",
"return",
"result",
"if",
"fc_data",
":",
"log",
".",
"debug",
"(",
"\"Raw forecast data: %s\"",
",",
"fc_data",
")",
"result",
"[",
"DATA",
"]",
"[",
"FORECAST",
"]",
"=",
"__parse_fc_data",
"(",
"fc_data",
")",
"return",
"result"
] | Parse the buienradar json and rain data. | [
"Parse",
"the",
"buienradar",
"json",
"and",
"rain",
"data",
"."
] | a70436f54e007ce921d5210cb296cf3e4adf9d09 | https://github.com/mjj4791/python-buienradar/blob/a70436f54e007ce921d5210cb296cf3e4adf9d09/buienradar/buienradar_json.py#L309-L344 | train |
mjj4791/python-buienradar | buienradar/buienradar_json.py | __parse_loc_data | def __parse_loc_data(loc_data, result):
"""Parse the json data from selected weatherstation."""
result[DATA] = {ATTRIBUTION: ATTRIBUTION_INFO,
FORECAST: [],
PRECIPITATION_FORECAST: None}
for key, [value, func] in SENSOR_TYPES.items():
result[DATA][key] = None
try:
sens_data = loc_data[value]
if key == CONDITION:
# update weather symbol & status text
desc = loc_data[__WEATHERDESCRIPTION]
result[DATA][CONDITION] = __cond_from_desc(desc)
result[DATA][CONDITION][IMAGE] = loc_data[__ICONURL]
continue
if key == STATIONNAME:
result[DATA][key] = __getStationName(loc_data[__STATIONNAME],
loc_data[__STATIONID])
continue
# update all other data:
if func is not None:
result[DATA][key] = func(sens_data)
else:
result[DATA][key] = sens_data
except KeyError:
if result[MESSAGE] is None:
result[MESSAGE] = "Missing key(s) in br data: "
result[MESSAGE] += "%s " % value
log.warning("Data element with key='%s' "
"not loaded from br data!", key)
result[SUCCESS] = True
return result | python | def __parse_loc_data(loc_data, result):
"""Parse the json data from selected weatherstation."""
result[DATA] = {ATTRIBUTION: ATTRIBUTION_INFO,
FORECAST: [],
PRECIPITATION_FORECAST: None}
for key, [value, func] in SENSOR_TYPES.items():
result[DATA][key] = None
try:
sens_data = loc_data[value]
if key == CONDITION:
# update weather symbol & status text
desc = loc_data[__WEATHERDESCRIPTION]
result[DATA][CONDITION] = __cond_from_desc(desc)
result[DATA][CONDITION][IMAGE] = loc_data[__ICONURL]
continue
if key == STATIONNAME:
result[DATA][key] = __getStationName(loc_data[__STATIONNAME],
loc_data[__STATIONID])
continue
# update all other data:
if func is not None:
result[DATA][key] = func(sens_data)
else:
result[DATA][key] = sens_data
except KeyError:
if result[MESSAGE] is None:
result[MESSAGE] = "Missing key(s) in br data: "
result[MESSAGE] += "%s " % value
log.warning("Data element with key='%s' "
"not loaded from br data!", key)
result[SUCCESS] = True
return result | [
"def",
"__parse_loc_data",
"(",
"loc_data",
",",
"result",
")",
":",
"result",
"[",
"DATA",
"]",
"=",
"{",
"ATTRIBUTION",
":",
"ATTRIBUTION_INFO",
",",
"FORECAST",
":",
"[",
"]",
",",
"PRECIPITATION_FORECAST",
":",
"None",
"}",
"for",
"key",
",",
"[",
"value",
",",
"func",
"]",
"in",
"SENSOR_TYPES",
".",
"items",
"(",
")",
":",
"result",
"[",
"DATA",
"]",
"[",
"key",
"]",
"=",
"None",
"try",
":",
"sens_data",
"=",
"loc_data",
"[",
"value",
"]",
"if",
"key",
"==",
"CONDITION",
":",
"desc",
"=",
"loc_data",
"[",
"__WEATHERDESCRIPTION",
"]",
"result",
"[",
"DATA",
"]",
"[",
"CONDITION",
"]",
"=",
"__cond_from_desc",
"(",
"desc",
")",
"result",
"[",
"DATA",
"]",
"[",
"CONDITION",
"]",
"[",
"IMAGE",
"]",
"=",
"loc_data",
"[",
"__ICONURL",
"]",
"continue",
"if",
"key",
"==",
"STATIONNAME",
":",
"result",
"[",
"DATA",
"]",
"[",
"key",
"]",
"=",
"__getStationName",
"(",
"loc_data",
"[",
"__STATIONNAME",
"]",
",",
"loc_data",
"[",
"__STATIONID",
"]",
")",
"continue",
"if",
"func",
"is",
"not",
"None",
":",
"result",
"[",
"DATA",
"]",
"[",
"key",
"]",
"=",
"func",
"(",
"sens_data",
")",
"else",
":",
"result",
"[",
"DATA",
"]",
"[",
"key",
"]",
"=",
"sens_data",
"except",
"KeyError",
":",
"if",
"result",
"[",
"MESSAGE",
"]",
"is",
"None",
":",
"result",
"[",
"MESSAGE",
"]",
"=",
"\"Missing key(s) in br data: \"",
"result",
"[",
"MESSAGE",
"]",
"+=",
"\"%s \"",
"%",
"value",
"log",
".",
"warning",
"(",
"\"Data element with key='%s' \"",
"\"not loaded from br data!\"",
",",
"key",
")",
"result",
"[",
"SUCCESS",
"]",
"=",
"True",
"return",
"result"
] | Parse the json data from selected weatherstation. | [
"Parse",
"the",
"json",
"data",
"from",
"selected",
"weatherstation",
"."
] | a70436f54e007ce921d5210cb296cf3e4adf9d09 | https://github.com/mjj4791/python-buienradar/blob/a70436f54e007ce921d5210cb296cf3e4adf9d09/buienradar/buienradar_json.py#L347-L379 | train |
mjj4791/python-buienradar | buienradar/buienradar_json.py | __parse_fc_data | def __parse_fc_data(fc_data):
"""Parse the forecast data from the json section."""
fc = []
for day in fc_data:
fcdata = {
CONDITION: __cond_from_desc(
__get_str(
day,
__WEATHERDESCRIPTION)
),
TEMPERATURE: __get_float(day, __MAXTEMPERATURE),
MIN_TEMP: __get_float(day, __MINTEMPERATURE),
MAX_TEMP: __get_float(day, __MAXTEMPERATURE),
SUN_CHANCE: __get_int(day, __SUNCHANCE),
RAIN_CHANCE: __get_int(day, __RAINCHANCE),
RAIN: __get_float(day, __MMRAINMAX),
MIN_RAIN: __get_float(day, __MMRAINMIN), # new
MAX_RAIN: __get_float(day, __MMRAINMAX), # new
SNOW: 0, # for compatibility
WINDFORCE: __get_int(day, __WIND),
WINDDIRECTION: __get_str(day, __WINDDIRECTION), # new
DATETIME: __to_localdatetime(__get_str(day, __DAY)),
}
fcdata[CONDITION][IMAGE] = day[__ICONURL]
fc.append(fcdata)
return fc | python | def __parse_fc_data(fc_data):
"""Parse the forecast data from the json section."""
fc = []
for day in fc_data:
fcdata = {
CONDITION: __cond_from_desc(
__get_str(
day,
__WEATHERDESCRIPTION)
),
TEMPERATURE: __get_float(day, __MAXTEMPERATURE),
MIN_TEMP: __get_float(day, __MINTEMPERATURE),
MAX_TEMP: __get_float(day, __MAXTEMPERATURE),
SUN_CHANCE: __get_int(day, __SUNCHANCE),
RAIN_CHANCE: __get_int(day, __RAINCHANCE),
RAIN: __get_float(day, __MMRAINMAX),
MIN_RAIN: __get_float(day, __MMRAINMIN), # new
MAX_RAIN: __get_float(day, __MMRAINMAX), # new
SNOW: 0, # for compatibility
WINDFORCE: __get_int(day, __WIND),
WINDDIRECTION: __get_str(day, __WINDDIRECTION), # new
DATETIME: __to_localdatetime(__get_str(day, __DAY)),
}
fcdata[CONDITION][IMAGE] = day[__ICONURL]
fc.append(fcdata)
return fc | [
"def",
"__parse_fc_data",
"(",
"fc_data",
")",
":",
"fc",
"=",
"[",
"]",
"for",
"day",
"in",
"fc_data",
":",
"fcdata",
"=",
"{",
"CONDITION",
":",
"__cond_from_desc",
"(",
"__get_str",
"(",
"day",
",",
"__WEATHERDESCRIPTION",
")",
")",
",",
"TEMPERATURE",
":",
"__get_float",
"(",
"day",
",",
"__MAXTEMPERATURE",
")",
",",
"MIN_TEMP",
":",
"__get_float",
"(",
"day",
",",
"__MINTEMPERATURE",
")",
",",
"MAX_TEMP",
":",
"__get_float",
"(",
"day",
",",
"__MAXTEMPERATURE",
")",
",",
"SUN_CHANCE",
":",
"__get_int",
"(",
"day",
",",
"__SUNCHANCE",
")",
",",
"RAIN_CHANCE",
":",
"__get_int",
"(",
"day",
",",
"__RAINCHANCE",
")",
",",
"RAIN",
":",
"__get_float",
"(",
"day",
",",
"__MMRAINMAX",
")",
",",
"MIN_RAIN",
":",
"__get_float",
"(",
"day",
",",
"__MMRAINMIN",
")",
",",
"MAX_RAIN",
":",
"__get_float",
"(",
"day",
",",
"__MMRAINMAX",
")",
",",
"SNOW",
":",
"0",
",",
"WINDFORCE",
":",
"__get_int",
"(",
"day",
",",
"__WIND",
")",
",",
"WINDDIRECTION",
":",
"__get_str",
"(",
"day",
",",
"__WINDDIRECTION",
")",
",",
"DATETIME",
":",
"__to_localdatetime",
"(",
"__get_str",
"(",
"day",
",",
"__DAY",
")",
")",
",",
"}",
"fcdata",
"[",
"CONDITION",
"]",
"[",
"IMAGE",
"]",
"=",
"day",
"[",
"__ICONURL",
"]",
"fc",
".",
"append",
"(",
"fcdata",
")",
"return",
"fc"
] | Parse the forecast data from the json section. | [
"Parse",
"the",
"forecast",
"data",
"from",
"the",
"json",
"section",
"."
] | a70436f54e007ce921d5210cb296cf3e4adf9d09 | https://github.com/mjj4791/python-buienradar/blob/a70436f54e007ce921d5210cb296cf3e4adf9d09/buienradar/buienradar_json.py#L382-L408 | train |
mjj4791/python-buienradar | buienradar/buienradar_json.py | __get_float | def __get_float(section, name):
"""Get the forecasted float from json section."""
try:
return float(section[name])
except (ValueError, TypeError, KeyError):
return float(0) | python | def __get_float(section, name):
"""Get the forecasted float from json section."""
try:
return float(section[name])
except (ValueError, TypeError, KeyError):
return float(0) | [
"def",
"__get_float",
"(",
"section",
",",
"name",
")",
":",
"try",
":",
"return",
"float",
"(",
"section",
"[",
"name",
"]",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
",",
"KeyError",
")",
":",
"return",
"float",
"(",
"0",
")"
] | Get the forecasted float from json section. | [
"Get",
"the",
"forecasted",
"float",
"from",
"json",
"section",
"."
] | a70436f54e007ce921d5210cb296cf3e4adf9d09 | https://github.com/mjj4791/python-buienradar/blob/a70436f54e007ce921d5210cb296cf3e4adf9d09/buienradar/buienradar_json.py#L419-L424 | train |
mjj4791/python-buienradar | buienradar/buienradar_json.py | __parse_precipfc_data | def __parse_precipfc_data(data, timeframe):
"""Parse the forecasted precipitation data."""
result = {AVERAGE: None, TOTAL: None, TIMEFRAME: None}
log.debug("Precipitation data: %s", data)
lines = data.splitlines()
index = 1
totalrain = 0
numberoflines = 0
nrlines = min(len(lines), round(float(timeframe) / 5) + 1)
# looping through lines of forecasted precipitation data and
# not using the time data (HH:MM) int the data. This is to allow for
# correct data in case we are running in a different timezone.
while index < nrlines:
line = lines[index]
log.debug("__parse_precipfc_data: line: %s", line)
# pylint: disable=unused-variable
(val, key) = line.split("|")
# See buienradar documentation for this api, attribution
# https://www.buienradar.nl/overbuienradar/gratis-weerdata
#
# Op basis van de door u gewenste coordinaten (latitude en longitude)
# kunt u de neerslag tot twee uur vooruit ophalen in tekstvorm. De
# data wordt iedere 5 minuten geupdatet. Op deze pagina kunt u de
# neerslag in tekst vinden. De waarde 0 geeft geen neerslag aan (droog)
# de waarde 255 geeft zware neerslag aan. Gebruik de volgende formule
# voor het omrekenen naar de neerslagintensiteit in de eenheid
# millimeter per uur (mm/u):
#
# Neerslagintensiteit = 10^((waarde-109)/32)
#
# Ter controle: een waarde van 77 is gelijk aan een neerslagintensiteit
# van 0,1 mm/u.
mmu = 10**(float((int(val) - 109)) / 32)
totalrain = totalrain + float(mmu)
numberoflines = numberoflines + 1
index += 1
if numberoflines > 0:
result[AVERAGE] = round((totalrain / numberoflines), 2)
else:
result[AVERAGE] = 0
result[TOTAL] = round(totalrain / 12, 2)
result[TIMEFRAME] = timeframe
return result | python | def __parse_precipfc_data(data, timeframe):
"""Parse the forecasted precipitation data."""
result = {AVERAGE: None, TOTAL: None, TIMEFRAME: None}
log.debug("Precipitation data: %s", data)
lines = data.splitlines()
index = 1
totalrain = 0
numberoflines = 0
nrlines = min(len(lines), round(float(timeframe) / 5) + 1)
# looping through lines of forecasted precipitation data and
# not using the time data (HH:MM) int the data. This is to allow for
# correct data in case we are running in a different timezone.
while index < nrlines:
line = lines[index]
log.debug("__parse_precipfc_data: line: %s", line)
# pylint: disable=unused-variable
(val, key) = line.split("|")
# See buienradar documentation for this api, attribution
# https://www.buienradar.nl/overbuienradar/gratis-weerdata
#
# Op basis van de door u gewenste coordinaten (latitude en longitude)
# kunt u de neerslag tot twee uur vooruit ophalen in tekstvorm. De
# data wordt iedere 5 minuten geupdatet. Op deze pagina kunt u de
# neerslag in tekst vinden. De waarde 0 geeft geen neerslag aan (droog)
# de waarde 255 geeft zware neerslag aan. Gebruik de volgende formule
# voor het omrekenen naar de neerslagintensiteit in de eenheid
# millimeter per uur (mm/u):
#
# Neerslagintensiteit = 10^((waarde-109)/32)
#
# Ter controle: een waarde van 77 is gelijk aan een neerslagintensiteit
# van 0,1 mm/u.
mmu = 10**(float((int(val) - 109)) / 32)
totalrain = totalrain + float(mmu)
numberoflines = numberoflines + 1
index += 1
if numberoflines > 0:
result[AVERAGE] = round((totalrain / numberoflines), 2)
else:
result[AVERAGE] = 0
result[TOTAL] = round(totalrain / 12, 2)
result[TIMEFRAME] = timeframe
return result | [
"def",
"__parse_precipfc_data",
"(",
"data",
",",
"timeframe",
")",
":",
"result",
"=",
"{",
"AVERAGE",
":",
"None",
",",
"TOTAL",
":",
"None",
",",
"TIMEFRAME",
":",
"None",
"}",
"log",
".",
"debug",
"(",
"\"Precipitation data: %s\"",
",",
"data",
")",
"lines",
"=",
"data",
".",
"splitlines",
"(",
")",
"index",
"=",
"1",
"totalrain",
"=",
"0",
"numberoflines",
"=",
"0",
"nrlines",
"=",
"min",
"(",
"len",
"(",
"lines",
")",
",",
"round",
"(",
"float",
"(",
"timeframe",
")",
"/",
"5",
")",
"+",
"1",
")",
"while",
"index",
"<",
"nrlines",
":",
"line",
"=",
"lines",
"[",
"index",
"]",
"log",
".",
"debug",
"(",
"\"__parse_precipfc_data: line: %s\"",
",",
"line",
")",
"(",
"val",
",",
"key",
")",
"=",
"line",
".",
"split",
"(",
"\"|\"",
")",
"mmu",
"=",
"10",
"**",
"(",
"float",
"(",
"(",
"int",
"(",
"val",
")",
"-",
"109",
")",
")",
"/",
"32",
")",
"totalrain",
"=",
"totalrain",
"+",
"float",
"(",
"mmu",
")",
"numberoflines",
"=",
"numberoflines",
"+",
"1",
"index",
"+=",
"1",
"if",
"numberoflines",
">",
"0",
":",
"result",
"[",
"AVERAGE",
"]",
"=",
"round",
"(",
"(",
"totalrain",
"/",
"numberoflines",
")",
",",
"2",
")",
"else",
":",
"result",
"[",
"AVERAGE",
"]",
"=",
"0",
"result",
"[",
"TOTAL",
"]",
"=",
"round",
"(",
"totalrain",
"/",
"12",
",",
"2",
")",
"result",
"[",
"TIMEFRAME",
"]",
"=",
"timeframe",
"return",
"result"
] | Parse the forecasted precipitation data. | [
"Parse",
"the",
"forecasted",
"precipitation",
"data",
"."
] | a70436f54e007ce921d5210cb296cf3e4adf9d09 | https://github.com/mjj4791/python-buienradar/blob/a70436f54e007ce921d5210cb296cf3e4adf9d09/buienradar/buienradar_json.py#L435-L480 | train |
mjj4791/python-buienradar | buienradar/buienradar_json.py | __cond_from_desc | def __cond_from_desc(desc):
"""Get the condition name from the condition description."""
# '{ 'code': 'conditon', 'detailed', 'exact', 'exact_nl'}
for code, [condition, detailed, exact, exact_nl] in __BRCONDITIONS.items():
if exact_nl == desc:
return {CONDCODE: code,
CONDITION: condition,
DETAILED: detailed,
EXACT: exact,
EXACTNL: exact_nl
}
return None | python | def __cond_from_desc(desc):
"""Get the condition name from the condition description."""
# '{ 'code': 'conditon', 'detailed', 'exact', 'exact_nl'}
for code, [condition, detailed, exact, exact_nl] in __BRCONDITIONS.items():
if exact_nl == desc:
return {CONDCODE: code,
CONDITION: condition,
DETAILED: detailed,
EXACT: exact,
EXACTNL: exact_nl
}
return None | [
"def",
"__cond_from_desc",
"(",
"desc",
")",
":",
"for",
"code",
",",
"[",
"condition",
",",
"detailed",
",",
"exact",
",",
"exact_nl",
"]",
"in",
"__BRCONDITIONS",
".",
"items",
"(",
")",
":",
"if",
"exact_nl",
"==",
"desc",
":",
"return",
"{",
"CONDCODE",
":",
"code",
",",
"CONDITION",
":",
"condition",
",",
"DETAILED",
":",
"detailed",
",",
"EXACT",
":",
"exact",
",",
"EXACTNL",
":",
"exact_nl",
"}",
"return",
"None"
] | Get the condition name from the condition description. | [
"Get",
"the",
"condition",
"name",
"from",
"the",
"condition",
"description",
"."
] | a70436f54e007ce921d5210cb296cf3e4adf9d09 | https://github.com/mjj4791/python-buienradar/blob/a70436f54e007ce921d5210cb296cf3e4adf9d09/buienradar/buienradar_json.py#L483-L494 | train |
mjj4791/python-buienradar | buienradar/buienradar_json.py | __get_ws_distance | def __get_ws_distance(wstation, latitude, longitude):
"""Get the distance to the weatherstation from wstation section of json.
wstation: weerstation section of buienradar json (dict)
latitude: our latitude
longitude: our longitude
"""
if wstation:
try:
wslat = float(wstation[__LAT])
wslon = float(wstation[__LON])
dist = vincenty((latitude, longitude), (wslat, wslon))
log.debug("calc distance: %s (latitude: %s, longitude: "
"%s, wslat: %s, wslon: %s)", dist, latitude,
longitude, wslat, wslon)
return dist
except (ValueError, TypeError, KeyError):
# value does not exist, or is not a float
return None
else:
return None | python | def __get_ws_distance(wstation, latitude, longitude):
"""Get the distance to the weatherstation from wstation section of json.
wstation: weerstation section of buienradar json (dict)
latitude: our latitude
longitude: our longitude
"""
if wstation:
try:
wslat = float(wstation[__LAT])
wslon = float(wstation[__LON])
dist = vincenty((latitude, longitude), (wslat, wslon))
log.debug("calc distance: %s (latitude: %s, longitude: "
"%s, wslat: %s, wslon: %s)", dist, latitude,
longitude, wslat, wslon)
return dist
except (ValueError, TypeError, KeyError):
# value does not exist, or is not a float
return None
else:
return None | [
"def",
"__get_ws_distance",
"(",
"wstation",
",",
"latitude",
",",
"longitude",
")",
":",
"if",
"wstation",
":",
"try",
":",
"wslat",
"=",
"float",
"(",
"wstation",
"[",
"__LAT",
"]",
")",
"wslon",
"=",
"float",
"(",
"wstation",
"[",
"__LON",
"]",
")",
"dist",
"=",
"vincenty",
"(",
"(",
"latitude",
",",
"longitude",
")",
",",
"(",
"wslat",
",",
"wslon",
")",
")",
"log",
".",
"debug",
"(",
"\"calc distance: %s (latitude: %s, longitude: \"",
"\"%s, wslat: %s, wslon: %s)\"",
",",
"dist",
",",
"latitude",
",",
"longitude",
",",
"wslat",
",",
"wslon",
")",
"return",
"dist",
"except",
"(",
"ValueError",
",",
"TypeError",
",",
"KeyError",
")",
":",
"return",
"None",
"else",
":",
"return",
"None"
] | Get the distance to the weatherstation from wstation section of json.
wstation: weerstation section of buienradar json (dict)
latitude: our latitude
longitude: our longitude | [
"Get",
"the",
"distance",
"to",
"the",
"weatherstation",
"from",
"wstation",
"section",
"of",
"json",
"."
] | a70436f54e007ce921d5210cb296cf3e4adf9d09 | https://github.com/mjj4791/python-buienradar/blob/a70436f54e007ce921d5210cb296cf3e4adf9d09/buienradar/buienradar_json.py#L538-L559 | train |
mjj4791/python-buienradar | buienradar/buienradar_json.py | __getStationName | def __getStationName(name, id):
"""Construct a staiion name."""
name = name.replace("Meetstation", "")
name = name.strip()
name += " (%s)" % id
return name | python | def __getStationName(name, id):
"""Construct a staiion name."""
name = name.replace("Meetstation", "")
name = name.strip()
name += " (%s)" % id
return name | [
"def",
"__getStationName",
"(",
"name",
",",
"id",
")",
":",
"name",
"=",
"name",
".",
"replace",
"(",
"\"Meetstation\"",
",",
"\"\"",
")",
"name",
"=",
"name",
".",
"strip",
"(",
")",
"name",
"+=",
"\" (%s)\"",
"%",
"id",
"return",
"name"
] | Construct a staiion name. | [
"Construct",
"a",
"staiion",
"name",
"."
] | a70436f54e007ce921d5210cb296cf3e4adf9d09 | https://github.com/mjj4791/python-buienradar/blob/a70436f54e007ce921d5210cb296cf3e4adf9d09/buienradar/buienradar_json.py#L575-L580 | train |
stephrdev/django-formwizard | formwizard/views.py | WizardView.as_view | def as_view(cls, *args, **kwargs):
"""
This method is used within urls.py to create unique formwizard
instances for every request. We need to override this method because
we add some kwargs which are needed to make the formwizard usable.
"""
initkwargs = cls.get_initkwargs(*args, **kwargs)
return super(WizardView, cls).as_view(**initkwargs) | python | def as_view(cls, *args, **kwargs):
"""
This method is used within urls.py to create unique formwizard
instances for every request. We need to override this method because
we add some kwargs which are needed to make the formwizard usable.
"""
initkwargs = cls.get_initkwargs(*args, **kwargs)
return super(WizardView, cls).as_view(**initkwargs) | [
"def",
"as_view",
"(",
"cls",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"initkwargs",
"=",
"cls",
".",
"get_initkwargs",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
"return",
"super",
"(",
"WizardView",
",",
"cls",
")",
".",
"as_view",
"(",
"**",
"initkwargs",
")"
] | This method is used within urls.py to create unique formwizard
instances for every request. We need to override this method because
we add some kwargs which are needed to make the formwizard usable. | [
"This",
"method",
"is",
"used",
"within",
"urls",
".",
"py",
"to",
"create",
"unique",
"formwizard",
"instances",
"for",
"every",
"request",
".",
"We",
"need",
"to",
"override",
"this",
"method",
"because",
"we",
"add",
"some",
"kwargs",
"which",
"are",
"needed",
"to",
"make",
"the",
"formwizard",
"usable",
"."
] | 7b35165f0340aae4e8302d5b05b0cb443f6c9904 | https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L103-L110 | train |
stephrdev/django-formwizard | formwizard/views.py | WizardView.get_initkwargs | def get_initkwargs(cls, form_list, initial_dict=None,
instance_dict=None, condition_dict=None, *args, **kwargs):
"""
Creates a dict with all needed parameters for the form wizard instances.
* `form_list` - is a list of forms. The list entries can be single form
classes or tuples of (`step_name`, `form_class`). If you pass a list
of forms, the formwizard will convert the class list to
(`zero_based_counter`, `form_class`). This is needed to access the
form for a specific step.
* `initial_dict` - contains a dictionary of initial data dictionaries.
The key should be equal to the `step_name` in the `form_list` (or
the str of the zero based counter - if no step_names added in the
`form_list`)
* `instance_dict` - contains a dictionary of instance objects. This list
is only used when `ModelForm`s are used. The key should be equal to
the `step_name` in the `form_list`. Same rules as for `initial_dict`
apply.
* `condition_dict` - contains a dictionary of boolean values or
callables. If the value of for a specific `step_name` is callable it
will be called with the formwizard instance as the only argument.
If the return value is true, the step's form will be used.
"""
kwargs.update({
'initial_dict': initial_dict or {},
'instance_dict': instance_dict or {},
'condition_dict': condition_dict or {},
})
init_form_list = SortedDict()
assert len(form_list) > 0, 'at least one form is needed'
# walk through the passed form list
for i, form in enumerate(form_list):
if isinstance(form, (list, tuple)):
# if the element is a tuple, add the tuple to the new created
# sorted dictionary.
init_form_list[unicode(form[0])] = form[1]
else:
# if not, add the form with a zero based counter as unicode
init_form_list[unicode(i)] = form
# walk through the ne created list of forms
for form in init_form_list.itervalues():
if issubclass(form, formsets.BaseFormSet):
# if the element is based on BaseFormSet (FormSet/ModelFormSet)
# we need to override the form variable.
form = form.form
# check if any form contains a FileField, if yes, we need a
# file_storage added to the formwizard (by subclassing).
for field in form.base_fields.itervalues():
if (isinstance(field, forms.FileField) and
not hasattr(cls, 'file_storage')):
raise NoFileStorageConfigured
# build the kwargs for the formwizard instances
kwargs['form_list'] = init_form_list
return kwargs | python | def get_initkwargs(cls, form_list, initial_dict=None,
instance_dict=None, condition_dict=None, *args, **kwargs):
"""
Creates a dict with all needed parameters for the form wizard instances.
* `form_list` - is a list of forms. The list entries can be single form
classes or tuples of (`step_name`, `form_class`). If you pass a list
of forms, the formwizard will convert the class list to
(`zero_based_counter`, `form_class`). This is needed to access the
form for a specific step.
* `initial_dict` - contains a dictionary of initial data dictionaries.
The key should be equal to the `step_name` in the `form_list` (or
the str of the zero based counter - if no step_names added in the
`form_list`)
* `instance_dict` - contains a dictionary of instance objects. This list
is only used when `ModelForm`s are used. The key should be equal to
the `step_name` in the `form_list`. Same rules as for `initial_dict`
apply.
* `condition_dict` - contains a dictionary of boolean values or
callables. If the value of for a specific `step_name` is callable it
will be called with the formwizard instance as the only argument.
If the return value is true, the step's form will be used.
"""
kwargs.update({
'initial_dict': initial_dict or {},
'instance_dict': instance_dict or {},
'condition_dict': condition_dict or {},
})
init_form_list = SortedDict()
assert len(form_list) > 0, 'at least one form is needed'
# walk through the passed form list
for i, form in enumerate(form_list):
if isinstance(form, (list, tuple)):
# if the element is a tuple, add the tuple to the new created
# sorted dictionary.
init_form_list[unicode(form[0])] = form[1]
else:
# if not, add the form with a zero based counter as unicode
init_form_list[unicode(i)] = form
# walk through the ne created list of forms
for form in init_form_list.itervalues():
if issubclass(form, formsets.BaseFormSet):
# if the element is based on BaseFormSet (FormSet/ModelFormSet)
# we need to override the form variable.
form = form.form
# check if any form contains a FileField, if yes, we need a
# file_storage added to the formwizard (by subclassing).
for field in form.base_fields.itervalues():
if (isinstance(field, forms.FileField) and
not hasattr(cls, 'file_storage')):
raise NoFileStorageConfigured
# build the kwargs for the formwizard instances
kwargs['form_list'] = init_form_list
return kwargs | [
"def",
"get_initkwargs",
"(",
"cls",
",",
"form_list",
",",
"initial_dict",
"=",
"None",
",",
"instance_dict",
"=",
"None",
",",
"condition_dict",
"=",
"None",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"kwargs",
".",
"update",
"(",
"{",
"'initial_dict'",
":",
"initial_dict",
"or",
"{",
"}",
",",
"'instance_dict'",
":",
"instance_dict",
"or",
"{",
"}",
",",
"'condition_dict'",
":",
"condition_dict",
"or",
"{",
"}",
",",
"}",
")",
"init_form_list",
"=",
"SortedDict",
"(",
")",
"assert",
"len",
"(",
"form_list",
")",
">",
"0",
",",
"'at least one form is needed'",
"for",
"i",
",",
"form",
"in",
"enumerate",
"(",
"form_list",
")",
":",
"if",
"isinstance",
"(",
"form",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"init_form_list",
"[",
"unicode",
"(",
"form",
"[",
"0",
"]",
")",
"]",
"=",
"form",
"[",
"1",
"]",
"else",
":",
"init_form_list",
"[",
"unicode",
"(",
"i",
")",
"]",
"=",
"form",
"for",
"form",
"in",
"init_form_list",
".",
"itervalues",
"(",
")",
":",
"if",
"issubclass",
"(",
"form",
",",
"formsets",
".",
"BaseFormSet",
")",
":",
"form",
"=",
"form",
".",
"form",
"for",
"field",
"in",
"form",
".",
"base_fields",
".",
"itervalues",
"(",
")",
":",
"if",
"(",
"isinstance",
"(",
"field",
",",
"forms",
".",
"FileField",
")",
"and",
"not",
"hasattr",
"(",
"cls",
",",
"'file_storage'",
")",
")",
":",
"raise",
"NoFileStorageConfigured",
"kwargs",
"[",
"'form_list'",
"]",
"=",
"init_form_list",
"return",
"kwargs"
] | Creates a dict with all needed parameters for the form wizard instances.
* `form_list` - is a list of forms. The list entries can be single form
classes or tuples of (`step_name`, `form_class`). If you pass a list
of forms, the formwizard will convert the class list to
(`zero_based_counter`, `form_class`). This is needed to access the
form for a specific step.
* `initial_dict` - contains a dictionary of initial data dictionaries.
The key should be equal to the `step_name` in the `form_list` (or
the str of the zero based counter - if no step_names added in the
`form_list`)
* `instance_dict` - contains a dictionary of instance objects. This list
is only used when `ModelForm`s are used. The key should be equal to
the `step_name` in the `form_list`. Same rules as for `initial_dict`
apply.
* `condition_dict` - contains a dictionary of boolean values or
callables. If the value of for a specific `step_name` is callable it
will be called with the formwizard instance as the only argument.
If the return value is true, the step's form will be used. | [
"Creates",
"a",
"dict",
"with",
"all",
"needed",
"parameters",
"for",
"the",
"form",
"wizard",
"instances",
"."
] | 7b35165f0340aae4e8302d5b05b0cb443f6c9904 | https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L113-L170 | train |
stephrdev/django-formwizard | formwizard/views.py | WizardView.dispatch | def dispatch(self, request, *args, **kwargs):
"""
This method gets called by the routing engine. The first argument is
`request` which contains a `HttpRequest` instance.
The request is stored in `self.request` for later use. The storage
instance is stored in `self.storage`.
After processing the request using the `dispatch` method, the
response gets updated by the storage engine (for example add cookies).
"""
# add the storage engine to the current formwizard instance
self.wizard_name = self.get_wizard_name()
self.prefix = self.get_prefix()
self.storage = get_storage(self.storage_name, self.prefix, request,
getattr(self, 'file_storage', None))
self.steps = StepsHelper(self)
response = super(WizardView, self).dispatch(request, *args, **kwargs)
# update the response (e.g. adding cookies)
self.storage.update_response(response)
return response | python | def dispatch(self, request, *args, **kwargs):
"""
This method gets called by the routing engine. The first argument is
`request` which contains a `HttpRequest` instance.
The request is stored in `self.request` for later use. The storage
instance is stored in `self.storage`.
After processing the request using the `dispatch` method, the
response gets updated by the storage engine (for example add cookies).
"""
# add the storage engine to the current formwizard instance
self.wizard_name = self.get_wizard_name()
self.prefix = self.get_prefix()
self.storage = get_storage(self.storage_name, self.prefix, request,
getattr(self, 'file_storage', None))
self.steps = StepsHelper(self)
response = super(WizardView, self).dispatch(request, *args, **kwargs)
# update the response (e.g. adding cookies)
self.storage.update_response(response)
return response | [
"def",
"dispatch",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"self",
".",
"wizard_name",
"=",
"self",
".",
"get_wizard_name",
"(",
")",
"self",
".",
"prefix",
"=",
"self",
".",
"get_prefix",
"(",
")",
"self",
".",
"storage",
"=",
"get_storage",
"(",
"self",
".",
"storage_name",
",",
"self",
".",
"prefix",
",",
"request",
",",
"getattr",
"(",
"self",
",",
"'file_storage'",
",",
"None",
")",
")",
"self",
".",
"steps",
"=",
"StepsHelper",
"(",
"self",
")",
"response",
"=",
"super",
"(",
"WizardView",
",",
"self",
")",
".",
"dispatch",
"(",
"request",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
"self",
".",
"storage",
".",
"update_response",
"(",
"response",
")",
"return",
"response"
] | This method gets called by the routing engine. The first argument is
`request` which contains a `HttpRequest` instance.
The request is stored in `self.request` for later use. The storage
instance is stored in `self.storage`.
After processing the request using the `dispatch` method, the
response gets updated by the storage engine (for example add cookies). | [
"This",
"method",
"gets",
"called",
"by",
"the",
"routing",
"engine",
".",
"The",
"first",
"argument",
"is",
"request",
"which",
"contains",
"a",
"HttpRequest",
"instance",
".",
"The",
"request",
"is",
"stored",
"in",
"self",
".",
"request",
"for",
"later",
"use",
".",
"The",
"storage",
"instance",
"is",
"stored",
"in",
"self",
".",
"storage",
"."
] | 7b35165f0340aae4e8302d5b05b0cb443f6c9904 | https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L202-L222 | train |
stephrdev/django-formwizard | formwizard/views.py | WizardView.get | def get(self, request, *args, **kwargs):
"""
This method handles GET requests.
If a GET request reaches this point, the wizard assumes that the user
just starts at the first step or wants to restart the process.
The data of the wizard will be resetted before rendering the first step.
"""
self.storage.reset()
# reset the current step to the first step.
self.storage.current_step = self.steps.first
return self.render(self.get_form()) | python | def get(self, request, *args, **kwargs):
"""
This method handles GET requests.
If a GET request reaches this point, the wizard assumes that the user
just starts at the first step or wants to restart the process.
The data of the wizard will be resetted before rendering the first step.
"""
self.storage.reset()
# reset the current step to the first step.
self.storage.current_step = self.steps.first
return self.render(self.get_form()) | [
"def",
"get",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"self",
".",
"storage",
".",
"reset",
"(",
")",
"self",
".",
"storage",
".",
"current_step",
"=",
"self",
".",
"steps",
".",
"first",
"return",
"self",
".",
"render",
"(",
"self",
".",
"get_form",
"(",
")",
")"
] | This method handles GET requests.
If a GET request reaches this point, the wizard assumes that the user
just starts at the first step or wants to restart the process.
The data of the wizard will be resetted before rendering the first step. | [
"This",
"method",
"handles",
"GET",
"requests",
"."
] | 7b35165f0340aae4e8302d5b05b0cb443f6c9904 | https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L224-L236 | train |
stephrdev/django-formwizard | formwizard/views.py | WizardView.post | def post(self, *args, **kwargs):
"""
This method handles POST requests.
The wizard will render either the current step (if form validation
wasn't successful), the next step (if the current step was stored
successful) or the done view (if no more steps are available)
"""
# Look for a wizard_prev_step element in the posted data which
# contains a valid step name. If one was found, render the requested
# form. (This makes stepping back a lot easier).
wizard_prev_step = self.request.POST.get('wizard_prev_step', None)
if wizard_prev_step and wizard_prev_step in self.get_form_list():
self.storage.current_step = wizard_prev_step
form = self.get_form(
data=self.storage.get_step_data(self.steps.current),
files=self.storage.get_step_files(self.steps.current))
return self.render(form)
# Check if form was refreshed
management_form = ManagementForm(self.request.POST, prefix=self.prefix)
if not management_form.is_valid():
raise ValidationError(
'ManagementForm data is missing or has been tampered.')
form_current_step = management_form.cleaned_data['current_step']
if (form_current_step != self.steps.current and
self.storage.current_step is not None):
# form refreshed, change current step
self.storage.current_step = form_current_step
# get the form for the current step
form = self.get_form(data=self.request.POST, files=self.request.FILES)
# and try to validate
if form.is_valid():
# if the form is valid, store the cleaned data and files.
self.storage.set_step_data(self.steps.current, self.process_step(form))
self.storage.set_step_files(self.steps.current, self.process_step_files(form))
# check if the current step is the last step
if self.steps.current == self.steps.last:
# no more steps, render done view
return self.render_done(form, **kwargs)
else:
# proceed to the next step
return self.render_next_step(form)
return self.render(form) | python | def post(self, *args, **kwargs):
"""
This method handles POST requests.
The wizard will render either the current step (if form validation
wasn't successful), the next step (if the current step was stored
successful) or the done view (if no more steps are available)
"""
# Look for a wizard_prev_step element in the posted data which
# contains a valid step name. If one was found, render the requested
# form. (This makes stepping back a lot easier).
wizard_prev_step = self.request.POST.get('wizard_prev_step', None)
if wizard_prev_step and wizard_prev_step in self.get_form_list():
self.storage.current_step = wizard_prev_step
form = self.get_form(
data=self.storage.get_step_data(self.steps.current),
files=self.storage.get_step_files(self.steps.current))
return self.render(form)
# Check if form was refreshed
management_form = ManagementForm(self.request.POST, prefix=self.prefix)
if not management_form.is_valid():
raise ValidationError(
'ManagementForm data is missing or has been tampered.')
form_current_step = management_form.cleaned_data['current_step']
if (form_current_step != self.steps.current and
self.storage.current_step is not None):
# form refreshed, change current step
self.storage.current_step = form_current_step
# get the form for the current step
form = self.get_form(data=self.request.POST, files=self.request.FILES)
# and try to validate
if form.is_valid():
# if the form is valid, store the cleaned data and files.
self.storage.set_step_data(self.steps.current, self.process_step(form))
self.storage.set_step_files(self.steps.current, self.process_step_files(form))
# check if the current step is the last step
if self.steps.current == self.steps.last:
# no more steps, render done view
return self.render_done(form, **kwargs)
else:
# proceed to the next step
return self.render_next_step(form)
return self.render(form) | [
"def",
"post",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"wizard_prev_step",
"=",
"self",
".",
"request",
".",
"POST",
".",
"get",
"(",
"'wizard_prev_step'",
",",
"None",
")",
"if",
"wizard_prev_step",
"and",
"wizard_prev_step",
"in",
"self",
".",
"get_form_list",
"(",
")",
":",
"self",
".",
"storage",
".",
"current_step",
"=",
"wizard_prev_step",
"form",
"=",
"self",
".",
"get_form",
"(",
"data",
"=",
"self",
".",
"storage",
".",
"get_step_data",
"(",
"self",
".",
"steps",
".",
"current",
")",
",",
"files",
"=",
"self",
".",
"storage",
".",
"get_step_files",
"(",
"self",
".",
"steps",
".",
"current",
")",
")",
"return",
"self",
".",
"render",
"(",
"form",
")",
"management_form",
"=",
"ManagementForm",
"(",
"self",
".",
"request",
".",
"POST",
",",
"prefix",
"=",
"self",
".",
"prefix",
")",
"if",
"not",
"management_form",
".",
"is_valid",
"(",
")",
":",
"raise",
"ValidationError",
"(",
"'ManagementForm data is missing or has been tampered.'",
")",
"form_current_step",
"=",
"management_form",
".",
"cleaned_data",
"[",
"'current_step'",
"]",
"if",
"(",
"form_current_step",
"!=",
"self",
".",
"steps",
".",
"current",
"and",
"self",
".",
"storage",
".",
"current_step",
"is",
"not",
"None",
")",
":",
"self",
".",
"storage",
".",
"current_step",
"=",
"form_current_step",
"form",
"=",
"self",
".",
"get_form",
"(",
"data",
"=",
"self",
".",
"request",
".",
"POST",
",",
"files",
"=",
"self",
".",
"request",
".",
"FILES",
")",
"if",
"form",
".",
"is_valid",
"(",
")",
":",
"self",
".",
"storage",
".",
"set_step_data",
"(",
"self",
".",
"steps",
".",
"current",
",",
"self",
".",
"process_step",
"(",
"form",
")",
")",
"self",
".",
"storage",
".",
"set_step_files",
"(",
"self",
".",
"steps",
".",
"current",
",",
"self",
".",
"process_step_files",
"(",
"form",
")",
")",
"if",
"self",
".",
"steps",
".",
"current",
"==",
"self",
".",
"steps",
".",
"last",
":",
"return",
"self",
".",
"render_done",
"(",
"form",
",",
"**",
"kwargs",
")",
"else",
":",
"return",
"self",
".",
"render_next_step",
"(",
"form",
")",
"return",
"self",
".",
"render",
"(",
"form",
")"
] | This method handles POST requests.
The wizard will render either the current step (if form validation
wasn't successful), the next step (if the current step was stored
successful) or the done view (if no more steps are available) | [
"This",
"method",
"handles",
"POST",
"requests",
"."
] | 7b35165f0340aae4e8302d5b05b0cb443f6c9904 | https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L238-L285 | train |
stephrdev/django-formwizard | formwizard/views.py | WizardView.render_done | def render_done(self, form, **kwargs):
"""
This method gets called when all forms passed. The method should also
re-validate all steps to prevent manipulation. If any form don't
validate, `render_revalidation_failure` should get called.
If everything is fine call `done`.
"""
final_form_list = []
# walk through the form list and try to validate the data again.
for form_key in self.get_form_list():
form_obj = self.get_form(step=form_key,
data=self.storage.get_step_data(form_key),
files=self.storage.get_step_files(form_key))
if not form_obj.is_valid():
return self.render_revalidation_failure(form_key, form_obj, **kwargs)
final_form_list.append(form_obj)
# render the done view and reset the wizard before returning the
# response. This is needed to prevent from rendering done with the
# same data twice.
done_response = self.done(final_form_list, **kwargs)
self.storage.reset()
return done_response | python | def render_done(self, form, **kwargs):
"""
This method gets called when all forms passed. The method should also
re-validate all steps to prevent manipulation. If any form don't
validate, `render_revalidation_failure` should get called.
If everything is fine call `done`.
"""
final_form_list = []
# walk through the form list and try to validate the data again.
for form_key in self.get_form_list():
form_obj = self.get_form(step=form_key,
data=self.storage.get_step_data(form_key),
files=self.storage.get_step_files(form_key))
if not form_obj.is_valid():
return self.render_revalidation_failure(form_key, form_obj, **kwargs)
final_form_list.append(form_obj)
# render the done view and reset the wizard before returning the
# response. This is needed to prevent from rendering done with the
# same data twice.
done_response = self.done(final_form_list, **kwargs)
self.storage.reset()
return done_response | [
"def",
"render_done",
"(",
"self",
",",
"form",
",",
"**",
"kwargs",
")",
":",
"final_form_list",
"=",
"[",
"]",
"for",
"form_key",
"in",
"self",
".",
"get_form_list",
"(",
")",
":",
"form_obj",
"=",
"self",
".",
"get_form",
"(",
"step",
"=",
"form_key",
",",
"data",
"=",
"self",
".",
"storage",
".",
"get_step_data",
"(",
"form_key",
")",
",",
"files",
"=",
"self",
".",
"storage",
".",
"get_step_files",
"(",
"form_key",
")",
")",
"if",
"not",
"form_obj",
".",
"is_valid",
"(",
")",
":",
"return",
"self",
".",
"render_revalidation_failure",
"(",
"form_key",
",",
"form_obj",
",",
"**",
"kwargs",
")",
"final_form_list",
".",
"append",
"(",
"form_obj",
")",
"done_response",
"=",
"self",
".",
"done",
"(",
"final_form_list",
",",
"**",
"kwargs",
")",
"self",
".",
"storage",
".",
"reset",
"(",
")",
"return",
"done_response"
] | This method gets called when all forms passed. The method should also
re-validate all steps to prevent manipulation. If any form don't
validate, `render_revalidation_failure` should get called.
If everything is fine call `done`. | [
"This",
"method",
"gets",
"called",
"when",
"all",
"forms",
"passed",
".",
"The",
"method",
"should",
"also",
"re",
"-",
"validate",
"all",
"steps",
"to",
"prevent",
"manipulation",
".",
"If",
"any",
"form",
"don",
"t",
"validate",
"render_revalidation_failure",
"should",
"get",
"called",
".",
"If",
"everything",
"is",
"fine",
"call",
"done",
"."
] | 7b35165f0340aae4e8302d5b05b0cb443f6c9904 | https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L303-L325 | train |
stephrdev/django-formwizard | formwizard/views.py | WizardView.get_form_prefix | def get_form_prefix(self, step=None, form=None):
"""
Returns the prefix which will be used when calling the actual form for
the given step. `step` contains the step-name, `form` the form which
will be called with the returned prefix.
If no step is given, the form_prefix will determine the current step
automatically.
"""
if step is None:
step = self.steps.current
return str(step) | python | def get_form_prefix(self, step=None, form=None):
"""
Returns the prefix which will be used when calling the actual form for
the given step. `step` contains the step-name, `form` the form which
will be called with the returned prefix.
If no step is given, the form_prefix will determine the current step
automatically.
"""
if step is None:
step = self.steps.current
return str(step) | [
"def",
"get_form_prefix",
"(",
"self",
",",
"step",
"=",
"None",
",",
"form",
"=",
"None",
")",
":",
"if",
"step",
"is",
"None",
":",
"step",
"=",
"self",
".",
"steps",
".",
"current",
"return",
"str",
"(",
"step",
")"
] | Returns the prefix which will be used when calling the actual form for
the given step. `step` contains the step-name, `form` the form which
will be called with the returned prefix.
If no step is given, the form_prefix will determine the current step
automatically. | [
"Returns",
"the",
"prefix",
"which",
"will",
"be",
"used",
"when",
"calling",
"the",
"actual",
"form",
"for",
"the",
"given",
"step",
".",
"step",
"contains",
"the",
"step",
"-",
"name",
"form",
"the",
"form",
"which",
"will",
"be",
"called",
"with",
"the",
"returned",
"prefix",
"."
] | 7b35165f0340aae4e8302d5b05b0cb443f6c9904 | https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L327-L338 | train |
stephrdev/django-formwizard | formwizard/views.py | WizardView.get_form | def get_form(self, step=None, data=None, files=None):
"""
Constructs the form for a given `step`. If no `step` is defined, the
current step will be determined automatically.
The form will be initialized using the `data` argument to prefill the
new form. If needed, instance or queryset (for `ModelForm` or
`ModelFormSet`) will be added too.
"""
if step is None:
step = self.steps.current
# prepare the kwargs for the form instance.
kwargs = self.get_form_kwargs(step)
kwargs.update({
'data': data,
'files': files,
'prefix': self.get_form_prefix(step, self.form_list[step]),
'initial': self.get_form_initial(step),
})
if issubclass(self.form_list[step], forms.ModelForm):
# If the form is based on ModelForm, add instance if available.
kwargs.update({'instance': self.get_form_instance(step)})
elif issubclass(self.form_list[step], forms.models.BaseModelFormSet):
# If the form is based on ModelFormSet, add queryset if available.
kwargs.update({'queryset': self.get_form_instance(step)})
return self.form_list[step](**kwargs) | python | def get_form(self, step=None, data=None, files=None):
"""
Constructs the form for a given `step`. If no `step` is defined, the
current step will be determined automatically.
The form will be initialized using the `data` argument to prefill the
new form. If needed, instance or queryset (for `ModelForm` or
`ModelFormSet`) will be added too.
"""
if step is None:
step = self.steps.current
# prepare the kwargs for the form instance.
kwargs = self.get_form_kwargs(step)
kwargs.update({
'data': data,
'files': files,
'prefix': self.get_form_prefix(step, self.form_list[step]),
'initial': self.get_form_initial(step),
})
if issubclass(self.form_list[step], forms.ModelForm):
# If the form is based on ModelForm, add instance if available.
kwargs.update({'instance': self.get_form_instance(step)})
elif issubclass(self.form_list[step], forms.models.BaseModelFormSet):
# If the form is based on ModelFormSet, add queryset if available.
kwargs.update({'queryset': self.get_form_instance(step)})
return self.form_list[step](**kwargs) | [
"def",
"get_form",
"(",
"self",
",",
"step",
"=",
"None",
",",
"data",
"=",
"None",
",",
"files",
"=",
"None",
")",
":",
"if",
"step",
"is",
"None",
":",
"step",
"=",
"self",
".",
"steps",
".",
"current",
"kwargs",
"=",
"self",
".",
"get_form_kwargs",
"(",
"step",
")",
"kwargs",
".",
"update",
"(",
"{",
"'data'",
":",
"data",
",",
"'files'",
":",
"files",
",",
"'prefix'",
":",
"self",
".",
"get_form_prefix",
"(",
"step",
",",
"self",
".",
"form_list",
"[",
"step",
"]",
")",
",",
"'initial'",
":",
"self",
".",
"get_form_initial",
"(",
"step",
")",
",",
"}",
")",
"if",
"issubclass",
"(",
"self",
".",
"form_list",
"[",
"step",
"]",
",",
"forms",
".",
"ModelForm",
")",
":",
"kwargs",
".",
"update",
"(",
"{",
"'instance'",
":",
"self",
".",
"get_form_instance",
"(",
"step",
")",
"}",
")",
"elif",
"issubclass",
"(",
"self",
".",
"form_list",
"[",
"step",
"]",
",",
"forms",
".",
"models",
".",
"BaseModelFormSet",
")",
":",
"kwargs",
".",
"update",
"(",
"{",
"'queryset'",
":",
"self",
".",
"get_form_instance",
"(",
"step",
")",
"}",
")",
"return",
"self",
".",
"form_list",
"[",
"step",
"]",
"(",
"**",
"kwargs",
")"
] | Constructs the form for a given `step`. If no `step` is defined, the
current step will be determined automatically.
The form will be initialized using the `data` argument to prefill the
new form. If needed, instance or queryset (for `ModelForm` or
`ModelFormSet`) will be added too. | [
"Constructs",
"the",
"form",
"for",
"a",
"given",
"step",
".",
"If",
"no",
"step",
"is",
"defined",
"the",
"current",
"step",
"will",
"be",
"determined",
"automatically",
"."
] | 7b35165f0340aae4e8302d5b05b0cb443f6c9904 | https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L363-L388 | train |
stephrdev/django-formwizard | formwizard/views.py | WizardView.render_revalidation_failure | def render_revalidation_failure(self, step, form, **kwargs):
"""
Gets called when a form doesn't validate when rendering the done
view. By default, it changed the current step to failing forms step
and renders the form.
"""
self.storage.current_step = step
return self.render(form, **kwargs) | python | def render_revalidation_failure(self, step, form, **kwargs):
"""
Gets called when a form doesn't validate when rendering the done
view. By default, it changed the current step to failing forms step
and renders the form.
"""
self.storage.current_step = step
return self.render(form, **kwargs) | [
"def",
"render_revalidation_failure",
"(",
"self",
",",
"step",
",",
"form",
",",
"**",
"kwargs",
")",
":",
"self",
".",
"storage",
".",
"current_step",
"=",
"step",
"return",
"self",
".",
"render",
"(",
"form",
",",
"**",
"kwargs",
")"
] | Gets called when a form doesn't validate when rendering the done
view. By default, it changed the current step to failing forms step
and renders the form. | [
"Gets",
"called",
"when",
"a",
"form",
"doesn",
"t",
"validate",
"when",
"rendering",
"the",
"done",
"view",
".",
"By",
"default",
"it",
"changed",
"the",
"current",
"step",
"to",
"failing",
"forms",
"step",
"and",
"renders",
"the",
"form",
"."
] | 7b35165f0340aae4e8302d5b05b0cb443f6c9904 | https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L404-L411 | train |
stephrdev/django-formwizard | formwizard/views.py | WizardView.get_all_cleaned_data | def get_all_cleaned_data(self):
"""
Returns a merged dictionary of all step cleaned_data dictionaries.
If a step contains a `FormSet`, the key will be prefixed with formset
and contain a list of the formset' cleaned_data dictionaries.
"""
cleaned_data = {}
for form_key in self.get_form_list():
form_obj = self.get_form(
step=form_key,
data=self.storage.get_step_data(form_key),
files=self.storage.get_step_files(form_key)
)
if form_obj.is_valid():
if isinstance(form_obj.cleaned_data, (tuple, list)):
cleaned_data.update({
'formset-%s' % form_key: form_obj.cleaned_data
})
else:
cleaned_data.update(form_obj.cleaned_data)
return cleaned_data | python | def get_all_cleaned_data(self):
"""
Returns a merged dictionary of all step cleaned_data dictionaries.
If a step contains a `FormSet`, the key will be prefixed with formset
and contain a list of the formset' cleaned_data dictionaries.
"""
cleaned_data = {}
for form_key in self.get_form_list():
form_obj = self.get_form(
step=form_key,
data=self.storage.get_step_data(form_key),
files=self.storage.get_step_files(form_key)
)
if form_obj.is_valid():
if isinstance(form_obj.cleaned_data, (tuple, list)):
cleaned_data.update({
'formset-%s' % form_key: form_obj.cleaned_data
})
else:
cleaned_data.update(form_obj.cleaned_data)
return cleaned_data | [
"def",
"get_all_cleaned_data",
"(",
"self",
")",
":",
"cleaned_data",
"=",
"{",
"}",
"for",
"form_key",
"in",
"self",
".",
"get_form_list",
"(",
")",
":",
"form_obj",
"=",
"self",
".",
"get_form",
"(",
"step",
"=",
"form_key",
",",
"data",
"=",
"self",
".",
"storage",
".",
"get_step_data",
"(",
"form_key",
")",
",",
"files",
"=",
"self",
".",
"storage",
".",
"get_step_files",
"(",
"form_key",
")",
")",
"if",
"form_obj",
".",
"is_valid",
"(",
")",
":",
"if",
"isinstance",
"(",
"form_obj",
".",
"cleaned_data",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"cleaned_data",
".",
"update",
"(",
"{",
"'formset-%s'",
"%",
"form_key",
":",
"form_obj",
".",
"cleaned_data",
"}",
")",
"else",
":",
"cleaned_data",
".",
"update",
"(",
"form_obj",
".",
"cleaned_data",
")",
"return",
"cleaned_data"
] | Returns a merged dictionary of all step cleaned_data dictionaries.
If a step contains a `FormSet`, the key will be prefixed with formset
and contain a list of the formset' cleaned_data dictionaries. | [
"Returns",
"a",
"merged",
"dictionary",
"of",
"all",
"step",
"cleaned_data",
"dictionaries",
".",
"If",
"a",
"step",
"contains",
"a",
"FormSet",
"the",
"key",
"will",
"be",
"prefixed",
"with",
"formset",
"and",
"contain",
"a",
"list",
"of",
"the",
"formset",
"cleaned_data",
"dictionaries",
"."
] | 7b35165f0340aae4e8302d5b05b0cb443f6c9904 | https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L427-L447 | train |
stephrdev/django-formwizard | formwizard/views.py | WizardView.get_cleaned_data_for_step | def get_cleaned_data_for_step(self, step):
"""
Returns the cleaned data for a given `step`. Before returning the
cleaned data, the stored values are being revalidated through the
form. If the data doesn't validate, None will be returned.
"""
if step in self.form_list:
form_obj = self.get_form(step=step,
data=self.storage.get_step_data(step),
files=self.storage.get_step_files(step))
if form_obj.is_valid():
return form_obj.cleaned_data
return None | python | def get_cleaned_data_for_step(self, step):
"""
Returns the cleaned data for a given `step`. Before returning the
cleaned data, the stored values are being revalidated through the
form. If the data doesn't validate, None will be returned.
"""
if step in self.form_list:
form_obj = self.get_form(step=step,
data=self.storage.get_step_data(step),
files=self.storage.get_step_files(step))
if form_obj.is_valid():
return form_obj.cleaned_data
return None | [
"def",
"get_cleaned_data_for_step",
"(",
"self",
",",
"step",
")",
":",
"if",
"step",
"in",
"self",
".",
"form_list",
":",
"form_obj",
"=",
"self",
".",
"get_form",
"(",
"step",
"=",
"step",
",",
"data",
"=",
"self",
".",
"storage",
".",
"get_step_data",
"(",
"step",
")",
",",
"files",
"=",
"self",
".",
"storage",
".",
"get_step_files",
"(",
"step",
")",
")",
"if",
"form_obj",
".",
"is_valid",
"(",
")",
":",
"return",
"form_obj",
".",
"cleaned_data",
"return",
"None"
] | Returns the cleaned data for a given `step`. Before returning the
cleaned data, the stored values are being revalidated through the
form. If the data doesn't validate, None will be returned. | [
"Returns",
"the",
"cleaned",
"data",
"for",
"a",
"given",
"step",
".",
"Before",
"returning",
"the",
"cleaned",
"data",
"the",
"stored",
"values",
"are",
"being",
"revalidated",
"through",
"the",
"form",
".",
"If",
"the",
"data",
"doesn",
"t",
"validate",
"None",
"will",
"be",
"returned",
"."
] | 7b35165f0340aae4e8302d5b05b0cb443f6c9904 | https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L449-L461 | train |
stephrdev/django-formwizard | formwizard/views.py | WizardView.get_step_index | def get_step_index(self, step=None):
"""
Returns the index for the given `step` name. If no step is given,
the current step will be used to get the index.
"""
if step is None:
step = self.steps.current
return self.get_form_list().keyOrder.index(step) | python | def get_step_index(self, step=None):
"""
Returns the index for the given `step` name. If no step is given,
the current step will be used to get the index.
"""
if step is None:
step = self.steps.current
return self.get_form_list().keyOrder.index(step) | [
"def",
"get_step_index",
"(",
"self",
",",
"step",
"=",
"None",
")",
":",
"if",
"step",
"is",
"None",
":",
"step",
"=",
"self",
".",
"steps",
".",
"current",
"return",
"self",
".",
"get_form_list",
"(",
")",
".",
"keyOrder",
".",
"index",
"(",
"step",
")"
] | Returns the index for the given `step` name. If no step is given,
the current step will be used to get the index. | [
"Returns",
"the",
"index",
"for",
"the",
"given",
"step",
"name",
".",
"If",
"no",
"step",
"is",
"given",
"the",
"current",
"step",
"will",
"be",
"used",
"to",
"get",
"the",
"index",
"."
] | 7b35165f0340aae4e8302d5b05b0cb443f6c9904 | https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L491-L498 | train |
stephrdev/django-formwizard | formwizard/views.py | WizardView.render | def render(self, form=None, **kwargs):
"""
Returns a ``HttpResponse`` containing a all needed context data.
"""
form = form or self.get_form()
context = self.get_context_data(form, **kwargs)
return self.render_to_response(context) | python | def render(self, form=None, **kwargs):
"""
Returns a ``HttpResponse`` containing a all needed context data.
"""
form = form or self.get_form()
context = self.get_context_data(form, **kwargs)
return self.render_to_response(context) | [
"def",
"render",
"(",
"self",
",",
"form",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"form",
"=",
"form",
"or",
"self",
".",
"get_form",
"(",
")",
"context",
"=",
"self",
".",
"get_context_data",
"(",
"form",
",",
"**",
"kwargs",
")",
"return",
"self",
".",
"render_to_response",
"(",
"context",
")"
] | Returns a ``HttpResponse`` containing a all needed context data. | [
"Returns",
"a",
"HttpResponse",
"containing",
"a",
"all",
"needed",
"context",
"data",
"."
] | 7b35165f0340aae4e8302d5b05b0cb443f6c9904 | https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L533-L539 | train |
stephrdev/django-formwizard | formwizard/views.py | NamedUrlWizardView.get_initkwargs | def get_initkwargs(cls, *args, **kwargs):
"""
We require a url_name to reverse URLs later. Additionally users can
pass a done_step_name to change the URL name of the "done" view.
"""
assert 'url_name' in kwargs, 'URL name is needed to resolve correct wizard URLs'
extra_kwargs = {
'done_step_name': kwargs.pop('done_step_name', 'done'),
'url_name': kwargs.pop('url_name'),
}
initkwargs = super(NamedUrlWizardView, cls).get_initkwargs(*args, **kwargs)
initkwargs.update(extra_kwargs)
assert initkwargs['done_step_name'] not in initkwargs['form_list'], \
'step name "%s" is reserved for "done" view' % initkwargs['done_step_name']
return initkwargs | python | def get_initkwargs(cls, *args, **kwargs):
"""
We require a url_name to reverse URLs later. Additionally users can
pass a done_step_name to change the URL name of the "done" view.
"""
assert 'url_name' in kwargs, 'URL name is needed to resolve correct wizard URLs'
extra_kwargs = {
'done_step_name': kwargs.pop('done_step_name', 'done'),
'url_name': kwargs.pop('url_name'),
}
initkwargs = super(NamedUrlWizardView, cls).get_initkwargs(*args, **kwargs)
initkwargs.update(extra_kwargs)
assert initkwargs['done_step_name'] not in initkwargs['form_list'], \
'step name "%s" is reserved for "done" view' % initkwargs['done_step_name']
return initkwargs | [
"def",
"get_initkwargs",
"(",
"cls",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"assert",
"'url_name'",
"in",
"kwargs",
",",
"'URL name is needed to resolve correct wizard URLs'",
"extra_kwargs",
"=",
"{",
"'done_step_name'",
":",
"kwargs",
".",
"pop",
"(",
"'done_step_name'",
",",
"'done'",
")",
",",
"'url_name'",
":",
"kwargs",
".",
"pop",
"(",
"'url_name'",
")",
",",
"}",
"initkwargs",
"=",
"super",
"(",
"NamedUrlWizardView",
",",
"cls",
")",
".",
"get_initkwargs",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
"initkwargs",
".",
"update",
"(",
"extra_kwargs",
")",
"assert",
"initkwargs",
"[",
"'done_step_name'",
"]",
"not",
"in",
"initkwargs",
"[",
"'form_list'",
"]",
",",
"'step name \"%s\" is reserved for \"done\" view'",
"%",
"initkwargs",
"[",
"'done_step_name'",
"]",
"return",
"initkwargs"
] | We require a url_name to reverse URLs later. Additionally users can
pass a done_step_name to change the URL name of the "done" view. | [
"We",
"require",
"a",
"url_name",
"to",
"reverse",
"URLs",
"later",
".",
"Additionally",
"users",
"can",
"pass",
"a",
"done_step_name",
"to",
"change",
"the",
"URL",
"name",
"of",
"the",
"done",
"view",
"."
] | 7b35165f0340aae4e8302d5b05b0cb443f6c9904 | https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L572-L588 | train |
stephrdev/django-formwizard | formwizard/views.py | NamedUrlWizardView.get | def get(self, *args, **kwargs):
"""
This renders the form or, if needed, does the http redirects.
"""
step_url = kwargs.get('step', None)
if step_url is None:
if 'reset' in self.request.GET:
self.storage.reset()
self.storage.current_step = self.steps.first
if self.request.GET:
query_string = "?%s" % self.request.GET.urlencode()
else:
query_string = ""
next_step_url = reverse(self.url_name, kwargs={
'step': self.steps.current,
}) + query_string
return redirect(next_step_url)
# is the current step the "done" name/view?
elif step_url == self.done_step_name:
last_step = self.steps.last
return self.render_done(self.get_form(step=last_step,
data=self.storage.get_step_data(last_step),
files=self.storage.get_step_files(last_step)
), **kwargs)
# is the url step name not equal to the step in the storage?
# if yes, change the step in the storage (if name exists)
elif step_url == self.steps.current:
# URL step name and storage step name are equal, render!
return self.render(self.get_form(
data=self.storage.current_step_data,
files=self.storage.current_step_data,
), **kwargs)
elif step_url in self.get_form_list():
self.storage.current_step = step_url
return self.render(self.get_form(
data=self.storage.current_step_data,
files=self.storage.current_step_data,
), **kwargs)
# invalid step name, reset to first and redirect.
else:
self.storage.current_step = self.steps.first
return redirect(self.url_name, step=self.steps.first) | python | def get(self, *args, **kwargs):
"""
This renders the form or, if needed, does the http redirects.
"""
step_url = kwargs.get('step', None)
if step_url is None:
if 'reset' in self.request.GET:
self.storage.reset()
self.storage.current_step = self.steps.first
if self.request.GET:
query_string = "?%s" % self.request.GET.urlencode()
else:
query_string = ""
next_step_url = reverse(self.url_name, kwargs={
'step': self.steps.current,
}) + query_string
return redirect(next_step_url)
# is the current step the "done" name/view?
elif step_url == self.done_step_name:
last_step = self.steps.last
return self.render_done(self.get_form(step=last_step,
data=self.storage.get_step_data(last_step),
files=self.storage.get_step_files(last_step)
), **kwargs)
# is the url step name not equal to the step in the storage?
# if yes, change the step in the storage (if name exists)
elif step_url == self.steps.current:
# URL step name and storage step name are equal, render!
return self.render(self.get_form(
data=self.storage.current_step_data,
files=self.storage.current_step_data,
), **kwargs)
elif step_url in self.get_form_list():
self.storage.current_step = step_url
return self.render(self.get_form(
data=self.storage.current_step_data,
files=self.storage.current_step_data,
), **kwargs)
# invalid step name, reset to first and redirect.
else:
self.storage.current_step = self.steps.first
return redirect(self.url_name, step=self.steps.first) | [
"def",
"get",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"step_url",
"=",
"kwargs",
".",
"get",
"(",
"'step'",
",",
"None",
")",
"if",
"step_url",
"is",
"None",
":",
"if",
"'reset'",
"in",
"self",
".",
"request",
".",
"GET",
":",
"self",
".",
"storage",
".",
"reset",
"(",
")",
"self",
".",
"storage",
".",
"current_step",
"=",
"self",
".",
"steps",
".",
"first",
"if",
"self",
".",
"request",
".",
"GET",
":",
"query_string",
"=",
"\"?%s\"",
"%",
"self",
".",
"request",
".",
"GET",
".",
"urlencode",
"(",
")",
"else",
":",
"query_string",
"=",
"\"\"",
"next_step_url",
"=",
"reverse",
"(",
"self",
".",
"url_name",
",",
"kwargs",
"=",
"{",
"'step'",
":",
"self",
".",
"steps",
".",
"current",
",",
"}",
")",
"+",
"query_string",
"return",
"redirect",
"(",
"next_step_url",
")",
"elif",
"step_url",
"==",
"self",
".",
"done_step_name",
":",
"last_step",
"=",
"self",
".",
"steps",
".",
"last",
"return",
"self",
".",
"render_done",
"(",
"self",
".",
"get_form",
"(",
"step",
"=",
"last_step",
",",
"data",
"=",
"self",
".",
"storage",
".",
"get_step_data",
"(",
"last_step",
")",
",",
"files",
"=",
"self",
".",
"storage",
".",
"get_step_files",
"(",
"last_step",
")",
")",
",",
"**",
"kwargs",
")",
"elif",
"step_url",
"==",
"self",
".",
"steps",
".",
"current",
":",
"return",
"self",
".",
"render",
"(",
"self",
".",
"get_form",
"(",
"data",
"=",
"self",
".",
"storage",
".",
"current_step_data",
",",
"files",
"=",
"self",
".",
"storage",
".",
"current_step_data",
",",
")",
",",
"**",
"kwargs",
")",
"elif",
"step_url",
"in",
"self",
".",
"get_form_list",
"(",
")",
":",
"self",
".",
"storage",
".",
"current_step",
"=",
"step_url",
"return",
"self",
".",
"render",
"(",
"self",
".",
"get_form",
"(",
"data",
"=",
"self",
".",
"storage",
".",
"current_step_data",
",",
"files",
"=",
"self",
".",
"storage",
".",
"current_step_data",
",",
")",
",",
"**",
"kwargs",
")",
"else",
":",
"self",
".",
"storage",
".",
"current_step",
"=",
"self",
".",
"steps",
".",
"first",
"return",
"redirect",
"(",
"self",
".",
"url_name",
",",
"step",
"=",
"self",
".",
"steps",
".",
"first",
")"
] | This renders the form or, if needed, does the http redirects. | [
"This",
"renders",
"the",
"form",
"or",
"if",
"needed",
"does",
"the",
"http",
"redirects",
"."
] | 7b35165f0340aae4e8302d5b05b0cb443f6c9904 | https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L590-L635 | train |
stephrdev/django-formwizard | formwizard/views.py | NamedUrlWizardView.post | def post(self, *args, **kwargs):
"""
Do a redirect if user presses the prev. step button. The rest of this
is super'd from FormWizard.
"""
prev_step = self.request.POST.get('wizard_prev_step', None)
if prev_step and prev_step in self.get_form_list():
self.storage.current_step = prev_step
return redirect(self.url_name, step=prev_step)
return super(NamedUrlWizardView, self).post(*args, **kwargs) | python | def post(self, *args, **kwargs):
"""
Do a redirect if user presses the prev. step button. The rest of this
is super'd from FormWizard.
"""
prev_step = self.request.POST.get('wizard_prev_step', None)
if prev_step and prev_step in self.get_form_list():
self.storage.current_step = prev_step
return redirect(self.url_name, step=prev_step)
return super(NamedUrlWizardView, self).post(*args, **kwargs) | [
"def",
"post",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"prev_step",
"=",
"self",
".",
"request",
".",
"POST",
".",
"get",
"(",
"'wizard_prev_step'",
",",
"None",
")",
"if",
"prev_step",
"and",
"prev_step",
"in",
"self",
".",
"get_form_list",
"(",
")",
":",
"self",
".",
"storage",
".",
"current_step",
"=",
"prev_step",
"return",
"redirect",
"(",
"self",
".",
"url_name",
",",
"step",
"=",
"prev_step",
")",
"return",
"super",
"(",
"NamedUrlWizardView",
",",
"self",
")",
".",
"post",
"(",
"*",
"args",
",",
"**",
"kwargs",
")"
] | Do a redirect if user presses the prev. step button. The rest of this
is super'd from FormWizard. | [
"Do",
"a",
"redirect",
"if",
"user",
"presses",
"the",
"prev",
".",
"step",
"button",
".",
"The",
"rest",
"of",
"this",
"is",
"super",
"d",
"from",
"FormWizard",
"."
] | 7b35165f0340aae4e8302d5b05b0cb443f6c9904 | https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L637-L646 | train |
stephrdev/django-formwizard | formwizard/views.py | NamedUrlWizardView.render_next_step | def render_next_step(self, form, **kwargs):
"""
When using the NamedUrlFormWizard, we have to redirect to update the
browser's URL to match the shown step.
"""
next_step = self.get_next_step()
self.storage.current_step = next_step
return redirect(self.url_name, step=next_step) | python | def render_next_step(self, form, **kwargs):
"""
When using the NamedUrlFormWizard, we have to redirect to update the
browser's URL to match the shown step.
"""
next_step = self.get_next_step()
self.storage.current_step = next_step
return redirect(self.url_name, step=next_step) | [
"def",
"render_next_step",
"(",
"self",
",",
"form",
",",
"**",
"kwargs",
")",
":",
"next_step",
"=",
"self",
".",
"get_next_step",
"(",
")",
"self",
".",
"storage",
".",
"current_step",
"=",
"next_step",
"return",
"redirect",
"(",
"self",
".",
"url_name",
",",
"step",
"=",
"next_step",
")"
] | When using the NamedUrlFormWizard, we have to redirect to update the
browser's URL to match the shown step. | [
"When",
"using",
"the",
"NamedUrlFormWizard",
"we",
"have",
"to",
"redirect",
"to",
"update",
"the",
"browser",
"s",
"URL",
"to",
"match",
"the",
"shown",
"step",
"."
] | 7b35165f0340aae4e8302d5b05b0cb443f6c9904 | https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L648-L655 | train |
stephrdev/django-formwizard | formwizard/views.py | NamedUrlWizardView.render_revalidation_failure | def render_revalidation_failure(self, failed_step, form, **kwargs):
"""
When a step fails, we have to redirect the user to the first failing
step.
"""
self.storage.current_step = failed_step
return redirect(self.url_name, step=failed_step) | python | def render_revalidation_failure(self, failed_step, form, **kwargs):
"""
When a step fails, we have to redirect the user to the first failing
step.
"""
self.storage.current_step = failed_step
return redirect(self.url_name, step=failed_step) | [
"def",
"render_revalidation_failure",
"(",
"self",
",",
"failed_step",
",",
"form",
",",
"**",
"kwargs",
")",
":",
"self",
".",
"storage",
".",
"current_step",
"=",
"failed_step",
"return",
"redirect",
"(",
"self",
".",
"url_name",
",",
"step",
"=",
"failed_step",
")"
] | When a step fails, we have to redirect the user to the first failing
step. | [
"When",
"a",
"step",
"fails",
"we",
"have",
"to",
"redirect",
"the",
"user",
"to",
"the",
"first",
"failing",
"step",
"."
] | 7b35165f0340aae4e8302d5b05b0cb443f6c9904 | https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L657-L663 | train |
budacom/trading-bots | trading_bots/core/storage.py | get_store | def get_store(logger: Logger=None) -> 'Store':
"""Get and configure the storage backend"""
from trading_bots.conf import settings
store_settings = settings.storage
store = store_settings.get('name', 'json')
if store == 'json':
store = 'trading_bots.core.storage.JSONStore'
elif store == 'redis':
store = 'trading_bots.core.storage.RedisStore'
store_cls = load_class_by_name(store)
kwargs = store_cls.configure(store_settings)
return store_cls(logger=logger, **kwargs) | python | def get_store(logger: Logger=None) -> 'Store':
"""Get and configure the storage backend"""
from trading_bots.conf import settings
store_settings = settings.storage
store = store_settings.get('name', 'json')
if store == 'json':
store = 'trading_bots.core.storage.JSONStore'
elif store == 'redis':
store = 'trading_bots.core.storage.RedisStore'
store_cls = load_class_by_name(store)
kwargs = store_cls.configure(store_settings)
return store_cls(logger=logger, **kwargs) | [
"def",
"get_store",
"(",
"logger",
":",
"Logger",
"=",
"None",
")",
"->",
"'Store'",
":",
"from",
"trading_bots",
".",
"conf",
"import",
"settings",
"store_settings",
"=",
"settings",
".",
"storage",
"store",
"=",
"store_settings",
".",
"get",
"(",
"'name'",
",",
"'json'",
")",
"if",
"store",
"==",
"'json'",
":",
"store",
"=",
"'trading_bots.core.storage.JSONStore'",
"elif",
"store",
"==",
"'redis'",
":",
"store",
"=",
"'trading_bots.core.storage.RedisStore'",
"store_cls",
"=",
"load_class_by_name",
"(",
"store",
")",
"kwargs",
"=",
"store_cls",
".",
"configure",
"(",
"store_settings",
")",
"return",
"store_cls",
"(",
"logger",
"=",
"logger",
",",
"**",
"kwargs",
")"
] | Get and configure the storage backend | [
"Get",
"and",
"configure",
"the",
"storage",
"backend"
] | 8cb68bb8d0b5f822108db1cc5dae336e3d3c3452 | https://github.com/budacom/trading-bots/blob/8cb68bb8d0b5f822108db1cc5dae336e3d3c3452/trading_bots/core/storage.py#L15-L26 | train |
coyo8/parinx | parinx/parser.py | parse_request_headers | def parse_request_headers(headers):
"""
convert headers in human readable format
:param headers:
:return:
"""
request_header_keys = set(headers.keys(lower=True))
request_meta_keys = set(XHEADERS_TO_ARGS_DICT.keys())
data_header_keys = request_header_keys.intersection(request_meta_keys)
return dict(([XHEADERS_TO_ARGS_DICT[key],
headers.get(key, None)] for key in data_header_keys)) | python | def parse_request_headers(headers):
"""
convert headers in human readable format
:param headers:
:return:
"""
request_header_keys = set(headers.keys(lower=True))
request_meta_keys = set(XHEADERS_TO_ARGS_DICT.keys())
data_header_keys = request_header_keys.intersection(request_meta_keys)
return dict(([XHEADERS_TO_ARGS_DICT[key],
headers.get(key, None)] for key in data_header_keys)) | [
"def",
"parse_request_headers",
"(",
"headers",
")",
":",
"request_header_keys",
"=",
"set",
"(",
"headers",
".",
"keys",
"(",
"lower",
"=",
"True",
")",
")",
"request_meta_keys",
"=",
"set",
"(",
"XHEADERS_TO_ARGS_DICT",
".",
"keys",
"(",
")",
")",
"data_header_keys",
"=",
"request_header_keys",
".",
"intersection",
"(",
"request_meta_keys",
")",
"return",
"dict",
"(",
"(",
"[",
"XHEADERS_TO_ARGS_DICT",
"[",
"key",
"]",
",",
"headers",
".",
"get",
"(",
"key",
",",
"None",
")",
"]",
"for",
"key",
"in",
"data_header_keys",
")",
")"
] | convert headers in human readable format
:param headers:
:return: | [
"convert",
"headers",
"in",
"human",
"readable",
"format"
] | 6493798ceba8089345d970f71be4a896eb6b081d | https://github.com/coyo8/parinx/blob/6493798ceba8089345d970f71be4a896eb6b081d/parinx/parser.py#L48-L59 | train |
coyo8/parinx | parinx/parser.py | split_docstring | def split_docstring(docstring):
"""
Separates the method's description and paramter's
:return: Return description string and list of fields strings
"""
docstring_list = [line.strip() for line in docstring.splitlines()]
description_list = list(
takewhile(lambda line: not (line.startswith(':') or
line.startswith('@inherit')), docstring_list))
description = ' '.join(description_list).strip()
first_field_line_number = len(description_list)
fields = []
if first_field_line_number >= len(docstring_list):
return description, fields # only description, without any field
last_field_lines = [docstring_list[first_field_line_number]]
for line in docstring_list[first_field_line_number + 1:]:
if line.strip().startswith(':') or line.strip().startswith('@inherit'):
fields.append(' '.join(last_field_lines))
last_field_lines = [line]
else:
last_field_lines.append(line)
fields.append(' '.join(last_field_lines))
return description, fields | python | def split_docstring(docstring):
"""
Separates the method's description and paramter's
:return: Return description string and list of fields strings
"""
docstring_list = [line.strip() for line in docstring.splitlines()]
description_list = list(
takewhile(lambda line: not (line.startswith(':') or
line.startswith('@inherit')), docstring_list))
description = ' '.join(description_list).strip()
first_field_line_number = len(description_list)
fields = []
if first_field_line_number >= len(docstring_list):
return description, fields # only description, without any field
last_field_lines = [docstring_list[first_field_line_number]]
for line in docstring_list[first_field_line_number + 1:]:
if line.strip().startswith(':') or line.strip().startswith('@inherit'):
fields.append(' '.join(last_field_lines))
last_field_lines = [line]
else:
last_field_lines.append(line)
fields.append(' '.join(last_field_lines))
return description, fields | [
"def",
"split_docstring",
"(",
"docstring",
")",
":",
"docstring_list",
"=",
"[",
"line",
".",
"strip",
"(",
")",
"for",
"line",
"in",
"docstring",
".",
"splitlines",
"(",
")",
"]",
"description_list",
"=",
"list",
"(",
"takewhile",
"(",
"lambda",
"line",
":",
"not",
"(",
"line",
".",
"startswith",
"(",
"':'",
")",
"or",
"line",
".",
"startswith",
"(",
"'@inherit'",
")",
")",
",",
"docstring_list",
")",
")",
"description",
"=",
"' '",
".",
"join",
"(",
"description_list",
")",
".",
"strip",
"(",
")",
"first_field_line_number",
"=",
"len",
"(",
"description_list",
")",
"fields",
"=",
"[",
"]",
"if",
"first_field_line_number",
">=",
"len",
"(",
"docstring_list",
")",
":",
"return",
"description",
",",
"fields",
"last_field_lines",
"=",
"[",
"docstring_list",
"[",
"first_field_line_number",
"]",
"]",
"for",
"line",
"in",
"docstring_list",
"[",
"first_field_line_number",
"+",
"1",
":",
"]",
":",
"if",
"line",
".",
"strip",
"(",
")",
".",
"startswith",
"(",
"':'",
")",
"or",
"line",
".",
"strip",
"(",
")",
".",
"startswith",
"(",
"'@inherit'",
")",
":",
"fields",
".",
"append",
"(",
"' '",
".",
"join",
"(",
"last_field_lines",
")",
")",
"last_field_lines",
"=",
"[",
"line",
"]",
"else",
":",
"last_field_lines",
".",
"append",
"(",
"line",
")",
"fields",
".",
"append",
"(",
"' '",
".",
"join",
"(",
"last_field_lines",
")",
")",
"return",
"description",
",",
"fields"
] | Separates the method's description and paramter's
:return: Return description string and list of fields strings | [
"Separates",
"the",
"method",
"s",
"description",
"and",
"paramter",
"s"
] | 6493798ceba8089345d970f71be4a896eb6b081d | https://github.com/coyo8/parinx/blob/6493798ceba8089345d970f71be4a896eb6b081d/parinx/parser.py#L125-L151 | train |
coyo8/parinx | parinx/parser.py | get_method_docstring | def get_method_docstring(cls, method_name):
"""
return method docstring
if method docstring is empty we get docstring from parent
:param method:
:type method:
:return:
:rtype:
"""
method = getattr(cls, method_name, None)
if method is None:
return
docstrign = inspect.getdoc(method)
if docstrign is None:
for base in cls.__bases__:
docstrign = get_method_docstring(base, method_name)
if docstrign:
return docstrign
else:
return None
return docstrign | python | def get_method_docstring(cls, method_name):
"""
return method docstring
if method docstring is empty we get docstring from parent
:param method:
:type method:
:return:
:rtype:
"""
method = getattr(cls, method_name, None)
if method is None:
return
docstrign = inspect.getdoc(method)
if docstrign is None:
for base in cls.__bases__:
docstrign = get_method_docstring(base, method_name)
if docstrign:
return docstrign
else:
return None
return docstrign | [
"def",
"get_method_docstring",
"(",
"cls",
",",
"method_name",
")",
":",
"method",
"=",
"getattr",
"(",
"cls",
",",
"method_name",
",",
"None",
")",
"if",
"method",
"is",
"None",
":",
"return",
"docstrign",
"=",
"inspect",
".",
"getdoc",
"(",
"method",
")",
"if",
"docstrign",
"is",
"None",
":",
"for",
"base",
"in",
"cls",
".",
"__bases__",
":",
"docstrign",
"=",
"get_method_docstring",
"(",
"base",
",",
"method_name",
")",
"if",
"docstrign",
":",
"return",
"docstrign",
"else",
":",
"return",
"None",
"return",
"docstrign"
] | return method docstring
if method docstring is empty we get docstring from parent
:param method:
:type method:
:return:
:rtype: | [
"return",
"method",
"docstring",
"if",
"method",
"docstring",
"is",
"empty",
"we",
"get",
"docstring",
"from",
"parent"
] | 6493798ceba8089345d970f71be4a896eb6b081d | https://github.com/coyo8/parinx/blob/6493798ceba8089345d970f71be4a896eb6b081d/parinx/parser.py#L154-L176 | train |
mjj4791/python-buienradar | buienradar/buienradar.py | condition_from_code | def condition_from_code(condcode):
"""Get the condition name from the condition code."""
if condcode in __BRCONDITIONS:
cond_data = __BRCONDITIONS[condcode]
return {CONDCODE: condcode,
CONDITION: cond_data[0],
DETAILED: cond_data[1],
EXACT: cond_data[2],
EXACTNL: cond_data[3],
}
return None | python | def condition_from_code(condcode):
"""Get the condition name from the condition code."""
if condcode in __BRCONDITIONS:
cond_data = __BRCONDITIONS[condcode]
return {CONDCODE: condcode,
CONDITION: cond_data[0],
DETAILED: cond_data[1],
EXACT: cond_data[2],
EXACTNL: cond_data[3],
}
return None | [
"def",
"condition_from_code",
"(",
"condcode",
")",
":",
"if",
"condcode",
"in",
"__BRCONDITIONS",
":",
"cond_data",
"=",
"__BRCONDITIONS",
"[",
"condcode",
"]",
"return",
"{",
"CONDCODE",
":",
"condcode",
",",
"CONDITION",
":",
"cond_data",
"[",
"0",
"]",
",",
"DETAILED",
":",
"cond_data",
"[",
"1",
"]",
",",
"EXACT",
":",
"cond_data",
"[",
"2",
"]",
",",
"EXACTNL",
":",
"cond_data",
"[",
"3",
"]",
",",
"}",
"return",
"None"
] | Get the condition name from the condition code. | [
"Get",
"the",
"condition",
"name",
"from",
"the",
"condition",
"code",
"."
] | a70436f54e007ce921d5210cb296cf3e4adf9d09 | https://github.com/mjj4791/python-buienradar/blob/a70436f54e007ce921d5210cb296cf3e4adf9d09/buienradar/buienradar.py#L41-L52 | train |
HEPData/hepdata-validator | hepdata_validator/submission_file_validator.py | SubmissionFileValidator.validate | def validate(self, **kwargs):
"""
Validates a submission file
:param file_path: path to file to be loaded.
:param data: pre loaded YAML object (optional).
:return: Bool to indicate the validity of the file.
"""
try:
submission_file_schema = json.load(open(self.default_schema_file, 'r'))
additional_file_section_schema = json.load(open(self.additional_info_schema, 'r'))
# even though we are using the yaml package to load,
# it supports JSON and YAML
data = kwargs.pop("data", None)
file_path = kwargs.pop("file_path", None)
if file_path is None:
raise LookupError("file_path argument must be supplied")
if data is None:
data = yaml.load_all(open(file_path, 'r'), Loader=Loader)
for data_item_index, data_item in enumerate(data):
if data_item is None:
continue
try:
if not data_item_index and 'data_file' not in data_item:
validate(data_item, additional_file_section_schema)
else:
validate(data_item, submission_file_schema)
except ValidationError as ve:
self.add_validation_message(
ValidationMessage(file=file_path,
message=ve.message + ' in ' + str(ve.instance)))
if self.has_errors(file_path):
return False
else:
return True
except ScannerError as se: # pragma: no cover
self.add_validation_message( # pragma: no cover
ValidationMessage(file=file_path, message=
'There was a problem parsing the file. '
'This can be because you forgot spaces '
'after colons in your YAML file for instance. '
'Diagnostic information follows.\n' + str(se)))
return False
except Exception as e:
self.add_validation_message(ValidationMessage(file=file_path, message=e.__str__()))
return False | python | def validate(self, **kwargs):
"""
Validates a submission file
:param file_path: path to file to be loaded.
:param data: pre loaded YAML object (optional).
:return: Bool to indicate the validity of the file.
"""
try:
submission_file_schema = json.load(open(self.default_schema_file, 'r'))
additional_file_section_schema = json.load(open(self.additional_info_schema, 'r'))
# even though we are using the yaml package to load,
# it supports JSON and YAML
data = kwargs.pop("data", None)
file_path = kwargs.pop("file_path", None)
if file_path is None:
raise LookupError("file_path argument must be supplied")
if data is None:
data = yaml.load_all(open(file_path, 'r'), Loader=Loader)
for data_item_index, data_item in enumerate(data):
if data_item is None:
continue
try:
if not data_item_index and 'data_file' not in data_item:
validate(data_item, additional_file_section_schema)
else:
validate(data_item, submission_file_schema)
except ValidationError as ve:
self.add_validation_message(
ValidationMessage(file=file_path,
message=ve.message + ' in ' + str(ve.instance)))
if self.has_errors(file_path):
return False
else:
return True
except ScannerError as se: # pragma: no cover
self.add_validation_message( # pragma: no cover
ValidationMessage(file=file_path, message=
'There was a problem parsing the file. '
'This can be because you forgot spaces '
'after colons in your YAML file for instance. '
'Diagnostic information follows.\n' + str(se)))
return False
except Exception as e:
self.add_validation_message(ValidationMessage(file=file_path, message=e.__str__()))
return False | [
"def",
"validate",
"(",
"self",
",",
"**",
"kwargs",
")",
":",
"try",
":",
"submission_file_schema",
"=",
"json",
".",
"load",
"(",
"open",
"(",
"self",
".",
"default_schema_file",
",",
"'r'",
")",
")",
"additional_file_section_schema",
"=",
"json",
".",
"load",
"(",
"open",
"(",
"self",
".",
"additional_info_schema",
",",
"'r'",
")",
")",
"data",
"=",
"kwargs",
".",
"pop",
"(",
"\"data\"",
",",
"None",
")",
"file_path",
"=",
"kwargs",
".",
"pop",
"(",
"\"file_path\"",
",",
"None",
")",
"if",
"file_path",
"is",
"None",
":",
"raise",
"LookupError",
"(",
"\"file_path argument must be supplied\"",
")",
"if",
"data",
"is",
"None",
":",
"data",
"=",
"yaml",
".",
"load_all",
"(",
"open",
"(",
"file_path",
",",
"'r'",
")",
",",
"Loader",
"=",
"Loader",
")",
"for",
"data_item_index",
",",
"data_item",
"in",
"enumerate",
"(",
"data",
")",
":",
"if",
"data_item",
"is",
"None",
":",
"continue",
"try",
":",
"if",
"not",
"data_item_index",
"and",
"'data_file'",
"not",
"in",
"data_item",
":",
"validate",
"(",
"data_item",
",",
"additional_file_section_schema",
")",
"else",
":",
"validate",
"(",
"data_item",
",",
"submission_file_schema",
")",
"except",
"ValidationError",
"as",
"ve",
":",
"self",
".",
"add_validation_message",
"(",
"ValidationMessage",
"(",
"file",
"=",
"file_path",
",",
"message",
"=",
"ve",
".",
"message",
"+",
"' in '",
"+",
"str",
"(",
"ve",
".",
"instance",
")",
")",
")",
"if",
"self",
".",
"has_errors",
"(",
"file_path",
")",
":",
"return",
"False",
"else",
":",
"return",
"True",
"except",
"ScannerError",
"as",
"se",
":",
"self",
".",
"add_validation_message",
"(",
"ValidationMessage",
"(",
"file",
"=",
"file_path",
",",
"message",
"=",
"'There was a problem parsing the file. '",
"'This can be because you forgot spaces '",
"'after colons in your YAML file for instance. '",
"'Diagnostic information follows.\\n'",
"+",
"str",
"(",
"se",
")",
")",
")",
"return",
"False",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"add_validation_message",
"(",
"ValidationMessage",
"(",
"file",
"=",
"file_path",
",",
"message",
"=",
"e",
".",
"__str__",
"(",
")",
")",
")",
"return",
"False"
] | Validates a submission file
:param file_path: path to file to be loaded.
:param data: pre loaded YAML object (optional).
:return: Bool to indicate the validity of the file. | [
"Validates",
"a",
"submission",
"file"
] | d0b0cab742a009c8f0e8aac9f8c8e434a524d43c | https://github.com/HEPData/hepdata-validator/blob/d0b0cab742a009c8f0e8aac9f8c8e434a524d43c/hepdata_validator/submission_file_validator.py#L26-L80 | train |
budacom/trading-bots | trading_bots/core/utils.py | load_class_by_name | def load_class_by_name(name: str):
"""Given a dotted path, returns the class"""
mod_path, _, cls_name = name.rpartition('.')
mod = importlib.import_module(mod_path)
cls = getattr(mod, cls_name)
return cls | python | def load_class_by_name(name: str):
"""Given a dotted path, returns the class"""
mod_path, _, cls_name = name.rpartition('.')
mod = importlib.import_module(mod_path)
cls = getattr(mod, cls_name)
return cls | [
"def",
"load_class_by_name",
"(",
"name",
":",
"str",
")",
":",
"mod_path",
",",
"_",
",",
"cls_name",
"=",
"name",
".",
"rpartition",
"(",
"'.'",
")",
"mod",
"=",
"importlib",
".",
"import_module",
"(",
"mod_path",
")",
"cls",
"=",
"getattr",
"(",
"mod",
",",
"cls_name",
")",
"return",
"cls"
] | Given a dotted path, returns the class | [
"Given",
"a",
"dotted",
"path",
"returns",
"the",
"class"
] | 8cb68bb8d0b5f822108db1cc5dae336e3d3c3452 | https://github.com/budacom/trading-bots/blob/8cb68bb8d0b5f822108db1cc5dae336e3d3c3452/trading_bots/core/utils.py#L7-L12 | train |
budacom/trading-bots | trading_bots/core/utils.py | load_yaml_file | def load_yaml_file(file_path: str):
"""Load a YAML file from path"""
with codecs.open(file_path, 'r') as f:
return yaml.safe_load(f) | python | def load_yaml_file(file_path: str):
"""Load a YAML file from path"""
with codecs.open(file_path, 'r') as f:
return yaml.safe_load(f) | [
"def",
"load_yaml_file",
"(",
"file_path",
":",
"str",
")",
":",
"with",
"codecs",
".",
"open",
"(",
"file_path",
",",
"'r'",
")",
"as",
"f",
":",
"return",
"yaml",
".",
"safe_load",
"(",
"f",
")"
] | Load a YAML file from path | [
"Load",
"a",
"YAML",
"file",
"from",
"path"
] | 8cb68bb8d0b5f822108db1cc5dae336e3d3c3452 | https://github.com/budacom/trading-bots/blob/8cb68bb8d0b5f822108db1cc5dae336e3d3c3452/trading_bots/core/utils.py#L15-L18 | train |
BD2KGenomics/protect | src/protect/addons/assess_immunotherapy_resistance.py | run_itx_resistance_assessment | def run_itx_resistance_assessment(job, rsem_files, univ_options, reports_options):
"""
A wrapper for assess_itx_resistance.
:param dict rsem_files: Results from running rsem
:param dict univ_options: Dict of universal options used by almost all tools
:param dict reports_options: Options specific to reporting modules
:return: The results of running assess_itx_resistance
:rtype: toil.fileStore.FileID
"""
return job.addChildJobFn(assess_itx_resistance, rsem_files['rsem.genes.results'],
univ_options, reports_options).rv() | python | def run_itx_resistance_assessment(job, rsem_files, univ_options, reports_options):
"""
A wrapper for assess_itx_resistance.
:param dict rsem_files: Results from running rsem
:param dict univ_options: Dict of universal options used by almost all tools
:param dict reports_options: Options specific to reporting modules
:return: The results of running assess_itx_resistance
:rtype: toil.fileStore.FileID
"""
return job.addChildJobFn(assess_itx_resistance, rsem_files['rsem.genes.results'],
univ_options, reports_options).rv() | [
"def",
"run_itx_resistance_assessment",
"(",
"job",
",",
"rsem_files",
",",
"univ_options",
",",
"reports_options",
")",
":",
"return",
"job",
".",
"addChildJobFn",
"(",
"assess_itx_resistance",
",",
"rsem_files",
"[",
"'rsem.genes.results'",
"]",
",",
"univ_options",
",",
"reports_options",
")",
".",
"rv",
"(",
")"
] | A wrapper for assess_itx_resistance.
:param dict rsem_files: Results from running rsem
:param dict univ_options: Dict of universal options used by almost all tools
:param dict reports_options: Options specific to reporting modules
:return: The results of running assess_itx_resistance
:rtype: toil.fileStore.FileID | [
"A",
"wrapper",
"for",
"assess_itx_resistance",
"."
] | 06310682c50dcf8917b912c8e551299ff7ee41ce | https://github.com/BD2KGenomics/protect/blob/06310682c50dcf8917b912c8e551299ff7ee41ce/src/protect/addons/assess_immunotherapy_resistance.py#L26-L37 | train |
APSL/django-kaio | kaio/mixins/celeryconf.py | CeleryMixin.CELERY_RESULT_BACKEND | def CELERY_RESULT_BACKEND(self):
"""Redis result backend config"""
# allow specify directly
configured = get('CELERY_RESULT_BACKEND', None)
if configured:
return configured
if not self._redis_available():
return None
host, port = self.REDIS_HOST, self.REDIS_PORT
if host and port:
default = "redis://{host}:{port}/{db}".format(
host=host, port=port,
db=self.CELERY_REDIS_RESULT_DB)
return default | python | def CELERY_RESULT_BACKEND(self):
"""Redis result backend config"""
# allow specify directly
configured = get('CELERY_RESULT_BACKEND', None)
if configured:
return configured
if not self._redis_available():
return None
host, port = self.REDIS_HOST, self.REDIS_PORT
if host and port:
default = "redis://{host}:{port}/{db}".format(
host=host, port=port,
db=self.CELERY_REDIS_RESULT_DB)
return default | [
"def",
"CELERY_RESULT_BACKEND",
"(",
"self",
")",
":",
"configured",
"=",
"get",
"(",
"'CELERY_RESULT_BACKEND'",
",",
"None",
")",
"if",
"configured",
":",
"return",
"configured",
"if",
"not",
"self",
".",
"_redis_available",
"(",
")",
":",
"return",
"None",
"host",
",",
"port",
"=",
"self",
".",
"REDIS_HOST",
",",
"self",
".",
"REDIS_PORT",
"if",
"host",
"and",
"port",
":",
"default",
"=",
"\"redis://{host}:{port}/{db}\"",
".",
"format",
"(",
"host",
"=",
"host",
",",
"port",
"=",
"port",
",",
"db",
"=",
"self",
".",
"CELERY_REDIS_RESULT_DB",
")",
"return",
"default"
] | Redis result backend config | [
"Redis",
"result",
"backend",
"config"
] | b74b109bcfba31d973723bc419e2c95d190b80b7 | https://github.com/APSL/django-kaio/blob/b74b109bcfba31d973723bc419e2c95d190b80b7/kaio/mixins/celeryconf.py#L35-L53 | train |
APSL/django-kaio | kaio/mixins/celeryconf.py | CeleryMixin.BROKER_TYPE | def BROKER_TYPE(self):
"""Custom setting allowing switch between rabbitmq, redis"""
broker_type = get('BROKER_TYPE', DEFAULT_BROKER_TYPE)
if broker_type not in SUPPORTED_BROKER_TYPES:
log.warn("Specified BROKER_TYPE {} not supported. Backing to default {}".format(
broker_type, DEFAULT_BROKER_TYPE))
return DEFAULT_BROKER_TYPE
else:
return broker_type | python | def BROKER_TYPE(self):
"""Custom setting allowing switch between rabbitmq, redis"""
broker_type = get('BROKER_TYPE', DEFAULT_BROKER_TYPE)
if broker_type not in SUPPORTED_BROKER_TYPES:
log.warn("Specified BROKER_TYPE {} not supported. Backing to default {}".format(
broker_type, DEFAULT_BROKER_TYPE))
return DEFAULT_BROKER_TYPE
else:
return broker_type | [
"def",
"BROKER_TYPE",
"(",
"self",
")",
":",
"broker_type",
"=",
"get",
"(",
"'BROKER_TYPE'",
",",
"DEFAULT_BROKER_TYPE",
")",
"if",
"broker_type",
"not",
"in",
"SUPPORTED_BROKER_TYPES",
":",
"log",
".",
"warn",
"(",
"\"Specified BROKER_TYPE {} not supported. Backing to default {}\"",
".",
"format",
"(",
"broker_type",
",",
"DEFAULT_BROKER_TYPE",
")",
")",
"return",
"DEFAULT_BROKER_TYPE",
"else",
":",
"return",
"broker_type"
] | Custom setting allowing switch between rabbitmq, redis | [
"Custom",
"setting",
"allowing",
"switch",
"between",
"rabbitmq",
"redis"
] | b74b109bcfba31d973723bc419e2c95d190b80b7 | https://github.com/APSL/django-kaio/blob/b74b109bcfba31d973723bc419e2c95d190b80b7/kaio/mixins/celeryconf.py#L76-L85 | train |
APSL/django-kaio | kaio/mixins/celeryconf.py | CeleryMixin.BROKER_URL | def BROKER_URL(self):
"""Sets BROKER_URL depending on redis or rabbitmq settings"""
# also allow specify broker_url
broker_url = get('BROKER_URL', None)
if broker_url:
log.info("Using BROKER_URL setting: {}".format(broker_url))
return broker_url
redis_available = self._redis_available()
broker_type = self.BROKER_TYPE
if broker_type == 'redis' and not redis_available:
log.warn("Choosed broker type is redis, but redis not available. \
Check redis package, and REDIS_HOST, REDIS_PORT settings")
if broker_type == 'redis' and redis_available:
return 'redis://{host}:{port}/{db}'.format(
host=self.REDIS_HOST,
port=self.REDIS_PORT,
db=self.CELERY_REDIS_BROKER_DB)
elif broker_type == 'rabbitmq':
return 'amqp://{user}:{passwd}@{host}:{port}/{vhost}'.format(
user=self.RABBITMQ_USER,
passwd=self.RABBITMQ_PASSWD,
host=self.RABBITMQ_HOST,
port=self.RABBITMQ_PORT,
vhost=self.RABBITMQ_VHOST)
else:
return DEFAULT_BROKER_URL | python | def BROKER_URL(self):
"""Sets BROKER_URL depending on redis or rabbitmq settings"""
# also allow specify broker_url
broker_url = get('BROKER_URL', None)
if broker_url:
log.info("Using BROKER_URL setting: {}".format(broker_url))
return broker_url
redis_available = self._redis_available()
broker_type = self.BROKER_TYPE
if broker_type == 'redis' and not redis_available:
log.warn("Choosed broker type is redis, but redis not available. \
Check redis package, and REDIS_HOST, REDIS_PORT settings")
if broker_type == 'redis' and redis_available:
return 'redis://{host}:{port}/{db}'.format(
host=self.REDIS_HOST,
port=self.REDIS_PORT,
db=self.CELERY_REDIS_BROKER_DB)
elif broker_type == 'rabbitmq':
return 'amqp://{user}:{passwd}@{host}:{port}/{vhost}'.format(
user=self.RABBITMQ_USER,
passwd=self.RABBITMQ_PASSWD,
host=self.RABBITMQ_HOST,
port=self.RABBITMQ_PORT,
vhost=self.RABBITMQ_VHOST)
else:
return DEFAULT_BROKER_URL | [
"def",
"BROKER_URL",
"(",
"self",
")",
":",
"broker_url",
"=",
"get",
"(",
"'BROKER_URL'",
",",
"None",
")",
"if",
"broker_url",
":",
"log",
".",
"info",
"(",
"\"Using BROKER_URL setting: {}\"",
".",
"format",
"(",
"broker_url",
")",
")",
"return",
"broker_url",
"redis_available",
"=",
"self",
".",
"_redis_available",
"(",
")",
"broker_type",
"=",
"self",
".",
"BROKER_TYPE",
"if",
"broker_type",
"==",
"'redis'",
"and",
"not",
"redis_available",
":",
"log",
".",
"warn",
"(",
"\"Choosed broker type is redis, but redis not available. \\ Check redis package, and REDIS_HOST, REDIS_PORT settings\"",
")",
"if",
"broker_type",
"==",
"'redis'",
"and",
"redis_available",
":",
"return",
"'redis://{host}:{port}/{db}'",
".",
"format",
"(",
"host",
"=",
"self",
".",
"REDIS_HOST",
",",
"port",
"=",
"self",
".",
"REDIS_PORT",
",",
"db",
"=",
"self",
".",
"CELERY_REDIS_BROKER_DB",
")",
"elif",
"broker_type",
"==",
"'rabbitmq'",
":",
"return",
"'amqp://{user}:{passwd}@{host}:{port}/{vhost}'",
".",
"format",
"(",
"user",
"=",
"self",
".",
"RABBITMQ_USER",
",",
"passwd",
"=",
"self",
".",
"RABBITMQ_PASSWD",
",",
"host",
"=",
"self",
".",
"RABBITMQ_HOST",
",",
"port",
"=",
"self",
".",
"RABBITMQ_PORT",
",",
"vhost",
"=",
"self",
".",
"RABBITMQ_VHOST",
")",
"else",
":",
"return",
"DEFAULT_BROKER_URL"
] | Sets BROKER_URL depending on redis or rabbitmq settings | [
"Sets",
"BROKER_URL",
"depending",
"on",
"redis",
"or",
"rabbitmq",
"settings"
] | b74b109bcfba31d973723bc419e2c95d190b80b7 | https://github.com/APSL/django-kaio/blob/b74b109bcfba31d973723bc419e2c95d190b80b7/kaio/mixins/celeryconf.py#L122-L152 | train |
idlesign/steampak | steampak/webapi/resources/user.py | User.traverse_inventory | def traverse_inventory(self, item_filter=None):
"""Generates market Item objects for each inventory item.
:param str item_filter: See `TAG_ITEM_CLASS_` contants from .market module.
"""
not self._intentory_raw and self._get_inventory_raw()
for item in self._intentory_raw['rgDescriptions'].values():
tags = item['tags']
for tag in tags:
internal_name = tag['internal_name']
if item_filter is None or internal_name == item_filter:
item_type = Item
if internal_name == TAG_ITEM_CLASS_CARD:
item_type = Card
appid = item['market_fee_app']
title = item['name']
yield item_type(appid, title) | python | def traverse_inventory(self, item_filter=None):
"""Generates market Item objects for each inventory item.
:param str item_filter: See `TAG_ITEM_CLASS_` contants from .market module.
"""
not self._intentory_raw and self._get_inventory_raw()
for item in self._intentory_raw['rgDescriptions'].values():
tags = item['tags']
for tag in tags:
internal_name = tag['internal_name']
if item_filter is None or internal_name == item_filter:
item_type = Item
if internal_name == TAG_ITEM_CLASS_CARD:
item_type = Card
appid = item['market_fee_app']
title = item['name']
yield item_type(appid, title) | [
"def",
"traverse_inventory",
"(",
"self",
",",
"item_filter",
"=",
"None",
")",
":",
"not",
"self",
".",
"_intentory_raw",
"and",
"self",
".",
"_get_inventory_raw",
"(",
")",
"for",
"item",
"in",
"self",
".",
"_intentory_raw",
"[",
"'rgDescriptions'",
"]",
".",
"values",
"(",
")",
":",
"tags",
"=",
"item",
"[",
"'tags'",
"]",
"for",
"tag",
"in",
"tags",
":",
"internal_name",
"=",
"tag",
"[",
"'internal_name'",
"]",
"if",
"item_filter",
"is",
"None",
"or",
"internal_name",
"==",
"item_filter",
":",
"item_type",
"=",
"Item",
"if",
"internal_name",
"==",
"TAG_ITEM_CLASS_CARD",
":",
"item_type",
"=",
"Card",
"appid",
"=",
"item",
"[",
"'market_fee_app'",
"]",
"title",
"=",
"item",
"[",
"'name'",
"]",
"yield",
"item_type",
"(",
"appid",
",",
"title",
")"
] | Generates market Item objects for each inventory item.
:param str item_filter: See `TAG_ITEM_CLASS_` contants from .market module. | [
"Generates",
"market",
"Item",
"objects",
"for",
"each",
"inventory",
"item",
"."
] | cb3f2c737e272b0360802d947e388df7e34f50f3 | https://github.com/idlesign/steampak/blob/cb3f2c737e272b0360802d947e388df7e34f50f3/steampak/webapi/resources/user.py#L36-L57 | train |
HEPData/hepdata-validator | hepdata_validator/data_file_validator.py | DataFileValidator.validate | def validate(self, **kwargs):
"""
Validates a data file
:param file_path: path to file to be loaded.
:param data: pre loaded YAML object (optional).
:return: Bool to indicate the validity of the file.
"""
default_data_schema = json.load(open(self.default_schema_file, 'r'))
# even though we are using the yaml package to load,
# it supports JSON and YAML
data = kwargs.pop("data", None)
file_path = kwargs.pop("file_path", None)
if file_path is None:
raise LookupError("file_path argument must be supplied")
if data is None:
try:
data = yaml.load(open(file_path, 'r'), Loader=Loader)
except Exception as e:
self.add_validation_message(ValidationMessage(file=file_path, message=
'There was a problem parsing the file.\n' + e.__str__()))
return False
try:
if 'type' in data:
custom_schema = self.load_custom_schema(data['type'])
json_validate(data, custom_schema)
else:
json_validate(data, default_data_schema)
except ValidationError as ve:
self.add_validation_message(
ValidationMessage(file=file_path,
message=ve.message + ' in ' + str(ve.instance)))
if self.has_errors(file_path):
return False
else:
return True | python | def validate(self, **kwargs):
"""
Validates a data file
:param file_path: path to file to be loaded.
:param data: pre loaded YAML object (optional).
:return: Bool to indicate the validity of the file.
"""
default_data_schema = json.load(open(self.default_schema_file, 'r'))
# even though we are using the yaml package to load,
# it supports JSON and YAML
data = kwargs.pop("data", None)
file_path = kwargs.pop("file_path", None)
if file_path is None:
raise LookupError("file_path argument must be supplied")
if data is None:
try:
data = yaml.load(open(file_path, 'r'), Loader=Loader)
except Exception as e:
self.add_validation_message(ValidationMessage(file=file_path, message=
'There was a problem parsing the file.\n' + e.__str__()))
return False
try:
if 'type' in data:
custom_schema = self.load_custom_schema(data['type'])
json_validate(data, custom_schema)
else:
json_validate(data, default_data_schema)
except ValidationError as ve:
self.add_validation_message(
ValidationMessage(file=file_path,
message=ve.message + ' in ' + str(ve.instance)))
if self.has_errors(file_path):
return False
else:
return True | [
"def",
"validate",
"(",
"self",
",",
"**",
"kwargs",
")",
":",
"default_data_schema",
"=",
"json",
".",
"load",
"(",
"open",
"(",
"self",
".",
"default_schema_file",
",",
"'r'",
")",
")",
"data",
"=",
"kwargs",
".",
"pop",
"(",
"\"data\"",
",",
"None",
")",
"file_path",
"=",
"kwargs",
".",
"pop",
"(",
"\"file_path\"",
",",
"None",
")",
"if",
"file_path",
"is",
"None",
":",
"raise",
"LookupError",
"(",
"\"file_path argument must be supplied\"",
")",
"if",
"data",
"is",
"None",
":",
"try",
":",
"data",
"=",
"yaml",
".",
"load",
"(",
"open",
"(",
"file_path",
",",
"'r'",
")",
",",
"Loader",
"=",
"Loader",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"add_validation_message",
"(",
"ValidationMessage",
"(",
"file",
"=",
"file_path",
",",
"message",
"=",
"'There was a problem parsing the file.\\n'",
"+",
"e",
".",
"__str__",
"(",
")",
")",
")",
"return",
"False",
"try",
":",
"if",
"'type'",
"in",
"data",
":",
"custom_schema",
"=",
"self",
".",
"load_custom_schema",
"(",
"data",
"[",
"'type'",
"]",
")",
"json_validate",
"(",
"data",
",",
"custom_schema",
")",
"else",
":",
"json_validate",
"(",
"data",
",",
"default_data_schema",
")",
"except",
"ValidationError",
"as",
"ve",
":",
"self",
".",
"add_validation_message",
"(",
"ValidationMessage",
"(",
"file",
"=",
"file_path",
",",
"message",
"=",
"ve",
".",
"message",
"+",
"' in '",
"+",
"str",
"(",
"ve",
".",
"instance",
")",
")",
")",
"if",
"self",
".",
"has_errors",
"(",
"file_path",
")",
":",
"return",
"False",
"else",
":",
"return",
"True"
] | Validates a data file
:param file_path: path to file to be loaded.
:param data: pre loaded YAML object (optional).
:return: Bool to indicate the validity of the file. | [
"Validates",
"a",
"data",
"file"
] | d0b0cab742a009c8f0e8aac9f8c8e434a524d43c | https://github.com/HEPData/hepdata-validator/blob/d0b0cab742a009c8f0e8aac9f8c8e434a524d43c/hepdata_validator/data_file_validator.py#L74-L119 | train |
proycon/python-timbl | timbl.py | b | def b(s):
"""Conversion to bytes"""
if sys.version < '3':
if isinstance(s, unicode): #pylint: disable=undefined-variable
return s.encode('utf-8')
else:
return s | python | def b(s):
"""Conversion to bytes"""
if sys.version < '3':
if isinstance(s, unicode): #pylint: disable=undefined-variable
return s.encode('utf-8')
else:
return s | [
"def",
"b",
"(",
"s",
")",
":",
"if",
"sys",
".",
"version",
"<",
"'3'",
":",
"if",
"isinstance",
"(",
"s",
",",
"unicode",
")",
":",
"return",
"s",
".",
"encode",
"(",
"'utf-8'",
")",
"else",
":",
"return",
"s"
] | Conversion to bytes | [
"Conversion",
"to",
"bytes"
] | e3c876711fa7f60648cfb1e4066c421a65faf524 | https://github.com/proycon/python-timbl/blob/e3c876711fa7f60648cfb1e4066c421a65faf524/timbl.py#L35-L41 | train |
proycon/python-timbl | timbl.py | TimblClassifier.validatefeatures | def validatefeatures(self,features):
"""Returns features in validated form, or raises an Exception. Mostly for internal use"""
validatedfeatures = []
for feature in features:
if isinstance(feature, int) or isinstance(feature, float):
validatedfeatures.append( str(feature) )
elif self.delimiter in feature and not self.sklearn:
raise ValueError("Feature contains delimiter: " + feature)
elif self.sklearn and isinstance(feature, str): #then is sparse added together
validatedfeatures.append(feature)
else:
validatedfeatures.append(feature)
return validatedfeatures | python | def validatefeatures(self,features):
"""Returns features in validated form, or raises an Exception. Mostly for internal use"""
validatedfeatures = []
for feature in features:
if isinstance(feature, int) or isinstance(feature, float):
validatedfeatures.append( str(feature) )
elif self.delimiter in feature and not self.sklearn:
raise ValueError("Feature contains delimiter: " + feature)
elif self.sklearn and isinstance(feature, str): #then is sparse added together
validatedfeatures.append(feature)
else:
validatedfeatures.append(feature)
return validatedfeatures | [
"def",
"validatefeatures",
"(",
"self",
",",
"features",
")",
":",
"validatedfeatures",
"=",
"[",
"]",
"for",
"feature",
"in",
"features",
":",
"if",
"isinstance",
"(",
"feature",
",",
"int",
")",
"or",
"isinstance",
"(",
"feature",
",",
"float",
")",
":",
"validatedfeatures",
".",
"append",
"(",
"str",
"(",
"feature",
")",
")",
"elif",
"self",
".",
"delimiter",
"in",
"feature",
"and",
"not",
"self",
".",
"sklearn",
":",
"raise",
"ValueError",
"(",
"\"Feature contains delimiter: \"",
"+",
"feature",
")",
"elif",
"self",
".",
"sklearn",
"and",
"isinstance",
"(",
"feature",
",",
"str",
")",
":",
"validatedfeatures",
".",
"append",
"(",
"feature",
")",
"else",
":",
"validatedfeatures",
".",
"append",
"(",
"feature",
")",
"return",
"validatedfeatures"
] | Returns features in validated form, or raises an Exception. Mostly for internal use | [
"Returns",
"features",
"in",
"validated",
"form",
"or",
"raises",
"an",
"Exception",
".",
"Mostly",
"for",
"internal",
"use"
] | e3c876711fa7f60648cfb1e4066c421a65faf524 | https://github.com/proycon/python-timbl/blob/e3c876711fa7f60648cfb1e4066c421a65faf524/timbl.py#L102-L114 | train |
proycon/python-timbl | timbl.py | TimblClassifier.addinstance | def addinstance(self, testfile, features, classlabel="?"):
"""Adds an instance to a specific file. Especially suitable for generating test files"""
features = self.validatefeatures(features)
if self.delimiter in classlabel:
raise ValueError("Class label contains delimiter: " + self.delimiter)
f = io.open(testfile,'a', encoding=self.encoding)
f.write(self.delimiter.join(features) + self.delimiter + classlabel + "\n")
f.close() | python | def addinstance(self, testfile, features, classlabel="?"):
"""Adds an instance to a specific file. Especially suitable for generating test files"""
features = self.validatefeatures(features)
if self.delimiter in classlabel:
raise ValueError("Class label contains delimiter: " + self.delimiter)
f = io.open(testfile,'a', encoding=self.encoding)
f.write(self.delimiter.join(features) + self.delimiter + classlabel + "\n")
f.close() | [
"def",
"addinstance",
"(",
"self",
",",
"testfile",
",",
"features",
",",
"classlabel",
"=",
"\"?\"",
")",
":",
"features",
"=",
"self",
".",
"validatefeatures",
"(",
"features",
")",
"if",
"self",
".",
"delimiter",
"in",
"classlabel",
":",
"raise",
"ValueError",
"(",
"\"Class label contains delimiter: \"",
"+",
"self",
".",
"delimiter",
")",
"f",
"=",
"io",
".",
"open",
"(",
"testfile",
",",
"'a'",
",",
"encoding",
"=",
"self",
".",
"encoding",
")",
"f",
".",
"write",
"(",
"self",
".",
"delimiter",
".",
"join",
"(",
"features",
")",
"+",
"self",
".",
"delimiter",
"+",
"classlabel",
"+",
"\"\\n\"",
")",
"f",
".",
"close",
"(",
")"
] | Adds an instance to a specific file. Especially suitable for generating test files | [
"Adds",
"an",
"instance",
"to",
"a",
"specific",
"file",
".",
"Especially",
"suitable",
"for",
"generating",
"test",
"files"
] | e3c876711fa7f60648cfb1e4066c421a65faf524 | https://github.com/proycon/python-timbl/blob/e3c876711fa7f60648cfb1e4066c421a65faf524/timbl.py#L247-L258 | train |
proycon/python-timbl | timbl.py | TimblClassifier.crossvalidate | def crossvalidate(self, foldsfile):
"""Train & Test using cross validation, testfile is a file that contains the filenames of all the folds!"""
options = "-F " + self.format + " " + self.timbloptions + " -t cross_validate"
print("Instantiating Timbl API : " + options,file=stderr)
if sys.version < '3':
self.api = timblapi.TimblAPI(b(options), b"")
else:
self.api = timblapi.TimblAPI(options, "")
if self.debug:
print("Enabling debug for timblapi",file=stderr)
self.api.enableDebug()
print("Calling Timbl Test : " + options,file=stderr)
if sys.version < '3':
self.api.test(b(foldsfile),b'',b'')
else:
self.api.test(u(foldsfile),'','')
a = self.api.getAccuracy()
del self.api
return a | python | def crossvalidate(self, foldsfile):
"""Train & Test using cross validation, testfile is a file that contains the filenames of all the folds!"""
options = "-F " + self.format + " " + self.timbloptions + " -t cross_validate"
print("Instantiating Timbl API : " + options,file=stderr)
if sys.version < '3':
self.api = timblapi.TimblAPI(b(options), b"")
else:
self.api = timblapi.TimblAPI(options, "")
if self.debug:
print("Enabling debug for timblapi",file=stderr)
self.api.enableDebug()
print("Calling Timbl Test : " + options,file=stderr)
if sys.version < '3':
self.api.test(b(foldsfile),b'',b'')
else:
self.api.test(u(foldsfile),'','')
a = self.api.getAccuracy()
del self.api
return a | [
"def",
"crossvalidate",
"(",
"self",
",",
"foldsfile",
")",
":",
"options",
"=",
"\"-F \"",
"+",
"self",
".",
"format",
"+",
"\" \"",
"+",
"self",
".",
"timbloptions",
"+",
"\" -t cross_validate\"",
"print",
"(",
"\"Instantiating Timbl API : \"",
"+",
"options",
",",
"file",
"=",
"stderr",
")",
"if",
"sys",
".",
"version",
"<",
"'3'",
":",
"self",
".",
"api",
"=",
"timblapi",
".",
"TimblAPI",
"(",
"b",
"(",
"options",
")",
",",
"b\"\"",
")",
"else",
":",
"self",
".",
"api",
"=",
"timblapi",
".",
"TimblAPI",
"(",
"options",
",",
"\"\"",
")",
"if",
"self",
".",
"debug",
":",
"print",
"(",
"\"Enabling debug for timblapi\"",
",",
"file",
"=",
"stderr",
")",
"self",
".",
"api",
".",
"enableDebug",
"(",
")",
"print",
"(",
"\"Calling Timbl Test : \"",
"+",
"options",
",",
"file",
"=",
"stderr",
")",
"if",
"sys",
".",
"version",
"<",
"'3'",
":",
"self",
".",
"api",
".",
"test",
"(",
"b",
"(",
"foldsfile",
")",
",",
"b''",
",",
"b''",
")",
"else",
":",
"self",
".",
"api",
".",
"test",
"(",
"u",
"(",
"foldsfile",
")",
",",
"''",
",",
"''",
")",
"a",
"=",
"self",
".",
"api",
".",
"getAccuracy",
"(",
")",
"del",
"self",
".",
"api",
"return",
"a"
] | Train & Test using cross validation, testfile is a file that contains the filenames of all the folds! | [
"Train",
"&",
"Test",
"using",
"cross",
"validation",
"testfile",
"is",
"a",
"file",
"that",
"contains",
"the",
"filenames",
"of",
"all",
"the",
"folds!"
] | e3c876711fa7f60648cfb1e4066c421a65faf524 | https://github.com/proycon/python-timbl/blob/e3c876711fa7f60648cfb1e4066c421a65faf524/timbl.py#L271-L289 | train |
proycon/python-timbl | timbl.py | TimblClassifier.leaveoneout | def leaveoneout(self):
"""Train & Test using leave one out"""
traintestfile = self.fileprefix + '.train'
options = "-F " + self.format + " " + self.timbloptions + " -t leave_one_out"
if sys.version < '3':
self.api = timblapi.TimblAPI(b(options), b"")
else:
self.api = timblapi.TimblAPI(options, "")
if self.debug:
print("Enabling debug for timblapi",file=stderr)
self.api.enableDebug()
print("Calling Timbl API : " + options,file=stderr)
if sys.version < '3':
self.api.learn(b(traintestfile))
self.api.test(b(traintestfile), b(self.fileprefix + '.out'),b'')
else:
self.api.learn(u(traintestfile))
self.api.test(u(traintestfile), u(self.fileprefix + '.out'),'')
return self.api.getAccuracy() | python | def leaveoneout(self):
"""Train & Test using leave one out"""
traintestfile = self.fileprefix + '.train'
options = "-F " + self.format + " " + self.timbloptions + " -t leave_one_out"
if sys.version < '3':
self.api = timblapi.TimblAPI(b(options), b"")
else:
self.api = timblapi.TimblAPI(options, "")
if self.debug:
print("Enabling debug for timblapi",file=stderr)
self.api.enableDebug()
print("Calling Timbl API : " + options,file=stderr)
if sys.version < '3':
self.api.learn(b(traintestfile))
self.api.test(b(traintestfile), b(self.fileprefix + '.out'),b'')
else:
self.api.learn(u(traintestfile))
self.api.test(u(traintestfile), u(self.fileprefix + '.out'),'')
return self.api.getAccuracy() | [
"def",
"leaveoneout",
"(",
"self",
")",
":",
"traintestfile",
"=",
"self",
".",
"fileprefix",
"+",
"'.train'",
"options",
"=",
"\"-F \"",
"+",
"self",
".",
"format",
"+",
"\" \"",
"+",
"self",
".",
"timbloptions",
"+",
"\" -t leave_one_out\"",
"if",
"sys",
".",
"version",
"<",
"'3'",
":",
"self",
".",
"api",
"=",
"timblapi",
".",
"TimblAPI",
"(",
"b",
"(",
"options",
")",
",",
"b\"\"",
")",
"else",
":",
"self",
".",
"api",
"=",
"timblapi",
".",
"TimblAPI",
"(",
"options",
",",
"\"\"",
")",
"if",
"self",
".",
"debug",
":",
"print",
"(",
"\"Enabling debug for timblapi\"",
",",
"file",
"=",
"stderr",
")",
"self",
".",
"api",
".",
"enableDebug",
"(",
")",
"print",
"(",
"\"Calling Timbl API : \"",
"+",
"options",
",",
"file",
"=",
"stderr",
")",
"if",
"sys",
".",
"version",
"<",
"'3'",
":",
"self",
".",
"api",
".",
"learn",
"(",
"b",
"(",
"traintestfile",
")",
")",
"self",
".",
"api",
".",
"test",
"(",
"b",
"(",
"traintestfile",
")",
",",
"b",
"(",
"self",
".",
"fileprefix",
"+",
"'.out'",
")",
",",
"b''",
")",
"else",
":",
"self",
".",
"api",
".",
"learn",
"(",
"u",
"(",
"traintestfile",
")",
")",
"self",
".",
"api",
".",
"test",
"(",
"u",
"(",
"traintestfile",
")",
",",
"u",
"(",
"self",
".",
"fileprefix",
"+",
"'.out'",
")",
",",
"''",
")",
"return",
"self",
".",
"api",
".",
"getAccuracy",
"(",
")"
] | Train & Test using leave one out | [
"Train",
"&",
"Test",
"using",
"leave",
"one",
"out"
] | e3c876711fa7f60648cfb1e4066c421a65faf524 | https://github.com/proycon/python-timbl/blob/e3c876711fa7f60648cfb1e4066c421a65faf524/timbl.py#L293-L311 | train |
inveniosoftware/invenio-access | invenio_access/ext.py | _AccessState.set_action_cache | def set_action_cache(self, action_key, data):
"""Store action needs and excludes.
.. note:: The action is saved only if a cache system is defined.
:param action_key: The unique action name.
:param data: The action to be saved.
"""
if self.cache:
self.cache.set(
self.app.config['ACCESS_ACTION_CACHE_PREFIX'] +
action_key, data
) | python | def set_action_cache(self, action_key, data):
"""Store action needs and excludes.
.. note:: The action is saved only if a cache system is defined.
:param action_key: The unique action name.
:param data: The action to be saved.
"""
if self.cache:
self.cache.set(
self.app.config['ACCESS_ACTION_CACHE_PREFIX'] +
action_key, data
) | [
"def",
"set_action_cache",
"(",
"self",
",",
"action_key",
",",
"data",
")",
":",
"if",
"self",
".",
"cache",
":",
"self",
".",
"cache",
".",
"set",
"(",
"self",
".",
"app",
".",
"config",
"[",
"'ACCESS_ACTION_CACHE_PREFIX'",
"]",
"+",
"action_key",
",",
"data",
")"
] | Store action needs and excludes.
.. note:: The action is saved only if a cache system is defined.
:param action_key: The unique action name.
:param data: The action to be saved. | [
"Store",
"action",
"needs",
"and",
"excludes",
"."
] | 3b033a4bdc110eb2f7e9f08f0744a780884bfc80 | https://github.com/inveniosoftware/invenio-access/blob/3b033a4bdc110eb2f7e9f08f0744a780884bfc80/invenio_access/ext.py#L52-L64 | train |
inveniosoftware/invenio-access | invenio_access/ext.py | _AccessState.get_action_cache | def get_action_cache(self, action_key):
"""Get action needs and excludes from cache.
.. note:: It returns the action if a cache system is defined.
:param action_key: The unique action name.
:returns: The action stored in cache or ``None``.
"""
data = None
if self.cache:
data = self.cache.get(
self.app.config['ACCESS_ACTION_CACHE_PREFIX'] +
action_key
)
return data | python | def get_action_cache(self, action_key):
"""Get action needs and excludes from cache.
.. note:: It returns the action if a cache system is defined.
:param action_key: The unique action name.
:returns: The action stored in cache or ``None``.
"""
data = None
if self.cache:
data = self.cache.get(
self.app.config['ACCESS_ACTION_CACHE_PREFIX'] +
action_key
)
return data | [
"def",
"get_action_cache",
"(",
"self",
",",
"action_key",
")",
":",
"data",
"=",
"None",
"if",
"self",
".",
"cache",
":",
"data",
"=",
"self",
".",
"cache",
".",
"get",
"(",
"self",
".",
"app",
".",
"config",
"[",
"'ACCESS_ACTION_CACHE_PREFIX'",
"]",
"+",
"action_key",
")",
"return",
"data"
] | Get action needs and excludes from cache.
.. note:: It returns the action if a cache system is defined.
:param action_key: The unique action name.
:returns: The action stored in cache or ``None``. | [
"Get",
"action",
"needs",
"and",
"excludes",
"from",
"cache",
"."
] | 3b033a4bdc110eb2f7e9f08f0744a780884bfc80 | https://github.com/inveniosoftware/invenio-access/blob/3b033a4bdc110eb2f7e9f08f0744a780884bfc80/invenio_access/ext.py#L66-L80 | train |
inveniosoftware/invenio-access | invenio_access/ext.py | _AccessState.delete_action_cache | def delete_action_cache(self, action_key):
"""Delete action needs and excludes from cache.
.. note:: It returns the action if a cache system is defined.
:param action_key: The unique action name.
"""
if self.cache:
self.cache.delete(
self.app.config['ACCESS_ACTION_CACHE_PREFIX'] +
action_key
) | python | def delete_action_cache(self, action_key):
"""Delete action needs and excludes from cache.
.. note:: It returns the action if a cache system is defined.
:param action_key: The unique action name.
"""
if self.cache:
self.cache.delete(
self.app.config['ACCESS_ACTION_CACHE_PREFIX'] +
action_key
) | [
"def",
"delete_action_cache",
"(",
"self",
",",
"action_key",
")",
":",
"if",
"self",
".",
"cache",
":",
"self",
".",
"cache",
".",
"delete",
"(",
"self",
".",
"app",
".",
"config",
"[",
"'ACCESS_ACTION_CACHE_PREFIX'",
"]",
"+",
"action_key",
")"
] | Delete action needs and excludes from cache.
.. note:: It returns the action if a cache system is defined.
:param action_key: The unique action name. | [
"Delete",
"action",
"needs",
"and",
"excludes",
"from",
"cache",
"."
] | 3b033a4bdc110eb2f7e9f08f0744a780884bfc80 | https://github.com/inveniosoftware/invenio-access/blob/3b033a4bdc110eb2f7e9f08f0744a780884bfc80/invenio_access/ext.py#L82-L93 | train |
inveniosoftware/invenio-access | invenio_access/ext.py | _AccessState.register_action | def register_action(self, action):
"""Register an action to be showed in the actions list.
.. note:: A action can't be registered two times. If it happens, then
an assert exception will be raised.
:param action: The action to be registered.
"""
assert action.value not in self.actions
self.actions[action.value] = action | python | def register_action(self, action):
"""Register an action to be showed in the actions list.
.. note:: A action can't be registered two times. If it happens, then
an assert exception will be raised.
:param action: The action to be registered.
"""
assert action.value not in self.actions
self.actions[action.value] = action | [
"def",
"register_action",
"(",
"self",
",",
"action",
")",
":",
"assert",
"action",
".",
"value",
"not",
"in",
"self",
".",
"actions",
"self",
".",
"actions",
"[",
"action",
".",
"value",
"]",
"=",
"action"
] | Register an action to be showed in the actions list.
.. note:: A action can't be registered two times. If it happens, then
an assert exception will be raised.
:param action: The action to be registered. | [
"Register",
"an",
"action",
"to",
"be",
"showed",
"in",
"the",
"actions",
"list",
"."
] | 3b033a4bdc110eb2f7e9f08f0744a780884bfc80 | https://github.com/inveniosoftware/invenio-access/blob/3b033a4bdc110eb2f7e9f08f0744a780884bfc80/invenio_access/ext.py#L95-L104 | train |
inveniosoftware/invenio-access | invenio_access/ext.py | _AccessState.register_system_role | def register_system_role(self, system_role):
"""Register a system role.
.. note:: A system role can't be registered two times. If it happens,
then an assert exception will be raised.
:param system_role: The system role to be registered.
"""
assert system_role.value not in self.system_roles
self.system_roles[system_role.value] = system_role | python | def register_system_role(self, system_role):
"""Register a system role.
.. note:: A system role can't be registered two times. If it happens,
then an assert exception will be raised.
:param system_role: The system role to be registered.
"""
assert system_role.value not in self.system_roles
self.system_roles[system_role.value] = system_role | [
"def",
"register_system_role",
"(",
"self",
",",
"system_role",
")",
":",
"assert",
"system_role",
".",
"value",
"not",
"in",
"self",
".",
"system_roles",
"self",
".",
"system_roles",
"[",
"system_role",
".",
"value",
"]",
"=",
"system_role"
] | Register a system role.
.. note:: A system role can't be registered two times. If it happens,
then an assert exception will be raised.
:param system_role: The system role to be registered. | [
"Register",
"a",
"system",
"role",
"."
] | 3b033a4bdc110eb2f7e9f08f0744a780884bfc80 | https://github.com/inveniosoftware/invenio-access/blob/3b033a4bdc110eb2f7e9f08f0744a780884bfc80/invenio_access/ext.py#L114-L123 | train |
inveniosoftware/invenio-access | invenio_access/ext.py | _AccessState.load_entry_point_system_roles | def load_entry_point_system_roles(self, entry_point_group):
"""Load system roles from an entry point group.
:param entry_point_group: The entrypoint for extensions.
"""
for ep in pkg_resources.iter_entry_points(group=entry_point_group):
self.register_system_role(ep.load()) | python | def load_entry_point_system_roles(self, entry_point_group):
"""Load system roles from an entry point group.
:param entry_point_group: The entrypoint for extensions.
"""
for ep in pkg_resources.iter_entry_points(group=entry_point_group):
self.register_system_role(ep.load()) | [
"def",
"load_entry_point_system_roles",
"(",
"self",
",",
"entry_point_group",
")",
":",
"for",
"ep",
"in",
"pkg_resources",
".",
"iter_entry_points",
"(",
"group",
"=",
"entry_point_group",
")",
":",
"self",
".",
"register_system_role",
"(",
"ep",
".",
"load",
"(",
")",
")"
] | Load system roles from an entry point group.
:param entry_point_group: The entrypoint for extensions. | [
"Load",
"system",
"roles",
"from",
"an",
"entry",
"point",
"group",
"."
] | 3b033a4bdc110eb2f7e9f08f0744a780884bfc80 | https://github.com/inveniosoftware/invenio-access/blob/3b033a4bdc110eb2f7e9f08f0744a780884bfc80/invenio_access/ext.py#L125-L131 | train |
mjj4791/python-buienradar | buienradar/__main__.py | main | def main(argv=sys.argv[1:]):
"""Parse argument and start main program."""
args = docopt(__doc__, argv=argv,
version=pkg_resources.require('buienradar')[0].version)
level = logging.ERROR
if args['-v']:
level = logging.INFO
if args['-v'] == 2:
level = logging.DEBUG
logging.basicConfig(level=level)
log = logging.getLogger(__name__)
log.info("Start...")
latitude = float(args['--latitude'])
longitude = float(args['--longitude'])
timeframe = int(args['--timeframe'])
usexml = False
if args['--usexml']:
usexml = True
result = get_data(latitude, longitude, usexml)
if result[SUCCESS]:
log.debug("Retrieved data:\n%s", result)
result = parse_data(result[CONTENT], result[RAINCONTENT],
latitude, longitude, timeframe, usexml)
log.info("result: %s", result)
print(result)
else:
log.error("Retrieving weather data was not successfull (%s)",
result[MESSAGE]) | python | def main(argv=sys.argv[1:]):
"""Parse argument and start main program."""
args = docopt(__doc__, argv=argv,
version=pkg_resources.require('buienradar')[0].version)
level = logging.ERROR
if args['-v']:
level = logging.INFO
if args['-v'] == 2:
level = logging.DEBUG
logging.basicConfig(level=level)
log = logging.getLogger(__name__)
log.info("Start...")
latitude = float(args['--latitude'])
longitude = float(args['--longitude'])
timeframe = int(args['--timeframe'])
usexml = False
if args['--usexml']:
usexml = True
result = get_data(latitude, longitude, usexml)
if result[SUCCESS]:
log.debug("Retrieved data:\n%s", result)
result = parse_data(result[CONTENT], result[RAINCONTENT],
latitude, longitude, timeframe, usexml)
log.info("result: %s", result)
print(result)
else:
log.error("Retrieving weather data was not successfull (%s)",
result[MESSAGE]) | [
"def",
"main",
"(",
"argv",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
")",
":",
"args",
"=",
"docopt",
"(",
"__doc__",
",",
"argv",
"=",
"argv",
",",
"version",
"=",
"pkg_resources",
".",
"require",
"(",
"'buienradar'",
")",
"[",
"0",
"]",
".",
"version",
")",
"level",
"=",
"logging",
".",
"ERROR",
"if",
"args",
"[",
"'-v'",
"]",
":",
"level",
"=",
"logging",
".",
"INFO",
"if",
"args",
"[",
"'-v'",
"]",
"==",
"2",
":",
"level",
"=",
"logging",
".",
"DEBUG",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"level",
")",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"log",
".",
"info",
"(",
"\"Start...\"",
")",
"latitude",
"=",
"float",
"(",
"args",
"[",
"'--latitude'",
"]",
")",
"longitude",
"=",
"float",
"(",
"args",
"[",
"'--longitude'",
"]",
")",
"timeframe",
"=",
"int",
"(",
"args",
"[",
"'--timeframe'",
"]",
")",
"usexml",
"=",
"False",
"if",
"args",
"[",
"'--usexml'",
"]",
":",
"usexml",
"=",
"True",
"result",
"=",
"get_data",
"(",
"latitude",
",",
"longitude",
",",
"usexml",
")",
"if",
"result",
"[",
"SUCCESS",
"]",
":",
"log",
".",
"debug",
"(",
"\"Retrieved data:\\n%s\"",
",",
"result",
")",
"result",
"=",
"parse_data",
"(",
"result",
"[",
"CONTENT",
"]",
",",
"result",
"[",
"RAINCONTENT",
"]",
",",
"latitude",
",",
"longitude",
",",
"timeframe",
",",
"usexml",
")",
"log",
".",
"info",
"(",
"\"result: %s\"",
",",
"result",
")",
"print",
"(",
"result",
")",
"else",
":",
"log",
".",
"error",
"(",
"\"Retrieving weather data was not successfull (%s)\"",
",",
"result",
"[",
"MESSAGE",
"]",
")"
] | Parse argument and start main program. | [
"Parse",
"argument",
"and",
"start",
"main",
"program",
"."
] | a70436f54e007ce921d5210cb296cf3e4adf9d09 | https://github.com/mjj4791/python-buienradar/blob/a70436f54e007ce921d5210cb296cf3e4adf9d09/buienradar/__main__.py#L29-L62 | train |
idlesign/steampak | steampak/libsteam/resources/stats.py | Achievement.global_unlock_percent | def global_unlock_percent(self):
"""Global achievement unlock percent.
:rtype: float
"""
percent = CRef.cfloat()
result = self._iface.get_ach_progress(self.name, percent)
if not result:
return 0.0
return float(percent) | python | def global_unlock_percent(self):
"""Global achievement unlock percent.
:rtype: float
"""
percent = CRef.cfloat()
result = self._iface.get_ach_progress(self.name, percent)
if not result:
return 0.0
return float(percent) | [
"def",
"global_unlock_percent",
"(",
"self",
")",
":",
"percent",
"=",
"CRef",
".",
"cfloat",
"(",
")",
"result",
"=",
"self",
".",
"_iface",
".",
"get_ach_progress",
"(",
"self",
".",
"name",
",",
"percent",
")",
"if",
"not",
"result",
":",
"return",
"0.0",
"return",
"float",
"(",
"percent",
")"
] | Global achievement unlock percent.
:rtype: float | [
"Global",
"achievement",
"unlock",
"percent",
"."
] | cb3f2c737e272b0360802d947e388df7e34f50f3 | https://github.com/idlesign/steampak/blob/cb3f2c737e272b0360802d947e388df7e34f50f3/steampak/libsteam/resources/stats.py#L56-L67 | train |
idlesign/steampak | steampak/libsteam/resources/stats.py | Achievement.unlocked | def unlocked(self):
"""``True`` if achievement is unlocked.
:rtype: bool
"""
achieved = CRef.cbool()
result = self._iface.get_ach(self.name, achieved)
if not result:
return False
return bool(achieved) | python | def unlocked(self):
"""``True`` if achievement is unlocked.
:rtype: bool
"""
achieved = CRef.cbool()
result = self._iface.get_ach(self.name, achieved)
if not result:
return False
return bool(achieved) | [
"def",
"unlocked",
"(",
"self",
")",
":",
"achieved",
"=",
"CRef",
".",
"cbool",
"(",
")",
"result",
"=",
"self",
".",
"_iface",
".",
"get_ach",
"(",
"self",
".",
"name",
",",
"achieved",
")",
"if",
"not",
"result",
":",
"return",
"False",
"return",
"bool",
"(",
"achieved",
")"
] | ``True`` if achievement is unlocked.
:rtype: bool | [
"True",
"if",
"achievement",
"is",
"unlocked",
"."
] | cb3f2c737e272b0360802d947e388df7e34f50f3 | https://github.com/idlesign/steampak/blob/cb3f2c737e272b0360802d947e388df7e34f50f3/steampak/libsteam/resources/stats.py#L78-L89 | train |
idlesign/steampak | steampak/libsteam/resources/stats.py | Achievement.unlock | def unlock(self, store=True):
"""Unlocks the achievement.
:param bool store: Whether to send data to server immediately (as to get overlay notification).
:rtype: bool
"""
result = self._iface.ach_unlock(self.name)
result and store and self._store()
return result | python | def unlock(self, store=True):
"""Unlocks the achievement.
:param bool store: Whether to send data to server immediately (as to get overlay notification).
:rtype: bool
"""
result = self._iface.ach_unlock(self.name)
result and store and self._store()
return result | [
"def",
"unlock",
"(",
"self",
",",
"store",
"=",
"True",
")",
":",
"result",
"=",
"self",
".",
"_iface",
".",
"ach_unlock",
"(",
"self",
".",
"name",
")",
"result",
"and",
"store",
"and",
"self",
".",
"_store",
"(",
")",
"return",
"result"
] | Unlocks the achievement.
:param bool store: Whether to send data to server immediately (as to get overlay notification).
:rtype: bool | [
"Unlocks",
"the",
"achievement",
"."
] | cb3f2c737e272b0360802d947e388df7e34f50f3 | https://github.com/idlesign/steampak/blob/cb3f2c737e272b0360802d947e388df7e34f50f3/steampak/libsteam/resources/stats.py#L91-L101 | train |
mjj4791/python-buienradar | buienradar/buienradar_xml.py | __parse_ws_data | def __parse_ws_data(content, latitude=52.091579, longitude=5.119734):
"""Parse the buienradar xml and rain data."""
log.info("Parse ws data: latitude: %s, longitude: %s", latitude, longitude)
result = {SUCCESS: False, MESSAGE: None, DATA: None}
# convert the xml data into a dictionary:
try:
xmldata = xmltodict.parse(content)[__BRROOT]
except (xmltodict.expat.ExpatError, KeyError):
result[MESSAGE] = "Unable to parse content as xml."
log.exception(result[MESSAGE])
return result
# select the nearest weather station
loc_data = __select_nearest_ws(xmldata, latitude, longitude)
# process current weather data from selected weatherstation
if not loc_data:
result[MESSAGE] = 'No location selected.'
return result
if not __is_valid(loc_data):
result[MESSAGE] = 'Location data is invalid.'
return result
# add distance to weatherstation
log.debug("Raw location data: %s", loc_data)
result[DISTANCE] = __get_ws_distance(loc_data, latitude, longitude)
result = __parse_loc_data(loc_data, result)
# extract weather forecast
try:
fc_data = xmldata[__BRWEERGEGEVENS][__BRVERWACHTING]
except (xmltodict.expat.ExpatError, KeyError):
result[MESSAGE] = 'Unable to extract forecast data.'
log.exception(result[MESSAGE])
return result
if fc_data:
# result = __parse_fc_data(fc_data, result)
log.debug("Raw forecast data: %s", fc_data)
# pylint: disable=unsupported-assignment-operation
result[DATA][FORECAST] = __parse_fc_data(fc_data)
return result | python | def __parse_ws_data(content, latitude=52.091579, longitude=5.119734):
"""Parse the buienradar xml and rain data."""
log.info("Parse ws data: latitude: %s, longitude: %s", latitude, longitude)
result = {SUCCESS: False, MESSAGE: None, DATA: None}
# convert the xml data into a dictionary:
try:
xmldata = xmltodict.parse(content)[__BRROOT]
except (xmltodict.expat.ExpatError, KeyError):
result[MESSAGE] = "Unable to parse content as xml."
log.exception(result[MESSAGE])
return result
# select the nearest weather station
loc_data = __select_nearest_ws(xmldata, latitude, longitude)
# process current weather data from selected weatherstation
if not loc_data:
result[MESSAGE] = 'No location selected.'
return result
if not __is_valid(loc_data):
result[MESSAGE] = 'Location data is invalid.'
return result
# add distance to weatherstation
log.debug("Raw location data: %s", loc_data)
result[DISTANCE] = __get_ws_distance(loc_data, latitude, longitude)
result = __parse_loc_data(loc_data, result)
# extract weather forecast
try:
fc_data = xmldata[__BRWEERGEGEVENS][__BRVERWACHTING]
except (xmltodict.expat.ExpatError, KeyError):
result[MESSAGE] = 'Unable to extract forecast data.'
log.exception(result[MESSAGE])
return result
if fc_data:
# result = __parse_fc_data(fc_data, result)
log.debug("Raw forecast data: %s", fc_data)
# pylint: disable=unsupported-assignment-operation
result[DATA][FORECAST] = __parse_fc_data(fc_data)
return result | [
"def",
"__parse_ws_data",
"(",
"content",
",",
"latitude",
"=",
"52.091579",
",",
"longitude",
"=",
"5.119734",
")",
":",
"log",
".",
"info",
"(",
"\"Parse ws data: latitude: %s, longitude: %s\"",
",",
"latitude",
",",
"longitude",
")",
"result",
"=",
"{",
"SUCCESS",
":",
"False",
",",
"MESSAGE",
":",
"None",
",",
"DATA",
":",
"None",
"}",
"try",
":",
"xmldata",
"=",
"xmltodict",
".",
"parse",
"(",
"content",
")",
"[",
"__BRROOT",
"]",
"except",
"(",
"xmltodict",
".",
"expat",
".",
"ExpatError",
",",
"KeyError",
")",
":",
"result",
"[",
"MESSAGE",
"]",
"=",
"\"Unable to parse content as xml.\"",
"log",
".",
"exception",
"(",
"result",
"[",
"MESSAGE",
"]",
")",
"return",
"result",
"loc_data",
"=",
"__select_nearest_ws",
"(",
"xmldata",
",",
"latitude",
",",
"longitude",
")",
"if",
"not",
"loc_data",
":",
"result",
"[",
"MESSAGE",
"]",
"=",
"'No location selected.'",
"return",
"result",
"if",
"not",
"__is_valid",
"(",
"loc_data",
")",
":",
"result",
"[",
"MESSAGE",
"]",
"=",
"'Location data is invalid.'",
"return",
"result",
"log",
".",
"debug",
"(",
"\"Raw location data: %s\"",
",",
"loc_data",
")",
"result",
"[",
"DISTANCE",
"]",
"=",
"__get_ws_distance",
"(",
"loc_data",
",",
"latitude",
",",
"longitude",
")",
"result",
"=",
"__parse_loc_data",
"(",
"loc_data",
",",
"result",
")",
"try",
":",
"fc_data",
"=",
"xmldata",
"[",
"__BRWEERGEGEVENS",
"]",
"[",
"__BRVERWACHTING",
"]",
"except",
"(",
"xmltodict",
".",
"expat",
".",
"ExpatError",
",",
"KeyError",
")",
":",
"result",
"[",
"MESSAGE",
"]",
"=",
"'Unable to extract forecast data.'",
"log",
".",
"exception",
"(",
"result",
"[",
"MESSAGE",
"]",
")",
"return",
"result",
"if",
"fc_data",
":",
"log",
".",
"debug",
"(",
"\"Raw forecast data: %s\"",
",",
"fc_data",
")",
"result",
"[",
"DATA",
"]",
"[",
"FORECAST",
"]",
"=",
"__parse_fc_data",
"(",
"fc_data",
")",
"return",
"result"
] | Parse the buienradar xml and rain data. | [
"Parse",
"the",
"buienradar",
"xml",
"and",
"rain",
"data",
"."
] | a70436f54e007ce921d5210cb296cf3e4adf9d09 | https://github.com/mjj4791/python-buienradar/blob/a70436f54e007ce921d5210cb296cf3e4adf9d09/buienradar/buienradar_xml.py#L253-L296 | train |
mjj4791/python-buienradar | buienradar/buienradar_xml.py | __parse_loc_data | def __parse_loc_data(loc_data, result):
"""Parse the xml data from selected weatherstation."""
result[DATA] = {ATTRIBUTION: ATTRIBUTION_INFO,
FORECAST: [],
PRECIPITATION_FORECAST: None}
for key, [value, func] in SENSOR_TYPES.items():
result[DATA][key] = None
try:
from buienradar.buienradar import condition_from_code
sens_data = loc_data[value]
if key == CONDITION:
# update weather symbol & status text
code = sens_data[__BRID][:1]
result[DATA][CONDITION] = condition_from_code(code)
result[DATA][CONDITION][IMAGE] = sens_data[__BRTEXT]
else:
if key == STATIONNAME:
name = sens_data[__BRTEXT].replace("Meetstation", "")
name = name.strip()
name += " (%s)" % loc_data[__BRSTATIONCODE]
result[DATA][key] = name
else:
# update all other data
if func is not None:
result[DATA][key] = func(sens_data)
else:
result[DATA][key] = sens_data
except KeyError:
if result[MESSAGE] is None:
result[MESSAGE] = "Missing key(s) in br data: "
result[MESSAGE] += "%s " % value
log.warning("Data element with key='%s' "
"not loaded from br data!", key)
result[SUCCESS] = True
return result | python | def __parse_loc_data(loc_data, result):
"""Parse the xml data from selected weatherstation."""
result[DATA] = {ATTRIBUTION: ATTRIBUTION_INFO,
FORECAST: [],
PRECIPITATION_FORECAST: None}
for key, [value, func] in SENSOR_TYPES.items():
result[DATA][key] = None
try:
from buienradar.buienradar import condition_from_code
sens_data = loc_data[value]
if key == CONDITION:
# update weather symbol & status text
code = sens_data[__BRID][:1]
result[DATA][CONDITION] = condition_from_code(code)
result[DATA][CONDITION][IMAGE] = sens_data[__BRTEXT]
else:
if key == STATIONNAME:
name = sens_data[__BRTEXT].replace("Meetstation", "")
name = name.strip()
name += " (%s)" % loc_data[__BRSTATIONCODE]
result[DATA][key] = name
else:
# update all other data
if func is not None:
result[DATA][key] = func(sens_data)
else:
result[DATA][key] = sens_data
except KeyError:
if result[MESSAGE] is None:
result[MESSAGE] = "Missing key(s) in br data: "
result[MESSAGE] += "%s " % value
log.warning("Data element with key='%s' "
"not loaded from br data!", key)
result[SUCCESS] = True
return result | [
"def",
"__parse_loc_data",
"(",
"loc_data",
",",
"result",
")",
":",
"result",
"[",
"DATA",
"]",
"=",
"{",
"ATTRIBUTION",
":",
"ATTRIBUTION_INFO",
",",
"FORECAST",
":",
"[",
"]",
",",
"PRECIPITATION_FORECAST",
":",
"None",
"}",
"for",
"key",
",",
"[",
"value",
",",
"func",
"]",
"in",
"SENSOR_TYPES",
".",
"items",
"(",
")",
":",
"result",
"[",
"DATA",
"]",
"[",
"key",
"]",
"=",
"None",
"try",
":",
"from",
"buienradar",
".",
"buienradar",
"import",
"condition_from_code",
"sens_data",
"=",
"loc_data",
"[",
"value",
"]",
"if",
"key",
"==",
"CONDITION",
":",
"code",
"=",
"sens_data",
"[",
"__BRID",
"]",
"[",
":",
"1",
"]",
"result",
"[",
"DATA",
"]",
"[",
"CONDITION",
"]",
"=",
"condition_from_code",
"(",
"code",
")",
"result",
"[",
"DATA",
"]",
"[",
"CONDITION",
"]",
"[",
"IMAGE",
"]",
"=",
"sens_data",
"[",
"__BRTEXT",
"]",
"else",
":",
"if",
"key",
"==",
"STATIONNAME",
":",
"name",
"=",
"sens_data",
"[",
"__BRTEXT",
"]",
".",
"replace",
"(",
"\"Meetstation\"",
",",
"\"\"",
")",
"name",
"=",
"name",
".",
"strip",
"(",
")",
"name",
"+=",
"\" (%s)\"",
"%",
"loc_data",
"[",
"__BRSTATIONCODE",
"]",
"result",
"[",
"DATA",
"]",
"[",
"key",
"]",
"=",
"name",
"else",
":",
"if",
"func",
"is",
"not",
"None",
":",
"result",
"[",
"DATA",
"]",
"[",
"key",
"]",
"=",
"func",
"(",
"sens_data",
")",
"else",
":",
"result",
"[",
"DATA",
"]",
"[",
"key",
"]",
"=",
"sens_data",
"except",
"KeyError",
":",
"if",
"result",
"[",
"MESSAGE",
"]",
"is",
"None",
":",
"result",
"[",
"MESSAGE",
"]",
"=",
"\"Missing key(s) in br data: \"",
"result",
"[",
"MESSAGE",
"]",
"+=",
"\"%s \"",
"%",
"value",
"log",
".",
"warning",
"(",
"\"Data element with key='%s' \"",
"\"not loaded from br data!\"",
",",
"key",
")",
"result",
"[",
"SUCCESS",
"]",
"=",
"True",
"return",
"result"
] | Parse the xml data from selected weatherstation. | [
"Parse",
"the",
"xml",
"data",
"from",
"selected",
"weatherstation",
"."
] | a70436f54e007ce921d5210cb296cf3e4adf9d09 | https://github.com/mjj4791/python-buienradar/blob/a70436f54e007ce921d5210cb296cf3e4adf9d09/buienradar/buienradar_xml.py#L357-L392 | train |
mjj4791/python-buienradar | buienradar/buienradar_xml.py | __parse_fc_data | def __parse_fc_data(fc_data):
"""Parse the forecast data from the xml section."""
from buienradar.buienradar import condition_from_code
fc = []
for daycnt in range(1, 6):
daysection = __BRDAYFC % daycnt
if daysection in fc_data:
tmpsect = fc_data[daysection]
fcdatetime = datetime.now(pytz.timezone(__TIMEZONE))
fcdatetime = fcdatetime.replace(hour=12,
minute=0,
second=0,
microsecond=0)
# add daycnt days
fcdatetime = fcdatetime + timedelta(days=daycnt)
code = tmpsect.get(__BRICOON, []).get(__BRID)
fcdata = {
CONDITION: condition_from_code(code),
TEMPERATURE: __get_float(tmpsect, __BRMAXTEMP),
MIN_TEMP: __get_float(tmpsect, __BRMINTEMP),
MAX_TEMP: __get_float(tmpsect, __BRMAXTEMP),
SUN_CHANCE: __get_int(tmpsect, __BRKANSZON),
RAIN_CHANCE: __get_int(tmpsect, __BRKANSREGEN),
RAIN: __get_float(tmpsect, __BRMAXMMREGEN),
SNOW: __get_float(tmpsect, __BRSNEEUWCMS),
WINDFORCE: __get_int(tmpsect, __BRWINDKRACHT),
DATETIME: fcdatetime,
}
fcdata[CONDITION][IMAGE] = tmpsect.get(__BRICOON, []).get(__BRTEXT)
fc.append(fcdata)
return fc | python | def __parse_fc_data(fc_data):
"""Parse the forecast data from the xml section."""
from buienradar.buienradar import condition_from_code
fc = []
for daycnt in range(1, 6):
daysection = __BRDAYFC % daycnt
if daysection in fc_data:
tmpsect = fc_data[daysection]
fcdatetime = datetime.now(pytz.timezone(__TIMEZONE))
fcdatetime = fcdatetime.replace(hour=12,
minute=0,
second=0,
microsecond=0)
# add daycnt days
fcdatetime = fcdatetime + timedelta(days=daycnt)
code = tmpsect.get(__BRICOON, []).get(__BRID)
fcdata = {
CONDITION: condition_from_code(code),
TEMPERATURE: __get_float(tmpsect, __BRMAXTEMP),
MIN_TEMP: __get_float(tmpsect, __BRMINTEMP),
MAX_TEMP: __get_float(tmpsect, __BRMAXTEMP),
SUN_CHANCE: __get_int(tmpsect, __BRKANSZON),
RAIN_CHANCE: __get_int(tmpsect, __BRKANSREGEN),
RAIN: __get_float(tmpsect, __BRMAXMMREGEN),
SNOW: __get_float(tmpsect, __BRSNEEUWCMS),
WINDFORCE: __get_int(tmpsect, __BRWINDKRACHT),
DATETIME: fcdatetime,
}
fcdata[CONDITION][IMAGE] = tmpsect.get(__BRICOON, []).get(__BRTEXT)
fc.append(fcdata)
return fc | [
"def",
"__parse_fc_data",
"(",
"fc_data",
")",
":",
"from",
"buienradar",
".",
"buienradar",
"import",
"condition_from_code",
"fc",
"=",
"[",
"]",
"for",
"daycnt",
"in",
"range",
"(",
"1",
",",
"6",
")",
":",
"daysection",
"=",
"__BRDAYFC",
"%",
"daycnt",
"if",
"daysection",
"in",
"fc_data",
":",
"tmpsect",
"=",
"fc_data",
"[",
"daysection",
"]",
"fcdatetime",
"=",
"datetime",
".",
"now",
"(",
"pytz",
".",
"timezone",
"(",
"__TIMEZONE",
")",
")",
"fcdatetime",
"=",
"fcdatetime",
".",
"replace",
"(",
"hour",
"=",
"12",
",",
"minute",
"=",
"0",
",",
"second",
"=",
"0",
",",
"microsecond",
"=",
"0",
")",
"fcdatetime",
"=",
"fcdatetime",
"+",
"timedelta",
"(",
"days",
"=",
"daycnt",
")",
"code",
"=",
"tmpsect",
".",
"get",
"(",
"__BRICOON",
",",
"[",
"]",
")",
".",
"get",
"(",
"__BRID",
")",
"fcdata",
"=",
"{",
"CONDITION",
":",
"condition_from_code",
"(",
"code",
")",
",",
"TEMPERATURE",
":",
"__get_float",
"(",
"tmpsect",
",",
"__BRMAXTEMP",
")",
",",
"MIN_TEMP",
":",
"__get_float",
"(",
"tmpsect",
",",
"__BRMINTEMP",
")",
",",
"MAX_TEMP",
":",
"__get_float",
"(",
"tmpsect",
",",
"__BRMAXTEMP",
")",
",",
"SUN_CHANCE",
":",
"__get_int",
"(",
"tmpsect",
",",
"__BRKANSZON",
")",
",",
"RAIN_CHANCE",
":",
"__get_int",
"(",
"tmpsect",
",",
"__BRKANSREGEN",
")",
",",
"RAIN",
":",
"__get_float",
"(",
"tmpsect",
",",
"__BRMAXMMREGEN",
")",
",",
"SNOW",
":",
"__get_float",
"(",
"tmpsect",
",",
"__BRSNEEUWCMS",
")",
",",
"WINDFORCE",
":",
"__get_int",
"(",
"tmpsect",
",",
"__BRWINDKRACHT",
")",
",",
"DATETIME",
":",
"fcdatetime",
",",
"}",
"fcdata",
"[",
"CONDITION",
"]",
"[",
"IMAGE",
"]",
"=",
"tmpsect",
".",
"get",
"(",
"__BRICOON",
",",
"[",
"]",
")",
".",
"get",
"(",
"__BRTEXT",
")",
"fc",
".",
"append",
"(",
"fcdata",
")",
"return",
"fc"
] | Parse the forecast data from the xml section. | [
"Parse",
"the",
"forecast",
"data",
"from",
"the",
"xml",
"section",
"."
] | a70436f54e007ce921d5210cb296cf3e4adf9d09 | https://github.com/mjj4791/python-buienradar/blob/a70436f54e007ce921d5210cb296cf3e4adf9d09/buienradar/buienradar_xml.py#L395-L426 | train |
mjj4791/python-buienradar | buienradar/buienradar_xml.py | __get_ws_distance | def __get_ws_distance(wstation, latitude, longitude):
"""Get the distance to the weatherstation from wstation section of xml.
wstation: weerstation section of buienradar xml (dict)
latitude: our latitude
longitude: our longitude
"""
if wstation:
try:
wslat = float(wstation[__BRLAT])
wslon = float(wstation[__BRLON])
dist = vincenty((latitude, longitude), (wslat, wslon))
log.debug("calc distance: %s (latitude: %s, longitude: "
"%s, wslat: %s, wslon: %s)", dist, latitude,
longitude, wslat, wslon)
return dist
except (ValueError, TypeError, KeyError):
# value does not exist, or is not a float
return None
else:
return None | python | def __get_ws_distance(wstation, latitude, longitude):
"""Get the distance to the weatherstation from wstation section of xml.
wstation: weerstation section of buienradar xml (dict)
latitude: our latitude
longitude: our longitude
"""
if wstation:
try:
wslat = float(wstation[__BRLAT])
wslon = float(wstation[__BRLON])
dist = vincenty((latitude, longitude), (wslat, wslon))
log.debug("calc distance: %s (latitude: %s, longitude: "
"%s, wslat: %s, wslon: %s)", dist, latitude,
longitude, wslat, wslon)
return dist
except (ValueError, TypeError, KeyError):
# value does not exist, or is not a float
return None
else:
return None | [
"def",
"__get_ws_distance",
"(",
"wstation",
",",
"latitude",
",",
"longitude",
")",
":",
"if",
"wstation",
":",
"try",
":",
"wslat",
"=",
"float",
"(",
"wstation",
"[",
"__BRLAT",
"]",
")",
"wslon",
"=",
"float",
"(",
"wstation",
"[",
"__BRLON",
"]",
")",
"dist",
"=",
"vincenty",
"(",
"(",
"latitude",
",",
"longitude",
")",
",",
"(",
"wslat",
",",
"wslon",
")",
")",
"log",
".",
"debug",
"(",
"\"calc distance: %s (latitude: %s, longitude: \"",
"\"%s, wslat: %s, wslon: %s)\"",
",",
"dist",
",",
"latitude",
",",
"longitude",
",",
"wslat",
",",
"wslon",
")",
"return",
"dist",
"except",
"(",
"ValueError",
",",
"TypeError",
",",
"KeyError",
")",
":",
"return",
"None",
"else",
":",
"return",
"None"
] | Get the distance to the weatherstation from wstation section of xml.
wstation: weerstation section of buienradar xml (dict)
latitude: our latitude
longitude: our longitude | [
"Get",
"the",
"distance",
"to",
"the",
"weatherstation",
"from",
"wstation",
"section",
"of",
"xml",
"."
] | a70436f54e007ce921d5210cb296cf3e4adf9d09 | https://github.com/mjj4791/python-buienradar/blob/a70436f54e007ce921d5210cb296cf3e4adf9d09/buienradar/buienradar_xml.py#L445-L466 | train |
BD2KGenomics/protect | src/protect/binding_prediction/mhcii.py | predict_mhcii_binding | def predict_mhcii_binding(job, peptfile, allele, univ_options, mhcii_options):
"""
Predict binding for each peptide in `peptfile` to `allele` using the IEDB mhcii binding
prediction tool.
:param toil.fileStore.FileID peptfile: The input peptide fasta
:param str allele: Allele to predict binding against
:param dict univ_options: Dict of universal options used by almost all tools
:param dict mhcii_options: Options specific to mhcii binding prediction
:return: tuple of fsID for file containing the predictions and the predictor used
:rtype: tuple(toil.fileStore.FileID, str|None)
"""
work_dir = os.getcwd()
input_files = {
'peptfile.faa': peptfile}
input_files = get_files_from_filestore(job, input_files, work_dir, docker=True)
peptides = read_peptide_file(os.path.join(os.getcwd(), 'peptfile.faa'))
parameters = [mhcii_options['pred'],
allele,
input_files['peptfile.faa']]
if not peptides:
return job.fileStore.writeGlobalFile(job.fileStore.getLocalTempFile()), None
with open('/'.join([work_dir, 'predictions.tsv']), 'w') as predfile:
docker_call(tool='mhcii', tool_parameters=parameters, work_dir=work_dir,
dockerhub=univ_options['dockerhub'], outfile=predfile, interactive=True,
tool_version=mhcii_options['version'])
run_netmhciipan = True
predictor = None
with open(predfile.name, 'r') as predfile:
for line in predfile:
if not line.startswith('HLA'):
continue
if line.strip().split('\t')[5] == 'NetMHCIIpan':
break
# If the predictor type is sturniolo then it needs to be processed differently
elif line.strip().split('\t')[5] == 'Sturniolo':
predictor = 'Sturniolo'
else:
predictor = 'Consensus'
run_netmhciipan = False
break
if run_netmhciipan:
netmhciipan = job.addChildJobFn(predict_netmhcii_binding, peptfile, allele, univ_options,
mhcii_options['netmhciipan'], disk='100M', memory='100M',
cores=1)
job.fileStore.logToMaster('Ran mhcii on %s:%s successfully'
% (univ_options['patient'], allele))
return netmhciipan.rv()
else:
output_file = job.fileStore.writeGlobalFile(predfile.name)
job.fileStore.logToMaster('Ran mhcii on %s:%s successfully'
% (univ_options['patient'], allele))
return output_file, predictor | python | def predict_mhcii_binding(job, peptfile, allele, univ_options, mhcii_options):
"""
Predict binding for each peptide in `peptfile` to `allele` using the IEDB mhcii binding
prediction tool.
:param toil.fileStore.FileID peptfile: The input peptide fasta
:param str allele: Allele to predict binding against
:param dict univ_options: Dict of universal options used by almost all tools
:param dict mhcii_options: Options specific to mhcii binding prediction
:return: tuple of fsID for file containing the predictions and the predictor used
:rtype: tuple(toil.fileStore.FileID, str|None)
"""
work_dir = os.getcwd()
input_files = {
'peptfile.faa': peptfile}
input_files = get_files_from_filestore(job, input_files, work_dir, docker=True)
peptides = read_peptide_file(os.path.join(os.getcwd(), 'peptfile.faa'))
parameters = [mhcii_options['pred'],
allele,
input_files['peptfile.faa']]
if not peptides:
return job.fileStore.writeGlobalFile(job.fileStore.getLocalTempFile()), None
with open('/'.join([work_dir, 'predictions.tsv']), 'w') as predfile:
docker_call(tool='mhcii', tool_parameters=parameters, work_dir=work_dir,
dockerhub=univ_options['dockerhub'], outfile=predfile, interactive=True,
tool_version=mhcii_options['version'])
run_netmhciipan = True
predictor = None
with open(predfile.name, 'r') as predfile:
for line in predfile:
if not line.startswith('HLA'):
continue
if line.strip().split('\t')[5] == 'NetMHCIIpan':
break
# If the predictor type is sturniolo then it needs to be processed differently
elif line.strip().split('\t')[5] == 'Sturniolo':
predictor = 'Sturniolo'
else:
predictor = 'Consensus'
run_netmhciipan = False
break
if run_netmhciipan:
netmhciipan = job.addChildJobFn(predict_netmhcii_binding, peptfile, allele, univ_options,
mhcii_options['netmhciipan'], disk='100M', memory='100M',
cores=1)
job.fileStore.logToMaster('Ran mhcii on %s:%s successfully'
% (univ_options['patient'], allele))
return netmhciipan.rv()
else:
output_file = job.fileStore.writeGlobalFile(predfile.name)
job.fileStore.logToMaster('Ran mhcii on %s:%s successfully'
% (univ_options['patient'], allele))
return output_file, predictor | [
"def",
"predict_mhcii_binding",
"(",
"job",
",",
"peptfile",
",",
"allele",
",",
"univ_options",
",",
"mhcii_options",
")",
":",
"work_dir",
"=",
"os",
".",
"getcwd",
"(",
")",
"input_files",
"=",
"{",
"'peptfile.faa'",
":",
"peptfile",
"}",
"input_files",
"=",
"get_files_from_filestore",
"(",
"job",
",",
"input_files",
",",
"work_dir",
",",
"docker",
"=",
"True",
")",
"peptides",
"=",
"read_peptide_file",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"'peptfile.faa'",
")",
")",
"parameters",
"=",
"[",
"mhcii_options",
"[",
"'pred'",
"]",
",",
"allele",
",",
"input_files",
"[",
"'peptfile.faa'",
"]",
"]",
"if",
"not",
"peptides",
":",
"return",
"job",
".",
"fileStore",
".",
"writeGlobalFile",
"(",
"job",
".",
"fileStore",
".",
"getLocalTempFile",
"(",
")",
")",
",",
"None",
"with",
"open",
"(",
"'/'",
".",
"join",
"(",
"[",
"work_dir",
",",
"'predictions.tsv'",
"]",
")",
",",
"'w'",
")",
"as",
"predfile",
":",
"docker_call",
"(",
"tool",
"=",
"'mhcii'",
",",
"tool_parameters",
"=",
"parameters",
",",
"work_dir",
"=",
"work_dir",
",",
"dockerhub",
"=",
"univ_options",
"[",
"'dockerhub'",
"]",
",",
"outfile",
"=",
"predfile",
",",
"interactive",
"=",
"True",
",",
"tool_version",
"=",
"mhcii_options",
"[",
"'version'",
"]",
")",
"run_netmhciipan",
"=",
"True",
"predictor",
"=",
"None",
"with",
"open",
"(",
"predfile",
".",
"name",
",",
"'r'",
")",
"as",
"predfile",
":",
"for",
"line",
"in",
"predfile",
":",
"if",
"not",
"line",
".",
"startswith",
"(",
"'HLA'",
")",
":",
"continue",
"if",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'\\t'",
")",
"[",
"5",
"]",
"==",
"'NetMHCIIpan'",
":",
"break",
"elif",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'\\t'",
")",
"[",
"5",
"]",
"==",
"'Sturniolo'",
":",
"predictor",
"=",
"'Sturniolo'",
"else",
":",
"predictor",
"=",
"'Consensus'",
"run_netmhciipan",
"=",
"False",
"break",
"if",
"run_netmhciipan",
":",
"netmhciipan",
"=",
"job",
".",
"addChildJobFn",
"(",
"predict_netmhcii_binding",
",",
"peptfile",
",",
"allele",
",",
"univ_options",
",",
"mhcii_options",
"[",
"'netmhciipan'",
"]",
",",
"disk",
"=",
"'100M'",
",",
"memory",
"=",
"'100M'",
",",
"cores",
"=",
"1",
")",
"job",
".",
"fileStore",
".",
"logToMaster",
"(",
"'Ran mhcii on %s:%s successfully'",
"%",
"(",
"univ_options",
"[",
"'patient'",
"]",
",",
"allele",
")",
")",
"return",
"netmhciipan",
".",
"rv",
"(",
")",
"else",
":",
"output_file",
"=",
"job",
".",
"fileStore",
".",
"writeGlobalFile",
"(",
"predfile",
".",
"name",
")",
"job",
".",
"fileStore",
".",
"logToMaster",
"(",
"'Ran mhcii on %s:%s successfully'",
"%",
"(",
"univ_options",
"[",
"'patient'",
"]",
",",
"allele",
")",
")",
"return",
"output_file",
",",
"predictor"
] | Predict binding for each peptide in `peptfile` to `allele` using the IEDB mhcii binding
prediction tool.
:param toil.fileStore.FileID peptfile: The input peptide fasta
:param str allele: Allele to predict binding against
:param dict univ_options: Dict of universal options used by almost all tools
:param dict mhcii_options: Options specific to mhcii binding prediction
:return: tuple of fsID for file containing the predictions and the predictor used
:rtype: tuple(toil.fileStore.FileID, str|None) | [
"Predict",
"binding",
"for",
"each",
"peptide",
"in",
"peptfile",
"to",
"allele",
"using",
"the",
"IEDB",
"mhcii",
"binding",
"prediction",
"tool",
"."
] | 06310682c50dcf8917b912c8e551299ff7ee41ce | https://github.com/BD2KGenomics/protect/blob/06310682c50dcf8917b912c8e551299ff7ee41ce/src/protect/binding_prediction/mhcii.py#L24-L76 | train |
BD2KGenomics/protect | src/protect/binding_prediction/mhcii.py | predict_netmhcii_binding | def predict_netmhcii_binding(job, peptfile, allele, univ_options, netmhciipan_options):
"""
Predict binding for each peptide in `peptfile` to `allele` using netMHCIIpan.
:param toil.fileStore.FileID peptfile: The input peptide fasta
:param str allele: Allele to predict binding against
:param dict univ_options: Dict of universal options used by almost all tools
:param dict netmhciipan_options: Options specific to netmhciipan binding prediction
:return: tuple of fsID for file containing the predictions and the predictor used (netMHCIIpan)
:rtype: tuple(toil.fileStore.FileID, str)
"""
work_dir = os.getcwd()
input_files = {
'peptfile.faa': peptfile}
input_files = get_files_from_filestore(job, input_files, work_dir, docker=True)
peptides = read_peptide_file(os.path.join(os.getcwd(), 'peptfile.faa'))
if not peptides:
return job.fileStore.writeGlobalFile(job.fileStore.getLocalTempFile()), None
# netMHCIIpan accepts differently formatted alleles so we need to modify the input alleles
if allele.startswith('HLA-DQA') or allele.startswith('HLA-DPA'):
allele = re.sub(r'[*:]', '', allele)
allele = re.sub(r'/', '-', allele)
elif allele.startswith('HLA-DRB'):
allele = re.sub(r':', '', allele)
allele = re.sub(r'\*', '_', allele)
allele = allele.lstrip('HLA-')
else:
raise RuntimeError('Unknown allele seen')
parameters = ['-a', allele,
'-xls', '1',
'-xlsfile', 'predictions.tsv',
'-f', input_files['peptfile.faa']]
# netMHC writes a lot of useless stuff to sys.stdout so we open /dev/null and dump output there.
with open(os.devnull, 'w') as output_catcher:
docker_call(tool='netmhciipan', tool_parameters=parameters, work_dir=work_dir,
dockerhub=univ_options['dockerhub'], outfile=output_catcher,
tool_version=netmhciipan_options['version'])
output_file = job.fileStore.writeGlobalFile('/'.join([work_dir, 'predictions.tsv']))
job.fileStore.logToMaster('Ran netmhciipan on %s successfully' % allele)
return output_file, 'netMHCIIpan' | python | def predict_netmhcii_binding(job, peptfile, allele, univ_options, netmhciipan_options):
"""
Predict binding for each peptide in `peptfile` to `allele` using netMHCIIpan.
:param toil.fileStore.FileID peptfile: The input peptide fasta
:param str allele: Allele to predict binding against
:param dict univ_options: Dict of universal options used by almost all tools
:param dict netmhciipan_options: Options specific to netmhciipan binding prediction
:return: tuple of fsID for file containing the predictions and the predictor used (netMHCIIpan)
:rtype: tuple(toil.fileStore.FileID, str)
"""
work_dir = os.getcwd()
input_files = {
'peptfile.faa': peptfile}
input_files = get_files_from_filestore(job, input_files, work_dir, docker=True)
peptides = read_peptide_file(os.path.join(os.getcwd(), 'peptfile.faa'))
if not peptides:
return job.fileStore.writeGlobalFile(job.fileStore.getLocalTempFile()), None
# netMHCIIpan accepts differently formatted alleles so we need to modify the input alleles
if allele.startswith('HLA-DQA') or allele.startswith('HLA-DPA'):
allele = re.sub(r'[*:]', '', allele)
allele = re.sub(r'/', '-', allele)
elif allele.startswith('HLA-DRB'):
allele = re.sub(r':', '', allele)
allele = re.sub(r'\*', '_', allele)
allele = allele.lstrip('HLA-')
else:
raise RuntimeError('Unknown allele seen')
parameters = ['-a', allele,
'-xls', '1',
'-xlsfile', 'predictions.tsv',
'-f', input_files['peptfile.faa']]
# netMHC writes a lot of useless stuff to sys.stdout so we open /dev/null and dump output there.
with open(os.devnull, 'w') as output_catcher:
docker_call(tool='netmhciipan', tool_parameters=parameters, work_dir=work_dir,
dockerhub=univ_options['dockerhub'], outfile=output_catcher,
tool_version=netmhciipan_options['version'])
output_file = job.fileStore.writeGlobalFile('/'.join([work_dir, 'predictions.tsv']))
job.fileStore.logToMaster('Ran netmhciipan on %s successfully' % allele)
return output_file, 'netMHCIIpan' | [
"def",
"predict_netmhcii_binding",
"(",
"job",
",",
"peptfile",
",",
"allele",
",",
"univ_options",
",",
"netmhciipan_options",
")",
":",
"work_dir",
"=",
"os",
".",
"getcwd",
"(",
")",
"input_files",
"=",
"{",
"'peptfile.faa'",
":",
"peptfile",
"}",
"input_files",
"=",
"get_files_from_filestore",
"(",
"job",
",",
"input_files",
",",
"work_dir",
",",
"docker",
"=",
"True",
")",
"peptides",
"=",
"read_peptide_file",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"'peptfile.faa'",
")",
")",
"if",
"not",
"peptides",
":",
"return",
"job",
".",
"fileStore",
".",
"writeGlobalFile",
"(",
"job",
".",
"fileStore",
".",
"getLocalTempFile",
"(",
")",
")",
",",
"None",
"if",
"allele",
".",
"startswith",
"(",
"'HLA-DQA'",
")",
"or",
"allele",
".",
"startswith",
"(",
"'HLA-DPA'",
")",
":",
"allele",
"=",
"re",
".",
"sub",
"(",
"r'[*:]'",
",",
"''",
",",
"allele",
")",
"allele",
"=",
"re",
".",
"sub",
"(",
"r'/'",
",",
"'-'",
",",
"allele",
")",
"elif",
"allele",
".",
"startswith",
"(",
"'HLA-DRB'",
")",
":",
"allele",
"=",
"re",
".",
"sub",
"(",
"r':'",
",",
"''",
",",
"allele",
")",
"allele",
"=",
"re",
".",
"sub",
"(",
"r'\\*'",
",",
"'_'",
",",
"allele",
")",
"allele",
"=",
"allele",
".",
"lstrip",
"(",
"'HLA-'",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
"'Unknown allele seen'",
")",
"parameters",
"=",
"[",
"'-a'",
",",
"allele",
",",
"'-xls'",
",",
"'1'",
",",
"'-xlsfile'",
",",
"'predictions.tsv'",
",",
"'-f'",
",",
"input_files",
"[",
"'peptfile.faa'",
"]",
"]",
"with",
"open",
"(",
"os",
".",
"devnull",
",",
"'w'",
")",
"as",
"output_catcher",
":",
"docker_call",
"(",
"tool",
"=",
"'netmhciipan'",
",",
"tool_parameters",
"=",
"parameters",
",",
"work_dir",
"=",
"work_dir",
",",
"dockerhub",
"=",
"univ_options",
"[",
"'dockerhub'",
"]",
",",
"outfile",
"=",
"output_catcher",
",",
"tool_version",
"=",
"netmhciipan_options",
"[",
"'version'",
"]",
")",
"output_file",
"=",
"job",
".",
"fileStore",
".",
"writeGlobalFile",
"(",
"'/'",
".",
"join",
"(",
"[",
"work_dir",
",",
"'predictions.tsv'",
"]",
")",
")",
"job",
".",
"fileStore",
".",
"logToMaster",
"(",
"'Ran netmhciipan on %s successfully'",
"%",
"allele",
")",
"return",
"output_file",
",",
"'netMHCIIpan'"
] | Predict binding for each peptide in `peptfile` to `allele` using netMHCIIpan.
:param toil.fileStore.FileID peptfile: The input peptide fasta
:param str allele: Allele to predict binding against
:param dict univ_options: Dict of universal options used by almost all tools
:param dict netmhciipan_options: Options specific to netmhciipan binding prediction
:return: tuple of fsID for file containing the predictions and the predictor used (netMHCIIpan)
:rtype: tuple(toil.fileStore.FileID, str) | [
"Predict",
"binding",
"for",
"each",
"peptide",
"in",
"peptfile",
"to",
"allele",
"using",
"netMHCIIpan",
"."
] | 06310682c50dcf8917b912c8e551299ff7ee41ce | https://github.com/BD2KGenomics/protect/blob/06310682c50dcf8917b912c8e551299ff7ee41ce/src/protect/binding_prediction/mhcii.py#L79-L118 | train |
inveniosoftware/invenio-access | invenio_access/permissions.py | _P.update | def update(self, permission):
"""In-place update of permissions."""
self.needs.update(permission.needs)
self.excludes.update(permission.excludes) | python | def update(self, permission):
"""In-place update of permissions."""
self.needs.update(permission.needs)
self.excludes.update(permission.excludes) | [
"def",
"update",
"(",
"self",
",",
"permission",
")",
":",
"self",
".",
"needs",
".",
"update",
"(",
"permission",
".",
"needs",
")",
"self",
".",
"excludes",
".",
"update",
"(",
"permission",
".",
"excludes",
")"
] | In-place update of permissions. | [
"In",
"-",
"place",
"update",
"of",
"permissions",
"."
] | 3b033a4bdc110eb2f7e9f08f0744a780884bfc80 | https://github.com/inveniosoftware/invenio-access/blob/3b033a4bdc110eb2f7e9f08f0744a780884bfc80/invenio_access/permissions.py#L61-L64 | train |
Subsets and Splits