repository_name
stringlengths 7
55
| func_path_in_repository
stringlengths 4
223
| func_name
stringlengths 1
134
| whole_func_string
stringlengths 75
104k
| language
stringclasses 1
value | func_code_string
stringlengths 75
104k
| func_code_tokens
sequencelengths 19
28.4k
| func_documentation_string
stringlengths 1
46.9k
| func_documentation_tokens
sequencelengths 1
1.97k
| split_name
stringclasses 1
value | func_code_url
stringlengths 87
315
|
---|---|---|---|---|---|---|---|---|---|---|
tomduck/pandoc-eqnos | pandoc_eqnos.py | _process_equation | def _process_equation(value, fmt):
"""Processes the equation. Returns a dict containing eq properties."""
# pylint: disable=global-statement
global Nreferences # Global references counter
global cursec # Current section
# Parse the equation
attrs = value[0]
# Initialize the return value
eq = {'is_unnumbered': False,
'is_unreferenceable': False,
'is_tagged': False,
'attrs': attrs}
# Bail out if the label does not conform
if not LABEL_PATTERN.match(attrs[0]):
eq['is_unnumbered'] = True
eq['is_unreferenceable'] = True
return eq
# Process unreferenceable equations
if attrs[0] == 'eq:': # Make up a unique description
attrs[0] = attrs[0] + str(uuid.uuid4())
eq['is_unreferenceable'] = True
unreferenceable.append(attrs[0])
# For html, hard-code in the section numbers as tags
kvs = PandocAttributes(attrs, 'pandoc').kvs
if numbersections and fmt in ['html', 'html5'] and 'tag' not in kvs:
if kvs['secno'] != cursec:
cursec = kvs['secno']
Nreferences = 1
kvs['tag'] = cursec + '.' + str(Nreferences)
Nreferences += 1
# Save to the global references tracker
eq['is_tagged'] = 'tag' in kvs
if eq['is_tagged']:
# Remove any surrounding quotes
if kvs['tag'][0] == '"' and kvs['tag'][-1] == '"':
kvs['tag'] = kvs['tag'].strip('"')
elif kvs['tag'][0] == "'" and kvs['tag'][-1] == "'":
kvs['tag'] = kvs['tag'].strip("'")
references[attrs[0]] = kvs['tag']
else:
Nreferences += 1
references[attrs[0]] = Nreferences
# Adjust equation depending on the output format
if fmt in ['latex', 'beamer']:
if not eq['is_unreferenceable']: # Code in the tags
value[-1] += r'\tag{%s}\label{%s}' % \
(references[attrs[0]].replace(' ', r'\ '), attrs[0]) \
if eq['is_tagged'] else r'\label{%s}'%attrs[0]
elif fmt in ('html', 'html5'):
pass # Insert html in process_equations() instead
else: # Hard-code in the number/tag
if isinstance(references[attrs[0]], int): # Numbered reference
value[-1] += r'\qquad (%d)' % references[attrs[0]]
else: # Tagged reference
assert isinstance(references[attrs[0]], STRTYPES)
text = references[attrs[0]].replace(' ', r'\ ')
if text.startswith('$') and text.endswith('$'): # Math
tag = text[1:-1]
else: # Text
tag = r'\text{%s}' % text
value[-1] += r'\qquad (%s)' % tag
return eq | python | def _process_equation(value, fmt):
"""Processes the equation. Returns a dict containing eq properties."""
# pylint: disable=global-statement
global Nreferences # Global references counter
global cursec # Current section
# Parse the equation
attrs = value[0]
# Initialize the return value
eq = {'is_unnumbered': False,
'is_unreferenceable': False,
'is_tagged': False,
'attrs': attrs}
# Bail out if the label does not conform
if not LABEL_PATTERN.match(attrs[0]):
eq['is_unnumbered'] = True
eq['is_unreferenceable'] = True
return eq
# Process unreferenceable equations
if attrs[0] == 'eq:': # Make up a unique description
attrs[0] = attrs[0] + str(uuid.uuid4())
eq['is_unreferenceable'] = True
unreferenceable.append(attrs[0])
# For html, hard-code in the section numbers as tags
kvs = PandocAttributes(attrs, 'pandoc').kvs
if numbersections and fmt in ['html', 'html5'] and 'tag' not in kvs:
if kvs['secno'] != cursec:
cursec = kvs['secno']
Nreferences = 1
kvs['tag'] = cursec + '.' + str(Nreferences)
Nreferences += 1
# Save to the global references tracker
eq['is_tagged'] = 'tag' in kvs
if eq['is_tagged']:
# Remove any surrounding quotes
if kvs['tag'][0] == '"' and kvs['tag'][-1] == '"':
kvs['tag'] = kvs['tag'].strip('"')
elif kvs['tag'][0] == "'" and kvs['tag'][-1] == "'":
kvs['tag'] = kvs['tag'].strip("'")
references[attrs[0]] = kvs['tag']
else:
Nreferences += 1
references[attrs[0]] = Nreferences
# Adjust equation depending on the output format
if fmt in ['latex', 'beamer']:
if not eq['is_unreferenceable']: # Code in the tags
value[-1] += r'\tag{%s}\label{%s}' % \
(references[attrs[0]].replace(' ', r'\ '), attrs[0]) \
if eq['is_tagged'] else r'\label{%s}'%attrs[0]
elif fmt in ('html', 'html5'):
pass # Insert html in process_equations() instead
else: # Hard-code in the number/tag
if isinstance(references[attrs[0]], int): # Numbered reference
value[-1] += r'\qquad (%d)' % references[attrs[0]]
else: # Tagged reference
assert isinstance(references[attrs[0]], STRTYPES)
text = references[attrs[0]].replace(' ', r'\ ')
if text.startswith('$') and text.endswith('$'): # Math
tag = text[1:-1]
else: # Text
tag = r'\text{%s}' % text
value[-1] += r'\qquad (%s)' % tag
return eq | [
"def",
"_process_equation",
"(",
"value",
",",
"fmt",
")",
":",
"# pylint: disable=global-statement",
"global",
"Nreferences",
"# Global references counter",
"global",
"cursec",
"# Current section",
"# Parse the equation",
"attrs",
"=",
"value",
"[",
"0",
"]",
"# Initialize the return value",
"eq",
"=",
"{",
"'is_unnumbered'",
":",
"False",
",",
"'is_unreferenceable'",
":",
"False",
",",
"'is_tagged'",
":",
"False",
",",
"'attrs'",
":",
"attrs",
"}",
"# Bail out if the label does not conform",
"if",
"not",
"LABEL_PATTERN",
".",
"match",
"(",
"attrs",
"[",
"0",
"]",
")",
":",
"eq",
"[",
"'is_unnumbered'",
"]",
"=",
"True",
"eq",
"[",
"'is_unreferenceable'",
"]",
"=",
"True",
"return",
"eq",
"# Process unreferenceable equations",
"if",
"attrs",
"[",
"0",
"]",
"==",
"'eq:'",
":",
"# Make up a unique description",
"attrs",
"[",
"0",
"]",
"=",
"attrs",
"[",
"0",
"]",
"+",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
"eq",
"[",
"'is_unreferenceable'",
"]",
"=",
"True",
"unreferenceable",
".",
"append",
"(",
"attrs",
"[",
"0",
"]",
")",
"# For html, hard-code in the section numbers as tags",
"kvs",
"=",
"PandocAttributes",
"(",
"attrs",
",",
"'pandoc'",
")",
".",
"kvs",
"if",
"numbersections",
"and",
"fmt",
"in",
"[",
"'html'",
",",
"'html5'",
"]",
"and",
"'tag'",
"not",
"in",
"kvs",
":",
"if",
"kvs",
"[",
"'secno'",
"]",
"!=",
"cursec",
":",
"cursec",
"=",
"kvs",
"[",
"'secno'",
"]",
"Nreferences",
"=",
"1",
"kvs",
"[",
"'tag'",
"]",
"=",
"cursec",
"+",
"'.'",
"+",
"str",
"(",
"Nreferences",
")",
"Nreferences",
"+=",
"1",
"# Save to the global references tracker",
"eq",
"[",
"'is_tagged'",
"]",
"=",
"'tag'",
"in",
"kvs",
"if",
"eq",
"[",
"'is_tagged'",
"]",
":",
"# Remove any surrounding quotes",
"if",
"kvs",
"[",
"'tag'",
"]",
"[",
"0",
"]",
"==",
"'\"'",
"and",
"kvs",
"[",
"'tag'",
"]",
"[",
"-",
"1",
"]",
"==",
"'\"'",
":",
"kvs",
"[",
"'tag'",
"]",
"=",
"kvs",
"[",
"'tag'",
"]",
".",
"strip",
"(",
"'\"'",
")",
"elif",
"kvs",
"[",
"'tag'",
"]",
"[",
"0",
"]",
"==",
"\"'\"",
"and",
"kvs",
"[",
"'tag'",
"]",
"[",
"-",
"1",
"]",
"==",
"\"'\"",
":",
"kvs",
"[",
"'tag'",
"]",
"=",
"kvs",
"[",
"'tag'",
"]",
".",
"strip",
"(",
"\"'\"",
")",
"references",
"[",
"attrs",
"[",
"0",
"]",
"]",
"=",
"kvs",
"[",
"'tag'",
"]",
"else",
":",
"Nreferences",
"+=",
"1",
"references",
"[",
"attrs",
"[",
"0",
"]",
"]",
"=",
"Nreferences",
"# Adjust equation depending on the output format",
"if",
"fmt",
"in",
"[",
"'latex'",
",",
"'beamer'",
"]",
":",
"if",
"not",
"eq",
"[",
"'is_unreferenceable'",
"]",
":",
"# Code in the tags",
"value",
"[",
"-",
"1",
"]",
"+=",
"r'\\tag{%s}\\label{%s}'",
"%",
"(",
"references",
"[",
"attrs",
"[",
"0",
"]",
"]",
".",
"replace",
"(",
"' '",
",",
"r'\\ '",
")",
",",
"attrs",
"[",
"0",
"]",
")",
"if",
"eq",
"[",
"'is_tagged'",
"]",
"else",
"r'\\label{%s}'",
"%",
"attrs",
"[",
"0",
"]",
"elif",
"fmt",
"in",
"(",
"'html'",
",",
"'html5'",
")",
":",
"pass",
"# Insert html in process_equations() instead",
"else",
":",
"# Hard-code in the number/tag",
"if",
"isinstance",
"(",
"references",
"[",
"attrs",
"[",
"0",
"]",
"]",
",",
"int",
")",
":",
"# Numbered reference",
"value",
"[",
"-",
"1",
"]",
"+=",
"r'\\qquad (%d)'",
"%",
"references",
"[",
"attrs",
"[",
"0",
"]",
"]",
"else",
":",
"# Tagged reference",
"assert",
"isinstance",
"(",
"references",
"[",
"attrs",
"[",
"0",
"]",
"]",
",",
"STRTYPES",
")",
"text",
"=",
"references",
"[",
"attrs",
"[",
"0",
"]",
"]",
".",
"replace",
"(",
"' '",
",",
"r'\\ '",
")",
"if",
"text",
".",
"startswith",
"(",
"'$'",
")",
"and",
"text",
".",
"endswith",
"(",
"'$'",
")",
":",
"# Math",
"tag",
"=",
"text",
"[",
"1",
":",
"-",
"1",
"]",
"else",
":",
"# Text",
"tag",
"=",
"r'\\text{%s}'",
"%",
"text",
"value",
"[",
"-",
"1",
"]",
"+=",
"r'\\qquad (%s)'",
"%",
"tag",
"return",
"eq"
] | Processes the equation. Returns a dict containing eq properties. | [
"Processes",
"the",
"equation",
".",
"Returns",
"a",
"dict",
"containing",
"eq",
"properties",
"."
] | train | https://github.com/tomduck/pandoc-eqnos/blob/a0e2b5684d2024ea96049ed2cff3acf4ab47c541/pandoc_eqnos.py#L84-L154 |
tomduck/pandoc-eqnos | pandoc_eqnos.py | process_equations | def process_equations(key, value, fmt, meta):
"""Processes the attributed equations."""
if key == 'Math' and len(value) == 3:
# Process the equation
eq = _process_equation(value, fmt)
# Get the attributes and label
attrs = eq['attrs']
label = attrs[0]
if eq['is_unreferenceable']:
attrs[0] = '' # The label isn't needed outside this function
# Context-dependent output
if eq['is_unnumbered']: # Unnumbered is also unreferenceable
return None
elif fmt in ['latex', 'beamer']:
return RawInline('tex',
r'\begin{equation}%s\end{equation}'%value[-1])
elif fmt in ('html', 'html5') and LABEL_PATTERN.match(label):
# Present equation and its number in a span
text = str(references[label])
outerspan = RawInline('html',
'<span %s style="display: inline-block; '
'position: relative; width: 100%%">'%(''\
if eq['is_unreferenceable'] \
else 'id="%s"'%label))
innerspan = RawInline('html',
'<span style="position: absolute; '
'right: 0em; top: %s; line-height:0; '
'text-align: right">' %
('0' if text.startswith('$') and
text.endswith('$') else '50%',))
num = Math({"t":"InlineMath"}, '(%s)' % text[1:-1]) \
if text.startswith('$') and text.endswith('$') \
else Str('(%s)' % text)
endspans = RawInline('html', '</span></span>')
return [outerspan, AttrMath(*value), innerspan, num, endspans]
elif fmt == 'docx':
# As per http://officeopenxml.com/WPhyperlink.php
bookmarkstart = \
RawInline('openxml',
'<w:bookmarkStart w:id="0" w:name="%s"/><w:r><w:t>'
%label)
bookmarkend = \
RawInline('openxml',
'</w:t></w:r><w:bookmarkEnd w:id="0"/>')
return [bookmarkstart, AttrMath(*value), bookmarkend]
return None | python | def process_equations(key, value, fmt, meta):
"""Processes the attributed equations."""
if key == 'Math' and len(value) == 3:
# Process the equation
eq = _process_equation(value, fmt)
# Get the attributes and label
attrs = eq['attrs']
label = attrs[0]
if eq['is_unreferenceable']:
attrs[0] = '' # The label isn't needed outside this function
# Context-dependent output
if eq['is_unnumbered']: # Unnumbered is also unreferenceable
return None
elif fmt in ['latex', 'beamer']:
return RawInline('tex',
r'\begin{equation}%s\end{equation}'%value[-1])
elif fmt in ('html', 'html5') and LABEL_PATTERN.match(label):
# Present equation and its number in a span
text = str(references[label])
outerspan = RawInline('html',
'<span %s style="display: inline-block; '
'position: relative; width: 100%%">'%(''\
if eq['is_unreferenceable'] \
else 'id="%s"'%label))
innerspan = RawInline('html',
'<span style="position: absolute; '
'right: 0em; top: %s; line-height:0; '
'text-align: right">' %
('0' if text.startswith('$') and
text.endswith('$') else '50%',))
num = Math({"t":"InlineMath"}, '(%s)' % text[1:-1]) \
if text.startswith('$') and text.endswith('$') \
else Str('(%s)' % text)
endspans = RawInline('html', '</span></span>')
return [outerspan, AttrMath(*value), innerspan, num, endspans]
elif fmt == 'docx':
# As per http://officeopenxml.com/WPhyperlink.php
bookmarkstart = \
RawInline('openxml',
'<w:bookmarkStart w:id="0" w:name="%s"/><w:r><w:t>'
%label)
bookmarkend = \
RawInline('openxml',
'</w:t></w:r><w:bookmarkEnd w:id="0"/>')
return [bookmarkstart, AttrMath(*value), bookmarkend]
return None | [
"def",
"process_equations",
"(",
"key",
",",
"value",
",",
"fmt",
",",
"meta",
")",
":",
"if",
"key",
"==",
"'Math'",
"and",
"len",
"(",
"value",
")",
"==",
"3",
":",
"# Process the equation",
"eq",
"=",
"_process_equation",
"(",
"value",
",",
"fmt",
")",
"# Get the attributes and label",
"attrs",
"=",
"eq",
"[",
"'attrs'",
"]",
"label",
"=",
"attrs",
"[",
"0",
"]",
"if",
"eq",
"[",
"'is_unreferenceable'",
"]",
":",
"attrs",
"[",
"0",
"]",
"=",
"''",
"# The label isn't needed outside this function",
"# Context-dependent output",
"if",
"eq",
"[",
"'is_unnumbered'",
"]",
":",
"# Unnumbered is also unreferenceable",
"return",
"None",
"elif",
"fmt",
"in",
"[",
"'latex'",
",",
"'beamer'",
"]",
":",
"return",
"RawInline",
"(",
"'tex'",
",",
"r'\\begin{equation}%s\\end{equation}'",
"%",
"value",
"[",
"-",
"1",
"]",
")",
"elif",
"fmt",
"in",
"(",
"'html'",
",",
"'html5'",
")",
"and",
"LABEL_PATTERN",
".",
"match",
"(",
"label",
")",
":",
"# Present equation and its number in a span",
"text",
"=",
"str",
"(",
"references",
"[",
"label",
"]",
")",
"outerspan",
"=",
"RawInline",
"(",
"'html'",
",",
"'<span %s style=\"display: inline-block; '",
"'position: relative; width: 100%%\">'",
"%",
"(",
"''",
"if",
"eq",
"[",
"'is_unreferenceable'",
"]",
"else",
"'id=\"%s\"'",
"%",
"label",
")",
")",
"innerspan",
"=",
"RawInline",
"(",
"'html'",
",",
"'<span style=\"position: absolute; '",
"'right: 0em; top: %s; line-height:0; '",
"'text-align: right\">'",
"%",
"(",
"'0'",
"if",
"text",
".",
"startswith",
"(",
"'$'",
")",
"and",
"text",
".",
"endswith",
"(",
"'$'",
")",
"else",
"'50%'",
",",
")",
")",
"num",
"=",
"Math",
"(",
"{",
"\"t\"",
":",
"\"InlineMath\"",
"}",
",",
"'(%s)'",
"%",
"text",
"[",
"1",
":",
"-",
"1",
"]",
")",
"if",
"text",
".",
"startswith",
"(",
"'$'",
")",
"and",
"text",
".",
"endswith",
"(",
"'$'",
")",
"else",
"Str",
"(",
"'(%s)'",
"%",
"text",
")",
"endspans",
"=",
"RawInline",
"(",
"'html'",
",",
"'</span></span>'",
")",
"return",
"[",
"outerspan",
",",
"AttrMath",
"(",
"*",
"value",
")",
",",
"innerspan",
",",
"num",
",",
"endspans",
"]",
"elif",
"fmt",
"==",
"'docx'",
":",
"# As per http://officeopenxml.com/WPhyperlink.php",
"bookmarkstart",
"=",
"RawInline",
"(",
"'openxml'",
",",
"'<w:bookmarkStart w:id=\"0\" w:name=\"%s\"/><w:r><w:t>'",
"%",
"label",
")",
"bookmarkend",
"=",
"RawInline",
"(",
"'openxml'",
",",
"'</w:t></w:r><w:bookmarkEnd w:id=\"0\"/>'",
")",
"return",
"[",
"bookmarkstart",
",",
"AttrMath",
"(",
"*",
"value",
")",
",",
"bookmarkend",
"]",
"return",
"None"
] | Processes the attributed equations. | [
"Processes",
"the",
"attributed",
"equations",
"."
] | train | https://github.com/tomduck/pandoc-eqnos/blob/a0e2b5684d2024ea96049ed2cff3acf4ab47c541/pandoc_eqnos.py#L158-L208 |
tomduck/pandoc-eqnos | pandoc_eqnos.py | process | def process(meta):
"""Saves metadata fields in global variables and returns a few
computed fields."""
# pylint: disable=global-statement
global capitalize
global use_cleveref_default
global plusname
global starname
global numbersections
# Read in the metadata fields and do some checking
for name in ['eqnos-cleveref', 'xnos-cleveref', 'cleveref']:
# 'xnos-cleveref' enables cleveref in all 3 of fignos/eqnos/tablenos
# 'cleveref' is deprecated
if name in meta:
use_cleveref_default = check_bool(get_meta(meta, name))
break
for name in ['eqnos-capitalize', 'eqnos-capitalise',
'xnos-capitalize', 'xnos-capitalise']:
# 'eqnos-capitalise' is an alternative spelling
# 'xnos-capitalise' enables capitalise in all 3 of fignos/eqnos/tablenos
# 'xnos-capitalize' is an alternative spelling
if name in meta:
capitalize = check_bool(get_meta(meta, name))
break
if 'eqnos-plus-name' in meta:
tmp = get_meta(meta, 'eqnos-plus-name')
if isinstance(tmp, list):
plusname = tmp
else:
plusname[0] = tmp
assert len(plusname) == 2
for name in plusname:
assert isinstance(name, STRTYPES)
if 'eqnos-star-name' in meta:
tmp = get_meta(meta, 'eqnos-star-name')
if isinstance(tmp, list):
starname = tmp
else:
starname[0] = tmp
assert len(starname) == 2
for name in starname:
assert isinstance(name, STRTYPES)
if 'xnos-number-sections' in meta:
numbersections = check_bool(get_meta(meta, 'xnos-number-sections')) | python | def process(meta):
"""Saves metadata fields in global variables and returns a few
computed fields."""
# pylint: disable=global-statement
global capitalize
global use_cleveref_default
global plusname
global starname
global numbersections
# Read in the metadata fields and do some checking
for name in ['eqnos-cleveref', 'xnos-cleveref', 'cleveref']:
# 'xnos-cleveref' enables cleveref in all 3 of fignos/eqnos/tablenos
# 'cleveref' is deprecated
if name in meta:
use_cleveref_default = check_bool(get_meta(meta, name))
break
for name in ['eqnos-capitalize', 'eqnos-capitalise',
'xnos-capitalize', 'xnos-capitalise']:
# 'eqnos-capitalise' is an alternative spelling
# 'xnos-capitalise' enables capitalise in all 3 of fignos/eqnos/tablenos
# 'xnos-capitalize' is an alternative spelling
if name in meta:
capitalize = check_bool(get_meta(meta, name))
break
if 'eqnos-plus-name' in meta:
tmp = get_meta(meta, 'eqnos-plus-name')
if isinstance(tmp, list):
plusname = tmp
else:
plusname[0] = tmp
assert len(plusname) == 2
for name in plusname:
assert isinstance(name, STRTYPES)
if 'eqnos-star-name' in meta:
tmp = get_meta(meta, 'eqnos-star-name')
if isinstance(tmp, list):
starname = tmp
else:
starname[0] = tmp
assert len(starname) == 2
for name in starname:
assert isinstance(name, STRTYPES)
if 'xnos-number-sections' in meta:
numbersections = check_bool(get_meta(meta, 'xnos-number-sections')) | [
"def",
"process",
"(",
"meta",
")",
":",
"# pylint: disable=global-statement",
"global",
"capitalize",
"global",
"use_cleveref_default",
"global",
"plusname",
"global",
"starname",
"global",
"numbersections",
"# Read in the metadata fields and do some checking",
"for",
"name",
"in",
"[",
"'eqnos-cleveref'",
",",
"'xnos-cleveref'",
",",
"'cleveref'",
"]",
":",
"# 'xnos-cleveref' enables cleveref in all 3 of fignos/eqnos/tablenos",
"# 'cleveref' is deprecated",
"if",
"name",
"in",
"meta",
":",
"use_cleveref_default",
"=",
"check_bool",
"(",
"get_meta",
"(",
"meta",
",",
"name",
")",
")",
"break",
"for",
"name",
"in",
"[",
"'eqnos-capitalize'",
",",
"'eqnos-capitalise'",
",",
"'xnos-capitalize'",
",",
"'xnos-capitalise'",
"]",
":",
"# 'eqnos-capitalise' is an alternative spelling",
"# 'xnos-capitalise' enables capitalise in all 3 of fignos/eqnos/tablenos",
"# 'xnos-capitalize' is an alternative spelling",
"if",
"name",
"in",
"meta",
":",
"capitalize",
"=",
"check_bool",
"(",
"get_meta",
"(",
"meta",
",",
"name",
")",
")",
"break",
"if",
"'eqnos-plus-name'",
"in",
"meta",
":",
"tmp",
"=",
"get_meta",
"(",
"meta",
",",
"'eqnos-plus-name'",
")",
"if",
"isinstance",
"(",
"tmp",
",",
"list",
")",
":",
"plusname",
"=",
"tmp",
"else",
":",
"plusname",
"[",
"0",
"]",
"=",
"tmp",
"assert",
"len",
"(",
"plusname",
")",
"==",
"2",
"for",
"name",
"in",
"plusname",
":",
"assert",
"isinstance",
"(",
"name",
",",
"STRTYPES",
")",
"if",
"'eqnos-star-name'",
"in",
"meta",
":",
"tmp",
"=",
"get_meta",
"(",
"meta",
",",
"'eqnos-star-name'",
")",
"if",
"isinstance",
"(",
"tmp",
",",
"list",
")",
":",
"starname",
"=",
"tmp",
"else",
":",
"starname",
"[",
"0",
"]",
"=",
"tmp",
"assert",
"len",
"(",
"starname",
")",
"==",
"2",
"for",
"name",
"in",
"starname",
":",
"assert",
"isinstance",
"(",
"name",
",",
"STRTYPES",
")",
"if",
"'xnos-number-sections'",
"in",
"meta",
":",
"numbersections",
"=",
"check_bool",
"(",
"get_meta",
"(",
"meta",
",",
"'xnos-number-sections'",
")",
")"
] | Saves metadata fields in global variables and returns a few
computed fields. | [
"Saves",
"metadata",
"fields",
"in",
"global",
"variables",
"and",
"returns",
"a",
"few",
"computed",
"fields",
"."
] | train | https://github.com/tomduck/pandoc-eqnos/blob/a0e2b5684d2024ea96049ed2cff3acf4ab47c541/pandoc_eqnos.py#L213-L263 |
tomduck/pandoc-eqnos | pandoc_eqnos.py | main | def main():
"""Filters the document AST."""
# pylint: disable=global-statement
global PANDOCVERSION
global AttrMath
# Get the output format and document
fmt = args.fmt
doc = json.loads(STDIN.read())
# Initialize pandocxnos
# pylint: disable=too-many-function-args
PANDOCVERSION = pandocxnos.init(args.pandocversion, doc)
# Element primitives
AttrMath = elt('Math', 3)
# Chop up the doc
meta = doc['meta'] if PANDOCVERSION >= '1.18' else doc[0]['unMeta']
blocks = doc['blocks'] if PANDOCVERSION >= '1.18' else doc[1:]
# Process the metadata variables
process(meta)
# First pass
attach_attrs_math = attach_attrs_factory(Math, allow_space=True)
detach_attrs_math = detach_attrs_factory(Math)
insert_secnos = insert_secnos_factory(Math)
delete_secnos = delete_secnos_factory(Math)
altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
[attach_attrs_math, insert_secnos,
process_equations, delete_secnos,
detach_attrs_math], blocks)
# Second pass
process_refs = process_refs_factory(references.keys())
replace_refs = replace_refs_factory(references,
use_cleveref_default, use_eqref,
plusname if not capitalize else
[name.title() for name in plusname],
starname, 'equation')
altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
[repair_refs, process_refs, replace_refs],
altered)
# Update the doc
if PANDOCVERSION >= '1.18':
doc['blocks'] = altered
else:
doc = doc[:1] + altered
# Dump the results
json.dump(doc, STDOUT)
# Flush stdout
STDOUT.flush() | python | def main():
"""Filters the document AST."""
# pylint: disable=global-statement
global PANDOCVERSION
global AttrMath
# Get the output format and document
fmt = args.fmt
doc = json.loads(STDIN.read())
# Initialize pandocxnos
# pylint: disable=too-many-function-args
PANDOCVERSION = pandocxnos.init(args.pandocversion, doc)
# Element primitives
AttrMath = elt('Math', 3)
# Chop up the doc
meta = doc['meta'] if PANDOCVERSION >= '1.18' else doc[0]['unMeta']
blocks = doc['blocks'] if PANDOCVERSION >= '1.18' else doc[1:]
# Process the metadata variables
process(meta)
# First pass
attach_attrs_math = attach_attrs_factory(Math, allow_space=True)
detach_attrs_math = detach_attrs_factory(Math)
insert_secnos = insert_secnos_factory(Math)
delete_secnos = delete_secnos_factory(Math)
altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
[attach_attrs_math, insert_secnos,
process_equations, delete_secnos,
detach_attrs_math], blocks)
# Second pass
process_refs = process_refs_factory(references.keys())
replace_refs = replace_refs_factory(references,
use_cleveref_default, use_eqref,
plusname if not capitalize else
[name.title() for name in plusname],
starname, 'equation')
altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
[repair_refs, process_refs, replace_refs],
altered)
# Update the doc
if PANDOCVERSION >= '1.18':
doc['blocks'] = altered
else:
doc = doc[:1] + altered
# Dump the results
json.dump(doc, STDOUT)
# Flush stdout
STDOUT.flush() | [
"def",
"main",
"(",
")",
":",
"# pylint: disable=global-statement",
"global",
"PANDOCVERSION",
"global",
"AttrMath",
"# Get the output format and document",
"fmt",
"=",
"args",
".",
"fmt",
"doc",
"=",
"json",
".",
"loads",
"(",
"STDIN",
".",
"read",
"(",
")",
")",
"# Initialize pandocxnos",
"# pylint: disable=too-many-function-args",
"PANDOCVERSION",
"=",
"pandocxnos",
".",
"init",
"(",
"args",
".",
"pandocversion",
",",
"doc",
")",
"# Element primitives",
"AttrMath",
"=",
"elt",
"(",
"'Math'",
",",
"3",
")",
"# Chop up the doc",
"meta",
"=",
"doc",
"[",
"'meta'",
"]",
"if",
"PANDOCVERSION",
">=",
"'1.18'",
"else",
"doc",
"[",
"0",
"]",
"[",
"'unMeta'",
"]",
"blocks",
"=",
"doc",
"[",
"'blocks'",
"]",
"if",
"PANDOCVERSION",
">=",
"'1.18'",
"else",
"doc",
"[",
"1",
":",
"]",
"# Process the metadata variables",
"process",
"(",
"meta",
")",
"# First pass",
"attach_attrs_math",
"=",
"attach_attrs_factory",
"(",
"Math",
",",
"allow_space",
"=",
"True",
")",
"detach_attrs_math",
"=",
"detach_attrs_factory",
"(",
"Math",
")",
"insert_secnos",
"=",
"insert_secnos_factory",
"(",
"Math",
")",
"delete_secnos",
"=",
"delete_secnos_factory",
"(",
"Math",
")",
"altered",
"=",
"functools",
".",
"reduce",
"(",
"lambda",
"x",
",",
"action",
":",
"walk",
"(",
"x",
",",
"action",
",",
"fmt",
",",
"meta",
")",
",",
"[",
"attach_attrs_math",
",",
"insert_secnos",
",",
"process_equations",
",",
"delete_secnos",
",",
"detach_attrs_math",
"]",
",",
"blocks",
")",
"# Second pass",
"process_refs",
"=",
"process_refs_factory",
"(",
"references",
".",
"keys",
"(",
")",
")",
"replace_refs",
"=",
"replace_refs_factory",
"(",
"references",
",",
"use_cleveref_default",
",",
"use_eqref",
",",
"plusname",
"if",
"not",
"capitalize",
"else",
"[",
"name",
".",
"title",
"(",
")",
"for",
"name",
"in",
"plusname",
"]",
",",
"starname",
",",
"'equation'",
")",
"altered",
"=",
"functools",
".",
"reduce",
"(",
"lambda",
"x",
",",
"action",
":",
"walk",
"(",
"x",
",",
"action",
",",
"fmt",
",",
"meta",
")",
",",
"[",
"repair_refs",
",",
"process_refs",
",",
"replace_refs",
"]",
",",
"altered",
")",
"# Update the doc",
"if",
"PANDOCVERSION",
">=",
"'1.18'",
":",
"doc",
"[",
"'blocks'",
"]",
"=",
"altered",
"else",
":",
"doc",
"=",
"doc",
"[",
":",
"1",
"]",
"+",
"altered",
"# Dump the results",
"json",
".",
"dump",
"(",
"doc",
",",
"STDOUT",
")",
"# Flush stdout",
"STDOUT",
".",
"flush",
"(",
")"
] | Filters the document AST. | [
"Filters",
"the",
"document",
"AST",
"."
] | train | https://github.com/tomduck/pandoc-eqnos/blob/a0e2b5684d2024ea96049ed2cff3acf4ab47c541/pandoc_eqnos.py#L266-L322 |
nedbat/django_coverage_plugin | django_coverage_plugin/plugin.py | check_debug | def check_debug():
"""Check that Django's template debugging is enabled.
Django's built-in "template debugging" records information the plugin needs
to do its work. Check that the setting is correct, and raise an exception
if it is not.
Returns True if the debug check was performed, False otherwise
"""
from django.conf import settings
if not settings.configured:
return False
# I _think_ this check is all that's needed and the 3 "hasattr" checks
# below can be removed, but it's not clear how to verify that
from django.apps import apps
if not apps.ready:
return False
# django.template.backends.django gets loaded lazily, so return false
# until they've been loaded
if not hasattr(django.template, "backends"):
return False
if not hasattr(django.template.backends, "django"):
return False
if not hasattr(django.template.backends.django, "DjangoTemplates"):
raise DjangoTemplatePluginException("Can't use non-Django templates.")
for engine in django.template.engines.all():
if not isinstance(engine, django.template.backends.django.DjangoTemplates):
raise DjangoTemplatePluginException(
"Can't use non-Django templates."
)
if not engine.engine.debug:
raise DjangoTemplatePluginException(
"Template debugging must be enabled in settings."
)
return True | python | def check_debug():
"""Check that Django's template debugging is enabled.
Django's built-in "template debugging" records information the plugin needs
to do its work. Check that the setting is correct, and raise an exception
if it is not.
Returns True if the debug check was performed, False otherwise
"""
from django.conf import settings
if not settings.configured:
return False
# I _think_ this check is all that's needed and the 3 "hasattr" checks
# below can be removed, but it's not clear how to verify that
from django.apps import apps
if not apps.ready:
return False
# django.template.backends.django gets loaded lazily, so return false
# until they've been loaded
if not hasattr(django.template, "backends"):
return False
if not hasattr(django.template.backends, "django"):
return False
if not hasattr(django.template.backends.django, "DjangoTemplates"):
raise DjangoTemplatePluginException("Can't use non-Django templates.")
for engine in django.template.engines.all():
if not isinstance(engine, django.template.backends.django.DjangoTemplates):
raise DjangoTemplatePluginException(
"Can't use non-Django templates."
)
if not engine.engine.debug:
raise DjangoTemplatePluginException(
"Template debugging must be enabled in settings."
)
return True | [
"def",
"check_debug",
"(",
")",
":",
"from",
"django",
".",
"conf",
"import",
"settings",
"if",
"not",
"settings",
".",
"configured",
":",
"return",
"False",
"# I _think_ this check is all that's needed and the 3 \"hasattr\" checks",
"# below can be removed, but it's not clear how to verify that",
"from",
"django",
".",
"apps",
"import",
"apps",
"if",
"not",
"apps",
".",
"ready",
":",
"return",
"False",
"# django.template.backends.django gets loaded lazily, so return false",
"# until they've been loaded",
"if",
"not",
"hasattr",
"(",
"django",
".",
"template",
",",
"\"backends\"",
")",
":",
"return",
"False",
"if",
"not",
"hasattr",
"(",
"django",
".",
"template",
".",
"backends",
",",
"\"django\"",
")",
":",
"return",
"False",
"if",
"not",
"hasattr",
"(",
"django",
".",
"template",
".",
"backends",
".",
"django",
",",
"\"DjangoTemplates\"",
")",
":",
"raise",
"DjangoTemplatePluginException",
"(",
"\"Can't use non-Django templates.\"",
")",
"for",
"engine",
"in",
"django",
".",
"template",
".",
"engines",
".",
"all",
"(",
")",
":",
"if",
"not",
"isinstance",
"(",
"engine",
",",
"django",
".",
"template",
".",
"backends",
".",
"django",
".",
"DjangoTemplates",
")",
":",
"raise",
"DjangoTemplatePluginException",
"(",
"\"Can't use non-Django templates.\"",
")",
"if",
"not",
"engine",
".",
"engine",
".",
"debug",
":",
"raise",
"DjangoTemplatePluginException",
"(",
"\"Template debugging must be enabled in settings.\"",
")",
"return",
"True"
] | Check that Django's template debugging is enabled.
Django's built-in "template debugging" records information the plugin needs
to do its work. Check that the setting is correct, and raise an exception
if it is not.
Returns True if the debug check was performed, False otherwise | [
"Check",
"that",
"Django",
"s",
"template",
"debugging",
"is",
"enabled",
"."
] | train | https://github.com/nedbat/django_coverage_plugin/blob/0072737c0ea5a1ca6b9f046af4947de191f13804/django_coverage_plugin/plugin.py#L50-L89 |
nedbat/django_coverage_plugin | django_coverage_plugin/plugin.py | read_template_source | def read_template_source(filename):
"""Read the source of a Django template, returning the Unicode text."""
# Import this late to be sure we don't trigger settings machinery too
# early.
from django.conf import settings
if not settings.configured:
settings.configure()
with open(filename, "rb") as f:
text = f.read().decode(settings.FILE_CHARSET)
return text | python | def read_template_source(filename):
"""Read the source of a Django template, returning the Unicode text."""
# Import this late to be sure we don't trigger settings machinery too
# early.
from django.conf import settings
if not settings.configured:
settings.configure()
with open(filename, "rb") as f:
text = f.read().decode(settings.FILE_CHARSET)
return text | [
"def",
"read_template_source",
"(",
"filename",
")",
":",
"# Import this late to be sure we don't trigger settings machinery too",
"# early.",
"from",
"django",
".",
"conf",
"import",
"settings",
"if",
"not",
"settings",
".",
"configured",
":",
"settings",
".",
"configure",
"(",
")",
"with",
"open",
"(",
"filename",
",",
"\"rb\"",
")",
"as",
"f",
":",
"text",
"=",
"f",
".",
"read",
"(",
")",
".",
"decode",
"(",
"settings",
".",
"FILE_CHARSET",
")",
"return",
"text"
] | Read the source of a Django template, returning the Unicode text. | [
"Read",
"the",
"source",
"of",
"a",
"Django",
"template",
"returning",
"the",
"Unicode",
"text",
"."
] | train | https://github.com/nedbat/django_coverage_plugin/blob/0072737c0ea5a1ca6b9f046af4947de191f13804/django_coverage_plugin/plugin.py#L127-L139 |
nedbat/django_coverage_plugin | django_coverage_plugin/plugin.py | get_line_number | def get_line_number(line_map, offset):
"""Find a line number, given a line map and a character offset."""
for lineno, line_offset in enumerate(line_map, start=1):
if line_offset > offset:
return lineno
return -1 | python | def get_line_number(line_map, offset):
"""Find a line number, given a line map and a character offset."""
for lineno, line_offset in enumerate(line_map, start=1):
if line_offset > offset:
return lineno
return -1 | [
"def",
"get_line_number",
"(",
"line_map",
",",
"offset",
")",
":",
"for",
"lineno",
",",
"line_offset",
"in",
"enumerate",
"(",
"line_map",
",",
"start",
"=",
"1",
")",
":",
"if",
"line_offset",
">",
"offset",
":",
"return",
"lineno",
"return",
"-",
"1"
] | Find a line number, given a line map and a character offset. | [
"Find",
"a",
"line",
"number",
"given",
"a",
"line",
"map",
"and",
"a",
"character",
"offset",
"."
] | train | https://github.com/nedbat/django_coverage_plugin/blob/0072737c0ea5a1ca6b9f046af4947de191f13804/django_coverage_plugin/plugin.py#L389-L394 |
nedbat/django_coverage_plugin | django_coverage_plugin/plugin.py | dump_frame | def dump_frame(frame, label=""):
"""Dump interesting information about this frame."""
locals = dict(frame.f_locals)
self = locals.get('self', None)
context = locals.get('context', None)
if "__builtins__" in locals:
del locals["__builtins__"]
if label:
label = " ( %s ) " % label
print("-- frame --%s---------------------" % label)
print("{}:{}:{}".format(
os.path.basename(frame.f_code.co_filename),
frame.f_lineno,
type(self),
))
print(locals)
if self:
print("self:", self.__dict__)
if context:
print("context:", context.__dict__)
print("\\--") | python | def dump_frame(frame, label=""):
"""Dump interesting information about this frame."""
locals = dict(frame.f_locals)
self = locals.get('self', None)
context = locals.get('context', None)
if "__builtins__" in locals:
del locals["__builtins__"]
if label:
label = " ( %s ) " % label
print("-- frame --%s---------------------" % label)
print("{}:{}:{}".format(
os.path.basename(frame.f_code.co_filename),
frame.f_lineno,
type(self),
))
print(locals)
if self:
print("self:", self.__dict__)
if context:
print("context:", context.__dict__)
print("\\--") | [
"def",
"dump_frame",
"(",
"frame",
",",
"label",
"=",
"\"\"",
")",
":",
"locals",
"=",
"dict",
"(",
"frame",
".",
"f_locals",
")",
"self",
"=",
"locals",
".",
"get",
"(",
"'self'",
",",
"None",
")",
"context",
"=",
"locals",
".",
"get",
"(",
"'context'",
",",
"None",
")",
"if",
"\"__builtins__\"",
"in",
"locals",
":",
"del",
"locals",
"[",
"\"__builtins__\"",
"]",
"if",
"label",
":",
"label",
"=",
"\" ( %s ) \"",
"%",
"label",
"print",
"(",
"\"-- frame --%s---------------------\"",
"%",
"label",
")",
"print",
"(",
"\"{}:{}:{}\"",
".",
"format",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"frame",
".",
"f_code",
".",
"co_filename",
")",
",",
"frame",
".",
"f_lineno",
",",
"type",
"(",
"self",
")",
",",
")",
")",
"print",
"(",
"locals",
")",
"if",
"self",
":",
"print",
"(",
"\"self:\"",
",",
"self",
".",
"__dict__",
")",
"if",
"context",
":",
"print",
"(",
"\"context:\"",
",",
"context",
".",
"__dict__",
")",
"print",
"(",
"\"\\\\--\"",
")"
] | Dump interesting information about this frame. | [
"Dump",
"interesting",
"information",
"about",
"this",
"frame",
"."
] | train | https://github.com/nedbat/django_coverage_plugin/blob/0072737c0ea5a1ca6b9f046af4947de191f13804/django_coverage_plugin/plugin.py#L397-L418 |
nedbat/django_coverage_plugin | django_coverage_plugin/plugin.py | DjangoTemplatePlugin.get_line_map | def get_line_map(self, filename):
"""The line map for `filename`.
A line map is a list of character offsets, indicating where each line
in the text begins. For example, a line map like this::
[13, 19, 30]
means that line 2 starts at character 13, line 3 starts at 19, etc.
Line 1 always starts at character 0.
"""
if filename not in self.source_map:
template_source = read_template_source(filename)
if 0: # change to see the template text
for i in range(0, len(template_source), 10):
print("%3d: %r" % (i, template_source[i:i+10]))
self.source_map[filename] = make_line_map(template_source)
return self.source_map[filename] | python | def get_line_map(self, filename):
"""The line map for `filename`.
A line map is a list of character offsets, indicating where each line
in the text begins. For example, a line map like this::
[13, 19, 30]
means that line 2 starts at character 13, line 3 starts at 19, etc.
Line 1 always starts at character 0.
"""
if filename not in self.source_map:
template_source = read_template_source(filename)
if 0: # change to see the template text
for i in range(0, len(template_source), 10):
print("%3d: %r" % (i, template_source[i:i+10]))
self.source_map[filename] = make_line_map(template_source)
return self.source_map[filename] | [
"def",
"get_line_map",
"(",
"self",
",",
"filename",
")",
":",
"if",
"filename",
"not",
"in",
"self",
".",
"source_map",
":",
"template_source",
"=",
"read_template_source",
"(",
"filename",
")",
"if",
"0",
":",
"# change to see the template text",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"template_source",
")",
",",
"10",
")",
":",
"print",
"(",
"\"%3d: %r\"",
"%",
"(",
"i",
",",
"template_source",
"[",
"i",
":",
"i",
"+",
"10",
"]",
")",
")",
"self",
".",
"source_map",
"[",
"filename",
"]",
"=",
"make_line_map",
"(",
"template_source",
")",
"return",
"self",
".",
"source_map",
"[",
"filename",
"]"
] | The line map for `filename`.
A line map is a list of character offsets, indicating where each line
in the text begins. For example, a line map like this::
[13, 19, 30]
means that line 2 starts at character 13, line 3 starts at 19, etc.
Line 1 always starts at character 0. | [
"The",
"line",
"map",
"for",
"filename",
"."
] | train | https://github.com/nedbat/django_coverage_plugin/blob/0072737c0ea5a1ca6b9f046af4947de191f13804/django_coverage_plugin/plugin.py#L256-L274 |
dylanaraps/bum | bum/display.py | init | def init(size=250):
"""Initialize mpv."""
player = mpv.MPV(start_event_thread=False)
player["force-window"] = "immediate"
player["keep-open"] = "yes"
player["geometry"] = f"{size}x{size}"
player["autofit"] = f"{size}x{size}"
player["title"] = "bum"
return player | python | def init(size=250):
"""Initialize mpv."""
player = mpv.MPV(start_event_thread=False)
player["force-window"] = "immediate"
player["keep-open"] = "yes"
player["geometry"] = f"{size}x{size}"
player["autofit"] = f"{size}x{size}"
player["title"] = "bum"
return player | [
"def",
"init",
"(",
"size",
"=",
"250",
")",
":",
"player",
"=",
"mpv",
".",
"MPV",
"(",
"start_event_thread",
"=",
"False",
")",
"player",
"[",
"\"force-window\"",
"]",
"=",
"\"immediate\"",
"player",
"[",
"\"keep-open\"",
"]",
"=",
"\"yes\"",
"player",
"[",
"\"geometry\"",
"]",
"=",
"f\"{size}x{size}\"",
"player",
"[",
"\"autofit\"",
"]",
"=",
"f\"{size}x{size}\"",
"player",
"[",
"\"title\"",
"]",
"=",
"\"bum\"",
"return",
"player"
] | Initialize mpv. | [
"Initialize",
"mpv",
"."
] | train | https://github.com/dylanaraps/bum/blob/004d795a67398e79f2c098d7775e9cd97231646b/bum/display.py#L7-L16 |
dylanaraps/bum | bum/util.py | bytes_to_file | def bytes_to_file(input_data, output_file):
"""Save bytes to a file."""
pathlib.Path(output_file.parent).mkdir(parents=True, exist_ok=True)
with open(output_file, "wb") as file:
file.write(input_data) | python | def bytes_to_file(input_data, output_file):
"""Save bytes to a file."""
pathlib.Path(output_file.parent).mkdir(parents=True, exist_ok=True)
with open(output_file, "wb") as file:
file.write(input_data) | [
"def",
"bytes_to_file",
"(",
"input_data",
",",
"output_file",
")",
":",
"pathlib",
".",
"Path",
"(",
"output_file",
".",
"parent",
")",
".",
"mkdir",
"(",
"parents",
"=",
"True",
",",
"exist_ok",
"=",
"True",
")",
"with",
"open",
"(",
"output_file",
",",
"\"wb\"",
")",
"as",
"file",
":",
"file",
".",
"write",
"(",
"input_data",
")"
] | Save bytes to a file. | [
"Save",
"bytes",
"to",
"a",
"file",
"."
] | train | https://github.com/dylanaraps/bum/blob/004d795a67398e79f2c098d7775e9cd97231646b/bum/util.py#L7-L12 |
dylanaraps/bum | bum/song.py | init | def init(port=6600, server="localhost"):
"""Initialize mpd."""
client = mpd.MPDClient()
try:
client.connect(server, port)
return client
except ConnectionRefusedError:
print("error: Connection refused to mpd/mopidy.")
os._exit(1) | python | def init(port=6600, server="localhost"):
"""Initialize mpd."""
client = mpd.MPDClient()
try:
client.connect(server, port)
return client
except ConnectionRefusedError:
print("error: Connection refused to mpd/mopidy.")
os._exit(1) | [
"def",
"init",
"(",
"port",
"=",
"6600",
",",
"server",
"=",
"\"localhost\"",
")",
":",
"client",
"=",
"mpd",
".",
"MPDClient",
"(",
")",
"try",
":",
"client",
".",
"connect",
"(",
"server",
",",
"port",
")",
"return",
"client",
"except",
"ConnectionRefusedError",
":",
"print",
"(",
"\"error: Connection refused to mpd/mopidy.\"",
")",
"os",
".",
"_exit",
"(",
"1",
")"
] | Initialize mpd. | [
"Initialize",
"mpd",
"."
] | train | https://github.com/dylanaraps/bum/blob/004d795a67398e79f2c098d7775e9cd97231646b/bum/song.py#L12-L22 |
dylanaraps/bum | bum/song.py | get_art | def get_art(cache_dir, size, client):
"""Get the album art."""
song = client.currentsong()
if len(song) < 2:
print("album: Nothing currently playing.")
return
file_name = f"{song['artist']}_{song['album']}_{size}.jpg".replace("/", "")
file_name = cache_dir / file_name
if file_name.is_file():
shutil.copy(file_name, cache_dir / "current.jpg")
print("album: Found cached art.")
else:
print("album: Downloading album art...")
brainz.init()
album_art = brainz.get_cover(song, size)
if album_art:
util.bytes_to_file(album_art, cache_dir / file_name)
util.bytes_to_file(album_art, cache_dir / "current.jpg")
print(f"album: Swapped art to {song['artist']}, {song['album']}.") | python | def get_art(cache_dir, size, client):
"""Get the album art."""
song = client.currentsong()
if len(song) < 2:
print("album: Nothing currently playing.")
return
file_name = f"{song['artist']}_{song['album']}_{size}.jpg".replace("/", "")
file_name = cache_dir / file_name
if file_name.is_file():
shutil.copy(file_name, cache_dir / "current.jpg")
print("album: Found cached art.")
else:
print("album: Downloading album art...")
brainz.init()
album_art = brainz.get_cover(song, size)
if album_art:
util.bytes_to_file(album_art, cache_dir / file_name)
util.bytes_to_file(album_art, cache_dir / "current.jpg")
print(f"album: Swapped art to {song['artist']}, {song['album']}.") | [
"def",
"get_art",
"(",
"cache_dir",
",",
"size",
",",
"client",
")",
":",
"song",
"=",
"client",
".",
"currentsong",
"(",
")",
"if",
"len",
"(",
"song",
")",
"<",
"2",
":",
"print",
"(",
"\"album: Nothing currently playing.\"",
")",
"return",
"file_name",
"=",
"f\"{song['artist']}_{song['album']}_{size}.jpg\"",
".",
"replace",
"(",
"\"/\"",
",",
"\"\"",
")",
"file_name",
"=",
"cache_dir",
"/",
"file_name",
"if",
"file_name",
".",
"is_file",
"(",
")",
":",
"shutil",
".",
"copy",
"(",
"file_name",
",",
"cache_dir",
"/",
"\"current.jpg\"",
")",
"print",
"(",
"\"album: Found cached art.\"",
")",
"else",
":",
"print",
"(",
"\"album: Downloading album art...\"",
")",
"brainz",
".",
"init",
"(",
")",
"album_art",
"=",
"brainz",
".",
"get_cover",
"(",
"song",
",",
"size",
")",
"if",
"album_art",
":",
"util",
".",
"bytes_to_file",
"(",
"album_art",
",",
"cache_dir",
"/",
"file_name",
")",
"util",
".",
"bytes_to_file",
"(",
"album_art",
",",
"cache_dir",
"/",
"\"current.jpg\"",
")",
"print",
"(",
"f\"album: Swapped art to {song['artist']}, {song['album']}.\"",
")"
] | Get the album art. | [
"Get",
"the",
"album",
"art",
"."
] | train | https://github.com/dylanaraps/bum/blob/004d795a67398e79f2c098d7775e9cd97231646b/bum/song.py#L25-L50 |
dylanaraps/bum | bum/brainz.py | get_cover | def get_cover(song, size=250):
"""Download the cover art."""
try:
data = mus.search_releases(artist=song["artist"],
release=song["album"],
limit=1)
release_id = data["release-list"][0]["release-group"]["id"]
print(f"album: Using release-id: {data['release-list'][0]['id']}")
return mus.get_release_group_image_front(release_id, size=size)
except mus.NetworkError:
get_cover(song, size)
except mus.ResponseError:
print("error: Couldn't find album art for",
f"{song['artist']} - {song['album']}") | python | def get_cover(song, size=250):
"""Download the cover art."""
try:
data = mus.search_releases(artist=song["artist"],
release=song["album"],
limit=1)
release_id = data["release-list"][0]["release-group"]["id"]
print(f"album: Using release-id: {data['release-list'][0]['id']}")
return mus.get_release_group_image_front(release_id, size=size)
except mus.NetworkError:
get_cover(song, size)
except mus.ResponseError:
print("error: Couldn't find album art for",
f"{song['artist']} - {song['album']}") | [
"def",
"get_cover",
"(",
"song",
",",
"size",
"=",
"250",
")",
":",
"try",
":",
"data",
"=",
"mus",
".",
"search_releases",
"(",
"artist",
"=",
"song",
"[",
"\"artist\"",
"]",
",",
"release",
"=",
"song",
"[",
"\"album\"",
"]",
",",
"limit",
"=",
"1",
")",
"release_id",
"=",
"data",
"[",
"\"release-list\"",
"]",
"[",
"0",
"]",
"[",
"\"release-group\"",
"]",
"[",
"\"id\"",
"]",
"print",
"(",
"f\"album: Using release-id: {data['release-list'][0]['id']}\"",
")",
"return",
"mus",
".",
"get_release_group_image_front",
"(",
"release_id",
",",
"size",
"=",
"size",
")",
"except",
"mus",
".",
"NetworkError",
":",
"get_cover",
"(",
"song",
",",
"size",
")",
"except",
"mus",
".",
"ResponseError",
":",
"print",
"(",
"\"error: Couldn't find album art for\"",
",",
"f\"{song['artist']} - {song['album']}\"",
")"
] | Download the cover art. | [
"Download",
"the",
"cover",
"art",
"."
] | train | https://github.com/dylanaraps/bum/blob/004d795a67398e79f2c098d7775e9cd97231646b/bum/brainz.py#L16-L32 |
dylanaraps/bum | bum/__main__.py | get_args | def get_args():
"""Get the script arguments."""
description = "bum - Download and display album art \
for mpd tracks."
arg = argparse.ArgumentParser(description=description)
arg.add_argument("--size", metavar="\"px\"",
help="what size to display the album art in.",
default=250)
arg.add_argument("--cache_dir", metavar="\"/path/to/dir\"",
help="Where to store the downloaded cover art.",
default=pathlib.Path.home() / ".cache/bum")
arg.add_argument("--version", action="store_true",
help="Print \"bum\" version.")
arg.add_argument("--port",
help="Use a custom mpd port.",
default=6600)
arg.add_argument("--server",
help="Use a remote server instead of localhost.",
default="localhost")
arg.add_argument("--no_display",
action="store_true",
help="Only download album art, don't display.")
return arg.parse_args() | python | def get_args():
"""Get the script arguments."""
description = "bum - Download and display album art \
for mpd tracks."
arg = argparse.ArgumentParser(description=description)
arg.add_argument("--size", metavar="\"px\"",
help="what size to display the album art in.",
default=250)
arg.add_argument("--cache_dir", metavar="\"/path/to/dir\"",
help="Where to store the downloaded cover art.",
default=pathlib.Path.home() / ".cache/bum")
arg.add_argument("--version", action="store_true",
help="Print \"bum\" version.")
arg.add_argument("--port",
help="Use a custom mpd port.",
default=6600)
arg.add_argument("--server",
help="Use a remote server instead of localhost.",
default="localhost")
arg.add_argument("--no_display",
action="store_true",
help="Only download album art, don't display.")
return arg.parse_args() | [
"def",
"get_args",
"(",
")",
":",
"description",
"=",
"\"bum - Download and display album art \\\n for mpd tracks.\"",
"arg",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"description",
")",
"arg",
".",
"add_argument",
"(",
"\"--size\"",
",",
"metavar",
"=",
"\"\\\"px\\\"\"",
",",
"help",
"=",
"\"what size to display the album art in.\"",
",",
"default",
"=",
"250",
")",
"arg",
".",
"add_argument",
"(",
"\"--cache_dir\"",
",",
"metavar",
"=",
"\"\\\"/path/to/dir\\\"\"",
",",
"help",
"=",
"\"Where to store the downloaded cover art.\"",
",",
"default",
"=",
"pathlib",
".",
"Path",
".",
"home",
"(",
")",
"/",
"\".cache/bum\"",
")",
"arg",
".",
"add_argument",
"(",
"\"--version\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Print \\\"bum\\\" version.\"",
")",
"arg",
".",
"add_argument",
"(",
"\"--port\"",
",",
"help",
"=",
"\"Use a custom mpd port.\"",
",",
"default",
"=",
"6600",
")",
"arg",
".",
"add_argument",
"(",
"\"--server\"",
",",
"help",
"=",
"\"Use a remote server instead of localhost.\"",
",",
"default",
"=",
"\"localhost\"",
")",
"arg",
".",
"add_argument",
"(",
"\"--no_display\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Only download album art, don't display.\"",
")",
"return",
"arg",
".",
"parse_args",
"(",
")"
] | Get the script arguments. | [
"Get",
"the",
"script",
"arguments",
"."
] | train | https://github.com/dylanaraps/bum/blob/004d795a67398e79f2c098d7775e9cd97231646b/bum/__main__.py#L19-L48 |
dylanaraps/bum | bum/__main__.py | main | def main():
"""Main script function."""
args = get_args()
process_args(args)
if not args.no_display:
disp = display.init(args.size)
client = song.init(args.port, args.server)
while True:
song.get_art(args.cache_dir, args.size, client)
if not args.no_display:
display.launch(disp, args.cache_dir / "current.jpg")
client.send_idle()
if client.fetch_idle(["player"]):
print("album: Received player event from mpd. Swapping cover art.")
continue | python | def main():
"""Main script function."""
args = get_args()
process_args(args)
if not args.no_display:
disp = display.init(args.size)
client = song.init(args.port, args.server)
while True:
song.get_art(args.cache_dir, args.size, client)
if not args.no_display:
display.launch(disp, args.cache_dir / "current.jpg")
client.send_idle()
if client.fetch_idle(["player"]):
print("album: Received player event from mpd. Swapping cover art.")
continue | [
"def",
"main",
"(",
")",
":",
"args",
"=",
"get_args",
"(",
")",
"process_args",
"(",
"args",
")",
"if",
"not",
"args",
".",
"no_display",
":",
"disp",
"=",
"display",
".",
"init",
"(",
"args",
".",
"size",
")",
"client",
"=",
"song",
".",
"init",
"(",
"args",
".",
"port",
",",
"args",
".",
"server",
")",
"while",
"True",
":",
"song",
".",
"get_art",
"(",
"args",
".",
"cache_dir",
",",
"args",
".",
"size",
",",
"client",
")",
"if",
"not",
"args",
".",
"no_display",
":",
"display",
".",
"launch",
"(",
"disp",
",",
"args",
".",
"cache_dir",
"/",
"\"current.jpg\"",
")",
"client",
".",
"send_idle",
"(",
")",
"if",
"client",
".",
"fetch_idle",
"(",
"[",
"\"player\"",
"]",
")",
":",
"print",
"(",
"\"album: Received player event from mpd. Swapping cover art.\"",
")",
"continue"
] | Main script function. | [
"Main",
"script",
"function",
"."
] | train | https://github.com/dylanaraps/bum/blob/004d795a67398e79f2c098d7775e9cd97231646b/bum/__main__.py#L58-L77 |
proycon/clam | clam/common/converters.py | AbstractConverter.convertforinput | def convertforinput(self,filepath, metadata):
"""Convert from target format into one of the source formats. Relevant if converters are used in InputTemplates. Metadata already is metadata for the to-be-generated file. 'filepath' is both the source and the target file, the source file will be erased and overwritten with the conversion result!"""
assert isinstance(metadata, CLAMMetaData) #metadata of the destination file (file to be generated here)
if not metadata.__class__ in self.acceptforinput:
raise Exception("Convertor " + self.__class__.__name__ + " can not convert input files to " + metadata.__class__.__name__ + "!")
return False | python | def convertforinput(self,filepath, metadata):
"""Convert from target format into one of the source formats. Relevant if converters are used in InputTemplates. Metadata already is metadata for the to-be-generated file. 'filepath' is both the source and the target file, the source file will be erased and overwritten with the conversion result!"""
assert isinstance(metadata, CLAMMetaData) #metadata of the destination file (file to be generated here)
if not metadata.__class__ in self.acceptforinput:
raise Exception("Convertor " + self.__class__.__name__ + " can not convert input files to " + metadata.__class__.__name__ + "!")
return False | [
"def",
"convertforinput",
"(",
"self",
",",
"filepath",
",",
"metadata",
")",
":",
"assert",
"isinstance",
"(",
"metadata",
",",
"CLAMMetaData",
")",
"#metadata of the destination file (file to be generated here)",
"if",
"not",
"metadata",
".",
"__class__",
"in",
"self",
".",
"acceptforinput",
":",
"raise",
"Exception",
"(",
"\"Convertor \"",
"+",
"self",
".",
"__class__",
".",
"__name__",
"+",
"\" can not convert input files to \"",
"+",
"metadata",
".",
"__class__",
".",
"__name__",
"+",
"\"!\"",
")",
"return",
"False"
] | Convert from target format into one of the source formats. Relevant if converters are used in InputTemplates. Metadata already is metadata for the to-be-generated file. 'filepath' is both the source and the target file, the source file will be erased and overwritten with the conversion result! | [
"Convert",
"from",
"target",
"format",
"into",
"one",
"of",
"the",
"source",
"formats",
".",
"Relevant",
"if",
"converters",
"are",
"used",
"in",
"InputTemplates",
".",
"Metadata",
"already",
"is",
"metadata",
"for",
"the",
"to",
"-",
"be",
"-",
"generated",
"file",
".",
"filepath",
"is",
"both",
"the",
"source",
"and",
"the",
"target",
"file",
"the",
"source",
"file",
"will",
"be",
"erased",
"and",
"overwritten",
"with",
"the",
"conversion",
"result!"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/converters.py#L37-L42 |
proycon/clam | clam/common/converters.py | AbstractConverter.convertforoutput | def convertforoutput(self,outputfile):
"""Convert from one of the source formats into target format. Relevant if converters are used in OutputTemplates. Sourcefile is a CLAMOutputFile instance."""
assert isinstance(outputfile, CLAMOutputFile) #metadata of the destination file (file to be generated here)
if not outputfile.metadata.__class__ in self.acceptforoutput:
raise Exception("Convertor " + self.__class__.__name__ + " can not convert input files to " + outputfile.metadata.__class__.__name__ + "!")
return [] | python | def convertforoutput(self,outputfile):
"""Convert from one of the source formats into target format. Relevant if converters are used in OutputTemplates. Sourcefile is a CLAMOutputFile instance."""
assert isinstance(outputfile, CLAMOutputFile) #metadata of the destination file (file to be generated here)
if not outputfile.metadata.__class__ in self.acceptforoutput:
raise Exception("Convertor " + self.__class__.__name__ + " can not convert input files to " + outputfile.metadata.__class__.__name__ + "!")
return [] | [
"def",
"convertforoutput",
"(",
"self",
",",
"outputfile",
")",
":",
"assert",
"isinstance",
"(",
"outputfile",
",",
"CLAMOutputFile",
")",
"#metadata of the destination file (file to be generated here)",
"if",
"not",
"outputfile",
".",
"metadata",
".",
"__class__",
"in",
"self",
".",
"acceptforoutput",
":",
"raise",
"Exception",
"(",
"\"Convertor \"",
"+",
"self",
".",
"__class__",
".",
"__name__",
"+",
"\" can not convert input files to \"",
"+",
"outputfile",
".",
"metadata",
".",
"__class__",
".",
"__name__",
"+",
"\"!\"",
")",
"return",
"[",
"]"
] | Convert from one of the source formats into target format. Relevant if converters are used in OutputTemplates. Sourcefile is a CLAMOutputFile instance. | [
"Convert",
"from",
"one",
"of",
"the",
"source",
"formats",
"into",
"target",
"format",
".",
"Relevant",
"if",
"converters",
"are",
"used",
"in",
"OutputTemplates",
".",
"Sourcefile",
"is",
"a",
"CLAMOutputFile",
"instance",
"."
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/converters.py#L44-L49 |
proycon/clam | clam/common/converters.py | CharEncodingConverter.convertforinput | def convertforinput(self,filepath, metadata=None):
"""Convert from target format into one of the source formats. Relevant if converters are used in InputTemplates. Metadata already is metadata for the to-be-generated file."""
super(CharEncodingConverter,self).convertforinput(filepath, metadata)
shutil.copy(filepath, filepath + '.convertsource')
try:
fsource = io.open(filepath + '.convertsource','r',encoding=self.charset)
ftarget = io.open(filepath,'w',encoding=metadata['encoding'])
for line in fsource:
ftarget.write(line + "\n")
success = True
except:
ftarget.close()
fsource.fclose()
success = False
finally:
os.unlink(filepath + '.convertsource')
return success | python | def convertforinput(self,filepath, metadata=None):
"""Convert from target format into one of the source formats. Relevant if converters are used in InputTemplates. Metadata already is metadata for the to-be-generated file."""
super(CharEncodingConverter,self).convertforinput(filepath, metadata)
shutil.copy(filepath, filepath + '.convertsource')
try:
fsource = io.open(filepath + '.convertsource','r',encoding=self.charset)
ftarget = io.open(filepath,'w',encoding=metadata['encoding'])
for line in fsource:
ftarget.write(line + "\n")
success = True
except:
ftarget.close()
fsource.fclose()
success = False
finally:
os.unlink(filepath + '.convertsource')
return success | [
"def",
"convertforinput",
"(",
"self",
",",
"filepath",
",",
"metadata",
"=",
"None",
")",
":",
"super",
"(",
"CharEncodingConverter",
",",
"self",
")",
".",
"convertforinput",
"(",
"filepath",
",",
"metadata",
")",
"shutil",
".",
"copy",
"(",
"filepath",
",",
"filepath",
"+",
"'.convertsource'",
")",
"try",
":",
"fsource",
"=",
"io",
".",
"open",
"(",
"filepath",
"+",
"'.convertsource'",
",",
"'r'",
",",
"encoding",
"=",
"self",
".",
"charset",
")",
"ftarget",
"=",
"io",
".",
"open",
"(",
"filepath",
",",
"'w'",
",",
"encoding",
"=",
"metadata",
"[",
"'encoding'",
"]",
")",
"for",
"line",
"in",
"fsource",
":",
"ftarget",
".",
"write",
"(",
"line",
"+",
"\"\\n\"",
")",
"success",
"=",
"True",
"except",
":",
"ftarget",
".",
"close",
"(",
")",
"fsource",
".",
"fclose",
"(",
")",
"success",
"=",
"False",
"finally",
":",
"os",
".",
"unlink",
"(",
"filepath",
"+",
"'.convertsource'",
")",
"return",
"success"
] | Convert from target format into one of the source formats. Relevant if converters are used in InputTemplates. Metadata already is metadata for the to-be-generated file. | [
"Convert",
"from",
"target",
"format",
"into",
"one",
"of",
"the",
"source",
"formats",
".",
"Relevant",
"if",
"converters",
"are",
"used",
"in",
"InputTemplates",
".",
"Metadata",
"already",
"is",
"metadata",
"for",
"the",
"to",
"-",
"be",
"-",
"generated",
"file",
"."
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/converters.py#L71-L90 |
proycon/clam | clam/common/converters.py | CharEncodingConverter.convertforoutput | def convertforoutput(self,outputfile):
"""Convert from one of the source formats into target format. Relevant if converters are used in OutputTemplates. Outputfile is a CLAMOutputFile instance."""
super(CharEncodingConverter,self).convertforoutput(outputfile)
return withheaders( flask.make_response( ( line.encode(self.charset) for line in outputfile ) ) , 'text/plain; charset=' + self.charset) | python | def convertforoutput(self,outputfile):
"""Convert from one of the source formats into target format. Relevant if converters are used in OutputTemplates. Outputfile is a CLAMOutputFile instance."""
super(CharEncodingConverter,self).convertforoutput(outputfile)
return withheaders( flask.make_response( ( line.encode(self.charset) for line in outputfile ) ) , 'text/plain; charset=' + self.charset) | [
"def",
"convertforoutput",
"(",
"self",
",",
"outputfile",
")",
":",
"super",
"(",
"CharEncodingConverter",
",",
"self",
")",
".",
"convertforoutput",
"(",
"outputfile",
")",
"return",
"withheaders",
"(",
"flask",
".",
"make_response",
"(",
"(",
"line",
".",
"encode",
"(",
"self",
".",
"charset",
")",
"for",
"line",
"in",
"outputfile",
")",
")",
",",
"'text/plain; charset='",
"+",
"self",
".",
"charset",
")"
] | Convert from one of the source formats into target format. Relevant if converters are used in OutputTemplates. Outputfile is a CLAMOutputFile instance. | [
"Convert",
"from",
"one",
"of",
"the",
"source",
"formats",
"into",
"target",
"format",
".",
"Relevant",
"if",
"converters",
"are",
"used",
"in",
"OutputTemplates",
".",
"Outputfile",
"is",
"a",
"CLAMOutputFile",
"instance",
"."
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/converters.py#L93-L97 |
proycon/clam | clam/common/data.py | getclamdata | def getclamdata(filename, custom_formats=None):
global CUSTOM_FORMATS #pylint: disable=global-statement
"""This function reads the CLAM Data from an XML file. Use this to read
the clam.xml file from your system wrapper. It returns a CLAMData instance.
If you make use of CUSTOM_FORMATS, you need to pass the CUSTOM_FORMATS list as 2nd argument.
"""
f = io.open(filename,'r',encoding='utf-8')
xml = f.read(os.path.getsize(filename))
f.close()
if custom_formats:
CUSTOM_FORMATS = custom_formats #dependency injection for CUSTOM_FORMATS
return CLAMData(xml, None, True) | python | def getclamdata(filename, custom_formats=None):
global CUSTOM_FORMATS #pylint: disable=global-statement
"""This function reads the CLAM Data from an XML file. Use this to read
the clam.xml file from your system wrapper. It returns a CLAMData instance.
If you make use of CUSTOM_FORMATS, you need to pass the CUSTOM_FORMATS list as 2nd argument.
"""
f = io.open(filename,'r',encoding='utf-8')
xml = f.read(os.path.getsize(filename))
f.close()
if custom_formats:
CUSTOM_FORMATS = custom_formats #dependency injection for CUSTOM_FORMATS
return CLAMData(xml, None, True) | [
"def",
"getclamdata",
"(",
"filename",
",",
"custom_formats",
"=",
"None",
")",
":",
"global",
"CUSTOM_FORMATS",
"#pylint: disable=global-statement",
"f",
"=",
"io",
".",
"open",
"(",
"filename",
",",
"'r'",
",",
"encoding",
"=",
"'utf-8'",
")",
"xml",
"=",
"f",
".",
"read",
"(",
"os",
".",
"path",
".",
"getsize",
"(",
"filename",
")",
")",
"f",
".",
"close",
"(",
")",
"if",
"custom_formats",
":",
"CUSTOM_FORMATS",
"=",
"custom_formats",
"#dependency injection for CUSTOM_FORMATS",
"return",
"CLAMData",
"(",
"xml",
",",
"None",
",",
"True",
")"
] | This function reads the CLAM Data from an XML file. Use this to read
the clam.xml file from your system wrapper. It returns a CLAMData instance.
If you make use of CUSTOM_FORMATS, you need to pass the CUSTOM_FORMATS list as 2nd argument. | [
"This",
"function",
"reads",
"the",
"CLAM",
"Data",
"from",
"an",
"XML",
"file",
".",
"Use",
"this",
"to",
"read",
"the",
"clam",
".",
"xml",
"file",
"from",
"your",
"system",
"wrapper",
".",
"It",
"returns",
"a",
"CLAMData",
"instance",
"."
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L379-L391 |
proycon/clam | clam/common/data.py | sanitizeparameters | def sanitizeparameters(parameters):
"""Construct a dictionary of parameters, for internal use only"""
if not isinstance(parameters,dict):
d = {}
for x in parameters:
if isinstance(x,tuple) and len(x) == 2:
for parameter in x[1]:
d[parameter.id] = parameter
elif isinstance(x, clam.common.parameters.AbstractParameter):
d[x.id] = x
return d
else:
return parameters | python | def sanitizeparameters(parameters):
"""Construct a dictionary of parameters, for internal use only"""
if not isinstance(parameters,dict):
d = {}
for x in parameters:
if isinstance(x,tuple) and len(x) == 2:
for parameter in x[1]:
d[parameter.id] = parameter
elif isinstance(x, clam.common.parameters.AbstractParameter):
d[x.id] = x
return d
else:
return parameters | [
"def",
"sanitizeparameters",
"(",
"parameters",
")",
":",
"if",
"not",
"isinstance",
"(",
"parameters",
",",
"dict",
")",
":",
"d",
"=",
"{",
"}",
"for",
"x",
"in",
"parameters",
":",
"if",
"isinstance",
"(",
"x",
",",
"tuple",
")",
"and",
"len",
"(",
"x",
")",
"==",
"2",
":",
"for",
"parameter",
"in",
"x",
"[",
"1",
"]",
":",
"d",
"[",
"parameter",
".",
"id",
"]",
"=",
"parameter",
"elif",
"isinstance",
"(",
"x",
",",
"clam",
".",
"common",
".",
"parameters",
".",
"AbstractParameter",
")",
":",
"d",
"[",
"x",
".",
"id",
"]",
"=",
"x",
"return",
"d",
"else",
":",
"return",
"parameters"
] | Construct a dictionary of parameters, for internal use only | [
"Construct",
"a",
"dictionary",
"of",
"parameters",
"for",
"internal",
"use",
"only"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L773-L785 |
proycon/clam | clam/common/data.py | profiler | def profiler(profiles, projectpath,parameters,serviceid,servicename,serviceurl,printdebug=None):
"""Given input files and parameters, produce metadata for outputfiles. Returns a list of matched profiles (empty if none match), and a program."""
parameters = sanitizeparameters(parameters)
matched = []
program = Program(projectpath)
for profile in profiles:
if profile.match(projectpath, parameters)[0]:
matched.append(profile)
program.update( profile.generate(projectpath,parameters,serviceid,servicename,serviceurl) )
return matched, program | python | def profiler(profiles, projectpath,parameters,serviceid,servicename,serviceurl,printdebug=None):
"""Given input files and parameters, produce metadata for outputfiles. Returns a list of matched profiles (empty if none match), and a program."""
parameters = sanitizeparameters(parameters)
matched = []
program = Program(projectpath)
for profile in profiles:
if profile.match(projectpath, parameters)[0]:
matched.append(profile)
program.update( profile.generate(projectpath,parameters,serviceid,servicename,serviceurl) )
return matched, program | [
"def",
"profiler",
"(",
"profiles",
",",
"projectpath",
",",
"parameters",
",",
"serviceid",
",",
"servicename",
",",
"serviceurl",
",",
"printdebug",
"=",
"None",
")",
":",
"parameters",
"=",
"sanitizeparameters",
"(",
"parameters",
")",
"matched",
"=",
"[",
"]",
"program",
"=",
"Program",
"(",
"projectpath",
")",
"for",
"profile",
"in",
"profiles",
":",
"if",
"profile",
".",
"match",
"(",
"projectpath",
",",
"parameters",
")",
"[",
"0",
"]",
":",
"matched",
".",
"append",
"(",
"profile",
")",
"program",
".",
"update",
"(",
"profile",
".",
"generate",
"(",
"projectpath",
",",
"parameters",
",",
"serviceid",
",",
"servicename",
",",
"serviceurl",
")",
")",
"return",
"matched",
",",
"program"
] | Given input files and parameters, produce metadata for outputfiles. Returns a list of matched profiles (empty if none match), and a program. | [
"Given",
"input",
"files",
"and",
"parameters",
"produce",
"metadata",
"for",
"outputfiles",
".",
"Returns",
"a",
"list",
"of",
"matched",
"profiles",
"(",
"empty",
"if",
"none",
"match",
")",
"and",
"a",
"program",
"."
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L789-L801 |
proycon/clam | clam/common/data.py | shellsafe | def shellsafe(s, quote='', doescape=True):
"""Returns the value string, wrapped in the specified quotes (if not empty), but checks and raises an Exception if the string is at risk of causing code injection"""
if sys.version[0] == '2' and not isinstance(s,unicode): #pylint: disable=undefined-variable
s = unicode(s,'utf-8') #pylint: disable=undefined-variable
if len(s) > 1024:
raise ValueError("Variable value rejected for security reasons: too long")
if quote:
if quote in s:
if doescape:
s = escape(s,quote)
else:
raise ValueError("Variable value rejected for security reasons: " + s)
return quote + s + quote
else:
for c in s:
if c in DISALLOWINSHELLSAFE:
raise ValueError("Variable value rejected for security reasons: " + s)
return s | python | def shellsafe(s, quote='', doescape=True):
"""Returns the value string, wrapped in the specified quotes (if not empty), but checks and raises an Exception if the string is at risk of causing code injection"""
if sys.version[0] == '2' and not isinstance(s,unicode): #pylint: disable=undefined-variable
s = unicode(s,'utf-8') #pylint: disable=undefined-variable
if len(s) > 1024:
raise ValueError("Variable value rejected for security reasons: too long")
if quote:
if quote in s:
if doescape:
s = escape(s,quote)
else:
raise ValueError("Variable value rejected for security reasons: " + s)
return quote + s + quote
else:
for c in s:
if c in DISALLOWINSHELLSAFE:
raise ValueError("Variable value rejected for security reasons: " + s)
return s | [
"def",
"shellsafe",
"(",
"s",
",",
"quote",
"=",
"''",
",",
"doescape",
"=",
"True",
")",
":",
"if",
"sys",
".",
"version",
"[",
"0",
"]",
"==",
"'2'",
"and",
"not",
"isinstance",
"(",
"s",
",",
"unicode",
")",
":",
"#pylint: disable=undefined-variable",
"s",
"=",
"unicode",
"(",
"s",
",",
"'utf-8'",
")",
"#pylint: disable=undefined-variable",
"if",
"len",
"(",
"s",
")",
">",
"1024",
":",
"raise",
"ValueError",
"(",
"\"Variable value rejected for security reasons: too long\"",
")",
"if",
"quote",
":",
"if",
"quote",
"in",
"s",
":",
"if",
"doescape",
":",
"s",
"=",
"escape",
"(",
"s",
",",
"quote",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Variable value rejected for security reasons: \"",
"+",
"s",
")",
"return",
"quote",
"+",
"s",
"+",
"quote",
"else",
":",
"for",
"c",
"in",
"s",
":",
"if",
"c",
"in",
"DISALLOWINSHELLSAFE",
":",
"raise",
"ValueError",
"(",
"\"Variable value rejected for security reasons: \"",
"+",
"s",
")",
"return",
"s"
] | Returns the value string, wrapped in the specified quotes (if not empty), but checks and raises an Exception if the string is at risk of causing code injection | [
"Returns",
"the",
"value",
"string",
"wrapped",
"in",
"the",
"specified",
"quotes",
"(",
"if",
"not",
"empty",
")",
"but",
"checks",
"and",
"raises",
"an",
"Exception",
"if",
"the",
"string",
"is",
"at",
"risk",
"of",
"causing",
"code",
"injection"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L2417-L2434 |
proycon/clam | clam/common/data.py | CLAMFile.attachviewers | def attachviewers(self, profiles):
"""Attach viewers *and converters* to file, automatically scan all profiles for outputtemplate or inputtemplate"""
if self.metadata:
template = None
for profile in profiles:
if isinstance(self, CLAMInputFile):
for t in profile.input:
if self.metadata.inputtemplate == t.id:
template = t
break
elif isinstance(self, CLAMOutputFile) and self.metadata and self.metadata.provenance:
for t in profile.outputtemplates():
if self.metadata.provenance.outputtemplate_id == t.id:
template = t
break
else:
raise NotImplementedError #Is ok, nothing to implement for now
if template:
break
if template and template.viewers:
for viewer in template.viewers:
self.viewers.append(viewer)
if template and template.converters:
for converter in template.converters:
self.converters.append(converter) | python | def attachviewers(self, profiles):
"""Attach viewers *and converters* to file, automatically scan all profiles for outputtemplate or inputtemplate"""
if self.metadata:
template = None
for profile in profiles:
if isinstance(self, CLAMInputFile):
for t in profile.input:
if self.metadata.inputtemplate == t.id:
template = t
break
elif isinstance(self, CLAMOutputFile) and self.metadata and self.metadata.provenance:
for t in profile.outputtemplates():
if self.metadata.provenance.outputtemplate_id == t.id:
template = t
break
else:
raise NotImplementedError #Is ok, nothing to implement for now
if template:
break
if template and template.viewers:
for viewer in template.viewers:
self.viewers.append(viewer)
if template and template.converters:
for converter in template.converters:
self.converters.append(converter) | [
"def",
"attachviewers",
"(",
"self",
",",
"profiles",
")",
":",
"if",
"self",
".",
"metadata",
":",
"template",
"=",
"None",
"for",
"profile",
"in",
"profiles",
":",
"if",
"isinstance",
"(",
"self",
",",
"CLAMInputFile",
")",
":",
"for",
"t",
"in",
"profile",
".",
"input",
":",
"if",
"self",
".",
"metadata",
".",
"inputtemplate",
"==",
"t",
".",
"id",
":",
"template",
"=",
"t",
"break",
"elif",
"isinstance",
"(",
"self",
",",
"CLAMOutputFile",
")",
"and",
"self",
".",
"metadata",
"and",
"self",
".",
"metadata",
".",
"provenance",
":",
"for",
"t",
"in",
"profile",
".",
"outputtemplates",
"(",
")",
":",
"if",
"self",
".",
"metadata",
".",
"provenance",
".",
"outputtemplate_id",
"==",
"t",
".",
"id",
":",
"template",
"=",
"t",
"break",
"else",
":",
"raise",
"NotImplementedError",
"#Is ok, nothing to implement for now",
"if",
"template",
":",
"break",
"if",
"template",
"and",
"template",
".",
"viewers",
":",
"for",
"viewer",
"in",
"template",
".",
"viewers",
":",
"self",
".",
"viewers",
".",
"append",
"(",
"viewer",
")",
"if",
"template",
"and",
"template",
".",
"converters",
":",
"for",
"converter",
"in",
"template",
".",
"converters",
":",
"self",
".",
"converters",
".",
"append",
"(",
"converter",
")"
] | Attach viewers *and converters* to file, automatically scan all profiles for outputtemplate or inputtemplate | [
"Attach",
"viewers",
"*",
"and",
"converters",
"*",
"to",
"file",
"automatically",
"scan",
"all",
"profiles",
"for",
"outputtemplate",
"or",
"inputtemplate"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L204-L228 |
proycon/clam | clam/common/data.py | CLAMFile.metafilename | def metafilename(self):
"""Returns the filename for the metadata file (not full path). Only used for local files."""
metafilename = os.path.dirname(self.filename)
if metafilename: metafilename += '/'
metafilename += '.' + os.path.basename(self.filename) + '.METADATA'
return metafilename | python | def metafilename(self):
"""Returns the filename for the metadata file (not full path). Only used for local files."""
metafilename = os.path.dirname(self.filename)
if metafilename: metafilename += '/'
metafilename += '.' + os.path.basename(self.filename) + '.METADATA'
return metafilename | [
"def",
"metafilename",
"(",
"self",
")",
":",
"metafilename",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"filename",
")",
"if",
"metafilename",
":",
"metafilename",
"+=",
"'/'",
"metafilename",
"+=",
"'.'",
"+",
"os",
".",
"path",
".",
"basename",
"(",
"self",
".",
"filename",
")",
"+",
"'.METADATA'",
"return",
"metafilename"
] | Returns the filename for the metadata file (not full path). Only used for local files. | [
"Returns",
"the",
"filename",
"for",
"the",
"metadata",
"file",
"(",
"not",
"full",
"path",
")",
".",
"Only",
"used",
"for",
"local",
"files",
"."
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L230-L235 |
proycon/clam | clam/common/data.py | CLAMFile.loadmetadata | def loadmetadata(self):
"""Load metadata for this file. This is usually called automatically upon instantiation, except if explicitly disabled. Works both locally as well as for clients connecting to a CLAM service."""
if not self.remote:
metafile = self.projectpath + self.basedir + '/' + self.metafilename()
if os.path.exists(metafile):
f = io.open(metafile, 'r',encoding='utf-8')
xml = "".join(f.readlines())
f.close()
else:
raise IOError(2, "No metadata found, expected " + metafile )
else:
if self.client:
requestparams = self.client.initrequest()
else:
requestparams = {}
response = requests.get(self.projectpath + self.basedir + '/' + self.filename + '/metadata', **requestparams)
if response.status_code != 200:
extramsg = ""
if not self.client: extramsg = "No client was associated with this CLAMFile, associating a client is necessary when authentication is needed"
raise HTTPError(2, "Can't download metadata for " + self.filename + ". " + extramsg)
xml = response.text
#parse metadata
try:
self.metadata = CLAMMetaData.fromxml(xml, self) #returns CLAMMetaData object (or child thereof)
except ElementTree.XMLSyntaxError:
raise ValueError("Metadata is not XML! Contents: " + xml) | python | def loadmetadata(self):
"""Load metadata for this file. This is usually called automatically upon instantiation, except if explicitly disabled. Works both locally as well as for clients connecting to a CLAM service."""
if not self.remote:
metafile = self.projectpath + self.basedir + '/' + self.metafilename()
if os.path.exists(metafile):
f = io.open(metafile, 'r',encoding='utf-8')
xml = "".join(f.readlines())
f.close()
else:
raise IOError(2, "No metadata found, expected " + metafile )
else:
if self.client:
requestparams = self.client.initrequest()
else:
requestparams = {}
response = requests.get(self.projectpath + self.basedir + '/' + self.filename + '/metadata', **requestparams)
if response.status_code != 200:
extramsg = ""
if not self.client: extramsg = "No client was associated with this CLAMFile, associating a client is necessary when authentication is needed"
raise HTTPError(2, "Can't download metadata for " + self.filename + ". " + extramsg)
xml = response.text
#parse metadata
try:
self.metadata = CLAMMetaData.fromxml(xml, self) #returns CLAMMetaData object (or child thereof)
except ElementTree.XMLSyntaxError:
raise ValueError("Metadata is not XML! Contents: " + xml) | [
"def",
"loadmetadata",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"remote",
":",
"metafile",
"=",
"self",
".",
"projectpath",
"+",
"self",
".",
"basedir",
"+",
"'/'",
"+",
"self",
".",
"metafilename",
"(",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"metafile",
")",
":",
"f",
"=",
"io",
".",
"open",
"(",
"metafile",
",",
"'r'",
",",
"encoding",
"=",
"'utf-8'",
")",
"xml",
"=",
"\"\"",
".",
"join",
"(",
"f",
".",
"readlines",
"(",
")",
")",
"f",
".",
"close",
"(",
")",
"else",
":",
"raise",
"IOError",
"(",
"2",
",",
"\"No metadata found, expected \"",
"+",
"metafile",
")",
"else",
":",
"if",
"self",
".",
"client",
":",
"requestparams",
"=",
"self",
".",
"client",
".",
"initrequest",
"(",
")",
"else",
":",
"requestparams",
"=",
"{",
"}",
"response",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"projectpath",
"+",
"self",
".",
"basedir",
"+",
"'/'",
"+",
"self",
".",
"filename",
"+",
"'/metadata'",
",",
"*",
"*",
"requestparams",
")",
"if",
"response",
".",
"status_code",
"!=",
"200",
":",
"extramsg",
"=",
"\"\"",
"if",
"not",
"self",
".",
"client",
":",
"extramsg",
"=",
"\"No client was associated with this CLAMFile, associating a client is necessary when authentication is needed\"",
"raise",
"HTTPError",
"(",
"2",
",",
"\"Can't download metadata for \"",
"+",
"self",
".",
"filename",
"+",
"\". \"",
"+",
"extramsg",
")",
"xml",
"=",
"response",
".",
"text",
"#parse metadata",
"try",
":",
"self",
".",
"metadata",
"=",
"CLAMMetaData",
".",
"fromxml",
"(",
"xml",
",",
"self",
")",
"#returns CLAMMetaData object (or child thereof)",
"except",
"ElementTree",
".",
"XMLSyntaxError",
":",
"raise",
"ValueError",
"(",
"\"Metadata is not XML! Contents: \"",
"+",
"xml",
")"
] | Load metadata for this file. This is usually called automatically upon instantiation, except if explicitly disabled. Works both locally as well as for clients connecting to a CLAM service. | [
"Load",
"metadata",
"for",
"this",
"file",
".",
"This",
"is",
"usually",
"called",
"automatically",
"upon",
"instantiation",
"except",
"if",
"explicitly",
"disabled",
".",
"Works",
"both",
"locally",
"as",
"well",
"as",
"for",
"clients",
"connecting",
"to",
"a",
"CLAM",
"service",
"."
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L237-L264 |
proycon/clam | clam/common/data.py | CLAMFile.delete | def delete(self):
"""Delete this file"""
if not self.remote:
if not os.path.exists(self.projectpath + self.basedir + '/' + self.filename):
return False
else:
os.unlink(self.projectpath + self.basedir + '/' + self.filename)
#Remove metadata
metafile = self.projectpath + self.basedir + '/' + self.metafilename()
if os.path.exists(metafile):
os.unlink(metafile)
#also remove any .*.INPUTTEMPLATE.* links that pointed to this file: simply remove all dead links
for linkf,realf in clam.common.util.globsymlinks(self.projectpath + self.basedir + '/.*.INPUTTEMPLATE.*'):
if not os.path.exists(realf):
os.unlink(linkf)
return True
else:
if self.client:
requestparams = self.client.initrequest()
else:
requestparams = {}
requests.delete( self.projectpath + self.basedir + '/' + self.filename, **requestparams)
return True | python | def delete(self):
"""Delete this file"""
if not self.remote:
if not os.path.exists(self.projectpath + self.basedir + '/' + self.filename):
return False
else:
os.unlink(self.projectpath + self.basedir + '/' + self.filename)
#Remove metadata
metafile = self.projectpath + self.basedir + '/' + self.metafilename()
if os.path.exists(metafile):
os.unlink(metafile)
#also remove any .*.INPUTTEMPLATE.* links that pointed to this file: simply remove all dead links
for linkf,realf in clam.common.util.globsymlinks(self.projectpath + self.basedir + '/.*.INPUTTEMPLATE.*'):
if not os.path.exists(realf):
os.unlink(linkf)
return True
else:
if self.client:
requestparams = self.client.initrequest()
else:
requestparams = {}
requests.delete( self.projectpath + self.basedir + '/' + self.filename, **requestparams)
return True | [
"def",
"delete",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"remote",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"projectpath",
"+",
"self",
".",
"basedir",
"+",
"'/'",
"+",
"self",
".",
"filename",
")",
":",
"return",
"False",
"else",
":",
"os",
".",
"unlink",
"(",
"self",
".",
"projectpath",
"+",
"self",
".",
"basedir",
"+",
"'/'",
"+",
"self",
".",
"filename",
")",
"#Remove metadata",
"metafile",
"=",
"self",
".",
"projectpath",
"+",
"self",
".",
"basedir",
"+",
"'/'",
"+",
"self",
".",
"metafilename",
"(",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"metafile",
")",
":",
"os",
".",
"unlink",
"(",
"metafile",
")",
"#also remove any .*.INPUTTEMPLATE.* links that pointed to this file: simply remove all dead links",
"for",
"linkf",
",",
"realf",
"in",
"clam",
".",
"common",
".",
"util",
".",
"globsymlinks",
"(",
"self",
".",
"projectpath",
"+",
"self",
".",
"basedir",
"+",
"'/.*.INPUTTEMPLATE.*'",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"realf",
")",
":",
"os",
".",
"unlink",
"(",
"linkf",
")",
"return",
"True",
"else",
":",
"if",
"self",
".",
"client",
":",
"requestparams",
"=",
"self",
".",
"client",
".",
"initrequest",
"(",
")",
"else",
":",
"requestparams",
"=",
"{",
"}",
"requests",
".",
"delete",
"(",
"self",
".",
"projectpath",
"+",
"self",
".",
"basedir",
"+",
"'/'",
"+",
"self",
".",
"filename",
",",
"*",
"*",
"requestparams",
")",
"return",
"True"
] | Delete this file | [
"Delete",
"this",
"file"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L300-L325 |
proycon/clam | clam/common/data.py | CLAMFile.read | def read(self):
"""Loads all lines in memory"""
lines = self.readlines()
if self.metadata and 'encoding' in self.metadata:
encoding = self.metadata['encoding']
else:
encoding = 'utf-8'
if sys.version < '3':
return "\n".join( unicode(line, 'utf-8') if isinstance(line, str) else line for line in lines)
else:
return "\n".join( str(line, 'utf-8') if isinstance(line, bytes) else line for line in lines) | python | def read(self):
"""Loads all lines in memory"""
lines = self.readlines()
if self.metadata and 'encoding' in self.metadata:
encoding = self.metadata['encoding']
else:
encoding = 'utf-8'
if sys.version < '3':
return "\n".join( unicode(line, 'utf-8') if isinstance(line, str) else line for line in lines)
else:
return "\n".join( str(line, 'utf-8') if isinstance(line, bytes) else line for line in lines) | [
"def",
"read",
"(",
"self",
")",
":",
"lines",
"=",
"self",
".",
"readlines",
"(",
")",
"if",
"self",
".",
"metadata",
"and",
"'encoding'",
"in",
"self",
".",
"metadata",
":",
"encoding",
"=",
"self",
".",
"metadata",
"[",
"'encoding'",
"]",
"else",
":",
"encoding",
"=",
"'utf-8'",
"if",
"sys",
".",
"version",
"<",
"'3'",
":",
"return",
"\"\\n\"",
".",
"join",
"(",
"unicode",
"(",
"line",
",",
"'utf-8'",
")",
"if",
"isinstance",
"(",
"line",
",",
"str",
")",
"else",
"line",
"for",
"line",
"in",
"lines",
")",
"else",
":",
"return",
"\"\\n\"",
".",
"join",
"(",
"str",
"(",
"line",
",",
"'utf-8'",
")",
"if",
"isinstance",
"(",
"line",
",",
"bytes",
")",
"else",
"line",
"for",
"line",
"in",
"lines",
")"
] | Loads all lines in memory | [
"Loads",
"all",
"lines",
"in",
"memory"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L332-L342 |
proycon/clam | clam/common/data.py | CLAMFile.copy | def copy(self, target, timeout=500):
"""Copy or download this file to a new local file"""
if self.metadata and 'encoding' in self.metadata:
with io.open(target,'w', encoding=self.metadata['encoding']) as f:
for line in self:
f.write(line)
else:
with io.open(target,'wb') as f:
for line in self:
if sys.version < '3' and isinstance(line,unicode): #pylint: disable=undefined-variable
f.write(line.encode('utf-8'))
elif sys.version >= '3' and isinstance(line,str):
f.write(line.encode('utf-8'))
else:
f.write(line) | python | def copy(self, target, timeout=500):
"""Copy or download this file to a new local file"""
if self.metadata and 'encoding' in self.metadata:
with io.open(target,'w', encoding=self.metadata['encoding']) as f:
for line in self:
f.write(line)
else:
with io.open(target,'wb') as f:
for line in self:
if sys.version < '3' and isinstance(line,unicode): #pylint: disable=undefined-variable
f.write(line.encode('utf-8'))
elif sys.version >= '3' and isinstance(line,str):
f.write(line.encode('utf-8'))
else:
f.write(line) | [
"def",
"copy",
"(",
"self",
",",
"target",
",",
"timeout",
"=",
"500",
")",
":",
"if",
"self",
".",
"metadata",
"and",
"'encoding'",
"in",
"self",
".",
"metadata",
":",
"with",
"io",
".",
"open",
"(",
"target",
",",
"'w'",
",",
"encoding",
"=",
"self",
".",
"metadata",
"[",
"'encoding'",
"]",
")",
"as",
"f",
":",
"for",
"line",
"in",
"self",
":",
"f",
".",
"write",
"(",
"line",
")",
"else",
":",
"with",
"io",
".",
"open",
"(",
"target",
",",
"'wb'",
")",
"as",
"f",
":",
"for",
"line",
"in",
"self",
":",
"if",
"sys",
".",
"version",
"<",
"'3'",
"and",
"isinstance",
"(",
"line",
",",
"unicode",
")",
":",
"#pylint: disable=undefined-variable",
"f",
".",
"write",
"(",
"line",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"elif",
"sys",
".",
"version",
">=",
"'3'",
"and",
"isinstance",
"(",
"line",
",",
"str",
")",
":",
"f",
".",
"write",
"(",
"line",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"else",
":",
"f",
".",
"write",
"(",
"line",
")"
] | Copy or download this file to a new local file | [
"Copy",
"or",
"download",
"this",
"file",
"to",
"a",
"new",
"local",
"file"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L345-L360 |
proycon/clam | clam/common/data.py | CLAMData.parseresponse | def parseresponse(self, xml, localroot = False):
"""Parses CLAM XML, there's usually no need to call this directly"""
root = parsexmlstring(xml)
if root.tag != 'clam':
raise FormatError("CLAM root tag not found")
self.system_id = root.attrib['id']
self.system_name = root.attrib['name']
if 'project' in root.attrib:
self.project = root.attrib['project']
else:
self.project = None
if 'baseurl' in root.attrib:
self.baseurl = root.attrib['baseurl']
if self.project:
if localroot is True: #implicit, assume CWD
self.remote = False
self.projecturl = '' #relative directory (assume CWD is project directory, as is the case when wrapper scripts are called)
elif localroot: #explicit
self.remote = False
self.projecturl = localroot + '/' + self.project + '/' #explicit directory
else:
self.remote = True #no directory: remote URL
self.projecturl = self.baseurl + '/' + self.project + '/'
if 'user' in root.attrib:
self.user = root.attrib['user']
else:
self.user = None
self.oauth_access_token = ""
if 'oauth_access_token' in root.attrib:
self.oauth_access_token = root.attrib['oauth_access_token']
for node in root: #pylint: disable=too-many-nested-blocks
if node.tag == "description":
self.description = node.text
elif node.tag == "version":
self.system_version = node.text
elif node.tag == "email":
self.system_email = node.text
elif node.tag == 'status':
self.status = int(node.attrib['code'])
self.statusmessage = node.attrib['message']
self.completion = node.attrib['completion']
if 'errors' in node.attrib:
self.errors = ((node.attrib['errors'] == 'yes') or (node.attrib['errors'] == '1'))
if 'errormsg' in node.attrib:
self.errormsg = node.attrib['errormsg']
elif node.tag == 'parameters':
for parametergroupnode in node:
if parametergroupnode.tag == 'parametergroup':
parameterlist = []
for parameternode in parametergroupnode:
if parameternode.tag in vars(clam.common.parameters):
parameterlist.append(vars(clam.common.parameters)[parameternode.tag].fromxml(parameternode))
else:
raise Exception("Expected parameter class '" + parameternode.tag + "', but not defined!")
self.parameters.append( (parametergroupnode.attrib['name'], parameterlist) )
elif node.tag == 'corpora':
for corpusnode in node:
if corpusnode.tag == 'corpus':
self.corpora.append(corpusnode.value)
elif node.tag == 'profiles':
for subnode in node:
if subnode.tag == 'profile':
self.profiles.append(Profile.fromxml(subnode))
elif node.tag == 'input':
for filenode in node:
if filenode.tag == 'file':
for n in filenode:
if n.tag == 'name':
self.input.append( CLAMInputFile( self.projecturl, n.text, self.loadmetadata, self.client,True) )
elif node.tag == 'output':
for filenode in node:
if filenode.tag == 'file':
for n in filenode:
if n.tag == 'name':
self.output.append( CLAMOutputFile( self.projecturl, n.text, self.loadmetadata, self.client ) )
elif node.tag == 'projects':
self.projects = []
for projectnode in node:
if projectnode.tag == 'project':
self.projects.append(projectnode.text)
elif node.tag == 'program':
self.program = Program(self.projecturl, [ int(i) for i in node.attrib['matchedprofiles'].split(',') ] )
for outputfilenode in node:
if outputfilenode.tag == 'outputfile':
inputfound = False
for inputfilenode in outputfilenode:
if inputfilenode.tag == 'inputfile':
inputfound = True
self.program.add(outputfilenode.attrib['name'],outputfilenode.attrib['template'],inputfilenode.attrib['name'], inputfilenode.attrib['template'])
if not inputfound:
self.program.add(outputfilenode.attrib['name'],outputfilenode.attrib['template']) | python | def parseresponse(self, xml, localroot = False):
"""Parses CLAM XML, there's usually no need to call this directly"""
root = parsexmlstring(xml)
if root.tag != 'clam':
raise FormatError("CLAM root tag not found")
self.system_id = root.attrib['id']
self.system_name = root.attrib['name']
if 'project' in root.attrib:
self.project = root.attrib['project']
else:
self.project = None
if 'baseurl' in root.attrib:
self.baseurl = root.attrib['baseurl']
if self.project:
if localroot is True: #implicit, assume CWD
self.remote = False
self.projecturl = '' #relative directory (assume CWD is project directory, as is the case when wrapper scripts are called)
elif localroot: #explicit
self.remote = False
self.projecturl = localroot + '/' + self.project + '/' #explicit directory
else:
self.remote = True #no directory: remote URL
self.projecturl = self.baseurl + '/' + self.project + '/'
if 'user' in root.attrib:
self.user = root.attrib['user']
else:
self.user = None
self.oauth_access_token = ""
if 'oauth_access_token' in root.attrib:
self.oauth_access_token = root.attrib['oauth_access_token']
for node in root: #pylint: disable=too-many-nested-blocks
if node.tag == "description":
self.description = node.text
elif node.tag == "version":
self.system_version = node.text
elif node.tag == "email":
self.system_email = node.text
elif node.tag == 'status':
self.status = int(node.attrib['code'])
self.statusmessage = node.attrib['message']
self.completion = node.attrib['completion']
if 'errors' in node.attrib:
self.errors = ((node.attrib['errors'] == 'yes') or (node.attrib['errors'] == '1'))
if 'errormsg' in node.attrib:
self.errormsg = node.attrib['errormsg']
elif node.tag == 'parameters':
for parametergroupnode in node:
if parametergroupnode.tag == 'parametergroup':
parameterlist = []
for parameternode in parametergroupnode:
if parameternode.tag in vars(clam.common.parameters):
parameterlist.append(vars(clam.common.parameters)[parameternode.tag].fromxml(parameternode))
else:
raise Exception("Expected parameter class '" + parameternode.tag + "', but not defined!")
self.parameters.append( (parametergroupnode.attrib['name'], parameterlist) )
elif node.tag == 'corpora':
for corpusnode in node:
if corpusnode.tag == 'corpus':
self.corpora.append(corpusnode.value)
elif node.tag == 'profiles':
for subnode in node:
if subnode.tag == 'profile':
self.profiles.append(Profile.fromxml(subnode))
elif node.tag == 'input':
for filenode in node:
if filenode.tag == 'file':
for n in filenode:
if n.tag == 'name':
self.input.append( CLAMInputFile( self.projecturl, n.text, self.loadmetadata, self.client,True) )
elif node.tag == 'output':
for filenode in node:
if filenode.tag == 'file':
for n in filenode:
if n.tag == 'name':
self.output.append( CLAMOutputFile( self.projecturl, n.text, self.loadmetadata, self.client ) )
elif node.tag == 'projects':
self.projects = []
for projectnode in node:
if projectnode.tag == 'project':
self.projects.append(projectnode.text)
elif node.tag == 'program':
self.program = Program(self.projecturl, [ int(i) for i in node.attrib['matchedprofiles'].split(',') ] )
for outputfilenode in node:
if outputfilenode.tag == 'outputfile':
inputfound = False
for inputfilenode in outputfilenode:
if inputfilenode.tag == 'inputfile':
inputfound = True
self.program.add(outputfilenode.attrib['name'],outputfilenode.attrib['template'],inputfilenode.attrib['name'], inputfilenode.attrib['template'])
if not inputfound:
self.program.add(outputfilenode.attrib['name'],outputfilenode.attrib['template']) | [
"def",
"parseresponse",
"(",
"self",
",",
"xml",
",",
"localroot",
"=",
"False",
")",
":",
"root",
"=",
"parsexmlstring",
"(",
"xml",
")",
"if",
"root",
".",
"tag",
"!=",
"'clam'",
":",
"raise",
"FormatError",
"(",
"\"CLAM root tag not found\"",
")",
"self",
".",
"system_id",
"=",
"root",
".",
"attrib",
"[",
"'id'",
"]",
"self",
".",
"system_name",
"=",
"root",
".",
"attrib",
"[",
"'name'",
"]",
"if",
"'project'",
"in",
"root",
".",
"attrib",
":",
"self",
".",
"project",
"=",
"root",
".",
"attrib",
"[",
"'project'",
"]",
"else",
":",
"self",
".",
"project",
"=",
"None",
"if",
"'baseurl'",
"in",
"root",
".",
"attrib",
":",
"self",
".",
"baseurl",
"=",
"root",
".",
"attrib",
"[",
"'baseurl'",
"]",
"if",
"self",
".",
"project",
":",
"if",
"localroot",
"is",
"True",
":",
"#implicit, assume CWD",
"self",
".",
"remote",
"=",
"False",
"self",
".",
"projecturl",
"=",
"''",
"#relative directory (assume CWD is project directory, as is the case when wrapper scripts are called)",
"elif",
"localroot",
":",
"#explicit",
"self",
".",
"remote",
"=",
"False",
"self",
".",
"projecturl",
"=",
"localroot",
"+",
"'/'",
"+",
"self",
".",
"project",
"+",
"'/'",
"#explicit directory",
"else",
":",
"self",
".",
"remote",
"=",
"True",
"#no directory: remote URL",
"self",
".",
"projecturl",
"=",
"self",
".",
"baseurl",
"+",
"'/'",
"+",
"self",
".",
"project",
"+",
"'/'",
"if",
"'user'",
"in",
"root",
".",
"attrib",
":",
"self",
".",
"user",
"=",
"root",
".",
"attrib",
"[",
"'user'",
"]",
"else",
":",
"self",
".",
"user",
"=",
"None",
"self",
".",
"oauth_access_token",
"=",
"\"\"",
"if",
"'oauth_access_token'",
"in",
"root",
".",
"attrib",
":",
"self",
".",
"oauth_access_token",
"=",
"root",
".",
"attrib",
"[",
"'oauth_access_token'",
"]",
"for",
"node",
"in",
"root",
":",
"#pylint: disable=too-many-nested-blocks",
"if",
"node",
".",
"tag",
"==",
"\"description\"",
":",
"self",
".",
"description",
"=",
"node",
".",
"text",
"elif",
"node",
".",
"tag",
"==",
"\"version\"",
":",
"self",
".",
"system_version",
"=",
"node",
".",
"text",
"elif",
"node",
".",
"tag",
"==",
"\"email\"",
":",
"self",
".",
"system_email",
"=",
"node",
".",
"text",
"elif",
"node",
".",
"tag",
"==",
"'status'",
":",
"self",
".",
"status",
"=",
"int",
"(",
"node",
".",
"attrib",
"[",
"'code'",
"]",
")",
"self",
".",
"statusmessage",
"=",
"node",
".",
"attrib",
"[",
"'message'",
"]",
"self",
".",
"completion",
"=",
"node",
".",
"attrib",
"[",
"'completion'",
"]",
"if",
"'errors'",
"in",
"node",
".",
"attrib",
":",
"self",
".",
"errors",
"=",
"(",
"(",
"node",
".",
"attrib",
"[",
"'errors'",
"]",
"==",
"'yes'",
")",
"or",
"(",
"node",
".",
"attrib",
"[",
"'errors'",
"]",
"==",
"'1'",
")",
")",
"if",
"'errormsg'",
"in",
"node",
".",
"attrib",
":",
"self",
".",
"errormsg",
"=",
"node",
".",
"attrib",
"[",
"'errormsg'",
"]",
"elif",
"node",
".",
"tag",
"==",
"'parameters'",
":",
"for",
"parametergroupnode",
"in",
"node",
":",
"if",
"parametergroupnode",
".",
"tag",
"==",
"'parametergroup'",
":",
"parameterlist",
"=",
"[",
"]",
"for",
"parameternode",
"in",
"parametergroupnode",
":",
"if",
"parameternode",
".",
"tag",
"in",
"vars",
"(",
"clam",
".",
"common",
".",
"parameters",
")",
":",
"parameterlist",
".",
"append",
"(",
"vars",
"(",
"clam",
".",
"common",
".",
"parameters",
")",
"[",
"parameternode",
".",
"tag",
"]",
".",
"fromxml",
"(",
"parameternode",
")",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"Expected parameter class '\"",
"+",
"parameternode",
".",
"tag",
"+",
"\"', but not defined!\"",
")",
"self",
".",
"parameters",
".",
"append",
"(",
"(",
"parametergroupnode",
".",
"attrib",
"[",
"'name'",
"]",
",",
"parameterlist",
")",
")",
"elif",
"node",
".",
"tag",
"==",
"'corpora'",
":",
"for",
"corpusnode",
"in",
"node",
":",
"if",
"corpusnode",
".",
"tag",
"==",
"'corpus'",
":",
"self",
".",
"corpora",
".",
"append",
"(",
"corpusnode",
".",
"value",
")",
"elif",
"node",
".",
"tag",
"==",
"'profiles'",
":",
"for",
"subnode",
"in",
"node",
":",
"if",
"subnode",
".",
"tag",
"==",
"'profile'",
":",
"self",
".",
"profiles",
".",
"append",
"(",
"Profile",
".",
"fromxml",
"(",
"subnode",
")",
")",
"elif",
"node",
".",
"tag",
"==",
"'input'",
":",
"for",
"filenode",
"in",
"node",
":",
"if",
"filenode",
".",
"tag",
"==",
"'file'",
":",
"for",
"n",
"in",
"filenode",
":",
"if",
"n",
".",
"tag",
"==",
"'name'",
":",
"self",
".",
"input",
".",
"append",
"(",
"CLAMInputFile",
"(",
"self",
".",
"projecturl",
",",
"n",
".",
"text",
",",
"self",
".",
"loadmetadata",
",",
"self",
".",
"client",
",",
"True",
")",
")",
"elif",
"node",
".",
"tag",
"==",
"'output'",
":",
"for",
"filenode",
"in",
"node",
":",
"if",
"filenode",
".",
"tag",
"==",
"'file'",
":",
"for",
"n",
"in",
"filenode",
":",
"if",
"n",
".",
"tag",
"==",
"'name'",
":",
"self",
".",
"output",
".",
"append",
"(",
"CLAMOutputFile",
"(",
"self",
".",
"projecturl",
",",
"n",
".",
"text",
",",
"self",
".",
"loadmetadata",
",",
"self",
".",
"client",
")",
")",
"elif",
"node",
".",
"tag",
"==",
"'projects'",
":",
"self",
".",
"projects",
"=",
"[",
"]",
"for",
"projectnode",
"in",
"node",
":",
"if",
"projectnode",
".",
"tag",
"==",
"'project'",
":",
"self",
".",
"projects",
".",
"append",
"(",
"projectnode",
".",
"text",
")",
"elif",
"node",
".",
"tag",
"==",
"'program'",
":",
"self",
".",
"program",
"=",
"Program",
"(",
"self",
".",
"projecturl",
",",
"[",
"int",
"(",
"i",
")",
"for",
"i",
"in",
"node",
".",
"attrib",
"[",
"'matchedprofiles'",
"]",
".",
"split",
"(",
"','",
")",
"]",
")",
"for",
"outputfilenode",
"in",
"node",
":",
"if",
"outputfilenode",
".",
"tag",
"==",
"'outputfile'",
":",
"inputfound",
"=",
"False",
"for",
"inputfilenode",
"in",
"outputfilenode",
":",
"if",
"inputfilenode",
".",
"tag",
"==",
"'inputfile'",
":",
"inputfound",
"=",
"True",
"self",
".",
"program",
".",
"add",
"(",
"outputfilenode",
".",
"attrib",
"[",
"'name'",
"]",
",",
"outputfilenode",
".",
"attrib",
"[",
"'template'",
"]",
",",
"inputfilenode",
".",
"attrib",
"[",
"'name'",
"]",
",",
"inputfilenode",
".",
"attrib",
"[",
"'template'",
"]",
")",
"if",
"not",
"inputfound",
":",
"self",
".",
"program",
".",
"add",
"(",
"outputfilenode",
".",
"attrib",
"[",
"'name'",
"]",
",",
"outputfilenode",
".",
"attrib",
"[",
"'template'",
"]",
")"
] | Parses CLAM XML, there's usually no need to call this directly | [
"Parses",
"CLAM",
"XML",
"there",
"s",
"usually",
"no",
"need",
"to",
"call",
"this",
"directly"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L560-L654 |
proycon/clam | clam/common/data.py | CLAMData.outputtemplate | def outputtemplate(self, template_id):
"""Get an output template by ID"""
for profile in self.profiles:
for outputtemplate in profile.outputtemplates():
if outputtemplate.id == template_id:
return outputtemplate
return KeyError("Outputtemplate " + template_id + " not found") | python | def outputtemplate(self, template_id):
"""Get an output template by ID"""
for profile in self.profiles:
for outputtemplate in profile.outputtemplates():
if outputtemplate.id == template_id:
return outputtemplate
return KeyError("Outputtemplate " + template_id + " not found") | [
"def",
"outputtemplate",
"(",
"self",
",",
"template_id",
")",
":",
"for",
"profile",
"in",
"self",
".",
"profiles",
":",
"for",
"outputtemplate",
"in",
"profile",
".",
"outputtemplates",
"(",
")",
":",
"if",
"outputtemplate",
".",
"id",
"==",
"template_id",
":",
"return",
"outputtemplate",
"return",
"KeyError",
"(",
"\"Outputtemplate \"",
"+",
"template_id",
"+",
"\" not found\"",
")"
] | Get an output template by ID | [
"Get",
"an",
"output",
"template",
"by",
"ID"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L656-L662 |
proycon/clam | clam/common/data.py | CLAMData.commandlineargs | def commandlineargs(self):
"""Obtain a string of all parameters, using the paramater flags they were defined with, in order to pass to an external command. This is shell-safe by definition."""
commandlineargs = []
for parametergroup, parameters in self.parameters: #pylint: disable=unused-variable
for parameter in parameters:
p = parameter.compilearg()
if p:
commandlineargs.append(p)
return " ".join(commandlineargs) | python | def commandlineargs(self):
"""Obtain a string of all parameters, using the paramater flags they were defined with, in order to pass to an external command. This is shell-safe by definition."""
commandlineargs = []
for parametergroup, parameters in self.parameters: #pylint: disable=unused-variable
for parameter in parameters:
p = parameter.compilearg()
if p:
commandlineargs.append(p)
return " ".join(commandlineargs) | [
"def",
"commandlineargs",
"(",
"self",
")",
":",
"commandlineargs",
"=",
"[",
"]",
"for",
"parametergroup",
",",
"parameters",
"in",
"self",
".",
"parameters",
":",
"#pylint: disable=unused-variable",
"for",
"parameter",
"in",
"parameters",
":",
"p",
"=",
"parameter",
".",
"compilearg",
"(",
")",
"if",
"p",
":",
"commandlineargs",
".",
"append",
"(",
"p",
")",
"return",
"\" \"",
".",
"join",
"(",
"commandlineargs",
")"
] | Obtain a string of all parameters, using the paramater flags they were defined with, in order to pass to an external command. This is shell-safe by definition. | [
"Obtain",
"a",
"string",
"of",
"all",
"parameters",
"using",
"the",
"paramater",
"flags",
"they",
"were",
"defined",
"with",
"in",
"order",
"to",
"pass",
"to",
"an",
"external",
"command",
".",
"This",
"is",
"shell",
"-",
"safe",
"by",
"definition",
"."
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L665-L673 |
proycon/clam | clam/common/data.py | CLAMData.parameter | def parameter(self, parameter_id):
"""Return the specified global parameter (the entire object, not just the value)"""
for parametergroup, parameters in self.parameters: #pylint: disable=unused-variable
for parameter in parameters:
if parameter.id == parameter_id:
return parameter
raise KeyError("No such parameter exists: " + parameter_id ) | python | def parameter(self, parameter_id):
"""Return the specified global parameter (the entire object, not just the value)"""
for parametergroup, parameters in self.parameters: #pylint: disable=unused-variable
for parameter in parameters:
if parameter.id == parameter_id:
return parameter
raise KeyError("No such parameter exists: " + parameter_id ) | [
"def",
"parameter",
"(",
"self",
",",
"parameter_id",
")",
":",
"for",
"parametergroup",
",",
"parameters",
"in",
"self",
".",
"parameters",
":",
"#pylint: disable=unused-variable",
"for",
"parameter",
"in",
"parameters",
":",
"if",
"parameter",
".",
"id",
"==",
"parameter_id",
":",
"return",
"parameter",
"raise",
"KeyError",
"(",
"\"No such parameter exists: \"",
"+",
"parameter_id",
")"
] | Return the specified global parameter (the entire object, not just the value) | [
"Return",
"the",
"specified",
"global",
"parameter",
"(",
"the",
"entire",
"object",
"not",
"just",
"the",
"value",
")"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L676-L682 |
proycon/clam | clam/common/data.py | CLAMData.parametererror | def parametererror(self):
"""Return the first parameter error, or False if there is none"""
for parametergroup, parameters in self.parameters: #pylint: disable=unused-variable
for parameter in parameters:
if parameter.error:
return parameter.error
return False | python | def parametererror(self):
"""Return the first parameter error, or False if there is none"""
for parametergroup, parameters in self.parameters: #pylint: disable=unused-variable
for parameter in parameters:
if parameter.error:
return parameter.error
return False | [
"def",
"parametererror",
"(",
"self",
")",
":",
"for",
"parametergroup",
",",
"parameters",
"in",
"self",
".",
"parameters",
":",
"#pylint: disable=unused-variable",
"for",
"parameter",
"in",
"parameters",
":",
"if",
"parameter",
".",
"error",
":",
"return",
"parameter",
".",
"error",
"return",
"False"
] | Return the first parameter error, or False if there is none | [
"Return",
"the",
"first",
"parameter",
"error",
"or",
"False",
"if",
"there",
"is",
"none"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L714-L720 |
proycon/clam | clam/common/data.py | CLAMData.passparameters | def passparameters(self):
"""Return all parameters as {id: value} dictionary"""
paramdict = {}
for parametergroup, params in self.parameters: #pylint: disable=unused-variable
for parameter in params:
if parameter.value:
if isinstance(parameter.value, list):
paramdict[parameter.id] = ",".join(parameter.value)
else:
paramdict[parameter.id] = parameter.value
return paramdict | python | def passparameters(self):
"""Return all parameters as {id: value} dictionary"""
paramdict = {}
for parametergroup, params in self.parameters: #pylint: disable=unused-variable
for parameter in params:
if parameter.value:
if isinstance(parameter.value, list):
paramdict[parameter.id] = ",".join(parameter.value)
else:
paramdict[parameter.id] = parameter.value
return paramdict | [
"def",
"passparameters",
"(",
"self",
")",
":",
"paramdict",
"=",
"{",
"}",
"for",
"parametergroup",
",",
"params",
"in",
"self",
".",
"parameters",
":",
"#pylint: disable=unused-variable",
"for",
"parameter",
"in",
"params",
":",
"if",
"parameter",
".",
"value",
":",
"if",
"isinstance",
"(",
"parameter",
".",
"value",
",",
"list",
")",
":",
"paramdict",
"[",
"parameter",
".",
"id",
"]",
"=",
"\",\"",
".",
"join",
"(",
"parameter",
".",
"value",
")",
"else",
":",
"paramdict",
"[",
"parameter",
".",
"id",
"]",
"=",
"parameter",
".",
"value",
"return",
"paramdict"
] | Return all parameters as {id: value} dictionary | [
"Return",
"all",
"parameters",
"as",
"{",
"id",
":",
"value",
"}",
"dictionary"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L722-L732 |
proycon/clam | clam/common/data.py | CLAMData.inputtemplates | def inputtemplates(self):
"""Return all input templates as a list (of InputTemplate instances)"""
l = []
for profile in self.profiles:
l += profile.input
return l | python | def inputtemplates(self):
"""Return all input templates as a list (of InputTemplate instances)"""
l = []
for profile in self.profiles:
l += profile.input
return l | [
"def",
"inputtemplates",
"(",
"self",
")",
":",
"l",
"=",
"[",
"]",
"for",
"profile",
"in",
"self",
".",
"profiles",
":",
"l",
"+=",
"profile",
".",
"input",
"return",
"l"
] | Return all input templates as a list (of InputTemplate instances) | [
"Return",
"all",
"input",
"templates",
"as",
"a",
"list",
"(",
"of",
"InputTemplate",
"instances",
")"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L735-L740 |
proycon/clam | clam/common/data.py | CLAMData.inputtemplate | def inputtemplate(self,template_id):
"""Return the inputtemplate with the specified ID. This is used to resolve a inputtemplate ID to an InputTemplate object instance"""
for profile in self.profiles:
for inputtemplate in profile.input:
if inputtemplate.id == template_id:
return inputtemplate
raise Exception("No such input template: " + repr(template_id)) | python | def inputtemplate(self,template_id):
"""Return the inputtemplate with the specified ID. This is used to resolve a inputtemplate ID to an InputTemplate object instance"""
for profile in self.profiles:
for inputtemplate in profile.input:
if inputtemplate.id == template_id:
return inputtemplate
raise Exception("No such input template: " + repr(template_id)) | [
"def",
"inputtemplate",
"(",
"self",
",",
"template_id",
")",
":",
"for",
"profile",
"in",
"self",
".",
"profiles",
":",
"for",
"inputtemplate",
"in",
"profile",
".",
"input",
":",
"if",
"inputtemplate",
".",
"id",
"==",
"template_id",
":",
"return",
"inputtemplate",
"raise",
"Exception",
"(",
"\"No such input template: \"",
"+",
"repr",
"(",
"template_id",
")",
")"
] | Return the inputtemplate with the specified ID. This is used to resolve a inputtemplate ID to an InputTemplate object instance | [
"Return",
"the",
"inputtemplate",
"with",
"the",
"specified",
"ID",
".",
"This",
"is",
"used",
"to",
"resolve",
"a",
"inputtemplate",
"ID",
"to",
"an",
"InputTemplate",
"object",
"instance"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L742-L748 |
proycon/clam | clam/common/data.py | CLAMData.inputfile | def inputfile(self, inputtemplate=None):
"""Return the inputfile for the specified inputtemplate, if ``inputtemplate=None``, inputfile is returned regardless of inputtemplate. This function may only return 1 and returns an error when multiple input files can be returned, use ``inputfiles()`` instead."""
inputfiles = list(self.inputfiles(inputtemplate))
if len(inputfiles) < 1:
raise Exception("No such input file")
elif len(inputfiles) > 1:
raise Exception("Multiple input files matched. Use inputfiles() instead!")
return inputfiles[0] | python | def inputfile(self, inputtemplate=None):
"""Return the inputfile for the specified inputtemplate, if ``inputtemplate=None``, inputfile is returned regardless of inputtemplate. This function may only return 1 and returns an error when multiple input files can be returned, use ``inputfiles()`` instead."""
inputfiles = list(self.inputfiles(inputtemplate))
if len(inputfiles) < 1:
raise Exception("No such input file")
elif len(inputfiles) > 1:
raise Exception("Multiple input files matched. Use inputfiles() instead!")
return inputfiles[0] | [
"def",
"inputfile",
"(",
"self",
",",
"inputtemplate",
"=",
"None",
")",
":",
"inputfiles",
"=",
"list",
"(",
"self",
".",
"inputfiles",
"(",
"inputtemplate",
")",
")",
"if",
"len",
"(",
"inputfiles",
")",
"<",
"1",
":",
"raise",
"Exception",
"(",
"\"No such input file\"",
")",
"elif",
"len",
"(",
"inputfiles",
")",
">",
"1",
":",
"raise",
"Exception",
"(",
"\"Multiple input files matched. Use inputfiles() instead!\"",
")",
"return",
"inputfiles",
"[",
"0",
"]"
] | Return the inputfile for the specified inputtemplate, if ``inputtemplate=None``, inputfile is returned regardless of inputtemplate. This function may only return 1 and returns an error when multiple input files can be returned, use ``inputfiles()`` instead. | [
"Return",
"the",
"inputfile",
"for",
"the",
"specified",
"inputtemplate",
"if",
"inputtemplate",
"=",
"None",
"inputfile",
"is",
"returned",
"regardless",
"of",
"inputtemplate",
".",
"This",
"function",
"may",
"only",
"return",
"1",
"and",
"returns",
"an",
"error",
"when",
"multiple",
"input",
"files",
"can",
"be",
"returned",
"use",
"inputfiles",
"()",
"instead",
"."
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L750-L757 |
proycon/clam | clam/common/data.py | CLAMData.inputfiles | def inputfiles(self, inputtemplate=None):
"""Generator yielding all inputfiles for the specified inputtemplate, if ``inputtemplate=None``, inputfiles are returned regardless of inputtemplate."""
if isinstance(inputtemplate, InputTemplate):
#ID suffices:
inputtemplate = inputtemplate.id
for inputfile in self.input:
if not inputtemplate or inputfile.metadata.inputtemplate == inputtemplate:
yield inputfile | python | def inputfiles(self, inputtemplate=None):
"""Generator yielding all inputfiles for the specified inputtemplate, if ``inputtemplate=None``, inputfiles are returned regardless of inputtemplate."""
if isinstance(inputtemplate, InputTemplate):
#ID suffices:
inputtemplate = inputtemplate.id
for inputfile in self.input:
if not inputtemplate or inputfile.metadata.inputtemplate == inputtemplate:
yield inputfile | [
"def",
"inputfiles",
"(",
"self",
",",
"inputtemplate",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"inputtemplate",
",",
"InputTemplate",
")",
":",
"#ID suffices:",
"inputtemplate",
"=",
"inputtemplate",
".",
"id",
"for",
"inputfile",
"in",
"self",
".",
"input",
":",
"if",
"not",
"inputtemplate",
"or",
"inputfile",
".",
"metadata",
".",
"inputtemplate",
"==",
"inputtemplate",
":",
"yield",
"inputfile"
] | Generator yielding all inputfiles for the specified inputtemplate, if ``inputtemplate=None``, inputfiles are returned regardless of inputtemplate. | [
"Generator",
"yielding",
"all",
"inputfiles",
"for",
"the",
"specified",
"inputtemplate",
"if",
"inputtemplate",
"=",
"None",
"inputfiles",
"are",
"returned",
"regardless",
"of",
"inputtemplate",
"."
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L764-L771 |
proycon/clam | clam/common/data.py | Profile.match | def match(self, projectpath, parameters):
"""Check if the profile matches all inputdata *and* produces output given the set parameters. Returns a boolean"""
parameters = sanitizeparameters(parameters)
mandatory_absent = [] #list of input templates that are missing but mandatory
optional_absent = [] #list of absent but optional input templates
#check if profile matches inputdata (if there are no inputtemplate, this always matches intentionally!)
for inputtemplate in self.input:
if not inputtemplate.matchingfiles(projectpath):
if inputtemplate.optional:
optional_absent.append(inputtemplate)
else:
mandatory_absent.append(inputtemplate)
if mandatory_absent:
return False, mandatory_absent
#check if output is produced
if not self.output: return False, mandatory_absent
for outputtemplate in self.output:
if isinstance(outputtemplate, ParameterCondition):
outputtemplate = outputtemplate.evaluate(parameters)
if not outputtemplate:
continue
assert isinstance(outputtemplate, OutputTemplate)
if outputtemplate.parent:
if outputtemplate.getparent(self) not in optional_absent: #pylint: disable=protected-access
return True, optional_absent
else:
return True, optional_absent
return False, optional_absent | python | def match(self, projectpath, parameters):
"""Check if the profile matches all inputdata *and* produces output given the set parameters. Returns a boolean"""
parameters = sanitizeparameters(parameters)
mandatory_absent = [] #list of input templates that are missing but mandatory
optional_absent = [] #list of absent but optional input templates
#check if profile matches inputdata (if there are no inputtemplate, this always matches intentionally!)
for inputtemplate in self.input:
if not inputtemplate.matchingfiles(projectpath):
if inputtemplate.optional:
optional_absent.append(inputtemplate)
else:
mandatory_absent.append(inputtemplate)
if mandatory_absent:
return False, mandatory_absent
#check if output is produced
if not self.output: return False, mandatory_absent
for outputtemplate in self.output:
if isinstance(outputtemplate, ParameterCondition):
outputtemplate = outputtemplate.evaluate(parameters)
if not outputtemplate:
continue
assert isinstance(outputtemplate, OutputTemplate)
if outputtemplate.parent:
if outputtemplate.getparent(self) not in optional_absent: #pylint: disable=protected-access
return True, optional_absent
else:
return True, optional_absent
return False, optional_absent | [
"def",
"match",
"(",
"self",
",",
"projectpath",
",",
"parameters",
")",
":",
"parameters",
"=",
"sanitizeparameters",
"(",
"parameters",
")",
"mandatory_absent",
"=",
"[",
"]",
"#list of input templates that are missing but mandatory",
"optional_absent",
"=",
"[",
"]",
"#list of absent but optional input templates",
"#check if profile matches inputdata (if there are no inputtemplate, this always matches intentionally!)",
"for",
"inputtemplate",
"in",
"self",
".",
"input",
":",
"if",
"not",
"inputtemplate",
".",
"matchingfiles",
"(",
"projectpath",
")",
":",
"if",
"inputtemplate",
".",
"optional",
":",
"optional_absent",
".",
"append",
"(",
"inputtemplate",
")",
"else",
":",
"mandatory_absent",
".",
"append",
"(",
"inputtemplate",
")",
"if",
"mandatory_absent",
":",
"return",
"False",
",",
"mandatory_absent",
"#check if output is produced",
"if",
"not",
"self",
".",
"output",
":",
"return",
"False",
",",
"mandatory_absent",
"for",
"outputtemplate",
"in",
"self",
".",
"output",
":",
"if",
"isinstance",
"(",
"outputtemplate",
",",
"ParameterCondition",
")",
":",
"outputtemplate",
"=",
"outputtemplate",
".",
"evaluate",
"(",
"parameters",
")",
"if",
"not",
"outputtemplate",
":",
"continue",
"assert",
"isinstance",
"(",
"outputtemplate",
",",
"OutputTemplate",
")",
"if",
"outputtemplate",
".",
"parent",
":",
"if",
"outputtemplate",
".",
"getparent",
"(",
"self",
")",
"not",
"in",
"optional_absent",
":",
"#pylint: disable=protected-access",
"return",
"True",
",",
"optional_absent",
"else",
":",
"return",
"True",
",",
"optional_absent",
"return",
"False",
",",
"optional_absent"
] | Check if the profile matches all inputdata *and* produces output given the set parameters. Returns a boolean | [
"Check",
"if",
"the",
"profile",
"matches",
"all",
"inputdata",
"*",
"and",
"*",
"produces",
"output",
"given",
"the",
"set",
"parameters",
".",
"Returns",
"a",
"boolean"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L857-L889 |
proycon/clam | clam/common/data.py | Profile.matchingfiles | def matchingfiles(self, projectpath):
"""Return a list of all inputfiles matching the profile (filenames)"""
l = []
for inputtemplate in self.input:
l += inputtemplate.matchingfiles(projectpath)
return l | python | def matchingfiles(self, projectpath):
"""Return a list of all inputfiles matching the profile (filenames)"""
l = []
for inputtemplate in self.input:
l += inputtemplate.matchingfiles(projectpath)
return l | [
"def",
"matchingfiles",
"(",
"self",
",",
"projectpath",
")",
":",
"l",
"=",
"[",
"]",
"for",
"inputtemplate",
"in",
"self",
".",
"input",
":",
"l",
"+=",
"inputtemplate",
".",
"matchingfiles",
"(",
"projectpath",
")",
"return",
"l"
] | Return a list of all inputfiles matching the profile (filenames) | [
"Return",
"a",
"list",
"of",
"all",
"inputfiles",
"matching",
"the",
"profile",
"(",
"filenames",
")"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L891-L896 |
proycon/clam | clam/common/data.py | Profile.outputtemplates | def outputtemplates(self):
"""Returns all outputtemplates, resolving ParameterConditions to all possibilities"""
outputtemplates = []
for o in self.output:
if isinstance(o, ParameterCondition):
outputtemplates += o.allpossibilities()
else:
assert isinstance(o, OutputTemplate)
outputtemplates.append(o)
return outputtemplates | python | def outputtemplates(self):
"""Returns all outputtemplates, resolving ParameterConditions to all possibilities"""
outputtemplates = []
for o in self.output:
if isinstance(o, ParameterCondition):
outputtemplates += o.allpossibilities()
else:
assert isinstance(o, OutputTemplate)
outputtemplates.append(o)
return outputtemplates | [
"def",
"outputtemplates",
"(",
"self",
")",
":",
"outputtemplates",
"=",
"[",
"]",
"for",
"o",
"in",
"self",
".",
"output",
":",
"if",
"isinstance",
"(",
"o",
",",
"ParameterCondition",
")",
":",
"outputtemplates",
"+=",
"o",
".",
"allpossibilities",
"(",
")",
"else",
":",
"assert",
"isinstance",
"(",
"o",
",",
"OutputTemplate",
")",
"outputtemplates",
".",
"append",
"(",
"o",
")",
"return",
"outputtemplates"
] | Returns all outputtemplates, resolving ParameterConditions to all possibilities | [
"Returns",
"all",
"outputtemplates",
"resolving",
"ParameterConditions",
"to",
"all",
"possibilities"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L898-L907 |
proycon/clam | clam/common/data.py | Profile.generate | def generate(self, projectpath, parameters, serviceid, servicename,serviceurl):
"""Generate output metadata on the basis of input files and parameters. Projectpath must be absolute. Returns a Program instance. """
#Make dictionary of parameters
parameters = sanitizeparameters(parameters)
program = Program(projectpath, [self])
match, optional_absent = self.match(projectpath, parameters) #Does the profile match?
if match: #pylint: disable=too-many-nested-blocks
#gather all input files that match
inputfiles = self.matchingfiles(projectpath) #list of (seqnr, filename,inputtemplate) tuples
inputfiles_full = [] #We need the full CLAMInputFiles for generating provenance data
for seqnr, filename, inputtemplate in inputfiles: #pylint: disable=unused-variable
inputfiles_full.append(CLAMInputFile(projectpath, filename))
for outputtemplate in self.output:
if isinstance(outputtemplate, ParameterCondition):
outputtemplate = outputtemplate.evaluate(parameters)
#generate output files
if outputtemplate:
if isinstance(outputtemplate, OutputTemplate):
#generate provenance data
provenancedata = CLAMProvenanceData(serviceid,servicename,serviceurl,outputtemplate.id, outputtemplate.label, inputfiles_full, parameters)
create = True
if outputtemplate.parent:
if outputtemplate.getparent(self) in optional_absent:
create = False
if create:
for inputtemplate, inputfilename, outputfilename, metadata in outputtemplate.generate(self, parameters, projectpath, inputfiles, provenancedata):
clam.common.util.printdebug("Writing metadata for outputfile " + outputfilename)
metafilename = os.path.dirname(outputfilename)
if metafilename: metafilename += '/'
metafilename += '.' + os.path.basename(outputfilename) + '.METADATA'
f = io.open(projectpath + '/output/' + metafilename,'w',encoding='utf-8')
f.write(metadata.xml())
f.close()
program.add(outputfilename, outputtemplate, inputfilename, inputtemplate)
else:
raise TypeError("OutputTemplate expected, but got " + outputtemplate.__class__.__name__)
return program | python | def generate(self, projectpath, parameters, serviceid, servicename,serviceurl):
"""Generate output metadata on the basis of input files and parameters. Projectpath must be absolute. Returns a Program instance. """
#Make dictionary of parameters
parameters = sanitizeparameters(parameters)
program = Program(projectpath, [self])
match, optional_absent = self.match(projectpath, parameters) #Does the profile match?
if match: #pylint: disable=too-many-nested-blocks
#gather all input files that match
inputfiles = self.matchingfiles(projectpath) #list of (seqnr, filename,inputtemplate) tuples
inputfiles_full = [] #We need the full CLAMInputFiles for generating provenance data
for seqnr, filename, inputtemplate in inputfiles: #pylint: disable=unused-variable
inputfiles_full.append(CLAMInputFile(projectpath, filename))
for outputtemplate in self.output:
if isinstance(outputtemplate, ParameterCondition):
outputtemplate = outputtemplate.evaluate(parameters)
#generate output files
if outputtemplate:
if isinstance(outputtemplate, OutputTemplate):
#generate provenance data
provenancedata = CLAMProvenanceData(serviceid,servicename,serviceurl,outputtemplate.id, outputtemplate.label, inputfiles_full, parameters)
create = True
if outputtemplate.parent:
if outputtemplate.getparent(self) in optional_absent:
create = False
if create:
for inputtemplate, inputfilename, outputfilename, metadata in outputtemplate.generate(self, parameters, projectpath, inputfiles, provenancedata):
clam.common.util.printdebug("Writing metadata for outputfile " + outputfilename)
metafilename = os.path.dirname(outputfilename)
if metafilename: metafilename += '/'
metafilename += '.' + os.path.basename(outputfilename) + '.METADATA'
f = io.open(projectpath + '/output/' + metafilename,'w',encoding='utf-8')
f.write(metadata.xml())
f.close()
program.add(outputfilename, outputtemplate, inputfilename, inputtemplate)
else:
raise TypeError("OutputTemplate expected, but got " + outputtemplate.__class__.__name__)
return program | [
"def",
"generate",
"(",
"self",
",",
"projectpath",
",",
"parameters",
",",
"serviceid",
",",
"servicename",
",",
"serviceurl",
")",
":",
"#Make dictionary of parameters",
"parameters",
"=",
"sanitizeparameters",
"(",
"parameters",
")",
"program",
"=",
"Program",
"(",
"projectpath",
",",
"[",
"self",
"]",
")",
"match",
",",
"optional_absent",
"=",
"self",
".",
"match",
"(",
"projectpath",
",",
"parameters",
")",
"#Does the profile match?",
"if",
"match",
":",
"#pylint: disable=too-many-nested-blocks",
"#gather all input files that match",
"inputfiles",
"=",
"self",
".",
"matchingfiles",
"(",
"projectpath",
")",
"#list of (seqnr, filename,inputtemplate) tuples",
"inputfiles_full",
"=",
"[",
"]",
"#We need the full CLAMInputFiles for generating provenance data",
"for",
"seqnr",
",",
"filename",
",",
"inputtemplate",
"in",
"inputfiles",
":",
"#pylint: disable=unused-variable",
"inputfiles_full",
".",
"append",
"(",
"CLAMInputFile",
"(",
"projectpath",
",",
"filename",
")",
")",
"for",
"outputtemplate",
"in",
"self",
".",
"output",
":",
"if",
"isinstance",
"(",
"outputtemplate",
",",
"ParameterCondition",
")",
":",
"outputtemplate",
"=",
"outputtemplate",
".",
"evaluate",
"(",
"parameters",
")",
"#generate output files",
"if",
"outputtemplate",
":",
"if",
"isinstance",
"(",
"outputtemplate",
",",
"OutputTemplate",
")",
":",
"#generate provenance data",
"provenancedata",
"=",
"CLAMProvenanceData",
"(",
"serviceid",
",",
"servicename",
",",
"serviceurl",
",",
"outputtemplate",
".",
"id",
",",
"outputtemplate",
".",
"label",
",",
"inputfiles_full",
",",
"parameters",
")",
"create",
"=",
"True",
"if",
"outputtemplate",
".",
"parent",
":",
"if",
"outputtemplate",
".",
"getparent",
"(",
"self",
")",
"in",
"optional_absent",
":",
"create",
"=",
"False",
"if",
"create",
":",
"for",
"inputtemplate",
",",
"inputfilename",
",",
"outputfilename",
",",
"metadata",
"in",
"outputtemplate",
".",
"generate",
"(",
"self",
",",
"parameters",
",",
"projectpath",
",",
"inputfiles",
",",
"provenancedata",
")",
":",
"clam",
".",
"common",
".",
"util",
".",
"printdebug",
"(",
"\"Writing metadata for outputfile \"",
"+",
"outputfilename",
")",
"metafilename",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"outputfilename",
")",
"if",
"metafilename",
":",
"metafilename",
"+=",
"'/'",
"metafilename",
"+=",
"'.'",
"+",
"os",
".",
"path",
".",
"basename",
"(",
"outputfilename",
")",
"+",
"'.METADATA'",
"f",
"=",
"io",
".",
"open",
"(",
"projectpath",
"+",
"'/output/'",
"+",
"metafilename",
",",
"'w'",
",",
"encoding",
"=",
"'utf-8'",
")",
"f",
".",
"write",
"(",
"metadata",
".",
"xml",
"(",
")",
")",
"f",
".",
"close",
"(",
")",
"program",
".",
"add",
"(",
"outputfilename",
",",
"outputtemplate",
",",
"inputfilename",
",",
"inputtemplate",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"OutputTemplate expected, but got \"",
"+",
"outputtemplate",
".",
"__class__",
".",
"__name__",
")",
"return",
"program"
] | Generate output metadata on the basis of input files and parameters. Projectpath must be absolute. Returns a Program instance. | [
"Generate",
"output",
"metadata",
"on",
"the",
"basis",
"of",
"input",
"files",
"and",
"parameters",
".",
"Projectpath",
"must",
"be",
"absolute",
".",
"Returns",
"a",
"Program",
"instance",
"."
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L910-L956 |
proycon/clam | clam/common/data.py | Profile.xml | def xml(self, indent = ""):
"""Produce XML output for the profile"""
xml = "\n" + indent + "<profile>\n"
xml += indent + " <input>\n"
for inputtemplate in self.input:
xml += inputtemplate.xml(indent +" ") + "\n"
xml += indent + " </input>\n"
xml += indent + " <output>\n"
for outputtemplate in self.output:
xml += outputtemplate.xml(indent +" ") + "\n" #works for ParameterCondition as well!
xml += indent + " </output>\n"
xml += indent + "</profile>\n"
return xml | python | def xml(self, indent = ""):
"""Produce XML output for the profile"""
xml = "\n" + indent + "<profile>\n"
xml += indent + " <input>\n"
for inputtemplate in self.input:
xml += inputtemplate.xml(indent +" ") + "\n"
xml += indent + " </input>\n"
xml += indent + " <output>\n"
for outputtemplate in self.output:
xml += outputtemplate.xml(indent +" ") + "\n" #works for ParameterCondition as well!
xml += indent + " </output>\n"
xml += indent + "</profile>\n"
return xml | [
"def",
"xml",
"(",
"self",
",",
"indent",
"=",
"\"\"",
")",
":",
"xml",
"=",
"\"\\n\"",
"+",
"indent",
"+",
"\"<profile>\\n\"",
"xml",
"+=",
"indent",
"+",
"\" <input>\\n\"",
"for",
"inputtemplate",
"in",
"self",
".",
"input",
":",
"xml",
"+=",
"inputtemplate",
".",
"xml",
"(",
"indent",
"+",
"\" \"",
")",
"+",
"\"\\n\"",
"xml",
"+=",
"indent",
"+",
"\" </input>\\n\"",
"xml",
"+=",
"indent",
"+",
"\" <output>\\n\"",
"for",
"outputtemplate",
"in",
"self",
".",
"output",
":",
"xml",
"+=",
"outputtemplate",
".",
"xml",
"(",
"indent",
"+",
"\" \"",
")",
"+",
"\"\\n\"",
"#works for ParameterCondition as well!",
"xml",
"+=",
"indent",
"+",
"\" </output>\\n\"",
"xml",
"+=",
"indent",
"+",
"\"</profile>\\n\"",
"return",
"xml"
] | Produce XML output for the profile | [
"Produce",
"XML",
"output",
"for",
"the",
"profile"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L959-L971 |
proycon/clam | clam/common/data.py | Profile.fromxml | def fromxml(node):
"""Return a profile instance from the given XML description. Node can be a string or an etree._Element."""
if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access
node = parsexmlstring(node)
args = []
if node.tag == 'profile':
for node in node:
if node.tag == 'input':
for subnode in node:
if subnode.tag.lower() == 'inputtemplate':
args.append(InputTemplate.fromxml(subnode))
elif node.tag == 'output':
for subnode in node:
if subnode.tag.lower() == 'outputtemplate':
args.append(OutputTemplate.fromxml(subnode))
elif subnode.tag.lower() == 'parametercondition':
args.append(ParameterCondition.fromxml(subnode))
return Profile(*args) | python | def fromxml(node):
"""Return a profile instance from the given XML description. Node can be a string or an etree._Element."""
if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access
node = parsexmlstring(node)
args = []
if node.tag == 'profile':
for node in node:
if node.tag == 'input':
for subnode in node:
if subnode.tag.lower() == 'inputtemplate':
args.append(InputTemplate.fromxml(subnode))
elif node.tag == 'output':
for subnode in node:
if subnode.tag.lower() == 'outputtemplate':
args.append(OutputTemplate.fromxml(subnode))
elif subnode.tag.lower() == 'parametercondition':
args.append(ParameterCondition.fromxml(subnode))
return Profile(*args) | [
"def",
"fromxml",
"(",
"node",
")",
":",
"if",
"not",
"isinstance",
"(",
"node",
",",
"ElementTree",
".",
"_Element",
")",
":",
"#pylint: disable=protected-access",
"node",
"=",
"parsexmlstring",
"(",
"node",
")",
"args",
"=",
"[",
"]",
"if",
"node",
".",
"tag",
"==",
"'profile'",
":",
"for",
"node",
"in",
"node",
":",
"if",
"node",
".",
"tag",
"==",
"'input'",
":",
"for",
"subnode",
"in",
"node",
":",
"if",
"subnode",
".",
"tag",
".",
"lower",
"(",
")",
"==",
"'inputtemplate'",
":",
"args",
".",
"append",
"(",
"InputTemplate",
".",
"fromxml",
"(",
"subnode",
")",
")",
"elif",
"node",
".",
"tag",
"==",
"'output'",
":",
"for",
"subnode",
"in",
"node",
":",
"if",
"subnode",
".",
"tag",
".",
"lower",
"(",
")",
"==",
"'outputtemplate'",
":",
"args",
".",
"append",
"(",
"OutputTemplate",
".",
"fromxml",
"(",
"subnode",
")",
")",
"elif",
"subnode",
".",
"tag",
".",
"lower",
"(",
")",
"==",
"'parametercondition'",
":",
"args",
".",
"append",
"(",
"ParameterCondition",
".",
"fromxml",
"(",
"subnode",
")",
")",
"return",
"Profile",
"(",
"*",
"args",
")"
] | Return a profile instance from the given XML description. Node can be a string or an etree._Element. | [
"Return",
"a",
"profile",
"instance",
"from",
"the",
"given",
"XML",
"description",
".",
"Node",
"can",
"be",
"a",
"string",
"or",
"an",
"etree",
".",
"_Element",
"."
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L985-L1004 |
proycon/clam | clam/common/data.py | Program.add | def add(self, outputfilename, outputtemplate, inputfilename=None, inputtemplate=None):
"""Add a new path to the program"""
if isinstance(outputtemplate,OutputTemplate):
outputtemplate = outputtemplate.id
if isinstance(inputtemplate,InputTemplate):
inputtemplate = inputtemplate.id
if outputfilename in self:
outputtemplate, inputfiles = self[outputfilename]
if inputfilename and inputtemplate:
inputfiles[inputfilename] = inputtemplate
else:
if inputfilename and inputtemplate:
self[outputfilename] = (outputtemplate, {inputfilename: inputtemplate})
else:
self[outputfilename] = (outputtemplate, {}) | python | def add(self, outputfilename, outputtemplate, inputfilename=None, inputtemplate=None):
"""Add a new path to the program"""
if isinstance(outputtemplate,OutputTemplate):
outputtemplate = outputtemplate.id
if isinstance(inputtemplate,InputTemplate):
inputtemplate = inputtemplate.id
if outputfilename in self:
outputtemplate, inputfiles = self[outputfilename]
if inputfilename and inputtemplate:
inputfiles[inputfilename] = inputtemplate
else:
if inputfilename and inputtemplate:
self[outputfilename] = (outputtemplate, {inputfilename: inputtemplate})
else:
self[outputfilename] = (outputtemplate, {}) | [
"def",
"add",
"(",
"self",
",",
"outputfilename",
",",
"outputtemplate",
",",
"inputfilename",
"=",
"None",
",",
"inputtemplate",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"outputtemplate",
",",
"OutputTemplate",
")",
":",
"outputtemplate",
"=",
"outputtemplate",
".",
"id",
"if",
"isinstance",
"(",
"inputtemplate",
",",
"InputTemplate",
")",
":",
"inputtemplate",
"=",
"inputtemplate",
".",
"id",
"if",
"outputfilename",
"in",
"self",
":",
"outputtemplate",
",",
"inputfiles",
"=",
"self",
"[",
"outputfilename",
"]",
"if",
"inputfilename",
"and",
"inputtemplate",
":",
"inputfiles",
"[",
"inputfilename",
"]",
"=",
"inputtemplate",
"else",
":",
"if",
"inputfilename",
"and",
"inputtemplate",
":",
"self",
"[",
"outputfilename",
"]",
"=",
"(",
"outputtemplate",
",",
"{",
"inputfilename",
":",
"inputtemplate",
"}",
")",
"else",
":",
"self",
"[",
"outputfilename",
"]",
"=",
"(",
"outputtemplate",
",",
"{",
"}",
")"
] | Add a new path to the program | [
"Add",
"a",
"new",
"path",
"to",
"the",
"program"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L1023-L1037 |
proycon/clam | clam/common/data.py | Program.getoutputfiles | def getoutputfiles(self, loadmetadata=True, client=None,requiremetadata=False):
"""Iterates over all output files and their output template. Yields (CLAMOutputFile, str:outputtemplate_id) tuples. The last three arguments are passed to its constructor."""
for outputfilename, outputtemplate in self.outputpairs():
yield CLAMOutputFile(self.projectpath, outputfilename, loadmetadata,client,requiremetadata), outputtemplate | python | def getoutputfiles(self, loadmetadata=True, client=None,requiremetadata=False):
"""Iterates over all output files and their output template. Yields (CLAMOutputFile, str:outputtemplate_id) tuples. The last three arguments are passed to its constructor."""
for outputfilename, outputtemplate in self.outputpairs():
yield CLAMOutputFile(self.projectpath, outputfilename, loadmetadata,client,requiremetadata), outputtemplate | [
"def",
"getoutputfiles",
"(",
"self",
",",
"loadmetadata",
"=",
"True",
",",
"client",
"=",
"None",
",",
"requiremetadata",
"=",
"False",
")",
":",
"for",
"outputfilename",
",",
"outputtemplate",
"in",
"self",
".",
"outputpairs",
"(",
")",
":",
"yield",
"CLAMOutputFile",
"(",
"self",
".",
"projectpath",
",",
"outputfilename",
",",
"loadmetadata",
",",
"client",
",",
"requiremetadata",
")",
",",
"outputtemplate"
] | Iterates over all output files and their output template. Yields (CLAMOutputFile, str:outputtemplate_id) tuples. The last three arguments are passed to its constructor. | [
"Iterates",
"over",
"all",
"output",
"files",
"and",
"their",
"output",
"template",
".",
"Yields",
"(",
"CLAMOutputFile",
"str",
":",
"outputtemplate_id",
")",
"tuples",
".",
"The",
"last",
"three",
"arguments",
"are",
"passed",
"to",
"its",
"constructor",
"."
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L1049-L1052 |
proycon/clam | clam/common/data.py | Program.getinputfiles | def getinputfiles(self, outputfile, loadmetadata=True, client=None,requiremetadata=False):
"""Iterates over all input files for the specified outputfile (you may pass a CLAMOutputFile instance or a filename string). Yields (CLAMInputFile,str:inputtemplate_id) tuples. The last three arguments are passed to its constructor."""
if isinstance(outputfile, CLAMOutputFile):
outputfilename = str(outputfile).replace(os.path.join(self.projectpath,'output/'),'')
else:
outputfilename = outputfile
outputtemplate, inputfiles = self[outputfilename]
for inputfilename, inputtemplate in inputfiles.items():
yield CLAMInputFile(self.projectpath, inputfilename, loadmetadata,client,requiremetadata), inputtemplate | python | def getinputfiles(self, outputfile, loadmetadata=True, client=None,requiremetadata=False):
"""Iterates over all input files for the specified outputfile (you may pass a CLAMOutputFile instance or a filename string). Yields (CLAMInputFile,str:inputtemplate_id) tuples. The last three arguments are passed to its constructor."""
if isinstance(outputfile, CLAMOutputFile):
outputfilename = str(outputfile).replace(os.path.join(self.projectpath,'output/'),'')
else:
outputfilename = outputfile
outputtemplate, inputfiles = self[outputfilename]
for inputfilename, inputtemplate in inputfiles.items():
yield CLAMInputFile(self.projectpath, inputfilename, loadmetadata,client,requiremetadata), inputtemplate | [
"def",
"getinputfiles",
"(",
"self",
",",
"outputfile",
",",
"loadmetadata",
"=",
"True",
",",
"client",
"=",
"None",
",",
"requiremetadata",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"outputfile",
",",
"CLAMOutputFile",
")",
":",
"outputfilename",
"=",
"str",
"(",
"outputfile",
")",
".",
"replace",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"projectpath",
",",
"'output/'",
")",
",",
"''",
")",
"else",
":",
"outputfilename",
"=",
"outputfile",
"outputtemplate",
",",
"inputfiles",
"=",
"self",
"[",
"outputfilename",
"]",
"for",
"inputfilename",
",",
"inputtemplate",
"in",
"inputfiles",
".",
"items",
"(",
")",
":",
"yield",
"CLAMInputFile",
"(",
"self",
".",
"projectpath",
",",
"inputfilename",
",",
"loadmetadata",
",",
"client",
",",
"requiremetadata",
")",
",",
"inputtemplate"
] | Iterates over all input files for the specified outputfile (you may pass a CLAMOutputFile instance or a filename string). Yields (CLAMInputFile,str:inputtemplate_id) tuples. The last three arguments are passed to its constructor. | [
"Iterates",
"over",
"all",
"input",
"files",
"for",
"the",
"specified",
"outputfile",
"(",
"you",
"may",
"pass",
"a",
"CLAMOutputFile",
"instance",
"or",
"a",
"filename",
"string",
")",
".",
"Yields",
"(",
"CLAMInputFile",
"str",
":",
"inputtemplate_id",
")",
"tuples",
".",
"The",
"last",
"three",
"arguments",
"are",
"passed",
"to",
"its",
"constructor",
"."
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L1054-L1062 |
proycon/clam | clam/common/data.py | Program.getinputfile | def getinputfile(self, outputfile, loadmetadata=True, client=None,requiremetadata=False):
"""Grabs one input file for the specified output filename (raises a KeyError exception if there is no such output, StopIteration if there are no input files for it). Shortcut for getinputfiles()"""
if isinstance(outputfile, CLAMOutputFile):
outputfilename = str(outputfile).replace(os.path.join(self.projectpath,'output/'),'')
else:
outputfilename = outputfile
if outputfilename not in self:
raise KeyError("No such outputfile " + outputfilename)
try:
return next(self.getinputfiles(outputfile,loadmetadata,client,requiremetadata))
except StopIteration:
raise StopIteration("No input files for outputfile " + outputfilename) | python | def getinputfile(self, outputfile, loadmetadata=True, client=None,requiremetadata=False):
"""Grabs one input file for the specified output filename (raises a KeyError exception if there is no such output, StopIteration if there are no input files for it). Shortcut for getinputfiles()"""
if isinstance(outputfile, CLAMOutputFile):
outputfilename = str(outputfile).replace(os.path.join(self.projectpath,'output/'),'')
else:
outputfilename = outputfile
if outputfilename not in self:
raise KeyError("No such outputfile " + outputfilename)
try:
return next(self.getinputfiles(outputfile,loadmetadata,client,requiremetadata))
except StopIteration:
raise StopIteration("No input files for outputfile " + outputfilename) | [
"def",
"getinputfile",
"(",
"self",
",",
"outputfile",
",",
"loadmetadata",
"=",
"True",
",",
"client",
"=",
"None",
",",
"requiremetadata",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"outputfile",
",",
"CLAMOutputFile",
")",
":",
"outputfilename",
"=",
"str",
"(",
"outputfile",
")",
".",
"replace",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"projectpath",
",",
"'output/'",
")",
",",
"''",
")",
"else",
":",
"outputfilename",
"=",
"outputfile",
"if",
"outputfilename",
"not",
"in",
"self",
":",
"raise",
"KeyError",
"(",
"\"No such outputfile \"",
"+",
"outputfilename",
")",
"try",
":",
"return",
"next",
"(",
"self",
".",
"getinputfiles",
"(",
"outputfile",
",",
"loadmetadata",
",",
"client",
",",
"requiremetadata",
")",
")",
"except",
"StopIteration",
":",
"raise",
"StopIteration",
"(",
"\"No input files for outputfile \"",
"+",
"outputfilename",
")"
] | Grabs one input file for the specified output filename (raises a KeyError exception if there is no such output, StopIteration if there are no input files for it). Shortcut for getinputfiles() | [
"Grabs",
"one",
"input",
"file",
"for",
"the",
"specified",
"output",
"filename",
"(",
"raises",
"a",
"KeyError",
"exception",
"if",
"there",
"is",
"no",
"such",
"output",
"StopIteration",
"if",
"there",
"are",
"no",
"input",
"files",
"for",
"it",
")",
".",
"Shortcut",
"for",
"getinputfiles",
"()"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L1064-L1075 |
proycon/clam | clam/common/data.py | Program.getoutputfile | def getoutputfile(self, loadmetadata=True, client=None,requiremetadata=False):
"""Grabs one output file (raises a StopIteration exception if there is none). Shortcut for getoutputfiles()"""
return next(self.getoutputfiles(loadmetadata,client,requiremetadata)) | python | def getoutputfile(self, loadmetadata=True, client=None,requiremetadata=False):
"""Grabs one output file (raises a StopIteration exception if there is none). Shortcut for getoutputfiles()"""
return next(self.getoutputfiles(loadmetadata,client,requiremetadata)) | [
"def",
"getoutputfile",
"(",
"self",
",",
"loadmetadata",
"=",
"True",
",",
"client",
"=",
"None",
",",
"requiremetadata",
"=",
"False",
")",
":",
"return",
"next",
"(",
"self",
".",
"getoutputfiles",
"(",
"loadmetadata",
",",
"client",
",",
"requiremetadata",
")",
")"
] | Grabs one output file (raises a StopIteration exception if there is none). Shortcut for getoutputfiles() | [
"Grabs",
"one",
"output",
"file",
"(",
"raises",
"a",
"StopIteration",
"exception",
"if",
"there",
"is",
"none",
")",
".",
"Shortcut",
"for",
"getoutputfiles",
"()"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L1077-L1079 |
proycon/clam | clam/common/data.py | CLAMProvenanceData.xml | def xml(self, indent = ""):
"""Serialise provenance data to XML. This is included in CLAM Metadata files"""
xml = indent + "<provenance type=\"clam\" id=\""+self.serviceid+"\" name=\"" +self.servicename+"\" url=\"" + self.serviceurl+"\" outputtemplate=\""+self.outputtemplate_id+"\" outputtemplatelabel=\""+self.outputtemplate_label+"\" timestamp=\""+str(self.timestamp)+"\">"
for filename, metadata in self.inputfiles:
xml += indent + " <inputfile name=\"" + clam.common.util.xmlescape(filename) + "\">"
xml += metadata.xml(indent + " ") + "\n"
xml += indent + " </inputfile>\n"
if self.parameters:
xml += indent + " <parameters>\n"
if isinstance(self.parameters, dict):
parameters = self.parameters.values()
elif isinstance(self.parameters, list):
parameters = self.parameters
for parameter in parameters:
xml += parameter.xml(indent +" ") + "\n"
xml += indent + " </parameters>\n"
xml += indent + "</provenance>"
return xml | python | def xml(self, indent = ""):
"""Serialise provenance data to XML. This is included in CLAM Metadata files"""
xml = indent + "<provenance type=\"clam\" id=\""+self.serviceid+"\" name=\"" +self.servicename+"\" url=\"" + self.serviceurl+"\" outputtemplate=\""+self.outputtemplate_id+"\" outputtemplatelabel=\""+self.outputtemplate_label+"\" timestamp=\""+str(self.timestamp)+"\">"
for filename, metadata in self.inputfiles:
xml += indent + " <inputfile name=\"" + clam.common.util.xmlescape(filename) + "\">"
xml += metadata.xml(indent + " ") + "\n"
xml += indent + " </inputfile>\n"
if self.parameters:
xml += indent + " <parameters>\n"
if isinstance(self.parameters, dict):
parameters = self.parameters.values()
elif isinstance(self.parameters, list):
parameters = self.parameters
for parameter in parameters:
xml += parameter.xml(indent +" ") + "\n"
xml += indent + " </parameters>\n"
xml += indent + "</provenance>"
return xml | [
"def",
"xml",
"(",
"self",
",",
"indent",
"=",
"\"\"",
")",
":",
"xml",
"=",
"indent",
"+",
"\"<provenance type=\\\"clam\\\" id=\\\"\"",
"+",
"self",
".",
"serviceid",
"+",
"\"\\\" name=\\\"\"",
"+",
"self",
".",
"servicename",
"+",
"\"\\\" url=\\\"\"",
"+",
"self",
".",
"serviceurl",
"+",
"\"\\\" outputtemplate=\\\"\"",
"+",
"self",
".",
"outputtemplate_id",
"+",
"\"\\\" outputtemplatelabel=\\\"\"",
"+",
"self",
".",
"outputtemplate_label",
"+",
"\"\\\" timestamp=\\\"\"",
"+",
"str",
"(",
"self",
".",
"timestamp",
")",
"+",
"\"\\\">\"",
"for",
"filename",
",",
"metadata",
"in",
"self",
".",
"inputfiles",
":",
"xml",
"+=",
"indent",
"+",
"\" <inputfile name=\\\"\"",
"+",
"clam",
".",
"common",
".",
"util",
".",
"xmlescape",
"(",
"filename",
")",
"+",
"\"\\\">\"",
"xml",
"+=",
"metadata",
".",
"xml",
"(",
"indent",
"+",
"\" \"",
")",
"+",
"\"\\n\"",
"xml",
"+=",
"indent",
"+",
"\" </inputfile>\\n\"",
"if",
"self",
".",
"parameters",
":",
"xml",
"+=",
"indent",
"+",
"\" <parameters>\\n\"",
"if",
"isinstance",
"(",
"self",
".",
"parameters",
",",
"dict",
")",
":",
"parameters",
"=",
"self",
".",
"parameters",
".",
"values",
"(",
")",
"elif",
"isinstance",
"(",
"self",
".",
"parameters",
",",
"list",
")",
":",
"parameters",
"=",
"self",
".",
"parameters",
"for",
"parameter",
"in",
"parameters",
":",
"xml",
"+=",
"parameter",
".",
"xml",
"(",
"indent",
"+",
"\" \"",
")",
"+",
"\"\\n\"",
"xml",
"+=",
"indent",
"+",
"\" </parameters>\\n\"",
"xml",
"+=",
"indent",
"+",
"\"</provenance>\"",
"return",
"xml"
] | Serialise provenance data to XML. This is included in CLAM Metadata files | [
"Serialise",
"provenance",
"data",
"to",
"XML",
".",
"This",
"is",
"included",
"in",
"CLAM",
"Metadata",
"files"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L1123-L1140 |
proycon/clam | clam/common/data.py | CLAMProvenanceData.fromxml | def fromxml(node):
"""Return a CLAMProvenanceData instance from the given XML description. Node can be a string or an lxml.etree._Element."""
if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access
node = parsexmlstring(node)
if node.tag == 'provenance': #pylint: disable=too-many-nested-blocks
if node.attrib['type'] == 'clam':
serviceid = node.attrib['id']
servicename = node.attrib['name']
serviceurl = node.attrib['url']
timestamp = node.attrib['timestamp']
outputtemplate = node.attrib['outputtemplate']
outputtemplatelabel = node.attrib['outputtemplatelabel']
inputfiles = []
parameters = []
for subnode in node:
if subnode.tag == 'inputfile':
filename = node.attrib['name']
metadata = None
for subsubnode in subnode:
if subsubnode.tag == 'CLAMMetaData':
metadata = CLAMMetaData.fromxml(subsubnode)
break
inputfiles.append( (filename, metadata) )
elif subnode.tag == 'parameters':
for subsubnode in subnode:
if subsubnode.tag in vars(clam.common.parameters):
parameters.append(vars(clam.common.parameters)[subsubnode.tag].fromxml(subsubnode))
else:
raise Exception("Expected parameter class '" + subsubnode.tag + "', but not defined!")
return CLAMProvenanceData(serviceid,servicename,serviceurl,outputtemplate, outputtemplatelabel, inputfiles, parameters, timestamp)
else:
raise NotImplementedError | python | def fromxml(node):
"""Return a CLAMProvenanceData instance from the given XML description. Node can be a string or an lxml.etree._Element."""
if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access
node = parsexmlstring(node)
if node.tag == 'provenance': #pylint: disable=too-many-nested-blocks
if node.attrib['type'] == 'clam':
serviceid = node.attrib['id']
servicename = node.attrib['name']
serviceurl = node.attrib['url']
timestamp = node.attrib['timestamp']
outputtemplate = node.attrib['outputtemplate']
outputtemplatelabel = node.attrib['outputtemplatelabel']
inputfiles = []
parameters = []
for subnode in node:
if subnode.tag == 'inputfile':
filename = node.attrib['name']
metadata = None
for subsubnode in subnode:
if subsubnode.tag == 'CLAMMetaData':
metadata = CLAMMetaData.fromxml(subsubnode)
break
inputfiles.append( (filename, metadata) )
elif subnode.tag == 'parameters':
for subsubnode in subnode:
if subsubnode.tag in vars(clam.common.parameters):
parameters.append(vars(clam.common.parameters)[subsubnode.tag].fromxml(subsubnode))
else:
raise Exception("Expected parameter class '" + subsubnode.tag + "', but not defined!")
return CLAMProvenanceData(serviceid,servicename,serviceurl,outputtemplate, outputtemplatelabel, inputfiles, parameters, timestamp)
else:
raise NotImplementedError | [
"def",
"fromxml",
"(",
"node",
")",
":",
"if",
"not",
"isinstance",
"(",
"node",
",",
"ElementTree",
".",
"_Element",
")",
":",
"#pylint: disable=protected-access",
"node",
"=",
"parsexmlstring",
"(",
"node",
")",
"if",
"node",
".",
"tag",
"==",
"'provenance'",
":",
"#pylint: disable=too-many-nested-blocks",
"if",
"node",
".",
"attrib",
"[",
"'type'",
"]",
"==",
"'clam'",
":",
"serviceid",
"=",
"node",
".",
"attrib",
"[",
"'id'",
"]",
"servicename",
"=",
"node",
".",
"attrib",
"[",
"'name'",
"]",
"serviceurl",
"=",
"node",
".",
"attrib",
"[",
"'url'",
"]",
"timestamp",
"=",
"node",
".",
"attrib",
"[",
"'timestamp'",
"]",
"outputtemplate",
"=",
"node",
".",
"attrib",
"[",
"'outputtemplate'",
"]",
"outputtemplatelabel",
"=",
"node",
".",
"attrib",
"[",
"'outputtemplatelabel'",
"]",
"inputfiles",
"=",
"[",
"]",
"parameters",
"=",
"[",
"]",
"for",
"subnode",
"in",
"node",
":",
"if",
"subnode",
".",
"tag",
"==",
"'inputfile'",
":",
"filename",
"=",
"node",
".",
"attrib",
"[",
"'name'",
"]",
"metadata",
"=",
"None",
"for",
"subsubnode",
"in",
"subnode",
":",
"if",
"subsubnode",
".",
"tag",
"==",
"'CLAMMetaData'",
":",
"metadata",
"=",
"CLAMMetaData",
".",
"fromxml",
"(",
"subsubnode",
")",
"break",
"inputfiles",
".",
"append",
"(",
"(",
"filename",
",",
"metadata",
")",
")",
"elif",
"subnode",
".",
"tag",
"==",
"'parameters'",
":",
"for",
"subsubnode",
"in",
"subnode",
":",
"if",
"subsubnode",
".",
"tag",
"in",
"vars",
"(",
"clam",
".",
"common",
".",
"parameters",
")",
":",
"parameters",
".",
"append",
"(",
"vars",
"(",
"clam",
".",
"common",
".",
"parameters",
")",
"[",
"subsubnode",
".",
"tag",
"]",
".",
"fromxml",
"(",
"subsubnode",
")",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"Expected parameter class '\"",
"+",
"subsubnode",
".",
"tag",
"+",
"\"', but not defined!\"",
")",
"return",
"CLAMProvenanceData",
"(",
"serviceid",
",",
"servicename",
",",
"serviceurl",
",",
"outputtemplate",
",",
"outputtemplatelabel",
",",
"inputfiles",
",",
"parameters",
",",
"timestamp",
")",
"else",
":",
"raise",
"NotImplementedError"
] | Return a CLAMProvenanceData instance from the given XML description. Node can be a string or an lxml.etree._Element. | [
"Return",
"a",
"CLAMProvenanceData",
"instance",
"from",
"the",
"given",
"XML",
"description",
".",
"Node",
"can",
"be",
"a",
"string",
"or",
"an",
"lxml",
".",
"etree",
".",
"_Element",
"."
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L1143-L1174 |
proycon/clam | clam/common/data.py | CLAMMetaData.xml | def xml(self, indent = ""):
"""Render an XML representation of the metadata""" #(independent of web.py for support in CLAM API)
if not indent:
xml = '<?xml version="1.0" encoding="UTF-8"?>\n'
else:
xml = ""
xml += indent + "<CLAMMetaData format=\"" + self.__class__.__name__ + "\""
if self.mimetype:
xml += " mimetype=\""+self.mimetype+"\""
if self.schema:
xml += " schema=\""+self.schema+"\""
if self.inputtemplate:
xml += " inputtemplate=\""+self.inputtemplate+"\""
xml += ">\n"
for key, value in self.data.items():
xml += indent + " <meta id=\""+clam.common.util.xmlescape(key)+"\">"+clam.common.util.xmlescape(str(value))+"</meta>\n"
if self.provenance:
xml += self.provenance.xml(indent + " ")
xml += indent + "</CLAMMetaData>"
return xml | python | def xml(self, indent = ""):
"""Render an XML representation of the metadata""" #(independent of web.py for support in CLAM API)
if not indent:
xml = '<?xml version="1.0" encoding="UTF-8"?>\n'
else:
xml = ""
xml += indent + "<CLAMMetaData format=\"" + self.__class__.__name__ + "\""
if self.mimetype:
xml += " mimetype=\""+self.mimetype+"\""
if self.schema:
xml += " schema=\""+self.schema+"\""
if self.inputtemplate:
xml += " inputtemplate=\""+self.inputtemplate+"\""
xml += ">\n"
for key, value in self.data.items():
xml += indent + " <meta id=\""+clam.common.util.xmlescape(key)+"\">"+clam.common.util.xmlescape(str(value))+"</meta>\n"
if self.provenance:
xml += self.provenance.xml(indent + " ")
xml += indent + "</CLAMMetaData>"
return xml | [
"def",
"xml",
"(",
"self",
",",
"indent",
"=",
"\"\"",
")",
":",
"#(independent of web.py for support in CLAM API)",
"if",
"not",
"indent",
":",
"xml",
"=",
"'<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n'",
"else",
":",
"xml",
"=",
"\"\"",
"xml",
"+=",
"indent",
"+",
"\"<CLAMMetaData format=\\\"\"",
"+",
"self",
".",
"__class__",
".",
"__name__",
"+",
"\"\\\"\"",
"if",
"self",
".",
"mimetype",
":",
"xml",
"+=",
"\" mimetype=\\\"\"",
"+",
"self",
".",
"mimetype",
"+",
"\"\\\"\"",
"if",
"self",
".",
"schema",
":",
"xml",
"+=",
"\" schema=\\\"\"",
"+",
"self",
".",
"schema",
"+",
"\"\\\"\"",
"if",
"self",
".",
"inputtemplate",
":",
"xml",
"+=",
"\" inputtemplate=\\\"\"",
"+",
"self",
".",
"inputtemplate",
"+",
"\"\\\"\"",
"xml",
"+=",
"\">\\n\"",
"for",
"key",
",",
"value",
"in",
"self",
".",
"data",
".",
"items",
"(",
")",
":",
"xml",
"+=",
"indent",
"+",
"\" <meta id=\\\"\"",
"+",
"clam",
".",
"common",
".",
"util",
".",
"xmlescape",
"(",
"key",
")",
"+",
"\"\\\">\"",
"+",
"clam",
".",
"common",
".",
"util",
".",
"xmlescape",
"(",
"str",
"(",
"value",
")",
")",
"+",
"\"</meta>\\n\"",
"if",
"self",
".",
"provenance",
":",
"xml",
"+=",
"self",
".",
"provenance",
".",
"xml",
"(",
"indent",
"+",
"\" \"",
")",
"xml",
"+=",
"indent",
"+",
"\"</CLAMMetaData>\"",
"return",
"xml"
] | Render an XML representation of the metadata | [
"Render",
"an",
"XML",
"representation",
"of",
"the",
"metadata"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L1283-L1305 |
proycon/clam | clam/common/data.py | CLAMMetaData.save | def save(self, filename):
"""Save metadata to XML file"""
with io.open(filename,'w',encoding='utf-8') as f:
f.write(self.xml()) | python | def save(self, filename):
"""Save metadata to XML file"""
with io.open(filename,'w',encoding='utf-8') as f:
f.write(self.xml()) | [
"def",
"save",
"(",
"self",
",",
"filename",
")",
":",
"with",
"io",
".",
"open",
"(",
"filename",
",",
"'w'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"self",
".",
"xml",
"(",
")",
")"
] | Save metadata to XML file | [
"Save",
"metadata",
"to",
"XML",
"file"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L1307-L1310 |
proycon/clam | clam/common/data.py | CLAMMetaData.fromxml | def fromxml(node, file=None):
"""Read metadata from XML. Static method returning an CLAMMetaData instance (or rather; the appropriate subclass of CLAMMetaData) from the given XML description. Node can be a string or an etree._Element."""
if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access
node = parsexmlstring(node)
if node.tag == 'CLAMMetaData':
dataformat = node.attrib['format']
formatclass = None
for C in CUSTOM_FORMATS: #CUSTOM_FORMATS will be injected by clamservice.py
if C.__name__ == dataformat:
formatclass = C
break
if formatclass is None and dataformat in vars(clam.common.formats) and issubclass(vars(clam.common.formats)[dataformat], CLAMMetaData):
formatclass = vars(clam.common.formats)[dataformat]
if formatclass is None:
raise Exception("Format class " + dataformat + " not found!")
data = {}
if 'inputtemplate' in node.attrib:
data['inputtemplate'] = node.attrib['inputtemplate']
if 'inputtemplatelabel' in node.attrib:
data['inputtemplatelabel'] = node.attrib['inputtemplatelabel']
for subnode in node:
if subnode.tag == 'meta':
key = subnode.attrib['id']
value = subnode.text
data[key] = value
elif subnode.tag == 'provenance':
data['provenance'] = CLAMProvenanceData.fromxml(subnode)
return formatclass(file, **data)
else:
raise Exception("Invalid CLAM Metadata!") | python | def fromxml(node, file=None):
"""Read metadata from XML. Static method returning an CLAMMetaData instance (or rather; the appropriate subclass of CLAMMetaData) from the given XML description. Node can be a string or an etree._Element."""
if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access
node = parsexmlstring(node)
if node.tag == 'CLAMMetaData':
dataformat = node.attrib['format']
formatclass = None
for C in CUSTOM_FORMATS: #CUSTOM_FORMATS will be injected by clamservice.py
if C.__name__ == dataformat:
formatclass = C
break
if formatclass is None and dataformat in vars(clam.common.formats) and issubclass(vars(clam.common.formats)[dataformat], CLAMMetaData):
formatclass = vars(clam.common.formats)[dataformat]
if formatclass is None:
raise Exception("Format class " + dataformat + " not found!")
data = {}
if 'inputtemplate' in node.attrib:
data['inputtemplate'] = node.attrib['inputtemplate']
if 'inputtemplatelabel' in node.attrib:
data['inputtemplatelabel'] = node.attrib['inputtemplatelabel']
for subnode in node:
if subnode.tag == 'meta':
key = subnode.attrib['id']
value = subnode.text
data[key] = value
elif subnode.tag == 'provenance':
data['provenance'] = CLAMProvenanceData.fromxml(subnode)
return formatclass(file, **data)
else:
raise Exception("Invalid CLAM Metadata!") | [
"def",
"fromxml",
"(",
"node",
",",
"file",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"node",
",",
"ElementTree",
".",
"_Element",
")",
":",
"#pylint: disable=protected-access",
"node",
"=",
"parsexmlstring",
"(",
"node",
")",
"if",
"node",
".",
"tag",
"==",
"'CLAMMetaData'",
":",
"dataformat",
"=",
"node",
".",
"attrib",
"[",
"'format'",
"]",
"formatclass",
"=",
"None",
"for",
"C",
"in",
"CUSTOM_FORMATS",
":",
"#CUSTOM_FORMATS will be injected by clamservice.py",
"if",
"C",
".",
"__name__",
"==",
"dataformat",
":",
"formatclass",
"=",
"C",
"break",
"if",
"formatclass",
"is",
"None",
"and",
"dataformat",
"in",
"vars",
"(",
"clam",
".",
"common",
".",
"formats",
")",
"and",
"issubclass",
"(",
"vars",
"(",
"clam",
".",
"common",
".",
"formats",
")",
"[",
"dataformat",
"]",
",",
"CLAMMetaData",
")",
":",
"formatclass",
"=",
"vars",
"(",
"clam",
".",
"common",
".",
"formats",
")",
"[",
"dataformat",
"]",
"if",
"formatclass",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"Format class \"",
"+",
"dataformat",
"+",
"\" not found!\"",
")",
"data",
"=",
"{",
"}",
"if",
"'inputtemplate'",
"in",
"node",
".",
"attrib",
":",
"data",
"[",
"'inputtemplate'",
"]",
"=",
"node",
".",
"attrib",
"[",
"'inputtemplate'",
"]",
"if",
"'inputtemplatelabel'",
"in",
"node",
".",
"attrib",
":",
"data",
"[",
"'inputtemplatelabel'",
"]",
"=",
"node",
".",
"attrib",
"[",
"'inputtemplatelabel'",
"]",
"for",
"subnode",
"in",
"node",
":",
"if",
"subnode",
".",
"tag",
"==",
"'meta'",
":",
"key",
"=",
"subnode",
".",
"attrib",
"[",
"'id'",
"]",
"value",
"=",
"subnode",
".",
"text",
"data",
"[",
"key",
"]",
"=",
"value",
"elif",
"subnode",
".",
"tag",
"==",
"'provenance'",
":",
"data",
"[",
"'provenance'",
"]",
"=",
"CLAMProvenanceData",
".",
"fromxml",
"(",
"subnode",
")",
"return",
"formatclass",
"(",
"file",
",",
"*",
"*",
"data",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"Invalid CLAM Metadata!\"",
")"
] | Read metadata from XML. Static method returning an CLAMMetaData instance (or rather; the appropriate subclass of CLAMMetaData) from the given XML description. Node can be a string or an etree._Element. | [
"Read",
"metadata",
"from",
"XML",
".",
"Static",
"method",
"returning",
"an",
"CLAMMetaData",
"instance",
"(",
"or",
"rather",
";",
"the",
"appropriate",
"subclass",
"of",
"CLAMMetaData",
")",
"from",
"the",
"given",
"XML",
"description",
".",
"Node",
"can",
"be",
"a",
"string",
"or",
"an",
"etree",
".",
"_Element",
"."
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L1328-L1362 |
proycon/clam | clam/common/data.py | InputTemplate.xml | def xml(self, indent = ""):
"""Produce Template XML"""
xml = indent + "<InputTemplate id=\""+self.id+"\" format=\"" + self.formatclass.__name__ + "\"" + " label=\"" + self.label + "\""
if self.formatclass.mimetype:
xml +=" mimetype=\""+self.formatclass.mimetype+"\""
if self.formatclass.schema:
xml +=" schema=\""+self.formatclass.schema+"\""
if self.filename:
xml +=" filename=\""+self.filename+"\""
if self.extension:
xml +=" extension=\""+self.extension+"\""
if self.optional:
xml +=" optional=\"yes\""
else:
xml +=" optional=\"no\""
if self.unique:
xml +=" unique=\"yes\""
else:
xml +=" unique=\"no\""
if self.acceptarchive:
xml +=" acceptarchive=\"yes\""
else:
xml +=" acceptarchive=\"no\""
xml += ">\n"
for parameter in self.parameters:
xml += parameter.xml(indent+" ") + "\n"
if self.converters:
for converter in self.converters:
xml += indent + " <converter id=\""+converter.id+"\">"+clam.common.util.xmlescape(converter.label)+"</converter>\n"
if self.inputsources:
for inputsource in self.inputsources:
xml += inputsource.xml(indent+" ")
xml += indent + "</InputTemplate>"
return xml | python | def xml(self, indent = ""):
"""Produce Template XML"""
xml = indent + "<InputTemplate id=\""+self.id+"\" format=\"" + self.formatclass.__name__ + "\"" + " label=\"" + self.label + "\""
if self.formatclass.mimetype:
xml +=" mimetype=\""+self.formatclass.mimetype+"\""
if self.formatclass.schema:
xml +=" schema=\""+self.formatclass.schema+"\""
if self.filename:
xml +=" filename=\""+self.filename+"\""
if self.extension:
xml +=" extension=\""+self.extension+"\""
if self.optional:
xml +=" optional=\"yes\""
else:
xml +=" optional=\"no\""
if self.unique:
xml +=" unique=\"yes\""
else:
xml +=" unique=\"no\""
if self.acceptarchive:
xml +=" acceptarchive=\"yes\""
else:
xml +=" acceptarchive=\"no\""
xml += ">\n"
for parameter in self.parameters:
xml += parameter.xml(indent+" ") + "\n"
if self.converters:
for converter in self.converters:
xml += indent + " <converter id=\""+converter.id+"\">"+clam.common.util.xmlescape(converter.label)+"</converter>\n"
if self.inputsources:
for inputsource in self.inputsources:
xml += inputsource.xml(indent+" ")
xml += indent + "</InputTemplate>"
return xml | [
"def",
"xml",
"(",
"self",
",",
"indent",
"=",
"\"\"",
")",
":",
"xml",
"=",
"indent",
"+",
"\"<InputTemplate id=\\\"\"",
"+",
"self",
".",
"id",
"+",
"\"\\\" format=\\\"\"",
"+",
"self",
".",
"formatclass",
".",
"__name__",
"+",
"\"\\\"\"",
"+",
"\" label=\\\"\"",
"+",
"self",
".",
"label",
"+",
"\"\\\"\"",
"if",
"self",
".",
"formatclass",
".",
"mimetype",
":",
"xml",
"+=",
"\" mimetype=\\\"\"",
"+",
"self",
".",
"formatclass",
".",
"mimetype",
"+",
"\"\\\"\"",
"if",
"self",
".",
"formatclass",
".",
"schema",
":",
"xml",
"+=",
"\" schema=\\\"\"",
"+",
"self",
".",
"formatclass",
".",
"schema",
"+",
"\"\\\"\"",
"if",
"self",
".",
"filename",
":",
"xml",
"+=",
"\" filename=\\\"\"",
"+",
"self",
".",
"filename",
"+",
"\"\\\"\"",
"if",
"self",
".",
"extension",
":",
"xml",
"+=",
"\" extension=\\\"\"",
"+",
"self",
".",
"extension",
"+",
"\"\\\"\"",
"if",
"self",
".",
"optional",
":",
"xml",
"+=",
"\" optional=\\\"yes\\\"\"",
"else",
":",
"xml",
"+=",
"\" optional=\\\"no\\\"\"",
"if",
"self",
".",
"unique",
":",
"xml",
"+=",
"\" unique=\\\"yes\\\"\"",
"else",
":",
"xml",
"+=",
"\" unique=\\\"no\\\"\"",
"if",
"self",
".",
"acceptarchive",
":",
"xml",
"+=",
"\" acceptarchive=\\\"yes\\\"\"",
"else",
":",
"xml",
"+=",
"\" acceptarchive=\\\"no\\\"\"",
"xml",
"+=",
"\">\\n\"",
"for",
"parameter",
"in",
"self",
".",
"parameters",
":",
"xml",
"+=",
"parameter",
".",
"xml",
"(",
"indent",
"+",
"\" \"",
")",
"+",
"\"\\n\"",
"if",
"self",
".",
"converters",
":",
"for",
"converter",
"in",
"self",
".",
"converters",
":",
"xml",
"+=",
"indent",
"+",
"\" <converter id=\\\"\"",
"+",
"converter",
".",
"id",
"+",
"\"\\\">\"",
"+",
"clam",
".",
"common",
".",
"util",
".",
"xmlescape",
"(",
"converter",
".",
"label",
")",
"+",
"\"</converter>\\n\"",
"if",
"self",
".",
"inputsources",
":",
"for",
"inputsource",
"in",
"self",
".",
"inputsources",
":",
"xml",
"+=",
"inputsource",
".",
"xml",
"(",
"indent",
"+",
"\" \"",
")",
"xml",
"+=",
"indent",
"+",
"\"</InputTemplate>\"",
"return",
"xml"
] | Produce Template XML | [
"Produce",
"Template",
"XML"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L1440-L1473 |
proycon/clam | clam/common/data.py | InputTemplate.json | def json(self):
"""Produce a JSON representation for the web interface"""
d = { 'id': self.id, 'format': self.formatclass.__name__,'label': self.label, 'mimetype': self.formatclass.mimetype, 'schema': self.formatclass.schema }
if self.unique:
d['unique'] = True
if self.filename:
d['filename'] = self.filename
if self.extension:
d['extension'] = self.extension
if self.acceptarchive:
d['acceptarchive'] = self.acceptarchive
#d['parameters'] = {}
#The actual parameters are included as XML, and transformed by clam.js using XSLT (parameter.xsl) to generate the forms
parametersxml = ''
for parameter in self.parameters:
parametersxml += parameter.xml()
d['parametersxml'] = '<?xml version="1.0" encoding="utf-8" ?><parameters>' + parametersxml + '</parameters>'
d['converters'] = [ {'id':x.id, 'label':x.label} for x in self.converters ]
d['inputsources'] = [ {'id':x.id, 'label':x.label} for x in self.inputsources ]
return json.dumps(d) | python | def json(self):
"""Produce a JSON representation for the web interface"""
d = { 'id': self.id, 'format': self.formatclass.__name__,'label': self.label, 'mimetype': self.formatclass.mimetype, 'schema': self.formatclass.schema }
if self.unique:
d['unique'] = True
if self.filename:
d['filename'] = self.filename
if self.extension:
d['extension'] = self.extension
if self.acceptarchive:
d['acceptarchive'] = self.acceptarchive
#d['parameters'] = {}
#The actual parameters are included as XML, and transformed by clam.js using XSLT (parameter.xsl) to generate the forms
parametersxml = ''
for parameter in self.parameters:
parametersxml += parameter.xml()
d['parametersxml'] = '<?xml version="1.0" encoding="utf-8" ?><parameters>' + parametersxml + '</parameters>'
d['converters'] = [ {'id':x.id, 'label':x.label} for x in self.converters ]
d['inputsources'] = [ {'id':x.id, 'label':x.label} for x in self.inputsources ]
return json.dumps(d) | [
"def",
"json",
"(",
"self",
")",
":",
"d",
"=",
"{",
"'id'",
":",
"self",
".",
"id",
",",
"'format'",
":",
"self",
".",
"formatclass",
".",
"__name__",
",",
"'label'",
":",
"self",
".",
"label",
",",
"'mimetype'",
":",
"self",
".",
"formatclass",
".",
"mimetype",
",",
"'schema'",
":",
"self",
".",
"formatclass",
".",
"schema",
"}",
"if",
"self",
".",
"unique",
":",
"d",
"[",
"'unique'",
"]",
"=",
"True",
"if",
"self",
".",
"filename",
":",
"d",
"[",
"'filename'",
"]",
"=",
"self",
".",
"filename",
"if",
"self",
".",
"extension",
":",
"d",
"[",
"'extension'",
"]",
"=",
"self",
".",
"extension",
"if",
"self",
".",
"acceptarchive",
":",
"d",
"[",
"'acceptarchive'",
"]",
"=",
"self",
".",
"acceptarchive",
"#d['parameters'] = {}",
"#The actual parameters are included as XML, and transformed by clam.js using XSLT (parameter.xsl) to generate the forms",
"parametersxml",
"=",
"''",
"for",
"parameter",
"in",
"self",
".",
"parameters",
":",
"parametersxml",
"+=",
"parameter",
".",
"xml",
"(",
")",
"d",
"[",
"'parametersxml'",
"]",
"=",
"'<?xml version=\"1.0\" encoding=\"utf-8\" ?><parameters>'",
"+",
"parametersxml",
"+",
"'</parameters>'",
"d",
"[",
"'converters'",
"]",
"=",
"[",
"{",
"'id'",
":",
"x",
".",
"id",
",",
"'label'",
":",
"x",
".",
"label",
"}",
"for",
"x",
"in",
"self",
".",
"converters",
"]",
"d",
"[",
"'inputsources'",
"]",
"=",
"[",
"{",
"'id'",
":",
"x",
".",
"id",
",",
"'label'",
":",
"x",
".",
"label",
"}",
"for",
"x",
"in",
"self",
".",
"inputsources",
"]",
"return",
"json",
".",
"dumps",
"(",
"d",
")"
] | Produce a JSON representation for the web interface | [
"Produce",
"a",
"JSON",
"representation",
"for",
"the",
"web",
"interface"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L1524-L1545 |
proycon/clam | clam/common/data.py | InputTemplate.match | def match(self, metadata, user = None):
"""Does the specified metadata match this template? returns (success,metadata,parameters)"""
assert isinstance(metadata, self.formatclass)
return self.generate(metadata,user) | python | def match(self, metadata, user = None):
"""Does the specified metadata match this template? returns (success,metadata,parameters)"""
assert isinstance(metadata, self.formatclass)
return self.generate(metadata,user) | [
"def",
"match",
"(",
"self",
",",
"metadata",
",",
"user",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"metadata",
",",
"self",
".",
"formatclass",
")",
"return",
"self",
".",
"generate",
"(",
"metadata",
",",
"user",
")"
] | Does the specified metadata match this template? returns (success,metadata,parameters) | [
"Does",
"the",
"specified",
"metadata",
"match",
"this",
"template?",
"returns",
"(",
"success",
"metadata",
"parameters",
")"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L1553-L1556 |
proycon/clam | clam/common/data.py | InputTemplate.matchingfiles | def matchingfiles(self, projectpath):
"""Checks if the input conditions are satisfied, i.e the required input files are present. We use the symbolic links .*.INPUTTEMPLATE.id.seqnr to determine this. Returns a list of matching results (seqnr, filename, inputtemplate)."""
results = []
if projectpath[-1] == '/':
inputpath = projectpath + 'input/'
else:
inputpath = projectpath + '/input/'
for linkf,realf in clam.common.util.globsymlinks(inputpath + '/.*.INPUTTEMPLATE.' + self.id + '.*'):
seqnr = int(linkf.split('.')[-1])
results.append( (seqnr, realf[len(inputpath):], self) )
results = sorted(results)
if self.unique and len(results) != 1:
return []
else:
return results | python | def matchingfiles(self, projectpath):
"""Checks if the input conditions are satisfied, i.e the required input files are present. We use the symbolic links .*.INPUTTEMPLATE.id.seqnr to determine this. Returns a list of matching results (seqnr, filename, inputtemplate)."""
results = []
if projectpath[-1] == '/':
inputpath = projectpath + 'input/'
else:
inputpath = projectpath + '/input/'
for linkf,realf in clam.common.util.globsymlinks(inputpath + '/.*.INPUTTEMPLATE.' + self.id + '.*'):
seqnr = int(linkf.split('.')[-1])
results.append( (seqnr, realf[len(inputpath):], self) )
results = sorted(results)
if self.unique and len(results) != 1:
return []
else:
return results | [
"def",
"matchingfiles",
"(",
"self",
",",
"projectpath",
")",
":",
"results",
"=",
"[",
"]",
"if",
"projectpath",
"[",
"-",
"1",
"]",
"==",
"'/'",
":",
"inputpath",
"=",
"projectpath",
"+",
"'input/'",
"else",
":",
"inputpath",
"=",
"projectpath",
"+",
"'/input/'",
"for",
"linkf",
",",
"realf",
"in",
"clam",
".",
"common",
".",
"util",
".",
"globsymlinks",
"(",
"inputpath",
"+",
"'/.*.INPUTTEMPLATE.'",
"+",
"self",
".",
"id",
"+",
"'.*'",
")",
":",
"seqnr",
"=",
"int",
"(",
"linkf",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
")",
"results",
".",
"append",
"(",
"(",
"seqnr",
",",
"realf",
"[",
"len",
"(",
"inputpath",
")",
":",
"]",
",",
"self",
")",
")",
"results",
"=",
"sorted",
"(",
"results",
")",
"if",
"self",
".",
"unique",
"and",
"len",
"(",
"results",
")",
"!=",
"1",
":",
"return",
"[",
"]",
"else",
":",
"return",
"results"
] | Checks if the input conditions are satisfied, i.e the required input files are present. We use the symbolic links .*.INPUTTEMPLATE.id.seqnr to determine this. Returns a list of matching results (seqnr, filename, inputtemplate). | [
"Checks",
"if",
"the",
"input",
"conditions",
"are",
"satisfied",
"i",
".",
"e",
"the",
"required",
"input",
"files",
"are",
"present",
".",
"We",
"use",
"the",
"symbolic",
"links",
".",
"*",
".",
"INPUTTEMPLATE",
".",
"id",
".",
"seqnr",
"to",
"determine",
"this",
".",
"Returns",
"a",
"list",
"of",
"matching",
"results",
"(",
"seqnr",
"filename",
"inputtemplate",
")",
"."
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L1558-L1574 |
proycon/clam | clam/common/data.py | InputTemplate.validate | def validate(self, postdata, user = None):
"""Validate posted data against the inputtemplate"""
clam.common.util.printdebug("Validating inputtemplate " + self.id + "...")
errors, parameters, _ = processparameters(postdata, self.parameters, user)
return errors, parameters | python | def validate(self, postdata, user = None):
"""Validate posted data against the inputtemplate"""
clam.common.util.printdebug("Validating inputtemplate " + self.id + "...")
errors, parameters, _ = processparameters(postdata, self.parameters, user)
return errors, parameters | [
"def",
"validate",
"(",
"self",
",",
"postdata",
",",
"user",
"=",
"None",
")",
":",
"clam",
".",
"common",
".",
"util",
".",
"printdebug",
"(",
"\"Validating inputtemplate \"",
"+",
"self",
".",
"id",
"+",
"\"...\"",
")",
"errors",
",",
"parameters",
",",
"_",
"=",
"processparameters",
"(",
"postdata",
",",
"self",
".",
"parameters",
",",
"user",
")",
"return",
"errors",
",",
"parameters"
] | Validate posted data against the inputtemplate | [
"Validate",
"posted",
"data",
"against",
"the",
"inputtemplate"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L1578-L1582 |
proycon/clam | clam/common/data.py | InputTemplate.generate | def generate(self, file, validatedata = None, inputdata=None, user = None):
"""Convert the template into instantiated metadata, validating the data in the process and returning errors otherwise. inputdata is a dictionary-compatible structure, such as the relevant postdata. Return (success, metadata, parameters), error messages can be extracted from parameters[].error. Validatedata is a (errors,parameters) tuple that can be passed if you did validation in a prior stage, if not specified, it will be done automatically."""
metadata = {}
if not validatedata:
assert inputdata
errors, parameters = self.validate(inputdata,user) #pylint: disable=unused-variable
else:
errors, parameters = validatedata #pylint: disable=unused-variable
#scan errors and set metadata
success = True
for parameter in parameters:
assert isinstance(parameter, clam.common.parameters.AbstractParameter)
if parameter.error:
success = False
else:
metadata[parameter.id] = parameter.value
if not success:
metadata = None
else:
try:
metadata = self.formatclass(file, **metadata)
except:
raise
return success, metadata, parameters | python | def generate(self, file, validatedata = None, inputdata=None, user = None):
"""Convert the template into instantiated metadata, validating the data in the process and returning errors otherwise. inputdata is a dictionary-compatible structure, such as the relevant postdata. Return (success, metadata, parameters), error messages can be extracted from parameters[].error. Validatedata is a (errors,parameters) tuple that can be passed if you did validation in a prior stage, if not specified, it will be done automatically."""
metadata = {}
if not validatedata:
assert inputdata
errors, parameters = self.validate(inputdata,user) #pylint: disable=unused-variable
else:
errors, parameters = validatedata #pylint: disable=unused-variable
#scan errors and set metadata
success = True
for parameter in parameters:
assert isinstance(parameter, clam.common.parameters.AbstractParameter)
if parameter.error:
success = False
else:
metadata[parameter.id] = parameter.value
if not success:
metadata = None
else:
try:
metadata = self.formatclass(file, **metadata)
except:
raise
return success, metadata, parameters | [
"def",
"generate",
"(",
"self",
",",
"file",
",",
"validatedata",
"=",
"None",
",",
"inputdata",
"=",
"None",
",",
"user",
"=",
"None",
")",
":",
"metadata",
"=",
"{",
"}",
"if",
"not",
"validatedata",
":",
"assert",
"inputdata",
"errors",
",",
"parameters",
"=",
"self",
".",
"validate",
"(",
"inputdata",
",",
"user",
")",
"#pylint: disable=unused-variable",
"else",
":",
"errors",
",",
"parameters",
"=",
"validatedata",
"#pylint: disable=unused-variable",
"#scan errors and set metadata",
"success",
"=",
"True",
"for",
"parameter",
"in",
"parameters",
":",
"assert",
"isinstance",
"(",
"parameter",
",",
"clam",
".",
"common",
".",
"parameters",
".",
"AbstractParameter",
")",
"if",
"parameter",
".",
"error",
":",
"success",
"=",
"False",
"else",
":",
"metadata",
"[",
"parameter",
".",
"id",
"]",
"=",
"parameter",
".",
"value",
"if",
"not",
"success",
":",
"metadata",
"=",
"None",
"else",
":",
"try",
":",
"metadata",
"=",
"self",
".",
"formatclass",
"(",
"file",
",",
"*",
"*",
"metadata",
")",
"except",
":",
"raise",
"return",
"success",
",",
"metadata",
",",
"parameters"
] | Convert the template into instantiated metadata, validating the data in the process and returning errors otherwise. inputdata is a dictionary-compatible structure, such as the relevant postdata. Return (success, metadata, parameters), error messages can be extracted from parameters[].error. Validatedata is a (errors,parameters) tuple that can be passed if you did validation in a prior stage, if not specified, it will be done automatically. | [
"Convert",
"the",
"template",
"into",
"instantiated",
"metadata",
"validating",
"the",
"data",
"in",
"the",
"process",
"and",
"returning",
"errors",
"otherwise",
".",
"inputdata",
"is",
"a",
"dictionary",
"-",
"compatible",
"structure",
"such",
"as",
"the",
"relevant",
"postdata",
".",
"Return",
"(",
"success",
"metadata",
"parameters",
")",
"error",
"messages",
"can",
"be",
"extracted",
"from",
"parameters",
"[]",
".",
"error",
".",
"Validatedata",
"is",
"a",
"(",
"errors",
"parameters",
")",
"tuple",
"that",
"can",
"be",
"passed",
"if",
"you",
"did",
"validation",
"in",
"a",
"prior",
"stage",
"if",
"not",
"specified",
"it",
"will",
"be",
"done",
"automatically",
"."
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L1587-L1615 |
proycon/clam | clam/common/data.py | AbstractMetaField.xml | def xml(self, operator='set', indent = ""):
"""Serialize the metadata field to XML"""
xml = indent + "<meta id=\"" + self.key + "\""
if operator != 'set':
xml += " operator=\"" + operator + "\""
if not self.value:
xml += " />"
else:
xml += ">" + self.value + "</meta>"
return xml | python | def xml(self, operator='set', indent = ""):
"""Serialize the metadata field to XML"""
xml = indent + "<meta id=\"" + self.key + "\""
if operator != 'set':
xml += " operator=\"" + operator + "\""
if not self.value:
xml += " />"
else:
xml += ">" + self.value + "</meta>"
return xml | [
"def",
"xml",
"(",
"self",
",",
"operator",
"=",
"'set'",
",",
"indent",
"=",
"\"\"",
")",
":",
"xml",
"=",
"indent",
"+",
"\"<meta id=\\\"\"",
"+",
"self",
".",
"key",
"+",
"\"\\\"\"",
"if",
"operator",
"!=",
"'set'",
":",
"xml",
"+=",
"\" operator=\\\"\"",
"+",
"operator",
"+",
"\"\\\"\"",
"if",
"not",
"self",
".",
"value",
":",
"xml",
"+=",
"\" />\"",
"else",
":",
"xml",
"+=",
"\">\"",
"+",
"self",
".",
"value",
"+",
"\"</meta>\"",
"return",
"xml"
] | Serialize the metadata field to XML | [
"Serialize",
"the",
"metadata",
"field",
"to",
"XML"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L1625-L1634 |
proycon/clam | clam/common/data.py | AbstractMetaField.fromxml | def fromxml(node):
"""Static method returning an MetaField instance (any subclass of AbstractMetaField) from the given XML description. Node can be a string or an etree._Element."""
if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access
node = parsexmlstring(node)
if node.tag.lower() != 'meta':
raise Exception("Expected meta tag but got '" + node.tag + "' instead")
key = node.attrib['id']
if node.text:
value = node.text
else:
value = None
operator = 'set'
if 'operator' in node.attrib:
operator= node.attrib['operator']
if operator == 'set':
cls = SetMetaField
elif operator == 'unset':
cls = UnsetMetaField
elif operator == 'copy':
cls = CopyMetaField
elif operator == 'parameter':
cls = ParameterMetaField
return cls(key, value) | python | def fromxml(node):
"""Static method returning an MetaField instance (any subclass of AbstractMetaField) from the given XML description. Node can be a string or an etree._Element."""
if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access
node = parsexmlstring(node)
if node.tag.lower() != 'meta':
raise Exception("Expected meta tag but got '" + node.tag + "' instead")
key = node.attrib['id']
if node.text:
value = node.text
else:
value = None
operator = 'set'
if 'operator' in node.attrib:
operator= node.attrib['operator']
if operator == 'set':
cls = SetMetaField
elif operator == 'unset':
cls = UnsetMetaField
elif operator == 'copy':
cls = CopyMetaField
elif operator == 'parameter':
cls = ParameterMetaField
return cls(key, value) | [
"def",
"fromxml",
"(",
"node",
")",
":",
"if",
"not",
"isinstance",
"(",
"node",
",",
"ElementTree",
".",
"_Element",
")",
":",
"#pylint: disable=protected-access",
"node",
"=",
"parsexmlstring",
"(",
"node",
")",
"if",
"node",
".",
"tag",
".",
"lower",
"(",
")",
"!=",
"'meta'",
":",
"raise",
"Exception",
"(",
"\"Expected meta tag but got '\"",
"+",
"node",
".",
"tag",
"+",
"\"' instead\"",
")",
"key",
"=",
"node",
".",
"attrib",
"[",
"'id'",
"]",
"if",
"node",
".",
"text",
":",
"value",
"=",
"node",
".",
"text",
"else",
":",
"value",
"=",
"None",
"operator",
"=",
"'set'",
"if",
"'operator'",
"in",
"node",
".",
"attrib",
":",
"operator",
"=",
"node",
".",
"attrib",
"[",
"'operator'",
"]",
"if",
"operator",
"==",
"'set'",
":",
"cls",
"=",
"SetMetaField",
"elif",
"operator",
"==",
"'unset'",
":",
"cls",
"=",
"UnsetMetaField",
"elif",
"operator",
"==",
"'copy'",
":",
"cls",
"=",
"CopyMetaField",
"elif",
"operator",
"==",
"'parameter'",
":",
"cls",
"=",
"ParameterMetaField",
"return",
"cls",
"(",
"key",
",",
"value",
")"
] | Static method returning an MetaField instance (any subclass of AbstractMetaField) from the given XML description. Node can be a string or an etree._Element. | [
"Static",
"method",
"returning",
"an",
"MetaField",
"instance",
"(",
"any",
"subclass",
"of",
"AbstractMetaField",
")",
"from",
"the",
"given",
"XML",
"description",
".",
"Node",
"can",
"be",
"a",
"string",
"or",
"an",
"etree",
".",
"_Element",
"."
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L1637-L1660 |
proycon/clam | clam/common/data.py | OutputTemplate.xml | def xml(self, indent = ""):
"""Produce Template XML"""
xml = indent + "<OutputTemplate id=\"" + self.id + "\" format=\"" + self.formatclass.__name__ + "\"" + " label=\"" + self.label + "\""
if self.formatclass.mimetype:
xml +=" mimetype=\""+self.formatclass.mimetype+"\""
if self.formatclass.schema:
xml +=" schema=\""+clam.common.util.xmlescape(self.formatclass.schema)+"\""
if self.filename:
xml +=" filename=\""+clam.common.util.xmlescape(self.filename)+"\""
if self.extension:
xml +=" extension=\""+clam.common.util.xmlescape(self.extension)+"\""
if self.parent:
xml +=" parent=\""+clam.common.util.xmlescape(self.parent)+"\""
if self.unique:
xml +=" unique=\"yes\""
else:
xml +=" unique=\"no\""
xml += ">\n"
for metafield in self.metafields:
xml += metafield.xml(indent + " ") + "\n"
xml += indent + "</OutputTemplate>"
return xml | python | def xml(self, indent = ""):
"""Produce Template XML"""
xml = indent + "<OutputTemplate id=\"" + self.id + "\" format=\"" + self.formatclass.__name__ + "\"" + " label=\"" + self.label + "\""
if self.formatclass.mimetype:
xml +=" mimetype=\""+self.formatclass.mimetype+"\""
if self.formatclass.schema:
xml +=" schema=\""+clam.common.util.xmlescape(self.formatclass.schema)+"\""
if self.filename:
xml +=" filename=\""+clam.common.util.xmlescape(self.filename)+"\""
if self.extension:
xml +=" extension=\""+clam.common.util.xmlescape(self.extension)+"\""
if self.parent:
xml +=" parent=\""+clam.common.util.xmlescape(self.parent)+"\""
if self.unique:
xml +=" unique=\"yes\""
else:
xml +=" unique=\"no\""
xml += ">\n"
for metafield in self.metafields:
xml += metafield.xml(indent + " ") + "\n"
xml += indent + "</OutputTemplate>"
return xml | [
"def",
"xml",
"(",
"self",
",",
"indent",
"=",
"\"\"",
")",
":",
"xml",
"=",
"indent",
"+",
"\"<OutputTemplate id=\\\"\"",
"+",
"self",
".",
"id",
"+",
"\"\\\" format=\\\"\"",
"+",
"self",
".",
"formatclass",
".",
"__name__",
"+",
"\"\\\"\"",
"+",
"\" label=\\\"\"",
"+",
"self",
".",
"label",
"+",
"\"\\\"\"",
"if",
"self",
".",
"formatclass",
".",
"mimetype",
":",
"xml",
"+=",
"\" mimetype=\\\"\"",
"+",
"self",
".",
"formatclass",
".",
"mimetype",
"+",
"\"\\\"\"",
"if",
"self",
".",
"formatclass",
".",
"schema",
":",
"xml",
"+=",
"\" schema=\\\"\"",
"+",
"clam",
".",
"common",
".",
"util",
".",
"xmlescape",
"(",
"self",
".",
"formatclass",
".",
"schema",
")",
"+",
"\"\\\"\"",
"if",
"self",
".",
"filename",
":",
"xml",
"+=",
"\" filename=\\\"\"",
"+",
"clam",
".",
"common",
".",
"util",
".",
"xmlescape",
"(",
"self",
".",
"filename",
")",
"+",
"\"\\\"\"",
"if",
"self",
".",
"extension",
":",
"xml",
"+=",
"\" extension=\\\"\"",
"+",
"clam",
".",
"common",
".",
"util",
".",
"xmlescape",
"(",
"self",
".",
"extension",
")",
"+",
"\"\\\"\"",
"if",
"self",
".",
"parent",
":",
"xml",
"+=",
"\" parent=\\\"\"",
"+",
"clam",
".",
"common",
".",
"util",
".",
"xmlescape",
"(",
"self",
".",
"parent",
")",
"+",
"\"\\\"\"",
"if",
"self",
".",
"unique",
":",
"xml",
"+=",
"\" unique=\\\"yes\\\"\"",
"else",
":",
"xml",
"+=",
"\" unique=\\\"no\\\"\"",
"xml",
"+=",
"\">\\n\"",
"for",
"metafield",
"in",
"self",
".",
"metafields",
":",
"xml",
"+=",
"metafield",
".",
"xml",
"(",
"indent",
"+",
"\" \"",
")",
"+",
"\"\\n\"",
"xml",
"+=",
"indent",
"+",
"\"</OutputTemplate>\"",
"return",
"xml"
] | Produce Template XML | [
"Produce",
"Template",
"XML"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L1800-L1822 |
proycon/clam | clam/common/data.py | OutputTemplate.fromxml | def fromxml(node):
"""Static method return an OutputTemplate instance from the given XML description. Node can be a string or an etree._Element."""
if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access
node = parsexmlstring(node)
assert node.tag.lower() == 'outputtemplate'
template_id = node.attrib['id']
dataformat = node.attrib['format']
label = node.attrib['label']
kwargs = {}
if 'filename' in node.attrib:
kwargs['filename'] = node.attrib['filename']
if 'extension' in node.attrib:
kwargs['extension'] = node.attrib['extension']
if 'unique' in node.attrib:
kwargs['unique'] = node.attrib['unique'].lower() == 'yes' or node.attrib['unique'].lower() == 'true' or node.attrib['unique'].lower() == '1'
if 'parent' in node.attrib:
kwargs['parent'] = node.attrib['parent']
#find formatclass
formatcls = None
for C in CUSTOM_FORMATS: #CUSTOM_FORMATS will be injected by clamservice.py
if C.__name__ == dataformat:
formatcls = C
break
if formatcls is None:
if dataformat in vars(clam.common.formats):
formatcls = vars(clam.common.formats)[dataformat]
else:
raise Exception("Specified format not defined! (" + dataformat + ")")
args = []
for subnode in node:
if subnode.tag == 'parametercondition':
args.append(ParameterCondition.fromxml(subnode))
elif subnode.tag == 'converter':
pass #MAYBE TODO: Reading converters from XML is not implemented (and not necessary at this stage)
elif subnode.tag == 'viewer':
pass #MAYBE TODO: Reading viewers from XML is not implemented (and not necessary at this stage)
else:
args.append(AbstractMetaField.fromxml(subnode))
return OutputTemplate(template_id,formatcls,label, *args, **kwargs) | python | def fromxml(node):
"""Static method return an OutputTemplate instance from the given XML description. Node can be a string or an etree._Element."""
if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access
node = parsexmlstring(node)
assert node.tag.lower() == 'outputtemplate'
template_id = node.attrib['id']
dataformat = node.attrib['format']
label = node.attrib['label']
kwargs = {}
if 'filename' in node.attrib:
kwargs['filename'] = node.attrib['filename']
if 'extension' in node.attrib:
kwargs['extension'] = node.attrib['extension']
if 'unique' in node.attrib:
kwargs['unique'] = node.attrib['unique'].lower() == 'yes' or node.attrib['unique'].lower() == 'true' or node.attrib['unique'].lower() == '1'
if 'parent' in node.attrib:
kwargs['parent'] = node.attrib['parent']
#find formatclass
formatcls = None
for C in CUSTOM_FORMATS: #CUSTOM_FORMATS will be injected by clamservice.py
if C.__name__ == dataformat:
formatcls = C
break
if formatcls is None:
if dataformat in vars(clam.common.formats):
formatcls = vars(clam.common.formats)[dataformat]
else:
raise Exception("Specified format not defined! (" + dataformat + ")")
args = []
for subnode in node:
if subnode.tag == 'parametercondition':
args.append(ParameterCondition.fromxml(subnode))
elif subnode.tag == 'converter':
pass #MAYBE TODO: Reading converters from XML is not implemented (and not necessary at this stage)
elif subnode.tag == 'viewer':
pass #MAYBE TODO: Reading viewers from XML is not implemented (and not necessary at this stage)
else:
args.append(AbstractMetaField.fromxml(subnode))
return OutputTemplate(template_id,formatcls,label, *args, **kwargs) | [
"def",
"fromxml",
"(",
"node",
")",
":",
"if",
"not",
"isinstance",
"(",
"node",
",",
"ElementTree",
".",
"_Element",
")",
":",
"#pylint: disable=protected-access",
"node",
"=",
"parsexmlstring",
"(",
"node",
")",
"assert",
"node",
".",
"tag",
".",
"lower",
"(",
")",
"==",
"'outputtemplate'",
"template_id",
"=",
"node",
".",
"attrib",
"[",
"'id'",
"]",
"dataformat",
"=",
"node",
".",
"attrib",
"[",
"'format'",
"]",
"label",
"=",
"node",
".",
"attrib",
"[",
"'label'",
"]",
"kwargs",
"=",
"{",
"}",
"if",
"'filename'",
"in",
"node",
".",
"attrib",
":",
"kwargs",
"[",
"'filename'",
"]",
"=",
"node",
".",
"attrib",
"[",
"'filename'",
"]",
"if",
"'extension'",
"in",
"node",
".",
"attrib",
":",
"kwargs",
"[",
"'extension'",
"]",
"=",
"node",
".",
"attrib",
"[",
"'extension'",
"]",
"if",
"'unique'",
"in",
"node",
".",
"attrib",
":",
"kwargs",
"[",
"'unique'",
"]",
"=",
"node",
".",
"attrib",
"[",
"'unique'",
"]",
".",
"lower",
"(",
")",
"==",
"'yes'",
"or",
"node",
".",
"attrib",
"[",
"'unique'",
"]",
".",
"lower",
"(",
")",
"==",
"'true'",
"or",
"node",
".",
"attrib",
"[",
"'unique'",
"]",
".",
"lower",
"(",
")",
"==",
"'1'",
"if",
"'parent'",
"in",
"node",
".",
"attrib",
":",
"kwargs",
"[",
"'parent'",
"]",
"=",
"node",
".",
"attrib",
"[",
"'parent'",
"]",
"#find formatclass",
"formatcls",
"=",
"None",
"for",
"C",
"in",
"CUSTOM_FORMATS",
":",
"#CUSTOM_FORMATS will be injected by clamservice.py",
"if",
"C",
".",
"__name__",
"==",
"dataformat",
":",
"formatcls",
"=",
"C",
"break",
"if",
"formatcls",
"is",
"None",
":",
"if",
"dataformat",
"in",
"vars",
"(",
"clam",
".",
"common",
".",
"formats",
")",
":",
"formatcls",
"=",
"vars",
"(",
"clam",
".",
"common",
".",
"formats",
")",
"[",
"dataformat",
"]",
"else",
":",
"raise",
"Exception",
"(",
"\"Specified format not defined! (\"",
"+",
"dataformat",
"+",
"\")\"",
")",
"args",
"=",
"[",
"]",
"for",
"subnode",
"in",
"node",
":",
"if",
"subnode",
".",
"tag",
"==",
"'parametercondition'",
":",
"args",
".",
"append",
"(",
"ParameterCondition",
".",
"fromxml",
"(",
"subnode",
")",
")",
"elif",
"subnode",
".",
"tag",
"==",
"'converter'",
":",
"pass",
"#MAYBE TODO: Reading converters from XML is not implemented (and not necessary at this stage)",
"elif",
"subnode",
".",
"tag",
"==",
"'viewer'",
":",
"pass",
"#MAYBE TODO: Reading viewers from XML is not implemented (and not necessary at this stage)",
"else",
":",
"args",
".",
"append",
"(",
"AbstractMetaField",
".",
"fromxml",
"(",
"subnode",
")",
")",
"return",
"OutputTemplate",
"(",
"template_id",
",",
"formatcls",
",",
"label",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Static method return an OutputTemplate instance from the given XML description. Node can be a string or an etree._Element. | [
"Static",
"method",
"return",
"an",
"OutputTemplate",
"instance",
"from",
"the",
"given",
"XML",
"description",
".",
"Node",
"can",
"be",
"a",
"string",
"or",
"an",
"etree",
".",
"_Element",
"."
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L1825-L1867 |
proycon/clam | clam/common/data.py | OutputTemplate.findparent | def findparent(self, inputtemplates):
"""Find the most suitable parent, that is: the first matching unique/multi inputtemplate"""
for inputtemplate in inputtemplates:
if self.unique == inputtemplate.unique:
return inputtemplate.id
return None | python | def findparent(self, inputtemplates):
"""Find the most suitable parent, that is: the first matching unique/multi inputtemplate"""
for inputtemplate in inputtemplates:
if self.unique == inputtemplate.unique:
return inputtemplate.id
return None | [
"def",
"findparent",
"(",
"self",
",",
"inputtemplates",
")",
":",
"for",
"inputtemplate",
"in",
"inputtemplates",
":",
"if",
"self",
".",
"unique",
"==",
"inputtemplate",
".",
"unique",
":",
"return",
"inputtemplate",
".",
"id",
"return",
"None"
] | Find the most suitable parent, that is: the first matching unique/multi inputtemplate | [
"Find",
"the",
"most",
"suitable",
"parent",
"that",
"is",
":",
"the",
"first",
"matching",
"unique",
"/",
"multi",
"inputtemplate"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L1874-L1879 |
proycon/clam | clam/common/data.py | OutputTemplate.getparent | def getparent(self, profile):
"""Resolve a parent ID"""
assert self.parent
for inputtemplate in profile.input:
if inputtemplate == self.parent:
return inputtemplate
raise Exception("Parent InputTemplate '"+self.parent+"' not found!") | python | def getparent(self, profile):
"""Resolve a parent ID"""
assert self.parent
for inputtemplate in profile.input:
if inputtemplate == self.parent:
return inputtemplate
raise Exception("Parent InputTemplate '"+self.parent+"' not found!") | [
"def",
"getparent",
"(",
"self",
",",
"profile",
")",
":",
"assert",
"self",
".",
"parent",
"for",
"inputtemplate",
"in",
"profile",
".",
"input",
":",
"if",
"inputtemplate",
"==",
"self",
".",
"parent",
":",
"return",
"inputtemplate",
"raise",
"Exception",
"(",
"\"Parent InputTemplate '\"",
"+",
"self",
".",
"parent",
"+",
"\"' not found!\"",
")"
] | Resolve a parent ID | [
"Resolve",
"a",
"parent",
"ID"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L1881-L1887 |
proycon/clam | clam/common/data.py | OutputTemplate.generate | def generate(self, profile, parameters, projectpath, inputfiles, provenancedata=None):
"""Yields (inputtemplate, inputfilename, outputfilename, metadata) tuples"""
project = os.path.basename(projectpath)
if self.parent: #pylint: disable=too-many-nested-blocks
#We have a parent, infer the correct filename
#copy filename from parent
parent = self.getparent(profile)
#get input files for the parent InputTemplate
parentinputfiles = parent.matchingfiles(projectpath)
if not parentinputfiles:
raise Exception("OutputTemplate '"+self.id + "' has parent '" + self.parent + "', but no matching input files were found!")
#Do we specify a full filename?
for seqnr, inputfilename, inputtemplate in parentinputfiles: #pylint: disable=unused-variable
if self.filename:
filename = self.filename
parentfile = CLAMInputFile(projectpath, inputfilename)
elif parent:
filename = inputfilename
parentfile = CLAMInputFile(projectpath, inputfilename)
else:
raise Exception("OutputTemplate '"+self.id + "' has no parent nor filename defined!")
#Make actual CLAMInputFile objects of ALL relevant input files, that is: all unique=True files and all unique=False files with the same sequence number
relevantinputfiles = []
for seqnr2, inputfilename2, inputtemplate2 in inputfiles:
if seqnr2 == 0 or seqnr2 == seqnr:
relevantinputfiles.append( (inputtemplate2, CLAMInputFile(projectpath, inputfilename2)) )
#resolve # in filename (done later)
#if not self.unique:
# filename.replace('#',str(seqnr))
if not self.filename and self.removeextensions:
#Remove unwanted extensions
if self.removeextensions is True:
#Remove any and all extensions
filename = filename.split('.')[0]
elif isinstance(self.removeextensions, list):
#Remove specified extension
for ext in self.removeextensions:
if ext:
if ext[0] != '.' and filename[-len(ext) - 1:] == '.' + ext:
filename = filename[:-len(ext) - 1]
elif ext[0] == '.' and filename[-len(ext):] == ext:
filename = filename[:-len(ext)]
if self.extension and not self.filename and filename[-len(self.extension) - 1:] != '.' + self.extension: #(also prevents duplicate extensions)
filename += '.' + self.extension
#Now we create the actual metadata
metadata = self.generatemetadata(parameters, parentfile, relevantinputfiles, provenancedata)
#Resolve filename
filename = resolveoutputfilename(filename, parameters, metadata, self, seqnr, project, inputfilename)
yield inputtemplate, inputfilename, filename, metadata
elif self.unique and self.filename:
#outputtemplate has no parent, but specified a filename and is unique, this implies it is not dependent on input files:
metadata = self.generatemetadata(parameters, None, [], provenancedata)
filename = resolveoutputfilename(self.filename, parameters, metadata, self, 0, project, None)
yield None, None, filename, metadata
else:
raise Exception("Unable to generate from OutputTemplate, no parent or filename specified") | python | def generate(self, profile, parameters, projectpath, inputfiles, provenancedata=None):
"""Yields (inputtemplate, inputfilename, outputfilename, metadata) tuples"""
project = os.path.basename(projectpath)
if self.parent: #pylint: disable=too-many-nested-blocks
#We have a parent, infer the correct filename
#copy filename from parent
parent = self.getparent(profile)
#get input files for the parent InputTemplate
parentinputfiles = parent.matchingfiles(projectpath)
if not parentinputfiles:
raise Exception("OutputTemplate '"+self.id + "' has parent '" + self.parent + "', but no matching input files were found!")
#Do we specify a full filename?
for seqnr, inputfilename, inputtemplate in parentinputfiles: #pylint: disable=unused-variable
if self.filename:
filename = self.filename
parentfile = CLAMInputFile(projectpath, inputfilename)
elif parent:
filename = inputfilename
parentfile = CLAMInputFile(projectpath, inputfilename)
else:
raise Exception("OutputTemplate '"+self.id + "' has no parent nor filename defined!")
#Make actual CLAMInputFile objects of ALL relevant input files, that is: all unique=True files and all unique=False files with the same sequence number
relevantinputfiles = []
for seqnr2, inputfilename2, inputtemplate2 in inputfiles:
if seqnr2 == 0 or seqnr2 == seqnr:
relevantinputfiles.append( (inputtemplate2, CLAMInputFile(projectpath, inputfilename2)) )
#resolve # in filename (done later)
#if not self.unique:
# filename.replace('#',str(seqnr))
if not self.filename and self.removeextensions:
#Remove unwanted extensions
if self.removeextensions is True:
#Remove any and all extensions
filename = filename.split('.')[0]
elif isinstance(self.removeextensions, list):
#Remove specified extension
for ext in self.removeextensions:
if ext:
if ext[0] != '.' and filename[-len(ext) - 1:] == '.' + ext:
filename = filename[:-len(ext) - 1]
elif ext[0] == '.' and filename[-len(ext):] == ext:
filename = filename[:-len(ext)]
if self.extension and not self.filename and filename[-len(self.extension) - 1:] != '.' + self.extension: #(also prevents duplicate extensions)
filename += '.' + self.extension
#Now we create the actual metadata
metadata = self.generatemetadata(parameters, parentfile, relevantinputfiles, provenancedata)
#Resolve filename
filename = resolveoutputfilename(filename, parameters, metadata, self, seqnr, project, inputfilename)
yield inputtemplate, inputfilename, filename, metadata
elif self.unique and self.filename:
#outputtemplate has no parent, but specified a filename and is unique, this implies it is not dependent on input files:
metadata = self.generatemetadata(parameters, None, [], provenancedata)
filename = resolveoutputfilename(self.filename, parameters, metadata, self, 0, project, None)
yield None, None, filename, metadata
else:
raise Exception("Unable to generate from OutputTemplate, no parent or filename specified") | [
"def",
"generate",
"(",
"self",
",",
"profile",
",",
"parameters",
",",
"projectpath",
",",
"inputfiles",
",",
"provenancedata",
"=",
"None",
")",
":",
"project",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"projectpath",
")",
"if",
"self",
".",
"parent",
":",
"#pylint: disable=too-many-nested-blocks",
"#We have a parent, infer the correct filename",
"#copy filename from parent",
"parent",
"=",
"self",
".",
"getparent",
"(",
"profile",
")",
"#get input files for the parent InputTemplate",
"parentinputfiles",
"=",
"parent",
".",
"matchingfiles",
"(",
"projectpath",
")",
"if",
"not",
"parentinputfiles",
":",
"raise",
"Exception",
"(",
"\"OutputTemplate '\"",
"+",
"self",
".",
"id",
"+",
"\"' has parent '\"",
"+",
"self",
".",
"parent",
"+",
"\"', but no matching input files were found!\"",
")",
"#Do we specify a full filename?",
"for",
"seqnr",
",",
"inputfilename",
",",
"inputtemplate",
"in",
"parentinputfiles",
":",
"#pylint: disable=unused-variable",
"if",
"self",
".",
"filename",
":",
"filename",
"=",
"self",
".",
"filename",
"parentfile",
"=",
"CLAMInputFile",
"(",
"projectpath",
",",
"inputfilename",
")",
"elif",
"parent",
":",
"filename",
"=",
"inputfilename",
"parentfile",
"=",
"CLAMInputFile",
"(",
"projectpath",
",",
"inputfilename",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"OutputTemplate '\"",
"+",
"self",
".",
"id",
"+",
"\"' has no parent nor filename defined!\"",
")",
"#Make actual CLAMInputFile objects of ALL relevant input files, that is: all unique=True files and all unique=False files with the same sequence number",
"relevantinputfiles",
"=",
"[",
"]",
"for",
"seqnr2",
",",
"inputfilename2",
",",
"inputtemplate2",
"in",
"inputfiles",
":",
"if",
"seqnr2",
"==",
"0",
"or",
"seqnr2",
"==",
"seqnr",
":",
"relevantinputfiles",
".",
"append",
"(",
"(",
"inputtemplate2",
",",
"CLAMInputFile",
"(",
"projectpath",
",",
"inputfilename2",
")",
")",
")",
"#resolve # in filename (done later)",
"#if not self.unique:",
"# filename.replace('#',str(seqnr))",
"if",
"not",
"self",
".",
"filename",
"and",
"self",
".",
"removeextensions",
":",
"#Remove unwanted extensions",
"if",
"self",
".",
"removeextensions",
"is",
"True",
":",
"#Remove any and all extensions",
"filename",
"=",
"filename",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"elif",
"isinstance",
"(",
"self",
".",
"removeextensions",
",",
"list",
")",
":",
"#Remove specified extension",
"for",
"ext",
"in",
"self",
".",
"removeextensions",
":",
"if",
"ext",
":",
"if",
"ext",
"[",
"0",
"]",
"!=",
"'.'",
"and",
"filename",
"[",
"-",
"len",
"(",
"ext",
")",
"-",
"1",
":",
"]",
"==",
"'.'",
"+",
"ext",
":",
"filename",
"=",
"filename",
"[",
":",
"-",
"len",
"(",
"ext",
")",
"-",
"1",
"]",
"elif",
"ext",
"[",
"0",
"]",
"==",
"'.'",
"and",
"filename",
"[",
"-",
"len",
"(",
"ext",
")",
":",
"]",
"==",
"ext",
":",
"filename",
"=",
"filename",
"[",
":",
"-",
"len",
"(",
"ext",
")",
"]",
"if",
"self",
".",
"extension",
"and",
"not",
"self",
".",
"filename",
"and",
"filename",
"[",
"-",
"len",
"(",
"self",
".",
"extension",
")",
"-",
"1",
":",
"]",
"!=",
"'.'",
"+",
"self",
".",
"extension",
":",
"#(also prevents duplicate extensions)",
"filename",
"+=",
"'.'",
"+",
"self",
".",
"extension",
"#Now we create the actual metadata",
"metadata",
"=",
"self",
".",
"generatemetadata",
"(",
"parameters",
",",
"parentfile",
",",
"relevantinputfiles",
",",
"provenancedata",
")",
"#Resolve filename",
"filename",
"=",
"resolveoutputfilename",
"(",
"filename",
",",
"parameters",
",",
"metadata",
",",
"self",
",",
"seqnr",
",",
"project",
",",
"inputfilename",
")",
"yield",
"inputtemplate",
",",
"inputfilename",
",",
"filename",
",",
"metadata",
"elif",
"self",
".",
"unique",
"and",
"self",
".",
"filename",
":",
"#outputtemplate has no parent, but specified a filename and is unique, this implies it is not dependent on input files:",
"metadata",
"=",
"self",
".",
"generatemetadata",
"(",
"parameters",
",",
"None",
",",
"[",
"]",
",",
"provenancedata",
")",
"filename",
"=",
"resolveoutputfilename",
"(",
"self",
".",
"filename",
",",
"parameters",
",",
"metadata",
",",
"self",
",",
"0",
",",
"project",
",",
"None",
")",
"yield",
"None",
",",
"None",
",",
"filename",
",",
"metadata",
"else",
":",
"raise",
"Exception",
"(",
"\"Unable to generate from OutputTemplate, no parent or filename specified\"",
")"
] | Yields (inputtemplate, inputfilename, outputfilename, metadata) tuples | [
"Yields",
"(",
"inputtemplate",
"inputfilename",
"outputfilename",
"metadata",
")",
"tuples"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L1889-L1963 |
proycon/clam | clam/common/data.py | OutputTemplate.generatemetadata | def generatemetadata(self, parameters, parentfile, relevantinputfiles, provenancedata = None):
"""Generate metadata, given a filename, parameters and a dictionary of inputdata (necessary in case we copy from it)"""
assert isinstance(provenancedata,CLAMProvenanceData) or provenancedata is None
data = {}
if self.copymetadata:
#Copy parent metadata
for key, value in parentfile.metadata.items():
data[key] = value
for metafield in self.metafields:
if isinstance(metafield, ParameterCondition):
metafield = metafield.evaluate(parameters)
if not metafield:
continue
assert isinstance(metafield, AbstractMetaField)
metafield.resolve(data, parameters, parentfile, relevantinputfiles)
if provenancedata:
data['provenance'] = provenancedata
return self.formatclass(None, **data) | python | def generatemetadata(self, parameters, parentfile, relevantinputfiles, provenancedata = None):
"""Generate metadata, given a filename, parameters and a dictionary of inputdata (necessary in case we copy from it)"""
assert isinstance(provenancedata,CLAMProvenanceData) or provenancedata is None
data = {}
if self.copymetadata:
#Copy parent metadata
for key, value in parentfile.metadata.items():
data[key] = value
for metafield in self.metafields:
if isinstance(metafield, ParameterCondition):
metafield = metafield.evaluate(parameters)
if not metafield:
continue
assert isinstance(metafield, AbstractMetaField)
metafield.resolve(data, parameters, parentfile, relevantinputfiles)
if provenancedata:
data['provenance'] = provenancedata
return self.formatclass(None, **data) | [
"def",
"generatemetadata",
"(",
"self",
",",
"parameters",
",",
"parentfile",
",",
"relevantinputfiles",
",",
"provenancedata",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"provenancedata",
",",
"CLAMProvenanceData",
")",
"or",
"provenancedata",
"is",
"None",
"data",
"=",
"{",
"}",
"if",
"self",
".",
"copymetadata",
":",
"#Copy parent metadata",
"for",
"key",
",",
"value",
"in",
"parentfile",
".",
"metadata",
".",
"items",
"(",
")",
":",
"data",
"[",
"key",
"]",
"=",
"value",
"for",
"metafield",
"in",
"self",
".",
"metafields",
":",
"if",
"isinstance",
"(",
"metafield",
",",
"ParameterCondition",
")",
":",
"metafield",
"=",
"metafield",
".",
"evaluate",
"(",
"parameters",
")",
"if",
"not",
"metafield",
":",
"continue",
"assert",
"isinstance",
"(",
"metafield",
",",
"AbstractMetaField",
")",
"metafield",
".",
"resolve",
"(",
"data",
",",
"parameters",
",",
"parentfile",
",",
"relevantinputfiles",
")",
"if",
"provenancedata",
":",
"data",
"[",
"'provenance'",
"]",
"=",
"provenancedata",
"return",
"self",
".",
"formatclass",
"(",
"None",
",",
"*",
"*",
"data",
")"
] | Generate metadata, given a filename, parameters and a dictionary of inputdata (necessary in case we copy from it) | [
"Generate",
"metadata",
"given",
"a",
"filename",
"parameters",
"and",
"a",
"dictionary",
"of",
"inputdata",
"(",
"necessary",
"in",
"case",
"we",
"copy",
"from",
"it",
")"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L1966-L1988 |
proycon/clam | clam/common/data.py | ParameterCondition.allpossibilities | def allpossibilities(self):
"""Returns all possible outputtemplates that may occur (recusrively applied)"""
l = []
if isinstance(self.then, ParameterCondition):
#recursive parametercondition
l += self.then.allpossibilities()
elif self.then:
l.append(self.then)
if self.otherwise:
if isinstance(self.otherwise, ParameterCondition):
l += self.otherwise.allpossibilities()
else:
l.append(self.otherwise)
return l | python | def allpossibilities(self):
"""Returns all possible outputtemplates that may occur (recusrively applied)"""
l = []
if isinstance(self.then, ParameterCondition):
#recursive parametercondition
l += self.then.allpossibilities()
elif self.then:
l.append(self.then)
if self.otherwise:
if isinstance(self.otherwise, ParameterCondition):
l += self.otherwise.allpossibilities()
else:
l.append(self.otherwise)
return l | [
"def",
"allpossibilities",
"(",
"self",
")",
":",
"l",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"self",
".",
"then",
",",
"ParameterCondition",
")",
":",
"#recursive parametercondition",
"l",
"+=",
"self",
".",
"then",
".",
"allpossibilities",
"(",
")",
"elif",
"self",
".",
"then",
":",
"l",
".",
"append",
"(",
"self",
".",
"then",
")",
"if",
"self",
".",
"otherwise",
":",
"if",
"isinstance",
"(",
"self",
".",
"otherwise",
",",
"ParameterCondition",
")",
":",
"l",
"+=",
"self",
".",
"otherwise",
".",
"allpossibilities",
"(",
")",
"else",
":",
"l",
".",
"append",
"(",
"self",
".",
"otherwise",
")",
"return",
"l"
] | Returns all possible outputtemplates that may occur (recusrively applied) | [
"Returns",
"all",
"possible",
"outputtemplates",
"that",
"may",
"occur",
"(",
"recusrively",
"applied",
")"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L2064-L2077 |
proycon/clam | clam/common/data.py | ParameterCondition.evaluate | def evaluate(self, parameters):
"""Returns False if there's no match, or whatever the ParameterCondition evaluates to (recursively applied!)"""
if self.match(parameters):
if isinstance(self.then, ParameterCondition):
#recursive parametercondition
return self.then.evaluate(parameters)
else:
return self.then
elif self.otherwise:
if isinstance(self.otherwise, ParameterCondition):
#recursive else
return self.otherwise.evaluate(parameters)
else:
return self.otherwise
return False | python | def evaluate(self, parameters):
"""Returns False if there's no match, or whatever the ParameterCondition evaluates to (recursively applied!)"""
if self.match(parameters):
if isinstance(self.then, ParameterCondition):
#recursive parametercondition
return self.then.evaluate(parameters)
else:
return self.then
elif self.otherwise:
if isinstance(self.otherwise, ParameterCondition):
#recursive else
return self.otherwise.evaluate(parameters)
else:
return self.otherwise
return False | [
"def",
"evaluate",
"(",
"self",
",",
"parameters",
")",
":",
"if",
"self",
".",
"match",
"(",
"parameters",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"then",
",",
"ParameterCondition",
")",
":",
"#recursive parametercondition",
"return",
"self",
".",
"then",
".",
"evaluate",
"(",
"parameters",
")",
"else",
":",
"return",
"self",
".",
"then",
"elif",
"self",
".",
"otherwise",
":",
"if",
"isinstance",
"(",
"self",
".",
"otherwise",
",",
"ParameterCondition",
")",
":",
"#recursive else",
"return",
"self",
".",
"otherwise",
".",
"evaluate",
"(",
"parameters",
")",
"else",
":",
"return",
"self",
".",
"otherwise",
"return",
"False"
] | Returns False if there's no match, or whatever the ParameterCondition evaluates to (recursively applied!) | [
"Returns",
"False",
"if",
"there",
"s",
"no",
"match",
"or",
"whatever",
"the",
"ParameterCondition",
"evaluates",
"to",
"(",
"recursively",
"applied!",
")"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L2079-L2093 |
proycon/clam | clam/common/data.py | ParameterCondition.fromxml | def fromxml(node):
"""Static method returning a ParameterCondition instance from the given XML description. Node can be a string or an etree._Element."""
if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access
node = parsexmlstring(node)
assert node.tag.lower() == 'parametercondition'
kwargs = {}
found = False
for node in node:
if node.tag == 'if':
#interpret conditions:
for subnode in node:
operator = subnode.tag
parameter = subnode.attrib['parameter']
value = subnode.text
kwargs[parameter + '_' + operator] = value
found = True
elif node.tag == 'then' or node.tag == 'else' or node.tag == 'otherwise':
#interpret statements:
for subnode in node: #MAYBE TODO LATER: Support for multiple statement in then=, else= ?
if subnode.tag.lower() == 'parametercondition':
kwargs[node.tag] = ParameterCondition.fromxml(subnode)
elif subnode.tag == 'meta':
#assume metafield?
kwargs[node.tag] = AbstractMetaField.fromxml(subnode)
elif subnode.tag.lower() == 'outputtemplate':
kwargs[node.tag] = OutputTemplate.fromxml(subnode)
if not found:
raise Exception("No condition found in ParameterCondition!")
return ParameterCondition(**kwargs) | python | def fromxml(node):
"""Static method returning a ParameterCondition instance from the given XML description. Node can be a string or an etree._Element."""
if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access
node = parsexmlstring(node)
assert node.tag.lower() == 'parametercondition'
kwargs = {}
found = False
for node in node:
if node.tag == 'if':
#interpret conditions:
for subnode in node:
operator = subnode.tag
parameter = subnode.attrib['parameter']
value = subnode.text
kwargs[parameter + '_' + operator] = value
found = True
elif node.tag == 'then' or node.tag == 'else' or node.tag == 'otherwise':
#interpret statements:
for subnode in node: #MAYBE TODO LATER: Support for multiple statement in then=, else= ?
if subnode.tag.lower() == 'parametercondition':
kwargs[node.tag] = ParameterCondition.fromxml(subnode)
elif subnode.tag == 'meta':
#assume metafield?
kwargs[node.tag] = AbstractMetaField.fromxml(subnode)
elif subnode.tag.lower() == 'outputtemplate':
kwargs[node.tag] = OutputTemplate.fromxml(subnode)
if not found:
raise Exception("No condition found in ParameterCondition!")
return ParameterCondition(**kwargs) | [
"def",
"fromxml",
"(",
"node",
")",
":",
"if",
"not",
"isinstance",
"(",
"node",
",",
"ElementTree",
".",
"_Element",
")",
":",
"#pylint: disable=protected-access",
"node",
"=",
"parsexmlstring",
"(",
"node",
")",
"assert",
"node",
".",
"tag",
".",
"lower",
"(",
")",
"==",
"'parametercondition'",
"kwargs",
"=",
"{",
"}",
"found",
"=",
"False",
"for",
"node",
"in",
"node",
":",
"if",
"node",
".",
"tag",
"==",
"'if'",
":",
"#interpret conditions:",
"for",
"subnode",
"in",
"node",
":",
"operator",
"=",
"subnode",
".",
"tag",
"parameter",
"=",
"subnode",
".",
"attrib",
"[",
"'parameter'",
"]",
"value",
"=",
"subnode",
".",
"text",
"kwargs",
"[",
"parameter",
"+",
"'_'",
"+",
"operator",
"]",
"=",
"value",
"found",
"=",
"True",
"elif",
"node",
".",
"tag",
"==",
"'then'",
"or",
"node",
".",
"tag",
"==",
"'else'",
"or",
"node",
".",
"tag",
"==",
"'otherwise'",
":",
"#interpret statements:",
"for",
"subnode",
"in",
"node",
":",
"#MAYBE TODO LATER: Support for multiple statement in then=, else= ?",
"if",
"subnode",
".",
"tag",
".",
"lower",
"(",
")",
"==",
"'parametercondition'",
":",
"kwargs",
"[",
"node",
".",
"tag",
"]",
"=",
"ParameterCondition",
".",
"fromxml",
"(",
"subnode",
")",
"elif",
"subnode",
".",
"tag",
"==",
"'meta'",
":",
"#assume metafield?",
"kwargs",
"[",
"node",
".",
"tag",
"]",
"=",
"AbstractMetaField",
".",
"fromxml",
"(",
"subnode",
")",
"elif",
"subnode",
".",
"tag",
".",
"lower",
"(",
")",
"==",
"'outputtemplate'",
":",
"kwargs",
"[",
"node",
".",
"tag",
"]",
"=",
"OutputTemplate",
".",
"fromxml",
"(",
"subnode",
")",
"if",
"not",
"found",
":",
"raise",
"Exception",
"(",
"\"No condition found in ParameterCondition!\"",
")",
"return",
"ParameterCondition",
"(",
"*",
"*",
"kwargs",
")"
] | Static method returning a ParameterCondition instance from the given XML description. Node can be a string or an etree._Element. | [
"Static",
"method",
"returning",
"a",
"ParameterCondition",
"instance",
"from",
"the",
"given",
"XML",
"description",
".",
"Node",
"can",
"be",
"a",
"string",
"or",
"an",
"etree",
".",
"_Element",
"."
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L2110-L2140 |
proycon/clam | clam/common/data.py | Action.fromxml | def fromxml(node):
"""Static method returning an Action instance from the given XML description. Node can be a string or an etree._Element."""
if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access
node = parsexmlstring(node)
assert node.tag.lower() == 'action'
kwargs = {}
args = []
if 'id' in node.attrib:
kwargs['id'] = node.attrib['id']
elif 'name' in node.attrib:
kwargs['name'] = node.attrib['name']
elif 'description' in node.attrib:
kwargs['description'] = node.attrib['description']
elif 'method' in node.attrib:
kwargs['method'] = node.attrib['method']
elif 'mimetype' in node.attrib:
kwargs['mimetype'] = node.attrib['mimetype']
elif 'allowanonymous' in node.attrib:
if node.attrib['allowanonymous'] == "yes":
kwargs['allowanonymous'] = True
found = False
for subnode in node:
if subnode.tag.lower() == 'parametercondition':
kwargs[node.tag] = ParameterCondition.fromxml(subnode)
elif subnode.tag in vars(clam.common.parameters):
args.append(vars(clam.common.parameters)[subnode.tag].fromxml(subnode))
if not found:
raise Exception("No condition found in ParameterCondition!")
return Action(*args, **kwargs) | python | def fromxml(node):
"""Static method returning an Action instance from the given XML description. Node can be a string or an etree._Element."""
if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access
node = parsexmlstring(node)
assert node.tag.lower() == 'action'
kwargs = {}
args = []
if 'id' in node.attrib:
kwargs['id'] = node.attrib['id']
elif 'name' in node.attrib:
kwargs['name'] = node.attrib['name']
elif 'description' in node.attrib:
kwargs['description'] = node.attrib['description']
elif 'method' in node.attrib:
kwargs['method'] = node.attrib['method']
elif 'mimetype' in node.attrib:
kwargs['mimetype'] = node.attrib['mimetype']
elif 'allowanonymous' in node.attrib:
if node.attrib['allowanonymous'] == "yes":
kwargs['allowanonymous'] = True
found = False
for subnode in node:
if subnode.tag.lower() == 'parametercondition':
kwargs[node.tag] = ParameterCondition.fromxml(subnode)
elif subnode.tag in vars(clam.common.parameters):
args.append(vars(clam.common.parameters)[subnode.tag].fromxml(subnode))
if not found:
raise Exception("No condition found in ParameterCondition!")
return Action(*args, **kwargs) | [
"def",
"fromxml",
"(",
"node",
")",
":",
"if",
"not",
"isinstance",
"(",
"node",
",",
"ElementTree",
".",
"_Element",
")",
":",
"#pylint: disable=protected-access",
"node",
"=",
"parsexmlstring",
"(",
"node",
")",
"assert",
"node",
".",
"tag",
".",
"lower",
"(",
")",
"==",
"'action'",
"kwargs",
"=",
"{",
"}",
"args",
"=",
"[",
"]",
"if",
"'id'",
"in",
"node",
".",
"attrib",
":",
"kwargs",
"[",
"'id'",
"]",
"=",
"node",
".",
"attrib",
"[",
"'id'",
"]",
"elif",
"'name'",
"in",
"node",
".",
"attrib",
":",
"kwargs",
"[",
"'name'",
"]",
"=",
"node",
".",
"attrib",
"[",
"'name'",
"]",
"elif",
"'description'",
"in",
"node",
".",
"attrib",
":",
"kwargs",
"[",
"'description'",
"]",
"=",
"node",
".",
"attrib",
"[",
"'description'",
"]",
"elif",
"'method'",
"in",
"node",
".",
"attrib",
":",
"kwargs",
"[",
"'method'",
"]",
"=",
"node",
".",
"attrib",
"[",
"'method'",
"]",
"elif",
"'mimetype'",
"in",
"node",
".",
"attrib",
":",
"kwargs",
"[",
"'mimetype'",
"]",
"=",
"node",
".",
"attrib",
"[",
"'mimetype'",
"]",
"elif",
"'allowanonymous'",
"in",
"node",
".",
"attrib",
":",
"if",
"node",
".",
"attrib",
"[",
"'allowanonymous'",
"]",
"==",
"\"yes\"",
":",
"kwargs",
"[",
"'allowanonymous'",
"]",
"=",
"True",
"found",
"=",
"False",
"for",
"subnode",
"in",
"node",
":",
"if",
"subnode",
".",
"tag",
".",
"lower",
"(",
")",
"==",
"'parametercondition'",
":",
"kwargs",
"[",
"node",
".",
"tag",
"]",
"=",
"ParameterCondition",
".",
"fromxml",
"(",
"subnode",
")",
"elif",
"subnode",
".",
"tag",
"in",
"vars",
"(",
"clam",
".",
"common",
".",
"parameters",
")",
":",
"args",
".",
"append",
"(",
"vars",
"(",
"clam",
".",
"common",
".",
"parameters",
")",
"[",
"subnode",
".",
"tag",
"]",
".",
"fromxml",
"(",
"subnode",
")",
")",
"if",
"not",
"found",
":",
"raise",
"Exception",
"(",
"\"No condition found in ParameterCondition!\"",
")",
"return",
"Action",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Static method returning an Action instance from the given XML description. Node can be a string or an etree._Element. | [
"Static",
"method",
"returning",
"an",
"Action",
"instance",
"from",
"the",
"given",
"XML",
"description",
".",
"Node",
"can",
"be",
"a",
"string",
"or",
"an",
"etree",
".",
"_Element",
"."
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L2294-L2324 |
proycon/clam | clam/wrappers/textstats.py | crude_tokenizer | def crude_tokenizer(line):
"""This is a very crude tokenizer from pynlpl"""
tokens = []
buffer = ''
for c in line.strip():
if c == ' ' or c in string.punctuation:
if buffer:
tokens.append(buffer)
buffer = ''
else:
buffer += c
if buffer: tokens.append(buffer)
return tokens | python | def crude_tokenizer(line):
"""This is a very crude tokenizer from pynlpl"""
tokens = []
buffer = ''
for c in line.strip():
if c == ' ' or c in string.punctuation:
if buffer:
tokens.append(buffer)
buffer = ''
else:
buffer += c
if buffer: tokens.append(buffer)
return tokens | [
"def",
"crude_tokenizer",
"(",
"line",
")",
":",
"tokens",
"=",
"[",
"]",
"buffer",
"=",
"''",
"for",
"c",
"in",
"line",
".",
"strip",
"(",
")",
":",
"if",
"c",
"==",
"' '",
"or",
"c",
"in",
"string",
".",
"punctuation",
":",
"if",
"buffer",
":",
"tokens",
".",
"append",
"(",
"buffer",
")",
"buffer",
"=",
"''",
"else",
":",
"buffer",
"+=",
"c",
"if",
"buffer",
":",
"tokens",
".",
"append",
"(",
"buffer",
")",
"return",
"tokens"
] | This is a very crude tokenizer from pynlpl | [
"This",
"is",
"a",
"very",
"crude",
"tokenizer",
"from",
"pynlpl"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/wrappers/textstats.py#L43-L55 |
proycon/clam | clam/wrappers/textstats.py | dicttotext | def dicttotext(d, sort=False, max = 0):
"""Function for converting dictionary to plaintext output, optionally with some (reverse) sorting"""
if sort:
f = lambda x: sorted(x, key=lambda y: -1 * y[1])
else:
f = lambda x: x
output = ""
for i, (key, value) in enumerate(f(d.items())):
output += key + "\t" + str(value) + "\n"
if max != 0 and i >= max:
break
return output | python | def dicttotext(d, sort=False, max = 0):
"""Function for converting dictionary to plaintext output, optionally with some (reverse) sorting"""
if sort:
f = lambda x: sorted(x, key=lambda y: -1 * y[1])
else:
f = lambda x: x
output = ""
for i, (key, value) in enumerate(f(d.items())):
output += key + "\t" + str(value) + "\n"
if max != 0 and i >= max:
break
return output | [
"def",
"dicttotext",
"(",
"d",
",",
"sort",
"=",
"False",
",",
"max",
"=",
"0",
")",
":",
"if",
"sort",
":",
"f",
"=",
"lambda",
"x",
":",
"sorted",
"(",
"x",
",",
"key",
"=",
"lambda",
"y",
":",
"-",
"1",
"*",
"y",
"[",
"1",
"]",
")",
"else",
":",
"f",
"=",
"lambda",
"x",
":",
"x",
"output",
"=",
"\"\"",
"for",
"i",
",",
"(",
"key",
",",
"value",
")",
"in",
"enumerate",
"(",
"f",
"(",
"d",
".",
"items",
"(",
")",
")",
")",
":",
"output",
"+=",
"key",
"+",
"\"\\t\"",
"+",
"str",
"(",
"value",
")",
"+",
"\"\\n\"",
"if",
"max",
"!=",
"0",
"and",
"i",
">=",
"max",
":",
"break",
"return",
"output"
] | Function for converting dictionary to plaintext output, optionally with some (reverse) sorting | [
"Function",
"for",
"converting",
"dictionary",
"to",
"plaintext",
"output",
"optionally",
"with",
"some",
"(",
"reverse",
")",
"sorting"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/wrappers/textstats.py#L105-L117 |
proycon/clam | clam/common/client.py | CLAMClient.initauth | def initauth(self):
"""Initialise authentication, for internal use"""
headers = {'User-agent': 'CLAMClientAPI-' + clam.common.data.VERSION}
if self.oauth:
if not self.oauth_access_token:
r = requests.get(self.url,headers=headers, verify=self.verify)
if r.status_code == 404:
raise clam.common.data.NotFound("Authorization provider not found")
elif r.status_code == 403:
raise clam.common.data.PermissionDenied("Authorization provider denies access")
elif not (r.status_code >= 200 and r.status_code <= 299):
raise Exception("An error occured, return code " + str(r.status_code))
data = self._parse(r.text)
if data is True: #indicates failure
raise Exception("No access token provided, but Authorization Provider requires manual user input. Unable to authenticate automatically. Obtain an access token from " + r.geturl())
else:
self.oauth_access_token = data.oauth_access_token
headers['Authorization'] = 'Bearer ' + self.oauth_access_token
return headers | python | def initauth(self):
"""Initialise authentication, for internal use"""
headers = {'User-agent': 'CLAMClientAPI-' + clam.common.data.VERSION}
if self.oauth:
if not self.oauth_access_token:
r = requests.get(self.url,headers=headers, verify=self.verify)
if r.status_code == 404:
raise clam.common.data.NotFound("Authorization provider not found")
elif r.status_code == 403:
raise clam.common.data.PermissionDenied("Authorization provider denies access")
elif not (r.status_code >= 200 and r.status_code <= 299):
raise Exception("An error occured, return code " + str(r.status_code))
data = self._parse(r.text)
if data is True: #indicates failure
raise Exception("No access token provided, but Authorization Provider requires manual user input. Unable to authenticate automatically. Obtain an access token from " + r.geturl())
else:
self.oauth_access_token = data.oauth_access_token
headers['Authorization'] = 'Bearer ' + self.oauth_access_token
return headers | [
"def",
"initauth",
"(",
"self",
")",
":",
"headers",
"=",
"{",
"'User-agent'",
":",
"'CLAMClientAPI-'",
"+",
"clam",
".",
"common",
".",
"data",
".",
"VERSION",
"}",
"if",
"self",
".",
"oauth",
":",
"if",
"not",
"self",
".",
"oauth_access_token",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"url",
",",
"headers",
"=",
"headers",
",",
"verify",
"=",
"self",
".",
"verify",
")",
"if",
"r",
".",
"status_code",
"==",
"404",
":",
"raise",
"clam",
".",
"common",
".",
"data",
".",
"NotFound",
"(",
"\"Authorization provider not found\"",
")",
"elif",
"r",
".",
"status_code",
"==",
"403",
":",
"raise",
"clam",
".",
"common",
".",
"data",
".",
"PermissionDenied",
"(",
"\"Authorization provider denies access\"",
")",
"elif",
"not",
"(",
"r",
".",
"status_code",
">=",
"200",
"and",
"r",
".",
"status_code",
"<=",
"299",
")",
":",
"raise",
"Exception",
"(",
"\"An error occured, return code \"",
"+",
"str",
"(",
"r",
".",
"status_code",
")",
")",
"data",
"=",
"self",
".",
"_parse",
"(",
"r",
".",
"text",
")",
"if",
"data",
"is",
"True",
":",
"#indicates failure",
"raise",
"Exception",
"(",
"\"No access token provided, but Authorization Provider requires manual user input. Unable to authenticate automatically. Obtain an access token from \"",
"+",
"r",
".",
"geturl",
"(",
")",
")",
"else",
":",
"self",
".",
"oauth_access_token",
"=",
"data",
".",
"oauth_access_token",
"headers",
"[",
"'Authorization'",
"]",
"=",
"'Bearer '",
"+",
"self",
".",
"oauth_access_token",
"return",
"headers"
] | Initialise authentication, for internal use | [
"Initialise",
"authentication",
"for",
"internal",
"use"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/client.py#L91-L112 |
proycon/clam | clam/common/client.py | CLAMClient.request | def request(self, url='', method = 'GET', data = None, parse=True, encoding=None):
"""Issue a HTTP request and parse CLAM XML response, this is a low-level function called by all of the higher-level communication methods in this class, use those instead"""
requestparams = self.initrequest(data)
if method == 'POST':
request = requests.post
elif method == 'DELETE':
request = requests.delete
elif method == 'PUT':
request = requests.put
else:
request = requests.get
r = request(self.url + url,**requestparams)
if encoding is not None:
r.encoding = encoding
if r.status_code == 400:
raise clam.common.data.BadRequest()
elif r.status_code == 401:
raise clam.common.data.AuthRequired()
elif r.status_code == 403: #pylint: disable=too-many-nested-blocks
content = r.text
if parse:
data = self._parse(content)
if data:
if data.errors:
error = data.parametererror()
#print("DEBUG: parametererror=" + str(error),file=sys.stderr)
#for parametergroup, parameters in data.parameters: #pylint: disable=unused-variable
# for parameter in parameters:
# print("DEBUG: ", parameter.id, parameter.error,file=sys.stderr)
if error:
raise clam.common.data.ParameterError(error)
#print(content,file=sys.stderr)
raise clam.common.data.PermissionDenied(data)
else:
raise clam.common.data.PermissionDenied(content)
else:
raise clam.common.data.PermissionDenied(content)
elif r.status_code == 404 and data:
raise clam.common.data.NotFound(r.text)
elif r.status_code == 500:
raise clam.common.data.ServerError(r.text)
elif r.status_code == 405:
raise clam.common.data.ServerError("Server returned 405: Method not allowed for " + method + " on " + self.url + url)
elif r.status_code == 408:
raise clam.common.data.TimeOut()
elif not (r.status_code >= 200 and r.status_code <= 299):
raise Exception("An error occured, return code " + str(r.status_code))
if parse:
return self._parse(r.text)
else:
return r.text | python | def request(self, url='', method = 'GET', data = None, parse=True, encoding=None):
"""Issue a HTTP request and parse CLAM XML response, this is a low-level function called by all of the higher-level communication methods in this class, use those instead"""
requestparams = self.initrequest(data)
if method == 'POST':
request = requests.post
elif method == 'DELETE':
request = requests.delete
elif method == 'PUT':
request = requests.put
else:
request = requests.get
r = request(self.url + url,**requestparams)
if encoding is not None:
r.encoding = encoding
if r.status_code == 400:
raise clam.common.data.BadRequest()
elif r.status_code == 401:
raise clam.common.data.AuthRequired()
elif r.status_code == 403: #pylint: disable=too-many-nested-blocks
content = r.text
if parse:
data = self._parse(content)
if data:
if data.errors:
error = data.parametererror()
#print("DEBUG: parametererror=" + str(error),file=sys.stderr)
#for parametergroup, parameters in data.parameters: #pylint: disable=unused-variable
# for parameter in parameters:
# print("DEBUG: ", parameter.id, parameter.error,file=sys.stderr)
if error:
raise clam.common.data.ParameterError(error)
#print(content,file=sys.stderr)
raise clam.common.data.PermissionDenied(data)
else:
raise clam.common.data.PermissionDenied(content)
else:
raise clam.common.data.PermissionDenied(content)
elif r.status_code == 404 and data:
raise clam.common.data.NotFound(r.text)
elif r.status_code == 500:
raise clam.common.data.ServerError(r.text)
elif r.status_code == 405:
raise clam.common.data.ServerError("Server returned 405: Method not allowed for " + method + " on " + self.url + url)
elif r.status_code == 408:
raise clam.common.data.TimeOut()
elif not (r.status_code >= 200 and r.status_code <= 299):
raise Exception("An error occured, return code " + str(r.status_code))
if parse:
return self._parse(r.text)
else:
return r.text | [
"def",
"request",
"(",
"self",
",",
"url",
"=",
"''",
",",
"method",
"=",
"'GET'",
",",
"data",
"=",
"None",
",",
"parse",
"=",
"True",
",",
"encoding",
"=",
"None",
")",
":",
"requestparams",
"=",
"self",
".",
"initrequest",
"(",
"data",
")",
"if",
"method",
"==",
"'POST'",
":",
"request",
"=",
"requests",
".",
"post",
"elif",
"method",
"==",
"'DELETE'",
":",
"request",
"=",
"requests",
".",
"delete",
"elif",
"method",
"==",
"'PUT'",
":",
"request",
"=",
"requests",
".",
"put",
"else",
":",
"request",
"=",
"requests",
".",
"get",
"r",
"=",
"request",
"(",
"self",
".",
"url",
"+",
"url",
",",
"*",
"*",
"requestparams",
")",
"if",
"encoding",
"is",
"not",
"None",
":",
"r",
".",
"encoding",
"=",
"encoding",
"if",
"r",
".",
"status_code",
"==",
"400",
":",
"raise",
"clam",
".",
"common",
".",
"data",
".",
"BadRequest",
"(",
")",
"elif",
"r",
".",
"status_code",
"==",
"401",
":",
"raise",
"clam",
".",
"common",
".",
"data",
".",
"AuthRequired",
"(",
")",
"elif",
"r",
".",
"status_code",
"==",
"403",
":",
"#pylint: disable=too-many-nested-blocks",
"content",
"=",
"r",
".",
"text",
"if",
"parse",
":",
"data",
"=",
"self",
".",
"_parse",
"(",
"content",
")",
"if",
"data",
":",
"if",
"data",
".",
"errors",
":",
"error",
"=",
"data",
".",
"parametererror",
"(",
")",
"#print(\"DEBUG: parametererror=\" + str(error),file=sys.stderr)",
"#for parametergroup, parameters in data.parameters: #pylint: disable=unused-variable",
"# for parameter in parameters:",
"# print(\"DEBUG: \", parameter.id, parameter.error,file=sys.stderr)",
"if",
"error",
":",
"raise",
"clam",
".",
"common",
".",
"data",
".",
"ParameterError",
"(",
"error",
")",
"#print(content,file=sys.stderr)",
"raise",
"clam",
".",
"common",
".",
"data",
".",
"PermissionDenied",
"(",
"data",
")",
"else",
":",
"raise",
"clam",
".",
"common",
".",
"data",
".",
"PermissionDenied",
"(",
"content",
")",
"else",
":",
"raise",
"clam",
".",
"common",
".",
"data",
".",
"PermissionDenied",
"(",
"content",
")",
"elif",
"r",
".",
"status_code",
"==",
"404",
"and",
"data",
":",
"raise",
"clam",
".",
"common",
".",
"data",
".",
"NotFound",
"(",
"r",
".",
"text",
")",
"elif",
"r",
".",
"status_code",
"==",
"500",
":",
"raise",
"clam",
".",
"common",
".",
"data",
".",
"ServerError",
"(",
"r",
".",
"text",
")",
"elif",
"r",
".",
"status_code",
"==",
"405",
":",
"raise",
"clam",
".",
"common",
".",
"data",
".",
"ServerError",
"(",
"\"Server returned 405: Method not allowed for \"",
"+",
"method",
"+",
"\" on \"",
"+",
"self",
".",
"url",
"+",
"url",
")",
"elif",
"r",
".",
"status_code",
"==",
"408",
":",
"raise",
"clam",
".",
"common",
".",
"data",
".",
"TimeOut",
"(",
")",
"elif",
"not",
"(",
"r",
".",
"status_code",
">=",
"200",
"and",
"r",
".",
"status_code",
"<=",
"299",
")",
":",
"raise",
"Exception",
"(",
"\"An error occured, return code \"",
"+",
"str",
"(",
"r",
".",
"status_code",
")",
")",
"if",
"parse",
":",
"return",
"self",
".",
"_parse",
"(",
"r",
".",
"text",
")",
"else",
":",
"return",
"r",
".",
"text"
] | Issue a HTTP request and parse CLAM XML response, this is a low-level function called by all of the higher-level communication methods in this class, use those instead | [
"Issue",
"a",
"HTTP",
"request",
"and",
"parse",
"CLAM",
"XML",
"response",
"this",
"is",
"a",
"low",
"-",
"level",
"function",
"called",
"by",
"all",
"of",
"the",
"higher",
"-",
"level",
"communication",
"methods",
"in",
"this",
"class",
"use",
"those",
"instead"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/client.py#L132-L188 |
proycon/clam | clam/common/client.py | CLAMClient._parse | def _parse(self, content):
"""Parses CLAM XML data and returns a ``CLAMData`` object. For internal use. Raises `ParameterError` exception on parameter errors."""
if content.find('<clam') != -1:
data = clam.common.data.CLAMData(content,self, loadmetadata=self.loadmetadata)
if data.errors:
error = data.parametererror()
if error:
raise clam.common.data.ParameterError(error)
return data
else:
return True | python | def _parse(self, content):
"""Parses CLAM XML data and returns a ``CLAMData`` object. For internal use. Raises `ParameterError` exception on parameter errors."""
if content.find('<clam') != -1:
data = clam.common.data.CLAMData(content,self, loadmetadata=self.loadmetadata)
if data.errors:
error = data.parametererror()
if error:
raise clam.common.data.ParameterError(error)
return data
else:
return True | [
"def",
"_parse",
"(",
"self",
",",
"content",
")",
":",
"if",
"content",
".",
"find",
"(",
"'<clam'",
")",
"!=",
"-",
"1",
":",
"data",
"=",
"clam",
".",
"common",
".",
"data",
".",
"CLAMData",
"(",
"content",
",",
"self",
",",
"loadmetadata",
"=",
"self",
".",
"loadmetadata",
")",
"if",
"data",
".",
"errors",
":",
"error",
"=",
"data",
".",
"parametererror",
"(",
")",
"if",
"error",
":",
"raise",
"clam",
".",
"common",
".",
"data",
".",
"ParameterError",
"(",
"error",
")",
"return",
"data",
"else",
":",
"return",
"True"
] | Parses CLAM XML data and returns a ``CLAMData`` object. For internal use. Raises `ParameterError` exception on parameter errors. | [
"Parses",
"CLAM",
"XML",
"data",
"and",
"returns",
"a",
"CLAMData",
"object",
".",
"For",
"internal",
"use",
".",
"Raises",
"ParameterError",
"exception",
"on",
"parameter",
"errors",
"."
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/client.py#L191-L201 |
proycon/clam | clam/common/client.py | CLAMClient.get | def get(self, project):
"""Query the project status. Returns a ``CLAMData`` instance or raises an exception according to the returned HTTP Status code"""
try:
data = self.request(project + '/')
except:
raise
if not isinstance(data, clam.common.data.CLAMData):
raise Exception("Unable to retrieve CLAM Data")
else:
return data | python | def get(self, project):
"""Query the project status. Returns a ``CLAMData`` instance or raises an exception according to the returned HTTP Status code"""
try:
data = self.request(project + '/')
except:
raise
if not isinstance(data, clam.common.data.CLAMData):
raise Exception("Unable to retrieve CLAM Data")
else:
return data | [
"def",
"get",
"(",
"self",
",",
"project",
")",
":",
"try",
":",
"data",
"=",
"self",
".",
"request",
"(",
"project",
"+",
"'/'",
")",
"except",
":",
"raise",
"if",
"not",
"isinstance",
"(",
"data",
",",
"clam",
".",
"common",
".",
"data",
".",
"CLAMData",
")",
":",
"raise",
"Exception",
"(",
"\"Unable to retrieve CLAM Data\"",
")",
"else",
":",
"return",
"data"
] | Query the project status. Returns a ``CLAMData`` instance or raises an exception according to the returned HTTP Status code | [
"Query",
"the",
"project",
"status",
".",
"Returns",
"a",
"CLAMData",
"instance",
"or",
"raises",
"an",
"exception",
"according",
"to",
"the",
"returned",
"HTTP",
"Status",
"code"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/client.py#L207-L216 |
proycon/clam | clam/common/client.py | CLAMClient.action | def action(self, action_id, **kwargs):
"""Query an action, specify the parameters for the action as keyword parameters. An optional keyword parameter method='GET' (default) or method='POST' can be set. The character set encoding of the response can be configured using the encoding keyword parameter (defaults to utf-8 by default)"""
if 'method' in kwargs:
method = kwargs['method']
del kwargs['method']
else:
method = 'GET'
if 'encoding' in kwargs:
encoding = kwargs['encoding']
del kwargs['encoding']
else:
encoding = 'utf-8'
return self.request('actions/' + action_id, method, kwargs, False,encoding) | python | def action(self, action_id, **kwargs):
"""Query an action, specify the parameters for the action as keyword parameters. An optional keyword parameter method='GET' (default) or method='POST' can be set. The character set encoding of the response can be configured using the encoding keyword parameter (defaults to utf-8 by default)"""
if 'method' in kwargs:
method = kwargs['method']
del kwargs['method']
else:
method = 'GET'
if 'encoding' in kwargs:
encoding = kwargs['encoding']
del kwargs['encoding']
else:
encoding = 'utf-8'
return self.request('actions/' + action_id, method, kwargs, False,encoding) | [
"def",
"action",
"(",
"self",
",",
"action_id",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'method'",
"in",
"kwargs",
":",
"method",
"=",
"kwargs",
"[",
"'method'",
"]",
"del",
"kwargs",
"[",
"'method'",
"]",
"else",
":",
"method",
"=",
"'GET'",
"if",
"'encoding'",
"in",
"kwargs",
":",
"encoding",
"=",
"kwargs",
"[",
"'encoding'",
"]",
"del",
"kwargs",
"[",
"'encoding'",
"]",
"else",
":",
"encoding",
"=",
"'utf-8'",
"return",
"self",
".",
"request",
"(",
"'actions/'",
"+",
"action_id",
",",
"method",
",",
"kwargs",
",",
"False",
",",
"encoding",
")"
] | Query an action, specify the parameters for the action as keyword parameters. An optional keyword parameter method='GET' (default) or method='POST' can be set. The character set encoding of the response can be configured using the encoding keyword parameter (defaults to utf-8 by default) | [
"Query",
"an",
"action",
"specify",
"the",
"parameters",
"for",
"the",
"action",
"as",
"keyword",
"parameters",
".",
"An",
"optional",
"keyword",
"parameter",
"method",
"=",
"GET",
"(",
"default",
")",
"or",
"method",
"=",
"POST",
"can",
"be",
"set",
".",
"The",
"character",
"set",
"encoding",
"of",
"the",
"response",
"can",
"be",
"configured",
"using",
"the",
"encoding",
"keyword",
"parameter",
"(",
"defaults",
"to",
"utf",
"-",
"8",
"by",
"default",
")"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/client.py#L228-L242 |
proycon/clam | clam/common/client.py | CLAMClient.start | def start(self, project, **parameters):
"""Start a run. ``project`` is the ID of the project, and ``parameters`` are keyword arguments for
the global parameters. Returns a ``CLAMData`` object or raises exceptions. Note that no exceptions are raised on parameter errors, you have to check for those manually! (Use startsafe instead if want Exceptions on parameter errors)::
response = client.start("myprojectname", parameter1="blah", parameterX=4.2)
"""
#auth = None
#if 'auth' in parameters:
# auth = parameters['auth']
# del parameters['auth']
for key in parameters:
if isinstance(parameters[key],list) or isinstance(parameters[key],tuple):
parameters[key] = ",".join(parameters[key])
return self.request(project + '/', 'POST', parameters) | python | def start(self, project, **parameters):
"""Start a run. ``project`` is the ID of the project, and ``parameters`` are keyword arguments for
the global parameters. Returns a ``CLAMData`` object or raises exceptions. Note that no exceptions are raised on parameter errors, you have to check for those manually! (Use startsafe instead if want Exceptions on parameter errors)::
response = client.start("myprojectname", parameter1="blah", parameterX=4.2)
"""
#auth = None
#if 'auth' in parameters:
# auth = parameters['auth']
# del parameters['auth']
for key in parameters:
if isinstance(parameters[key],list) or isinstance(parameters[key],tuple):
parameters[key] = ",".join(parameters[key])
return self.request(project + '/', 'POST', parameters) | [
"def",
"start",
"(",
"self",
",",
"project",
",",
"*",
"*",
"parameters",
")",
":",
"#auth = None",
"#if 'auth' in parameters:",
"# auth = parameters['auth']",
"# del parameters['auth']",
"for",
"key",
"in",
"parameters",
":",
"if",
"isinstance",
"(",
"parameters",
"[",
"key",
"]",
",",
"list",
")",
"or",
"isinstance",
"(",
"parameters",
"[",
"key",
"]",
",",
"tuple",
")",
":",
"parameters",
"[",
"key",
"]",
"=",
"\",\"",
".",
"join",
"(",
"parameters",
"[",
"key",
"]",
")",
"return",
"self",
".",
"request",
"(",
"project",
"+",
"'/'",
",",
"'POST'",
",",
"parameters",
")"
] | Start a run. ``project`` is the ID of the project, and ``parameters`` are keyword arguments for
the global parameters. Returns a ``CLAMData`` object or raises exceptions. Note that no exceptions are raised on parameter errors, you have to check for those manually! (Use startsafe instead if want Exceptions on parameter errors)::
response = client.start("myprojectname", parameter1="blah", parameterX=4.2) | [
"Start",
"a",
"run",
".",
"project",
"is",
"the",
"ID",
"of",
"the",
"project",
"and",
"parameters",
"are",
"keyword",
"arguments",
"for",
"the",
"global",
"parameters",
".",
"Returns",
"a",
"CLAMData",
"object",
"or",
"raises",
"exceptions",
".",
"Note",
"that",
"no",
"exceptions",
"are",
"raised",
"on",
"parameter",
"errors",
"you",
"have",
"to",
"check",
"for",
"those",
"manually!",
"(",
"Use",
"startsafe",
"instead",
"if",
"want",
"Exceptions",
"on",
"parameter",
"errors",
")",
"::"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/client.py#L246-L261 |
proycon/clam | clam/common/client.py | CLAMClient.startsafe | def startsafe(self, project, **parameters):
"""Start a run. ``project`` is the ID of the project, and ``parameters`` are keyword arguments for
the global parameters. Returns a ``CLAMData`` object or raises exceptions. This version, unlike ``start()``, raises Exceptions (``ParameterError``) on parameter errors.
response = client.startsafe("myprojectname", parameter1="blah", parameterX=4.2)
"""
try:
data = self.start(project, **parameters)
for parametergroup, paramlist in data.parameters: #pylint: disable=unused-variable
for parameter in paramlist:
if parameter.error:
raise clam.common.data.ParameterError(parameter.error)
return data
except:
raise | python | def startsafe(self, project, **parameters):
"""Start a run. ``project`` is the ID of the project, and ``parameters`` are keyword arguments for
the global parameters. Returns a ``CLAMData`` object or raises exceptions. This version, unlike ``start()``, raises Exceptions (``ParameterError``) on parameter errors.
response = client.startsafe("myprojectname", parameter1="blah", parameterX=4.2)
"""
try:
data = self.start(project, **parameters)
for parametergroup, paramlist in data.parameters: #pylint: disable=unused-variable
for parameter in paramlist:
if parameter.error:
raise clam.common.data.ParameterError(parameter.error)
return data
except:
raise | [
"def",
"startsafe",
"(",
"self",
",",
"project",
",",
"*",
"*",
"parameters",
")",
":",
"try",
":",
"data",
"=",
"self",
".",
"start",
"(",
"project",
",",
"*",
"*",
"parameters",
")",
"for",
"parametergroup",
",",
"paramlist",
"in",
"data",
".",
"parameters",
":",
"#pylint: disable=unused-variable",
"for",
"parameter",
"in",
"paramlist",
":",
"if",
"parameter",
".",
"error",
":",
"raise",
"clam",
".",
"common",
".",
"data",
".",
"ParameterError",
"(",
"parameter",
".",
"error",
")",
"return",
"data",
"except",
":",
"raise"
] | Start a run. ``project`` is the ID of the project, and ``parameters`` are keyword arguments for
the global parameters. Returns a ``CLAMData`` object or raises exceptions. This version, unlike ``start()``, raises Exceptions (``ParameterError``) on parameter errors.
response = client.startsafe("myprojectname", parameter1="blah", parameterX=4.2) | [
"Start",
"a",
"run",
".",
"project",
"is",
"the",
"ID",
"of",
"the",
"project",
"and",
"parameters",
"are",
"keyword",
"arguments",
"for",
"the",
"global",
"parameters",
".",
"Returns",
"a",
"CLAMData",
"object",
"or",
"raises",
"exceptions",
".",
"This",
"version",
"unlike",
"start",
"()",
"raises",
"Exceptions",
"(",
"ParameterError",
")",
"on",
"parameter",
"errors",
"."
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/client.py#L263-L279 |
proycon/clam | clam/common/client.py | CLAMClient.downloadarchive | def downloadarchive(self, project, targetfile, archiveformat = 'zip'):
"""Download all output files as a single archive:
* *targetfile* - path for the new local file to be written
* *archiveformat* - the format of the archive, can be 'zip','gz','bz2'
Example::
client.downloadarchive("myproject","allresults.zip","zip")
"""
if isinstance(targetfile,str) or (sys.version < '3' and isinstance(targetfile,unicode)): #pylint: disable=undefined-variable
targetfile = open(targetfile,'wb')
r = requests.get(self.url + project + '/output/' + archiveformat,**self.initrequest())
CHUNK = 16 * 1024
for chunk in r.iter_content(chunk_size=CHUNK):
if chunk: # filter out keep-alive new chunks
targetfile.write(chunk)
targetfile.flush()
targetfile.close() | python | def downloadarchive(self, project, targetfile, archiveformat = 'zip'):
"""Download all output files as a single archive:
* *targetfile* - path for the new local file to be written
* *archiveformat* - the format of the archive, can be 'zip','gz','bz2'
Example::
client.downloadarchive("myproject","allresults.zip","zip")
"""
if isinstance(targetfile,str) or (sys.version < '3' and isinstance(targetfile,unicode)): #pylint: disable=undefined-variable
targetfile = open(targetfile,'wb')
r = requests.get(self.url + project + '/output/' + archiveformat,**self.initrequest())
CHUNK = 16 * 1024
for chunk in r.iter_content(chunk_size=CHUNK):
if chunk: # filter out keep-alive new chunks
targetfile.write(chunk)
targetfile.flush()
targetfile.close() | [
"def",
"downloadarchive",
"(",
"self",
",",
"project",
",",
"targetfile",
",",
"archiveformat",
"=",
"'zip'",
")",
":",
"if",
"isinstance",
"(",
"targetfile",
",",
"str",
")",
"or",
"(",
"sys",
".",
"version",
"<",
"'3'",
"and",
"isinstance",
"(",
"targetfile",
",",
"unicode",
")",
")",
":",
"#pylint: disable=undefined-variable",
"targetfile",
"=",
"open",
"(",
"targetfile",
",",
"'wb'",
")",
"r",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"url",
"+",
"project",
"+",
"'/output/'",
"+",
"archiveformat",
",",
"*",
"*",
"self",
".",
"initrequest",
"(",
")",
")",
"CHUNK",
"=",
"16",
"*",
"1024",
"for",
"chunk",
"in",
"r",
".",
"iter_content",
"(",
"chunk_size",
"=",
"CHUNK",
")",
":",
"if",
"chunk",
":",
"# filter out keep-alive new chunks",
"targetfile",
".",
"write",
"(",
"chunk",
")",
"targetfile",
".",
"flush",
"(",
")",
"targetfile",
".",
"close",
"(",
")"
] | Download all output files as a single archive:
* *targetfile* - path for the new local file to be written
* *archiveformat* - the format of the archive, can be 'zip','gz','bz2'
Example::
client.downloadarchive("myproject","allresults.zip","zip") | [
"Download",
"all",
"output",
"files",
"as",
"a",
"single",
"archive",
":"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/client.py#L297-L316 |
proycon/clam | clam/common/client.py | CLAMClient.getinputfilename | def getinputfilename(self, inputtemplate, filename):
"""Determine the final filename for an input file given an inputtemplate and a given filename.
Example::
filenameonserver = client.getinputfilename("someinputtemplate","/path/to/local/file")
"""
if inputtemplate.filename:
filename = inputtemplate.filename
elif inputtemplate.extension:
if filename.lower()[-4:] == '.zip' or filename.lower()[-7:] == '.tar.gz' or filename.lower()[-8:] == '.tar.bz2':
#pass archives as-is
return filename
if filename[-len(inputtemplate.extension) - 1:].lower() != '.' + inputtemplate.extension.lower():
filename += '.' + inputtemplate.extension
return filename | python | def getinputfilename(self, inputtemplate, filename):
"""Determine the final filename for an input file given an inputtemplate and a given filename.
Example::
filenameonserver = client.getinputfilename("someinputtemplate","/path/to/local/file")
"""
if inputtemplate.filename:
filename = inputtemplate.filename
elif inputtemplate.extension:
if filename.lower()[-4:] == '.zip' or filename.lower()[-7:] == '.tar.gz' or filename.lower()[-8:] == '.tar.bz2':
#pass archives as-is
return filename
if filename[-len(inputtemplate.extension) - 1:].lower() != '.' + inputtemplate.extension.lower():
filename += '.' + inputtemplate.extension
return filename | [
"def",
"getinputfilename",
"(",
"self",
",",
"inputtemplate",
",",
"filename",
")",
":",
"if",
"inputtemplate",
".",
"filename",
":",
"filename",
"=",
"inputtemplate",
".",
"filename",
"elif",
"inputtemplate",
".",
"extension",
":",
"if",
"filename",
".",
"lower",
"(",
")",
"[",
"-",
"4",
":",
"]",
"==",
"'.zip'",
"or",
"filename",
".",
"lower",
"(",
")",
"[",
"-",
"7",
":",
"]",
"==",
"'.tar.gz'",
"or",
"filename",
".",
"lower",
"(",
")",
"[",
"-",
"8",
":",
"]",
"==",
"'.tar.bz2'",
":",
"#pass archives as-is",
"return",
"filename",
"if",
"filename",
"[",
"-",
"len",
"(",
"inputtemplate",
".",
"extension",
")",
"-",
"1",
":",
"]",
".",
"lower",
"(",
")",
"!=",
"'.'",
"+",
"inputtemplate",
".",
"extension",
".",
"lower",
"(",
")",
":",
"filename",
"+=",
"'.'",
"+",
"inputtemplate",
".",
"extension",
"return",
"filename"
] | Determine the final filename for an input file given an inputtemplate and a given filename.
Example::
filenameonserver = client.getinputfilename("someinputtemplate","/path/to/local/file") | [
"Determine",
"the",
"final",
"filename",
"for",
"an",
"input",
"file",
"given",
"an",
"inputtemplate",
"and",
"a",
"given",
"filename",
"."
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/client.py#L318-L336 |
proycon/clam | clam/common/client.py | CLAMClient._parseupload | def _parseupload(self, node):
"""Parse CLAM Upload XML Responses. For internal use"""
if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access
try:
node = clam.common.data.parsexmlstring(node)
except:
raise Exception(node)
if node.tag != 'clamupload':
raise Exception("Not a valid CLAM upload response")
for node2 in node: #pylint: disable=too-many-nested-blocks
if node2.tag == 'upload':
for subnode in node2:
if subnode.tag == 'error':
raise clam.common.data.UploadError(subnode.text)
if subnode.tag == 'parameters':
if 'errors' in subnode.attrib and subnode.attrib['errors'] == 'yes':
errormsg = "The submitted metadata did not validate properly" #default
for parameternode in subnode:
if 'error' in parameternode.attrib:
errormsg = parameternode.attrib['error']
raise clam.common.data.ParameterError(errormsg + " (parameter="+parameternode.attrib['id']+")")
raise clam.common.data.ParameterError(errormsg)
return True | python | def _parseupload(self, node):
"""Parse CLAM Upload XML Responses. For internal use"""
if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access
try:
node = clam.common.data.parsexmlstring(node)
except:
raise Exception(node)
if node.tag != 'clamupload':
raise Exception("Not a valid CLAM upload response")
for node2 in node: #pylint: disable=too-many-nested-blocks
if node2.tag == 'upload':
for subnode in node2:
if subnode.tag == 'error':
raise clam.common.data.UploadError(subnode.text)
if subnode.tag == 'parameters':
if 'errors' in subnode.attrib and subnode.attrib['errors'] == 'yes':
errormsg = "The submitted metadata did not validate properly" #default
for parameternode in subnode:
if 'error' in parameternode.attrib:
errormsg = parameternode.attrib['error']
raise clam.common.data.ParameterError(errormsg + " (parameter="+parameternode.attrib['id']+")")
raise clam.common.data.ParameterError(errormsg)
return True | [
"def",
"_parseupload",
"(",
"self",
",",
"node",
")",
":",
"if",
"not",
"isinstance",
"(",
"node",
",",
"ElementTree",
".",
"_Element",
")",
":",
"#pylint: disable=protected-access",
"try",
":",
"node",
"=",
"clam",
".",
"common",
".",
"data",
".",
"parsexmlstring",
"(",
"node",
")",
"except",
":",
"raise",
"Exception",
"(",
"node",
")",
"if",
"node",
".",
"tag",
"!=",
"'clamupload'",
":",
"raise",
"Exception",
"(",
"\"Not a valid CLAM upload response\"",
")",
"for",
"node2",
"in",
"node",
":",
"#pylint: disable=too-many-nested-blocks",
"if",
"node2",
".",
"tag",
"==",
"'upload'",
":",
"for",
"subnode",
"in",
"node2",
":",
"if",
"subnode",
".",
"tag",
"==",
"'error'",
":",
"raise",
"clam",
".",
"common",
".",
"data",
".",
"UploadError",
"(",
"subnode",
".",
"text",
")",
"if",
"subnode",
".",
"tag",
"==",
"'parameters'",
":",
"if",
"'errors'",
"in",
"subnode",
".",
"attrib",
"and",
"subnode",
".",
"attrib",
"[",
"'errors'",
"]",
"==",
"'yes'",
":",
"errormsg",
"=",
"\"The submitted metadata did not validate properly\"",
"#default",
"for",
"parameternode",
"in",
"subnode",
":",
"if",
"'error'",
"in",
"parameternode",
".",
"attrib",
":",
"errormsg",
"=",
"parameternode",
".",
"attrib",
"[",
"'error'",
"]",
"raise",
"clam",
".",
"common",
".",
"data",
".",
"ParameterError",
"(",
"errormsg",
"+",
"\" (parameter=\"",
"+",
"parameternode",
".",
"attrib",
"[",
"'id'",
"]",
"+",
"\")\"",
")",
"raise",
"clam",
".",
"common",
".",
"data",
".",
"ParameterError",
"(",
"errormsg",
")",
"return",
"True"
] | Parse CLAM Upload XML Responses. For internal use | [
"Parse",
"CLAM",
"Upload",
"XML",
"Responses",
".",
"For",
"internal",
"use"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/client.py#L338-L360 |
proycon/clam | clam/common/client.py | CLAMClient.addinputfile | def addinputfile(self, project, inputtemplate, sourcefile, **kwargs):
"""Add/upload an input file to the CLAM service. Supports proper file upload streaming.
project - the ID of the project you want to add the file to.
inputtemplate - The input template you want to use to add this file (InputTemplate instance)
sourcefile - The file you want to add: string containing a filename (or instance of ``file``)
Keyword arguments (optional but recommended!):
* ``filename`` - the filename on the server (will be same as sourcefile if not specified)
* ``metadata`` - A metadata object.
* ``metafile`` - A metadata file (filename)
Any other keyword arguments will be passed as metadata and matched with the input template's parameters.
Example::
client.addinputfile("myproject", "someinputtemplate", "/path/to/local/file")
With metadata, assuming such metadata parameters are defined::
client.addinputfile("myproject", "someinputtemplate", "/path/to/local/file", parameter1="blah", parameterX=3.5)
"""
if isinstance( inputtemplate, str) or (sys.version < '3' and isinstance( inputtemplate, unicode)): #pylint: disable=undefined-variable
data = self.get(project) #causes an extra query to server
inputtemplate = data.inputtemplate(inputtemplate)
elif not isinstance(inputtemplate, clam.common.data.InputTemplate):
raise Exception("inputtemplate must be instance of InputTemplate. Get from CLAMData.inputtemplate(id)")
if not isinstance(sourcefile, IOBase):
sourcefile = open(sourcefile,'rb')
if 'filename' in kwargs:
filename = self.getinputfilename(inputtemplate, kwargs['filename'])
else:
filename = self.getinputfilename(inputtemplate, os.path.basename(sourcefile.name) )
data = {"file": (filename,sourcefile,inputtemplate.formatclass.mimetype), 'inputtemplate': inputtemplate.id}
for key, value in kwargs.items():
if key == 'filename':
pass #nothing to do
elif key == 'metadata':
assert isinstance(value, clam.common.data.CLAMMetaData)
data['metadata'] = value.xml()
elif key == 'metafile':
data['metafile'] = open(value,'rb')
else:
data[key] = value
requestparams = self.initrequest(data)
if 'auth'in requestparams:
#TODO: streaming support doesn't work with authentication unfortunately, disabling streaming for now:
del data['file']
requestparams['data'] = data
requestparams['files'] = [('file', (filename,sourcefile, inputtemplate.formatclass.mimetype))]
if 'metafile' in kwargs:
del data['metafile']
requestparams['files'].append(('metafile',('.'+ filename + '.METADATA', open(kwargs['metafile'],'rb'), 'text/xml')))
else:
#streaming support
encodeddata = MultipartEncoder(fields=requestparams['data']) #from requests-toolbelt, necessary for streaming support
requestparams['data'] = encodeddata
requestparams['headers']['Content-Type'] = encodeddata.content_type
r = requests.post(self.url + project + '/input/' + filename,**requestparams)
sourcefile.close()
if r.status_code == 400:
raise clam.common.data.BadRequest()
elif r.status_code == 401:
raise clam.common.data.AuthRequired()
elif r.status_code == 403:
if r.text[0] == '<':
#XML response
return self._parseupload(r.text)
else:
raise clam.common.data.PermissionDenied(r.text)
elif r.status_code == 404:
raise clam.common.data.NotFound(r.text)
elif r.status_code == 500:
raise clam.common.data.ServerError(r.text)
elif r.status_code == 405:
raise clam.common.data.ServerError("Server returned 405: Method not allowed for POST on " + self.url + project + '/input/' + filename)
elif r.status_code == 408:
raise clam.common.data.TimeOut()
elif not (r.status_code >= 200 and r.status_code <= 299):
raise Exception("An error occured, return code " + str(r.status_code))
return self._parseupload(r.text) | python | def addinputfile(self, project, inputtemplate, sourcefile, **kwargs):
"""Add/upload an input file to the CLAM service. Supports proper file upload streaming.
project - the ID of the project you want to add the file to.
inputtemplate - The input template you want to use to add this file (InputTemplate instance)
sourcefile - The file you want to add: string containing a filename (or instance of ``file``)
Keyword arguments (optional but recommended!):
* ``filename`` - the filename on the server (will be same as sourcefile if not specified)
* ``metadata`` - A metadata object.
* ``metafile`` - A metadata file (filename)
Any other keyword arguments will be passed as metadata and matched with the input template's parameters.
Example::
client.addinputfile("myproject", "someinputtemplate", "/path/to/local/file")
With metadata, assuming such metadata parameters are defined::
client.addinputfile("myproject", "someinputtemplate", "/path/to/local/file", parameter1="blah", parameterX=3.5)
"""
if isinstance( inputtemplate, str) or (sys.version < '3' and isinstance( inputtemplate, unicode)): #pylint: disable=undefined-variable
data = self.get(project) #causes an extra query to server
inputtemplate = data.inputtemplate(inputtemplate)
elif not isinstance(inputtemplate, clam.common.data.InputTemplate):
raise Exception("inputtemplate must be instance of InputTemplate. Get from CLAMData.inputtemplate(id)")
if not isinstance(sourcefile, IOBase):
sourcefile = open(sourcefile,'rb')
if 'filename' in kwargs:
filename = self.getinputfilename(inputtemplate, kwargs['filename'])
else:
filename = self.getinputfilename(inputtemplate, os.path.basename(sourcefile.name) )
data = {"file": (filename,sourcefile,inputtemplate.formatclass.mimetype), 'inputtemplate': inputtemplate.id}
for key, value in kwargs.items():
if key == 'filename':
pass #nothing to do
elif key == 'metadata':
assert isinstance(value, clam.common.data.CLAMMetaData)
data['metadata'] = value.xml()
elif key == 'metafile':
data['metafile'] = open(value,'rb')
else:
data[key] = value
requestparams = self.initrequest(data)
if 'auth'in requestparams:
#TODO: streaming support doesn't work with authentication unfortunately, disabling streaming for now:
del data['file']
requestparams['data'] = data
requestparams['files'] = [('file', (filename,sourcefile, inputtemplate.formatclass.mimetype))]
if 'metafile' in kwargs:
del data['metafile']
requestparams['files'].append(('metafile',('.'+ filename + '.METADATA', open(kwargs['metafile'],'rb'), 'text/xml')))
else:
#streaming support
encodeddata = MultipartEncoder(fields=requestparams['data']) #from requests-toolbelt, necessary for streaming support
requestparams['data'] = encodeddata
requestparams['headers']['Content-Type'] = encodeddata.content_type
r = requests.post(self.url + project + '/input/' + filename,**requestparams)
sourcefile.close()
if r.status_code == 400:
raise clam.common.data.BadRequest()
elif r.status_code == 401:
raise clam.common.data.AuthRequired()
elif r.status_code == 403:
if r.text[0] == '<':
#XML response
return self._parseupload(r.text)
else:
raise clam.common.data.PermissionDenied(r.text)
elif r.status_code == 404:
raise clam.common.data.NotFound(r.text)
elif r.status_code == 500:
raise clam.common.data.ServerError(r.text)
elif r.status_code == 405:
raise clam.common.data.ServerError("Server returned 405: Method not allowed for POST on " + self.url + project + '/input/' + filename)
elif r.status_code == 408:
raise clam.common.data.TimeOut()
elif not (r.status_code >= 200 and r.status_code <= 299):
raise Exception("An error occured, return code " + str(r.status_code))
return self._parseupload(r.text) | [
"def",
"addinputfile",
"(",
"self",
",",
"project",
",",
"inputtemplate",
",",
"sourcefile",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"inputtemplate",
",",
"str",
")",
"or",
"(",
"sys",
".",
"version",
"<",
"'3'",
"and",
"isinstance",
"(",
"inputtemplate",
",",
"unicode",
")",
")",
":",
"#pylint: disable=undefined-variable",
"data",
"=",
"self",
".",
"get",
"(",
"project",
")",
"#causes an extra query to server",
"inputtemplate",
"=",
"data",
".",
"inputtemplate",
"(",
"inputtemplate",
")",
"elif",
"not",
"isinstance",
"(",
"inputtemplate",
",",
"clam",
".",
"common",
".",
"data",
".",
"InputTemplate",
")",
":",
"raise",
"Exception",
"(",
"\"inputtemplate must be instance of InputTemplate. Get from CLAMData.inputtemplate(id)\"",
")",
"if",
"not",
"isinstance",
"(",
"sourcefile",
",",
"IOBase",
")",
":",
"sourcefile",
"=",
"open",
"(",
"sourcefile",
",",
"'rb'",
")",
"if",
"'filename'",
"in",
"kwargs",
":",
"filename",
"=",
"self",
".",
"getinputfilename",
"(",
"inputtemplate",
",",
"kwargs",
"[",
"'filename'",
"]",
")",
"else",
":",
"filename",
"=",
"self",
".",
"getinputfilename",
"(",
"inputtemplate",
",",
"os",
".",
"path",
".",
"basename",
"(",
"sourcefile",
".",
"name",
")",
")",
"data",
"=",
"{",
"\"file\"",
":",
"(",
"filename",
",",
"sourcefile",
",",
"inputtemplate",
".",
"formatclass",
".",
"mimetype",
")",
",",
"'inputtemplate'",
":",
"inputtemplate",
".",
"id",
"}",
"for",
"key",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"key",
"==",
"'filename'",
":",
"pass",
"#nothing to do",
"elif",
"key",
"==",
"'metadata'",
":",
"assert",
"isinstance",
"(",
"value",
",",
"clam",
".",
"common",
".",
"data",
".",
"CLAMMetaData",
")",
"data",
"[",
"'metadata'",
"]",
"=",
"value",
".",
"xml",
"(",
")",
"elif",
"key",
"==",
"'metafile'",
":",
"data",
"[",
"'metafile'",
"]",
"=",
"open",
"(",
"value",
",",
"'rb'",
")",
"else",
":",
"data",
"[",
"key",
"]",
"=",
"value",
"requestparams",
"=",
"self",
".",
"initrequest",
"(",
"data",
")",
"if",
"'auth'",
"in",
"requestparams",
":",
"#TODO: streaming support doesn't work with authentication unfortunately, disabling streaming for now:",
"del",
"data",
"[",
"'file'",
"]",
"requestparams",
"[",
"'data'",
"]",
"=",
"data",
"requestparams",
"[",
"'files'",
"]",
"=",
"[",
"(",
"'file'",
",",
"(",
"filename",
",",
"sourcefile",
",",
"inputtemplate",
".",
"formatclass",
".",
"mimetype",
")",
")",
"]",
"if",
"'metafile'",
"in",
"kwargs",
":",
"del",
"data",
"[",
"'metafile'",
"]",
"requestparams",
"[",
"'files'",
"]",
".",
"append",
"(",
"(",
"'metafile'",
",",
"(",
"'.'",
"+",
"filename",
"+",
"'.METADATA'",
",",
"open",
"(",
"kwargs",
"[",
"'metafile'",
"]",
",",
"'rb'",
")",
",",
"'text/xml'",
")",
")",
")",
"else",
":",
"#streaming support",
"encodeddata",
"=",
"MultipartEncoder",
"(",
"fields",
"=",
"requestparams",
"[",
"'data'",
"]",
")",
"#from requests-toolbelt, necessary for streaming support",
"requestparams",
"[",
"'data'",
"]",
"=",
"encodeddata",
"requestparams",
"[",
"'headers'",
"]",
"[",
"'Content-Type'",
"]",
"=",
"encodeddata",
".",
"content_type",
"r",
"=",
"requests",
".",
"post",
"(",
"self",
".",
"url",
"+",
"project",
"+",
"'/input/'",
"+",
"filename",
",",
"*",
"*",
"requestparams",
")",
"sourcefile",
".",
"close",
"(",
")",
"if",
"r",
".",
"status_code",
"==",
"400",
":",
"raise",
"clam",
".",
"common",
".",
"data",
".",
"BadRequest",
"(",
")",
"elif",
"r",
".",
"status_code",
"==",
"401",
":",
"raise",
"clam",
".",
"common",
".",
"data",
".",
"AuthRequired",
"(",
")",
"elif",
"r",
".",
"status_code",
"==",
"403",
":",
"if",
"r",
".",
"text",
"[",
"0",
"]",
"==",
"'<'",
":",
"#XML response",
"return",
"self",
".",
"_parseupload",
"(",
"r",
".",
"text",
")",
"else",
":",
"raise",
"clam",
".",
"common",
".",
"data",
".",
"PermissionDenied",
"(",
"r",
".",
"text",
")",
"elif",
"r",
".",
"status_code",
"==",
"404",
":",
"raise",
"clam",
".",
"common",
".",
"data",
".",
"NotFound",
"(",
"r",
".",
"text",
")",
"elif",
"r",
".",
"status_code",
"==",
"500",
":",
"raise",
"clam",
".",
"common",
".",
"data",
".",
"ServerError",
"(",
"r",
".",
"text",
")",
"elif",
"r",
".",
"status_code",
"==",
"405",
":",
"raise",
"clam",
".",
"common",
".",
"data",
".",
"ServerError",
"(",
"\"Server returned 405: Method not allowed for POST on \"",
"+",
"self",
".",
"url",
"+",
"project",
"+",
"'/input/'",
"+",
"filename",
")",
"elif",
"r",
".",
"status_code",
"==",
"408",
":",
"raise",
"clam",
".",
"common",
".",
"data",
".",
"TimeOut",
"(",
")",
"elif",
"not",
"(",
"r",
".",
"status_code",
">=",
"200",
"and",
"r",
".",
"status_code",
"<=",
"299",
")",
":",
"raise",
"Exception",
"(",
"\"An error occured, return code \"",
"+",
"str",
"(",
"r",
".",
"status_code",
")",
")",
"return",
"self",
".",
"_parseupload",
"(",
"r",
".",
"text",
")"
] | Add/upload an input file to the CLAM service. Supports proper file upload streaming.
project - the ID of the project you want to add the file to.
inputtemplate - The input template you want to use to add this file (InputTemplate instance)
sourcefile - The file you want to add: string containing a filename (or instance of ``file``)
Keyword arguments (optional but recommended!):
* ``filename`` - the filename on the server (will be same as sourcefile if not specified)
* ``metadata`` - A metadata object.
* ``metafile`` - A metadata file (filename)
Any other keyword arguments will be passed as metadata and matched with the input template's parameters.
Example::
client.addinputfile("myproject", "someinputtemplate", "/path/to/local/file")
With metadata, assuming such metadata parameters are defined::
client.addinputfile("myproject", "someinputtemplate", "/path/to/local/file", parameter1="blah", parameterX=3.5) | [
"Add",
"/",
"upload",
"an",
"input",
"file",
"to",
"the",
"CLAM",
"service",
".",
"Supports",
"proper",
"file",
"upload",
"streaming",
"."
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/client.py#L363-L450 |
proycon/clam | clam/common/client.py | CLAMClient.addinput | def addinput(self, project, inputtemplate, contents, **kwargs):
"""Add an input file to the CLAM service. Explictly providing the contents as a string. This is not suitable for large files as the contents are kept in memory! Use ``addinputfile()`` instead for large files.
project - the ID of the project you want to add the file to.
inputtemplate - The input template you want to use to add this file (InputTemplate instance)
contents - The contents for the file to add (string)
Keyword arguments:
* filename - the filename on the server (mandatory!)
* metadata - A metadata object.
* metafile - A metadata file (filename)
Any other keyword arguments will be passed as metadata and matched with the input template's parameters.
Example::
client.addinput("myproject", "someinputtemplate", "This is a test.", filename="test.txt")
With metadata, assuming such metadata parameters are defined::
client.addinput("myproject", "someinputtemplate", "This is a test.", filename="test.txt", parameter1="blah", parameterX=3.5))
"""
if isinstance( inputtemplate, str) or (sys.version < '3' and isinstance( inputtemplate, unicode)): #pylint: disable=undefined-variable
data = self.get(project) #causes an extra query to server
inputtemplate = data.inputtemplate(inputtemplate)
elif not isinstance(inputtemplate, clam.common.data.InputTemplate):
raise Exception("inputtemplate must be instance of InputTemplate. Get from CLAMData.inputtemplate(id)")
if 'filename' in kwargs:
filename = self.getinputfilename(inputtemplate, kwargs['filename'])
else:
raise Exception("No filename provided!")
data = {"contents": contents, 'inputtemplate': inputtemplate.id}
for key, value in kwargs.items():
if key == 'filename':
pass #nothing to do
elif key == 'metadata':
assert isinstance(value, clam.common.data.CLAMMetaData)
data['metadata'] = value.xml()
elif key == 'metafile':
data['metafile'] = open(value,'r')
else:
data[key] = value
requestparams = self.initrequest(data)
r = requests.post(self.url + project + '/input/' + filename,**requestparams)
if r.status_code == 400:
raise clam.common.data.BadRequest()
elif r.status_code == 401:
raise clam.common.data.AuthRequired()
elif r.status_code == 403:
if r.text[0] == '<':
#XML response
return self._parseupload(r.text)
else:
raise clam.common.data.PermissionDenied(r.text)
elif r.status_code == 404:
raise clam.common.data.NotFound(r.text)
elif r.status_code == 500:
raise clam.common.data.ServerError(r.text)
elif r.status_code == 405:
raise clam.common.data.ServerError("Server returned 405: Method not allowed for POST on " + self.url + project + '/input/' + filename)
elif r.status_code == 408:
raise clam.common.data.TimeOut()
elif not (r.status_code >= 200 and r.status_code <= 299):
raise Exception("An error occured, return code " + str(r.status_code))
return self._parseupload(r.text) | python | def addinput(self, project, inputtemplate, contents, **kwargs):
"""Add an input file to the CLAM service. Explictly providing the contents as a string. This is not suitable for large files as the contents are kept in memory! Use ``addinputfile()`` instead for large files.
project - the ID of the project you want to add the file to.
inputtemplate - The input template you want to use to add this file (InputTemplate instance)
contents - The contents for the file to add (string)
Keyword arguments:
* filename - the filename on the server (mandatory!)
* metadata - A metadata object.
* metafile - A metadata file (filename)
Any other keyword arguments will be passed as metadata and matched with the input template's parameters.
Example::
client.addinput("myproject", "someinputtemplate", "This is a test.", filename="test.txt")
With metadata, assuming such metadata parameters are defined::
client.addinput("myproject", "someinputtemplate", "This is a test.", filename="test.txt", parameter1="blah", parameterX=3.5))
"""
if isinstance( inputtemplate, str) or (sys.version < '3' and isinstance( inputtemplate, unicode)): #pylint: disable=undefined-variable
data = self.get(project) #causes an extra query to server
inputtemplate = data.inputtemplate(inputtemplate)
elif not isinstance(inputtemplate, clam.common.data.InputTemplate):
raise Exception("inputtemplate must be instance of InputTemplate. Get from CLAMData.inputtemplate(id)")
if 'filename' in kwargs:
filename = self.getinputfilename(inputtemplate, kwargs['filename'])
else:
raise Exception("No filename provided!")
data = {"contents": contents, 'inputtemplate': inputtemplate.id}
for key, value in kwargs.items():
if key == 'filename':
pass #nothing to do
elif key == 'metadata':
assert isinstance(value, clam.common.data.CLAMMetaData)
data['metadata'] = value.xml()
elif key == 'metafile':
data['metafile'] = open(value,'r')
else:
data[key] = value
requestparams = self.initrequest(data)
r = requests.post(self.url + project + '/input/' + filename,**requestparams)
if r.status_code == 400:
raise clam.common.data.BadRequest()
elif r.status_code == 401:
raise clam.common.data.AuthRequired()
elif r.status_code == 403:
if r.text[0] == '<':
#XML response
return self._parseupload(r.text)
else:
raise clam.common.data.PermissionDenied(r.text)
elif r.status_code == 404:
raise clam.common.data.NotFound(r.text)
elif r.status_code == 500:
raise clam.common.data.ServerError(r.text)
elif r.status_code == 405:
raise clam.common.data.ServerError("Server returned 405: Method not allowed for POST on " + self.url + project + '/input/' + filename)
elif r.status_code == 408:
raise clam.common.data.TimeOut()
elif not (r.status_code >= 200 and r.status_code <= 299):
raise Exception("An error occured, return code " + str(r.status_code))
return self._parseupload(r.text) | [
"def",
"addinput",
"(",
"self",
",",
"project",
",",
"inputtemplate",
",",
"contents",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"inputtemplate",
",",
"str",
")",
"or",
"(",
"sys",
".",
"version",
"<",
"'3'",
"and",
"isinstance",
"(",
"inputtemplate",
",",
"unicode",
")",
")",
":",
"#pylint: disable=undefined-variable",
"data",
"=",
"self",
".",
"get",
"(",
"project",
")",
"#causes an extra query to server",
"inputtemplate",
"=",
"data",
".",
"inputtemplate",
"(",
"inputtemplate",
")",
"elif",
"not",
"isinstance",
"(",
"inputtemplate",
",",
"clam",
".",
"common",
".",
"data",
".",
"InputTemplate",
")",
":",
"raise",
"Exception",
"(",
"\"inputtemplate must be instance of InputTemplate. Get from CLAMData.inputtemplate(id)\"",
")",
"if",
"'filename'",
"in",
"kwargs",
":",
"filename",
"=",
"self",
".",
"getinputfilename",
"(",
"inputtemplate",
",",
"kwargs",
"[",
"'filename'",
"]",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"No filename provided!\"",
")",
"data",
"=",
"{",
"\"contents\"",
":",
"contents",
",",
"'inputtemplate'",
":",
"inputtemplate",
".",
"id",
"}",
"for",
"key",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"key",
"==",
"'filename'",
":",
"pass",
"#nothing to do",
"elif",
"key",
"==",
"'metadata'",
":",
"assert",
"isinstance",
"(",
"value",
",",
"clam",
".",
"common",
".",
"data",
".",
"CLAMMetaData",
")",
"data",
"[",
"'metadata'",
"]",
"=",
"value",
".",
"xml",
"(",
")",
"elif",
"key",
"==",
"'metafile'",
":",
"data",
"[",
"'metafile'",
"]",
"=",
"open",
"(",
"value",
",",
"'r'",
")",
"else",
":",
"data",
"[",
"key",
"]",
"=",
"value",
"requestparams",
"=",
"self",
".",
"initrequest",
"(",
"data",
")",
"r",
"=",
"requests",
".",
"post",
"(",
"self",
".",
"url",
"+",
"project",
"+",
"'/input/'",
"+",
"filename",
",",
"*",
"*",
"requestparams",
")",
"if",
"r",
".",
"status_code",
"==",
"400",
":",
"raise",
"clam",
".",
"common",
".",
"data",
".",
"BadRequest",
"(",
")",
"elif",
"r",
".",
"status_code",
"==",
"401",
":",
"raise",
"clam",
".",
"common",
".",
"data",
".",
"AuthRequired",
"(",
")",
"elif",
"r",
".",
"status_code",
"==",
"403",
":",
"if",
"r",
".",
"text",
"[",
"0",
"]",
"==",
"'<'",
":",
"#XML response",
"return",
"self",
".",
"_parseupload",
"(",
"r",
".",
"text",
")",
"else",
":",
"raise",
"clam",
".",
"common",
".",
"data",
".",
"PermissionDenied",
"(",
"r",
".",
"text",
")",
"elif",
"r",
".",
"status_code",
"==",
"404",
":",
"raise",
"clam",
".",
"common",
".",
"data",
".",
"NotFound",
"(",
"r",
".",
"text",
")",
"elif",
"r",
".",
"status_code",
"==",
"500",
":",
"raise",
"clam",
".",
"common",
".",
"data",
".",
"ServerError",
"(",
"r",
".",
"text",
")",
"elif",
"r",
".",
"status_code",
"==",
"405",
":",
"raise",
"clam",
".",
"common",
".",
"data",
".",
"ServerError",
"(",
"\"Server returned 405: Method not allowed for POST on \"",
"+",
"self",
".",
"url",
"+",
"project",
"+",
"'/input/'",
"+",
"filename",
")",
"elif",
"r",
".",
"status_code",
"==",
"408",
":",
"raise",
"clam",
".",
"common",
".",
"data",
".",
"TimeOut",
"(",
")",
"elif",
"not",
"(",
"r",
".",
"status_code",
">=",
"200",
"and",
"r",
".",
"status_code",
"<=",
"299",
")",
":",
"raise",
"Exception",
"(",
"\"An error occured, return code \"",
"+",
"str",
"(",
"r",
".",
"status_code",
")",
")",
"return",
"self",
".",
"_parseupload",
"(",
"r",
".",
"text",
")"
] | Add an input file to the CLAM service. Explictly providing the contents as a string. This is not suitable for large files as the contents are kept in memory! Use ``addinputfile()`` instead for large files.
project - the ID of the project you want to add the file to.
inputtemplate - The input template you want to use to add this file (InputTemplate instance)
contents - The contents for the file to add (string)
Keyword arguments:
* filename - the filename on the server (mandatory!)
* metadata - A metadata object.
* metafile - A metadata file (filename)
Any other keyword arguments will be passed as metadata and matched with the input template's parameters.
Example::
client.addinput("myproject", "someinputtemplate", "This is a test.", filename="test.txt")
With metadata, assuming such metadata parameters are defined::
client.addinput("myproject", "someinputtemplate", "This is a test.", filename="test.txt", parameter1="blah", parameterX=3.5)) | [
"Add",
"an",
"input",
"file",
"to",
"the",
"CLAM",
"service",
".",
"Explictly",
"providing",
"the",
"contents",
"as",
"a",
"string",
".",
"This",
"is",
"not",
"suitable",
"for",
"large",
"files",
"as",
"the",
"contents",
"are",
"kept",
"in",
"memory!",
"Use",
"addinputfile",
"()",
"instead",
"for",
"large",
"files",
"."
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/client.py#L454-L526 |
proycon/clam | clam/common/client.py | CLAMClient.upload | def upload(self,project, inputtemplate, sourcefile, **kwargs):
"""Alias for ``addinputfile()``"""
return self.addinputfile(project, inputtemplate,sourcefile, **kwargs) | python | def upload(self,project, inputtemplate, sourcefile, **kwargs):
"""Alias for ``addinputfile()``"""
return self.addinputfile(project, inputtemplate,sourcefile, **kwargs) | [
"def",
"upload",
"(",
"self",
",",
"project",
",",
"inputtemplate",
",",
"sourcefile",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"addinputfile",
"(",
"project",
",",
"inputtemplate",
",",
"sourcefile",
",",
"*",
"*",
"kwargs",
")"
] | Alias for ``addinputfile()`` | [
"Alias",
"for",
"addinputfile",
"()"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/client.py#L530-L532 |
proycon/clam | clam/common/client.py | CLAMClient.download | def download(self, project, filename, targetfilename, loadmetadata=None):
"""Download an output file"""
if loadmetadata is None: loadmetadata = self.loadmetadata
f = clam.common.data.CLAMOutputFile(self.url + project, filename, loadmetadata, self)
f.copy(targetfilename) | python | def download(self, project, filename, targetfilename, loadmetadata=None):
"""Download an output file"""
if loadmetadata is None: loadmetadata = self.loadmetadata
f = clam.common.data.CLAMOutputFile(self.url + project, filename, loadmetadata, self)
f.copy(targetfilename) | [
"def",
"download",
"(",
"self",
",",
"project",
",",
"filename",
",",
"targetfilename",
",",
"loadmetadata",
"=",
"None",
")",
":",
"if",
"loadmetadata",
"is",
"None",
":",
"loadmetadata",
"=",
"self",
".",
"loadmetadata",
"f",
"=",
"clam",
".",
"common",
".",
"data",
".",
"CLAMOutputFile",
"(",
"self",
".",
"url",
"+",
"project",
",",
"filename",
",",
"loadmetadata",
",",
"self",
")",
"f",
".",
"copy",
"(",
"targetfilename",
")"
] | Download an output file | [
"Download",
"an",
"output",
"file"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/client.py#L534-L538 |
proycon/clam | clam/common/parameters.py | AbstractParameter.validate | def validate(self,value):
"""Validate the parameter"""
if self.validator is not None:
try:
valid = self.validator(value)
except Exception as e:
import pdb; pdb.set_trace()
if isinstance(valid, tuple) and len(valid) == 2:
valid, errormsg = valid
elif isinstance(valid, bool):
errormsg = "Invalid value"
else:
raise TypeError("Custom validator must return a boolean or a (bool, errormsg) tuple.")
if valid:
self.error = None
else:
self.error = errormsg
return valid
else:
self.error = None #reset error
return True | python | def validate(self,value):
"""Validate the parameter"""
if self.validator is not None:
try:
valid = self.validator(value)
except Exception as e:
import pdb; pdb.set_trace()
if isinstance(valid, tuple) and len(valid) == 2:
valid, errormsg = valid
elif isinstance(valid, bool):
errormsg = "Invalid value"
else:
raise TypeError("Custom validator must return a boolean or a (bool, errormsg) tuple.")
if valid:
self.error = None
else:
self.error = errormsg
return valid
else:
self.error = None #reset error
return True | [
"def",
"validate",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"validator",
"is",
"not",
"None",
":",
"try",
":",
"valid",
"=",
"self",
".",
"validator",
"(",
"value",
")",
"except",
"Exception",
"as",
"e",
":",
"import",
"pdb",
"pdb",
".",
"set_trace",
"(",
")",
"if",
"isinstance",
"(",
"valid",
",",
"tuple",
")",
"and",
"len",
"(",
"valid",
")",
"==",
"2",
":",
"valid",
",",
"errormsg",
"=",
"valid",
"elif",
"isinstance",
"(",
"valid",
",",
"bool",
")",
":",
"errormsg",
"=",
"\"Invalid value\"",
"else",
":",
"raise",
"TypeError",
"(",
"\"Custom validator must return a boolean or a (bool, errormsg) tuple.\"",
")",
"if",
"valid",
":",
"self",
".",
"error",
"=",
"None",
"else",
":",
"self",
".",
"error",
"=",
"errormsg",
"return",
"valid",
"else",
":",
"self",
".",
"error",
"=",
"None",
"#reset error",
"return",
"True"
] | Validate the parameter | [
"Validate",
"the",
"parameter"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/parameters.py#L96-L116 |
proycon/clam | clam/common/parameters.py | AbstractParameter.compilearg | def compilearg(self):
"""This method compiles the parameter into syntax that can be used on the shell, such as for example: --paramflag=value"""
if self.paramflag and self.paramflag[-1] == '=' or self.nospace:
sep = ''
elif self.paramflag:
sep = ' '
else:
return str(self.value)
return self.paramflag + sep + str(self.value) | python | def compilearg(self):
"""This method compiles the parameter into syntax that can be used on the shell, such as for example: --paramflag=value"""
if self.paramflag and self.paramflag[-1] == '=' or self.nospace:
sep = ''
elif self.paramflag:
sep = ' '
else:
return str(self.value)
return self.paramflag + sep + str(self.value) | [
"def",
"compilearg",
"(",
"self",
")",
":",
"if",
"self",
".",
"paramflag",
"and",
"self",
".",
"paramflag",
"[",
"-",
"1",
"]",
"==",
"'='",
"or",
"self",
".",
"nospace",
":",
"sep",
"=",
"''",
"elif",
"self",
".",
"paramflag",
":",
"sep",
"=",
"' '",
"else",
":",
"return",
"str",
"(",
"self",
".",
"value",
")",
"return",
"self",
".",
"paramflag",
"+",
"sep",
"+",
"str",
"(",
"self",
".",
"value",
")"
] | This method compiles the parameter into syntax that can be used on the shell, such as for example: --paramflag=value | [
"This",
"method",
"compiles",
"the",
"parameter",
"into",
"syntax",
"that",
"can",
"be",
"used",
"on",
"the",
"shell",
"such",
"as",
"for",
"example",
":",
"--",
"paramflag",
"=",
"value"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/parameters.py#L118-L126 |
proycon/clam | clam/common/parameters.py | AbstractParameter.xml | def xml(self, indent = ""):
"""This methods renders an XML representation of this parameter, along with
its selected value, and feedback on validation errors"""
xml = indent + "<" + self.__class__.__name__
xml += ' id="'+self.id + '"'
xml += ' name="'+xmlescape(self.name) + '"'
xml += ' description="'+xmlescape(self.description) + '"'
if self.paramflag:
xml += ' flag="'+self.paramflag + '"'
for key, v in self.kwargs.items():
if key not in ('value','error','name','description','flag','paramflag', 'validator'):
if isinstance(v, bool):
xml += ' ' + key + '="' + str(int(v))+ '"'
elif isinstance(v, list):
xml += ' ' + key + '="'+xmlescape(",".join(v))+ '"'
elif isinstance(v, str) or ( sys.version < '3' and isinstance(v, unicode)): #pylint: disable=undefined-variable
xml += ' ' + key + '="'+xmlescape(v)+ '"'
else:
xml += ' ' + key + '="'+xmlescape(str(v))+ '"'
if self.hasvalue:
if sys.version < '3':
xml += ' value="'+xmlescape(unicode(self.value)) + '"' #pylint: disable=undefined-variable
else:
xml += ' value="'+xmlescape(str(self.value)) + '"'
if self.error:
xml += ' error="'+xmlescape(self.error) + '"'
xml += " />"
return xml | python | def xml(self, indent = ""):
"""This methods renders an XML representation of this parameter, along with
its selected value, and feedback on validation errors"""
xml = indent + "<" + self.__class__.__name__
xml += ' id="'+self.id + '"'
xml += ' name="'+xmlescape(self.name) + '"'
xml += ' description="'+xmlescape(self.description) + '"'
if self.paramflag:
xml += ' flag="'+self.paramflag + '"'
for key, v in self.kwargs.items():
if key not in ('value','error','name','description','flag','paramflag', 'validator'):
if isinstance(v, bool):
xml += ' ' + key + '="' + str(int(v))+ '"'
elif isinstance(v, list):
xml += ' ' + key + '="'+xmlescape(",".join(v))+ '"'
elif isinstance(v, str) or ( sys.version < '3' and isinstance(v, unicode)): #pylint: disable=undefined-variable
xml += ' ' + key + '="'+xmlescape(v)+ '"'
else:
xml += ' ' + key + '="'+xmlescape(str(v))+ '"'
if self.hasvalue:
if sys.version < '3':
xml += ' value="'+xmlescape(unicode(self.value)) + '"' #pylint: disable=undefined-variable
else:
xml += ' value="'+xmlescape(str(self.value)) + '"'
if self.error:
xml += ' error="'+xmlescape(self.error) + '"'
xml += " />"
return xml | [
"def",
"xml",
"(",
"self",
",",
"indent",
"=",
"\"\"",
")",
":",
"xml",
"=",
"indent",
"+",
"\"<\"",
"+",
"self",
".",
"__class__",
".",
"__name__",
"xml",
"+=",
"' id=\"'",
"+",
"self",
".",
"id",
"+",
"'\"'",
"xml",
"+=",
"' name=\"'",
"+",
"xmlescape",
"(",
"self",
".",
"name",
")",
"+",
"'\"'",
"xml",
"+=",
"' description=\"'",
"+",
"xmlescape",
"(",
"self",
".",
"description",
")",
"+",
"'\"'",
"if",
"self",
".",
"paramflag",
":",
"xml",
"+=",
"' flag=\"'",
"+",
"self",
".",
"paramflag",
"+",
"'\"'",
"for",
"key",
",",
"v",
"in",
"self",
".",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"key",
"not",
"in",
"(",
"'value'",
",",
"'error'",
",",
"'name'",
",",
"'description'",
",",
"'flag'",
",",
"'paramflag'",
",",
"'validator'",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"bool",
")",
":",
"xml",
"+=",
"' '",
"+",
"key",
"+",
"'=\"'",
"+",
"str",
"(",
"int",
"(",
"v",
")",
")",
"+",
"'\"'",
"elif",
"isinstance",
"(",
"v",
",",
"list",
")",
":",
"xml",
"+=",
"' '",
"+",
"key",
"+",
"'=\"'",
"+",
"xmlescape",
"(",
"\",\"",
".",
"join",
"(",
"v",
")",
")",
"+",
"'\"'",
"elif",
"isinstance",
"(",
"v",
",",
"str",
")",
"or",
"(",
"sys",
".",
"version",
"<",
"'3'",
"and",
"isinstance",
"(",
"v",
",",
"unicode",
")",
")",
":",
"#pylint: disable=undefined-variable",
"xml",
"+=",
"' '",
"+",
"key",
"+",
"'=\"'",
"+",
"xmlescape",
"(",
"v",
")",
"+",
"'\"'",
"else",
":",
"xml",
"+=",
"' '",
"+",
"key",
"+",
"'=\"'",
"+",
"xmlescape",
"(",
"str",
"(",
"v",
")",
")",
"+",
"'\"'",
"if",
"self",
".",
"hasvalue",
":",
"if",
"sys",
".",
"version",
"<",
"'3'",
":",
"xml",
"+=",
"' value=\"'",
"+",
"xmlescape",
"(",
"unicode",
"(",
"self",
".",
"value",
")",
")",
"+",
"'\"'",
"#pylint: disable=undefined-variable",
"else",
":",
"xml",
"+=",
"' value=\"'",
"+",
"xmlescape",
"(",
"str",
"(",
"self",
".",
"value",
")",
")",
"+",
"'\"'",
"if",
"self",
".",
"error",
":",
"xml",
"+=",
"' error=\"'",
"+",
"xmlescape",
"(",
"self",
".",
"error",
")",
"+",
"'\"'",
"xml",
"+=",
"\" />\"",
"return",
"xml"
] | This methods renders an XML representation of this parameter, along with
its selected value, and feedback on validation errors | [
"This",
"methods",
"renders",
"an",
"XML",
"representation",
"of",
"this",
"parameter",
"along",
"with",
"its",
"selected",
"value",
"and",
"feedback",
"on",
"validation",
"errors"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/parameters.py#L128-L155 |
proycon/clam | clam/common/parameters.py | AbstractParameter.set | def set(self, value):
"""This parameter method attempts to set a specific value for this parameter. The value will be validated first, and if it can not be set. An error message will be set in the error property of this parameter"""
if self.validate(value):
#print "Parameter " + self.id + " successfully set to " + repr(value)
self.hasvalue = True
self.value = value
return True
else:
#print "Parameter " + self.id + " COULD NOT BE set to " + repr(value)
return False | python | def set(self, value):
"""This parameter method attempts to set a specific value for this parameter. The value will be validated first, and if it can not be set. An error message will be set in the error property of this parameter"""
if self.validate(value):
#print "Parameter " + self.id + " successfully set to " + repr(value)
self.hasvalue = True
self.value = value
return True
else:
#print "Parameter " + self.id + " COULD NOT BE set to " + repr(value)
return False | [
"def",
"set",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"validate",
"(",
"value",
")",
":",
"#print \"Parameter \" + self.id + \" successfully set to \" + repr(value)",
"self",
".",
"hasvalue",
"=",
"True",
"self",
".",
"value",
"=",
"value",
"return",
"True",
"else",
":",
"#print \"Parameter \" + self.id + \" COULD NOT BE set to \" + repr(value)",
"return",
"False"
] | This parameter method attempts to set a specific value for this parameter. The value will be validated first, and if it can not be set. An error message will be set in the error property of this parameter | [
"This",
"parameter",
"method",
"attempts",
"to",
"set",
"a",
"specific",
"value",
"for",
"this",
"parameter",
".",
"The",
"value",
"will",
"be",
"validated",
"first",
"and",
"if",
"it",
"can",
"not",
"be",
"set",
".",
"An",
"error",
"message",
"will",
"be",
"set",
"in",
"the",
"error",
"property",
"of",
"this",
"parameter"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/parameters.py#L182-L191 |
proycon/clam | clam/common/parameters.py | AbstractParameter.access | def access(self, user):
"""This method checks if the given user has access to see/set this parameter, based on the denyusers and/or allowusers option."""
if self.denyusers:
if user in self.denyusers:
return False
if self.allowusers:
if not user in self.allowusers:
return False
return True | python | def access(self, user):
"""This method checks if the given user has access to see/set this parameter, based on the denyusers and/or allowusers option."""
if self.denyusers:
if user in self.denyusers:
return False
if self.allowusers:
if not user in self.allowusers:
return False
return True | [
"def",
"access",
"(",
"self",
",",
"user",
")",
":",
"if",
"self",
".",
"denyusers",
":",
"if",
"user",
"in",
"self",
".",
"denyusers",
":",
"return",
"False",
"if",
"self",
".",
"allowusers",
":",
"if",
"not",
"user",
"in",
"self",
".",
"allowusers",
":",
"return",
"False",
"return",
"True"
] | This method checks if the given user has access to see/set this parameter, based on the denyusers and/or allowusers option. | [
"This",
"method",
"checks",
"if",
"the",
"given",
"user",
"has",
"access",
"to",
"see",
"/",
"set",
"this",
"parameter",
"based",
"on",
"the",
"denyusers",
"and",
"/",
"or",
"allowusers",
"option",
"."
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/parameters.py#L201-L209 |
proycon/clam | clam/common/parameters.py | AbstractParameter.fromxml | def fromxml(node):
"""Create a Parameter instance (of any class derived from AbstractParameter!) given its XML description. Node can be a string containing XML or an lxml _Element"""
if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access
node = ElementTree.parse(StringIO(node)).getroot()
if node.tag in globals():
id = ''
paramflag = ''
name = ''
description = ''
kwargs = {}
error = None
for attrib, value in node.attrib.items():
if attrib == 'id':
id = value
elif attrib == 'paramflag':
paramflag = value
elif attrib == 'name':
name = value
elif attrib == 'description':
description = value
elif attrib == 'error':
error = value
else:
kwargs[attrib] = value
#extra parsing for choice parameter (TODO: put in a better spot)
if 'multi' in kwargs and (kwargs['multi'] == 'yes' or kwargs['multi'] == '1' or kwargs['multi'] == 'true'):
kwargs['value'] = []
for subtag in node: #parse possible subtags
if subtag.tag == 'choice': #extra parsing for choice parameter (TODO: put in a better spot)
if 'choices' not in kwargs: kwargs['choices'] = {}
kwargs['choices'][subtag.attrib['id']] = subtag.text
if 'selected' in subtag.attrib and (subtag.attrib['selected'] == '1' or subtag.attrib['selected'] == 'yes'):
if 'multi' in kwargs and (kwargs['multi'] == 'yes' or kwargs['multi'] == '1' or kwargs['multi'] == 'true'):
kwargs['value'].append(subtag.attrib['id'])
else:
kwargs['value'] = subtag.attrib['id']
parameter = globals()[node.tag](id, name, description, **kwargs) #return parameter instance
if error:
parameter.error = error #prevent error from getting reset
return parameter
else:
raise Exception("No such parameter exists: " + node.tag) | python | def fromxml(node):
"""Create a Parameter instance (of any class derived from AbstractParameter!) given its XML description. Node can be a string containing XML or an lxml _Element"""
if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access
node = ElementTree.parse(StringIO(node)).getroot()
if node.tag in globals():
id = ''
paramflag = ''
name = ''
description = ''
kwargs = {}
error = None
for attrib, value in node.attrib.items():
if attrib == 'id':
id = value
elif attrib == 'paramflag':
paramflag = value
elif attrib == 'name':
name = value
elif attrib == 'description':
description = value
elif attrib == 'error':
error = value
else:
kwargs[attrib] = value
#extra parsing for choice parameter (TODO: put in a better spot)
if 'multi' in kwargs and (kwargs['multi'] == 'yes' or kwargs['multi'] == '1' or kwargs['multi'] == 'true'):
kwargs['value'] = []
for subtag in node: #parse possible subtags
if subtag.tag == 'choice': #extra parsing for choice parameter (TODO: put in a better spot)
if 'choices' not in kwargs: kwargs['choices'] = {}
kwargs['choices'][subtag.attrib['id']] = subtag.text
if 'selected' in subtag.attrib and (subtag.attrib['selected'] == '1' or subtag.attrib['selected'] == 'yes'):
if 'multi' in kwargs and (kwargs['multi'] == 'yes' or kwargs['multi'] == '1' or kwargs['multi'] == 'true'):
kwargs['value'].append(subtag.attrib['id'])
else:
kwargs['value'] = subtag.attrib['id']
parameter = globals()[node.tag](id, name, description, **kwargs) #return parameter instance
if error:
parameter.error = error #prevent error from getting reset
return parameter
else:
raise Exception("No such parameter exists: " + node.tag) | [
"def",
"fromxml",
"(",
"node",
")",
":",
"if",
"not",
"isinstance",
"(",
"node",
",",
"ElementTree",
".",
"_Element",
")",
":",
"#pylint: disable=protected-access",
"node",
"=",
"ElementTree",
".",
"parse",
"(",
"StringIO",
"(",
"node",
")",
")",
".",
"getroot",
"(",
")",
"if",
"node",
".",
"tag",
"in",
"globals",
"(",
")",
":",
"id",
"=",
"''",
"paramflag",
"=",
"''",
"name",
"=",
"''",
"description",
"=",
"''",
"kwargs",
"=",
"{",
"}",
"error",
"=",
"None",
"for",
"attrib",
",",
"value",
"in",
"node",
".",
"attrib",
".",
"items",
"(",
")",
":",
"if",
"attrib",
"==",
"'id'",
":",
"id",
"=",
"value",
"elif",
"attrib",
"==",
"'paramflag'",
":",
"paramflag",
"=",
"value",
"elif",
"attrib",
"==",
"'name'",
":",
"name",
"=",
"value",
"elif",
"attrib",
"==",
"'description'",
":",
"description",
"=",
"value",
"elif",
"attrib",
"==",
"'error'",
":",
"error",
"=",
"value",
"else",
":",
"kwargs",
"[",
"attrib",
"]",
"=",
"value",
"#extra parsing for choice parameter (TODO: put in a better spot)",
"if",
"'multi'",
"in",
"kwargs",
"and",
"(",
"kwargs",
"[",
"'multi'",
"]",
"==",
"'yes'",
"or",
"kwargs",
"[",
"'multi'",
"]",
"==",
"'1'",
"or",
"kwargs",
"[",
"'multi'",
"]",
"==",
"'true'",
")",
":",
"kwargs",
"[",
"'value'",
"]",
"=",
"[",
"]",
"for",
"subtag",
"in",
"node",
":",
"#parse possible subtags",
"if",
"subtag",
".",
"tag",
"==",
"'choice'",
":",
"#extra parsing for choice parameter (TODO: put in a better spot)",
"if",
"'choices'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'choices'",
"]",
"=",
"{",
"}",
"kwargs",
"[",
"'choices'",
"]",
"[",
"subtag",
".",
"attrib",
"[",
"'id'",
"]",
"]",
"=",
"subtag",
".",
"text",
"if",
"'selected'",
"in",
"subtag",
".",
"attrib",
"and",
"(",
"subtag",
".",
"attrib",
"[",
"'selected'",
"]",
"==",
"'1'",
"or",
"subtag",
".",
"attrib",
"[",
"'selected'",
"]",
"==",
"'yes'",
")",
":",
"if",
"'multi'",
"in",
"kwargs",
"and",
"(",
"kwargs",
"[",
"'multi'",
"]",
"==",
"'yes'",
"or",
"kwargs",
"[",
"'multi'",
"]",
"==",
"'1'",
"or",
"kwargs",
"[",
"'multi'",
"]",
"==",
"'true'",
")",
":",
"kwargs",
"[",
"'value'",
"]",
".",
"append",
"(",
"subtag",
".",
"attrib",
"[",
"'id'",
"]",
")",
"else",
":",
"kwargs",
"[",
"'value'",
"]",
"=",
"subtag",
".",
"attrib",
"[",
"'id'",
"]",
"parameter",
"=",
"globals",
"(",
")",
"[",
"node",
".",
"tag",
"]",
"(",
"id",
",",
"name",
",",
"description",
",",
"*",
"*",
"kwargs",
")",
"#return parameter instance",
"if",
"error",
":",
"parameter",
".",
"error",
"=",
"error",
"#prevent error from getting reset",
"return",
"parameter",
"else",
":",
"raise",
"Exception",
"(",
"\"No such parameter exists: \"",
"+",
"node",
".",
"tag",
")"
] | Create a Parameter instance (of any class derived from AbstractParameter!) given its XML description. Node can be a string containing XML or an lxml _Element | [
"Create",
"a",
"Parameter",
"instance",
"(",
"of",
"any",
"class",
"derived",
"from",
"AbstractParameter!",
")",
"given",
"its",
"XML",
"description",
".",
"Node",
"can",
"be",
"a",
"string",
"containing",
"XML",
"or",
"an",
"lxml",
"_Element"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/parameters.py#L212-L256 |
proycon/clam | clam/common/parameters.py | BooleanParameter.set | def set(self, value = True):
"""Set the boolean parameter"""
value = value in (True,1) or ( (isinstance(value, str) or (sys.version < '3' and isinstance(value, unicode))) and (value.lower() in ("1","yes","true","enabled"))) #pylint: disable=undefined-variable
return super(BooleanParameter,self).set(value) | python | def set(self, value = True):
"""Set the boolean parameter"""
value = value in (True,1) or ( (isinstance(value, str) or (sys.version < '3' and isinstance(value, unicode))) and (value.lower() in ("1","yes","true","enabled"))) #pylint: disable=undefined-variable
return super(BooleanParameter,self).set(value) | [
"def",
"set",
"(",
"self",
",",
"value",
"=",
"True",
")",
":",
"value",
"=",
"value",
"in",
"(",
"True",
",",
"1",
")",
"or",
"(",
"(",
"isinstance",
"(",
"value",
",",
"str",
")",
"or",
"(",
"sys",
".",
"version",
"<",
"'3'",
"and",
"isinstance",
"(",
"value",
",",
"unicode",
")",
")",
")",
"and",
"(",
"value",
".",
"lower",
"(",
")",
"in",
"(",
"\"1\"",
",",
"\"yes\"",
",",
"\"true\"",
",",
"\"enabled\"",
")",
")",
")",
"#pylint: disable=undefined-variable",
"return",
"super",
"(",
"BooleanParameter",
",",
"self",
")",
".",
"set",
"(",
"value",
")"
] | Set the boolean parameter | [
"Set",
"the",
"boolean",
"parameter"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/parameters.py#L280-L283 |
proycon/clam | clam/common/parameters.py | BooleanParameter.valuefrompostdata | def valuefrompostdata(self, postdata):
"""This parameter method searches the POST data and retrieves the values it needs. It does not set the value yet though, but simply returns it. Needs to be explicitly passed to parameter.set(). It typically returns the default None when something is left unset (but that default can be overridden)"""
if self.id in postdata:
if ( (isinstance(postdata[self.id], bool) and postdata[self.id]) or postdata[self.id] == 1 or postdata[self.id].lower() in ('true','yes','enabled','1')):
return True #postdata[self.id]
else:
return False
else:
return None | python | def valuefrompostdata(self, postdata):
"""This parameter method searches the POST data and retrieves the values it needs. It does not set the value yet though, but simply returns it. Needs to be explicitly passed to parameter.set(). It typically returns the default None when something is left unset (but that default can be overridden)"""
if self.id in postdata:
if ( (isinstance(postdata[self.id], bool) and postdata[self.id]) or postdata[self.id] == 1 or postdata[self.id].lower() in ('true','yes','enabled','1')):
return True #postdata[self.id]
else:
return False
else:
return None | [
"def",
"valuefrompostdata",
"(",
"self",
",",
"postdata",
")",
":",
"if",
"self",
".",
"id",
"in",
"postdata",
":",
"if",
"(",
"(",
"isinstance",
"(",
"postdata",
"[",
"self",
".",
"id",
"]",
",",
"bool",
")",
"and",
"postdata",
"[",
"self",
".",
"id",
"]",
")",
"or",
"postdata",
"[",
"self",
".",
"id",
"]",
"==",
"1",
"or",
"postdata",
"[",
"self",
".",
"id",
"]",
".",
"lower",
"(",
")",
"in",
"(",
"'true'",
",",
"'yes'",
",",
"'enabled'",
",",
"'1'",
")",
")",
":",
"return",
"True",
"#postdata[self.id]",
"else",
":",
"return",
"False",
"else",
":",
"return",
"None"
] | This parameter method searches the POST data and retrieves the values it needs. It does not set the value yet though, but simply returns it. Needs to be explicitly passed to parameter.set(). It typically returns the default None when something is left unset (but that default can be overridden) | [
"This",
"parameter",
"method",
"searches",
"the",
"POST",
"data",
"and",
"retrieves",
"the",
"values",
"it",
"needs",
".",
"It",
"does",
"not",
"set",
"the",
"value",
"yet",
"though",
"but",
"simply",
"returns",
"it",
".",
"Needs",
"to",
"be",
"explicitly",
"passed",
"to",
"parameter",
".",
"set",
"()",
".",
"It",
"typically",
"returns",
"the",
"default",
"None",
"when",
"something",
"is",
"left",
"unset",
"(",
"but",
"that",
"default",
"can",
"be",
"overridden",
")"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/parameters.py#L298-L306 |
proycon/clam | clam/common/parameters.py | ChoiceParameter.compilearg | def compilearg(self):
"""This method compiles the parameter into syntax that can be used on the shell, such as -paramflag=value"""
if isinstance(self.value,list):
value = self.delimiter.join(self.value)
else:
value = self.value
if value.find(" ") >= 0:
value = '"' + value + '"' #wrap all in quotes
#for some odd, reason this produced an error, as if we're not an instance of choiceparameter
#return super(ChoiceParameter,self).compilearg(value)
#workaround:
if self.paramflag and self.paramflag[-1] == '=' or self.nospace:
sep = ''
elif self.paramflag:
sep = ' '
else:
return str(value)
return self.paramflag + sep + str(value) | python | def compilearg(self):
"""This method compiles the parameter into syntax that can be used on the shell, such as -paramflag=value"""
if isinstance(self.value,list):
value = self.delimiter.join(self.value)
else:
value = self.value
if value.find(" ") >= 0:
value = '"' + value + '"' #wrap all in quotes
#for some odd, reason this produced an error, as if we're not an instance of choiceparameter
#return super(ChoiceParameter,self).compilearg(value)
#workaround:
if self.paramflag and self.paramflag[-1] == '=' or self.nospace:
sep = ''
elif self.paramflag:
sep = ' '
else:
return str(value)
return self.paramflag + sep + str(value) | [
"def",
"compilearg",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"value",
",",
"list",
")",
":",
"value",
"=",
"self",
".",
"delimiter",
".",
"join",
"(",
"self",
".",
"value",
")",
"else",
":",
"value",
"=",
"self",
".",
"value",
"if",
"value",
".",
"find",
"(",
"\" \"",
")",
">=",
"0",
":",
"value",
"=",
"'\"'",
"+",
"value",
"+",
"'\"'",
"#wrap all in quotes",
"#for some odd, reason this produced an error, as if we're not an instance of choiceparameter",
"#return super(ChoiceParameter,self).compilearg(value)",
"#workaround:",
"if",
"self",
".",
"paramflag",
"and",
"self",
".",
"paramflag",
"[",
"-",
"1",
"]",
"==",
"'='",
"or",
"self",
".",
"nospace",
":",
"sep",
"=",
"''",
"elif",
"self",
".",
"paramflag",
":",
"sep",
"=",
"' '",
"else",
":",
"return",
"str",
"(",
"value",
")",
"return",
"self",
".",
"paramflag",
"+",
"sep",
"+",
"str",
"(",
"value",
")"
] | This method compiles the parameter into syntax that can be used on the shell, such as -paramflag=value | [
"This",
"method",
"compiles",
"the",
"parameter",
"into",
"syntax",
"that",
"can",
"be",
"used",
"on",
"the",
"shell",
"such",
"as",
"-",
"paramflag",
"=",
"value"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/parameters.py#L438-L457 |
proycon/clam | clam/common/parameters.py | ChoiceParameter.xml | def xml(self, indent = ""):
"""This methods renders an XML representation of this parameter, along with
its selected value, and feedback on validation errors"""
xml = indent + "<" + self.__class__.__name__
xml += ' id="'+self.id + '"'
xml += ' name="'+xmlescape(self.name) + '"'
xml += ' description="'+xmlescape(self.description) + '"'
if self.paramflag:
xml += ' flag="'+self.paramflag + '"'
if self.multi:
xml += ' multi="true"'
for key, value in self.kwargs.items():
if key != 'choices' and key != 'default' and key != 'flag' and key != 'paramflag':
if isinstance(value, bool):
xml += ' ' + key + '="' + str(int(value))+ '"'
elif isinstance(value, list):
xml += ' ' + key + '="'+",".join(value)+ '"'
else:
xml += ' ' + key + '="'+xmlescape(value)+ '"'
if self.error:
xml += ' error="'+self.error + '"'
xml += ">"
for key, value in self.choices:
if self.value == key or (isinstance(self.value ,list) and key in self.value):
xml += " <choice id=\""+key+"\" selected=\"1\">" + xmlescape(value) + "</choice>"
else:
xml += " <choice id=\""+key+"\">" + xmlescape(value) + "</choice>"
xml += "</" + self.__class__.__name__ + ">"
return xml | python | def xml(self, indent = ""):
"""This methods renders an XML representation of this parameter, along with
its selected value, and feedback on validation errors"""
xml = indent + "<" + self.__class__.__name__
xml += ' id="'+self.id + '"'
xml += ' name="'+xmlescape(self.name) + '"'
xml += ' description="'+xmlescape(self.description) + '"'
if self.paramflag:
xml += ' flag="'+self.paramflag + '"'
if self.multi:
xml += ' multi="true"'
for key, value in self.kwargs.items():
if key != 'choices' and key != 'default' and key != 'flag' and key != 'paramflag':
if isinstance(value, bool):
xml += ' ' + key + '="' + str(int(value))+ '"'
elif isinstance(value, list):
xml += ' ' + key + '="'+",".join(value)+ '"'
else:
xml += ' ' + key + '="'+xmlescape(value)+ '"'
if self.error:
xml += ' error="'+self.error + '"'
xml += ">"
for key, value in self.choices:
if self.value == key or (isinstance(self.value ,list) and key in self.value):
xml += " <choice id=\""+key+"\" selected=\"1\">" + xmlescape(value) + "</choice>"
else:
xml += " <choice id=\""+key+"\">" + xmlescape(value) + "</choice>"
xml += "</" + self.__class__.__name__ + ">"
return xml | [
"def",
"xml",
"(",
"self",
",",
"indent",
"=",
"\"\"",
")",
":",
"xml",
"=",
"indent",
"+",
"\"<\"",
"+",
"self",
".",
"__class__",
".",
"__name__",
"xml",
"+=",
"' id=\"'",
"+",
"self",
".",
"id",
"+",
"'\"'",
"xml",
"+=",
"' name=\"'",
"+",
"xmlescape",
"(",
"self",
".",
"name",
")",
"+",
"'\"'",
"xml",
"+=",
"' description=\"'",
"+",
"xmlescape",
"(",
"self",
".",
"description",
")",
"+",
"'\"'",
"if",
"self",
".",
"paramflag",
":",
"xml",
"+=",
"' flag=\"'",
"+",
"self",
".",
"paramflag",
"+",
"'\"'",
"if",
"self",
".",
"multi",
":",
"xml",
"+=",
"' multi=\"true\"'",
"for",
"key",
",",
"value",
"in",
"self",
".",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"key",
"!=",
"'choices'",
"and",
"key",
"!=",
"'default'",
"and",
"key",
"!=",
"'flag'",
"and",
"key",
"!=",
"'paramflag'",
":",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"xml",
"+=",
"' '",
"+",
"key",
"+",
"'=\"'",
"+",
"str",
"(",
"int",
"(",
"value",
")",
")",
"+",
"'\"'",
"elif",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"xml",
"+=",
"' '",
"+",
"key",
"+",
"'=\"'",
"+",
"\",\"",
".",
"join",
"(",
"value",
")",
"+",
"'\"'",
"else",
":",
"xml",
"+=",
"' '",
"+",
"key",
"+",
"'=\"'",
"+",
"xmlescape",
"(",
"value",
")",
"+",
"'\"'",
"if",
"self",
".",
"error",
":",
"xml",
"+=",
"' error=\"'",
"+",
"self",
".",
"error",
"+",
"'\"'",
"xml",
"+=",
"\">\"",
"for",
"key",
",",
"value",
"in",
"self",
".",
"choices",
":",
"if",
"self",
".",
"value",
"==",
"key",
"or",
"(",
"isinstance",
"(",
"self",
".",
"value",
",",
"list",
")",
"and",
"key",
"in",
"self",
".",
"value",
")",
":",
"xml",
"+=",
"\" <choice id=\\\"\"",
"+",
"key",
"+",
"\"\\\" selected=\\\"1\\\">\"",
"+",
"xmlescape",
"(",
"value",
")",
"+",
"\"</choice>\"",
"else",
":",
"xml",
"+=",
"\" <choice id=\\\"\"",
"+",
"key",
"+",
"\"\\\">\"",
"+",
"xmlescape",
"(",
"value",
")",
"+",
"\"</choice>\"",
"xml",
"+=",
"\"</\"",
"+",
"self",
".",
"__class__",
".",
"__name__",
"+",
"\">\"",
"return",
"xml"
] | This methods renders an XML representation of this parameter, along with
its selected value, and feedback on validation errors | [
"This",
"methods",
"renders",
"an",
"XML",
"representation",
"of",
"this",
"parameter",
"along",
"with",
"its",
"selected",
"value",
"and",
"feedback",
"on",
"validation",
"errors"
] | train | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/parameters.py#L459-L487 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.