repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | clean_whitespace | def clean_whitespace(string, compact=False):
"""Return string with compressed whitespace."""
for a, b in (('\r\n', '\n'), ('\r', '\n'), ('\n\n', '\n'),
('\t', ' '), (' ', ' ')):
string = string.replace(a, b)
if compact:
for a, b in (('\n', ' '), ('[ ', '['),
(' ', ' '), (' ', ' '), (' ', ' ')):
string = string.replace(a, b)
return string.strip() | python | def clean_whitespace(string, compact=False):
"""Return string with compressed whitespace."""
for a, b in (('\r\n', '\n'), ('\r', '\n'), ('\n\n', '\n'),
('\t', ' '), (' ', ' ')):
string = string.replace(a, b)
if compact:
for a, b in (('\n', ' '), ('[ ', '['),
(' ', ' '), (' ', ' '), (' ', ' ')):
string = string.replace(a, b)
return string.strip() | [
"def",
"clean_whitespace",
"(",
"string",
",",
"compact",
"=",
"False",
")",
":",
"for",
"a",
",",
"b",
"in",
"(",
"(",
"'\\r\\n'",
",",
"'\\n'",
")",
",",
"(",
"'\\r'",
",",
"'\\n'",
")",
",",
"(",
"'\\n\\n'",
",",
"'\\n'",
")",
",",
"(",
"'\\t'... | Return string with compressed whitespace. | [
"Return",
"string",
"with",
"compressed",
"whitespace",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L10488-L10497 | train | 52,700 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | pformat_xml | def pformat_xml(xml):
"""Return pretty formatted XML."""
try:
from lxml import etree # delayed import
if not isinstance(xml, bytes):
xml = xml.encode('utf-8')
xml = etree.parse(io.BytesIO(xml))
xml = etree.tostring(xml, pretty_print=True, xml_declaration=True,
encoding=xml.docinfo.encoding)
xml = bytes2str(xml)
except Exception:
if isinstance(xml, bytes):
xml = bytes2str(xml)
xml = xml.replace('><', '>\n<')
return xml.replace(' ', ' ').replace('\t', ' ') | python | def pformat_xml(xml):
"""Return pretty formatted XML."""
try:
from lxml import etree # delayed import
if not isinstance(xml, bytes):
xml = xml.encode('utf-8')
xml = etree.parse(io.BytesIO(xml))
xml = etree.tostring(xml, pretty_print=True, xml_declaration=True,
encoding=xml.docinfo.encoding)
xml = bytes2str(xml)
except Exception:
if isinstance(xml, bytes):
xml = bytes2str(xml)
xml = xml.replace('><', '>\n<')
return xml.replace(' ', ' ').replace('\t', ' ') | [
"def",
"pformat_xml",
"(",
"xml",
")",
":",
"try",
":",
"from",
"lxml",
"import",
"etree",
"# delayed import",
"if",
"not",
"isinstance",
"(",
"xml",
",",
"bytes",
")",
":",
"xml",
"=",
"xml",
".",
"encode",
"(",
"'utf-8'",
")",
"xml",
"=",
"etree",
... | Return pretty formatted XML. | [
"Return",
"pretty",
"formatted",
"XML",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L10500-L10514 | train | 52,701 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | pformat | def pformat(arg, width=79, height=24, compact=True):
"""Return pretty formatted representation of object as string.
Whitespace might be altered.
"""
if height is None or height < 1:
height = 1024
if width is None or width < 1:
width = 256
npopt = numpy.get_printoptions()
numpy.set_printoptions(threshold=100, linewidth=width)
if isinstance(arg, basestring):
if arg[:5].lower() in ('<?xml', b'<?xml'):
if isinstance(arg, bytes):
arg = bytes2str(arg)
if height == 1:
arg = arg[:4*width]
else:
arg = pformat_xml(arg)
elif isinstance(arg, bytes):
if isprintable(arg):
arg = bytes2str(arg)
arg = clean_whitespace(arg)
else:
numpy.set_printoptions(**npopt)
return hexdump(arg, width=width, height=height, modulo=1)
arg = arg.rstrip()
elif isinstance(arg, numpy.record):
arg = arg.pprint()
else:
import pprint # delayed import
compact = {} if sys.version_info[0] == 2 else dict(compact=compact)
arg = pprint.pformat(arg, width=width, **compact)
numpy.set_printoptions(**npopt)
if height == 1:
arg = clean_whitespace(arg, compact=True)
return arg[:width]
argl = list(arg.splitlines())
if len(argl) > height:
arg = '\n'.join(argl[:height//2] + ['...'] + argl[-height//2:])
return arg | python | def pformat(arg, width=79, height=24, compact=True):
"""Return pretty formatted representation of object as string.
Whitespace might be altered.
"""
if height is None or height < 1:
height = 1024
if width is None or width < 1:
width = 256
npopt = numpy.get_printoptions()
numpy.set_printoptions(threshold=100, linewidth=width)
if isinstance(arg, basestring):
if arg[:5].lower() in ('<?xml', b'<?xml'):
if isinstance(arg, bytes):
arg = bytes2str(arg)
if height == 1:
arg = arg[:4*width]
else:
arg = pformat_xml(arg)
elif isinstance(arg, bytes):
if isprintable(arg):
arg = bytes2str(arg)
arg = clean_whitespace(arg)
else:
numpy.set_printoptions(**npopt)
return hexdump(arg, width=width, height=height, modulo=1)
arg = arg.rstrip()
elif isinstance(arg, numpy.record):
arg = arg.pprint()
else:
import pprint # delayed import
compact = {} if sys.version_info[0] == 2 else dict(compact=compact)
arg = pprint.pformat(arg, width=width, **compact)
numpy.set_printoptions(**npopt)
if height == 1:
arg = clean_whitespace(arg, compact=True)
return arg[:width]
argl = list(arg.splitlines())
if len(argl) > height:
arg = '\n'.join(argl[:height//2] + ['...'] + argl[-height//2:])
return arg | [
"def",
"pformat",
"(",
"arg",
",",
"width",
"=",
"79",
",",
"height",
"=",
"24",
",",
"compact",
"=",
"True",
")",
":",
"if",
"height",
"is",
"None",
"or",
"height",
"<",
"1",
":",
"height",
"=",
"1024",
"if",
"width",
"is",
"None",
"or",
"width"... | Return pretty formatted representation of object as string.
Whitespace might be altered. | [
"Return",
"pretty",
"formatted",
"representation",
"of",
"object",
"as",
"string",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L10517-L10563 | train | 52,702 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | snipstr | def snipstr(string, width=79, snipat=None, ellipsis='...'):
"""Return string cut to specified length.
>>> snipstr('abcdefghijklmnop', 8)
'abc...op'
"""
if snipat is None:
snipat = 0.5
if ellipsis is None:
if isinstance(string, bytes):
ellipsis = b'...'
else:
ellipsis = u'\u2026' # does not print on win-py3.5
esize = len(ellipsis)
splitlines = string.splitlines()
# TODO: finish and test multiline snip
result = []
for line in splitlines:
if line is None:
result.append(ellipsis)
continue
linelen = len(line)
if linelen <= width:
result.append(string)
continue
split = snipat
if split is None or split == 1:
split = linelen
elif 0 < abs(split) < 1:
split = int(math.floor(linelen * split))
if split < 0:
split += linelen
if split < 0:
split = 0
if esize == 0 or width < esize + 1:
if split <= 0:
result.append(string[-width:])
else:
result.append(string[:width])
elif split <= 0:
result.append(ellipsis + string[esize-width:])
elif split >= linelen or width < esize + 4:
result.append(string[:width-esize] + ellipsis)
else:
splitlen = linelen - width + esize
end1 = split - splitlen // 2
end2 = end1 + splitlen
result.append(string[:end1] + ellipsis + string[end2:])
if isinstance(string, bytes):
return b'\n'.join(result)
return '\n'.join(result) | python | def snipstr(string, width=79, snipat=None, ellipsis='...'):
"""Return string cut to specified length.
>>> snipstr('abcdefghijklmnop', 8)
'abc...op'
"""
if snipat is None:
snipat = 0.5
if ellipsis is None:
if isinstance(string, bytes):
ellipsis = b'...'
else:
ellipsis = u'\u2026' # does not print on win-py3.5
esize = len(ellipsis)
splitlines = string.splitlines()
# TODO: finish and test multiline snip
result = []
for line in splitlines:
if line is None:
result.append(ellipsis)
continue
linelen = len(line)
if linelen <= width:
result.append(string)
continue
split = snipat
if split is None or split == 1:
split = linelen
elif 0 < abs(split) < 1:
split = int(math.floor(linelen * split))
if split < 0:
split += linelen
if split < 0:
split = 0
if esize == 0 or width < esize + 1:
if split <= 0:
result.append(string[-width:])
else:
result.append(string[:width])
elif split <= 0:
result.append(ellipsis + string[esize-width:])
elif split >= linelen or width < esize + 4:
result.append(string[:width-esize] + ellipsis)
else:
splitlen = linelen - width + esize
end1 = split - splitlen // 2
end2 = end1 + splitlen
result.append(string[:end1] + ellipsis + string[end2:])
if isinstance(string, bytes):
return b'\n'.join(result)
return '\n'.join(result) | [
"def",
"snipstr",
"(",
"string",
",",
"width",
"=",
"79",
",",
"snipat",
"=",
"None",
",",
"ellipsis",
"=",
"'...'",
")",
":",
"if",
"snipat",
"is",
"None",
":",
"snipat",
"=",
"0.5",
"if",
"ellipsis",
"is",
"None",
":",
"if",
"isinstance",
"(",
"s... | Return string cut to specified length.
>>> snipstr('abcdefghijklmnop', 8)
'abc...op' | [
"Return",
"string",
"cut",
"to",
"specified",
"length",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L10566-L10622 | train | 52,703 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | enumarg | def enumarg(enum, arg):
"""Return enum member from its name or value.
>>> enumarg(TIFF.PHOTOMETRIC, 2)
<PHOTOMETRIC.RGB: 2>
>>> enumarg(TIFF.PHOTOMETRIC, 'RGB')
<PHOTOMETRIC.RGB: 2>
"""
try:
return enum(arg)
except Exception:
try:
return enum[arg.upper()]
except Exception:
raise ValueError('invalid argument %s' % arg) | python | def enumarg(enum, arg):
"""Return enum member from its name or value.
>>> enumarg(TIFF.PHOTOMETRIC, 2)
<PHOTOMETRIC.RGB: 2>
>>> enumarg(TIFF.PHOTOMETRIC, 'RGB')
<PHOTOMETRIC.RGB: 2>
"""
try:
return enum(arg)
except Exception:
try:
return enum[arg.upper()]
except Exception:
raise ValueError('invalid argument %s' % arg) | [
"def",
"enumarg",
"(",
"enum",
",",
"arg",
")",
":",
"try",
":",
"return",
"enum",
"(",
"arg",
")",
"except",
"Exception",
":",
"try",
":",
"return",
"enum",
"[",
"arg",
".",
"upper",
"(",
")",
"]",
"except",
"Exception",
":",
"raise",
"ValueError",
... | Return enum member from its name or value.
>>> enumarg(TIFF.PHOTOMETRIC, 2)
<PHOTOMETRIC.RGB: 2>
>>> enumarg(TIFF.PHOTOMETRIC, 'RGB')
<PHOTOMETRIC.RGB: 2> | [
"Return",
"enum",
"member",
"from",
"its",
"name",
"or",
"value",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L10625-L10640 | train | 52,704 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | parse_kwargs | def parse_kwargs(kwargs, *keys, **keyvalues):
"""Return dict with keys from keys|keyvals and values from kwargs|keyvals.
Existing keys are deleted from kwargs.
>>> kwargs = {'one': 1, 'two': 2, 'four': 4}
>>> kwargs2 = parse_kwargs(kwargs, 'two', 'three', four=None, five=5)
>>> kwargs == {'one': 1}
True
>>> kwargs2 == {'two': 2, 'four': 4, 'five': 5}
True
"""
result = {}
for key in keys:
if key in kwargs:
result[key] = kwargs[key]
del kwargs[key]
for key, value in keyvalues.items():
if key in kwargs:
result[key] = kwargs[key]
del kwargs[key]
else:
result[key] = value
return result | python | def parse_kwargs(kwargs, *keys, **keyvalues):
"""Return dict with keys from keys|keyvals and values from kwargs|keyvals.
Existing keys are deleted from kwargs.
>>> kwargs = {'one': 1, 'two': 2, 'four': 4}
>>> kwargs2 = parse_kwargs(kwargs, 'two', 'three', four=None, five=5)
>>> kwargs == {'one': 1}
True
>>> kwargs2 == {'two': 2, 'four': 4, 'five': 5}
True
"""
result = {}
for key in keys:
if key in kwargs:
result[key] = kwargs[key]
del kwargs[key]
for key, value in keyvalues.items():
if key in kwargs:
result[key] = kwargs[key]
del kwargs[key]
else:
result[key] = value
return result | [
"def",
"parse_kwargs",
"(",
"kwargs",
",",
"*",
"keys",
",",
"*",
"*",
"keyvalues",
")",
":",
"result",
"=",
"{",
"}",
"for",
"key",
"in",
"keys",
":",
"if",
"key",
"in",
"kwargs",
":",
"result",
"[",
"key",
"]",
"=",
"kwargs",
"[",
"key",
"]",
... | Return dict with keys from keys|keyvals and values from kwargs|keyvals.
Existing keys are deleted from kwargs.
>>> kwargs = {'one': 1, 'two': 2, 'four': 4}
>>> kwargs2 = parse_kwargs(kwargs, 'two', 'three', four=None, five=5)
>>> kwargs == {'one': 1}
True
>>> kwargs2 == {'two': 2, 'four': 4, 'five': 5}
True | [
"Return",
"dict",
"with",
"keys",
"from",
"keys|keyvals",
"and",
"values",
"from",
"kwargs|keyvals",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L10643-L10667 | train | 52,705 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | update_kwargs | def update_kwargs(kwargs, **keyvalues):
"""Update dict with keys and values if keys do not already exist.
>>> kwargs = {'one': 1, }
>>> update_kwargs(kwargs, one=None, two=2)
>>> kwargs == {'one': 1, 'two': 2}
True
"""
for key, value in keyvalues.items():
if key not in kwargs:
kwargs[key] = value | python | def update_kwargs(kwargs, **keyvalues):
"""Update dict with keys and values if keys do not already exist.
>>> kwargs = {'one': 1, }
>>> update_kwargs(kwargs, one=None, two=2)
>>> kwargs == {'one': 1, 'two': 2}
True
"""
for key, value in keyvalues.items():
if key not in kwargs:
kwargs[key] = value | [
"def",
"update_kwargs",
"(",
"kwargs",
",",
"*",
"*",
"keyvalues",
")",
":",
"for",
"key",
",",
"value",
"in",
"keyvalues",
".",
"items",
"(",
")",
":",
"if",
"key",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"key",
"]",
"=",
"value"
] | Update dict with keys and values if keys do not already exist.
>>> kwargs = {'one': 1, }
>>> update_kwargs(kwargs, one=None, two=2)
>>> kwargs == {'one': 1, 'two': 2}
True | [
"Update",
"dict",
"with",
"keys",
"and",
"values",
"if",
"keys",
"do",
"not",
"already",
"exist",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L10670-L10681 | train | 52,706 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | validate_jhove | def validate_jhove(filename, jhove=None, ignore=None):
"""Validate TIFF file using jhove -m TIFF-hul.
Raise ValueError if jhove outputs an error message unless the message
contains one of the strings in 'ignore'.
JHOVE does not support bigtiff or more than 50 IFDs.
See `JHOVE TIFF-hul Module <http://jhove.sourceforge.net/tiff-hul.html>`_
"""
import subprocess # noqa: delayed import
if ignore is None:
ignore = ['More than 50 IFDs']
if jhove is None:
jhove = 'jhove'
out = subprocess.check_output([jhove, filename, '-m', 'TIFF-hul'])
if b'ErrorMessage: ' in out:
for line in out.splitlines():
line = line.strip()
if line.startswith(b'ErrorMessage: '):
error = line[14:].decode('utf8')
for i in ignore:
if i in error:
break
else:
raise ValueError(error)
break | python | def validate_jhove(filename, jhove=None, ignore=None):
"""Validate TIFF file using jhove -m TIFF-hul.
Raise ValueError if jhove outputs an error message unless the message
contains one of the strings in 'ignore'.
JHOVE does not support bigtiff or more than 50 IFDs.
See `JHOVE TIFF-hul Module <http://jhove.sourceforge.net/tiff-hul.html>`_
"""
import subprocess # noqa: delayed import
if ignore is None:
ignore = ['More than 50 IFDs']
if jhove is None:
jhove = 'jhove'
out = subprocess.check_output([jhove, filename, '-m', 'TIFF-hul'])
if b'ErrorMessage: ' in out:
for line in out.splitlines():
line = line.strip()
if line.startswith(b'ErrorMessage: '):
error = line[14:].decode('utf8')
for i in ignore:
if i in error:
break
else:
raise ValueError(error)
break | [
"def",
"validate_jhove",
"(",
"filename",
",",
"jhove",
"=",
"None",
",",
"ignore",
"=",
"None",
")",
":",
"import",
"subprocess",
"# noqa: delayed import",
"if",
"ignore",
"is",
"None",
":",
"ignore",
"=",
"[",
"'More than 50 IFDs'",
"]",
"if",
"jhove",
"is... | Validate TIFF file using jhove -m TIFF-hul.
Raise ValueError if jhove outputs an error message unless the message
contains one of the strings in 'ignore'.
JHOVE does not support bigtiff or more than 50 IFDs.
See `JHOVE TIFF-hul Module <http://jhove.sourceforge.net/tiff-hul.html>`_ | [
"Validate",
"TIFF",
"file",
"using",
"jhove",
"-",
"m",
"TIFF",
"-",
"hul",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L10684-L10711 | train | 52,707 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffWriter._write_image_description | def _write_image_description(self):
"""Write metadata to ImageDescription tag."""
if (not self._datashape or self._datashape[0] == 1 or
self._descriptionoffset <= 0):
return
colormapped = self._colormap is not None
if self._imagej:
isrgb = self._shape[-1] in (3, 4)
description = imagej_description(
self._datashape, isrgb, colormapped, **self._metadata)
else:
description = json_description(self._datashape, **self._metadata)
# rewrite description and its length to file
description = description.encode('utf-8')
description = description[:self._descriptionlen-1]
pos = self._fh.tell()
self._fh.seek(self._descriptionoffset)
self._fh.write(description)
self._fh.seek(self._descriptionlenoffset)
self._fh.write(struct.pack(self._byteorder+self._offsetformat,
len(description)+1))
self._fh.seek(pos)
self._descriptionoffset = 0
self._descriptionlenoffset = 0
self._descriptionlen = 0 | python | def _write_image_description(self):
"""Write metadata to ImageDescription tag."""
if (not self._datashape or self._datashape[0] == 1 or
self._descriptionoffset <= 0):
return
colormapped = self._colormap is not None
if self._imagej:
isrgb = self._shape[-1] in (3, 4)
description = imagej_description(
self._datashape, isrgb, colormapped, **self._metadata)
else:
description = json_description(self._datashape, **self._metadata)
# rewrite description and its length to file
description = description.encode('utf-8')
description = description[:self._descriptionlen-1]
pos = self._fh.tell()
self._fh.seek(self._descriptionoffset)
self._fh.write(description)
self._fh.seek(self._descriptionlenoffset)
self._fh.write(struct.pack(self._byteorder+self._offsetformat,
len(description)+1))
self._fh.seek(pos)
self._descriptionoffset = 0
self._descriptionlenoffset = 0
self._descriptionlen = 0 | [
"def",
"_write_image_description",
"(",
"self",
")",
":",
"if",
"(",
"not",
"self",
".",
"_datashape",
"or",
"self",
".",
"_datashape",
"[",
"0",
"]",
"==",
"1",
"or",
"self",
".",
"_descriptionoffset",
"<=",
"0",
")",
":",
"return",
"colormapped",
"=",
... | Write metadata to ImageDescription tag. | [
"Write",
"metadata",
"to",
"ImageDescription",
"tag",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L1865-L1892 | train | 52,708 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffWriter.close | def close(self):
"""Write remaining pages and close file handle."""
if not self._truncate:
self._write_remaining_pages()
self._write_image_description()
self._fh.close() | python | def close(self):
"""Write remaining pages and close file handle."""
if not self._truncate:
self._write_remaining_pages()
self._write_image_description()
self._fh.close() | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_truncate",
":",
"self",
".",
"_write_remaining_pages",
"(",
")",
"self",
".",
"_write_image_description",
"(",
")",
"self",
".",
"_fh",
".",
"close",
"(",
")"
] | Write remaining pages and close file handle. | [
"Write",
"remaining",
"pages",
"and",
"close",
"file",
"handle",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L1898-L1903 | train | 52,709 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffFile.series | def series(self):
"""Return related pages as TiffPageSeries.
Side effect: after calling this function, TiffFile.pages might contain
TiffPage and TiffFrame instances.
"""
if not self.pages:
return []
useframes = self.pages.useframes
keyframe = self.pages.keyframe.index
series = []
for name in ('lsm', 'ome', 'imagej', 'shaped', 'fluoview', 'sis',
'uniform', 'mdgel'):
if getattr(self, 'is_' + name, False):
series = getattr(self, '_series_' + name)()
break
self.pages.useframes = useframes
self.pages.keyframe = keyframe
if not series:
series = self._series_generic()
# remove empty series, e.g. in MD Gel files
series = [s for s in series if product(s.shape) > 0]
for i, s in enumerate(series):
s.index = i
return series | python | def series(self):
"""Return related pages as TiffPageSeries.
Side effect: after calling this function, TiffFile.pages might contain
TiffPage and TiffFrame instances.
"""
if not self.pages:
return []
useframes = self.pages.useframes
keyframe = self.pages.keyframe.index
series = []
for name in ('lsm', 'ome', 'imagej', 'shaped', 'fluoview', 'sis',
'uniform', 'mdgel'):
if getattr(self, 'is_' + name, False):
series = getattr(self, '_series_' + name)()
break
self.pages.useframes = useframes
self.pages.keyframe = keyframe
if not series:
series = self._series_generic()
# remove empty series, e.g. in MD Gel files
series = [s for s in series if product(s.shape) > 0]
for i, s in enumerate(series):
s.index = i
return series | [
"def",
"series",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"pages",
":",
"return",
"[",
"]",
"useframes",
"=",
"self",
".",
"pages",
".",
"useframes",
"keyframe",
"=",
"self",
".",
"pages",
".",
"keyframe",
".",
"index",
"series",
"=",
"[",
... | Return related pages as TiffPageSeries.
Side effect: after calling this function, TiffFile.pages might contain
TiffPage and TiffFrame instances. | [
"Return",
"related",
"pages",
"as",
"TiffPageSeries",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L2182-L2210 | train | 52,710 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffFile._series_generic | def _series_generic(self):
"""Return image series in file.
A series is a sequence of TiffPages with the same hash.
"""
pages = self.pages
pages._clear(False)
pages.useframes = False
if pages.cache:
pages._load()
result = []
keys = []
series = {}
for page in pages:
if not page.shape or product(page.shape) == 0:
continue
key = page.hash
if key in series:
series[key].append(page)
else:
keys.append(key)
series[key] = [page]
for key in keys:
pages = series[key]
page = pages[0]
shape = page.shape
axes = page.axes
if len(pages) > 1:
shape = (len(pages),) + shape
axes = 'I' + axes
result.append(TiffPageSeries(pages, shape, page.dtype, axes,
kind='Generic'))
self.is_uniform = len(result) == 1
return result | python | def _series_generic(self):
"""Return image series in file.
A series is a sequence of TiffPages with the same hash.
"""
pages = self.pages
pages._clear(False)
pages.useframes = False
if pages.cache:
pages._load()
result = []
keys = []
series = {}
for page in pages:
if not page.shape or product(page.shape) == 0:
continue
key = page.hash
if key in series:
series[key].append(page)
else:
keys.append(key)
series[key] = [page]
for key in keys:
pages = series[key]
page = pages[0]
shape = page.shape
axes = page.axes
if len(pages) > 1:
shape = (len(pages),) + shape
axes = 'I' + axes
result.append(TiffPageSeries(pages, shape, page.dtype, axes,
kind='Generic'))
self.is_uniform = len(result) == 1
return result | [
"def",
"_series_generic",
"(",
"self",
")",
":",
"pages",
"=",
"self",
".",
"pages",
"pages",
".",
"_clear",
"(",
"False",
")",
"pages",
".",
"useframes",
"=",
"False",
"if",
"pages",
".",
"cache",
":",
"pages",
".",
"_load",
"(",
")",
"result",
"=",... | Return image series in file.
A series is a sequence of TiffPages with the same hash. | [
"Return",
"image",
"series",
"in",
"file",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L2212-L2249 | train | 52,711 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffFile._series_uniform | def _series_uniform(self):
"""Return all images in file as single series."""
page = self.pages[0]
shape = page.shape
axes = page.axes
dtype = page.dtype
validate = not (page.is_scanimage or page.is_nih)
pages = self.pages._getlist(validate=validate)
lenpages = len(pages)
if lenpages > 1:
shape = (lenpages,) + shape
axes = 'I' + axes
if page.is_scanimage:
kind = 'ScanImage'
elif page.is_nih:
kind = 'NIHImage'
else:
kind = 'Uniform'
return [TiffPageSeries(pages, shape, dtype, axes, kind=kind)] | python | def _series_uniform(self):
"""Return all images in file as single series."""
page = self.pages[0]
shape = page.shape
axes = page.axes
dtype = page.dtype
validate = not (page.is_scanimage or page.is_nih)
pages = self.pages._getlist(validate=validate)
lenpages = len(pages)
if lenpages > 1:
shape = (lenpages,) + shape
axes = 'I' + axes
if page.is_scanimage:
kind = 'ScanImage'
elif page.is_nih:
kind = 'NIHImage'
else:
kind = 'Uniform'
return [TiffPageSeries(pages, shape, dtype, axes, kind=kind)] | [
"def",
"_series_uniform",
"(",
"self",
")",
":",
"page",
"=",
"self",
".",
"pages",
"[",
"0",
"]",
"shape",
"=",
"page",
".",
"shape",
"axes",
"=",
"page",
".",
"axes",
"dtype",
"=",
"page",
".",
"dtype",
"validate",
"=",
"not",
"(",
"page",
".",
... | Return all images in file as single series. | [
"Return",
"all",
"images",
"in",
"file",
"as",
"single",
"series",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L2251-L2269 | train | 52,712 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffFile._series_shaped | def _series_shaped(self):
"""Return image series in "shaped" file."""
pages = self.pages
pages.useframes = True
lenpages = len(pages)
def append_series(series, pages, axes, shape, reshape, name,
truncated):
page = pages[0]
if not axes:
shape = page.shape
axes = page.axes
if len(pages) > 1:
shape = (len(pages),) + shape
axes = 'Q' + axes
size = product(shape)
resize = product(reshape)
if page.is_contiguous and resize > size and resize % size == 0:
if truncated is None:
truncated = True
axes = 'Q' + axes
shape = (resize // size,) + shape
try:
axes = reshape_axes(axes, shape, reshape)
shape = reshape
except ValueError as exc:
log.warning('Shaped series: %s: %s',
exc.__class__.__name__, exc)
series.append(
TiffPageSeries(pages, shape, page.dtype, axes, name=name,
kind='Shaped', truncated=truncated))
keyframe = axes = shape = reshape = name = None
series = []
index = 0
while True:
if index >= lenpages:
break
# new keyframe; start of new series
pages.keyframe = index
keyframe = pages.keyframe
if not keyframe.is_shaped:
log.warning(
'Shaped series: invalid metadata or corrupted file')
return None
# read metadata
axes = None
shape = None
metadata = json_description_metadata(keyframe.is_shaped)
name = metadata.get('name', '')
reshape = metadata['shape']
truncated = metadata.get('truncated', None)
if 'axes' in metadata:
axes = metadata['axes']
if len(axes) == len(reshape):
shape = reshape
else:
axes = ''
log.warning('Shaped series: axes do not match shape')
# skip pages if possible
spages = [keyframe]
size = product(reshape)
npages, mod = divmod(size, product(keyframe.shape))
if mod:
log.warning(
'Shaped series: series shape does not match page shape')
return None
if 1 < npages <= lenpages - index:
size *= keyframe._dtype.itemsize
if truncated:
npages = 1
elif (keyframe.is_final and
keyframe.offset + size < pages[index+1].offset):
truncated = False
else:
# need to read all pages for series
truncated = False
for j in range(index+1, index+npages):
page = pages[j]
page.keyframe = keyframe
spages.append(page)
append_series(series, spages, axes, shape, reshape, name,
truncated)
index += npages
self.is_uniform = len(series) == 1
return series | python | def _series_shaped(self):
"""Return image series in "shaped" file."""
pages = self.pages
pages.useframes = True
lenpages = len(pages)
def append_series(series, pages, axes, shape, reshape, name,
truncated):
page = pages[0]
if not axes:
shape = page.shape
axes = page.axes
if len(pages) > 1:
shape = (len(pages),) + shape
axes = 'Q' + axes
size = product(shape)
resize = product(reshape)
if page.is_contiguous and resize > size and resize % size == 0:
if truncated is None:
truncated = True
axes = 'Q' + axes
shape = (resize // size,) + shape
try:
axes = reshape_axes(axes, shape, reshape)
shape = reshape
except ValueError as exc:
log.warning('Shaped series: %s: %s',
exc.__class__.__name__, exc)
series.append(
TiffPageSeries(pages, shape, page.dtype, axes, name=name,
kind='Shaped', truncated=truncated))
keyframe = axes = shape = reshape = name = None
series = []
index = 0
while True:
if index >= lenpages:
break
# new keyframe; start of new series
pages.keyframe = index
keyframe = pages.keyframe
if not keyframe.is_shaped:
log.warning(
'Shaped series: invalid metadata or corrupted file')
return None
# read metadata
axes = None
shape = None
metadata = json_description_metadata(keyframe.is_shaped)
name = metadata.get('name', '')
reshape = metadata['shape']
truncated = metadata.get('truncated', None)
if 'axes' in metadata:
axes = metadata['axes']
if len(axes) == len(reshape):
shape = reshape
else:
axes = ''
log.warning('Shaped series: axes do not match shape')
# skip pages if possible
spages = [keyframe]
size = product(reshape)
npages, mod = divmod(size, product(keyframe.shape))
if mod:
log.warning(
'Shaped series: series shape does not match page shape')
return None
if 1 < npages <= lenpages - index:
size *= keyframe._dtype.itemsize
if truncated:
npages = 1
elif (keyframe.is_final and
keyframe.offset + size < pages[index+1].offset):
truncated = False
else:
# need to read all pages for series
truncated = False
for j in range(index+1, index+npages):
page = pages[j]
page.keyframe = keyframe
spages.append(page)
append_series(series, spages, axes, shape, reshape, name,
truncated)
index += npages
self.is_uniform = len(series) == 1
return series | [
"def",
"_series_shaped",
"(",
"self",
")",
":",
"pages",
"=",
"self",
".",
"pages",
"pages",
".",
"useframes",
"=",
"True",
"lenpages",
"=",
"len",
"(",
"pages",
")",
"def",
"append_series",
"(",
"series",
",",
"pages",
",",
"axes",
",",
"shape",
",",
... | Return image series in "shaped" file. | [
"Return",
"image",
"series",
"in",
"shaped",
"file",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L2271-L2358 | train | 52,713 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffFile._series_imagej | def _series_imagej(self):
"""Return image series in ImageJ file."""
# ImageJ's dimension order is always TZCYXS
# TODO: fix loading of color, composite, or palette images
pages = self.pages
pages.useframes = True
pages.keyframe = 0
page = pages[0]
ij = self.imagej_metadata
def is_hyperstack():
# ImageJ hyperstack store all image metadata in the first page and
# image data are stored contiguously before the second page, if any
if not page.is_final:
return False
images = ij.get('images', 0)
if images <= 1:
return False
offset, count = page.is_contiguous
if (count != product(page.shape) * page.bitspersample // 8
or offset + count*images > self.filehandle.size):
raise ValueError()
# check that next page is stored after data
if len(pages) > 1 and offset + count*images > pages[1].offset:
return False
return True
try:
hyperstack = is_hyperstack()
except ValueError:
log.warning('ImageJ series: invalid metadata or corrupted file')
return None
if hyperstack:
# no need to read other pages
pages = [page]
else:
pages = pages[:]
shape = []
axes = []
if 'frames' in ij:
shape.append(ij['frames'])
axes.append('T')
if 'slices' in ij:
shape.append(ij['slices'])
axes.append('Z')
if 'channels' in ij and not (page.photometric == 2 and not
ij.get('hyperstack', False)):
shape.append(ij['channels'])
axes.append('C')
remain = ij.get('images', len(pages))//(product(shape) if shape else 1)
if remain > 1:
shape.append(remain)
axes.append('I')
if page.axes[0] == 'I':
# contiguous multiple images
shape.extend(page.shape[1:])
axes.extend(page.axes[1:])
elif page.axes[:2] == 'SI':
# color-mapped contiguous multiple images
shape = page.shape[0:1] + tuple(shape) + page.shape[2:]
axes = list(page.axes[0]) + axes + list(page.axes[2:])
else:
shape.extend(page.shape)
axes.extend(page.axes)
truncated = (
hyperstack and len(self.pages) == 1 and
page.is_contiguous[1] != product(shape) * page.bitspersample // 8)
self.is_uniform = True
return [TiffPageSeries(pages, shape, page.dtype, axes, kind='ImageJ',
truncated=truncated)] | python | def _series_imagej(self):
"""Return image series in ImageJ file."""
# ImageJ's dimension order is always TZCYXS
# TODO: fix loading of color, composite, or palette images
pages = self.pages
pages.useframes = True
pages.keyframe = 0
page = pages[0]
ij = self.imagej_metadata
def is_hyperstack():
# ImageJ hyperstack store all image metadata in the first page and
# image data are stored contiguously before the second page, if any
if not page.is_final:
return False
images = ij.get('images', 0)
if images <= 1:
return False
offset, count = page.is_contiguous
if (count != product(page.shape) * page.bitspersample // 8
or offset + count*images > self.filehandle.size):
raise ValueError()
# check that next page is stored after data
if len(pages) > 1 and offset + count*images > pages[1].offset:
return False
return True
try:
hyperstack = is_hyperstack()
except ValueError:
log.warning('ImageJ series: invalid metadata or corrupted file')
return None
if hyperstack:
# no need to read other pages
pages = [page]
else:
pages = pages[:]
shape = []
axes = []
if 'frames' in ij:
shape.append(ij['frames'])
axes.append('T')
if 'slices' in ij:
shape.append(ij['slices'])
axes.append('Z')
if 'channels' in ij and not (page.photometric == 2 and not
ij.get('hyperstack', False)):
shape.append(ij['channels'])
axes.append('C')
remain = ij.get('images', len(pages))//(product(shape) if shape else 1)
if remain > 1:
shape.append(remain)
axes.append('I')
if page.axes[0] == 'I':
# contiguous multiple images
shape.extend(page.shape[1:])
axes.extend(page.axes[1:])
elif page.axes[:2] == 'SI':
# color-mapped contiguous multiple images
shape = page.shape[0:1] + tuple(shape) + page.shape[2:]
axes = list(page.axes[0]) + axes + list(page.axes[2:])
else:
shape.extend(page.shape)
axes.extend(page.axes)
truncated = (
hyperstack and len(self.pages) == 1 and
page.is_contiguous[1] != product(shape) * page.bitspersample // 8)
self.is_uniform = True
return [TiffPageSeries(pages, shape, page.dtype, axes, kind='ImageJ',
truncated=truncated)] | [
"def",
"_series_imagej",
"(",
"self",
")",
":",
"# ImageJ's dimension order is always TZCYXS",
"# TODO: fix loading of color, composite, or palette images",
"pages",
"=",
"self",
".",
"pages",
"pages",
".",
"useframes",
"=",
"True",
"pages",
".",
"keyframe",
"=",
"0",
"... | Return image series in ImageJ file. | [
"Return",
"image",
"series",
"in",
"ImageJ",
"file",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L2360-L2433 | train | 52,714 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffFile._series_fluoview | def _series_fluoview(self):
"""Return image series in FluoView file."""
pages = self.pages._getlist(validate=False)
mm = self.fluoview_metadata
mmhd = list(reversed(mm['Dimensions']))
axes = ''.join(TIFF.MM_DIMENSIONS.get(i[0].upper(), 'Q')
for i in mmhd if i[1] > 1)
shape = tuple(int(i[1]) for i in mmhd if i[1] > 1)
self.is_uniform = True
return [TiffPageSeries(pages, shape, pages[0].dtype, axes,
name=mm['ImageName'], kind='FluoView')] | python | def _series_fluoview(self):
"""Return image series in FluoView file."""
pages = self.pages._getlist(validate=False)
mm = self.fluoview_metadata
mmhd = list(reversed(mm['Dimensions']))
axes = ''.join(TIFF.MM_DIMENSIONS.get(i[0].upper(), 'Q')
for i in mmhd if i[1] > 1)
shape = tuple(int(i[1]) for i in mmhd if i[1] > 1)
self.is_uniform = True
return [TiffPageSeries(pages, shape, pages[0].dtype, axes,
name=mm['ImageName'], kind='FluoView')] | [
"def",
"_series_fluoview",
"(",
"self",
")",
":",
"pages",
"=",
"self",
".",
"pages",
".",
"_getlist",
"(",
"validate",
"=",
"False",
")",
"mm",
"=",
"self",
".",
"fluoview_metadata",
"mmhd",
"=",
"list",
"(",
"reversed",
"(",
"mm",
"[",
"'Dimensions'",
... | Return image series in FluoView file. | [
"Return",
"image",
"series",
"in",
"FluoView",
"file",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L2435-L2446 | train | 52,715 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffFile._series_mdgel | def _series_mdgel(self):
"""Return image series in MD Gel file."""
# only a single page, scaled according to metadata in second page
self.pages.useframes = False
self.pages.keyframe = 0
md = self.mdgel_metadata
if md['FileTag'] in (2, 128):
dtype = numpy.dtype('float32')
scale = md['ScalePixel']
scale = scale[0] / scale[1] # rational
if md['FileTag'] == 2:
# squary root data format
def transform(a):
return a.astype('float32')**2 * scale
else:
def transform(a):
return a.astype('float32') * scale
else:
transform = None
page = self.pages[0]
self.is_uniform = False
return [TiffPageSeries([page], page.shape, dtype, page.axes,
transform=transform, kind='MDGel')] | python | def _series_mdgel(self):
"""Return image series in MD Gel file."""
# only a single page, scaled according to metadata in second page
self.pages.useframes = False
self.pages.keyframe = 0
md = self.mdgel_metadata
if md['FileTag'] in (2, 128):
dtype = numpy.dtype('float32')
scale = md['ScalePixel']
scale = scale[0] / scale[1] # rational
if md['FileTag'] == 2:
# squary root data format
def transform(a):
return a.astype('float32')**2 * scale
else:
def transform(a):
return a.astype('float32') * scale
else:
transform = None
page = self.pages[0]
self.is_uniform = False
return [TiffPageSeries([page], page.shape, dtype, page.axes,
transform=transform, kind='MDGel')] | [
"def",
"_series_mdgel",
"(",
"self",
")",
":",
"# only a single page, scaled according to metadata in second page",
"self",
".",
"pages",
".",
"useframes",
"=",
"False",
"self",
".",
"pages",
".",
"keyframe",
"=",
"0",
"md",
"=",
"self",
".",
"mdgel_metadata",
"if... | Return image series in MD Gel file. | [
"Return",
"image",
"series",
"in",
"MD",
"Gel",
"file",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L2448-L2470 | train | 52,716 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffFile._series_sis | def _series_sis(self):
"""Return image series in Olympus SIS file."""
pages = self.pages._getlist(validate=False)
page = pages[0]
lenpages = len(pages)
md = self.sis_metadata
if 'shape' in md and 'axes' in md:
shape = md['shape'] + page.shape
axes = md['axes'] + page.axes
elif lenpages == 1:
shape = page.shape
axes = page.axes
else:
shape = (lenpages,) + page.shape
axes = 'I' + page.axes
self.is_uniform = True
return [TiffPageSeries(pages, shape, page.dtype, axes, kind='SIS')] | python | def _series_sis(self):
"""Return image series in Olympus SIS file."""
pages = self.pages._getlist(validate=False)
page = pages[0]
lenpages = len(pages)
md = self.sis_metadata
if 'shape' in md and 'axes' in md:
shape = md['shape'] + page.shape
axes = md['axes'] + page.axes
elif lenpages == 1:
shape = page.shape
axes = page.axes
else:
shape = (lenpages,) + page.shape
axes = 'I' + page.axes
self.is_uniform = True
return [TiffPageSeries(pages, shape, page.dtype, axes, kind='SIS')] | [
"def",
"_series_sis",
"(",
"self",
")",
":",
"pages",
"=",
"self",
".",
"pages",
".",
"_getlist",
"(",
"validate",
"=",
"False",
")",
"page",
"=",
"pages",
"[",
"0",
"]",
"lenpages",
"=",
"len",
"(",
"pages",
")",
"md",
"=",
"self",
".",
"sis_metad... | Return image series in Olympus SIS file. | [
"Return",
"image",
"series",
"in",
"Olympus",
"SIS",
"file",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L2472-L2488 | train | 52,717 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffFile._series_lsm | def _series_lsm(self):
"""Return main and thumbnail series in LSM file."""
lsmi = self.lsm_metadata
axes = TIFF.CZ_LSMINFO_SCANTYPE[lsmi['ScanType']]
if self.pages[0].photometric == 2: # RGB; more than one channel
axes = axes.replace('C', '').replace('XY', 'XYC')
if lsmi.get('DimensionP', 0) > 1:
axes += 'P'
if lsmi.get('DimensionM', 0) > 1:
axes += 'M'
axes = axes[::-1]
shape = tuple(int(lsmi[TIFF.CZ_LSMINFO_DIMENSIONS[i]]) for i in axes)
name = lsmi.get('Name', '')
pages = self.pages._getlist(slice(0, None, 2), validate=False)
dtype = pages[0].dtype
series = [TiffPageSeries(pages, shape, dtype, axes, name=name,
kind='LSM')]
if self.pages[1].is_reduced:
pages = self.pages._getlist(slice(1, None, 2), validate=False)
dtype = pages[0].dtype
cp = 1
i = 0
while cp < len(pages) and i < len(shape)-2:
cp *= shape[i]
i += 1
shape = shape[:i] + pages[0].shape
axes = axes[:i] + 'CYX'
series.append(TiffPageSeries(pages, shape, dtype, axes, name=name,
kind='LSMreduced'))
self.is_uniform = False
return series | python | def _series_lsm(self):
"""Return main and thumbnail series in LSM file."""
lsmi = self.lsm_metadata
axes = TIFF.CZ_LSMINFO_SCANTYPE[lsmi['ScanType']]
if self.pages[0].photometric == 2: # RGB; more than one channel
axes = axes.replace('C', '').replace('XY', 'XYC')
if lsmi.get('DimensionP', 0) > 1:
axes += 'P'
if lsmi.get('DimensionM', 0) > 1:
axes += 'M'
axes = axes[::-1]
shape = tuple(int(lsmi[TIFF.CZ_LSMINFO_DIMENSIONS[i]]) for i in axes)
name = lsmi.get('Name', '')
pages = self.pages._getlist(slice(0, None, 2), validate=False)
dtype = pages[0].dtype
series = [TiffPageSeries(pages, shape, dtype, axes, name=name,
kind='LSM')]
if self.pages[1].is_reduced:
pages = self.pages._getlist(slice(1, None, 2), validate=False)
dtype = pages[0].dtype
cp = 1
i = 0
while cp < len(pages) and i < len(shape)-2:
cp *= shape[i]
i += 1
shape = shape[:i] + pages[0].shape
axes = axes[:i] + 'CYX'
series.append(TiffPageSeries(pages, shape, dtype, axes, name=name,
kind='LSMreduced'))
self.is_uniform = False
return series | [
"def",
"_series_lsm",
"(",
"self",
")",
":",
"lsmi",
"=",
"self",
".",
"lsm_metadata",
"axes",
"=",
"TIFF",
".",
"CZ_LSMINFO_SCANTYPE",
"[",
"lsmi",
"[",
"'ScanType'",
"]",
"]",
"if",
"self",
".",
"pages",
"[",
"0",
"]",
".",
"photometric",
"==",
"2",
... | Return main and thumbnail series in LSM file. | [
"Return",
"main",
"and",
"thumbnail",
"series",
"in",
"LSM",
"file",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L2696-L2728 | train | 52,718 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffFile._lsm_load_pages | def _lsm_load_pages(self):
"""Load and fix all pages from LSM file."""
# cache all pages to preserve corrected values
pages = self.pages
pages.cache = True
pages.useframes = True
# use first and second page as keyframes
pages.keyframe = 1
pages.keyframe = 0
# load remaining pages as frames
pages._load(keyframe=None)
# fix offsets and bytecounts first
self._lsm_fix_strip_offsets()
self._lsm_fix_strip_bytecounts()
# assign keyframes for data and thumbnail series
keyframe = pages[0]
for page in pages[::2]:
page.keyframe = keyframe
keyframe = pages[1]
for page in pages[1::2]:
page.keyframe = keyframe | python | def _lsm_load_pages(self):
"""Load and fix all pages from LSM file."""
# cache all pages to preserve corrected values
pages = self.pages
pages.cache = True
pages.useframes = True
# use first and second page as keyframes
pages.keyframe = 1
pages.keyframe = 0
# load remaining pages as frames
pages._load(keyframe=None)
# fix offsets and bytecounts first
self._lsm_fix_strip_offsets()
self._lsm_fix_strip_bytecounts()
# assign keyframes for data and thumbnail series
keyframe = pages[0]
for page in pages[::2]:
page.keyframe = keyframe
keyframe = pages[1]
for page in pages[1::2]:
page.keyframe = keyframe | [
"def",
"_lsm_load_pages",
"(",
"self",
")",
":",
"# cache all pages to preserve corrected values",
"pages",
"=",
"self",
".",
"pages",
"pages",
".",
"cache",
"=",
"True",
"pages",
".",
"useframes",
"=",
"True",
"# use first and second page as keyframes",
"pages",
".",... | Load and fix all pages from LSM file. | [
"Load",
"and",
"fix",
"all",
"pages",
"from",
"LSM",
"file",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L2730-L2750 | train | 52,719 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffFile._lsm_fix_strip_offsets | def _lsm_fix_strip_offsets(self):
"""Unwrap strip offsets for LSM files greater than 4 GB.
Each series and position require separate unwrapping (undocumented).
"""
if self.filehandle.size < 2**32:
return
pages = self.pages
npages = len(pages)
series = self.series[0]
axes = series.axes
# find positions
positions = 1
for i in 0, 1:
if series.axes[i] in 'PM':
positions *= series.shape[i]
# make time axis first
if positions > 1:
ntimes = 0
for i in 1, 2:
if axes[i] == 'T':
ntimes = series.shape[i]
break
if ntimes:
div, mod = divmod(npages, 2*positions*ntimes)
assert mod == 0
shape = (positions, ntimes, div, 2)
indices = numpy.arange(product(shape)).reshape(shape)
indices = numpy.moveaxis(indices, 1, 0)
else:
indices = numpy.arange(npages).reshape(-1, 2)
# images of reduced page might be stored first
if pages[0]._offsetscounts[0][0] > pages[1]._offsetscounts[0][0]:
indices = indices[..., ::-1]
# unwrap offsets
wrap = 0
previousoffset = 0
for i in indices.flat:
page = pages[int(i)]
dataoffsets = []
for currentoffset in page._offsetscounts[0]:
if currentoffset < previousoffset:
wrap += 2**32
dataoffsets.append(currentoffset + wrap)
previousoffset = currentoffset
page._offsetscounts = dataoffsets, page._offsetscounts[1] | python | def _lsm_fix_strip_offsets(self):
"""Unwrap strip offsets for LSM files greater than 4 GB.
Each series and position require separate unwrapping (undocumented).
"""
if self.filehandle.size < 2**32:
return
pages = self.pages
npages = len(pages)
series = self.series[0]
axes = series.axes
# find positions
positions = 1
for i in 0, 1:
if series.axes[i] in 'PM':
positions *= series.shape[i]
# make time axis first
if positions > 1:
ntimes = 0
for i in 1, 2:
if axes[i] == 'T':
ntimes = series.shape[i]
break
if ntimes:
div, mod = divmod(npages, 2*positions*ntimes)
assert mod == 0
shape = (positions, ntimes, div, 2)
indices = numpy.arange(product(shape)).reshape(shape)
indices = numpy.moveaxis(indices, 1, 0)
else:
indices = numpy.arange(npages).reshape(-1, 2)
# images of reduced page might be stored first
if pages[0]._offsetscounts[0][0] > pages[1]._offsetscounts[0][0]:
indices = indices[..., ::-1]
# unwrap offsets
wrap = 0
previousoffset = 0
for i in indices.flat:
page = pages[int(i)]
dataoffsets = []
for currentoffset in page._offsetscounts[0]:
if currentoffset < previousoffset:
wrap += 2**32
dataoffsets.append(currentoffset + wrap)
previousoffset = currentoffset
page._offsetscounts = dataoffsets, page._offsetscounts[1] | [
"def",
"_lsm_fix_strip_offsets",
"(",
"self",
")",
":",
"if",
"self",
".",
"filehandle",
".",
"size",
"<",
"2",
"**",
"32",
":",
"return",
"pages",
"=",
"self",
".",
"pages",
"npages",
"=",
"len",
"(",
"pages",
")",
"series",
"=",
"self",
".",
"serie... | Unwrap strip offsets for LSM files greater than 4 GB.
Each series and position require separate unwrapping (undocumented). | [
"Unwrap",
"strip",
"offsets",
"for",
"LSM",
"files",
"greater",
"than",
"4",
"GB",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L2752-L2803 | train | 52,720 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffFile._lsm_fix_strip_bytecounts | def _lsm_fix_strip_bytecounts(self):
"""Set databytecounts to size of compressed data.
The StripByteCounts tag in LSM files contains the number of bytes
for the uncompressed data.
"""
pages = self.pages
if pages[0].compression == 1:
return
# sort pages by first strip offset
pages = sorted(pages, key=lambda p: p._offsetscounts[0][0])
npages = len(pages) - 1
for i, page in enumerate(pages):
if page.index % 2:
continue
offsets, bytecounts = page._offsetscounts
if i < npages:
lastoffset = pages[i+1]._offsetscounts[0][0]
else:
# LZW compressed strips might be longer than uncompressed
lastoffset = min(offsets[-1] + 2*bytecounts[-1], self._fh.size)
for j in range(len(bytecounts) - 1):
bytecounts[j] = offsets[j+1] - offsets[j]
bytecounts[-1] = lastoffset - offsets[-1] | python | def _lsm_fix_strip_bytecounts(self):
"""Set databytecounts to size of compressed data.
The StripByteCounts tag in LSM files contains the number of bytes
for the uncompressed data.
"""
pages = self.pages
if pages[0].compression == 1:
return
# sort pages by first strip offset
pages = sorted(pages, key=lambda p: p._offsetscounts[0][0])
npages = len(pages) - 1
for i, page in enumerate(pages):
if page.index % 2:
continue
offsets, bytecounts = page._offsetscounts
if i < npages:
lastoffset = pages[i+1]._offsetscounts[0][0]
else:
# LZW compressed strips might be longer than uncompressed
lastoffset = min(offsets[-1] + 2*bytecounts[-1], self._fh.size)
for j in range(len(bytecounts) - 1):
bytecounts[j] = offsets[j+1] - offsets[j]
bytecounts[-1] = lastoffset - offsets[-1] | [
"def",
"_lsm_fix_strip_bytecounts",
"(",
"self",
")",
":",
"pages",
"=",
"self",
".",
"pages",
"if",
"pages",
"[",
"0",
"]",
".",
"compression",
"==",
"1",
":",
"return",
"# sort pages by first strip offset",
"pages",
"=",
"sorted",
"(",
"pages",
",",
"key",... | Set databytecounts to size of compressed data.
The StripByteCounts tag in LSM files contains the number of bytes
for the uncompressed data. | [
"Set",
"databytecounts",
"to",
"size",
"of",
"compressed",
"data",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L2805-L2829 | train | 52,721 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffFile.is_mdgel | def is_mdgel(self):
"""File has MD Gel format."""
# TODO: this likely reads the second page from file
try:
ismdgel = self.pages[0].is_mdgel or self.pages[1].is_mdgel
if ismdgel:
self.is_uniform = False
return ismdgel
except IndexError:
return False | python | def is_mdgel(self):
"""File has MD Gel format."""
# TODO: this likely reads the second page from file
try:
ismdgel = self.pages[0].is_mdgel or self.pages[1].is_mdgel
if ismdgel:
self.is_uniform = False
return ismdgel
except IndexError:
return False | [
"def",
"is_mdgel",
"(",
"self",
")",
":",
"# TODO: this likely reads the second page from file",
"try",
":",
"ismdgel",
"=",
"self",
".",
"pages",
"[",
"0",
"]",
".",
"is_mdgel",
"or",
"self",
".",
"pages",
"[",
"1",
"]",
".",
"is_mdgel",
"if",
"ismdgel",
... | File has MD Gel format. | [
"File",
"has",
"MD",
"Gel",
"format",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L2911-L2920 | train | 52,722 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffFile.is_uniform | def is_uniform(self):
"""Return if file contains a uniform series of pages."""
# the hashes of IFDs 0, 7, and -1 are the same
pages = self.pages
page = pages[0]
if page.is_scanimage or page.is_nih:
return True
try:
useframes = pages.useframes
pages.useframes = False
h = page.hash
for i in (1, 7, -1):
if pages[i].aspage().hash != h:
return False
except IndexError:
return False
finally:
pages.useframes = useframes
return True | python | def is_uniform(self):
"""Return if file contains a uniform series of pages."""
# the hashes of IFDs 0, 7, and -1 are the same
pages = self.pages
page = pages[0]
if page.is_scanimage or page.is_nih:
return True
try:
useframes = pages.useframes
pages.useframes = False
h = page.hash
for i in (1, 7, -1):
if pages[i].aspage().hash != h:
return False
except IndexError:
return False
finally:
pages.useframes = useframes
return True | [
"def",
"is_uniform",
"(",
"self",
")",
":",
"# the hashes of IFDs 0, 7, and -1 are the same",
"pages",
"=",
"self",
".",
"pages",
"page",
"=",
"pages",
"[",
"0",
"]",
"if",
"page",
".",
"is_scanimage",
"or",
"page",
".",
"is_nih",
":",
"return",
"True",
"try... | Return if file contains a uniform series of pages. | [
"Return",
"if",
"file",
"contains",
"a",
"uniform",
"series",
"of",
"pages",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L2923-L2941 | train | 52,723 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffFile.is_appendable | def is_appendable(self):
"""Return if pages can be appended to file without corrupting."""
# TODO: check other formats
return not (self.is_lsm or self.is_stk or self.is_imagej or
self.is_fluoview or self.is_micromanager) | python | def is_appendable(self):
"""Return if pages can be appended to file without corrupting."""
# TODO: check other formats
return not (self.is_lsm or self.is_stk or self.is_imagej or
self.is_fluoview or self.is_micromanager) | [
"def",
"is_appendable",
"(",
"self",
")",
":",
"# TODO: check other formats",
"return",
"not",
"(",
"self",
".",
"is_lsm",
"or",
"self",
".",
"is_stk",
"or",
"self",
".",
"is_imagej",
"or",
"self",
".",
"is_fluoview",
"or",
"self",
".",
"is_micromanager",
")... | Return if pages can be appended to file without corrupting. | [
"Return",
"if",
"pages",
"can",
"be",
"appended",
"to",
"file",
"without",
"corrupting",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L2944-L2948 | train | 52,724 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffFile.shaped_metadata | def shaped_metadata(self):
"""Return tifffile metadata from JSON descriptions as dicts."""
if not self.is_shaped:
return None
return tuple(json_description_metadata(s.pages[0].is_shaped)
for s in self.series if s.kind.lower() == 'shaped') | python | def shaped_metadata(self):
"""Return tifffile metadata from JSON descriptions as dicts."""
if not self.is_shaped:
return None
return tuple(json_description_metadata(s.pages[0].is_shaped)
for s in self.series if s.kind.lower() == 'shaped') | [
"def",
"shaped_metadata",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_shaped",
":",
"return",
"None",
"return",
"tuple",
"(",
"json_description_metadata",
"(",
"s",
".",
"pages",
"[",
"0",
"]",
".",
"is_shaped",
")",
"for",
"s",
"in",
"self",
... | Return tifffile metadata from JSON descriptions as dicts. | [
"Return",
"tifffile",
"metadata",
"from",
"JSON",
"descriptions",
"as",
"dicts",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L2951-L2956 | train | 52,725 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffFile.stk_metadata | def stk_metadata(self):
"""Return STK metadata from UIC tags as dict."""
if not self.is_stk:
return None
page = self.pages[0]
tags = page.tags
result = {}
result['NumberPlanes'] = tags['UIC2tag'].count
if page.description:
result['PlaneDescriptions'] = page.description.split('\0')
# result['plane_descriptions'] = stk_description_metadata(
# page.image_description)
if 'UIC1tag' in tags:
result.update(tags['UIC1tag'].value)
if 'UIC3tag' in tags:
result.update(tags['UIC3tag'].value) # wavelengths
if 'UIC4tag' in tags:
result.update(tags['UIC4tag'].value) # override uic1 tags
uic2tag = tags['UIC2tag'].value
result['ZDistance'] = uic2tag['ZDistance']
result['TimeCreated'] = uic2tag['TimeCreated']
result['TimeModified'] = uic2tag['TimeModified']
try:
result['DatetimeCreated'] = numpy.array(
[julian_datetime(*dt) for dt in
zip(uic2tag['DateCreated'], uic2tag['TimeCreated'])],
dtype='datetime64[ns]')
result['DatetimeModified'] = numpy.array(
[julian_datetime(*dt) for dt in
zip(uic2tag['DateModified'], uic2tag['TimeModified'])],
dtype='datetime64[ns]')
except ValueError as exc:
log.warning('STK metadata: %s: %s', exc.__class__.__name__, exc)
return result | python | def stk_metadata(self):
"""Return STK metadata from UIC tags as dict."""
if not self.is_stk:
return None
page = self.pages[0]
tags = page.tags
result = {}
result['NumberPlanes'] = tags['UIC2tag'].count
if page.description:
result['PlaneDescriptions'] = page.description.split('\0')
# result['plane_descriptions'] = stk_description_metadata(
# page.image_description)
if 'UIC1tag' in tags:
result.update(tags['UIC1tag'].value)
if 'UIC3tag' in tags:
result.update(tags['UIC3tag'].value) # wavelengths
if 'UIC4tag' in tags:
result.update(tags['UIC4tag'].value) # override uic1 tags
uic2tag = tags['UIC2tag'].value
result['ZDistance'] = uic2tag['ZDistance']
result['TimeCreated'] = uic2tag['TimeCreated']
result['TimeModified'] = uic2tag['TimeModified']
try:
result['DatetimeCreated'] = numpy.array(
[julian_datetime(*dt) for dt in
zip(uic2tag['DateCreated'], uic2tag['TimeCreated'])],
dtype='datetime64[ns]')
result['DatetimeModified'] = numpy.array(
[julian_datetime(*dt) for dt in
zip(uic2tag['DateModified'], uic2tag['TimeModified'])],
dtype='datetime64[ns]')
except ValueError as exc:
log.warning('STK metadata: %s: %s', exc.__class__.__name__, exc)
return result | [
"def",
"stk_metadata",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_stk",
":",
"return",
"None",
"page",
"=",
"self",
".",
"pages",
"[",
"0",
"]",
"tags",
"=",
"page",
".",
"tags",
"result",
"=",
"{",
"}",
"result",
"[",
"'NumberPlanes'",
"... | Return STK metadata from UIC tags as dict. | [
"Return",
"STK",
"metadata",
"from",
"UIC",
"tags",
"as",
"dict",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L2974-L3007 | train | 52,726 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffFile.imagej_metadata | def imagej_metadata(self):
"""Return consolidated ImageJ metadata as dict."""
if not self.is_imagej:
return None
page = self.pages[0]
result = imagej_description_metadata(page.is_imagej)
if 'IJMetadata' in page.tags:
try:
result.update(page.tags['IJMetadata'].value)
except Exception:
pass
return result | python | def imagej_metadata(self):
"""Return consolidated ImageJ metadata as dict."""
if not self.is_imagej:
return None
page = self.pages[0]
result = imagej_description_metadata(page.is_imagej)
if 'IJMetadata' in page.tags:
try:
result.update(page.tags['IJMetadata'].value)
except Exception:
pass
return result | [
"def",
"imagej_metadata",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_imagej",
":",
"return",
"None",
"page",
"=",
"self",
".",
"pages",
"[",
"0",
"]",
"result",
"=",
"imagej_description_metadata",
"(",
"page",
".",
"is_imagej",
")",
"if",
"'IJM... | Return consolidated ImageJ metadata as dict. | [
"Return",
"consolidated",
"ImageJ",
"metadata",
"as",
"dict",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L3010-L3021 | train | 52,727 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffFile.fluoview_metadata | def fluoview_metadata(self):
"""Return consolidated FluoView metadata as dict."""
if not self.is_fluoview:
return None
result = {}
page = self.pages[0]
result.update(page.tags['MM_Header'].value)
# TODO: read stamps from all pages
result['Stamp'] = page.tags['MM_Stamp'].value
# skip parsing image description; not reliable
# try:
# t = fluoview_description_metadata(page.image_description)
# if t is not None:
# result['ImageDescription'] = t
# except Exception as exc:
# log.warning('FluoView metadata: '
# 'failed to parse image description (%s)', str(exc))
return result | python | def fluoview_metadata(self):
"""Return consolidated FluoView metadata as dict."""
if not self.is_fluoview:
return None
result = {}
page = self.pages[0]
result.update(page.tags['MM_Header'].value)
# TODO: read stamps from all pages
result['Stamp'] = page.tags['MM_Stamp'].value
# skip parsing image description; not reliable
# try:
# t = fluoview_description_metadata(page.image_description)
# if t is not None:
# result['ImageDescription'] = t
# except Exception as exc:
# log.warning('FluoView metadata: '
# 'failed to parse image description (%s)', str(exc))
return result | [
"def",
"fluoview_metadata",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_fluoview",
":",
"return",
"None",
"result",
"=",
"{",
"}",
"page",
"=",
"self",
".",
"pages",
"[",
"0",
"]",
"result",
".",
"update",
"(",
"page",
".",
"tags",
"[",
"'... | Return consolidated FluoView metadata as dict. | [
"Return",
"consolidated",
"FluoView",
"metadata",
"as",
"dict",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L3024-L3041 | train | 52,728 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffFile.fei_metadata | def fei_metadata(self):
"""Return FEI metadata from SFEG or HELIOS tags as dict."""
if not self.is_fei:
return None
tags = self.pages[0].tags
if 'FEI_SFEG' in tags:
return tags['FEI_SFEG'].value
if 'FEI_HELIOS' in tags:
return tags['FEI_HELIOS'].value
return None | python | def fei_metadata(self):
"""Return FEI metadata from SFEG or HELIOS tags as dict."""
if not self.is_fei:
return None
tags = self.pages[0].tags
if 'FEI_SFEG' in tags:
return tags['FEI_SFEG'].value
if 'FEI_HELIOS' in tags:
return tags['FEI_HELIOS'].value
return None | [
"def",
"fei_metadata",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_fei",
":",
"return",
"None",
"tags",
"=",
"self",
".",
"pages",
"[",
"0",
"]",
".",
"tags",
"if",
"'FEI_SFEG'",
"in",
"tags",
":",
"return",
"tags",
"[",
"'FEI_SFEG'",
"]",
... | Return FEI metadata from SFEG or HELIOS tags as dict. | [
"Return",
"FEI",
"metadata",
"from",
"SFEG",
"or",
"HELIOS",
"tags",
"as",
"dict",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L3051-L3060 | train | 52,729 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffFile.sis_metadata | def sis_metadata(self):
"""Return Olympus SIS metadata from SIS and INI tags as dict."""
if not self.is_sis:
return None
tags = self.pages[0].tags
result = {}
try:
result.update(tags['OlympusINI'].value)
except Exception:
pass
try:
result.update(tags['OlympusSIS'].value)
except Exception:
pass
return result | python | def sis_metadata(self):
"""Return Olympus SIS metadata from SIS and INI tags as dict."""
if not self.is_sis:
return None
tags = self.pages[0].tags
result = {}
try:
result.update(tags['OlympusINI'].value)
except Exception:
pass
try:
result.update(tags['OlympusSIS'].value)
except Exception:
pass
return result | [
"def",
"sis_metadata",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_sis",
":",
"return",
"None",
"tags",
"=",
"self",
".",
"pages",
"[",
"0",
"]",
".",
"tags",
"result",
"=",
"{",
"}",
"try",
":",
"result",
".",
"update",
"(",
"tags",
"["... | Return Olympus SIS metadata from SIS and INI tags as dict. | [
"Return",
"Olympus",
"SIS",
"metadata",
"from",
"SIS",
"and",
"INI",
"tags",
"as",
"dict",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L3070-L3084 | train | 52,730 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffFile.mdgel_metadata | def mdgel_metadata(self):
"""Return consolidated metadata from MD GEL tags as dict."""
for page in self.pages[:2]:
if 'MDFileTag' in page.tags:
tags = page.tags
break
else:
return None
result = {}
for code in range(33445, 33453):
name = TIFF.TAGS[code]
if name not in tags:
continue
result[name[2:]] = tags[name].value
return result | python | def mdgel_metadata(self):
"""Return consolidated metadata from MD GEL tags as dict."""
for page in self.pages[:2]:
if 'MDFileTag' in page.tags:
tags = page.tags
break
else:
return None
result = {}
for code in range(33445, 33453):
name = TIFF.TAGS[code]
if name not in tags:
continue
result[name[2:]] = tags[name].value
return result | [
"def",
"mdgel_metadata",
"(",
"self",
")",
":",
"for",
"page",
"in",
"self",
".",
"pages",
"[",
":",
"2",
"]",
":",
"if",
"'MDFileTag'",
"in",
"page",
".",
"tags",
":",
"tags",
"=",
"page",
".",
"tags",
"break",
"else",
":",
"return",
"None",
"resu... | Return consolidated metadata from MD GEL tags as dict. | [
"Return",
"consolidated",
"metadata",
"from",
"MD",
"GEL",
"tags",
"as",
"dict",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L3087-L3101 | train | 52,731 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffFile.micromanager_metadata | def micromanager_metadata(self):
"""Return consolidated MicroManager metadata as dict."""
if not self.is_micromanager:
return None
# from file header
result = read_micromanager_metadata(self._fh)
# from tag
result.update(self.pages[0].tags['MicroManagerMetadata'].value)
return result | python | def micromanager_metadata(self):
"""Return consolidated MicroManager metadata as dict."""
if not self.is_micromanager:
return None
# from file header
result = read_micromanager_metadata(self._fh)
# from tag
result.update(self.pages[0].tags['MicroManagerMetadata'].value)
return result | [
"def",
"micromanager_metadata",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_micromanager",
":",
"return",
"None",
"# from file header",
"result",
"=",
"read_micromanager_metadata",
"(",
"self",
".",
"_fh",
")",
"# from tag",
"result",
".",
"update",
"("... | Return consolidated MicroManager metadata as dict. | [
"Return",
"consolidated",
"MicroManager",
"metadata",
"as",
"dict",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L3135-L3143 | train | 52,732 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffFile.scanimage_metadata | def scanimage_metadata(self):
"""Return ScanImage non-varying frame and ROI metadata as dict."""
if not self.is_scanimage:
return None
result = {}
try:
framedata, roidata = read_scanimage_metadata(self._fh)
result['FrameData'] = framedata
result.update(roidata)
except ValueError:
pass
# TODO: scanimage_artist_metadata
try:
result['Description'] = scanimage_description_metadata(
self.pages[0].description)
except Exception as exc:
log.warning('ScanImage metadata: %s: %s',
exc.__class__.__name__, exc)
return result | python | def scanimage_metadata(self):
"""Return ScanImage non-varying frame and ROI metadata as dict."""
if not self.is_scanimage:
return None
result = {}
try:
framedata, roidata = read_scanimage_metadata(self._fh)
result['FrameData'] = framedata
result.update(roidata)
except ValueError:
pass
# TODO: scanimage_artist_metadata
try:
result['Description'] = scanimage_description_metadata(
self.pages[0].description)
except Exception as exc:
log.warning('ScanImage metadata: %s: %s',
exc.__class__.__name__, exc)
return result | [
"def",
"scanimage_metadata",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_scanimage",
":",
"return",
"None",
"result",
"=",
"{",
"}",
"try",
":",
"framedata",
",",
"roidata",
"=",
"read_scanimage_metadata",
"(",
"self",
".",
"_fh",
")",
"result",
... | Return ScanImage non-varying frame and ROI metadata as dict. | [
"Return",
"ScanImage",
"non",
"-",
"varying",
"frame",
"and",
"ROI",
"metadata",
"as",
"dict",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L3146-L3164 | train | 52,733 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffPages.keyframe | def keyframe(self, index):
"""Set current keyframe. Load TiffPage from file if necessary."""
index = int(index)
if index < 0:
index %= len(self)
if self._keyframe.index == index:
return
if index == 0:
self._keyframe = self.pages[0]
return
if self._indexed or index < len(self.pages):
page = self.pages[index]
if isinstance(page, TiffPage):
self._keyframe = page
return
if isinstance(page, TiffFrame):
# remove existing TiffFrame
self.pages[index] = page.offset
# load TiffPage from file
tiffpage = self._tiffpage
self._tiffpage = TiffPage
try:
self._keyframe = self._getitem(index)
finally:
self._tiffpage = tiffpage
# always cache keyframes
self.pages[index] = self._keyframe | python | def keyframe(self, index):
"""Set current keyframe. Load TiffPage from file if necessary."""
index = int(index)
if index < 0:
index %= len(self)
if self._keyframe.index == index:
return
if index == 0:
self._keyframe = self.pages[0]
return
if self._indexed or index < len(self.pages):
page = self.pages[index]
if isinstance(page, TiffPage):
self._keyframe = page
return
if isinstance(page, TiffFrame):
# remove existing TiffFrame
self.pages[index] = page.offset
# load TiffPage from file
tiffpage = self._tiffpage
self._tiffpage = TiffPage
try:
self._keyframe = self._getitem(index)
finally:
self._tiffpage = tiffpage
# always cache keyframes
self.pages[index] = self._keyframe | [
"def",
"keyframe",
"(",
"self",
",",
"index",
")",
":",
"index",
"=",
"int",
"(",
"index",
")",
"if",
"index",
"<",
"0",
":",
"index",
"%=",
"len",
"(",
"self",
")",
"if",
"self",
".",
"_keyframe",
".",
"index",
"==",
"index",
":",
"return",
"if"... | Set current keyframe. Load TiffPage from file if necessary. | [
"Set",
"current",
"keyframe",
".",
"Load",
"TiffPage",
"from",
"file",
"if",
"necessary",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L3264-L3290 | train | 52,734 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffPages._load | def _load(self, keyframe=True):
"""Read all remaining pages from file."""
if self._cached:
return
pages = self.pages
if not pages:
return
if not self._indexed:
self._seek(-1)
if not self._cache:
return
fh = self.parent.filehandle
if keyframe is not None:
keyframe = self._keyframe
for i, page in enumerate(pages):
if isinstance(page, inttypes):
fh.seek(page)
page = self._tiffpage(self.parent, index=i, keyframe=keyframe)
pages[i] = page
self._cached = True | python | def _load(self, keyframe=True):
"""Read all remaining pages from file."""
if self._cached:
return
pages = self.pages
if not pages:
return
if not self._indexed:
self._seek(-1)
if not self._cache:
return
fh = self.parent.filehandle
if keyframe is not None:
keyframe = self._keyframe
for i, page in enumerate(pages):
if isinstance(page, inttypes):
fh.seek(page)
page = self._tiffpage(self.parent, index=i, keyframe=keyframe)
pages[i] = page
self._cached = True | [
"def",
"_load",
"(",
"self",
",",
"keyframe",
"=",
"True",
")",
":",
"if",
"self",
".",
"_cached",
":",
"return",
"pages",
"=",
"self",
".",
"pages",
"if",
"not",
"pages",
":",
"return",
"if",
"not",
"self",
".",
"_indexed",
":",
"self",
".",
"_see... | Read all remaining pages from file. | [
"Read",
"all",
"remaining",
"pages",
"from",
"file",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L3299-L3318 | train | 52,735 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffPages._load_virtual_frames | def _load_virtual_frames(self):
"""Calculate virtual TiffFrames."""
pages = self.pages
try:
if sys.version_info[0] == 2:
raise ValueError('not supported on Python 2')
if len(pages) > 1:
raise ValueError('pages already loaded')
page = pages[0]
bytecounts = page._offsetscounts[1]
if len(bytecounts) != 1:
raise ValueError('data not contiguous')
self._seek(4)
delta = pages[2] - pages[1]
if pages[3] - pages[2] != delta or pages[4] - pages[3] != delta:
raise ValueError('page offsets not equidistant')
page1 = self._getitem(1, validate=page.hash)
offsetoffset = page1._offsetscounts[0][0] - page1.offset
if offsetoffset < 0 or offsetoffset > delta:
raise ValueError('page offsets not equidistant')
pages = [page, page1]
filesize = self.parent.filehandle.size - delta
for index, offset in enumerate(range(page1.offset+delta,
filesize, delta)):
offsets = [offset + offsetoffset]
offset = offset if offset < 2**31 else None
pages.append(
TiffFrame(parent=page.parent, index=index+2, offset=None,
offsets=offsets, bytecounts=bytecounts,
keyframe=page))
except Exception as exc:
log.warning(
'TiffPages: failed to load virtual frames: %s', str(exc))
assert pages[1]
self.pages = pages
self._cache = True
self._cached = True
self._indexed = True | python | def _load_virtual_frames(self):
"""Calculate virtual TiffFrames."""
pages = self.pages
try:
if sys.version_info[0] == 2:
raise ValueError('not supported on Python 2')
if len(pages) > 1:
raise ValueError('pages already loaded')
page = pages[0]
bytecounts = page._offsetscounts[1]
if len(bytecounts) != 1:
raise ValueError('data not contiguous')
self._seek(4)
delta = pages[2] - pages[1]
if pages[3] - pages[2] != delta or pages[4] - pages[3] != delta:
raise ValueError('page offsets not equidistant')
page1 = self._getitem(1, validate=page.hash)
offsetoffset = page1._offsetscounts[0][0] - page1.offset
if offsetoffset < 0 or offsetoffset > delta:
raise ValueError('page offsets not equidistant')
pages = [page, page1]
filesize = self.parent.filehandle.size - delta
for index, offset in enumerate(range(page1.offset+delta,
filesize, delta)):
offsets = [offset + offsetoffset]
offset = offset if offset < 2**31 else None
pages.append(
TiffFrame(parent=page.parent, index=index+2, offset=None,
offsets=offsets, bytecounts=bytecounts,
keyframe=page))
except Exception as exc:
log.warning(
'TiffPages: failed to load virtual frames: %s', str(exc))
assert pages[1]
self.pages = pages
self._cache = True
self._cached = True
self._indexed = True | [
"def",
"_load_virtual_frames",
"(",
"self",
")",
":",
"pages",
"=",
"self",
".",
"pages",
"try",
":",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"==",
"2",
":",
"raise",
"ValueError",
"(",
"'not supported on Python 2'",
")",
"if",
"len",
"(",
"page... | Calculate virtual TiffFrames. | [
"Calculate",
"virtual",
"TiffFrames",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L3320-L3357 | train | 52,736 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffPages._clear | def _clear(self, fully=True):
"""Delete all but first page from cache. Set keyframe to first page."""
pages = self.pages
if not pages:
return
self._keyframe = pages[0]
if fully:
# delete all but first TiffPage/TiffFrame
for i, page in enumerate(pages[1:]):
if not isinstance(page, inttypes) and page.offset is not None:
pages[i+1] = page.offset
elif TiffFrame is not TiffPage:
# delete only TiffFrames
for i, page in enumerate(pages):
if isinstance(page, TiffFrame) and page.offset is not None:
pages[i] = page.offset
self._cached = False | python | def _clear(self, fully=True):
"""Delete all but first page from cache. Set keyframe to first page."""
pages = self.pages
if not pages:
return
self._keyframe = pages[0]
if fully:
# delete all but first TiffPage/TiffFrame
for i, page in enumerate(pages[1:]):
if not isinstance(page, inttypes) and page.offset is not None:
pages[i+1] = page.offset
elif TiffFrame is not TiffPage:
# delete only TiffFrames
for i, page in enumerate(pages):
if isinstance(page, TiffFrame) and page.offset is not None:
pages[i] = page.offset
self._cached = False | [
"def",
"_clear",
"(",
"self",
",",
"fully",
"=",
"True",
")",
":",
"pages",
"=",
"self",
".",
"pages",
"if",
"not",
"pages",
":",
"return",
"self",
".",
"_keyframe",
"=",
"pages",
"[",
"0",
"]",
"if",
"fully",
":",
"# delete all but first TiffPage/TiffFr... | Delete all but first page from cache. Set keyframe to first page. | [
"Delete",
"all",
"but",
"first",
"page",
"from",
"cache",
".",
"Set",
"keyframe",
"to",
"first",
"page",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L3359-L3375 | train | 52,737 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffPages._seek | def _seek(self, index, maxpages=None):
"""Seek file to offset of page specified by index."""
pages = self.pages
lenpages = len(pages)
if lenpages == 0:
raise IndexError('index out of range')
fh = self.parent.filehandle
if fh.closed:
raise ValueError('seek of closed file')
if self._indexed or 0 <= index < lenpages:
page = pages[index]
offset = page if isinstance(page, inttypes) else page.offset
fh.seek(offset)
return
tiff = self.parent.tiff
offsetformat = tiff.ifdoffsetformat
offsetsize = tiff.ifdoffsetsize
tagnoformat = tiff.tagnoformat
tagnosize = tiff.tagnosize
tagsize = tiff.tagsize
unpack = struct.unpack
page = pages[-1]
offset = page if isinstance(page, inttypes) else page.offset
if maxpages is None:
maxpages = 2**22
while lenpages < maxpages:
# read offsets to pages from file until index is reached
fh.seek(offset)
# skip tags
try:
tagno = unpack(tagnoformat, fh.read(tagnosize))[0]
if tagno > 4096:
raise TiffFileError(
'suspicious number of tags: %i' % tagno)
except Exception:
log.warning('TiffPages: corrupted tag list of page %i @ %i',
lenpages, offset)
del pages[-1]
lenpages -= 1
self._indexed = True
break
self._nextpageoffset = offset + tagnosize + tagno * tagsize
fh.seek(self._nextpageoffset)
# read offset to next page
offset = unpack(offsetformat, fh.read(offsetsize))[0]
if offset == 0:
self._indexed = True
break
if offset >= fh.size:
log.warning('TiffPages: invalid page offset (%i)', offset)
self._indexed = True
break
pages.append(offset)
lenpages += 1
if 0 <= index < lenpages:
break
# detect some circular references
if lenpages == 100:
for p in pages[:-1]:
if offset == (p if isinstance(p, inttypes) else p.offset):
raise TiffFileError('invalid circular IFD reference')
if index >= lenpages:
raise IndexError('index out of range')
page = pages[index]
fh.seek(page if isinstance(page, inttypes) else page.offset) | python | def _seek(self, index, maxpages=None):
"""Seek file to offset of page specified by index."""
pages = self.pages
lenpages = len(pages)
if lenpages == 0:
raise IndexError('index out of range')
fh = self.parent.filehandle
if fh.closed:
raise ValueError('seek of closed file')
if self._indexed or 0 <= index < lenpages:
page = pages[index]
offset = page if isinstance(page, inttypes) else page.offset
fh.seek(offset)
return
tiff = self.parent.tiff
offsetformat = tiff.ifdoffsetformat
offsetsize = tiff.ifdoffsetsize
tagnoformat = tiff.tagnoformat
tagnosize = tiff.tagnosize
tagsize = tiff.tagsize
unpack = struct.unpack
page = pages[-1]
offset = page if isinstance(page, inttypes) else page.offset
if maxpages is None:
maxpages = 2**22
while lenpages < maxpages:
# read offsets to pages from file until index is reached
fh.seek(offset)
# skip tags
try:
tagno = unpack(tagnoformat, fh.read(tagnosize))[0]
if tagno > 4096:
raise TiffFileError(
'suspicious number of tags: %i' % tagno)
except Exception:
log.warning('TiffPages: corrupted tag list of page %i @ %i',
lenpages, offset)
del pages[-1]
lenpages -= 1
self._indexed = True
break
self._nextpageoffset = offset + tagnosize + tagno * tagsize
fh.seek(self._nextpageoffset)
# read offset to next page
offset = unpack(offsetformat, fh.read(offsetsize))[0]
if offset == 0:
self._indexed = True
break
if offset >= fh.size:
log.warning('TiffPages: invalid page offset (%i)', offset)
self._indexed = True
break
pages.append(offset)
lenpages += 1
if 0 <= index < lenpages:
break
# detect some circular references
if lenpages == 100:
for p in pages[:-1]:
if offset == (p if isinstance(p, inttypes) else p.offset):
raise TiffFileError('invalid circular IFD reference')
if index >= lenpages:
raise IndexError('index out of range')
page = pages[index]
fh.seek(page if isinstance(page, inttypes) else page.offset) | [
"def",
"_seek",
"(",
"self",
",",
"index",
",",
"maxpages",
"=",
"None",
")",
":",
"pages",
"=",
"self",
".",
"pages",
"lenpages",
"=",
"len",
"(",
"pages",
")",
"if",
"lenpages",
"==",
"0",
":",
"raise",
"IndexError",
"(",
"'index out of range'",
")",... | Seek file to offset of page specified by index. | [
"Seek",
"file",
"to",
"offset",
"of",
"page",
"specified",
"by",
"index",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L3377-L3451 | train | 52,738 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffPages._getlist | def _getlist(self, key=None, useframes=True, validate=True):
"""Return specified pages as list of TiffPages or TiffFrames.
The first item is a TiffPage, and is used as a keyframe for
following TiffFrames.
"""
getitem = self._getitem
_useframes = self.useframes
if key is None:
key = iter(range(len(self)))
elif isinstance(key, Iterable):
key = iter(key)
elif isinstance(key, slice):
start, stop, _ = key.indices(2**31-1)
if not self._indexed and max(stop, start) > len(self.pages):
self._seek(-1)
key = iter(range(*key.indices(len(self.pages))))
elif isinstance(key, inttypes):
# return single TiffPage
self.useframes = False
if key == 0:
return [self.pages[key]]
try:
return [getitem(key)]
finally:
self.useframes = _useframes
else:
raise TypeError('key must be an integer, slice, or iterable')
# use first page as keyframe
keyframe = self._keyframe
self.keyframe = next(key)
if validate:
validate = self._keyframe.hash
if useframes:
self.useframes = True
try:
pages = [getitem(i, validate) for i in key]
pages.insert(0, self._keyframe)
finally:
# restore state
self._keyframe = keyframe
if useframes:
self.useframes = _useframes
return pages | python | def _getlist(self, key=None, useframes=True, validate=True):
"""Return specified pages as list of TiffPages or TiffFrames.
The first item is a TiffPage, and is used as a keyframe for
following TiffFrames.
"""
getitem = self._getitem
_useframes = self.useframes
if key is None:
key = iter(range(len(self)))
elif isinstance(key, Iterable):
key = iter(key)
elif isinstance(key, slice):
start, stop, _ = key.indices(2**31-1)
if not self._indexed and max(stop, start) > len(self.pages):
self._seek(-1)
key = iter(range(*key.indices(len(self.pages))))
elif isinstance(key, inttypes):
# return single TiffPage
self.useframes = False
if key == 0:
return [self.pages[key]]
try:
return [getitem(key)]
finally:
self.useframes = _useframes
else:
raise TypeError('key must be an integer, slice, or iterable')
# use first page as keyframe
keyframe = self._keyframe
self.keyframe = next(key)
if validate:
validate = self._keyframe.hash
if useframes:
self.useframes = True
try:
pages = [getitem(i, validate) for i in key]
pages.insert(0, self._keyframe)
finally:
# restore state
self._keyframe = keyframe
if useframes:
self.useframes = _useframes
return pages | [
"def",
"_getlist",
"(",
"self",
",",
"key",
"=",
"None",
",",
"useframes",
"=",
"True",
",",
"validate",
"=",
"True",
")",
":",
"getitem",
"=",
"self",
".",
"_getitem",
"_useframes",
"=",
"self",
".",
"useframes",
"if",
"key",
"is",
"None",
":",
"key... | Return specified pages as list of TiffPages or TiffFrames.
The first item is a TiffPage, and is used as a keyframe for
following TiffFrames. | [
"Return",
"specified",
"pages",
"as",
"list",
"of",
"TiffPages",
"or",
"TiffFrames",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L3453-L3500 | train | 52,739 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffPages._getitem | def _getitem(self, key, validate=False):
"""Return specified page from cache or file."""
key = int(key)
pages = self.pages
if key < 0:
key %= len(self)
elif self._indexed and key >= len(pages):
raise IndexError('index out of range')
if key < len(pages):
page = pages[key]
if self._cache:
if not isinstance(page, inttypes):
if validate and validate != page.hash:
raise RuntimeError('page hash mismatch')
return page
elif isinstance(page, (TiffPage, self._tiffpage)):
if validate and validate != page.hash:
raise RuntimeError('page hash mismatch')
return page
self._seek(key)
page = self._tiffpage(self.parent, index=key, keyframe=self._keyframe)
if validate and validate != page.hash:
raise RuntimeError('page hash mismatch')
if self._cache:
pages[key] = page
return page | python | def _getitem(self, key, validate=False):
"""Return specified page from cache or file."""
key = int(key)
pages = self.pages
if key < 0:
key %= len(self)
elif self._indexed and key >= len(pages):
raise IndexError('index out of range')
if key < len(pages):
page = pages[key]
if self._cache:
if not isinstance(page, inttypes):
if validate and validate != page.hash:
raise RuntimeError('page hash mismatch')
return page
elif isinstance(page, (TiffPage, self._tiffpage)):
if validate and validate != page.hash:
raise RuntimeError('page hash mismatch')
return page
self._seek(key)
page = self._tiffpage(self.parent, index=key, keyframe=self._keyframe)
if validate and validate != page.hash:
raise RuntimeError('page hash mismatch')
if self._cache:
pages[key] = page
return page | [
"def",
"_getitem",
"(",
"self",
",",
"key",
",",
"validate",
"=",
"False",
")",
":",
"key",
"=",
"int",
"(",
"key",
")",
"pages",
"=",
"self",
".",
"pages",
"if",
"key",
"<",
"0",
":",
"key",
"%=",
"len",
"(",
"self",
")",
"elif",
"self",
".",
... | Return specified page from cache or file. | [
"Return",
"specified",
"page",
"from",
"cache",
"or",
"file",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L3502-L3530 | train | 52,740 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffPage.hash | def hash(self):
"""Return checksum to identify pages in same series."""
return hash(
self._shape + (
self.tilewidth, self.tilelength, self.tiledepth,
self.bitspersample, self.fillorder, self.predictor,
self.extrasamples, self.photometric, self.compression,
self.planarconfig)) | python | def hash(self):
"""Return checksum to identify pages in same series."""
return hash(
self._shape + (
self.tilewidth, self.tilelength, self.tiledepth,
self.bitspersample, self.fillorder, self.predictor,
self.extrasamples, self.photometric, self.compression,
self.planarconfig)) | [
"def",
"hash",
"(",
"self",
")",
":",
"return",
"hash",
"(",
"self",
".",
"_shape",
"+",
"(",
"self",
".",
"tilewidth",
",",
"self",
".",
"tilelength",
",",
"self",
".",
"tiledepth",
",",
"self",
".",
"bitspersample",
",",
"self",
".",
"fillorder",
"... | Return checksum to identify pages in same series. | [
"Return",
"checksum",
"to",
"identify",
"pages",
"in",
"same",
"series",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L4240-L4247 | train | 52,741 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffPage._offsetscounts | def _offsetscounts(self):
"""Return simplified offsets and bytecounts."""
if self.is_contiguous:
offset, bytecount = self.is_contiguous
return [offset], [bytecount]
if self.is_tiled:
return self.dataoffsets, self.databytecounts
return clean_offsetscounts(self.dataoffsets, self.databytecounts) | python | def _offsetscounts(self):
"""Return simplified offsets and bytecounts."""
if self.is_contiguous:
offset, bytecount = self.is_contiguous
return [offset], [bytecount]
if self.is_tiled:
return self.dataoffsets, self.databytecounts
return clean_offsetscounts(self.dataoffsets, self.databytecounts) | [
"def",
"_offsetscounts",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_contiguous",
":",
"offset",
",",
"bytecount",
"=",
"self",
".",
"is_contiguous",
"return",
"[",
"offset",
"]",
",",
"[",
"bytecount",
"]",
"if",
"self",
".",
"is_tiled",
":",
"return"... | Return simplified offsets and bytecounts. | [
"Return",
"simplified",
"offsets",
"and",
"bytecounts",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L4250-L4257 | train | 52,742 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffPage.is_final | def is_final(self):
"""Return if page's image data are stored in final form.
Excludes byte-swapping.
"""
return (self.is_contiguous and self.fillorder == 1 and
self.predictor == 1 and not self.is_subsampled) | python | def is_final(self):
"""Return if page's image data are stored in final form.
Excludes byte-swapping.
"""
return (self.is_contiguous and self.fillorder == 1 and
self.predictor == 1 and not self.is_subsampled) | [
"def",
"is_final",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"is_contiguous",
"and",
"self",
".",
"fillorder",
"==",
"1",
"and",
"self",
".",
"predictor",
"==",
"1",
"and",
"not",
"self",
".",
"is_subsampled",
")"
] | Return if page's image data are stored in final form.
Excludes byte-swapping. | [
"Return",
"if",
"page",
"s",
"image",
"data",
"are",
"stored",
"in",
"final",
"form",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L4290-L4297 | train | 52,743 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffPage.is_memmappable | def is_memmappable(self):
"""Return if page's image data in file can be memory-mapped."""
return (self.parent.filehandle.is_file and self.is_final and
# (self.bitspersample == 8 or self.parent.isnative) and
self.is_contiguous[0] % self.dtype.itemsize == 0) | python | def is_memmappable(self):
"""Return if page's image data in file can be memory-mapped."""
return (self.parent.filehandle.is_file and self.is_final and
# (self.bitspersample == 8 or self.parent.isnative) and
self.is_contiguous[0] % self.dtype.itemsize == 0) | [
"def",
"is_memmappable",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"parent",
".",
"filehandle",
".",
"is_file",
"and",
"self",
".",
"is_final",
"and",
"# (self.bitspersample == 8 or self.parent.isnative) and",
"self",
".",
"is_contiguous",
"[",
"0",
"]",
... | Return if page's image data in file can be memory-mapped. | [
"Return",
"if",
"page",
"s",
"image",
"data",
"in",
"file",
"can",
"be",
"memory",
"-",
"mapped",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L4300-L4304 | train | 52,744 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffPage.flags | def flags(self):
"""Return set of flags."""
return set((name.lower() for name in sorted(TIFF.FILE_FLAGS)
if getattr(self, 'is_' + name))) | python | def flags(self):
"""Return set of flags."""
return set((name.lower() for name in sorted(TIFF.FILE_FLAGS)
if getattr(self, 'is_' + name))) | [
"def",
"flags",
"(",
"self",
")",
":",
"return",
"set",
"(",
"(",
"name",
".",
"lower",
"(",
")",
"for",
"name",
"in",
"sorted",
"(",
"TIFF",
".",
"FILE_FLAGS",
")",
"if",
"getattr",
"(",
"self",
",",
"'is_'",
"+",
"name",
")",
")",
")"
] | Return set of flags. | [
"Return",
"set",
"of",
"flags",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L4366-L4369 | train | 52,745 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffPage.andor_tags | def andor_tags(self):
"""Return consolidated metadata from Andor tags as dict.
Remove Andor tags from self.tags.
"""
if not self.is_andor:
return None
tags = self.tags
result = {'Id': tags['AndorId'].value}
for tag in list(self.tags.values()):
code = tag.code
if not 4864 < code < 5031:
continue
value = tag.value
name = tag.name[5:] if len(tag.name) > 5 else tag.name
result[name] = value
del tags[tag.name]
return result | python | def andor_tags(self):
"""Return consolidated metadata from Andor tags as dict.
Remove Andor tags from self.tags.
"""
if not self.is_andor:
return None
tags = self.tags
result = {'Id': tags['AndorId'].value}
for tag in list(self.tags.values()):
code = tag.code
if not 4864 < code < 5031:
continue
value = tag.value
name = tag.name[5:] if len(tag.name) > 5 else tag.name
result[name] = value
del tags[tag.name]
return result | [
"def",
"andor_tags",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_andor",
":",
"return",
"None",
"tags",
"=",
"self",
".",
"tags",
"result",
"=",
"{",
"'Id'",
":",
"tags",
"[",
"'AndorId'",
"]",
".",
"value",
"}",
"for",
"tag",
"in",
"list"... | Return consolidated metadata from Andor tags as dict.
Remove Andor tags from self.tags. | [
"Return",
"consolidated",
"metadata",
"from",
"Andor",
"tags",
"as",
"dict",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L4382-L4400 | train | 52,746 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffPage.epics_tags | def epics_tags(self):
"""Return consolidated metadata from EPICS areaDetector tags as dict.
Remove areaDetector tags from self.tags.
"""
if not self.is_epics:
return None
result = {}
tags = self.tags
for tag in list(self.tags.values()):
code = tag.code
if not 65000 <= code < 65500:
continue
value = tag.value
if code == 65000:
result['timeStamp'] = datetime.datetime.fromtimestamp(
float(value))
elif code == 65001:
result['uniqueID'] = int(value)
elif code == 65002:
result['epicsTSSec'] = int(value)
elif code == 65003:
result['epicsTSNsec'] = int(value)
else:
key, value = value.split(':', 1)
result[key] = astype(value)
del tags[tag.name]
return result | python | def epics_tags(self):
"""Return consolidated metadata from EPICS areaDetector tags as dict.
Remove areaDetector tags from self.tags.
"""
if not self.is_epics:
return None
result = {}
tags = self.tags
for tag in list(self.tags.values()):
code = tag.code
if not 65000 <= code < 65500:
continue
value = tag.value
if code == 65000:
result['timeStamp'] = datetime.datetime.fromtimestamp(
float(value))
elif code == 65001:
result['uniqueID'] = int(value)
elif code == 65002:
result['epicsTSSec'] = int(value)
elif code == 65003:
result['epicsTSNsec'] = int(value)
else:
key, value = value.split(':', 1)
result[key] = astype(value)
del tags[tag.name]
return result | [
"def",
"epics_tags",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_epics",
":",
"return",
"None",
"result",
"=",
"{",
"}",
"tags",
"=",
"self",
".",
"tags",
"for",
"tag",
"in",
"list",
"(",
"self",
".",
"tags",
".",
"values",
"(",
")",
")"... | Return consolidated metadata from EPICS areaDetector tags as dict.
Remove areaDetector tags from self.tags. | [
"Return",
"consolidated",
"metadata",
"from",
"EPICS",
"areaDetector",
"tags",
"as",
"dict",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L4403-L4431 | train | 52,747 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffPage.ndpi_tags | def ndpi_tags(self):
"""Return consolidated metadata from Hamamatsu NDPI as dict."""
if not self.is_ndpi:
return None
tags = self.tags
result = {}
for name in ('Make', 'Model', 'Software'):
result[name] = tags[name].value
for code, name in TIFF.NDPI_TAGS.items():
code = str(code)
if code in tags:
result[name] = tags[code].value
# del tags[code]
return result | python | def ndpi_tags(self):
"""Return consolidated metadata from Hamamatsu NDPI as dict."""
if not self.is_ndpi:
return None
tags = self.tags
result = {}
for name in ('Make', 'Model', 'Software'):
result[name] = tags[name].value
for code, name in TIFF.NDPI_TAGS.items():
code = str(code)
if code in tags:
result[name] = tags[code].value
# del tags[code]
return result | [
"def",
"ndpi_tags",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_ndpi",
":",
"return",
"None",
"tags",
"=",
"self",
".",
"tags",
"result",
"=",
"{",
"}",
"for",
"name",
"in",
"(",
"'Make'",
",",
"'Model'",
",",
"'Software'",
")",
":",
"resu... | Return consolidated metadata from Hamamatsu NDPI as dict. | [
"Return",
"consolidated",
"metadata",
"from",
"Hamamatsu",
"NDPI",
"as",
"dict",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L4434-L4447 | train | 52,748 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffPage.is_imagej | def is_imagej(self):
"""Return ImageJ description if exists, else None."""
for description in (self.description, self.description1):
if not description:
return None
if description[:7] == 'ImageJ=':
return description
return None | python | def is_imagej(self):
"""Return ImageJ description if exists, else None."""
for description in (self.description, self.description1):
if not description:
return None
if description[:7] == 'ImageJ=':
return description
return None | [
"def",
"is_imagej",
"(",
"self",
")",
":",
"for",
"description",
"in",
"(",
"self",
".",
"description",
",",
"self",
".",
"description1",
")",
":",
"if",
"not",
"description",
":",
"return",
"None",
"if",
"description",
"[",
":",
"7",
"]",
"==",
"'Imag... | Return ImageJ description if exists, else None. | [
"Return",
"ImageJ",
"description",
"if",
"exists",
"else",
"None",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L4575-L4582 | train | 52,749 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffPage.is_shaped | def is_shaped(self):
"""Return description containing array shape if exists, else None."""
for description in (self.description, self.description1):
if not description:
return None
if description[:1] == '{' and '"shape":' in description:
return description
if description[:6] == 'shape=':
return description
return None | python | def is_shaped(self):
"""Return description containing array shape if exists, else None."""
for description in (self.description, self.description1):
if not description:
return None
if description[:1] == '{' and '"shape":' in description:
return description
if description[:6] == 'shape=':
return description
return None | [
"def",
"is_shaped",
"(",
"self",
")",
":",
"for",
"description",
"in",
"(",
"self",
".",
"description",
",",
"self",
".",
"description1",
")",
":",
"if",
"not",
"description",
":",
"return",
"None",
"if",
"description",
"[",
":",
"1",
"]",
"==",
"'{'",... | Return description containing array shape if exists, else None. | [
"Return",
"description",
"containing",
"array",
"shape",
"if",
"exists",
"else",
"None",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L4585-L4594 | train | 52,750 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffPage.is_metaseries | def is_metaseries(self):
"""Page contains MDS MetaSeries metadata in ImageDescription tag."""
if self.index > 1 or self.software != 'MetaSeries':
return False
d = self.description
return d.startswith('<MetaData>') and d.endswith('</MetaData>') | python | def is_metaseries(self):
"""Page contains MDS MetaSeries metadata in ImageDescription tag."""
if self.index > 1 or self.software != 'MetaSeries':
return False
d = self.description
return d.startswith('<MetaData>') and d.endswith('</MetaData>') | [
"def",
"is_metaseries",
"(",
"self",
")",
":",
"if",
"self",
".",
"index",
">",
"1",
"or",
"self",
".",
"software",
"!=",
"'MetaSeries'",
":",
"return",
"False",
"d",
"=",
"self",
".",
"description",
"return",
"d",
".",
"startswith",
"(",
"'<MetaData>'",... | Page contains MDS MetaSeries metadata in ImageDescription tag. | [
"Page",
"contains",
"MDS",
"MetaSeries",
"metadata",
"in",
"ImageDescription",
"tag",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L4638-L4643 | train | 52,751 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffPage.is_ome | def is_ome(self):
"""Page contains OME-XML in ImageDescription tag."""
if self.index > 1 or not self.description:
return False
d = self.description
return d[:14] == '<?xml version=' and d[-6:] == '</OME>' | python | def is_ome(self):
"""Page contains OME-XML in ImageDescription tag."""
if self.index > 1 or not self.description:
return False
d = self.description
return d[:14] == '<?xml version=' and d[-6:] == '</OME>' | [
"def",
"is_ome",
"(",
"self",
")",
":",
"if",
"self",
".",
"index",
">",
"1",
"or",
"not",
"self",
".",
"description",
":",
"return",
"False",
"d",
"=",
"self",
".",
"description",
"return",
"d",
"[",
":",
"14",
"]",
"==",
"'<?xml version='",
"and",
... | Page contains OME-XML in ImageDescription tag. | [
"Page",
"contains",
"OME",
"-",
"XML",
"in",
"ImageDescription",
"tag",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L4646-L4651 | train | 52,752 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffPage.is_scn | def is_scn(self):
"""Page contains Leica SCN XML in ImageDescription tag."""
if self.index > 1 or not self.description:
return False
d = self.description
return d[:14] == '<?xml version=' and d[-6:] == '</scn>' | python | def is_scn(self):
"""Page contains Leica SCN XML in ImageDescription tag."""
if self.index > 1 or not self.description:
return False
d = self.description
return d[:14] == '<?xml version=' and d[-6:] == '</scn>' | [
"def",
"is_scn",
"(",
"self",
")",
":",
"if",
"self",
".",
"index",
">",
"1",
"or",
"not",
"self",
".",
"description",
":",
"return",
"False",
"d",
"=",
"self",
".",
"description",
"return",
"d",
"[",
":",
"14",
"]",
"==",
"'<?xml version='",
"and",
... | Page contains Leica SCN XML in ImageDescription tag. | [
"Page",
"contains",
"Leica",
"SCN",
"XML",
"in",
"ImageDescription",
"tag",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L4654-L4659 | train | 52,753 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffFrame.aspage | def aspage(self):
"""Return TiffPage from file."""
if self.offset is None:
raise ValueError('cannot return virtual frame as page.')
self.parent.filehandle.seek(self.offset)
return TiffPage(self.parent, index=self.index) | python | def aspage(self):
"""Return TiffPage from file."""
if self.offset is None:
raise ValueError('cannot return virtual frame as page.')
self.parent.filehandle.seek(self.offset)
return TiffPage(self.parent, index=self.index) | [
"def",
"aspage",
"(",
"self",
")",
":",
"if",
"self",
".",
"offset",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'cannot return virtual frame as page.'",
")",
"self",
".",
"parent",
".",
"filehandle",
".",
"seek",
"(",
"self",
".",
"offset",
")",
"retu... | Return TiffPage from file. | [
"Return",
"TiffPage",
"from",
"file",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L4848-L4853 | train | 52,754 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffFrame.asrgb | def asrgb(self, *args, **kwargs):
"""Read image data from file and return RGB image as numpy array."""
if self._keyframe is None:
raise RuntimeError('keyframe not set')
kwargs['validate'] = False
return TiffPage.asrgb(self, *args, **kwargs) | python | def asrgb(self, *args, **kwargs):
"""Read image data from file and return RGB image as numpy array."""
if self._keyframe is None:
raise RuntimeError('keyframe not set')
kwargs['validate'] = False
return TiffPage.asrgb(self, *args, **kwargs) | [
"def",
"asrgb",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_keyframe",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"'keyframe not set'",
")",
"kwargs",
"[",
"'validate'",
"]",
"=",
"False",
"return",
"Tif... | Read image data from file and return RGB image as numpy array. | [
"Read",
"image",
"data",
"from",
"file",
"and",
"return",
"RGB",
"image",
"as",
"numpy",
"array",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L4865-L4870 | train | 52,755 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffFrame.keyframe | def keyframe(self, keyframe):
"""Set keyframe."""
if self._keyframe == keyframe:
return
if self._keyframe is not None:
raise RuntimeError('cannot reset keyframe')
if len(self._offsetscounts[0]) != len(keyframe.dataoffsets):
raise RuntimeError('incompatible keyframe')
if keyframe.is_tiled:
pass
if keyframe.is_contiguous:
self._offsetscounts = ([self._offsetscounts[0][0]],
[keyframe.is_contiguous[1]])
else:
self._offsetscounts = clean_offsetscounts(*self._offsetscounts)
self._keyframe = keyframe | python | def keyframe(self, keyframe):
"""Set keyframe."""
if self._keyframe == keyframe:
return
if self._keyframe is not None:
raise RuntimeError('cannot reset keyframe')
if len(self._offsetscounts[0]) != len(keyframe.dataoffsets):
raise RuntimeError('incompatible keyframe')
if keyframe.is_tiled:
pass
if keyframe.is_contiguous:
self._offsetscounts = ([self._offsetscounts[0][0]],
[keyframe.is_contiguous[1]])
else:
self._offsetscounts = clean_offsetscounts(*self._offsetscounts)
self._keyframe = keyframe | [
"def",
"keyframe",
"(",
"self",
",",
"keyframe",
")",
":",
"if",
"self",
".",
"_keyframe",
"==",
"keyframe",
":",
"return",
"if",
"self",
".",
"_keyframe",
"is",
"not",
"None",
":",
"raise",
"RuntimeError",
"(",
"'cannot reset keyframe'",
")",
"if",
"len",... | Set keyframe. | [
"Set",
"keyframe",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L4878-L4893 | train | 52,756 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffTag.name | def name(self):
"""Return name of tag from TIFF.TAGS registry."""
try:
return TIFF.TAGS[self.code]
except KeyError:
return str(self.code) | python | def name(self):
"""Return name of tag from TIFF.TAGS registry."""
try:
return TIFF.TAGS[self.code]
except KeyError:
return str(self.code) | [
"def",
"name",
"(",
"self",
")",
":",
"try",
":",
"return",
"TIFF",
".",
"TAGS",
"[",
"self",
".",
"code",
"]",
"except",
"KeyError",
":",
"return",
"str",
"(",
"self",
".",
"code",
")"
] | Return name of tag from TIFF.TAGS registry. | [
"Return",
"name",
"of",
"tag",
"from",
"TIFF",
".",
"TAGS",
"registry",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5038-L5043 | train | 52,757 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffTag._fix_lsm_bitspersample | def _fix_lsm_bitspersample(self, parent):
"""Correct LSM bitspersample tag.
Old LSM writers may use a separate region for two 16-bit values,
although they fit into the tag value element of the tag.
"""
if self.code != 258 or self.count != 2:
return
# TODO: test this case; need example file
log.warning('TiffTag %i: correcting LSM bitspersample tag', self.code)
value = struct.pack('<HH', *self.value)
self.valueoffset = struct.unpack('<I', value)[0]
parent.filehandle.seek(self.valueoffset)
self.value = struct.unpack('<HH', parent.filehandle.read(4)) | python | def _fix_lsm_bitspersample(self, parent):
"""Correct LSM bitspersample tag.
Old LSM writers may use a separate region for two 16-bit values,
although they fit into the tag value element of the tag.
"""
if self.code != 258 or self.count != 2:
return
# TODO: test this case; need example file
log.warning('TiffTag %i: correcting LSM bitspersample tag', self.code)
value = struct.pack('<HH', *self.value)
self.valueoffset = struct.unpack('<I', value)[0]
parent.filehandle.seek(self.valueoffset)
self.value = struct.unpack('<HH', parent.filehandle.read(4)) | [
"def",
"_fix_lsm_bitspersample",
"(",
"self",
",",
"parent",
")",
":",
"if",
"self",
".",
"code",
"!=",
"258",
"or",
"self",
".",
"count",
"!=",
"2",
":",
"return",
"# TODO: test this case; need example file",
"log",
".",
"warning",
"(",
"'TiffTag %i: correcting... | Correct LSM bitspersample tag.
Old LSM writers may use a separate region for two 16-bit values,
although they fit into the tag value element of the tag. | [
"Correct",
"LSM",
"bitspersample",
"tag",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5045-L5059 | train | 52,758 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffPageSeries.asarray | def asarray(self, out=None):
"""Return image data from series of TIFF pages as numpy array."""
if self.parent:
result = self.parent.asarray(series=self, out=out)
if self.transform is not None:
result = self.transform(result)
return result
return None | python | def asarray(self, out=None):
"""Return image data from series of TIFF pages as numpy array."""
if self.parent:
result = self.parent.asarray(series=self, out=out)
if self.transform is not None:
result = self.transform(result)
return result
return None | [
"def",
"asarray",
"(",
"self",
",",
"out",
"=",
"None",
")",
":",
"if",
"self",
".",
"parent",
":",
"result",
"=",
"self",
".",
"parent",
".",
"asarray",
"(",
"series",
"=",
"self",
",",
"out",
"=",
"out",
")",
"if",
"self",
".",
"transform",
"is... | Return image data from series of TIFF pages as numpy array. | [
"Return",
"image",
"data",
"from",
"series",
"of",
"TIFF",
"pages",
"as",
"numpy",
"array",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5127-L5134 | train | 52,759 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffPageSeries.offset | def offset(self):
"""Return offset to series data in file, if any."""
if not self._pages:
return None
pos = 0
for page in self._pages:
if page is None:
return None
if not page.is_final:
return None
if not pos:
pos = page.is_contiguous[0] + page.is_contiguous[1]
continue
if pos != page.is_contiguous[0]:
return None
pos += page.is_contiguous[1]
page = self._pages[0]
offset = page.is_contiguous[0]
if (page.is_imagej or page.is_shaped) and len(self._pages) == 1:
# truncated files
return offset
if pos == offset + product(self.shape) * self.dtype.itemsize:
return offset
return None | python | def offset(self):
"""Return offset to series data in file, if any."""
if not self._pages:
return None
pos = 0
for page in self._pages:
if page is None:
return None
if not page.is_final:
return None
if not pos:
pos = page.is_contiguous[0] + page.is_contiguous[1]
continue
if pos != page.is_contiguous[0]:
return None
pos += page.is_contiguous[1]
page = self._pages[0]
offset = page.is_contiguous[0]
if (page.is_imagej or page.is_shaped) and len(self._pages) == 1:
# truncated files
return offset
if pos == offset + product(self.shape) * self.dtype.itemsize:
return offset
return None | [
"def",
"offset",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_pages",
":",
"return",
"None",
"pos",
"=",
"0",
"for",
"page",
"in",
"self",
".",
"_pages",
":",
"if",
"page",
"is",
"None",
":",
"return",
"None",
"if",
"not",
"page",
".",
"is_... | Return offset to series data in file, if any. | [
"Return",
"offset",
"to",
"series",
"data",
"in",
"file",
"if",
"any",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5137-L5162 | train | 52,760 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffPageSeries._getitem | def _getitem(self, key):
"""Return specified page of series from cache or file."""
key = int(key)
if key < 0:
key %= self._len
if len(self._pages) == 1 and 0 < key < self._len:
index = self._pages[0].index
return self.parent.pages._getitem(index + key)
return self._pages[key] | python | def _getitem(self, key):
"""Return specified page of series from cache or file."""
key = int(key)
if key < 0:
key %= self._len
if len(self._pages) == 1 and 0 < key < self._len:
index = self._pages[0].index
return self.parent.pages._getitem(index + key)
return self._pages[key] | [
"def",
"_getitem",
"(",
"self",
",",
"key",
")",
":",
"key",
"=",
"int",
"(",
"key",
")",
"if",
"key",
"<",
"0",
":",
"key",
"%=",
"self",
".",
"_len",
"if",
"len",
"(",
"self",
".",
"_pages",
")",
"==",
"1",
"and",
"0",
"<",
"key",
"<",
"s... | Return specified page of series from cache or file. | [
"Return",
"specified",
"page",
"of",
"series",
"from",
"cache",
"or",
"file",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5180-L5188 | train | 52,761 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffSequence.asarray | def asarray(self, file=None, out=None, **kwargs):
"""Read image data from files and return as numpy array.
The kwargs parameters are passed to the imread function.
Raise IndexError or ValueError if image shapes do not match.
"""
if file is not None:
if isinstance(file, int):
return self.imread(self.files[file], **kwargs)
return self.imread(file, **kwargs)
im = self.imread(self.files[0], **kwargs)
shape = self.shape + im.shape
result = create_output(out, shape, dtype=im.dtype)
result = result.reshape(-1, *im.shape)
for index, fname in zip(self._indices, self.files):
index = [i-j for i, j in zip(index, self._startindex)]
index = numpy.ravel_multi_index(index, self.shape)
im = self.imread(fname, **kwargs)
result[index] = im
result.shape = shape
return result | python | def asarray(self, file=None, out=None, **kwargs):
"""Read image data from files and return as numpy array.
The kwargs parameters are passed to the imread function.
Raise IndexError or ValueError if image shapes do not match.
"""
if file is not None:
if isinstance(file, int):
return self.imread(self.files[file], **kwargs)
return self.imread(file, **kwargs)
im = self.imread(self.files[0], **kwargs)
shape = self.shape + im.shape
result = create_output(out, shape, dtype=im.dtype)
result = result.reshape(-1, *im.shape)
for index, fname in zip(self._indices, self.files):
index = [i-j for i, j in zip(index, self._startindex)]
index = numpy.ravel_multi_index(index, self.shape)
im = self.imread(fname, **kwargs)
result[index] = im
result.shape = shape
return result | [
"def",
"asarray",
"(",
"self",
",",
"file",
"=",
"None",
",",
"out",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"file",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"file",
",",
"int",
")",
":",
"return",
"self",
".",
"imread",
... | Read image data from files and return as numpy array.
The kwargs parameters are passed to the imread function.
Raise IndexError or ValueError if image shapes do not match. | [
"Read",
"image",
"data",
"from",
"files",
"and",
"return",
"as",
"numpy",
"array",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5377-L5400 | train | 52,762 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | TiffSequence._parse | def _parse(self):
"""Get axes and shape from file names."""
if not self.pattern:
raise TiffSequence.ParseError('invalid pattern')
pattern = re.compile(self.pattern, re.IGNORECASE | re.VERBOSE)
matches = pattern.findall(os.path.split(self.files[0])[-1])
if not matches:
raise TiffSequence.ParseError('pattern does not match file names')
matches = matches[-1]
if len(matches) % 2:
raise TiffSequence.ParseError(
'pattern does not match axis name and index')
axes = ''.join(m for m in matches[::2] if m)
if not axes:
raise TiffSequence.ParseError('pattern does not match file names')
indices = []
for fname in self.files:
fname = os.path.split(fname)[-1]
matches = pattern.findall(fname)[-1]
if axes != ''.join(m for m in matches[::2] if m):
raise ValueError('axes do not match within image sequence')
indices.append([int(m) for m in matches[1::2] if m])
shape = tuple(numpy.max(indices, axis=0))
startindex = tuple(numpy.min(indices, axis=0))
shape = tuple(i-j+1 for i, j in zip(shape, startindex))
if product(shape) != len(self.files):
log.warning(
'TiffSequence: files are missing. Missing data are zeroed')
self.axes = axes.upper()
self.shape = shape
self._indices = indices
self._startindex = startindex | python | def _parse(self):
"""Get axes and shape from file names."""
if not self.pattern:
raise TiffSequence.ParseError('invalid pattern')
pattern = re.compile(self.pattern, re.IGNORECASE | re.VERBOSE)
matches = pattern.findall(os.path.split(self.files[0])[-1])
if not matches:
raise TiffSequence.ParseError('pattern does not match file names')
matches = matches[-1]
if len(matches) % 2:
raise TiffSequence.ParseError(
'pattern does not match axis name and index')
axes = ''.join(m for m in matches[::2] if m)
if not axes:
raise TiffSequence.ParseError('pattern does not match file names')
indices = []
for fname in self.files:
fname = os.path.split(fname)[-1]
matches = pattern.findall(fname)[-1]
if axes != ''.join(m for m in matches[::2] if m):
raise ValueError('axes do not match within image sequence')
indices.append([int(m) for m in matches[1::2] if m])
shape = tuple(numpy.max(indices, axis=0))
startindex = tuple(numpy.min(indices, axis=0))
shape = tuple(i-j+1 for i, j in zip(shape, startindex))
if product(shape) != len(self.files):
log.warning(
'TiffSequence: files are missing. Missing data are zeroed')
self.axes = axes.upper()
self.shape = shape
self._indices = indices
self._startindex = startindex | [
"def",
"_parse",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"pattern",
":",
"raise",
"TiffSequence",
".",
"ParseError",
"(",
"'invalid pattern'",
")",
"pattern",
"=",
"re",
".",
"compile",
"(",
"self",
".",
"pattern",
",",
"re",
".",
"IGNORECASE",
... | Get axes and shape from file names. | [
"Get",
"axes",
"and",
"shape",
"from",
"file",
"names",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5402-L5435 | train | 52,763 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | FileHandle.open | def open(self):
"""Open or re-open file."""
if self._fh:
return # file is open
if isinstance(self._file, pathlib.Path):
self._file = str(self._file)
if isinstance(self._file, basestring):
# file name
self._file = os.path.realpath(self._file)
self._dir, self._name = os.path.split(self._file)
self._fh = open(self._file, self._mode)
self._close = True
if self._offset is None:
self._offset = 0
elif isinstance(self._file, FileHandle):
# FileHandle
self._fh = self._file._fh
if self._offset is None:
self._offset = 0
self._offset += self._file._offset
self._close = False
if not self._name:
if self._offset:
name, ext = os.path.splitext(self._file._name)
self._name = '%s@%i%s' % (name, self._offset, ext)
else:
self._name = self._file._name
if self._mode and self._mode != self._file._mode:
raise ValueError('FileHandle has wrong mode')
self._mode = self._file._mode
self._dir = self._file._dir
elif hasattr(self._file, 'seek'):
# binary stream: open file, BytesIO
try:
self._file.tell()
except Exception:
raise ValueError('binary stream is not seekable')
self._fh = self._file
if self._offset is None:
self._offset = self._file.tell()
self._close = False
if not self._name:
try:
self._dir, self._name = os.path.split(self._fh.name)
except AttributeError:
self._name = 'Unnamed binary stream'
try:
self._mode = self._fh.mode
except AttributeError:
pass
else:
raise ValueError('The first parameter must be a file name, '
'seekable binary stream, or FileHandle')
if self._offset:
self._fh.seek(self._offset)
if self._size is None:
pos = self._fh.tell()
self._fh.seek(self._offset, 2)
self._size = self._fh.tell()
self._fh.seek(pos)
try:
self._fh.fileno()
self.is_file = True
except Exception:
self.is_file = False | python | def open(self):
"""Open or re-open file."""
if self._fh:
return # file is open
if isinstance(self._file, pathlib.Path):
self._file = str(self._file)
if isinstance(self._file, basestring):
# file name
self._file = os.path.realpath(self._file)
self._dir, self._name = os.path.split(self._file)
self._fh = open(self._file, self._mode)
self._close = True
if self._offset is None:
self._offset = 0
elif isinstance(self._file, FileHandle):
# FileHandle
self._fh = self._file._fh
if self._offset is None:
self._offset = 0
self._offset += self._file._offset
self._close = False
if not self._name:
if self._offset:
name, ext = os.path.splitext(self._file._name)
self._name = '%s@%i%s' % (name, self._offset, ext)
else:
self._name = self._file._name
if self._mode and self._mode != self._file._mode:
raise ValueError('FileHandle has wrong mode')
self._mode = self._file._mode
self._dir = self._file._dir
elif hasattr(self._file, 'seek'):
# binary stream: open file, BytesIO
try:
self._file.tell()
except Exception:
raise ValueError('binary stream is not seekable')
self._fh = self._file
if self._offset is None:
self._offset = self._file.tell()
self._close = False
if not self._name:
try:
self._dir, self._name = os.path.split(self._fh.name)
except AttributeError:
self._name = 'Unnamed binary stream'
try:
self._mode = self._fh.mode
except AttributeError:
pass
else:
raise ValueError('The first parameter must be a file name, '
'seekable binary stream, or FileHandle')
if self._offset:
self._fh.seek(self._offset)
if self._size is None:
pos = self._fh.tell()
self._fh.seek(self._offset, 2)
self._size = self._fh.tell()
self._fh.seek(pos)
try:
self._fh.fileno()
self.is_file = True
except Exception:
self.is_file = False | [
"def",
"open",
"(",
"self",
")",
":",
"if",
"self",
".",
"_fh",
":",
"return",
"# file is open",
"if",
"isinstance",
"(",
"self",
".",
"_file",
",",
"pathlib",
".",
"Path",
")",
":",
"self",
".",
"_file",
"=",
"str",
"(",
"self",
".",
"_file",
")",... | Open or re-open file. | [
"Open",
"or",
"re",
"-",
"open",
"file",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5502-L5570 | train | 52,764 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | FileHandle.read | def read(self, size=-1):
"""Read 'size' bytes from file, or until EOF is reached."""
if size < 0 and self._offset:
size = self._size
return self._fh.read(size) | python | def read(self, size=-1):
"""Read 'size' bytes from file, or until EOF is reached."""
if size < 0 and self._offset:
size = self._size
return self._fh.read(size) | [
"def",
"read",
"(",
"self",
",",
"size",
"=",
"-",
"1",
")",
":",
"if",
"size",
"<",
"0",
"and",
"self",
".",
"_offset",
":",
"size",
"=",
"self",
".",
"_size",
"return",
"self",
".",
"_fh",
".",
"read",
"(",
"size",
")"
] | Read 'size' bytes from file, or until EOF is reached. | [
"Read",
"size",
"bytes",
"from",
"file",
"or",
"until",
"EOF",
"is",
"reached",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5572-L5576 | train | 52,765 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | FileHandle.memmap_array | def memmap_array(self, dtype, shape, offset=0, mode='r', order='C'):
"""Return numpy.memmap of data stored in file."""
if not self.is_file:
raise ValueError('Cannot memory-map file without fileno')
return numpy.memmap(self._fh, dtype=dtype, mode=mode,
offset=self._offset + offset,
shape=shape, order=order) | python | def memmap_array(self, dtype, shape, offset=0, mode='r', order='C'):
"""Return numpy.memmap of data stored in file."""
if not self.is_file:
raise ValueError('Cannot memory-map file without fileno')
return numpy.memmap(self._fh, dtype=dtype, mode=mode,
offset=self._offset + offset,
shape=shape, order=order) | [
"def",
"memmap_array",
"(",
"self",
",",
"dtype",
",",
"shape",
",",
"offset",
"=",
"0",
",",
"mode",
"=",
"'r'",
",",
"order",
"=",
"'C'",
")",
":",
"if",
"not",
"self",
".",
"is_file",
":",
"raise",
"ValueError",
"(",
"'Cannot memory-map file without f... | Return numpy.memmap of data stored in file. | [
"Return",
"numpy",
".",
"memmap",
"of",
"data",
"stored",
"in",
"file",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5590-L5596 | train | 52,766 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | FileHandle.read_array | def read_array(self, dtype, count=-1, out=None):
"""Return numpy array from file in native byte order."""
fh = self._fh
dtype = numpy.dtype(dtype)
if count < 0:
size = self._size if out is None else out.nbytes
count = size // dtype.itemsize
else:
size = count * dtype.itemsize
result = numpy.empty(count, dtype) if out is None else out
if result.nbytes != size:
raise ValueError('size mismatch')
n = fh.readinto(result)
if n != size:
raise ValueError('failed to read %i bytes' % size)
if not result.dtype.isnative:
if not dtype.isnative:
result.byteswap(True)
result = result.newbyteorder()
elif result.dtype.isnative != dtype.isnative:
result.byteswap(True)
if out is not None:
if hasattr(out, 'flush'):
out.flush()
return result | python | def read_array(self, dtype, count=-1, out=None):
"""Return numpy array from file in native byte order."""
fh = self._fh
dtype = numpy.dtype(dtype)
if count < 0:
size = self._size if out is None else out.nbytes
count = size // dtype.itemsize
else:
size = count * dtype.itemsize
result = numpy.empty(count, dtype) if out is None else out
if result.nbytes != size:
raise ValueError('size mismatch')
n = fh.readinto(result)
if n != size:
raise ValueError('failed to read %i bytes' % size)
if not result.dtype.isnative:
if not dtype.isnative:
result.byteswap(True)
result = result.newbyteorder()
elif result.dtype.isnative != dtype.isnative:
result.byteswap(True)
if out is not None:
if hasattr(out, 'flush'):
out.flush()
return result | [
"def",
"read_array",
"(",
"self",
",",
"dtype",
",",
"count",
"=",
"-",
"1",
",",
"out",
"=",
"None",
")",
":",
"fh",
"=",
"self",
".",
"_fh",
"dtype",
"=",
"numpy",
".",
"dtype",
"(",
"dtype",
")",
"if",
"count",
"<",
"0",
":",
"size",
"=",
... | Return numpy array from file in native byte order. | [
"Return",
"numpy",
"array",
"from",
"file",
"in",
"native",
"byte",
"order",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5598-L5629 | train | 52,767 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | FileHandle.read_record | def read_record(self, dtype, shape=1, byteorder=None):
"""Return numpy record from file."""
rec = numpy.rec
try:
record = rec.fromfile(self._fh, dtype, shape, byteorder=byteorder)
except Exception:
dtype = numpy.dtype(dtype)
if shape is None:
shape = self._size // dtype.itemsize
size = product(sequence(shape)) * dtype.itemsize
data = self._fh.read(size)
record = rec.fromstring(data, dtype, shape, byteorder=byteorder)
return record[0] if shape == 1 else record | python | def read_record(self, dtype, shape=1, byteorder=None):
"""Return numpy record from file."""
rec = numpy.rec
try:
record = rec.fromfile(self._fh, dtype, shape, byteorder=byteorder)
except Exception:
dtype = numpy.dtype(dtype)
if shape is None:
shape = self._size // dtype.itemsize
size = product(sequence(shape)) * dtype.itemsize
data = self._fh.read(size)
record = rec.fromstring(data, dtype, shape, byteorder=byteorder)
return record[0] if shape == 1 else record | [
"def",
"read_record",
"(",
"self",
",",
"dtype",
",",
"shape",
"=",
"1",
",",
"byteorder",
"=",
"None",
")",
":",
"rec",
"=",
"numpy",
".",
"rec",
"try",
":",
"record",
"=",
"rec",
".",
"fromfile",
"(",
"self",
".",
"_fh",
",",
"dtype",
",",
"sha... | Return numpy record from file. | [
"Return",
"numpy",
"record",
"from",
"file",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5631-L5643 | train | 52,768 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | FileHandle.write_empty | def write_empty(self, size):
"""Append size bytes to file. Position must be at end of file."""
if size < 1:
return
self._fh.seek(size-1, 1)
self._fh.write(b'\x00') | python | def write_empty(self, size):
"""Append size bytes to file. Position must be at end of file."""
if size < 1:
return
self._fh.seek(size-1, 1)
self._fh.write(b'\x00') | [
"def",
"write_empty",
"(",
"self",
",",
"size",
")",
":",
"if",
"size",
"<",
"1",
":",
"return",
"self",
".",
"_fh",
".",
"seek",
"(",
"size",
"-",
"1",
",",
"1",
")",
"self",
".",
"_fh",
".",
"write",
"(",
"b'\\x00'",
")"
] | Append size bytes to file. Position must be at end of file. | [
"Append",
"size",
"bytes",
"to",
"file",
".",
"Position",
"must",
"be",
"at",
"end",
"of",
"file",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5645-L5650 | train | 52,769 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | FileHandle.write_array | def write_array(self, data):
"""Write numpy array to binary file."""
try:
data.tofile(self._fh)
except Exception:
# BytesIO
self._fh.write(data.tostring()) | python | def write_array(self, data):
"""Write numpy array to binary file."""
try:
data.tofile(self._fh)
except Exception:
# BytesIO
self._fh.write(data.tostring()) | [
"def",
"write_array",
"(",
"self",
",",
"data",
")",
":",
"try",
":",
"data",
".",
"tofile",
"(",
"self",
".",
"_fh",
")",
"except",
"Exception",
":",
"# BytesIO",
"self",
".",
"_fh",
".",
"write",
"(",
"data",
".",
"tostring",
"(",
")",
")"
] | Write numpy array to binary file. | [
"Write",
"numpy",
"array",
"to",
"binary",
"file",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5652-L5658 | train | 52,770 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | FileHandle.seek | def seek(self, offset, whence=0):
"""Set file's current position."""
if self._offset:
if whence == 0:
self._fh.seek(self._offset + offset, whence)
return
if whence == 2 and self._size > 0:
self._fh.seek(self._offset + self._size + offset, 0)
return
self._fh.seek(offset, whence) | python | def seek(self, offset, whence=0):
"""Set file's current position."""
if self._offset:
if whence == 0:
self._fh.seek(self._offset + offset, whence)
return
if whence == 2 and self._size > 0:
self._fh.seek(self._offset + self._size + offset, 0)
return
self._fh.seek(offset, whence) | [
"def",
"seek",
"(",
"self",
",",
"offset",
",",
"whence",
"=",
"0",
")",
":",
"if",
"self",
".",
"_offset",
":",
"if",
"whence",
"==",
"0",
":",
"self",
".",
"_fh",
".",
"seek",
"(",
"self",
".",
"_offset",
"+",
"offset",
",",
"whence",
")",
"r... | Set file's current position. | [
"Set",
"file",
"s",
"current",
"position",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5664-L5673 | train | 52,771 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | FileHandle.close | def close(self):
"""Close file."""
if self._close and self._fh:
self._fh.close()
self._fh = None | python | def close(self):
"""Close file."""
if self._close and self._fh:
self._fh.close()
self._fh = None | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_close",
"and",
"self",
".",
"_fh",
":",
"self",
".",
"_fh",
".",
"close",
"(",
")",
"self",
".",
"_fh",
"=",
"None"
] | Close file. | [
"Close",
"file",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5675-L5679 | train | 52,772 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | OpenFileCache.open | def open(self, filehandle):
"""Re-open file if necessary."""
with self.lock:
if filehandle in self.files:
self.files[filehandle] += 1
elif filehandle.closed:
filehandle.open()
self.files[filehandle] = 1
self.past.append(filehandle) | python | def open(self, filehandle):
"""Re-open file if necessary."""
with self.lock:
if filehandle in self.files:
self.files[filehandle] += 1
elif filehandle.closed:
filehandle.open()
self.files[filehandle] = 1
self.past.append(filehandle) | [
"def",
"open",
"(",
"self",
",",
"filehandle",
")",
":",
"with",
"self",
".",
"lock",
":",
"if",
"filehandle",
"in",
"self",
".",
"files",
":",
"self",
".",
"files",
"[",
"filehandle",
"]",
"+=",
"1",
"elif",
"filehandle",
".",
"closed",
":",
"fileha... | Re-open file if necessary. | [
"Re",
"-",
"open",
"file",
"if",
"necessary",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5749-L5757 | train | 52,773 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | OpenFileCache.close | def close(self, filehandle):
"""Close openend file if no longer used."""
with self.lock:
if filehandle in self.files:
self.files[filehandle] -= 1
# trim the file cache
index = 0
size = len(self.past)
while size > self.size and index < size:
filehandle = self.past[index]
if self.files[filehandle] == 0:
filehandle.close()
del self.files[filehandle]
del self.past[index]
size -= 1
else:
index += 1 | python | def close(self, filehandle):
"""Close openend file if no longer used."""
with self.lock:
if filehandle in self.files:
self.files[filehandle] -= 1
# trim the file cache
index = 0
size = len(self.past)
while size > self.size and index < size:
filehandle = self.past[index]
if self.files[filehandle] == 0:
filehandle.close()
del self.files[filehandle]
del self.past[index]
size -= 1
else:
index += 1 | [
"def",
"close",
"(",
"self",
",",
"filehandle",
")",
":",
"with",
"self",
".",
"lock",
":",
"if",
"filehandle",
"in",
"self",
".",
"files",
":",
"self",
".",
"files",
"[",
"filehandle",
"]",
"-=",
"1",
"# trim the file cache",
"index",
"=",
"0",
"size"... | Close openend file if no longer used. | [
"Close",
"openend",
"file",
"if",
"no",
"longer",
"used",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5759-L5775 | train | 52,774 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | OpenFileCache.clear | def clear(self):
"""Close all opened files if not in use."""
with self.lock:
for filehandle, refcount in list(self.files.items()):
if refcount == 0:
filehandle.close()
del self.files[filehandle]
del self.past[self.past.index(filehandle)] | python | def clear(self):
"""Close all opened files if not in use."""
with self.lock:
for filehandle, refcount in list(self.files.items()):
if refcount == 0:
filehandle.close()
del self.files[filehandle]
del self.past[self.past.index(filehandle)] | [
"def",
"clear",
"(",
"self",
")",
":",
"with",
"self",
".",
"lock",
":",
"for",
"filehandle",
",",
"refcount",
"in",
"list",
"(",
"self",
".",
"files",
".",
"items",
"(",
")",
")",
":",
"if",
"refcount",
"==",
"0",
":",
"filehandle",
".",
"close",
... | Close all opened files if not in use. | [
"Close",
"all",
"opened",
"files",
"if",
"not",
"in",
"use",
"."
] | e9ae37f01faa9332c48b647f93afd5ef2166b155 | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5777-L5784 | train | 52,775 |
noahmorrison/chevron | chevron/tokenizer.py | grab_literal | def grab_literal(template, l_del):
"""Parse a literal from the template"""
global _CURRENT_LINE
try:
# Look for the next tag and move the template to it
literal, template = template.split(l_del, 1)
_CURRENT_LINE += literal.count('\n')
return (literal, template)
# There are no more tags in the template?
except ValueError:
# Then the rest of the template is a literal
return (template, '') | python | def grab_literal(template, l_del):
"""Parse a literal from the template"""
global _CURRENT_LINE
try:
# Look for the next tag and move the template to it
literal, template = template.split(l_del, 1)
_CURRENT_LINE += literal.count('\n')
return (literal, template)
# There are no more tags in the template?
except ValueError:
# Then the rest of the template is a literal
return (template, '') | [
"def",
"grab_literal",
"(",
"template",
",",
"l_del",
")",
":",
"global",
"_CURRENT_LINE",
"try",
":",
"# Look for the next tag and move the template to it",
"literal",
",",
"template",
"=",
"template",
".",
"split",
"(",
"l_del",
",",
"1",
")",
"_CURRENT_LINE",
"... | Parse a literal from the template | [
"Parse",
"a",
"literal",
"from",
"the",
"template"
] | 78f1a384eddef16906732d8db66deea6d37049b7 | https://github.com/noahmorrison/chevron/blob/78f1a384eddef16906732d8db66deea6d37049b7/chevron/tokenizer.py#L14-L28 | train | 52,776 |
noahmorrison/chevron | chevron/tokenizer.py | l_sa_check | def l_sa_check(template, literal, is_standalone):
"""Do a preliminary check to see if a tag could be a standalone"""
# If there is a newline, or the previous tag was a standalone
if literal.find('\n') != -1 or is_standalone:
padding = literal.split('\n')[-1]
# If all the characters since the last newline are spaces
if padding.isspace() or padding == '':
# Then the next tag could be a standalone
return True
else:
# Otherwise it can't be
return False | python | def l_sa_check(template, literal, is_standalone):
"""Do a preliminary check to see if a tag could be a standalone"""
# If there is a newline, or the previous tag was a standalone
if literal.find('\n') != -1 or is_standalone:
padding = literal.split('\n')[-1]
# If all the characters since the last newline are spaces
if padding.isspace() or padding == '':
# Then the next tag could be a standalone
return True
else:
# Otherwise it can't be
return False | [
"def",
"l_sa_check",
"(",
"template",
",",
"literal",
",",
"is_standalone",
")",
":",
"# If there is a newline, or the previous tag was a standalone",
"if",
"literal",
".",
"find",
"(",
"'\\n'",
")",
"!=",
"-",
"1",
"or",
"is_standalone",
":",
"padding",
"=",
"lit... | Do a preliminary check to see if a tag could be a standalone | [
"Do",
"a",
"preliminary",
"check",
"to",
"see",
"if",
"a",
"tag",
"could",
"be",
"a",
"standalone"
] | 78f1a384eddef16906732d8db66deea6d37049b7 | https://github.com/noahmorrison/chevron/blob/78f1a384eddef16906732d8db66deea6d37049b7/chevron/tokenizer.py#L31-L44 | train | 52,777 |
noahmorrison/chevron | chevron/tokenizer.py | r_sa_check | def r_sa_check(template, tag_type, is_standalone):
"""Do a final checkto see if a tag could be a standalone"""
# Check right side if we might be a standalone
if is_standalone and tag_type not in ['variable', 'no escape']:
on_newline = template.split('\n', 1)
# If the stuff to the right of us are spaces we're a standalone
if on_newline[0].isspace() or not on_newline[0]:
return True
else:
return False
# If we're a tag can't be a standalone
else:
return False | python | def r_sa_check(template, tag_type, is_standalone):
"""Do a final checkto see if a tag could be a standalone"""
# Check right side if we might be a standalone
if is_standalone and tag_type not in ['variable', 'no escape']:
on_newline = template.split('\n', 1)
# If the stuff to the right of us are spaces we're a standalone
if on_newline[0].isspace() or not on_newline[0]:
return True
else:
return False
# If we're a tag can't be a standalone
else:
return False | [
"def",
"r_sa_check",
"(",
"template",
",",
"tag_type",
",",
"is_standalone",
")",
":",
"# Check right side if we might be a standalone",
"if",
"is_standalone",
"and",
"tag_type",
"not",
"in",
"[",
"'variable'",
",",
"'no escape'",
"]",
":",
"on_newline",
"=",
"templ... | Do a final checkto see if a tag could be a standalone | [
"Do",
"a",
"final",
"checkto",
"see",
"if",
"a",
"tag",
"could",
"be",
"a",
"standalone"
] | 78f1a384eddef16906732d8db66deea6d37049b7 | https://github.com/noahmorrison/chevron/blob/78f1a384eddef16906732d8db66deea6d37049b7/chevron/tokenizer.py#L47-L62 | train | 52,778 |
noahmorrison/chevron | chevron/tokenizer.py | parse_tag | def parse_tag(template, l_del, r_del):
"""Parse a tag from a template"""
global _CURRENT_LINE
global _LAST_TAG_LINE
tag_types = {
'!': 'comment',
'#': 'section',
'^': 'inverted section',
'/': 'end',
'>': 'partial',
'=': 'set delimiter?',
'{': 'no escape?',
'&': 'no escape'
}
# Get the tag
try:
tag, template = template.split(r_del, 1)
except ValueError:
raise ChevronError('unclosed tag '
'at line {0}'.format(_CURRENT_LINE))
# Find the type meaning of the first character
tag_type = tag_types.get(tag[0], 'variable')
# If the type is not a variable
if tag_type != 'variable':
# Then that first character is not needed
tag = tag[1:]
# If we might be a set delimiter tag
if tag_type == 'set delimiter?':
# Double check to make sure we are
if tag.endswith('='):
tag_type = 'set delimiter'
# Remove the equal sign
tag = tag[:-1]
# Otherwise we should complain
else:
raise ChevronError('unclosed set delimiter tag\n'
'at line {0}'.format(_CURRENT_LINE))
# If we might be a no html escape tag
elif tag_type == 'no escape?':
# And we have a third curly brace
# (And are using curly braces as delimiters)
if l_del == '{{' and r_del == '}}' and template.startswith('}'):
# Then we are a no html escape tag
template = template[1:]
tag_type = 'no escape'
# Strip the whitespace off the key and return
return ((tag_type, tag.strip()), template) | python | def parse_tag(template, l_del, r_del):
"""Parse a tag from a template"""
global _CURRENT_LINE
global _LAST_TAG_LINE
tag_types = {
'!': 'comment',
'#': 'section',
'^': 'inverted section',
'/': 'end',
'>': 'partial',
'=': 'set delimiter?',
'{': 'no escape?',
'&': 'no escape'
}
# Get the tag
try:
tag, template = template.split(r_del, 1)
except ValueError:
raise ChevronError('unclosed tag '
'at line {0}'.format(_CURRENT_LINE))
# Find the type meaning of the first character
tag_type = tag_types.get(tag[0], 'variable')
# If the type is not a variable
if tag_type != 'variable':
# Then that first character is not needed
tag = tag[1:]
# If we might be a set delimiter tag
if tag_type == 'set delimiter?':
# Double check to make sure we are
if tag.endswith('='):
tag_type = 'set delimiter'
# Remove the equal sign
tag = tag[:-1]
# Otherwise we should complain
else:
raise ChevronError('unclosed set delimiter tag\n'
'at line {0}'.format(_CURRENT_LINE))
# If we might be a no html escape tag
elif tag_type == 'no escape?':
# And we have a third curly brace
# (And are using curly braces as delimiters)
if l_del == '{{' and r_del == '}}' and template.startswith('}'):
# Then we are a no html escape tag
template = template[1:]
tag_type = 'no escape'
# Strip the whitespace off the key and return
return ((tag_type, tag.strip()), template) | [
"def",
"parse_tag",
"(",
"template",
",",
"l_del",
",",
"r_del",
")",
":",
"global",
"_CURRENT_LINE",
"global",
"_LAST_TAG_LINE",
"tag_types",
"=",
"{",
"'!'",
":",
"'comment'",
",",
"'#'",
":",
"'section'",
",",
"'^'",
":",
"'inverted section'",
",",
"'/'",... | Parse a tag from a template | [
"Parse",
"a",
"tag",
"from",
"a",
"template"
] | 78f1a384eddef16906732d8db66deea6d37049b7 | https://github.com/noahmorrison/chevron/blob/78f1a384eddef16906732d8db66deea6d37049b7/chevron/tokenizer.py#L65-L119 | train | 52,779 |
noahmorrison/chevron | chevron/tokenizer.py | tokenize | def tokenize(template, def_ldel='{{', def_rdel='}}'):
"""Tokenize a mustache template
Tokenizes a mustache template in a generator fashion,
using file-like objects. It also accepts a string containing
the template.
Arguments:
template -- a file-like object, or a string of a mustache template
def_ldel -- The default left delimiter
("{{" by default, as in spec compliant mustache)
def_rdel -- The default right delimiter
("}}" by default, as in spec compliant mustache)
Returns:
A generator of mustache tags in the form of a tuple
-- (tag_type, tag_key)
Where tag_type is one of:
* literal
* section
* inverted section
* end
* partial
* no escape
And tag_key is either the key or in the case of a literal tag,
the literal itself.
"""
global _CURRENT_LINE, _LAST_TAG_LINE
_CURRENT_LINE = 1
_LAST_TAG_LINE = None
# If the template is a file-like object then read it
try:
template = template.read()
except AttributeError:
pass
is_standalone = True
open_sections = []
l_del = def_ldel
r_del = def_rdel
while template:
literal, template = grab_literal(template, l_del)
# If the template is completed
if not template:
# Then yield the literal and leave
yield ('literal', literal)
break
# Do the first check to see if we could be a standalone
is_standalone = l_sa_check(template, literal, is_standalone)
# Parse the tag
tag, template = parse_tag(template, l_del, r_del)
tag_type, tag_key = tag
# Special tag logic
# If we are a set delimiter tag
if tag_type == 'set delimiter':
# Then get and set the delimiters
dels = tag_key.strip().split(' ')
l_del, r_del = dels[0], dels[-1]
# If we are a section tag
elif tag_type in ['section', 'inverted section']:
# Then open a new section
open_sections.append(tag_key)
_LAST_TAG_LINE = _CURRENT_LINE
# If we are an end tag
elif tag_type == 'end':
# Then check to see if the last opened section
# is the same as us
try:
last_section = open_sections.pop()
except IndexError:
raise ChevronError('Trying to close tag "{0}"\n'
'Looks like it was not opened.\n'
'line {1}'
.format(tag_key, _CURRENT_LINE + 1))
if tag_key != last_section:
# Otherwise we need to complain
raise ChevronError('Trying to close tag "{0}"\n'
'last open tag is "{1}"\n'
'line {2}'
.format(tag_key, last_section,
_CURRENT_LINE + 1))
# Do the second check to see if we're a standalone
is_standalone = r_sa_check(template, tag_type, is_standalone)
# Which if we are
if is_standalone:
# Remove the stuff before the newline
template = template.split('\n', 1)[-1]
# Partials need to keep the spaces on their left
if tag_type != 'partial':
# But other tags don't
literal = literal.rstrip(' ')
# Start yielding
# Ignore literals that are empty
if literal != '':
yield ('literal', literal)
# Ignore comments and set delimiters
if tag_type not in ['comment', 'set delimiter?']:
yield (tag_type, tag_key)
# If there are any open sections when we're done
if open_sections:
# Then we need to complain
raise ChevronError('Unexpected EOF\n'
'the tag "{0}" was never closed\n'
'was opened at line {1}'
.format(open_sections[-1], _LAST_TAG_LINE)) | python | def tokenize(template, def_ldel='{{', def_rdel='}}'):
"""Tokenize a mustache template
Tokenizes a mustache template in a generator fashion,
using file-like objects. It also accepts a string containing
the template.
Arguments:
template -- a file-like object, or a string of a mustache template
def_ldel -- The default left delimiter
("{{" by default, as in spec compliant mustache)
def_rdel -- The default right delimiter
("}}" by default, as in spec compliant mustache)
Returns:
A generator of mustache tags in the form of a tuple
-- (tag_type, tag_key)
Where tag_type is one of:
* literal
* section
* inverted section
* end
* partial
* no escape
And tag_key is either the key or in the case of a literal tag,
the literal itself.
"""
global _CURRENT_LINE, _LAST_TAG_LINE
_CURRENT_LINE = 1
_LAST_TAG_LINE = None
# If the template is a file-like object then read it
try:
template = template.read()
except AttributeError:
pass
is_standalone = True
open_sections = []
l_del = def_ldel
r_del = def_rdel
while template:
literal, template = grab_literal(template, l_del)
# If the template is completed
if not template:
# Then yield the literal and leave
yield ('literal', literal)
break
# Do the first check to see if we could be a standalone
is_standalone = l_sa_check(template, literal, is_standalone)
# Parse the tag
tag, template = parse_tag(template, l_del, r_del)
tag_type, tag_key = tag
# Special tag logic
# If we are a set delimiter tag
if tag_type == 'set delimiter':
# Then get and set the delimiters
dels = tag_key.strip().split(' ')
l_del, r_del = dels[0], dels[-1]
# If we are a section tag
elif tag_type in ['section', 'inverted section']:
# Then open a new section
open_sections.append(tag_key)
_LAST_TAG_LINE = _CURRENT_LINE
# If we are an end tag
elif tag_type == 'end':
# Then check to see if the last opened section
# is the same as us
try:
last_section = open_sections.pop()
except IndexError:
raise ChevronError('Trying to close tag "{0}"\n'
'Looks like it was not opened.\n'
'line {1}'
.format(tag_key, _CURRENT_LINE + 1))
if tag_key != last_section:
# Otherwise we need to complain
raise ChevronError('Trying to close tag "{0}"\n'
'last open tag is "{1}"\n'
'line {2}'
.format(tag_key, last_section,
_CURRENT_LINE + 1))
# Do the second check to see if we're a standalone
is_standalone = r_sa_check(template, tag_type, is_standalone)
# Which if we are
if is_standalone:
# Remove the stuff before the newline
template = template.split('\n', 1)[-1]
# Partials need to keep the spaces on their left
if tag_type != 'partial':
# But other tags don't
literal = literal.rstrip(' ')
# Start yielding
# Ignore literals that are empty
if literal != '':
yield ('literal', literal)
# Ignore comments and set delimiters
if tag_type not in ['comment', 'set delimiter?']:
yield (tag_type, tag_key)
# If there are any open sections when we're done
if open_sections:
# Then we need to complain
raise ChevronError('Unexpected EOF\n'
'the tag "{0}" was never closed\n'
'was opened at line {1}'
.format(open_sections[-1], _LAST_TAG_LINE)) | [
"def",
"tokenize",
"(",
"template",
",",
"def_ldel",
"=",
"'{{'",
",",
"def_rdel",
"=",
"'}}'",
")",
":",
"global",
"_CURRENT_LINE",
",",
"_LAST_TAG_LINE",
"_CURRENT_LINE",
"=",
"1",
"_LAST_TAG_LINE",
"=",
"None",
"# If the template is a file-like object then read it"... | Tokenize a mustache template
Tokenizes a mustache template in a generator fashion,
using file-like objects. It also accepts a string containing
the template.
Arguments:
template -- a file-like object, or a string of a mustache template
def_ldel -- The default left delimiter
("{{" by default, as in spec compliant mustache)
def_rdel -- The default right delimiter
("}}" by default, as in spec compliant mustache)
Returns:
A generator of mustache tags in the form of a tuple
-- (tag_type, tag_key)
Where tag_type is one of:
* literal
* section
* inverted section
* end
* partial
* no escape
And tag_key is either the key or in the case of a literal tag,
the literal itself. | [
"Tokenize",
"a",
"mustache",
"template"
] | 78f1a384eddef16906732d8db66deea6d37049b7 | https://github.com/noahmorrison/chevron/blob/78f1a384eddef16906732d8db66deea6d37049b7/chevron/tokenizer.py#L126-L254 | train | 52,780 |
noahmorrison/chevron | chevron/main.py | cli_main | def cli_main():
"""Render mustache templates using json files"""
import argparse
import os
def is_file_or_pipe(arg):
if not os.path.exists(arg) or os.path.isdir(arg):
parser.error('The file {0} does not exist!'.format(arg))
else:
return arg
def is_dir(arg):
if not os.path.isdir(arg):
parser.error('The directory {0} does not exist!'.format(arg))
else:
return arg
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-v', '--version', action='version',
version=version)
parser.add_argument('template', help='The mustache file',
type=is_file_or_pipe)
parser.add_argument('-d', '--data', dest='data',
help='The json data file',
type=is_file_or_pipe, default={})
parser.add_argument('-p', '--path', dest='partials_path',
help='The directory where your partials reside',
type=is_dir, default='.')
parser.add_argument('-e', '--ext', dest='partials_ext',
help='The extension for your mustache\
partials, \'mustache\' by default',
default='mustache')
parser.add_argument('-l', '--left-delimiter', dest='def_ldel',
help='The default left delimiter, "{{" by default.',
default='{{')
parser.add_argument('-r', '--right-delimiter', dest='def_rdel',
help='The default right delimiter, "}}" by default.',
default='}}')
args = vars(parser.parse_args())
try:
sys.stdout.write(main(**args))
sys.stdout.flush()
except SyntaxError as e:
print('Chevron: syntax error')
print(' ' + '\n '.join(e.args[0].split('\n')))
exit(1) | python | def cli_main():
"""Render mustache templates using json files"""
import argparse
import os
def is_file_or_pipe(arg):
if not os.path.exists(arg) or os.path.isdir(arg):
parser.error('The file {0} does not exist!'.format(arg))
else:
return arg
def is_dir(arg):
if not os.path.isdir(arg):
parser.error('The directory {0} does not exist!'.format(arg))
else:
return arg
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-v', '--version', action='version',
version=version)
parser.add_argument('template', help='The mustache file',
type=is_file_or_pipe)
parser.add_argument('-d', '--data', dest='data',
help='The json data file',
type=is_file_or_pipe, default={})
parser.add_argument('-p', '--path', dest='partials_path',
help='The directory where your partials reside',
type=is_dir, default='.')
parser.add_argument('-e', '--ext', dest='partials_ext',
help='The extension for your mustache\
partials, \'mustache\' by default',
default='mustache')
parser.add_argument('-l', '--left-delimiter', dest='def_ldel',
help='The default left delimiter, "{{" by default.',
default='{{')
parser.add_argument('-r', '--right-delimiter', dest='def_rdel',
help='The default right delimiter, "}}" by default.',
default='}}')
args = vars(parser.parse_args())
try:
sys.stdout.write(main(**args))
sys.stdout.flush()
except SyntaxError as e:
print('Chevron: syntax error')
print(' ' + '\n '.join(e.args[0].split('\n')))
exit(1) | [
"def",
"cli_main",
"(",
")",
":",
"import",
"argparse",
"import",
"os",
"def",
"is_file_or_pipe",
"(",
"arg",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"arg",
")",
"or",
"os",
".",
"path",
".",
"isdir",
"(",
"arg",
")",
":",
"... | Render mustache templates using json files | [
"Render",
"mustache",
"templates",
"using",
"json",
"files"
] | 78f1a384eddef16906732d8db66deea6d37049b7 | https://github.com/noahmorrison/chevron/blob/78f1a384eddef16906732d8db66deea6d37049b7/chevron/main.py#L35-L89 | train | 52,781 |
noahmorrison/chevron | chevron/renderer.py | _get_key | def _get_key(key, scopes):
"""Get a key from the current scope"""
# If the key is a dot
if key == '.':
# Then just return the current scope
return scopes[0]
# Loop through the scopes
for scope in scopes:
try:
# For every dot seperated key
for child in key.split('.'):
# Move into the scope
try:
# Try subscripting (Normal dictionaries)
scope = scope[child]
except (TypeError, AttributeError):
try:
# Try the dictionary (Complex types)
scope = scope.__dict__[child]
except (TypeError, AttributeError):
# Try as a list
scope = scope[int(child)]
# Return an empty string if falsy, with two exceptions
# 0 should return 0, and False should return False
# While using is for this check is undefined it works and is fast
if scope is 0: # noqa: F632
return 0
if scope is False:
return False
try:
# This allows for custom falsy data types
# https://github.com/noahmorrison/chevron/issues/35
if scope._CHEVRON_return_scope_when_falsy:
return scope
except AttributeError:
return scope or ''
except (AttributeError, KeyError, IndexError, ValueError):
# We couldn't find the key in the current scope
# We'll try again on the next pass
pass
# We couldn't find the key in any of the scopes
return '' | python | def _get_key(key, scopes):
"""Get a key from the current scope"""
# If the key is a dot
if key == '.':
# Then just return the current scope
return scopes[0]
# Loop through the scopes
for scope in scopes:
try:
# For every dot seperated key
for child in key.split('.'):
# Move into the scope
try:
# Try subscripting (Normal dictionaries)
scope = scope[child]
except (TypeError, AttributeError):
try:
# Try the dictionary (Complex types)
scope = scope.__dict__[child]
except (TypeError, AttributeError):
# Try as a list
scope = scope[int(child)]
# Return an empty string if falsy, with two exceptions
# 0 should return 0, and False should return False
# While using is for this check is undefined it works and is fast
if scope is 0: # noqa: F632
return 0
if scope is False:
return False
try:
# This allows for custom falsy data types
# https://github.com/noahmorrison/chevron/issues/35
if scope._CHEVRON_return_scope_when_falsy:
return scope
except AttributeError:
return scope or ''
except (AttributeError, KeyError, IndexError, ValueError):
# We couldn't find the key in the current scope
# We'll try again on the next pass
pass
# We couldn't find the key in any of the scopes
return '' | [
"def",
"_get_key",
"(",
"key",
",",
"scopes",
")",
":",
"# If the key is a dot",
"if",
"key",
"==",
"'.'",
":",
"# Then just return the current scope",
"return",
"scopes",
"[",
"0",
"]",
"# Loop through the scopes",
"for",
"scope",
"in",
"scopes",
":",
"try",
":... | Get a key from the current scope | [
"Get",
"a",
"key",
"from",
"the",
"current",
"scope"
] | 78f1a384eddef16906732d8db66deea6d37049b7 | https://github.com/noahmorrison/chevron/blob/78f1a384eddef16906732d8db66deea6d37049b7/chevron/renderer.py#L50-L96 | train | 52,782 |
noahmorrison/chevron | chevron/renderer.py | _get_partial | def _get_partial(name, partials_dict, partials_path, partials_ext):
"""Load a partial"""
try:
# Maybe the partial is in the dictionary
return partials_dict[name]
except KeyError:
# Nope...
try:
# Maybe it's in the file system
path_ext = ('.' + partials_ext if partials_ext else '')
path = partials_path + '/' + name + path_ext
with io.open(path, 'r', encoding='utf-8') as partial:
return partial.read()
except IOError:
# Alright I give up on you
return '' | python | def _get_partial(name, partials_dict, partials_path, partials_ext):
"""Load a partial"""
try:
# Maybe the partial is in the dictionary
return partials_dict[name]
except KeyError:
# Nope...
try:
# Maybe it's in the file system
path_ext = ('.' + partials_ext if partials_ext else '')
path = partials_path + '/' + name + path_ext
with io.open(path, 'r', encoding='utf-8') as partial:
return partial.read()
except IOError:
# Alright I give up on you
return '' | [
"def",
"_get_partial",
"(",
"name",
",",
"partials_dict",
",",
"partials_path",
",",
"partials_ext",
")",
":",
"try",
":",
"# Maybe the partial is in the dictionary",
"return",
"partials_dict",
"[",
"name",
"]",
"except",
"KeyError",
":",
"# Nope...",
"try",
":",
... | Load a partial | [
"Load",
"a",
"partial"
] | 78f1a384eddef16906732d8db66deea6d37049b7 | https://github.com/noahmorrison/chevron/blob/78f1a384eddef16906732d8db66deea6d37049b7/chevron/renderer.py#L99-L115 | train | 52,783 |
tapanpandita/pocket | pocket.py | Pocket.commit | def commit(self):
'''
This method executes the bulk query, flushes stored queries and
returns the response
'''
url = self.api_endpoints['send']
payload = {
'actions': self._bulk_query,
}
payload.update(self._payload)
self._bulk_query = []
return self._make_request(
url,
json.dumps(payload),
headers={'content-type': 'application/json'},
) | python | def commit(self):
'''
This method executes the bulk query, flushes stored queries and
returns the response
'''
url = self.api_endpoints['send']
payload = {
'actions': self._bulk_query,
}
payload.update(self._payload)
self._bulk_query = []
return self._make_request(
url,
json.dumps(payload),
headers={'content-type': 'application/json'},
) | [
"def",
"commit",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"api_endpoints",
"[",
"'send'",
"]",
"payload",
"=",
"{",
"'actions'",
":",
"self",
".",
"_bulk_query",
",",
"}",
"payload",
".",
"update",
"(",
"self",
".",
"_payload",
")",
"self",
".... | This method executes the bulk query, flushes stored queries and
returns the response | [
"This",
"method",
"executes",
"the",
"bulk",
"query",
"flushes",
"stored",
"queries",
"and",
"returns",
"the",
"response"
] | 5a144438cc89bfc0ec94db960718ccf1f76468c1 | https://github.com/tapanpandita/pocket/blob/5a144438cc89bfc0ec94db960718ccf1f76468c1/pocket.py#L280-L297 | train | 52,784 |
tapanpandita/pocket | pocket.py | Pocket.get_request_token | def get_request_token(
cls, consumer_key, redirect_uri='http://example.com/', state=None
):
'''
Returns the request token that can be used to fetch the access token
'''
headers = {
'X-Accept': 'application/json',
}
url = 'https://getpocket.com/v3/oauth/request'
payload = {
'consumer_key': consumer_key,
'redirect_uri': redirect_uri,
}
if state:
payload['state'] = state
return cls._make_request(url, payload, headers)[0]['code'] | python | def get_request_token(
cls, consumer_key, redirect_uri='http://example.com/', state=None
):
'''
Returns the request token that can be used to fetch the access token
'''
headers = {
'X-Accept': 'application/json',
}
url = 'https://getpocket.com/v3/oauth/request'
payload = {
'consumer_key': consumer_key,
'redirect_uri': redirect_uri,
}
if state:
payload['state'] = state
return cls._make_request(url, payload, headers)[0]['code'] | [
"def",
"get_request_token",
"(",
"cls",
",",
"consumer_key",
",",
"redirect_uri",
"=",
"'http://example.com/'",
",",
"state",
"=",
"None",
")",
":",
"headers",
"=",
"{",
"'X-Accept'",
":",
"'application/json'",
",",
"}",
"url",
"=",
"'https://getpocket.com/v3/oaut... | Returns the request token that can be used to fetch the access token | [
"Returns",
"the",
"request",
"token",
"that",
"can",
"be",
"used",
"to",
"fetch",
"the",
"access",
"token"
] | 5a144438cc89bfc0ec94db960718ccf1f76468c1 | https://github.com/tapanpandita/pocket/blob/5a144438cc89bfc0ec94db960718ccf1f76468c1/pocket.py#L300-L319 | train | 52,785 |
tapanpandita/pocket | pocket.py | Pocket.get_credentials | def get_credentials(cls, consumer_key, code):
'''
Fetches access token from using the request token and consumer key
'''
headers = {
'X-Accept': 'application/json',
}
url = 'https://getpocket.com/v3/oauth/authorize'
payload = {
'consumer_key': consumer_key,
'code': code,
}
return cls._make_request(url, payload, headers)[0] | python | def get_credentials(cls, consumer_key, code):
'''
Fetches access token from using the request token and consumer key
'''
headers = {
'X-Accept': 'application/json',
}
url = 'https://getpocket.com/v3/oauth/authorize'
payload = {
'consumer_key': consumer_key,
'code': code,
}
return cls._make_request(url, payload, headers)[0] | [
"def",
"get_credentials",
"(",
"cls",
",",
"consumer_key",
",",
"code",
")",
":",
"headers",
"=",
"{",
"'X-Accept'",
":",
"'application/json'",
",",
"}",
"url",
"=",
"'https://getpocket.com/v3/oauth/authorize'",
"payload",
"=",
"{",
"'consumer_key'",
":",
"consume... | Fetches access token from using the request token and consumer key | [
"Fetches",
"access",
"token",
"from",
"using",
"the",
"request",
"token",
"and",
"consumer",
"key"
] | 5a144438cc89bfc0ec94db960718ccf1f76468c1 | https://github.com/tapanpandita/pocket/blob/5a144438cc89bfc0ec94db960718ccf1f76468c1/pocket.py#L322-L336 | train | 52,786 |
adewes/blitzdb | blitzdb/backends/sql/relations.py | ManyToManyProxy.remove | def remove(self,obj):
"""
Remove an object from the relation
"""
relationship_table = self.params['relationship_table']
with self.obj.backend.transaction(implicit = True):
condition = and_(relationship_table.c[self.params['related_pk_field_name']] == obj.pk,
relationship_table.c[self.params['pk_field_name']] == self.obj.pk)
self.obj.backend.connection.execute(delete(relationship_table).where(condition))
self._queryset = None | python | def remove(self,obj):
"""
Remove an object from the relation
"""
relationship_table = self.params['relationship_table']
with self.obj.backend.transaction(implicit = True):
condition = and_(relationship_table.c[self.params['related_pk_field_name']] == obj.pk,
relationship_table.c[self.params['pk_field_name']] == self.obj.pk)
self.obj.backend.connection.execute(delete(relationship_table).where(condition))
self._queryset = None | [
"def",
"remove",
"(",
"self",
",",
"obj",
")",
":",
"relationship_table",
"=",
"self",
".",
"params",
"[",
"'relationship_table'",
"]",
"with",
"self",
".",
"obj",
".",
"backend",
".",
"transaction",
"(",
"implicit",
"=",
"True",
")",
":",
"condition",
"... | Remove an object from the relation | [
"Remove",
"an",
"object",
"from",
"the",
"relation"
] | 4b459e0bcde9e1f6224dd4e3bea74194586864b0 | https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/sql/relations.py#L123-L132 | train | 52,787 |
adewes/blitzdb | blitzdb/backends/file/backend.py | Backend.begin | def begin(self):
"""Start a new transaction."""
if self.in_transaction: # we're already in a transaction...
if self._auto_transaction:
self._auto_transaction = False
return
self.commit()
self.in_transaction = True
for collection, store in self.stores.items():
store.begin()
indexes = self.indexes[collection]
for index in indexes.values():
index.begin() | python | def begin(self):
"""Start a new transaction."""
if self.in_transaction: # we're already in a transaction...
if self._auto_transaction:
self._auto_transaction = False
return
self.commit()
self.in_transaction = True
for collection, store in self.stores.items():
store.begin()
indexes = self.indexes[collection]
for index in indexes.values():
index.begin() | [
"def",
"begin",
"(",
"self",
")",
":",
"if",
"self",
".",
"in_transaction",
":",
"# we're already in a transaction...",
"if",
"self",
".",
"_auto_transaction",
":",
"self",
".",
"_auto_transaction",
"=",
"False",
"return",
"self",
".",
"commit",
"(",
")",
"sel... | Start a new transaction. | [
"Start",
"a",
"new",
"transaction",
"."
] | 4b459e0bcde9e1f6224dd4e3bea74194586864b0 | https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/backend.py#L113-L125 | train | 52,788 |
adewes/blitzdb | blitzdb/backends/file/backend.py | Backend.rollback | def rollback(self, transaction = None):
"""Roll back a transaction."""
if not self.in_transaction:
raise NotInTransaction
for collection, store in self.stores.items():
store.rollback()
indexes = self.indexes[collection]
indexes_to_rebuild = []
for key, index in indexes.items():
try:
index.rollback()
except NotInTransaction:
# this index is "dirty" and needs to be rebuilt
# (probably it has been created within a transaction)
indexes_to_rebuild.append(key)
if indexes_to_rebuild:
self.rebuild_indexes(collection, indexes_to_rebuild)
self.in_transaction = False | python | def rollback(self, transaction = None):
"""Roll back a transaction."""
if not self.in_transaction:
raise NotInTransaction
for collection, store in self.stores.items():
store.rollback()
indexes = self.indexes[collection]
indexes_to_rebuild = []
for key, index in indexes.items():
try:
index.rollback()
except NotInTransaction:
# this index is "dirty" and needs to be rebuilt
# (probably it has been created within a transaction)
indexes_to_rebuild.append(key)
if indexes_to_rebuild:
self.rebuild_indexes(collection, indexes_to_rebuild)
self.in_transaction = False | [
"def",
"rollback",
"(",
"self",
",",
"transaction",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"in_transaction",
":",
"raise",
"NotInTransaction",
"for",
"collection",
",",
"store",
"in",
"self",
".",
"stores",
".",
"items",
"(",
")",
":",
"store",... | Roll back a transaction. | [
"Roll",
"back",
"a",
"transaction",
"."
] | 4b459e0bcde9e1f6224dd4e3bea74194586864b0 | https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/backend.py#L143-L160 | train | 52,789 |
adewes/blitzdb | blitzdb/backends/file/backend.py | Backend.commit | def commit(self,transaction = None):
"""Commit all pending transactions to the database.
.. admonition:: Warning
This operation can be **expensive** in runtime if a large number of
documents (>100.000) is contained in the database, since it will
cause all database indexes to be written to disk.
"""
for collection in self.collections:
store = self.get_collection_store(collection)
store.commit()
indexes = self.get_collection_indexes(collection)
for index in indexes.values():
index.commit()
self.in_transaction = False
self.begin() | python | def commit(self,transaction = None):
"""Commit all pending transactions to the database.
.. admonition:: Warning
This operation can be **expensive** in runtime if a large number of
documents (>100.000) is contained in the database, since it will
cause all database indexes to be written to disk.
"""
for collection in self.collections:
store = self.get_collection_store(collection)
store.commit()
indexes = self.get_collection_indexes(collection)
for index in indexes.values():
index.commit()
self.in_transaction = False
self.begin() | [
"def",
"commit",
"(",
"self",
",",
"transaction",
"=",
"None",
")",
":",
"for",
"collection",
"in",
"self",
".",
"collections",
":",
"store",
"=",
"self",
".",
"get_collection_store",
"(",
"collection",
")",
"store",
".",
"commit",
"(",
")",
"indexes",
"... | Commit all pending transactions to the database.
.. admonition:: Warning
This operation can be **expensive** in runtime if a large number of
documents (>100.000) is contained in the database, since it will
cause all database indexes to be written to disk. | [
"Commit",
"all",
"pending",
"transactions",
"to",
"the",
"database",
"."
] | 4b459e0bcde9e1f6224dd4e3bea74194586864b0 | https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/backend.py#L162-L179 | train | 52,790 |
adewes/blitzdb | blitzdb/backends/file/backend.py | Backend.get_pk_index | def get_pk_index(self, collection):
"""Return the primary key index for a given collection.
:param collection: the collection for which to return the primary index
:returns: the primary key index of the given collection
"""
cls = self.collections[collection]
if not cls.get_pk_name() in self.indexes[collection]:
self.create_index(cls.get_pk_name(), collection)
return self.indexes[collection][cls.get_pk_name()] | python | def get_pk_index(self, collection):
"""Return the primary key index for a given collection.
:param collection: the collection for which to return the primary index
:returns: the primary key index of the given collection
"""
cls = self.collections[collection]
if not cls.get_pk_name() in self.indexes[collection]:
self.create_index(cls.get_pk_name(), collection)
return self.indexes[collection][cls.get_pk_name()] | [
"def",
"get_pk_index",
"(",
"self",
",",
"collection",
")",
":",
"cls",
"=",
"self",
".",
"collections",
"[",
"collection",
"]",
"if",
"not",
"cls",
".",
"get_pk_name",
"(",
")",
"in",
"self",
".",
"indexes",
"[",
"collection",
"]",
":",
"self",
".",
... | Return the primary key index for a given collection.
:param collection: the collection for which to return the primary index
:returns: the primary key index of the given collection | [
"Return",
"the",
"primary",
"key",
"index",
"for",
"a",
"given",
"collection",
"."
] | 4b459e0bcde9e1f6224dd4e3bea74194586864b0 | https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/backend.py#L252-L264 | train | 52,791 |
adewes/blitzdb | blitzdb/backends/base.py | Backend.register | def register(self, cls, parameters=None,overwrite = False):
"""
Explicitly register a new document class for use in the backend.
:param cls: A reference to the class to be defined
:param parameters: A dictionary of parameters. Currently, only the `collection` parameter is used
to specify the collection in which to store the documents of the given class.
.. admonition:: Registering classes
If possible, always use `autodiscover_classes = True` or register your document classes beforehand
using the `register` function, since this ensures that related documents can be initialized
appropriately. For example, suppose you have a document class `Author` that contains a list of
references to documents of class `Book`. If you retrieve an instance of an `Author` object from
the database without having registered the `Book` class, the references to that class will not get
parsed properly and will just show up as dictionaries containing a primary key and a collection name.
Also, when :py:meth:`blitzdb.backends.base.Backend.autoregister` is used to register a class,
you can't pass in any parameters to customize e.g. the collection name for that class
(you can of course do this throught the `Meta` attribute of the class)
## Inheritance
If `register` encounters a document class with a collection name that overlaps with the
collection name of an already registered document class, it checks if the new class is a
subclass of the one that is already register. If yes, it associates the new class to the
collection name. Otherwise, it leaves the collection associated to the already
registered class.
"""
if cls in self.deprecated_classes and not overwrite:
return False
if parameters is None:
parameters = {}
if 'collection' in parameters:
collection_name = parameters['collection']
elif hasattr(cls.Meta,'collection'):
collection_name = cls.Meta.collection
else:
collection_name = cls.__name__.lower()
delete_list = []
def register_class(collection_name,cls):
self.collections[collection_name] = cls
self.classes[cls] = parameters.copy()
self.classes[cls]['collection'] = collection_name
if collection_name in self.collections:
old_cls = self.collections[collection_name]
if (issubclass(cls,old_cls) and not (cls is old_cls)) or overwrite:
logger.warning("Replacing class %s with %s for collection %s" % (old_cls,cls,collection_name))
self.deprecated_classes[old_cls] = self.classes[old_cls]
del self.classes[old_cls]
register_class(collection_name,cls)
return True
else:
logger.debug("Registering class %s under collection %s" % (cls,collection_name))
register_class(collection_name,cls)
return True
return False | python | def register(self, cls, parameters=None,overwrite = False):
"""
Explicitly register a new document class for use in the backend.
:param cls: A reference to the class to be defined
:param parameters: A dictionary of parameters. Currently, only the `collection` parameter is used
to specify the collection in which to store the documents of the given class.
.. admonition:: Registering classes
If possible, always use `autodiscover_classes = True` or register your document classes beforehand
using the `register` function, since this ensures that related documents can be initialized
appropriately. For example, suppose you have a document class `Author` that contains a list of
references to documents of class `Book`. If you retrieve an instance of an `Author` object from
the database without having registered the `Book` class, the references to that class will not get
parsed properly and will just show up as dictionaries containing a primary key and a collection name.
Also, when :py:meth:`blitzdb.backends.base.Backend.autoregister` is used to register a class,
you can't pass in any parameters to customize e.g. the collection name for that class
(you can of course do this throught the `Meta` attribute of the class)
## Inheritance
If `register` encounters a document class with a collection name that overlaps with the
collection name of an already registered document class, it checks if the new class is a
subclass of the one that is already register. If yes, it associates the new class to the
collection name. Otherwise, it leaves the collection associated to the already
registered class.
"""
if cls in self.deprecated_classes and not overwrite:
return False
if parameters is None:
parameters = {}
if 'collection' in parameters:
collection_name = parameters['collection']
elif hasattr(cls.Meta,'collection'):
collection_name = cls.Meta.collection
else:
collection_name = cls.__name__.lower()
delete_list = []
def register_class(collection_name,cls):
self.collections[collection_name] = cls
self.classes[cls] = parameters.copy()
self.classes[cls]['collection'] = collection_name
if collection_name in self.collections:
old_cls = self.collections[collection_name]
if (issubclass(cls,old_cls) and not (cls is old_cls)) or overwrite:
logger.warning("Replacing class %s with %s for collection %s" % (old_cls,cls,collection_name))
self.deprecated_classes[old_cls] = self.classes[old_cls]
del self.classes[old_cls]
register_class(collection_name,cls)
return True
else:
logger.debug("Registering class %s under collection %s" % (cls,collection_name))
register_class(collection_name,cls)
return True
return False | [
"def",
"register",
"(",
"self",
",",
"cls",
",",
"parameters",
"=",
"None",
",",
"overwrite",
"=",
"False",
")",
":",
"if",
"cls",
"in",
"self",
".",
"deprecated_classes",
"and",
"not",
"overwrite",
":",
"return",
"False",
"if",
"parameters",
"is",
"None... | Explicitly register a new document class for use in the backend.
:param cls: A reference to the class to be defined
:param parameters: A dictionary of parameters. Currently, only the `collection` parameter is used
to specify the collection in which to store the documents of the given class.
.. admonition:: Registering classes
If possible, always use `autodiscover_classes = True` or register your document classes beforehand
using the `register` function, since this ensures that related documents can be initialized
appropriately. For example, suppose you have a document class `Author` that contains a list of
references to documents of class `Book`. If you retrieve an instance of an `Author` object from
the database without having registered the `Book` class, the references to that class will not get
parsed properly and will just show up as dictionaries containing a primary key and a collection name.
Also, when :py:meth:`blitzdb.backends.base.Backend.autoregister` is used to register a class,
you can't pass in any parameters to customize e.g. the collection name for that class
(you can of course do this throught the `Meta` attribute of the class)
## Inheritance
If `register` encounters a document class with a collection name that overlaps with the
collection name of an already registered document class, it checks if the new class is a
subclass of the one that is already register. If yes, it associates the new class to the
collection name. Otherwise, it leaves the collection associated to the already
registered class. | [
"Explicitly",
"register",
"a",
"new",
"document",
"class",
"for",
"use",
"in",
"the",
"backend",
"."
] | 4b459e0bcde9e1f6224dd4e3bea74194586864b0 | https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/base.py#L101-L163 | train | 52,792 |
adewes/blitzdb | blitzdb/backends/base.py | Backend.autoregister | def autoregister(self, cls):
"""
Autoregister a class that is encountered for the first time.
:param cls: The class that should be registered.
"""
params = self.get_meta_attributes(cls)
return self.register(cls, params) | python | def autoregister(self, cls):
"""
Autoregister a class that is encountered for the first time.
:param cls: The class that should be registered.
"""
params = self.get_meta_attributes(cls)
return self.register(cls, params) | [
"def",
"autoregister",
"(",
"self",
",",
"cls",
")",
":",
"params",
"=",
"self",
".",
"get_meta_attributes",
"(",
"cls",
")",
"return",
"self",
".",
"register",
"(",
"cls",
",",
"params",
")"
] | Autoregister a class that is encountered for the first time.
:param cls: The class that should be registered. | [
"Autoregister",
"a",
"class",
"that",
"is",
"encountered",
"for",
"the",
"first",
"time",
"."
] | 4b459e0bcde9e1f6224dd4e3bea74194586864b0 | https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/base.py#L180-L188 | train | 52,793 |
adewes/blitzdb | blitzdb/backends/base.py | Backend.create_instance | def create_instance(self, collection_or_class, attributes, lazy=False, call_hook=True, deserialize=True, db_loader=None):
"""
Creates an instance of a `Document` class corresponding to the given collection name or class.
:param collection_or_class: The name of the collection or a reference to the class for which to create an instance.
:param attributes: The attributes of the instance to be created
:param lazy: Whether to create a `lazy` object or not.
:returns: An instance of the requested Document class with the given attributes.
"""
creation_args = {
'backend' : self,
'autoload' : self._autoload_embedded,
'lazy' : lazy,
'db_loader' : db_loader
}
if collection_or_class in self.classes:
cls = collection_or_class
elif collection_or_class in self.collections:
cls = self.collections[collection_or_class]
else:
raise AttributeError("Unknown collection or class: %s!" % str(collection_or_class))
#we deserialize the attributes that we receive
if deserialize:
deserialized_attributes = self.deserialize(attributes, create_instance=False)
else:
deserialized_attributes = attributes
if 'constructor' in self.classes[cls]:
obj = self.classes[cls]['constructor'](deserialized_attributes, **creation_args)
else:
obj = cls(deserialized_attributes, **creation_args)
if call_hook:
self.call_hook('after_load',obj)
return obj | python | def create_instance(self, collection_or_class, attributes, lazy=False, call_hook=True, deserialize=True, db_loader=None):
"""
Creates an instance of a `Document` class corresponding to the given collection name or class.
:param collection_or_class: The name of the collection or a reference to the class for which to create an instance.
:param attributes: The attributes of the instance to be created
:param lazy: Whether to create a `lazy` object or not.
:returns: An instance of the requested Document class with the given attributes.
"""
creation_args = {
'backend' : self,
'autoload' : self._autoload_embedded,
'lazy' : lazy,
'db_loader' : db_loader
}
if collection_or_class in self.classes:
cls = collection_or_class
elif collection_or_class in self.collections:
cls = self.collections[collection_or_class]
else:
raise AttributeError("Unknown collection or class: %s!" % str(collection_or_class))
#we deserialize the attributes that we receive
if deserialize:
deserialized_attributes = self.deserialize(attributes, create_instance=False)
else:
deserialized_attributes = attributes
if 'constructor' in self.classes[cls]:
obj = self.classes[cls]['constructor'](deserialized_attributes, **creation_args)
else:
obj = cls(deserialized_attributes, **creation_args)
if call_hook:
self.call_hook('after_load',obj)
return obj | [
"def",
"create_instance",
"(",
"self",
",",
"collection_or_class",
",",
"attributes",
",",
"lazy",
"=",
"False",
",",
"call_hook",
"=",
"True",
",",
"deserialize",
"=",
"True",
",",
"db_loader",
"=",
"None",
")",
":",
"creation_args",
"=",
"{",
"'backend'",
... | Creates an instance of a `Document` class corresponding to the given collection name or class.
:param collection_or_class: The name of the collection or a reference to the class for which to create an instance.
:param attributes: The attributes of the instance to be created
:param lazy: Whether to create a `lazy` object or not.
:returns: An instance of the requested Document class with the given attributes. | [
"Creates",
"an",
"instance",
"of",
"a",
"Document",
"class",
"corresponding",
"to",
"the",
"given",
"collection",
"name",
"or",
"class",
"."
] | 4b459e0bcde9e1f6224dd4e3bea74194586864b0 | https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/base.py#L342-L380 | train | 52,794 |
adewes/blitzdb | blitzdb/backends/base.py | Backend.transaction | def transaction(self,implicit = False):
"""
This returns a context guard which will automatically open and close a transaction
"""
class TransactionManager(object):
def __init__(self,backend,implicit = False):
self.backend = backend
self.implicit = implicit
def __enter__(self):
self.within_transaction = True if self.backend.current_transaction else False
self.transaction = self.backend.begin()
def __exit__(self,exc_type,exc_value,traceback_obj):
if exc_type:
self.backend.rollback(self.transaction)
return False
else:
#if the transaction has been created implicitly and we are not within
#another transaction, we leave it open (the user needs to call commit manually)
#if self.implicit and not self.within_transaction:
# return
self.backend.commit(self.transaction)
return TransactionManager(self,implicit = implicit) | python | def transaction(self,implicit = False):
"""
This returns a context guard which will automatically open and close a transaction
"""
class TransactionManager(object):
def __init__(self,backend,implicit = False):
self.backend = backend
self.implicit = implicit
def __enter__(self):
self.within_transaction = True if self.backend.current_transaction else False
self.transaction = self.backend.begin()
def __exit__(self,exc_type,exc_value,traceback_obj):
if exc_type:
self.backend.rollback(self.transaction)
return False
else:
#if the transaction has been created implicitly and we are not within
#another transaction, we leave it open (the user needs to call commit manually)
#if self.implicit and not self.within_transaction:
# return
self.backend.commit(self.transaction)
return TransactionManager(self,implicit = implicit) | [
"def",
"transaction",
"(",
"self",
",",
"implicit",
"=",
"False",
")",
":",
"class",
"TransactionManager",
"(",
"object",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"backend",
",",
"implicit",
"=",
"False",
")",
":",
"self",
".",
"backend",
"=",
"b... | This returns a context guard which will automatically open and close a transaction | [
"This",
"returns",
"a",
"context",
"guard",
"which",
"will",
"automatically",
"open",
"and",
"close",
"a",
"transaction"
] | 4b459e0bcde9e1f6224dd4e3bea74194586864b0 | https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/base.py#L387-L413 | train | 52,795 |
adewes/blitzdb | blitzdb/backends/base.py | Backend.get_cls_for_collection | def get_cls_for_collection(self, collection):
"""
Return the class for a given collection name.
:param collection: The name of the collection for which to return the class.
:returns: A reference to the class for the given collection name.
"""
for cls, params in self.classes.items():
if params['collection'] == collection:
return cls
raise AttributeError("Unknown collection: %s" % collection) | python | def get_cls_for_collection(self, collection):
"""
Return the class for a given collection name.
:param collection: The name of the collection for which to return the class.
:returns: A reference to the class for the given collection name.
"""
for cls, params in self.classes.items():
if params['collection'] == collection:
return cls
raise AttributeError("Unknown collection: %s" % collection) | [
"def",
"get_cls_for_collection",
"(",
"self",
",",
"collection",
")",
":",
"for",
"cls",
",",
"params",
"in",
"self",
".",
"classes",
".",
"items",
"(",
")",
":",
"if",
"params",
"[",
"'collection'",
"]",
"==",
"collection",
":",
"return",
"cls",
"raise"... | Return the class for a given collection name.
:param collection: The name of the collection for which to return the class.
:returns: A reference to the class for the given collection name. | [
"Return",
"the",
"class",
"for",
"a",
"given",
"collection",
"name",
"."
] | 4b459e0bcde9e1f6224dd4e3bea74194586864b0 | https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/base.py#L454-L465 | train | 52,796 |
adewes/blitzdb | blitzdb/backends/file/index.py | Index.clear | def clear(self):
"""Clear index."""
self._index = defaultdict(list)
self._reverse_index = defaultdict(list)
self._undefined_keys = {} | python | def clear(self):
"""Clear index."""
self._index = defaultdict(list)
self._reverse_index = defaultdict(list)
self._undefined_keys = {} | [
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"_index",
"=",
"defaultdict",
"(",
"list",
")",
"self",
".",
"_reverse_index",
"=",
"defaultdict",
"(",
"list",
")",
"self",
".",
"_undefined_keys",
"=",
"{",
"}"
] | Clear index. | [
"Clear",
"index",
"."
] | 4b459e0bcde9e1f6224dd4e3bea74194586864b0 | https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L54-L58 | train | 52,797 |
adewes/blitzdb | blitzdb/backends/file/index.py | Index.get_value | def get_value(self, attributes,key = None):
"""Get value to be indexed from document attributes.
:param attributes: Document attributes
:type attributes: dict
:return: Value to be indexed
:rtype: object
"""
value = attributes
if key is None:
key = self._splitted_key
# A splitted key like 'a.b.c' goes into nested properties
# and the value is retrieved recursively
for i,elem in enumerate(key):
if isinstance(value, (list,tuple)):
#if this is a list, we return all matching values for the given list items
return [self.get_value(v,key[i:]) for v in value]
else:
value = value[elem]
return value | python | def get_value(self, attributes,key = None):
"""Get value to be indexed from document attributes.
:param attributes: Document attributes
:type attributes: dict
:return: Value to be indexed
:rtype: object
"""
value = attributes
if key is None:
key = self._splitted_key
# A splitted key like 'a.b.c' goes into nested properties
# and the value is retrieved recursively
for i,elem in enumerate(key):
if isinstance(value, (list,tuple)):
#if this is a list, we return all matching values for the given list items
return [self.get_value(v,key[i:]) for v in value]
else:
value = value[elem]
return value | [
"def",
"get_value",
"(",
"self",
",",
"attributes",
",",
"key",
"=",
"None",
")",
":",
"value",
"=",
"attributes",
"if",
"key",
"is",
"None",
":",
"key",
"=",
"self",
".",
"_splitted_key",
"# A splitted key like 'a.b.c' goes into nested properties",
"# and the val... | Get value to be indexed from document attributes.
:param attributes: Document attributes
:type attributes: dict
:return: Value to be indexed
:rtype: object | [
"Get",
"value",
"to",
"be",
"indexed",
"from",
"document",
"attributes",
"."
] | 4b459e0bcde9e1f6224dd4e3bea74194586864b0 | https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L74-L97 | train | 52,798 |
adewes/blitzdb | blitzdb/backends/file/index.py | Index.save_to_store | def save_to_store(self):
"""Save index to store.
:raise AttributeError: If no datastore is defined
"""
if not self._store:
raise AttributeError('No datastore defined!')
saved_data = self.save_to_data(in_place=True)
data = Serializer.serialize(saved_data)
self._store.store_blob(data, 'all_keys_with_undefined') | python | def save_to_store(self):
"""Save index to store.
:raise AttributeError: If no datastore is defined
"""
if not self._store:
raise AttributeError('No datastore defined!')
saved_data = self.save_to_data(in_place=True)
data = Serializer.serialize(saved_data)
self._store.store_blob(data, 'all_keys_with_undefined') | [
"def",
"save_to_store",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_store",
":",
"raise",
"AttributeError",
"(",
"'No datastore defined!'",
")",
"saved_data",
"=",
"self",
".",
"save_to_data",
"(",
"in_place",
"=",
"True",
")",
"data",
"=",
"Serialize... | Save index to store.
:raise AttributeError: If no datastore is defined | [
"Save",
"index",
"to",
"store",
"."
] | 4b459e0bcde9e1f6224dd4e3bea74194586864b0 | https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L99-L109 | train | 52,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.