id int32 0 252k | 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 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
229,700 | psd-tools/psd-tools | src/psd_tools/api/pil_io.py | _apply_icc | def _apply_icc(image, icc_profile):
"""Apply ICC Color profile."""
from io import BytesIO
try:
from PIL import ImageCms
except ImportError:
logger.debug(
'ICC profile found but not supported. Install little-cms.'
)
return image
if image.mode not in ('RGB',):
logger.debug('%s ICC profile is not supported.' % image.mode)
return image
try:
in_profile = ImageCms.ImageCmsProfile(BytesIO(icc_profile))
out_profile = ImageCms.createProfile('sRGB')
return ImageCms.profileToProfile(image, in_profile, out_profile)
except ImageCms.PyCMSError as e:
logger.warning('PyCMSError: %s' % (e))
return image | python | def _apply_icc(image, icc_profile):
from io import BytesIO
try:
from PIL import ImageCms
except ImportError:
logger.debug(
'ICC profile found but not supported. Install little-cms.'
)
return image
if image.mode not in ('RGB',):
logger.debug('%s ICC profile is not supported.' % image.mode)
return image
try:
in_profile = ImageCms.ImageCmsProfile(BytesIO(icc_profile))
out_profile = ImageCms.createProfile('sRGB')
return ImageCms.profileToProfile(image, in_profile, out_profile)
except ImageCms.PyCMSError as e:
logger.warning('PyCMSError: %s' % (e))
return image | [
"def",
"_apply_icc",
"(",
"image",
",",
"icc_profile",
")",
":",
"from",
"io",
"import",
"BytesIO",
"try",
":",
"from",
"PIL",
"import",
"ImageCms",
"except",
"ImportError",
":",
"logger",
".",
"debug",
"(",
"'ICC profile found but not supported. Install little-cms.... | Apply ICC Color profile. | [
"Apply",
"ICC",
"Color",
"profile",
"."
] | 4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/pil_io.py#L223-L245 |
229,701 | psd-tools/psd-tools | src/psd_tools/api/pil_io.py | _remove_white_background | def _remove_white_background(image):
"""Remove white background in the preview image."""
from PIL import ImageMath, Image
if image.mode == "RGBA":
bands = image.split()
a = bands[3]
rgb = [
ImageMath.eval(
'convert('
'float(x + a - 255) * 255.0 / float(max(a, 1)) * '
'float(min(a, 1)) + float(x) * float(1 - min(a, 1))'
', "L")',
x=x, a=a
)
for x in bands[:3]
]
return Image.merge(bands=rgb + [a], mode="RGBA")
return image | python | def _remove_white_background(image):
from PIL import ImageMath, Image
if image.mode == "RGBA":
bands = image.split()
a = bands[3]
rgb = [
ImageMath.eval(
'convert('
'float(x + a - 255) * 255.0 / float(max(a, 1)) * '
'float(min(a, 1)) + float(x) * float(1 - min(a, 1))'
', "L")',
x=x, a=a
)
for x in bands[:3]
]
return Image.merge(bands=rgb + [a], mode="RGBA")
return image | [
"def",
"_remove_white_background",
"(",
"image",
")",
":",
"from",
"PIL",
"import",
"ImageMath",
",",
"Image",
"if",
"image",
".",
"mode",
"==",
"\"RGBA\"",
":",
"bands",
"=",
"image",
".",
"split",
"(",
")",
"a",
"=",
"bands",
"[",
"3",
"]",
"rgb",
... | Remove white background in the preview image. | [
"Remove",
"white",
"background",
"in",
"the",
"preview",
"image",
"."
] | 4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/pil_io.py#L248-L266 |
229,702 | psd-tools/psd-tools | src/psd_tools/api/mask.py | Mask.background_color | def background_color(self):
"""Background color."""
if self._has_real():
return self._data.real_background_color
return self._data.background_color | python | def background_color(self):
if self._has_real():
return self._data.real_background_color
return self._data.background_color | [
"def",
"background_color",
"(",
"self",
")",
":",
"if",
"self",
".",
"_has_real",
"(",
")",
":",
"return",
"self",
".",
"_data",
".",
"real_background_color",
"return",
"self",
".",
"_data",
".",
"background_color"
] | Background color. | [
"Background",
"color",
"."
] | 4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/mask.py#L25-L29 |
229,703 | psd-tools/psd-tools | src/psd_tools/api/mask.py | Mask.left | def left(self):
"""Left coordinate."""
if self._has_real():
return self._data.real_left
return self._data.left | python | def left(self):
if self._has_real():
return self._data.real_left
return self._data.left | [
"def",
"left",
"(",
"self",
")",
":",
"if",
"self",
".",
"_has_real",
"(",
")",
":",
"return",
"self",
".",
"_data",
".",
"real_left",
"return",
"self",
".",
"_data",
".",
"left"
] | Left coordinate. | [
"Left",
"coordinate",
"."
] | 4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/mask.py#L37-L41 |
229,704 | psd-tools/psd-tools | src/psd_tools/api/mask.py | Mask.right | def right(self):
"""Right coordinate."""
if self._has_real():
return self._data.real_right
return self._data.right | python | def right(self):
if self._has_real():
return self._data.real_right
return self._data.right | [
"def",
"right",
"(",
"self",
")",
":",
"if",
"self",
".",
"_has_real",
"(",
")",
":",
"return",
"self",
".",
"_data",
".",
"real_right",
"return",
"self",
".",
"_data",
".",
"right"
] | Right coordinate. | [
"Right",
"coordinate",
"."
] | 4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/mask.py#L44-L48 |
229,705 | psd-tools/psd-tools | src/psd_tools/api/mask.py | Mask.top | def top(self):
"""Top coordinate."""
if self._has_real():
return self._data.real_top
return self._data.top | python | def top(self):
if self._has_real():
return self._data.real_top
return self._data.top | [
"def",
"top",
"(",
"self",
")",
":",
"if",
"self",
".",
"_has_real",
"(",
")",
":",
"return",
"self",
".",
"_data",
".",
"real_top",
"return",
"self",
".",
"_data",
".",
"top"
] | Top coordinate. | [
"Top",
"coordinate",
"."
] | 4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/mask.py#L51-L55 |
229,706 | psd-tools/psd-tools | src/psd_tools/api/mask.py | Mask.bottom | def bottom(self):
"""Bottom coordinate."""
if self._has_real():
return self._data.real_bottom
return self._data.bottom | python | def bottom(self):
if self._has_real():
return self._data.real_bottom
return self._data.bottom | [
"def",
"bottom",
"(",
"self",
")",
":",
"if",
"self",
".",
"_has_real",
"(",
")",
":",
"return",
"self",
".",
"_data",
".",
"real_bottom",
"return",
"self",
".",
"_data",
".",
"bottom"
] | Bottom coordinate. | [
"Bottom",
"coordinate",
"."
] | 4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/mask.py#L58-L62 |
229,707 | psd-tools/psd-tools | src/psd_tools/compression.py | compress | def compress(data, compression, width, height, depth, version=1):
"""Compress raw data.
:param data: raw data bytes to write.
:param compression: compression type, see :py:class:`.Compression`.
:param width: width.
:param height: height.
:param depth: bit depth of the pixel.
:param version: psd file version.
:return: compressed data bytes.
"""
if compression == Compression.RAW:
result = data
elif compression == Compression.PACK_BITS:
result = encode_packbits(data, width, height, depth, version)
elif compression == Compression.ZIP:
result = zlib.compress(data)
else:
encoded = encode_prediction(data, width, height, depth)
result = zlib.compress(encoded)
return result | python | def compress(data, compression, width, height, depth, version=1):
if compression == Compression.RAW:
result = data
elif compression == Compression.PACK_BITS:
result = encode_packbits(data, width, height, depth, version)
elif compression == Compression.ZIP:
result = zlib.compress(data)
else:
encoded = encode_prediction(data, width, height, depth)
result = zlib.compress(encoded)
return result | [
"def",
"compress",
"(",
"data",
",",
"compression",
",",
"width",
",",
"height",
",",
"depth",
",",
"version",
"=",
"1",
")",
":",
"if",
"compression",
"==",
"Compression",
".",
"RAW",
":",
"result",
"=",
"data",
"elif",
"compression",
"==",
"Compression... | Compress raw data.
:param data: raw data bytes to write.
:param compression: compression type, see :py:class:`.Compression`.
:param width: width.
:param height: height.
:param depth: bit depth of the pixel.
:param version: psd file version.
:return: compressed data bytes. | [
"Compress",
"raw",
"data",
"."
] | 4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/compression.py#L16-L37 |
229,708 | psd-tools/psd-tools | src/psd_tools/compression.py | decompress | def decompress(data, compression, width, height, depth, version=1):
"""Decompress raw data.
:param data: compressed data bytes.
:param compression: compression type,
see :py:class:`~psd_tools.constants.Compression`.
:param width: width.
:param height: height.
:param depth: bit depth of the pixel.
:param version: psd file version.
:return: decompressed data bytes.
"""
length = width * height * depth // 8
result = None
if compression == Compression.RAW:
result = data[:length]
elif compression == Compression.PACK_BITS:
result = decode_packbits(data, height, version)
elif compression == Compression.ZIP:
result = zlib.decompress(data)
else:
decompressed = zlib.decompress(data)
result = decode_prediction(decompressed, width, height, depth)
assert len(result) == length, 'len=%d, expected=%d' % (
len(result), length
)
return result | python | def decompress(data, compression, width, height, depth, version=1):
length = width * height * depth // 8
result = None
if compression == Compression.RAW:
result = data[:length]
elif compression == Compression.PACK_BITS:
result = decode_packbits(data, height, version)
elif compression == Compression.ZIP:
result = zlib.decompress(data)
else:
decompressed = zlib.decompress(data)
result = decode_prediction(decompressed, width, height, depth)
assert len(result) == length, 'len=%d, expected=%d' % (
len(result), length
)
return result | [
"def",
"decompress",
"(",
"data",
",",
"compression",
",",
"width",
",",
"height",
",",
"depth",
",",
"version",
"=",
"1",
")",
":",
"length",
"=",
"width",
"*",
"height",
"*",
"depth",
"//",
"8",
"result",
"=",
"None",
"if",
"compression",
"==",
"Co... | Decompress raw data.
:param data: compressed data bytes.
:param compression: compression type,
see :py:class:`~psd_tools.constants.Compression`.
:param width: width.
:param height: height.
:param depth: bit depth of the pixel.
:param version: psd file version.
:return: decompressed data bytes. | [
"Decompress",
"raw",
"data",
"."
] | 4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/compression.py#L40-L69 |
229,709 | psd-tools/psd-tools | src/psd_tools/compression.py | _shuffled_order | def _shuffled_order(w, h):
"""
Generator for the order of 4-byte values.
32bit channels are also encoded using delta encoding,
but it make no sense to apply delta compression to bytes.
It is possible to apply delta compression to 2-byte or 4-byte
words, but it seems it is not the best way either.
In PSD, each 4-byte item is split into 4 bytes and these
bytes are packed together: "123412341234" becomes "111222333444";
delta compression is applied to the packed data.
So we have to (a) decompress data from the delta compression
and (b) recombine data back to 4-byte values.
"""
rowsize = 4 * w
for row in range(0, rowsize * h, rowsize):
for offset in range(row, row + w):
for x in range(offset, offset + rowsize, w):
yield x | python | def _shuffled_order(w, h):
rowsize = 4 * w
for row in range(0, rowsize * h, rowsize):
for offset in range(row, row + w):
for x in range(offset, offset + rowsize, w):
yield x | [
"def",
"_shuffled_order",
"(",
"w",
",",
"h",
")",
":",
"rowsize",
"=",
"4",
"*",
"w",
"for",
"row",
"in",
"range",
"(",
"0",
",",
"rowsize",
"*",
"h",
",",
"rowsize",
")",
":",
"for",
"offset",
"in",
"range",
"(",
"row",
",",
"row",
"+",
"w",
... | Generator for the order of 4-byte values.
32bit channels are also encoded using delta encoding,
but it make no sense to apply delta compression to bytes.
It is possible to apply delta compression to 2-byte or 4-byte
words, but it seems it is not the best way either.
In PSD, each 4-byte item is split into 4 bytes and these
bytes are packed together: "123412341234" becomes "111222333444";
delta compression is applied to the packed data.
So we have to (a) decompress data from the delta compression
and (b) recombine data back to 4-byte values. | [
"Generator",
"for",
"the",
"order",
"of",
"4",
"-",
"byte",
"values",
"."
] | 4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/compression.py#L154-L173 |
229,710 | psd-tools/psd-tools | src/psd_tools/api/composer.py | compose_layer | def compose_layer(layer, force=False, **kwargs):
"""Compose a single layer with pixels."""
from PIL import Image, ImageChops
assert layer.bbox != (0, 0, 0, 0), 'Layer bbox is (0, 0, 0, 0)'
image = layer.topil(**kwargs)
if image is None or force:
texture = create_fill(layer)
if texture is not None:
image = texture
if image is None:
return image
# TODO: Group should have the following too.
# Apply mask.
if layer.has_mask() and not layer.mask.disabled:
mask_bbox = layer.mask.bbox
if (
(mask_bbox[2] - mask_bbox[0]) > 0 and
(mask_bbox[3] - mask_bbox[1]) > 0
):
color = layer.mask.background_color
offset = (mask_bbox[0] - layer.left, mask_bbox[1] - layer.top)
mask = Image.new('L', image.size, color=color)
mask.paste(layer.mask.topil(), offset)
if image.mode.endswith('A'):
# What should we do here? There are two alpha channels.
pass
image.putalpha(mask)
elif layer.has_vector_mask() and (force or not layer.has_pixels()):
mask = draw_vector_mask(layer)
# TODO: Stroke drawing.
texture = image
image = Image.new(image.mode, image.size, 'white')
image.paste(texture, mask=mask)
# Apply layer fill effects.
apply_effect(layer, image)
# Clip layers.
if layer.has_clip_layers():
clip_box = extract_bbox(layer.clip_layers)
inter_box = intersect(layer.bbox, clip_box)
if inter_box != (0, 0, 0, 0):
clip_image = compose(layer.clip_layers, bbox=layer.bbox)
mask = image.getchannel('A')
if clip_image.mode.endswith('A'):
mask = ImageChops.multiply(clip_image.getchannel('A'), mask)
clip_image.putalpha(mask)
image = _blend(image, clip_image, (0, 0))
# Apply opacity.
if layer.opacity < 255:
opacity = layer.opacity
if image.mode.endswith('A'):
opacity = opacity / 255.
channels = list(image.split())
channels[-1] = channels[-1].point(lambda x: int(x * opacity))
image = Image.merge(image.mode, channels)
else:
image.putalpha(opacity)
return image | python | def compose_layer(layer, force=False, **kwargs):
from PIL import Image, ImageChops
assert layer.bbox != (0, 0, 0, 0), 'Layer bbox is (0, 0, 0, 0)'
image = layer.topil(**kwargs)
if image is None or force:
texture = create_fill(layer)
if texture is not None:
image = texture
if image is None:
return image
# TODO: Group should have the following too.
# Apply mask.
if layer.has_mask() and not layer.mask.disabled:
mask_bbox = layer.mask.bbox
if (
(mask_bbox[2] - mask_bbox[0]) > 0 and
(mask_bbox[3] - mask_bbox[1]) > 0
):
color = layer.mask.background_color
offset = (mask_bbox[0] - layer.left, mask_bbox[1] - layer.top)
mask = Image.new('L', image.size, color=color)
mask.paste(layer.mask.topil(), offset)
if image.mode.endswith('A'):
# What should we do here? There are two alpha channels.
pass
image.putalpha(mask)
elif layer.has_vector_mask() and (force or not layer.has_pixels()):
mask = draw_vector_mask(layer)
# TODO: Stroke drawing.
texture = image
image = Image.new(image.mode, image.size, 'white')
image.paste(texture, mask=mask)
# Apply layer fill effects.
apply_effect(layer, image)
# Clip layers.
if layer.has_clip_layers():
clip_box = extract_bbox(layer.clip_layers)
inter_box = intersect(layer.bbox, clip_box)
if inter_box != (0, 0, 0, 0):
clip_image = compose(layer.clip_layers, bbox=layer.bbox)
mask = image.getchannel('A')
if clip_image.mode.endswith('A'):
mask = ImageChops.multiply(clip_image.getchannel('A'), mask)
clip_image.putalpha(mask)
image = _blend(image, clip_image, (0, 0))
# Apply opacity.
if layer.opacity < 255:
opacity = layer.opacity
if image.mode.endswith('A'):
opacity = opacity / 255.
channels = list(image.split())
channels[-1] = channels[-1].point(lambda x: int(x * opacity))
image = Image.merge(image.mode, channels)
else:
image.putalpha(opacity)
return image | [
"def",
"compose_layer",
"(",
"layer",
",",
"force",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"PIL",
"import",
"Image",
",",
"ImageChops",
"assert",
"layer",
".",
"bbox",
"!=",
"(",
"0",
",",
"0",
",",
"0",
",",
"0",
")",
",",
"'La... | Compose a single layer with pixels. | [
"Compose",
"a",
"single",
"layer",
"with",
"pixels",
"."
] | 4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/composer.py#L144-L208 |
229,711 | psd-tools/psd-tools | src/psd_tools/api/composer.py | apply_effect | def apply_effect(layer, image):
"""Apply effect to the image.
..note: Correct effect order is the following. All the effects are first
applied to the original image then blended together.
* dropshadow
* outerglow
* (original)
* patternoverlay
* gradientoverlay
* coloroverlay
* innershadow
* innerglow
* bevelemboss
* satin
* stroke
"""
for effect in layer.effects:
if effect.__class__.__name__ == 'PatternOverlay':
draw_pattern_fill(image, layer._psd, effect.value)
for effect in layer.effects:
if effect.__class__.__name__ == 'GradientOverlay':
draw_gradient_fill(image, effect.value)
for effect in layer.effects:
if effect.__class__.__name__ == 'ColorOverlay':
draw_solid_color_fill(image, effect.value) | python | def apply_effect(layer, image):
for effect in layer.effects:
if effect.__class__.__name__ == 'PatternOverlay':
draw_pattern_fill(image, layer._psd, effect.value)
for effect in layer.effects:
if effect.__class__.__name__ == 'GradientOverlay':
draw_gradient_fill(image, effect.value)
for effect in layer.effects:
if effect.__class__.__name__ == 'ColorOverlay':
draw_solid_color_fill(image, effect.value) | [
"def",
"apply_effect",
"(",
"layer",
",",
"image",
")",
":",
"for",
"effect",
"in",
"layer",
".",
"effects",
":",
"if",
"effect",
".",
"__class__",
".",
"__name__",
"==",
"'PatternOverlay'",
":",
"draw_pattern_fill",
"(",
"image",
",",
"layer",
".",
"_psd"... | Apply effect to the image.
..note: Correct effect order is the following. All the effects are first
applied to the original image then blended together.
* dropshadow
* outerglow
* (original)
* patternoverlay
* gradientoverlay
* coloroverlay
* innershadow
* innerglow
* bevelemboss
* satin
* stroke | [
"Apply",
"effect",
"to",
"the",
"image",
"."
] | 4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/composer.py#L236-L264 |
229,712 | psd-tools/psd-tools | src/psd_tools/api/composer.py | _generate_symbol | def _generate_symbol(path, width, height, command='C'):
"""Sequence generator for SVG path."""
if len(path) == 0:
return
# Initial point.
yield 'M'
yield path[0].anchor[1] * width
yield path[0].anchor[0] * height
yield command
# Closed path or open path
points = (zip(path, path[1:] + path[0:1]) if path.is_closed()
else zip(path, path[1:]))
# Rest of the points.
for p1, p2 in points:
yield p1.leaving[1] * width
yield p1.leaving[0] * height
yield p2.preceding[1] * width
yield p2.preceding[0] * height
yield p2.anchor[1] * width
yield p2.anchor[0] * height
if path.is_closed():
yield 'Z' | python | def _generate_symbol(path, width, height, command='C'):
if len(path) == 0:
return
# Initial point.
yield 'M'
yield path[0].anchor[1] * width
yield path[0].anchor[0] * height
yield command
# Closed path or open path
points = (zip(path, path[1:] + path[0:1]) if path.is_closed()
else zip(path, path[1:]))
# Rest of the points.
for p1, p2 in points:
yield p1.leaving[1] * width
yield p1.leaving[0] * height
yield p2.preceding[1] * width
yield p2.preceding[0] * height
yield p2.anchor[1] * width
yield p2.anchor[0] * height
if path.is_closed():
yield 'Z' | [
"def",
"_generate_symbol",
"(",
"path",
",",
"width",
",",
"height",
",",
"command",
"=",
"'C'",
")",
":",
"if",
"len",
"(",
"path",
")",
"==",
"0",
":",
"return",
"# Initial point.",
"yield",
"'M'",
"yield",
"path",
"[",
"0",
"]",
".",
"anchor",
"["... | Sequence generator for SVG path. | [
"Sequence",
"generator",
"for",
"SVG",
"path",
"."
] | 4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/composer.py#L307-L332 |
229,713 | psd-tools/psd-tools | src/psd_tools/api/composer.py | draw_pattern_fill | def draw_pattern_fill(image, psd, setting, blend=True):
"""
Draw pattern fill on the image.
:param image: Image to be filled.
:param psd: :py:class:`PSDImage`.
:param setting: Descriptor containing pattern fill.
:param blend: Blend the fill or ignore. Effects blend.
"""
from PIL import Image
pattern_id = setting[b'Ptrn'][b'Idnt'].value.rstrip('\x00')
pattern = psd._get_pattern(pattern_id)
if not pattern:
logger.error('Pattern not found: %s' % (pattern_id))
return None
panel = convert_pattern_to_pil(pattern, psd._record.header.version)
scale = setting.get(b'Scl ', 100) / 100.
if scale != 1.:
panel = panel.resize((
int(panel.width * scale),
int(panel.height * scale)
))
opacity = int(setting.get(b'Opct', 100) / 100. * 255)
if opacity != 255:
panel.putalpha(opacity)
pattern_image = Image.new(image.mode, image.size)
mask = image.getchannel('A') if blend else Image.new('L', image.size, 255)
for left in range(0, pattern_image.width, panel.width):
for top in range(0, pattern_image.height, panel.height):
panel_mask = mask.crop(
(left, top, left + panel.width, top + panel.height)
)
pattern_image.paste(panel, (left, top), panel_mask)
if blend:
image.paste(_blend(image, pattern_image, (0, 0)))
else:
image.paste(pattern_image) | python | def draw_pattern_fill(image, psd, setting, blend=True):
from PIL import Image
pattern_id = setting[b'Ptrn'][b'Idnt'].value.rstrip('\x00')
pattern = psd._get_pattern(pattern_id)
if not pattern:
logger.error('Pattern not found: %s' % (pattern_id))
return None
panel = convert_pattern_to_pil(pattern, psd._record.header.version)
scale = setting.get(b'Scl ', 100) / 100.
if scale != 1.:
panel = panel.resize((
int(panel.width * scale),
int(panel.height * scale)
))
opacity = int(setting.get(b'Opct', 100) / 100. * 255)
if opacity != 255:
panel.putalpha(opacity)
pattern_image = Image.new(image.mode, image.size)
mask = image.getchannel('A') if blend else Image.new('L', image.size, 255)
for left in range(0, pattern_image.width, panel.width):
for top in range(0, pattern_image.height, panel.height):
panel_mask = mask.crop(
(left, top, left + panel.width, top + panel.height)
)
pattern_image.paste(panel, (left, top), panel_mask)
if blend:
image.paste(_blend(image, pattern_image, (0, 0)))
else:
image.paste(pattern_image) | [
"def",
"draw_pattern_fill",
"(",
"image",
",",
"psd",
",",
"setting",
",",
"blend",
"=",
"True",
")",
":",
"from",
"PIL",
"import",
"Image",
"pattern_id",
"=",
"setting",
"[",
"b'Ptrn'",
"]",
"[",
"b'Idnt'",
"]",
".",
"value",
".",
"rstrip",
"(",
"'\\x... | Draw pattern fill on the image.
:param image: Image to be filled.
:param psd: :py:class:`PSDImage`.
:param setting: Descriptor containing pattern fill.
:param blend: Blend the fill or ignore. Effects blend. | [
"Draw",
"pattern",
"fill",
"on",
"the",
"image",
"."
] | 4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/composer.py#L349-L390 |
229,714 | psd-tools/psd-tools | src/psd_tools/api/composer.py | _make_linear_gradient | def _make_linear_gradient(width, height, angle=90.):
"""Generates index map for linear gradients."""
import numpy as np
X, Y = np.meshgrid(np.linspace(0, 1, width), np.linspace(0, 1, height))
theta = np.radians(angle % 360)
c, s = np.cos(theta), np.sin(theta)
if 0 <= theta and theta < 0.5 * np.pi:
Z = np.abs(c * X + s * Y)
elif 0.5 * np.pi <= theta and theta < np.pi:
Z = np.abs(c * (X - width) + s * Y)
elif np.pi <= theta and theta < 1.5 * np.pi:
Z = np.abs(c * (X - width) + s * (Y - height))
elif 1.5 * np.pi <= theta and theta < 2.0 * np.pi:
Z = np.abs(c * X + s * (Y - height))
return (Z - Z.min()) / (Z.max() - Z.min()) | python | def _make_linear_gradient(width, height, angle=90.):
import numpy as np
X, Y = np.meshgrid(np.linspace(0, 1, width), np.linspace(0, 1, height))
theta = np.radians(angle % 360)
c, s = np.cos(theta), np.sin(theta)
if 0 <= theta and theta < 0.5 * np.pi:
Z = np.abs(c * X + s * Y)
elif 0.5 * np.pi <= theta and theta < np.pi:
Z = np.abs(c * (X - width) + s * Y)
elif np.pi <= theta and theta < 1.5 * np.pi:
Z = np.abs(c * (X - width) + s * (Y - height))
elif 1.5 * np.pi <= theta and theta < 2.0 * np.pi:
Z = np.abs(c * X + s * (Y - height))
return (Z - Z.min()) / (Z.max() - Z.min()) | [
"def",
"_make_linear_gradient",
"(",
"width",
",",
"height",
",",
"angle",
"=",
"90.",
")",
":",
"import",
"numpy",
"as",
"np",
"X",
",",
"Y",
"=",
"np",
".",
"meshgrid",
"(",
"np",
".",
"linspace",
"(",
"0",
",",
"1",
",",
"width",
")",
",",
"np... | Generates index map for linear gradients. | [
"Generates",
"index",
"map",
"for",
"linear",
"gradients",
"."
] | 4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/composer.py#L417-L431 |
229,715 | psd-tools/psd-tools | src/psd_tools/api/shape.py | Stroke.line_cap_type | def line_cap_type(self):
"""Cap type, one of `butt`, `round`, `square`."""
key = self._data.get(b'strokeStyleLineCapType').enum
return self.STROKE_STYLE_LINE_CAP_TYPES.get(key, str(key)) | python | def line_cap_type(self):
key = self._data.get(b'strokeStyleLineCapType').enum
return self.STROKE_STYLE_LINE_CAP_TYPES.get(key, str(key)) | [
"def",
"line_cap_type",
"(",
"self",
")",
":",
"key",
"=",
"self",
".",
"_data",
".",
"get",
"(",
"b'strokeStyleLineCapType'",
")",
".",
"enum",
"return",
"self",
".",
"STROKE_STYLE_LINE_CAP_TYPES",
".",
"get",
"(",
"key",
",",
"str",
"(",
"key",
")",
")... | Cap type, one of `butt`, `round`, `square`. | [
"Cap",
"type",
"one",
"of",
"butt",
"round",
"square",
"."
] | 4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/shape.py#L208-L211 |
229,716 | psd-tools/psd-tools | src/psd_tools/api/shape.py | Stroke.line_join_type | def line_join_type(self):
"""Join type, one of `miter`, `round`, `bevel`."""
key = self._data.get(b'strokeStyleLineJoinType').enum
return self.STROKE_STYLE_LINE_JOIN_TYPES.get(key, str(key)) | python | def line_join_type(self):
key = self._data.get(b'strokeStyleLineJoinType').enum
return self.STROKE_STYLE_LINE_JOIN_TYPES.get(key, str(key)) | [
"def",
"line_join_type",
"(",
"self",
")",
":",
"key",
"=",
"self",
".",
"_data",
".",
"get",
"(",
"b'strokeStyleLineJoinType'",
")",
".",
"enum",
"return",
"self",
".",
"STROKE_STYLE_LINE_JOIN_TYPES",
".",
"get",
"(",
"key",
",",
"str",
"(",
"key",
")",
... | Join type, one of `miter`, `round`, `bevel`. | [
"Join",
"type",
"one",
"of",
"miter",
"round",
"bevel",
"."
] | 4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/shape.py#L214-L217 |
229,717 | psd-tools/psd-tools | src/psd_tools/api/shape.py | Stroke.line_alignment | def line_alignment(self):
"""Alignment, one of `inner`, `outer`, `center`."""
key = self._data.get(b'strokeStyleLineAlignment').enum
return self.STROKE_STYLE_LINE_ALIGNMENTS.get(key, str(key)) | python | def line_alignment(self):
key = self._data.get(b'strokeStyleLineAlignment').enum
return self.STROKE_STYLE_LINE_ALIGNMENTS.get(key, str(key)) | [
"def",
"line_alignment",
"(",
"self",
")",
":",
"key",
"=",
"self",
".",
"_data",
".",
"get",
"(",
"b'strokeStyleLineAlignment'",
")",
".",
"enum",
"return",
"self",
".",
"STROKE_STYLE_LINE_ALIGNMENTS",
".",
"get",
"(",
"key",
",",
"str",
"(",
"key",
")",
... | Alignment, one of `inner`, `outer`, `center`. | [
"Alignment",
"one",
"of",
"inner",
"outer",
"center",
"."
] | 4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/shape.py#L220-L223 |
229,718 | psd-tools/psd-tools | src/psd_tools/api/shape.py | Origination.bbox | def bbox(self):
"""
Bounding box of the live shape.
:return: :py:class:`~psd_tools.psd.descriptor.Descriptor`
"""
bbox = self._data.get(b'keyOriginShapeBBox')
if bbox:
return (
bbox.get(b'Left').value,
bbox.get(b'Top ').value,
bbox.get(b'Rght').value,
bbox.get(b'Btom').value,
)
return (0, 0, 0, 0) | python | def bbox(self):
bbox = self._data.get(b'keyOriginShapeBBox')
if bbox:
return (
bbox.get(b'Left').value,
bbox.get(b'Top ').value,
bbox.get(b'Rght').value,
bbox.get(b'Btom').value,
)
return (0, 0, 0, 0) | [
"def",
"bbox",
"(",
"self",
")",
":",
"bbox",
"=",
"self",
".",
"_data",
".",
"get",
"(",
"b'keyOriginShapeBBox'",
")",
"if",
"bbox",
":",
"return",
"(",
"bbox",
".",
"get",
"(",
"b'Left'",
")",
".",
"value",
",",
"bbox",
".",
"get",
"(",
"b'Top '"... | Bounding box of the live shape.
:return: :py:class:`~psd_tools.psd.descriptor.Descriptor` | [
"Bounding",
"box",
"of",
"the",
"live",
"shape",
"."
] | 4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/shape.py#L298-L312 |
229,719 | psd-tools/psd-tools | src/psd_tools/api/layers.py | Layer.mask | def mask(self):
"""
Returns mask associated with this layer.
:return: :py:class:`~psd_tools.api.mask.Mask` or `None`
"""
if not hasattr(self, "_mask"):
self._mask = Mask(self) if self.has_mask() else None
return self._mask | python | def mask(self):
if not hasattr(self, "_mask"):
self._mask = Mask(self) if self.has_mask() else None
return self._mask | [
"def",
"mask",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"_mask\"",
")",
":",
"self",
".",
"_mask",
"=",
"Mask",
"(",
"self",
")",
"if",
"self",
".",
"has_mask",
"(",
")",
"else",
"None",
"return",
"self",
".",
"_mask"
] | Returns mask associated with this layer.
:return: :py:class:`~psd_tools.api.mask.Mask` or `None` | [
"Returns",
"mask",
"associated",
"with",
"this",
"layer",
"."
] | 4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/layers.py#L259-L267 |
229,720 | psd-tools/psd-tools | src/psd_tools/api/layers.py | Layer.vector_mask | def vector_mask(self):
"""
Returns vector mask associated with this layer.
:return: :py:class:`~psd_tools.api.shape.VectorMask` or `None`
"""
if not hasattr(self, '_vector_mask'):
self._vector_mask = None
blocks = self.tagged_blocks
for key in ('VECTOR_MASK_SETTING1', 'VECTOR_MASK_SETTING2'):
if key in blocks:
self._vector_mask = VectorMask(blocks.get_data(key))
return self._vector_mask | python | def vector_mask(self):
if not hasattr(self, '_vector_mask'):
self._vector_mask = None
blocks = self.tagged_blocks
for key in ('VECTOR_MASK_SETTING1', 'VECTOR_MASK_SETTING2'):
if key in blocks:
self._vector_mask = VectorMask(blocks.get_data(key))
return self._vector_mask | [
"def",
"vector_mask",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_vector_mask'",
")",
":",
"self",
".",
"_vector_mask",
"=",
"None",
"blocks",
"=",
"self",
".",
"tagged_blocks",
"for",
"key",
"in",
"(",
"'VECTOR_MASK_SETTING1'",
","... | Returns vector mask associated with this layer.
:return: :py:class:`~psd_tools.api.shape.VectorMask` or `None` | [
"Returns",
"vector",
"mask",
"associated",
"with",
"this",
"layer",
"."
] | 4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/layers.py#L281-L293 |
229,721 | psd-tools/psd-tools | src/psd_tools/api/layers.py | Layer.origination | def origination(self):
"""
Property for a list of live shapes or a line.
Some of the vector masks have associated live shape properties, that
are Photoshop feature to handle primitive shapes such as a rectangle,
an ellipse, or a line. Vector masks without live shape properties are
plain path objects.
See :py:mod:`psd_tools.api.shape`.
:return: List of :py:class:`~psd_tools.api.shape.Invalidated`,
:py:class:`~psd_tools.api.shape.Rectangle`,
:py:class:`~psd_tools.api.shape.RoundedRectangle`,
:py:class:`~psd_tools.api.shape.Ellipse`, or
:py:class:`~psd_tools.api.shape.Line`.
"""
if not hasattr(self, '_origination'):
data = self.tagged_blocks.get_data('VECTOR_ORIGINATION_DATA', {})
self._origination = [
Origination.create(x) for x
in data.get(b'keyDescriptorList', [])
if not data.get(b'keyShapeInvalidated')
]
return self._origination | python | def origination(self):
if not hasattr(self, '_origination'):
data = self.tagged_blocks.get_data('VECTOR_ORIGINATION_DATA', {})
self._origination = [
Origination.create(x) for x
in data.get(b'keyDescriptorList', [])
if not data.get(b'keyShapeInvalidated')
]
return self._origination | [
"def",
"origination",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_origination'",
")",
":",
"data",
"=",
"self",
".",
"tagged_blocks",
".",
"get_data",
"(",
"'VECTOR_ORIGINATION_DATA'",
",",
"{",
"}",
")",
"self",
".",
"_origination"... | Property for a list of live shapes or a line.
Some of the vector masks have associated live shape properties, that
are Photoshop feature to handle primitive shapes such as a rectangle,
an ellipse, or a line. Vector masks without live shape properties are
plain path objects.
See :py:mod:`psd_tools.api.shape`.
:return: List of :py:class:`~psd_tools.api.shape.Invalidated`,
:py:class:`~psd_tools.api.shape.Rectangle`,
:py:class:`~psd_tools.api.shape.RoundedRectangle`,
:py:class:`~psd_tools.api.shape.Ellipse`, or
:py:class:`~psd_tools.api.shape.Line`. | [
"Property",
"for",
"a",
"list",
"of",
"live",
"shapes",
"or",
"a",
"line",
"."
] | 4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/layers.py#L306-L330 |
229,722 | psd-tools/psd-tools | src/psd_tools/api/layers.py | Layer.effects | def effects(self):
"""
Layer effects.
:return: :py:class:`~psd_tools.api.effects.Effects`
"""
if not hasattr(self, '_effects'):
self._effects = Effects(self)
return self._effects | python | def effects(self):
if not hasattr(self, '_effects'):
self._effects = Effects(self)
return self._effects | [
"def",
"effects",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_effects'",
")",
":",
"self",
".",
"_effects",
"=",
"Effects",
"(",
"self",
")",
"return",
"self",
".",
"_effects"
] | Layer effects.
:return: :py:class:`~psd_tools.api.effects.Effects` | [
"Layer",
"effects",
"."
] | 4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/layers.py#L388-L396 |
229,723 | psd-tools/psd-tools | src/psd_tools/api/layers.py | GroupMixin.descendants | def descendants(self, include_clip=True):
"""
Return a generator to iterate over all descendant layers.
Example::
# Iterate over all layers
for layer in psd.descendants():
print(layer)
# Iterate over all layers in reverse order
for layer in reversed(list(psd.descendants())):
print(layer)
:param include_clip: include clipping layers.
"""
for layer in self:
yield layer
if layer.is_group():
for child in layer.descendants(include_clip):
yield child
if include_clip and hasattr(layer, 'clip_layers'):
for clip_layer in layer.clip_layers:
yield clip_layer | python | def descendants(self, include_clip=True):
for layer in self:
yield layer
if layer.is_group():
for child in layer.descendants(include_clip):
yield child
if include_clip and hasattr(layer, 'clip_layers'):
for clip_layer in layer.clip_layers:
yield clip_layer | [
"def",
"descendants",
"(",
"self",
",",
"include_clip",
"=",
"True",
")",
":",
"for",
"layer",
"in",
"self",
":",
"yield",
"layer",
"if",
"layer",
".",
"is_group",
"(",
")",
":",
"for",
"child",
"in",
"layer",
".",
"descendants",
"(",
"include_clip",
"... | Return a generator to iterate over all descendant layers.
Example::
# Iterate over all layers
for layer in psd.descendants():
print(layer)
# Iterate over all layers in reverse order
for layer in reversed(list(psd.descendants())):
print(layer)
:param include_clip: include clipping layers. | [
"Return",
"a",
"generator",
"to",
"iterate",
"over",
"all",
"descendant",
"layers",
"."
] | 4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/layers.py#L494-L517 |
229,724 | psd-tools/psd-tools | src/psd_tools/api/layers.py | Artboard.compose | def compose(self, bbox=None, **kwargs):
"""
Compose the artboard.
See :py:func:`~psd_tools.compose` for available extra arguments.
:param bbox: Viewport tuple (left, top, right, bottom).
:return: :py:class:`PIL.Image`, or `None` if there is no pixel.
"""
from psd_tools.api.composer import compose
return compose(self, bbox=bbox or self.bbox, **kwargs) | python | def compose(self, bbox=None, **kwargs):
from psd_tools.api.composer import compose
return compose(self, bbox=bbox or self.bbox, **kwargs) | [
"def",
"compose",
"(",
"self",
",",
"bbox",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"psd_tools",
".",
"api",
".",
"composer",
"import",
"compose",
"return",
"compose",
"(",
"self",
",",
"bbox",
"=",
"bbox",
"or",
"self",
".",
"bbox",
... | Compose the artboard.
See :py:func:`~psd_tools.compose` for available extra arguments.
:param bbox: Viewport tuple (left, top, right, bottom).
:return: :py:class:`PIL.Image`, or `None` if there is no pixel. | [
"Compose",
"the",
"artboard",
"."
] | 4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/layers.py#L591-L601 |
229,725 | psd-tools/psd-tools | src/psd_tools/api/layers.py | SmartObjectLayer.smart_object | def smart_object(self):
"""
Associated smart object.
:return: :py:class:`~psd_tools.api.smart_object.SmartObject`.
"""
if not hasattr(self, '_smart_object'):
self._smart_object = SmartObject(self)
return self._smart_object | python | def smart_object(self):
if not hasattr(self, '_smart_object'):
self._smart_object = SmartObject(self)
return self._smart_object | [
"def",
"smart_object",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_smart_object'",
")",
":",
"self",
".",
"_smart_object",
"=",
"SmartObject",
"(",
"self",
")",
"return",
"self",
".",
"_smart_object"
] | Associated smart object.
:return: :py:class:`~psd_tools.api.smart_object.SmartObject`. | [
"Associated",
"smart",
"object",
"."
] | 4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/layers.py#L635-L643 |
229,726 | psd-tools/psd-tools | src/psd_tools/api/layers.py | ShapeLayer.stroke | def stroke(self):
"""Property for strokes."""
if not hasattr(self, '_stroke'):
self._stroke = None
stroke = self.tagged_blocks.get_data('VECTOR_STROKE_DATA')
if stroke:
self._stroke = Stroke(stroke)
return self._stroke | python | def stroke(self):
if not hasattr(self, '_stroke'):
self._stroke = None
stroke = self.tagged_blocks.get_data('VECTOR_STROKE_DATA')
if stroke:
self._stroke = Stroke(stroke)
return self._stroke | [
"def",
"stroke",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_stroke'",
")",
":",
"self",
".",
"_stroke",
"=",
"None",
"stroke",
"=",
"self",
".",
"tagged_blocks",
".",
"get_data",
"(",
"'VECTOR_STROKE_DATA'",
")",
"if",
"stroke",
... | Property for strokes. | [
"Property",
"for",
"strokes",
"."
] | 4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/layers.py#L828-L835 |
229,727 | psd-tools/psd-tools | src/psd_tools/utils.py | read_fmt | def read_fmt(fmt, fp):
"""
Reads data from ``fp`` according to ``fmt``.
"""
fmt = str(">" + fmt)
fmt_size = struct.calcsize(fmt)
data = fp.read(fmt_size)
assert len(data) == fmt_size, 'read=%d, expected=%d' % (
len(data), fmt_size
)
return struct.unpack(fmt, data) | python | def read_fmt(fmt, fp):
fmt = str(">" + fmt)
fmt_size = struct.calcsize(fmt)
data = fp.read(fmt_size)
assert len(data) == fmt_size, 'read=%d, expected=%d' % (
len(data), fmt_size
)
return struct.unpack(fmt, data) | [
"def",
"read_fmt",
"(",
"fmt",
",",
"fp",
")",
":",
"fmt",
"=",
"str",
"(",
"\">\"",
"+",
"fmt",
")",
"fmt_size",
"=",
"struct",
".",
"calcsize",
"(",
"fmt",
")",
"data",
"=",
"fp",
".",
"read",
"(",
"fmt_size",
")",
"assert",
"len",
"(",
"data",... | Reads data from ``fp`` according to ``fmt``. | [
"Reads",
"data",
"from",
"fp",
"according",
"to",
"fmt",
"."
] | 4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/utils.py#L28-L38 |
229,728 | psd-tools/psd-tools | src/psd_tools/utils.py | write_fmt | def write_fmt(fp, fmt, *args):
"""
Writes data to ``fp`` according to ``fmt``.
"""
fmt = str(">" + fmt)
fmt_size = struct.calcsize(fmt)
written = write_bytes(fp, struct.pack(fmt, *args))
assert written == fmt_size, 'written=%d, expected=%d' % (
written, fmt_size
)
return written | python | def write_fmt(fp, fmt, *args):
fmt = str(">" + fmt)
fmt_size = struct.calcsize(fmt)
written = write_bytes(fp, struct.pack(fmt, *args))
assert written == fmt_size, 'written=%d, expected=%d' % (
written, fmt_size
)
return written | [
"def",
"write_fmt",
"(",
"fp",
",",
"fmt",
",",
"*",
"args",
")",
":",
"fmt",
"=",
"str",
"(",
"\">\"",
"+",
"fmt",
")",
"fmt_size",
"=",
"struct",
".",
"calcsize",
"(",
"fmt",
")",
"written",
"=",
"write_bytes",
"(",
"fp",
",",
"struct",
".",
"p... | Writes data to ``fp`` according to ``fmt``. | [
"Writes",
"data",
"to",
"fp",
"according",
"to",
"fmt",
"."
] | 4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/utils.py#L41-L51 |
229,729 | psd-tools/psd-tools | src/psd_tools/utils.py | write_bytes | def write_bytes(fp, data):
"""
Write bytes to the file object and returns bytes written.
:return: written byte size
"""
pos = fp.tell()
fp.write(data)
written = fp.tell() - pos
assert written == len(data), 'written=%d, expected=%d' % (
written, len(data)
)
return written | python | def write_bytes(fp, data):
pos = fp.tell()
fp.write(data)
written = fp.tell() - pos
assert written == len(data), 'written=%d, expected=%d' % (
written, len(data)
)
return written | [
"def",
"write_bytes",
"(",
"fp",
",",
"data",
")",
":",
"pos",
"=",
"fp",
".",
"tell",
"(",
")",
"fp",
".",
"write",
"(",
"data",
")",
"written",
"=",
"fp",
".",
"tell",
"(",
")",
"-",
"pos",
"assert",
"written",
"==",
"len",
"(",
"data",
")",
... | Write bytes to the file object and returns bytes written.
:return: written byte size | [
"Write",
"bytes",
"to",
"the",
"file",
"object",
"and",
"returns",
"bytes",
"written",
"."
] | 4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/utils.py#L54-L66 |
229,730 | psd-tools/psd-tools | src/psd_tools/utils.py | read_length_block | def read_length_block(fp, fmt='I', padding=1):
"""
Read a block of data with a length marker at the beginning.
:param fp: file-like
:param fmt: format of the length marker
:return: bytes object
"""
length = read_fmt(fmt, fp)[0]
data = fp.read(length)
assert len(data) == length, (len(data), length)
read_padding(fp, length, padding)
return data | python | def read_length_block(fp, fmt='I', padding=1):
length = read_fmt(fmt, fp)[0]
data = fp.read(length)
assert len(data) == length, (len(data), length)
read_padding(fp, length, padding)
return data | [
"def",
"read_length_block",
"(",
"fp",
",",
"fmt",
"=",
"'I'",
",",
"padding",
"=",
"1",
")",
":",
"length",
"=",
"read_fmt",
"(",
"fmt",
",",
"fp",
")",
"[",
"0",
"]",
"data",
"=",
"fp",
".",
"read",
"(",
"length",
")",
"assert",
"len",
"(",
"... | Read a block of data with a length marker at the beginning.
:param fp: file-like
:param fmt: format of the length marker
:return: bytes object | [
"Read",
"a",
"block",
"of",
"data",
"with",
"a",
"length",
"marker",
"at",
"the",
"beginning",
"."
] | 4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/utils.py#L69-L81 |
229,731 | psd-tools/psd-tools | src/psd_tools/utils.py | write_length_block | def write_length_block(fp, writer, fmt='I', padding=1, **kwargs):
"""
Writes a block of data with a length marker at the beginning.
Example::
with io.BytesIO() as fp:
write_length_block(fp, lambda f: f.write(b'\x00\x00'))
:param fp: file-like
:param writer: function object that takes file-like object as an argument
:param fmt: format of the length marker
:param padding: divisor for padding not included in length marker
:return: written byte size
"""
length_position = reserve_position(fp, fmt)
written = writer(fp, **kwargs)
written += write_position(fp, length_position, written, fmt)
written += write_padding(fp, written, padding)
return written | python | def write_length_block(fp, writer, fmt='I', padding=1, **kwargs):
length_position = reserve_position(fp, fmt)
written = writer(fp, **kwargs)
written += write_position(fp, length_position, written, fmt)
written += write_padding(fp, written, padding)
return written | [
"def",
"write_length_block",
"(",
"fp",
",",
"writer",
",",
"fmt",
"=",
"'I'",
",",
"padding",
"=",
"1",
",",
"*",
"*",
"kwargs",
")",
":",
"length_position",
"=",
"reserve_position",
"(",
"fp",
",",
"fmt",
")",
"written",
"=",
"writer",
"(",
"fp",
"... | Writes a block of data with a length marker at the beginning.
Example::
with io.BytesIO() as fp:
write_length_block(fp, lambda f: f.write(b'\x00\x00'))
:param fp: file-like
:param writer: function object that takes file-like object as an argument
:param fmt: format of the length marker
:param padding: divisor for padding not included in length marker
:return: written byte size | [
"Writes",
"a",
"block",
"of",
"data",
"with",
"a",
"length",
"marker",
"at",
"the",
"beginning",
"."
] | 4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/utils.py#L84-L103 |
229,732 | psd-tools/psd-tools | src/psd_tools/utils.py | reserve_position | def reserve_position(fp, fmt='I'):
"""
Reserves the current position for write.
Use with `write_position`.
:param fp: file-like object
:param fmt: format of the reserved position
:return: the position
"""
position = fp.tell()
fp.seek(struct.calcsize(str('>' + fmt)), 1)
return position | python | def reserve_position(fp, fmt='I'):
position = fp.tell()
fp.seek(struct.calcsize(str('>' + fmt)), 1)
return position | [
"def",
"reserve_position",
"(",
"fp",
",",
"fmt",
"=",
"'I'",
")",
":",
"position",
"=",
"fp",
".",
"tell",
"(",
")",
"fp",
".",
"seek",
"(",
"struct",
".",
"calcsize",
"(",
"str",
"(",
"'>'",
"+",
"fmt",
")",
")",
",",
"1",
")",
"return",
"pos... | Reserves the current position for write.
Use with `write_position`.
:param fp: file-like object
:param fmt: format of the reserved position
:return: the position | [
"Reserves",
"the",
"current",
"position",
"for",
"write",
"."
] | 4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/utils.py#L106-L118 |
229,733 | psd-tools/psd-tools | src/psd_tools/utils.py | write_position | def write_position(fp, position, value, fmt='I'):
"""
Writes a value to the specified position.
:param fp: file-like object
:param position: position of the value marker
:param value: value to write
:param fmt: format of the value
:return: written byte size
"""
current_position = fp.tell()
fp.seek(position)
written = write_bytes(fp, struct.pack(str('>' + fmt), value))
fp.seek(current_position)
return written | python | def write_position(fp, position, value, fmt='I'):
current_position = fp.tell()
fp.seek(position)
written = write_bytes(fp, struct.pack(str('>' + fmt), value))
fp.seek(current_position)
return written | [
"def",
"write_position",
"(",
"fp",
",",
"position",
",",
"value",
",",
"fmt",
"=",
"'I'",
")",
":",
"current_position",
"=",
"fp",
".",
"tell",
"(",
")",
"fp",
".",
"seek",
"(",
"position",
")",
"written",
"=",
"write_bytes",
"(",
"fp",
",",
"struct... | Writes a value to the specified position.
:param fp: file-like object
:param position: position of the value marker
:param value: value to write
:param fmt: format of the value
:return: written byte size | [
"Writes",
"a",
"value",
"to",
"the",
"specified",
"position",
"."
] | 4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/utils.py#L121-L135 |
229,734 | psd-tools/psd-tools | src/psd_tools/utils.py | read_padding | def read_padding(fp, size, divisor=2):
"""
Read padding bytes for the given byte size.
:param fp: file-like object
:param divisor: divisor of the byte alignment
:return: read byte size
"""
remainder = size % divisor
if remainder:
return fp.read(divisor - remainder)
return b'' | python | def read_padding(fp, size, divisor=2):
remainder = size % divisor
if remainder:
return fp.read(divisor - remainder)
return b'' | [
"def",
"read_padding",
"(",
"fp",
",",
"size",
",",
"divisor",
"=",
"2",
")",
":",
"remainder",
"=",
"size",
"%",
"divisor",
"if",
"remainder",
":",
"return",
"fp",
".",
"read",
"(",
"divisor",
"-",
"remainder",
")",
"return",
"b''"
] | Read padding bytes for the given byte size.
:param fp: file-like object
:param divisor: divisor of the byte alignment
:return: read byte size | [
"Read",
"padding",
"bytes",
"for",
"the",
"given",
"byte",
"size",
"."
] | 4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/utils.py#L138-L149 |
229,735 | psd-tools/psd-tools | src/psd_tools/utils.py | write_padding | def write_padding(fp, size, divisor=2):
"""
Writes padding bytes given the currently written size.
:param fp: file-like object
:param divisor: divisor of the byte alignment
:return: written byte size
"""
remainder = size % divisor
if remainder:
return write_bytes(fp, struct.pack('%dx' % (divisor - remainder)))
return 0 | python | def write_padding(fp, size, divisor=2):
remainder = size % divisor
if remainder:
return write_bytes(fp, struct.pack('%dx' % (divisor - remainder)))
return 0 | [
"def",
"write_padding",
"(",
"fp",
",",
"size",
",",
"divisor",
"=",
"2",
")",
":",
"remainder",
"=",
"size",
"%",
"divisor",
"if",
"remainder",
":",
"return",
"write_bytes",
"(",
"fp",
",",
"struct",
".",
"pack",
"(",
"'%dx'",
"%",
"(",
"divisor",
"... | Writes padding bytes given the currently written size.
:param fp: file-like object
:param divisor: divisor of the byte alignment
:return: written byte size | [
"Writes",
"padding",
"bytes",
"given",
"the",
"currently",
"written",
"size",
"."
] | 4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/utils.py#L152-L163 |
229,736 | psd-tools/psd-tools | src/psd_tools/utils.py | is_readable | def is_readable(fp, size=1):
"""
Check if the file-like object is readable.
:param fp: file-like object
:param size: byte size
:return: bool
"""
read_size = len(fp.read(size))
fp.seek(-read_size, 1)
return read_size == size | python | def is_readable(fp, size=1):
read_size = len(fp.read(size))
fp.seek(-read_size, 1)
return read_size == size | [
"def",
"is_readable",
"(",
"fp",
",",
"size",
"=",
"1",
")",
":",
"read_size",
"=",
"len",
"(",
"fp",
".",
"read",
"(",
"size",
")",
")",
"fp",
".",
"seek",
"(",
"-",
"read_size",
",",
"1",
")",
"return",
"read_size",
"==",
"size"
] | Check if the file-like object is readable.
:param fp: file-like object
:param size: byte size
:return: bool | [
"Check",
"if",
"the",
"file",
"-",
"like",
"object",
"is",
"readable",
"."
] | 4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/utils.py#L166-L176 |
229,737 | psd-tools/psd-tools | src/psd_tools/utils.py | read_be_array | def read_be_array(fmt, count, fp):
"""
Reads an array from a file with big-endian data.
"""
arr = array.array(str(fmt))
if hasattr(arr, 'frombytes'):
arr.frombytes(fp.read(count * arr.itemsize))
else:
arr.fromstring(fp.read(count * arr.itemsize))
return fix_byteorder(arr) | python | def read_be_array(fmt, count, fp):
arr = array.array(str(fmt))
if hasattr(arr, 'frombytes'):
arr.frombytes(fp.read(count * arr.itemsize))
else:
arr.fromstring(fp.read(count * arr.itemsize))
return fix_byteorder(arr) | [
"def",
"read_be_array",
"(",
"fmt",
",",
"count",
",",
"fp",
")",
":",
"arr",
"=",
"array",
".",
"array",
"(",
"str",
"(",
"fmt",
")",
")",
"if",
"hasattr",
"(",
"arr",
",",
"'frombytes'",
")",
":",
"arr",
".",
"frombytes",
"(",
"fp",
".",
"read"... | Reads an array from a file with big-endian data. | [
"Reads",
"an",
"array",
"from",
"a",
"file",
"with",
"big",
"-",
"endian",
"data",
"."
] | 4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/utils.py#L226-L235 |
229,738 | psd-tools/psd-tools | src/psd_tools/utils.py | be_array_from_bytes | def be_array_from_bytes(fmt, data):
"""
Reads an array from bytestring with big-endian data.
"""
arr = array.array(str(fmt), data)
return fix_byteorder(arr) | python | def be_array_from_bytes(fmt, data):
arr = array.array(str(fmt), data)
return fix_byteorder(arr) | [
"def",
"be_array_from_bytes",
"(",
"fmt",
",",
"data",
")",
":",
"arr",
"=",
"array",
".",
"array",
"(",
"str",
"(",
"fmt",
")",
",",
"data",
")",
"return",
"fix_byteorder",
"(",
"arr",
")"
] | Reads an array from bytestring with big-endian data. | [
"Reads",
"an",
"array",
"from",
"bytestring",
"with",
"big",
"-",
"endian",
"data",
"."
] | 4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/utils.py#L255-L260 |
229,739 | psd-tools/psd-tools | src/psd_tools/utils.py | be_array_to_bytes | def be_array_to_bytes(arr):
"""
Writes an array to bytestring with big-endian data.
"""
data = fix_byteorder(arr)
if hasattr(arr, 'tobytes'):
return data.tobytes()
else:
return data.tostring() | python | def be_array_to_bytes(arr):
data = fix_byteorder(arr)
if hasattr(arr, 'tobytes'):
return data.tobytes()
else:
return data.tostring() | [
"def",
"be_array_to_bytes",
"(",
"arr",
")",
":",
"data",
"=",
"fix_byteorder",
"(",
"arr",
")",
"if",
"hasattr",
"(",
"arr",
",",
"'tobytes'",
")",
":",
"return",
"data",
".",
"tobytes",
"(",
")",
"else",
":",
"return",
"data",
".",
"tostring",
"(",
... | Writes an array to bytestring with big-endian data. | [
"Writes",
"an",
"array",
"to",
"bytestring",
"with",
"big",
"-",
"endian",
"data",
"."
] | 4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/utils.py#L263-L271 |
229,740 | psd-tools/psd-tools | src/psd_tools/utils.py | new_registry | def new_registry(attribute=None):
"""
Returns an empty dict and a @register decorator.
"""
registry = {}
def register(key):
def decorator(func):
registry[key] = func
if attribute:
setattr(func, attribute, key)
return func
return decorator
return registry, register | python | def new_registry(attribute=None):
registry = {}
def register(key):
def decorator(func):
registry[key] = func
if attribute:
setattr(func, attribute, key)
return func
return decorator
return registry, register | [
"def",
"new_registry",
"(",
"attribute",
"=",
"None",
")",
":",
"registry",
"=",
"{",
"}",
"def",
"register",
"(",
"key",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"registry",
"[",
"key",
"]",
"=",
"func",
"if",
"attribute",
":",
"setattr"... | Returns an empty dict and a @register decorator. | [
"Returns",
"an",
"empty",
"dict",
"and",
"a"
] | 4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/utils.py#L293-L307 |
229,741 | google/neuroglancer | python/neuroglancer/server.py | stop | def stop():
"""Stop the server, invalidating any viewer URLs.
This allows any previously-referenced data arrays to be garbage collected if there are no other
references to them.
"""
global global_server
if global_server is not None:
ioloop = global_server.ioloop
def stop_ioloop():
ioloop.stop()
ioloop.close()
global_server.ioloop.add_callback(stop_ioloop)
global_server = None | python | def stop():
global global_server
if global_server is not None:
ioloop = global_server.ioloop
def stop_ioloop():
ioloop.stop()
ioloop.close()
global_server.ioloop.add_callback(stop_ioloop)
global_server = None | [
"def",
"stop",
"(",
")",
":",
"global",
"global_server",
"if",
"global_server",
"is",
"not",
"None",
":",
"ioloop",
"=",
"global_server",
".",
"ioloop",
"def",
"stop_ioloop",
"(",
")",
":",
"ioloop",
".",
"stop",
"(",
")",
"ioloop",
".",
"close",
"(",
... | Stop the server, invalidating any viewer URLs.
This allows any previously-referenced data arrays to be garbage collected if there are no other
references to them. | [
"Stop",
"the",
"server",
"invalidating",
"any",
"viewer",
"URLs",
"."
] | 9efd12741013f464286f0bf3fa0b667f75a66658 | https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/server.py#L245-L258 |
229,742 | google/neuroglancer | python/neuroglancer/server.py | defer_callback | def defer_callback(callback, *args, **kwargs):
"""Register `callback` to run in the server event loop thread."""
start()
global_server.ioloop.add_callback(lambda: callback(*args, **kwargs)) | python | def defer_callback(callback, *args, **kwargs):
start()
global_server.ioloop.add_callback(lambda: callback(*args, **kwargs)) | [
"def",
"defer_callback",
"(",
"callback",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"start",
"(",
")",
"global_server",
".",
"ioloop",
".",
"add_callback",
"(",
"lambda",
":",
"callback",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"... | Register `callback` to run in the server event loop thread. | [
"Register",
"callback",
"to",
"run",
"in",
"the",
"server",
"event",
"loop",
"thread",
"."
] | 9efd12741013f464286f0bf3fa0b667f75a66658 | https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/server.py#L280-L283 |
229,743 | google/neuroglancer | python/neuroglancer/downsample_scales.py | compute_near_isotropic_downsampling_scales | def compute_near_isotropic_downsampling_scales(size,
voxel_size,
dimensions_to_downsample,
max_scales=DEFAULT_MAX_DOWNSAMPLING_SCALES,
max_downsampling=DEFAULT_MAX_DOWNSAMPLING,
max_downsampled_size=DEFAULT_MAX_DOWNSAMPLED_SIZE):
"""Compute a list of successive downsampling factors."""
num_dims = len(voxel_size)
cur_scale = np.ones((num_dims, ), dtype=int)
scales = [tuple(cur_scale)]
while (len(scales) < max_scales and (np.prod(cur_scale) < max_downsampling) and
(size / cur_scale).max() > max_downsampled_size):
# Find dimension with smallest voxelsize.
cur_voxel_size = cur_scale * voxel_size
smallest_cur_voxel_size_dim = dimensions_to_downsample[np.argmin(cur_voxel_size[
dimensions_to_downsample])]
cur_scale[smallest_cur_voxel_size_dim] *= 2
target_voxel_size = cur_voxel_size[smallest_cur_voxel_size_dim] * 2
for d in dimensions_to_downsample:
if d == smallest_cur_voxel_size_dim:
continue
d_voxel_size = cur_voxel_size[d]
if abs(d_voxel_size - target_voxel_size) > abs(d_voxel_size * 2 - target_voxel_size):
cur_scale[d] *= 2
scales.append(tuple(cur_scale))
return scales | python | def compute_near_isotropic_downsampling_scales(size,
voxel_size,
dimensions_to_downsample,
max_scales=DEFAULT_MAX_DOWNSAMPLING_SCALES,
max_downsampling=DEFAULT_MAX_DOWNSAMPLING,
max_downsampled_size=DEFAULT_MAX_DOWNSAMPLED_SIZE):
num_dims = len(voxel_size)
cur_scale = np.ones((num_dims, ), dtype=int)
scales = [tuple(cur_scale)]
while (len(scales) < max_scales and (np.prod(cur_scale) < max_downsampling) and
(size / cur_scale).max() > max_downsampled_size):
# Find dimension with smallest voxelsize.
cur_voxel_size = cur_scale * voxel_size
smallest_cur_voxel_size_dim = dimensions_to_downsample[np.argmin(cur_voxel_size[
dimensions_to_downsample])]
cur_scale[smallest_cur_voxel_size_dim] *= 2
target_voxel_size = cur_voxel_size[smallest_cur_voxel_size_dim] * 2
for d in dimensions_to_downsample:
if d == smallest_cur_voxel_size_dim:
continue
d_voxel_size = cur_voxel_size[d]
if abs(d_voxel_size - target_voxel_size) > abs(d_voxel_size * 2 - target_voxel_size):
cur_scale[d] *= 2
scales.append(tuple(cur_scale))
return scales | [
"def",
"compute_near_isotropic_downsampling_scales",
"(",
"size",
",",
"voxel_size",
",",
"dimensions_to_downsample",
",",
"max_scales",
"=",
"DEFAULT_MAX_DOWNSAMPLING_SCALES",
",",
"max_downsampling",
"=",
"DEFAULT_MAX_DOWNSAMPLING",
",",
"max_downsampled_size",
"=",
"DEFAULT_... | Compute a list of successive downsampling factors. | [
"Compute",
"a",
"list",
"of",
"successive",
"downsampling",
"factors",
"."
] | 9efd12741013f464286f0bf3fa0b667f75a66658 | https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/downsample_scales.py#L24-L50 |
229,744 | google/neuroglancer | python/neuroglancer/downsample_scales.py | compute_two_dimensional_near_isotropic_downsampling_scales | def compute_two_dimensional_near_isotropic_downsampling_scales(
size,
voxel_size,
max_scales=float('inf'),
max_downsampling=DEFAULT_MAX_DOWNSAMPLING,
max_downsampled_size=DEFAULT_MAX_DOWNSAMPLED_SIZE):
"""Compute a list of successive downsampling factors for 2-d tiles."""
max_scales = min(max_scales, 10)
# First compute a set of 2-d downsamplings for XY, XZ, and YZ with a high
# number of max_scales, and ignoring other criteria.
scales_transpose = [
compute_near_isotropic_downsampling_scales(
size=size,
voxel_size=voxel_size,
dimensions_to_downsample=dimensions_to_downsample,
max_scales=max_scales,
max_downsampling=float('inf'),
max_downsampled_size=0, ) for dimensions_to_downsample in [[0, 1], [0, 2], [1, 2]]
]
# Truncate all list of scales to the same length, once the stopping criteria
# is reached for all values of dimensions_to_downsample.
scales = [((1, ) * 3, ) * 3]
size = np.array(size)
def scale_satisfies_criteria(scale):
return np.prod(scale) < max_downsampling and (size / scale).max() > max_downsampled_size
for i in range(1, max_scales):
cur_scales = tuple(scales_transpose[d][i] for d in range(3))
if all(not scale_satisfies_criteria(scale) for scale in cur_scales):
break
scales.append(cur_scales)
return scales | python | def compute_two_dimensional_near_isotropic_downsampling_scales(
size,
voxel_size,
max_scales=float('inf'),
max_downsampling=DEFAULT_MAX_DOWNSAMPLING,
max_downsampled_size=DEFAULT_MAX_DOWNSAMPLED_SIZE):
max_scales = min(max_scales, 10)
# First compute a set of 2-d downsamplings for XY, XZ, and YZ with a high
# number of max_scales, and ignoring other criteria.
scales_transpose = [
compute_near_isotropic_downsampling_scales(
size=size,
voxel_size=voxel_size,
dimensions_to_downsample=dimensions_to_downsample,
max_scales=max_scales,
max_downsampling=float('inf'),
max_downsampled_size=0, ) for dimensions_to_downsample in [[0, 1], [0, 2], [1, 2]]
]
# Truncate all list of scales to the same length, once the stopping criteria
# is reached for all values of dimensions_to_downsample.
scales = [((1, ) * 3, ) * 3]
size = np.array(size)
def scale_satisfies_criteria(scale):
return np.prod(scale) < max_downsampling and (size / scale).max() > max_downsampled_size
for i in range(1, max_scales):
cur_scales = tuple(scales_transpose[d][i] for d in range(3))
if all(not scale_satisfies_criteria(scale) for scale in cur_scales):
break
scales.append(cur_scales)
return scales | [
"def",
"compute_two_dimensional_near_isotropic_downsampling_scales",
"(",
"size",
",",
"voxel_size",
",",
"max_scales",
"=",
"float",
"(",
"'inf'",
")",
",",
"max_downsampling",
"=",
"DEFAULT_MAX_DOWNSAMPLING",
",",
"max_downsampled_size",
"=",
"DEFAULT_MAX_DOWNSAMPLED_SIZE",... | Compute a list of successive downsampling factors for 2-d tiles. | [
"Compute",
"a",
"list",
"of",
"successive",
"downsampling",
"factors",
"for",
"2",
"-",
"d",
"tiles",
"."
] | 9efd12741013f464286f0bf3fa0b667f75a66658 | https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/downsample_scales.py#L53-L88 |
229,745 | google/neuroglancer | python/neuroglancer/json_utils.py | json_encoder_default | def json_encoder_default(obj):
"""JSON encoder function that handles some numpy types."""
if isinstance(obj, numbers.Integral) and (obj < min_safe_integer or obj > max_safe_integer):
return str(obj)
if isinstance(obj, np.integer):
return str(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, np.ndarray):
return list(obj)
elif isinstance(obj, (set, frozenset)):
return list(obj)
raise TypeError | python | def json_encoder_default(obj):
if isinstance(obj, numbers.Integral) and (obj < min_safe_integer or obj > max_safe_integer):
return str(obj)
if isinstance(obj, np.integer):
return str(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, np.ndarray):
return list(obj)
elif isinstance(obj, (set, frozenset)):
return list(obj)
raise TypeError | [
"def",
"json_encoder_default",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"numbers",
".",
"Integral",
")",
"and",
"(",
"obj",
"<",
"min_safe_integer",
"or",
"obj",
">",
"max_safe_integer",
")",
":",
"return",
"str",
"(",
"obj",
")",
"if",... | JSON encoder function that handles some numpy types. | [
"JSON",
"encoder",
"function",
"that",
"handles",
"some",
"numpy",
"types",
"."
] | 9efd12741013f464286f0bf3fa0b667f75a66658 | https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/json_utils.py#L28-L40 |
229,746 | google/neuroglancer | python/neuroglancer/sockjs_handler.py | StateHandler._on_state_changed | def _on_state_changed(self):
"""Invoked when the viewer state changes."""
raw_state, generation = self.state.raw_state_and_generation
if generation != self._last_generation:
self._last_generation = generation
self._send_update(raw_state, generation) | python | def _on_state_changed(self):
raw_state, generation = self.state.raw_state_and_generation
if generation != self._last_generation:
self._last_generation = generation
self._send_update(raw_state, generation) | [
"def",
"_on_state_changed",
"(",
"self",
")",
":",
"raw_state",
",",
"generation",
"=",
"self",
".",
"state",
".",
"raw_state_and_generation",
"if",
"generation",
"!=",
"self",
".",
"_last_generation",
":",
"self",
".",
"_last_generation",
"=",
"generation",
"se... | Invoked when the viewer state changes. | [
"Invoked",
"when",
"the",
"viewer",
"state",
"changes",
"."
] | 9efd12741013f464286f0bf3fa0b667f75a66658 | https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/sockjs_handler.py#L83-L88 |
229,747 | google/neuroglancer | python/neuroglancer/futures.py | future_then_immediate | def future_then_immediate(future, func):
"""Returns a future that maps the result of `future` by `func`.
If `future` succeeds, sets the result of the returned future to `func(future.result())`. If
`future` fails or `func` raises an exception, the exception is stored in the returned future.
If `future` has not yet finished, `func` is invoked by the same thread that finishes it.
Otherwise, it is invoked immediately in the same thread that calls `future_then_immediate`.
"""
result = concurrent.futures.Future()
def on_done(f):
try:
result.set_result(func(f.result()))
except Exception as e:
result.set_exception(e)
future.add_done_callback(on_done)
return result | python | def future_then_immediate(future, func):
result = concurrent.futures.Future()
def on_done(f):
try:
result.set_result(func(f.result()))
except Exception as e:
result.set_exception(e)
future.add_done_callback(on_done)
return result | [
"def",
"future_then_immediate",
"(",
"future",
",",
"func",
")",
":",
"result",
"=",
"concurrent",
".",
"futures",
".",
"Future",
"(",
")",
"def",
"on_done",
"(",
"f",
")",
":",
"try",
":",
"result",
".",
"set_result",
"(",
"func",
"(",
"f",
".",
"re... | Returns a future that maps the result of `future` by `func`.
If `future` succeeds, sets the result of the returned future to `func(future.result())`. If
`future` fails or `func` raises an exception, the exception is stored in the returned future.
If `future` has not yet finished, `func` is invoked by the same thread that finishes it.
Otherwise, it is invoked immediately in the same thread that calls `future_then_immediate`. | [
"Returns",
"a",
"future",
"that",
"maps",
"the",
"result",
"of",
"future",
"by",
"func",
"."
] | 9efd12741013f464286f0bf3fa0b667f75a66658 | https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/futures.py#L23-L41 |
229,748 | google/neuroglancer | python/neuroglancer/downsample.py | downsample_with_averaging | def downsample_with_averaging(array, factor):
"""Downsample x by factor using averaging.
@return: The downsampled array, of the same type as x.
"""
factor = tuple(factor)
output_shape = tuple(int(math.ceil(s / f)) for s, f in zip(array.shape, factor))
temp = np.zeros(output_shape, dtype=np.float32)
counts = np.zeros(output_shape, np.int)
for offset in np.ndindex(factor):
part = array[tuple(np.s_[o::f] for o, f in zip(offset, factor))]
indexing_expr = tuple(np.s_[:s] for s in part.shape)
temp[indexing_expr] += part
counts[indexing_expr] += 1
return np.cast[array.dtype](temp / counts) | python | def downsample_with_averaging(array, factor):
factor = tuple(factor)
output_shape = tuple(int(math.ceil(s / f)) for s, f in zip(array.shape, factor))
temp = np.zeros(output_shape, dtype=np.float32)
counts = np.zeros(output_shape, np.int)
for offset in np.ndindex(factor):
part = array[tuple(np.s_[o::f] for o, f in zip(offset, factor))]
indexing_expr = tuple(np.s_[:s] for s in part.shape)
temp[indexing_expr] += part
counts[indexing_expr] += 1
return np.cast[array.dtype](temp / counts) | [
"def",
"downsample_with_averaging",
"(",
"array",
",",
"factor",
")",
":",
"factor",
"=",
"tuple",
"(",
"factor",
")",
"output_shape",
"=",
"tuple",
"(",
"int",
"(",
"math",
".",
"ceil",
"(",
"s",
"/",
"f",
")",
")",
"for",
"s",
",",
"f",
"in",
"zi... | Downsample x by factor using averaging.
@return: The downsampled array, of the same type as x. | [
"Downsample",
"x",
"by",
"factor",
"using",
"averaging",
"."
] | 9efd12741013f464286f0bf3fa0b667f75a66658 | https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/downsample.py#L22-L36 |
229,749 | google/neuroglancer | python/neuroglancer/downsample.py | downsample_with_striding | def downsample_with_striding(array, factor):
"""Downsample x by factor using striding.
@return: The downsampled array, of the same type as x.
"""
return array[tuple(np.s_[::f] for f in factor)] | python | def downsample_with_striding(array, factor):
return array[tuple(np.s_[::f] for f in factor)] | [
"def",
"downsample_with_striding",
"(",
"array",
",",
"factor",
")",
":",
"return",
"array",
"[",
"tuple",
"(",
"np",
".",
"s_",
"[",
":",
":",
"f",
"]",
"for",
"f",
"in",
"factor",
")",
"]"
] | Downsample x by factor using striding.
@return: The downsampled array, of the same type as x. | [
"Downsample",
"x",
"by",
"factor",
"using",
"striding",
"."
] | 9efd12741013f464286f0bf3fa0b667f75a66658 | https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/downsample.py#L39-L44 |
229,750 | google/neuroglancer | python/neuroglancer/equivalence_map.py | EquivalenceMap._get_representative | def _get_representative(self, obj):
"""Finds and returns the root of the set containing `obj`."""
if obj not in self._parents:
self._parents[obj] = obj
self._weights[obj] = 1
self._prev_next[obj] = [obj, obj]
self._min_values[obj] = obj
return obj
path = [obj]
root = self._parents[obj]
while root != path[-1]:
path.append(root)
root = self._parents[root]
# compress the path and return
for ancestor in path:
self._parents[ancestor] = root
return root | python | def _get_representative(self, obj):
if obj not in self._parents:
self._parents[obj] = obj
self._weights[obj] = 1
self._prev_next[obj] = [obj, obj]
self._min_values[obj] = obj
return obj
path = [obj]
root = self._parents[obj]
while root != path[-1]:
path.append(root)
root = self._parents[root]
# compress the path and return
for ancestor in path:
self._parents[ancestor] = root
return root | [
"def",
"_get_representative",
"(",
"self",
",",
"obj",
")",
":",
"if",
"obj",
"not",
"in",
"self",
".",
"_parents",
":",
"self",
".",
"_parents",
"[",
"obj",
"]",
"=",
"obj",
"self",
".",
"_weights",
"[",
"obj",
"]",
"=",
"1",
"self",
".",
"_prev_n... | Finds and returns the root of the set containing `obj`. | [
"Finds",
"and",
"returns",
"the",
"root",
"of",
"the",
"set",
"containing",
"obj",
"."
] | 9efd12741013f464286f0bf3fa0b667f75a66658 | https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/equivalence_map.py#L47-L66 |
229,751 | google/neuroglancer | python/neuroglancer/equivalence_map.py | EquivalenceMap.members | def members(self, x):
"""Yields the members of the equivalence class containing `x`."""
if x not in self._parents:
yield x
return
cur_x = x
while True:
yield cur_x
cur_x = self._prev_next[cur_x][1]
if cur_x == x:
break | python | def members(self, x):
if x not in self._parents:
yield x
return
cur_x = x
while True:
yield cur_x
cur_x = self._prev_next[cur_x][1]
if cur_x == x:
break | [
"def",
"members",
"(",
"self",
",",
"x",
")",
":",
"if",
"x",
"not",
"in",
"self",
".",
"_parents",
":",
"yield",
"x",
"return",
"cur_x",
"=",
"x",
"while",
"True",
":",
"yield",
"cur_x",
"cur_x",
"=",
"self",
".",
"_prev_next",
"[",
"cur_x",
"]",
... | Yields the members of the equivalence class containing `x`. | [
"Yields",
"the",
"members",
"of",
"the",
"equivalence",
"class",
"containing",
"x",
"."
] | 9efd12741013f464286f0bf3fa0b667f75a66658 | https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/equivalence_map.py#L134-L144 |
229,752 | google/neuroglancer | python/neuroglancer/equivalence_map.py | EquivalenceMap.sets | def sets(self):
"""Returns the equivalence classes as a set of sets."""
sets = {}
for x in self._parents:
sets.setdefault(self[x], set()).add(x)
return frozenset(frozenset(v) for v in six.viewvalues(sets)) | python | def sets(self):
sets = {}
for x in self._parents:
sets.setdefault(self[x], set()).add(x)
return frozenset(frozenset(v) for v in six.viewvalues(sets)) | [
"def",
"sets",
"(",
"self",
")",
":",
"sets",
"=",
"{",
"}",
"for",
"x",
"in",
"self",
".",
"_parents",
":",
"sets",
".",
"setdefault",
"(",
"self",
"[",
"x",
"]",
",",
"set",
"(",
")",
")",
".",
"add",
"(",
"x",
")",
"return",
"frozenset",
"... | Returns the equivalence classes as a set of sets. | [
"Returns",
"the",
"equivalence",
"classes",
"as",
"a",
"set",
"of",
"sets",
"."
] | 9efd12741013f464286f0bf3fa0b667f75a66658 | https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/equivalence_map.py#L146-L151 |
229,753 | google/neuroglancer | python/neuroglancer/equivalence_map.py | EquivalenceMap.to_json | def to_json(self):
"""Returns the equivalence classes a sorted list of sorted lists."""
sets = self.sets()
return sorted(sorted(x) for x in sets) | python | def to_json(self):
sets = self.sets()
return sorted(sorted(x) for x in sets) | [
"def",
"to_json",
"(",
"self",
")",
":",
"sets",
"=",
"self",
".",
"sets",
"(",
")",
"return",
"sorted",
"(",
"sorted",
"(",
"x",
")",
"for",
"x",
"in",
"sets",
")"
] | Returns the equivalence classes a sorted list of sorted lists. | [
"Returns",
"the",
"equivalence",
"classes",
"a",
"sorted",
"list",
"of",
"sorted",
"lists",
"."
] | 9efd12741013f464286f0bf3fa0b667f75a66658 | https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/equivalence_map.py#L153-L156 |
229,754 | google/neuroglancer | python/neuroglancer/equivalence_map.py | EquivalenceMap.delete_set | def delete_set(self, x):
"""Removes the equivalence class containing `x`."""
if x not in self._parents:
return
members = list(self.members(x))
for v in members:
del self._parents[v]
del self._weights[v]
del self._prev_next[v]
del self._min_values[v] | python | def delete_set(self, x):
if x not in self._parents:
return
members = list(self.members(x))
for v in members:
del self._parents[v]
del self._weights[v]
del self._prev_next[v]
del self._min_values[v] | [
"def",
"delete_set",
"(",
"self",
",",
"x",
")",
":",
"if",
"x",
"not",
"in",
"self",
".",
"_parents",
":",
"return",
"members",
"=",
"list",
"(",
"self",
".",
"members",
"(",
"x",
")",
")",
"for",
"v",
"in",
"members",
":",
"del",
"self",
".",
... | Removes the equivalence class containing `x`. | [
"Removes",
"the",
"equivalence",
"class",
"containing",
"x",
"."
] | 9efd12741013f464286f0bf3fa0b667f75a66658 | https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/equivalence_map.py#L175-L184 |
229,755 | google/neuroglancer | python/neuroglancer/equivalence_map.py | EquivalenceMap.isolate_element | def isolate_element(self, x):
"""Isolates `x` from its equivalence class."""
members = list(self.members(x))
self.delete_set(x)
self.union(*(v for v in members if v != x)) | python | def isolate_element(self, x):
members = list(self.members(x))
self.delete_set(x)
self.union(*(v for v in members if v != x)) | [
"def",
"isolate_element",
"(",
"self",
",",
"x",
")",
":",
"members",
"=",
"list",
"(",
"self",
".",
"members",
"(",
"x",
")",
")",
"self",
".",
"delete_set",
"(",
"x",
")",
"self",
".",
"union",
"(",
"*",
"(",
"v",
"for",
"v",
"in",
"members",
... | Isolates `x` from its equivalence class. | [
"Isolates",
"x",
"from",
"its",
"equivalence",
"class",
"."
] | 9efd12741013f464286f0bf3fa0b667f75a66658 | https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/equivalence_map.py#L186-L190 |
229,756 | google/neuroglancer | python/neuroglancer/viewer_state.py | quaternion_slerp | def quaternion_slerp(a, b, t):
"""Spherical linear interpolation for unit quaternions.
This is based on the implementation in the gl-matrix package:
https://github.com/toji/gl-matrix
"""
if a is None:
a = unit_quaternion()
if b is None:
b = unit_quaternion()
# calc cosine
cosom = np.dot(a, b)
# adjust signs (if necessary)
if cosom < 0.0:
cosom = -cosom
b = -b
# calculate coefficients
if (1.0 - cosom) > 0.000001:
# standard case (slerp)
omega = math.acos(cosom)
sinom = math.sin(omega)
scale0 = math.sin((1.0 - t) * omega) / sinom
scale1 = math.sin(t * omega) / sinom
else:
# "from" and "to" quaternions are very close
# ... so we can do a linear interpolation
scale0 = 1.0 - t
scale1 = t
return scale0 * a + scale1 * b | python | def quaternion_slerp(a, b, t):
if a is None:
a = unit_quaternion()
if b is None:
b = unit_quaternion()
# calc cosine
cosom = np.dot(a, b)
# adjust signs (if necessary)
if cosom < 0.0:
cosom = -cosom
b = -b
# calculate coefficients
if (1.0 - cosom) > 0.000001:
# standard case (slerp)
omega = math.acos(cosom)
sinom = math.sin(omega)
scale0 = math.sin((1.0 - t) * omega) / sinom
scale1 = math.sin(t * omega) / sinom
else:
# "from" and "to" quaternions are very close
# ... so we can do a linear interpolation
scale0 = 1.0 - t
scale1 = t
return scale0 * a + scale1 * b | [
"def",
"quaternion_slerp",
"(",
"a",
",",
"b",
",",
"t",
")",
":",
"if",
"a",
"is",
"None",
":",
"a",
"=",
"unit_quaternion",
"(",
")",
"if",
"b",
"is",
"None",
":",
"b",
"=",
"unit_quaternion",
"(",
")",
"# calc cosine",
"cosom",
"=",
"np",
".",
... | Spherical linear interpolation for unit quaternions.
This is based on the implementation in the gl-matrix package:
https://github.com/toji/gl-matrix | [
"Spherical",
"linear",
"interpolation",
"for",
"unit",
"quaternions",
"."
] | 9efd12741013f464286f0bf3fa0b667f75a66658 | https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/viewer_state.py#L65-L94 |
229,757 | google/neuroglancer | python/neuroglancer/tool/agglomeration_split_tool.py | GreedyMulticut.remove_edge_from_heap | def remove_edge_from_heap(self, segment_ids):
"""Remove an edge from the heap."""
self._initialize_heap()
key = normalize_edge(segment_ids)
if key in self.edge_map:
self.edge_map[key][0] = None
self.num_valid_edges -= 1 | python | def remove_edge_from_heap(self, segment_ids):
self._initialize_heap()
key = normalize_edge(segment_ids)
if key in self.edge_map:
self.edge_map[key][0] = None
self.num_valid_edges -= 1 | [
"def",
"remove_edge_from_heap",
"(",
"self",
",",
"segment_ids",
")",
":",
"self",
".",
"_initialize_heap",
"(",
")",
"key",
"=",
"normalize_edge",
"(",
"segment_ids",
")",
"if",
"key",
"in",
"self",
".",
"edge_map",
":",
"self",
".",
"edge_map",
"[",
"key... | Remove an edge from the heap. | [
"Remove",
"an",
"edge",
"from",
"the",
"heap",
"."
] | 9efd12741013f464286f0bf3fa0b667f75a66658 | https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/tool/agglomeration_split_tool.py#L73-L79 |
229,758 | google/neuroglancer | python/neuroglancer/trackable_state.py | TrackableState.txn | def txn(self, overwrite=False, lock=True):
"""Context manager for a state modification transaction."""
if lock:
self._lock.acquire()
try:
new_state, existing_generation = self.state_and_generation
new_state = copy.deepcopy(new_state)
yield new_state
if overwrite:
existing_generation = None
self.set_state(new_state, existing_generation=existing_generation)
finally:
if lock:
self._lock.release() | python | def txn(self, overwrite=False, lock=True):
if lock:
self._lock.acquire()
try:
new_state, existing_generation = self.state_and_generation
new_state = copy.deepcopy(new_state)
yield new_state
if overwrite:
existing_generation = None
self.set_state(new_state, existing_generation=existing_generation)
finally:
if lock:
self._lock.release() | [
"def",
"txn",
"(",
"self",
",",
"overwrite",
"=",
"False",
",",
"lock",
"=",
"True",
")",
":",
"if",
"lock",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"new_state",
",",
"existing_generation",
"=",
"self",
".",
"state_and_generati... | Context manager for a state modification transaction. | [
"Context",
"manager",
"for",
"a",
"state",
"modification",
"transaction",
"."
] | 9efd12741013f464286f0bf3fa0b667f75a66658 | https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/trackable_state.py#L108-L121 |
229,759 | google/neuroglancer | python/neuroglancer/local_volume.py | LocalVolume.invalidate | def invalidate(self):
"""Mark the data invalidated. Clients will refetch the volume."""
with self._mesh_generator_lock:
self._mesh_generator_pending = None
self._mesh_generator = None
self._dispatch_changed_callbacks() | python | def invalidate(self):
with self._mesh_generator_lock:
self._mesh_generator_pending = None
self._mesh_generator = None
self._dispatch_changed_callbacks() | [
"def",
"invalidate",
"(",
"self",
")",
":",
"with",
"self",
".",
"_mesh_generator_lock",
":",
"self",
".",
"_mesh_generator_pending",
"=",
"None",
"self",
".",
"_mesh_generator",
"=",
"None",
"self",
".",
"_dispatch_changed_callbacks",
"(",
")"
] | Mark the data invalidated. Clients will refetch the volume. | [
"Mark",
"the",
"data",
"invalidated",
".",
"Clients",
"will",
"refetch",
"the",
"volume",
"."
] | 9efd12741013f464286f0bf3fa0b667f75a66658 | https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/local_volume.py#L289-L294 |
229,760 | saulpw/visidata | visidata/loaders/markdown.py | save_md | def save_md(p, *vsheets):
'pipe tables compatible with org-mode'
with p.open_text(mode='w') as fp:
for vs in vsheets:
if len(vsheets) > 1:
fp.write('# %s\n\n' % vs.name)
fp.write('|' + '|'.join('%-*s' % (col.width or options.default_width, markdown_escape(col.name)) for col in vs.visibleCols) + '|\n')
fp.write('|' + '+'.join(markdown_colhdr(col) for col in vs.visibleCols) + '|\n')
for row in Progress(vs.rows, 'saving'):
fp.write('|' + '|'.join('%-*s' % (col.width or options.default_width, markdown_escape(col.getDisplayValue(row))) for col in vs.visibleCols) + '|\n')
fp.write('\n')
status('%s save finished' % p) | python | def save_md(p, *vsheets):
'pipe tables compatible with org-mode'
with p.open_text(mode='w') as fp:
for vs in vsheets:
if len(vsheets) > 1:
fp.write('# %s\n\n' % vs.name)
fp.write('|' + '|'.join('%-*s' % (col.width or options.default_width, markdown_escape(col.name)) for col in vs.visibleCols) + '|\n')
fp.write('|' + '+'.join(markdown_colhdr(col) for col in vs.visibleCols) + '|\n')
for row in Progress(vs.rows, 'saving'):
fp.write('|' + '|'.join('%-*s' % (col.width or options.default_width, markdown_escape(col.getDisplayValue(row))) for col in vs.visibleCols) + '|\n')
fp.write('\n')
status('%s save finished' % p) | [
"def",
"save_md",
"(",
"p",
",",
"*",
"vsheets",
")",
":",
"with",
"p",
".",
"open_text",
"(",
"mode",
"=",
"'w'",
")",
"as",
"fp",
":",
"for",
"vs",
"in",
"vsheets",
":",
"if",
"len",
"(",
"vsheets",
")",
">",
"1",
":",
"fp",
".",
"write",
"... | pipe tables compatible with org-mode | [
"pipe",
"tables",
"compatible",
"with",
"org",
"-",
"mode"
] | 32771e0cea6c24fc7902683d14558391395c591f | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/loaders/markdown.py#L18-L31 |
229,761 | saulpw/visidata | visidata/pyobj.py | load_pyobj | def load_pyobj(name, pyobj):
'Return Sheet object of appropriate type for given sources in `args`.'
if isinstance(pyobj, list) or isinstance(pyobj, tuple):
if getattr(pyobj, '_fields', None): # list of namedtuple
return SheetNamedTuple(name, pyobj)
else:
return SheetList(name, pyobj)
elif isinstance(pyobj, dict):
return SheetDict(name, pyobj)
elif isinstance(pyobj, object):
return SheetObject(name, pyobj)
else:
error("cannot load '%s' as pyobj" % type(pyobj).__name__) | python | def load_pyobj(name, pyobj):
'Return Sheet object of appropriate type for given sources in `args`.'
if isinstance(pyobj, list) or isinstance(pyobj, tuple):
if getattr(pyobj, '_fields', None): # list of namedtuple
return SheetNamedTuple(name, pyobj)
else:
return SheetList(name, pyobj)
elif isinstance(pyobj, dict):
return SheetDict(name, pyobj)
elif isinstance(pyobj, object):
return SheetObject(name, pyobj)
else:
error("cannot load '%s' as pyobj" % type(pyobj).__name__) | [
"def",
"load_pyobj",
"(",
"name",
",",
"pyobj",
")",
":",
"if",
"isinstance",
"(",
"pyobj",
",",
"list",
")",
"or",
"isinstance",
"(",
"pyobj",
",",
"tuple",
")",
":",
"if",
"getattr",
"(",
"pyobj",
",",
"'_fields'",
",",
"None",
")",
":",
"# list of... | Return Sheet object of appropriate type for given sources in `args`. | [
"Return",
"Sheet",
"object",
"of",
"appropriate",
"type",
"for",
"given",
"sources",
"in",
"args",
"."
] | 32771e0cea6c24fc7902683d14558391395c591f | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/pyobj.py#L90-L102 |
229,762 | saulpw/visidata | visidata/pyobj.py | PyobjColumns | def PyobjColumns(obj):
'Return columns for each public attribute on an object.'
return [ColumnAttr(k, type(getattr(obj, k))) for k in getPublicAttrs(obj)] | python | def PyobjColumns(obj):
'Return columns for each public attribute on an object.'
return [ColumnAttr(k, type(getattr(obj, k))) for k in getPublicAttrs(obj)] | [
"def",
"PyobjColumns",
"(",
"obj",
")",
":",
"return",
"[",
"ColumnAttr",
"(",
"k",
",",
"type",
"(",
"getattr",
"(",
"obj",
",",
"k",
")",
")",
")",
"for",
"k",
"in",
"getPublicAttrs",
"(",
"obj",
")",
"]"
] | Return columns for each public attribute on an object. | [
"Return",
"columns",
"for",
"each",
"public",
"attribute",
"on",
"an",
"object",
"."
] | 32771e0cea6c24fc7902683d14558391395c591f | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/pyobj.py#L112-L114 |
229,763 | saulpw/visidata | visidata/pyobj.py | DictKeyColumns | def DictKeyColumns(d):
'Return a list of Column objects from dictionary keys.'
return [ColumnItem(k, k, type=deduceType(d[k])) for k in d.keys()] | python | def DictKeyColumns(d):
'Return a list of Column objects from dictionary keys.'
return [ColumnItem(k, k, type=deduceType(d[k])) for k in d.keys()] | [
"def",
"DictKeyColumns",
"(",
"d",
")",
":",
"return",
"[",
"ColumnItem",
"(",
"k",
",",
"k",
",",
"type",
"=",
"deduceType",
"(",
"d",
"[",
"k",
"]",
")",
")",
"for",
"k",
"in",
"d",
".",
"keys",
"(",
")",
"]"
] | Return a list of Column objects from dictionary keys. | [
"Return",
"a",
"list",
"of",
"Column",
"objects",
"from",
"dictionary",
"keys",
"."
] | 32771e0cea6c24fc7902683d14558391395c591f | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/pyobj.py#L120-L122 |
229,764 | saulpw/visidata | visidata/pyobj.py | SheetList | def SheetList(name, src, **kwargs):
'Creates a Sheet from a list of homogenous dicts or namedtuples.'
if not src:
status('no content in ' + name)
return
if isinstance(src[0], dict):
return ListOfDictSheet(name, source=src, **kwargs)
elif isinstance(src[0], tuple):
if getattr(src[0], '_fields', None): # looks like a namedtuple
return ListOfNamedTupleSheet(name, source=src, **kwargs)
# simple list
return ListOfPyobjSheet(name, source=src, **kwargs) | python | def SheetList(name, src, **kwargs):
'Creates a Sheet from a list of homogenous dicts or namedtuples.'
if not src:
status('no content in ' + name)
return
if isinstance(src[0], dict):
return ListOfDictSheet(name, source=src, **kwargs)
elif isinstance(src[0], tuple):
if getattr(src[0], '_fields', None): # looks like a namedtuple
return ListOfNamedTupleSheet(name, source=src, **kwargs)
# simple list
return ListOfPyobjSheet(name, source=src, **kwargs) | [
"def",
"SheetList",
"(",
"name",
",",
"src",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"src",
":",
"status",
"(",
"'no content in '",
"+",
"name",
")",
"return",
"if",
"isinstance",
"(",
"src",
"[",
"0",
"]",
",",
"dict",
")",
":",
"return",
... | Creates a Sheet from a list of homogenous dicts or namedtuples. | [
"Creates",
"a",
"Sheet",
"from",
"a",
"list",
"of",
"homogenous",
"dicts",
"or",
"namedtuples",
"."
] | 32771e0cea6c24fc7902683d14558391395c591f | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/pyobj.py#L124-L138 |
229,765 | saulpw/visidata | visidata/freqtbl.py | SheetFreqTable.reload | def reload(self):
'Generate histrow for each row and then reverse-sort by length.'
self.rows = []
# if len(self.origCols) == 1 and self.origCols[0].type in (int, float, currency):
# self.numericBinning()
# else:
self.discreteBinning()
# automatically add cache to all columns now that everything is binned
for c in self.nonKeyVisibleCols:
c._cachedValues = collections.OrderedDict() | python | def reload(self):
'Generate histrow for each row and then reverse-sort by length.'
self.rows = []
# if len(self.origCols) == 1 and self.origCols[0].type in (int, float, currency):
# self.numericBinning()
# else:
self.discreteBinning()
# automatically add cache to all columns now that everything is binned
for c in self.nonKeyVisibleCols:
c._cachedValues = collections.OrderedDict() | [
"def",
"reload",
"(",
"self",
")",
":",
"self",
".",
"rows",
"=",
"[",
"]",
"# if len(self.origCols) == 1 and self.origCols[0].type in (int, float, currency):",
"# self.numericBinning()",
"# else:",
"self",
".",
"discreteBinning",
"(",
")",
"# automat... | Generate histrow for each row and then reverse-sort by length. | [
"Generate",
"histrow",
"for",
"each",
"row",
"and",
"then",
"reverse",
"-",
"sort",
"by",
"length",
"."
] | 32771e0cea6c24fc7902683d14558391395c591f | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/freqtbl.py#L153-L164 |
229,766 | saulpw/visidata | visidata/clipboard.py | saveToClipboard | def saveToClipboard(sheet, rows, filetype=None):
'copy rows from sheet to system clipboard'
filetype = filetype or options.save_filetype
vs = copy(sheet)
vs.rows = rows
status('copying rows to clipboard')
clipboard().save(vs, filetype) | python | def saveToClipboard(sheet, rows, filetype=None):
'copy rows from sheet to system clipboard'
filetype = filetype or options.save_filetype
vs = copy(sheet)
vs.rows = rows
status('copying rows to clipboard')
clipboard().save(vs, filetype) | [
"def",
"saveToClipboard",
"(",
"sheet",
",",
"rows",
",",
"filetype",
"=",
"None",
")",
":",
"filetype",
"=",
"filetype",
"or",
"options",
".",
"save_filetype",
"vs",
"=",
"copy",
"(",
"sheet",
")",
"vs",
".",
"rows",
"=",
"rows",
"status",
"(",
"'copy... | copy rows from sheet to system clipboard | [
"copy",
"rows",
"from",
"sheet",
"to",
"system",
"clipboard"
] | 32771e0cea6c24fc7902683d14558391395c591f | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/clipboard.py#L114-L120 |
229,767 | saulpw/visidata | visidata/clipboard.py | _Clipboard.copy | def copy(self, value):
'Copy a cell to the system clipboard.'
with tempfile.NamedTemporaryFile() as temp:
with open(temp.name, 'w', encoding=options.encoding) as fp:
fp.write(str(value))
p = subprocess.Popen(
self.command,
stdin=open(temp.name, 'r', encoding=options.encoding),
stdout=subprocess.DEVNULL)
p.communicate() | python | def copy(self, value):
'Copy a cell to the system clipboard.'
with tempfile.NamedTemporaryFile() as temp:
with open(temp.name, 'w', encoding=options.encoding) as fp:
fp.write(str(value))
p = subprocess.Popen(
self.command,
stdin=open(temp.name, 'r', encoding=options.encoding),
stdout=subprocess.DEVNULL)
p.communicate() | [
"def",
"copy",
"(",
"self",
",",
"value",
")",
":",
"with",
"tempfile",
".",
"NamedTemporaryFile",
"(",
")",
"as",
"temp",
":",
"with",
"open",
"(",
"temp",
".",
"name",
",",
"'w'",
",",
"encoding",
"=",
"options",
".",
"encoding",
")",
"as",
"fp",
... | Copy a cell to the system clipboard. | [
"Copy",
"a",
"cell",
"to",
"the",
"system",
"clipboard",
"."
] | 32771e0cea6c24fc7902683d14558391395c591f | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/clipboard.py#L79-L90 |
229,768 | saulpw/visidata | visidata/clipboard.py | _Clipboard.save | def save(self, vs, filetype):
'Copy rows to the system clipboard.'
# use NTF to generate filename and delete file on context exit
with tempfile.NamedTemporaryFile(suffix='.'+filetype) as temp:
saveSheets(temp.name, vs)
sync(1)
p = subprocess.Popen(
self.command,
stdin=open(temp.name, 'r', encoding=options.encoding),
stdout=subprocess.DEVNULL,
close_fds=True)
p.communicate() | python | def save(self, vs, filetype):
'Copy rows to the system clipboard.'
# use NTF to generate filename and delete file on context exit
with tempfile.NamedTemporaryFile(suffix='.'+filetype) as temp:
saveSheets(temp.name, vs)
sync(1)
p = subprocess.Popen(
self.command,
stdin=open(temp.name, 'r', encoding=options.encoding),
stdout=subprocess.DEVNULL,
close_fds=True)
p.communicate() | [
"def",
"save",
"(",
"self",
",",
"vs",
",",
"filetype",
")",
":",
"# use NTF to generate filename and delete file on context exit",
"with",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"suffix",
"=",
"'.'",
"+",
"filetype",
")",
"as",
"temp",
":",
"saveSheets",
"("... | Copy rows to the system clipboard. | [
"Copy",
"rows",
"to",
"the",
"system",
"clipboard",
"."
] | 32771e0cea6c24fc7902683d14558391395c591f | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/clipboard.py#L92-L104 |
229,769 | saulpw/visidata | plugins/vgit/vgit.py | LogSheet.amendPrevious | def amendPrevious(self, targethash):
'amend targethash with current index, then rebase newer commits on top'
prevBranch = loggit_all('rev-parse', '--symbolic-full-name', '--abbrev-ref', 'HEAD').strip()
ret = loggit_all('commit', '-m', 'MERGE '+targethash) # commit index to viewed branch
newChanges = loggit_all('rev-parse', 'HEAD').strip()
ret += loggit_all('stash', 'save', '--keep-index') # stash everything else
with GitUndo('stash', 'pop'):
tmpBranch = randomBranchName()
ret += loggit_all('checkout', '-b', tmpBranch) # create/switch to tmp branch
with GitUndo('checkout', prevBranch), GitUndo('branch', '-D', tmpBranch):
ret += loggit_all('reset', '--hard', targethash) # tmpbranch now at targethash
ret += loggit_all('cherry-pick', '-n', newChanges) # pick new change from original branch
ret += loggit_all('commit', '--amend', '--no-edit') # recommit to fix targethash (which will change)
ret += loggit_all('rebase', '--onto', tmpBranch, 'HEAD@{1}', prevBranch) # replay the rest
return ret.splitlines() | python | def amendPrevious(self, targethash):
'amend targethash with current index, then rebase newer commits on top'
prevBranch = loggit_all('rev-parse', '--symbolic-full-name', '--abbrev-ref', 'HEAD').strip()
ret = loggit_all('commit', '-m', 'MERGE '+targethash) # commit index to viewed branch
newChanges = loggit_all('rev-parse', 'HEAD').strip()
ret += loggit_all('stash', 'save', '--keep-index') # stash everything else
with GitUndo('stash', 'pop'):
tmpBranch = randomBranchName()
ret += loggit_all('checkout', '-b', tmpBranch) # create/switch to tmp branch
with GitUndo('checkout', prevBranch), GitUndo('branch', '-D', tmpBranch):
ret += loggit_all('reset', '--hard', targethash) # tmpbranch now at targethash
ret += loggit_all('cherry-pick', '-n', newChanges) # pick new change from original branch
ret += loggit_all('commit', '--amend', '--no-edit') # recommit to fix targethash (which will change)
ret += loggit_all('rebase', '--onto', tmpBranch, 'HEAD@{1}', prevBranch) # replay the rest
return ret.splitlines() | [
"def",
"amendPrevious",
"(",
"self",
",",
"targethash",
")",
":",
"prevBranch",
"=",
"loggit_all",
"(",
"'rev-parse'",
",",
"'--symbolic-full-name'",
",",
"'--abbrev-ref'",
",",
"'HEAD'",
")",
".",
"strip",
"(",
")",
"ret",
"=",
"loggit_all",
"(",
"'commit'",
... | amend targethash with current index, then rebase newer commits on top | [
"amend",
"targethash",
"with",
"current",
"index",
"then",
"rebase",
"newer",
"commits",
"on",
"top"
] | 32771e0cea6c24fc7902683d14558391395c591f | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/plugins/vgit/vgit.py#L79-L97 |
229,770 | saulpw/visidata | visidata/loaders/html.py | save_html | def save_html(p, *vsheets):
'Save vsheets as HTML tables in a single file'
with open(p.resolve(), 'w', encoding='ascii', errors='xmlcharrefreplace') as fp:
for sheet in vsheets:
fp.write('<h2 class="sheetname">%s</h2>\n'.format(sheetname=html.escape(sheet.name)))
fp.write('<table id="{sheetname}">\n'.format(sheetname=html.escape(sheet.name)))
# headers
fp.write('<tr>')
for col in sheet.visibleCols:
contents = html.escape(col.name)
fp.write('<th>{colname}</th>'.format(colname=contents))
fp.write('</tr>\n')
# rows
for r in Progress(sheet.rows, 'saving'):
fp.write('<tr>')
for col in sheet.visibleCols:
fp.write('<td>')
fp.write(html.escape(col.getDisplayValue(r)))
fp.write('</td>')
fp.write('</tr>\n')
fp.write('</table>')
status('%s save finished' % p) | python | def save_html(p, *vsheets):
'Save vsheets as HTML tables in a single file'
with open(p.resolve(), 'w', encoding='ascii', errors='xmlcharrefreplace') as fp:
for sheet in vsheets:
fp.write('<h2 class="sheetname">%s</h2>\n'.format(sheetname=html.escape(sheet.name)))
fp.write('<table id="{sheetname}">\n'.format(sheetname=html.escape(sheet.name)))
# headers
fp.write('<tr>')
for col in sheet.visibleCols:
contents = html.escape(col.name)
fp.write('<th>{colname}</th>'.format(colname=contents))
fp.write('</tr>\n')
# rows
for r in Progress(sheet.rows, 'saving'):
fp.write('<tr>')
for col in sheet.visibleCols:
fp.write('<td>')
fp.write(html.escape(col.getDisplayValue(r)))
fp.write('</td>')
fp.write('</tr>\n')
fp.write('</table>')
status('%s save finished' % p) | [
"def",
"save_html",
"(",
"p",
",",
"*",
"vsheets",
")",
":",
"with",
"open",
"(",
"p",
".",
"resolve",
"(",
")",
",",
"'w'",
",",
"encoding",
"=",
"'ascii'",
",",
"errors",
"=",
"'xmlcharrefreplace'",
")",
"as",
"fp",
":",
"for",
"sheet",
"in",
"vs... | Save vsheets as HTML tables in a single file | [
"Save",
"vsheets",
"as",
"HTML",
"tables",
"in",
"a",
"single",
"file"
] | 32771e0cea6c24fc7902683d14558391395c591f | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/loaders/html.py#L99-L126 |
229,771 | saulpw/visidata | visidata/loaders/tsv.py | tsv_trdict | def tsv_trdict(vs):
'returns string.translate dictionary for replacing tabs and newlines'
if options.safety_first:
delim = options.get('delimiter', vs)
return {ord(delim): options.get('tsv_safe_tab', vs), # \t
10: options.get('tsv_safe_newline', vs), # \n
13: options.get('tsv_safe_newline', vs), # \r
}
return {} | python | def tsv_trdict(vs):
'returns string.translate dictionary for replacing tabs and newlines'
if options.safety_first:
delim = options.get('delimiter', vs)
return {ord(delim): options.get('tsv_safe_tab', vs), # \t
10: options.get('tsv_safe_newline', vs), # \n
13: options.get('tsv_safe_newline', vs), # \r
}
return {} | [
"def",
"tsv_trdict",
"(",
"vs",
")",
":",
"if",
"options",
".",
"safety_first",
":",
"delim",
"=",
"options",
".",
"get",
"(",
"'delimiter'",
",",
"vs",
")",
"return",
"{",
"ord",
"(",
"delim",
")",
":",
"options",
".",
"get",
"(",
"'tsv_safe_tab'",
... | returns string.translate dictionary for replacing tabs and newlines | [
"returns",
"string",
".",
"translate",
"dictionary",
"for",
"replacing",
"tabs",
"and",
"newlines"
] | 32771e0cea6c24fc7902683d14558391395c591f | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/loaders/tsv.py#L83-L91 |
229,772 | saulpw/visidata | visidata/loaders/tsv.py | save_tsv_header | def save_tsv_header(p, vs):
'Write tsv header for Sheet `vs` to Path `p`.'
trdict = tsv_trdict(vs)
delim = options.delimiter
with p.open_text(mode='w') as fp:
colhdr = delim.join(col.name.translate(trdict) for col in vs.visibleCols) + '\n'
if colhdr.strip(): # is anything but whitespace
fp.write(colhdr) | python | def save_tsv_header(p, vs):
'Write tsv header for Sheet `vs` to Path `p`.'
trdict = tsv_trdict(vs)
delim = options.delimiter
with p.open_text(mode='w') as fp:
colhdr = delim.join(col.name.translate(trdict) for col in vs.visibleCols) + '\n'
if colhdr.strip(): # is anything but whitespace
fp.write(colhdr) | [
"def",
"save_tsv_header",
"(",
"p",
",",
"vs",
")",
":",
"trdict",
"=",
"tsv_trdict",
"(",
"vs",
")",
"delim",
"=",
"options",
".",
"delimiter",
"with",
"p",
".",
"open_text",
"(",
"mode",
"=",
"'w'",
")",
"as",
"fp",
":",
"colhdr",
"=",
"delim",
"... | Write tsv header for Sheet `vs` to Path `p`. | [
"Write",
"tsv",
"header",
"for",
"Sheet",
"vs",
"to",
"Path",
"p",
"."
] | 32771e0cea6c24fc7902683d14558391395c591f | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/loaders/tsv.py#L93-L101 |
229,773 | saulpw/visidata | visidata/loaders/tsv.py | save_tsv | def save_tsv(p, vs):
'Write sheet to file `fn` as TSV.'
delim = options.get('delimiter', vs)
trdict = tsv_trdict(vs)
save_tsv_header(p, vs)
with p.open_text(mode='a') as fp:
for dispvals in genAllValues(vs.rows, vs.visibleCols, trdict, format=True):
fp.write(delim.join(dispvals))
fp.write('\n')
status('%s save finished' % p) | python | def save_tsv(p, vs):
'Write sheet to file `fn` as TSV.'
delim = options.get('delimiter', vs)
trdict = tsv_trdict(vs)
save_tsv_header(p, vs)
with p.open_text(mode='a') as fp:
for dispvals in genAllValues(vs.rows, vs.visibleCols, trdict, format=True):
fp.write(delim.join(dispvals))
fp.write('\n')
status('%s save finished' % p) | [
"def",
"save_tsv",
"(",
"p",
",",
"vs",
")",
":",
"delim",
"=",
"options",
".",
"get",
"(",
"'delimiter'",
",",
"vs",
")",
"trdict",
"=",
"tsv_trdict",
"(",
"vs",
")",
"save_tsv_header",
"(",
"p",
",",
"vs",
")",
"with",
"p",
".",
"open_text",
"(",... | Write sheet to file `fn` as TSV. | [
"Write",
"sheet",
"to",
"file",
"fn",
"as",
"TSV",
"."
] | 32771e0cea6c24fc7902683d14558391395c591f | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/loaders/tsv.py#L140-L152 |
229,774 | saulpw/visidata | visidata/loaders/tsv.py | append_tsv_row | def append_tsv_row(vs, row):
'Append `row` to vs.source, creating file with correct headers if necessary. For internal use only.'
if not vs.source.exists():
with contextlib.suppress(FileExistsError):
parentdir = vs.source.parent.resolve()
if parentdir:
os.makedirs(parentdir)
save_tsv_header(vs.source, vs)
with vs.source.open_text(mode='a') as fp:
fp.write('\t'.join(col.getDisplayValue(row) for col in vs.visibleCols) + '\n') | python | def append_tsv_row(vs, row):
'Append `row` to vs.source, creating file with correct headers if necessary. For internal use only.'
if not vs.source.exists():
with contextlib.suppress(FileExistsError):
parentdir = vs.source.parent.resolve()
if parentdir:
os.makedirs(parentdir)
save_tsv_header(vs.source, vs)
with vs.source.open_text(mode='a') as fp:
fp.write('\t'.join(col.getDisplayValue(row) for col in vs.visibleCols) + '\n') | [
"def",
"append_tsv_row",
"(",
"vs",
",",
"row",
")",
":",
"if",
"not",
"vs",
".",
"source",
".",
"exists",
"(",
")",
":",
"with",
"contextlib",
".",
"suppress",
"(",
"FileExistsError",
")",
":",
"parentdir",
"=",
"vs",
".",
"source",
".",
"parent",
"... | Append `row` to vs.source, creating file with correct headers if necessary. For internal use only. | [
"Append",
"row",
"to",
"vs",
".",
"source",
"creating",
"file",
"with",
"correct",
"headers",
"if",
"necessary",
".",
"For",
"internal",
"use",
"only",
"."
] | 32771e0cea6c24fc7902683d14558391395c591f | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/loaders/tsv.py#L155-L166 |
229,775 | saulpw/visidata | visidata/loaders/tsv.py | TsvSheet.reload_sync | def reload_sync(self):
'Perform synchronous loading of TSV file, discarding header lines.'
header_lines = options.get('header', self)
delim = options.get('delimiter', self)
with self.source.open_text() as fp:
# get one line anyway to determine number of columns
lines = list(getlines(fp, int(header_lines) or 1))
headers = [L.split(delim) for L in lines]
if header_lines <= 0:
self.columns = [ColumnItem('', i) for i in range(len(headers[0]))]
else:
self.columns = [
ColumnItem('\\n'.join(x), i)
for i, x in enumerate(zip(*headers[:header_lines]))
]
lines = lines[header_lines:] # in case of header_lines == 0
self._rowtype = namedlist('tsvobj', [c.name for c in self.columns])
self.recalc()
self.rows = []
with Progress(total=self.source.filesize) as prog:
for L in itertools.chain(lines, getlines(fp)):
row = L.split(delim)
ncols = self._rowtype.length() # current number of cols
if len(row) > ncols:
# add unnamed columns to the type not found in the header
newcols = [ColumnItem('', len(row)+i, width=8) for i in range(len(row)-ncols)]
self._rowtype = namedlist(self._rowtype.__name__, list(self._rowtype._fields) + ['_' for c in newcols])
for c in newcols:
self.addColumn(c)
elif len(row) < ncols:
# extend rows that are missing entries
row.extend([None]*(ncols-len(row)))
self.addRow(self._rowtype(row))
prog.addProgress(len(L)) | python | def reload_sync(self):
'Perform synchronous loading of TSV file, discarding header lines.'
header_lines = options.get('header', self)
delim = options.get('delimiter', self)
with self.source.open_text() as fp:
# get one line anyway to determine number of columns
lines = list(getlines(fp, int(header_lines) or 1))
headers = [L.split(delim) for L in lines]
if header_lines <= 0:
self.columns = [ColumnItem('', i) for i in range(len(headers[0]))]
else:
self.columns = [
ColumnItem('\\n'.join(x), i)
for i, x in enumerate(zip(*headers[:header_lines]))
]
lines = lines[header_lines:] # in case of header_lines == 0
self._rowtype = namedlist('tsvobj', [c.name for c in self.columns])
self.recalc()
self.rows = []
with Progress(total=self.source.filesize) as prog:
for L in itertools.chain(lines, getlines(fp)):
row = L.split(delim)
ncols = self._rowtype.length() # current number of cols
if len(row) > ncols:
# add unnamed columns to the type not found in the header
newcols = [ColumnItem('', len(row)+i, width=8) for i in range(len(row)-ncols)]
self._rowtype = namedlist(self._rowtype.__name__, list(self._rowtype._fields) + ['_' for c in newcols])
for c in newcols:
self.addColumn(c)
elif len(row) < ncols:
# extend rows that are missing entries
row.extend([None]*(ncols-len(row)))
self.addRow(self._rowtype(row))
prog.addProgress(len(L)) | [
"def",
"reload_sync",
"(",
"self",
")",
":",
"header_lines",
"=",
"options",
".",
"get",
"(",
"'header'",
",",
"self",
")",
"delim",
"=",
"options",
".",
"get",
"(",
"'delimiter'",
",",
"self",
")",
"with",
"self",
".",
"source",
".",
"open_text",
"(",... | Perform synchronous loading of TSV file, discarding header lines. | [
"Perform",
"synchronous",
"loading",
"of",
"TSV",
"file",
"discarding",
"header",
"lines",
"."
] | 32771e0cea6c24fc7902683d14558391395c591f | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/loaders/tsv.py#L39-L78 |
229,776 | saulpw/visidata | visidata/loaders/csv.py | load_csv | def load_csv(vs):
'Convert from CSV, first handling header row specially.'
with vs.source.open_text() as fp:
for i in range(options.skip):
wrappedNext(fp) # discard initial lines
if options.safety_first:
rdr = csv.reader(removeNulls(fp), **csvoptions())
else:
rdr = csv.reader(fp, **csvoptions())
vs.rows = []
# headers first, to setup columns before adding rows
headers = [wrappedNext(rdr) for i in range(int(options.header))]
if headers:
# columns ideally reflect the max number of fields over all rows
vs.columns = ArrayNamedColumns('\\n'.join(x) for x in zip(*headers))
else:
r = wrappedNext(rdr)
vs.addRow(r)
vs.columns = ArrayColumns(len(vs.rows[0]))
if not vs.columns:
vs.columns = [ColumnItem(0)]
vs.recalc() # make columns usable
with Progress(total=vs.source.filesize) as prog:
try:
samplelen = 0
for i in range(options_num_first_rows): # for progress below
row = wrappedNext(rdr)
vs.addRow(row)
samplelen += sum(len(x) for x in row)
samplelen //= options_num_first_rows # avg len of first n rows
while True:
vs.addRow(wrappedNext(rdr))
prog.addProgress(samplelen)
except StopIteration:
pass # as expected
vs.recalc()
return vs | python | def load_csv(vs):
'Convert from CSV, first handling header row specially.'
with vs.source.open_text() as fp:
for i in range(options.skip):
wrappedNext(fp) # discard initial lines
if options.safety_first:
rdr = csv.reader(removeNulls(fp), **csvoptions())
else:
rdr = csv.reader(fp, **csvoptions())
vs.rows = []
# headers first, to setup columns before adding rows
headers = [wrappedNext(rdr) for i in range(int(options.header))]
if headers:
# columns ideally reflect the max number of fields over all rows
vs.columns = ArrayNamedColumns('\\n'.join(x) for x in zip(*headers))
else:
r = wrappedNext(rdr)
vs.addRow(r)
vs.columns = ArrayColumns(len(vs.rows[0]))
if not vs.columns:
vs.columns = [ColumnItem(0)]
vs.recalc() # make columns usable
with Progress(total=vs.source.filesize) as prog:
try:
samplelen = 0
for i in range(options_num_first_rows): # for progress below
row = wrappedNext(rdr)
vs.addRow(row)
samplelen += sum(len(x) for x in row)
samplelen //= options_num_first_rows # avg len of first n rows
while True:
vs.addRow(wrappedNext(rdr))
prog.addProgress(samplelen)
except StopIteration:
pass # as expected
vs.recalc()
return vs | [
"def",
"load_csv",
"(",
"vs",
")",
":",
"with",
"vs",
".",
"source",
".",
"open_text",
"(",
")",
"as",
"fp",
":",
"for",
"i",
"in",
"range",
"(",
"options",
".",
"skip",
")",
":",
"wrappedNext",
"(",
"fp",
")",
"# discard initial lines",
"if",
"optio... | Convert from CSV, first handling header row specially. | [
"Convert",
"from",
"CSV",
"first",
"handling",
"header",
"row",
"specially",
"."
] | 32771e0cea6c24fc7902683d14558391395c591f | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/loaders/csv.py#L42-L87 |
229,777 | saulpw/visidata | visidata/loaders/csv.py | save_csv | def save_csv(p, sheet):
'Save as single CSV file, handling column names as first line.'
with p.open_text(mode='w') as fp:
cw = csv.writer(fp, **csvoptions())
colnames = [col.name for col in sheet.visibleCols]
if ''.join(colnames):
cw.writerow(colnames)
for r in Progress(sheet.rows, 'saving'):
cw.writerow([col.getDisplayValue(r) for col in sheet.visibleCols]) | python | def save_csv(p, sheet):
'Save as single CSV file, handling column names as first line.'
with p.open_text(mode='w') as fp:
cw = csv.writer(fp, **csvoptions())
colnames = [col.name for col in sheet.visibleCols]
if ''.join(colnames):
cw.writerow(colnames)
for r in Progress(sheet.rows, 'saving'):
cw.writerow([col.getDisplayValue(r) for col in sheet.visibleCols]) | [
"def",
"save_csv",
"(",
"p",
",",
"sheet",
")",
":",
"with",
"p",
".",
"open_text",
"(",
"mode",
"=",
"'w'",
")",
"as",
"fp",
":",
"cw",
"=",
"csv",
".",
"writer",
"(",
"fp",
",",
"*",
"*",
"csvoptions",
"(",
")",
")",
"colnames",
"=",
"[",
"... | Save as single CSV file, handling column names as first line. | [
"Save",
"as",
"single",
"CSV",
"file",
"handling",
"column",
"names",
"as",
"first",
"line",
"."
] | 32771e0cea6c24fc7902683d14558391395c591f | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/loaders/csv.py#L91-L99 |
229,778 | saulpw/visidata | snippets/usd.py | currency_multiplier | def currency_multiplier(src_currency, dest_currency):
'returns equivalent value in USD for an amt of currency_code'
if src_currency == 'USD':
return 1.0
usd_mult = currency_rates()[src_currency]
if dest_currency == 'USD':
return usd_mult
return usd_mult/currency_rates()[dest_currency] | python | def currency_multiplier(src_currency, dest_currency):
'returns equivalent value in USD for an amt of currency_code'
if src_currency == 'USD':
return 1.0
usd_mult = currency_rates()[src_currency]
if dest_currency == 'USD':
return usd_mult
return usd_mult/currency_rates()[dest_currency] | [
"def",
"currency_multiplier",
"(",
"src_currency",
",",
"dest_currency",
")",
":",
"if",
"src_currency",
"==",
"'USD'",
":",
"return",
"1.0",
"usd_mult",
"=",
"currency_rates",
"(",
")",
"[",
"src_currency",
"]",
"if",
"dest_currency",
"==",
"'USD'",
":",
"ret... | returns equivalent value in USD for an amt of currency_code | [
"returns",
"equivalent",
"value",
"in",
"USD",
"for",
"an",
"amt",
"of",
"currency_code"
] | 32771e0cea6c24fc7902683d14558391395c591f | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/snippets/usd.py#L27-L34 |
229,779 | saulpw/visidata | visidata/slide.py | moveVisibleCol | def moveVisibleCol(sheet, fromVisColIdx, toVisColIdx):
'Move visible column to another visible index in sheet.'
toVisColIdx = min(max(toVisColIdx, 0), sheet.nVisibleCols)
fromColIdx = sheet.columns.index(sheet.visibleCols[fromVisColIdx])
toColIdx = sheet.columns.index(sheet.visibleCols[toVisColIdx])
moveListItem(sheet.columns, fromColIdx, toColIdx)
return toVisColIdx | python | def moveVisibleCol(sheet, fromVisColIdx, toVisColIdx):
'Move visible column to another visible index in sheet.'
toVisColIdx = min(max(toVisColIdx, 0), sheet.nVisibleCols)
fromColIdx = sheet.columns.index(sheet.visibleCols[fromVisColIdx])
toColIdx = sheet.columns.index(sheet.visibleCols[toVisColIdx])
moveListItem(sheet.columns, fromColIdx, toColIdx)
return toVisColIdx | [
"def",
"moveVisibleCol",
"(",
"sheet",
",",
"fromVisColIdx",
",",
"toVisColIdx",
")",
":",
"toVisColIdx",
"=",
"min",
"(",
"max",
"(",
"toVisColIdx",
",",
"0",
")",
",",
"sheet",
".",
"nVisibleCols",
")",
"fromColIdx",
"=",
"sheet",
".",
"columns",
".",
... | Move visible column to another visible index in sheet. | [
"Move",
"visible",
"column",
"to",
"another",
"visible",
"index",
"in",
"sheet",
"."
] | 32771e0cea6c24fc7902683d14558391395c591f | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/slide.py#L19-L25 |
229,780 | saulpw/visidata | visidata/utils.py | moveListItem | def moveListItem(L, fromidx, toidx):
"Move element within list `L` and return element's new index."
r = L.pop(fromidx)
L.insert(toidx, r)
return toidx | python | def moveListItem(L, fromidx, toidx):
"Move element within list `L` and return element's new index."
r = L.pop(fromidx)
L.insert(toidx, r)
return toidx | [
"def",
"moveListItem",
"(",
"L",
",",
"fromidx",
",",
"toidx",
")",
":",
"r",
"=",
"L",
".",
"pop",
"(",
"fromidx",
")",
"L",
".",
"insert",
"(",
"toidx",
",",
"r",
")",
"return",
"toidx"
] | Move element within list `L` and return element's new index. | [
"Move",
"element",
"within",
"list",
"L",
"and",
"return",
"element",
"s",
"new",
"index",
"."
] | 32771e0cea6c24fc7902683d14558391395c591f | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/utils.py#L7-L11 |
229,781 | saulpw/visidata | visidata/urlcache.py | urlcache | def urlcache(url, cachesecs=24*60*60):
'Returns Path object to local cache of url contents.'
p = Path(os.path.join(options.visidata_dir, 'cache', urllib.parse.quote(url, safe='')))
if p.exists():
secs = time.time() - p.stat().st_mtime
if secs < cachesecs:
return p
if not p.parent.exists():
os.makedirs(p.parent.resolve(), exist_ok=True)
assert p.parent.is_dir(), p.parent
req = urllib.request.Request(url, headers={'User-Agent': __version_info__})
with urllib.request.urlopen(req) as fp:
ret = fp.read().decode('utf-8').strip()
with p.open_text(mode='w') as fpout:
fpout.write(ret)
return p | python | def urlcache(url, cachesecs=24*60*60):
'Returns Path object to local cache of url contents.'
p = Path(os.path.join(options.visidata_dir, 'cache', urllib.parse.quote(url, safe='')))
if p.exists():
secs = time.time() - p.stat().st_mtime
if secs < cachesecs:
return p
if not p.parent.exists():
os.makedirs(p.parent.resolve(), exist_ok=True)
assert p.parent.is_dir(), p.parent
req = urllib.request.Request(url, headers={'User-Agent': __version_info__})
with urllib.request.urlopen(req) as fp:
ret = fp.read().decode('utf-8').strip()
with p.open_text(mode='w') as fpout:
fpout.write(ret)
return p | [
"def",
"urlcache",
"(",
"url",
",",
"cachesecs",
"=",
"24",
"*",
"60",
"*",
"60",
")",
":",
"p",
"=",
"Path",
"(",
"os",
".",
"path",
".",
"join",
"(",
"options",
".",
"visidata_dir",
",",
"'cache'",
",",
"urllib",
".",
"parse",
".",
"quote",
"("... | Returns Path object to local cache of url contents. | [
"Returns",
"Path",
"object",
"to",
"local",
"cache",
"of",
"url",
"contents",
"."
] | 32771e0cea6c24fc7902683d14558391395c591f | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/urlcache.py#L10-L29 |
229,782 | saulpw/visidata | visidata/data.py | fillNullValues | def fillNullValues(col, rows):
'Fill null cells in col with the previous non-null value'
lastval = None
nullfunc = isNullFunc()
n = 0
rowsToFill = list(rows)
for r in Progress(col.sheet.rows, 'filling'): # loop over all rows
try:
val = col.getValue(r)
except Exception as e:
val = e
if nullfunc(val) and r in rowsToFill:
if lastval:
col.setValue(r, lastval)
n += 1
else:
lastval = val
col.recalc()
status("filled %d values" % n) | python | def fillNullValues(col, rows):
'Fill null cells in col with the previous non-null value'
lastval = None
nullfunc = isNullFunc()
n = 0
rowsToFill = list(rows)
for r in Progress(col.sheet.rows, 'filling'): # loop over all rows
try:
val = col.getValue(r)
except Exception as e:
val = e
if nullfunc(val) and r in rowsToFill:
if lastval:
col.setValue(r, lastval)
n += 1
else:
lastval = val
col.recalc()
status("filled %d values" % n) | [
"def",
"fillNullValues",
"(",
"col",
",",
"rows",
")",
":",
"lastval",
"=",
"None",
"nullfunc",
"=",
"isNullFunc",
"(",
")",
"n",
"=",
"0",
"rowsToFill",
"=",
"list",
"(",
"rows",
")",
"for",
"r",
"in",
"Progress",
"(",
"col",
".",
"sheet",
".",
"r... | Fill null cells in col with the previous non-null value | [
"Fill",
"null",
"cells",
"in",
"col",
"with",
"the",
"previous",
"non",
"-",
"null",
"value"
] | 32771e0cea6c24fc7902683d14558391395c591f | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/data.py#L60-L80 |
229,783 | saulpw/visidata | visidata/data.py | saveSheets | def saveSheets(fn, *vsheets, confirm_overwrite=False):
'Save sheet `vs` with given filename `fn`.'
givenpath = Path(fn)
# determine filetype to save as
filetype = ''
basename, ext = os.path.splitext(fn)
if ext:
filetype = ext[1:]
filetype = filetype or options.save_filetype
if len(vsheets) > 1:
if not fn.endswith('/'): # forcibly specify save individual files into directory by ending path with /
savefunc = getGlobals().get('multisave_' + filetype, None)
if savefunc:
# use specific multisave function
return savefunc(givenpath, *vsheets)
# more than one sheet; either no specific multisave for save filetype, or path ends with /
# save as individual files in the givenpath directory
if not givenpath.exists():
try:
os.makedirs(givenpath.resolve(), exist_ok=True)
except FileExistsError:
pass
assert givenpath.is_dir(), filetype + ' cannot save multiple sheets to non-dir'
# get save function to call
savefunc = getGlobals().get('save_' + filetype) or fail('no function save_'+filetype)
if givenpath.exists():
if confirm_overwrite:
confirm('%s already exists. overwrite? ' % fn)
status('saving %s sheets to %s' % (len(vsheets), givenpath.fqpn))
for vs in vsheets:
p = Path(os.path.join(givenpath.fqpn, vs.name+'.'+filetype))
savefunc(p, vs)
else:
# get save function to call
savefunc = getGlobals().get('save_' + filetype) or fail('no function save_'+filetype)
if givenpath.exists():
if confirm_overwrite:
confirm('%s already exists. overwrite? ' % fn)
status('saving to %s as %s' % (givenpath.fqpn, filetype))
savefunc(givenpath, vsheets[0]) | python | def saveSheets(fn, *vsheets, confirm_overwrite=False):
'Save sheet `vs` with given filename `fn`.'
givenpath = Path(fn)
# determine filetype to save as
filetype = ''
basename, ext = os.path.splitext(fn)
if ext:
filetype = ext[1:]
filetype = filetype or options.save_filetype
if len(vsheets) > 1:
if not fn.endswith('/'): # forcibly specify save individual files into directory by ending path with /
savefunc = getGlobals().get('multisave_' + filetype, None)
if savefunc:
# use specific multisave function
return savefunc(givenpath, *vsheets)
# more than one sheet; either no specific multisave for save filetype, or path ends with /
# save as individual files in the givenpath directory
if not givenpath.exists():
try:
os.makedirs(givenpath.resolve(), exist_ok=True)
except FileExistsError:
pass
assert givenpath.is_dir(), filetype + ' cannot save multiple sheets to non-dir'
# get save function to call
savefunc = getGlobals().get('save_' + filetype) or fail('no function save_'+filetype)
if givenpath.exists():
if confirm_overwrite:
confirm('%s already exists. overwrite? ' % fn)
status('saving %s sheets to %s' % (len(vsheets), givenpath.fqpn))
for vs in vsheets:
p = Path(os.path.join(givenpath.fqpn, vs.name+'.'+filetype))
savefunc(p, vs)
else:
# get save function to call
savefunc = getGlobals().get('save_' + filetype) or fail('no function save_'+filetype)
if givenpath.exists():
if confirm_overwrite:
confirm('%s already exists. overwrite? ' % fn)
status('saving to %s as %s' % (givenpath.fqpn, filetype))
savefunc(givenpath, vsheets[0]) | [
"def",
"saveSheets",
"(",
"fn",
",",
"*",
"vsheets",
",",
"confirm_overwrite",
"=",
"False",
")",
":",
"givenpath",
"=",
"Path",
"(",
"fn",
")",
"# determine filetype to save as",
"filetype",
"=",
"''",
"basename",
",",
"ext",
"=",
"os",
".",
"path",
".",
... | Save sheet `vs` with given filename `fn`. | [
"Save",
"sheet",
"vs",
"with",
"given",
"filename",
"fn",
"."
] | 32771e0cea6c24fc7902683d14558391395c591f | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/data.py#L152-L202 |
229,784 | saulpw/visidata | visidata/data.py | open_txt | def open_txt(p):
'Create sheet from `.txt` file at Path `p`, checking whether it is TSV.'
with p.open_text() as fp:
if options.delimiter in next(fp): # peek at the first line
return open_tsv(p) # TSV often have .txt extension
return TextSheet(p.name, p) | python | def open_txt(p):
'Create sheet from `.txt` file at Path `p`, checking whether it is TSV.'
with p.open_text() as fp:
if options.delimiter in next(fp): # peek at the first line
return open_tsv(p) # TSV often have .txt extension
return TextSheet(p.name, p) | [
"def",
"open_txt",
"(",
"p",
")",
":",
"with",
"p",
".",
"open_text",
"(",
")",
"as",
"fp",
":",
"if",
"options",
".",
"delimiter",
"in",
"next",
"(",
"fp",
")",
":",
"# peek at the first line",
"return",
"open_tsv",
"(",
"p",
")",
"# TSV often have .txt... | Create sheet from `.txt` file at Path `p`, checking whether it is TSV. | [
"Create",
"sheet",
"from",
".",
"txt",
"file",
"at",
"Path",
"p",
"checking",
"whether",
"it",
"is",
"TSV",
"."
] | 32771e0cea6c24fc7902683d14558391395c591f | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/data.py#L276-L281 |
229,785 | saulpw/visidata | visidata/data.py | loadInternalSheet | def loadInternalSheet(klass, p, **kwargs):
'Load internal sheet of given klass. Internal sheets are always tsv.'
vs = klass(p.name, source=p, **kwargs)
options._set('encoding', 'utf8', vs)
if p.exists():
vd.sheets.insert(0, vs)
vs.reload.__wrapped__(vs)
vd.sheets.pop(0)
return vs | python | def loadInternalSheet(klass, p, **kwargs):
'Load internal sheet of given klass. Internal sheets are always tsv.'
vs = klass(p.name, source=p, **kwargs)
options._set('encoding', 'utf8', vs)
if p.exists():
vd.sheets.insert(0, vs)
vs.reload.__wrapped__(vs)
vd.sheets.pop(0)
return vs | [
"def",
"loadInternalSheet",
"(",
"klass",
",",
"p",
",",
"*",
"*",
"kwargs",
")",
":",
"vs",
"=",
"klass",
"(",
"p",
".",
"name",
",",
"source",
"=",
"p",
",",
"*",
"*",
"kwargs",
")",
"options",
".",
"_set",
"(",
"'encoding'",
",",
"'utf8'",
","... | Load internal sheet of given klass. Internal sheets are always tsv. | [
"Load",
"internal",
"sheet",
"of",
"given",
"klass",
".",
"Internal",
"sheets",
"are",
"always",
"tsv",
"."
] | 32771e0cea6c24fc7902683d14558391395c591f | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/data.py#L296-L304 |
229,786 | saulpw/visidata | visidata/namedlist.py | namedlist | def namedlist(objname, fieldnames):
'like namedtuple but editable'
class NamedListTemplate(list):
__name__ = objname
_fields = fieldnames
def __init__(self, L=None, **kwargs):
if L is None:
L = [None]*len(fieldnames)
super().__init__(L)
for k, v in kwargs.items():
setattr(self, k, v)
@classmethod
def length(cls):
return len(cls._fields)
for i, attrname in enumerate(fieldnames):
# create property getter/setter for each field
setattr(NamedListTemplate, attrname, property(operator.itemgetter(i), itemsetter(i)))
return NamedListTemplate | python | def namedlist(objname, fieldnames):
'like namedtuple but editable'
class NamedListTemplate(list):
__name__ = objname
_fields = fieldnames
def __init__(self, L=None, **kwargs):
if L is None:
L = [None]*len(fieldnames)
super().__init__(L)
for k, v in kwargs.items():
setattr(self, k, v)
@classmethod
def length(cls):
return len(cls._fields)
for i, attrname in enumerate(fieldnames):
# create property getter/setter for each field
setattr(NamedListTemplate, attrname, property(operator.itemgetter(i), itemsetter(i)))
return NamedListTemplate | [
"def",
"namedlist",
"(",
"objname",
",",
"fieldnames",
")",
":",
"class",
"NamedListTemplate",
"(",
"list",
")",
":",
"__name__",
"=",
"objname",
"_fields",
"=",
"fieldnames",
"def",
"__init__",
"(",
"self",
",",
"L",
"=",
"None",
",",
"*",
"*",
"kwargs"... | like namedtuple but editable | [
"like",
"namedtuple",
"but",
"editable"
] | 32771e0cea6c24fc7902683d14558391395c591f | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/namedlist.py#L10-L31 |
229,787 | saulpw/visidata | visidata/loaders/pcap.py | Host.get_by_ip | def get_by_ip(cls, ip):
'Returns Host instance for the given ip address.'
ret = cls.hosts_by_ip.get(ip)
if ret is None:
ret = cls.hosts_by_ip[ip] = [Host(ip)]
return ret | python | def get_by_ip(cls, ip):
'Returns Host instance for the given ip address.'
ret = cls.hosts_by_ip.get(ip)
if ret is None:
ret = cls.hosts_by_ip[ip] = [Host(ip)]
return ret | [
"def",
"get_by_ip",
"(",
"cls",
",",
"ip",
")",
":",
"ret",
"=",
"cls",
".",
"hosts_by_ip",
".",
"get",
"(",
"ip",
")",
"if",
"ret",
"is",
"None",
":",
"ret",
"=",
"cls",
".",
"hosts_by_ip",
"[",
"ip",
"]",
"=",
"[",
"Host",
"(",
"ip",
")",
"... | Returns Host instance for the given ip address. | [
"Returns",
"Host",
"instance",
"for",
"the",
"given",
"ip",
"address",
"."
] | 32771e0cea6c24fc7902683d14558391395c591f | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/loaders/pcap.py#L150-L155 |
229,788 | saulpw/visidata | visidata/_profile.py | threadProfileCode | def threadProfileCode(func, *args, **kwargs):
'Toplevel thread profile wrapper.'
with ThreadProfiler(threading.current_thread()) as prof:
try:
prof.thread.status = threadProfileCode.__wrapped__(func, *args, **kwargs)
except EscapeException as e:
prof.thread.status = e | python | def threadProfileCode(func, *args, **kwargs):
'Toplevel thread profile wrapper.'
with ThreadProfiler(threading.current_thread()) as prof:
try:
prof.thread.status = threadProfileCode.__wrapped__(func, *args, **kwargs)
except EscapeException as e:
prof.thread.status = e | [
"def",
"threadProfileCode",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"ThreadProfiler",
"(",
"threading",
".",
"current_thread",
"(",
")",
")",
"as",
"prof",
":",
"try",
":",
"prof",
".",
"thread",
".",
"status",
"=",
... | Toplevel thread profile wrapper. | [
"Toplevel",
"thread",
"profile",
"wrapper",
"."
] | 32771e0cea6c24fc7902683d14558391395c591f | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/_profile.py#L36-L42 |
229,789 | saulpw/visidata | visidata/metasheets.py | combineColumns | def combineColumns(cols):
'Return Column object formed by joining fields in given columns.'
return Column("+".join(c.name for c in cols),
getter=lambda col,row,cols=cols,ch=' ': ch.join(c.getDisplayValue(row) for c in cols)) | python | def combineColumns(cols):
'Return Column object formed by joining fields in given columns.'
return Column("+".join(c.name for c in cols),
getter=lambda col,row,cols=cols,ch=' ': ch.join(c.getDisplayValue(row) for c in cols)) | [
"def",
"combineColumns",
"(",
"cols",
")",
":",
"return",
"Column",
"(",
"\"+\"",
".",
"join",
"(",
"c",
".",
"name",
"for",
"c",
"in",
"cols",
")",
",",
"getter",
"=",
"lambda",
"col",
",",
"row",
",",
"cols",
"=",
"cols",
",",
"ch",
"=",
"' '",... | Return Column object formed by joining fields in given columns. | [
"Return",
"Column",
"object",
"formed",
"by",
"joining",
"fields",
"in",
"given",
"columns",
"."
] | 32771e0cea6c24fc7902683d14558391395c591f | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/metasheets.py#L203-L206 |
229,790 | saulpw/visidata | visidata/asyncthread.py | cancelThread | def cancelThread(*threads, exception=EscapeException):
'Raise exception on another thread.'
for t in threads:
ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(t.ident), ctypes.py_object(exception)) | python | def cancelThread(*threads, exception=EscapeException):
'Raise exception on another thread.'
for t in threads:
ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(t.ident), ctypes.py_object(exception)) | [
"def",
"cancelThread",
"(",
"*",
"threads",
",",
"exception",
"=",
"EscapeException",
")",
":",
"for",
"t",
"in",
"threads",
":",
"ctypes",
".",
"pythonapi",
".",
"PyThreadState_SetAsyncExc",
"(",
"ctypes",
".",
"c_long",
"(",
"t",
".",
"ident",
")",
",",
... | Raise exception on another thread. | [
"Raise",
"exception",
"on",
"another",
"thread",
"."
] | 32771e0cea6c24fc7902683d14558391395c591f | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/asyncthread.py#L16-L19 |
229,791 | saulpw/visidata | plugins/vgit/git.py | git_all | def git_all(*args, git=maybeloggit, **kwargs):
'Return entire output of git command.'
try:
cmd = git(*args, _err_to_out=True, _decode_errors='replace', **kwargs)
out = cmd.stdout
except sh.ErrorReturnCode as e:
status('exit_code=%s' % e.exit_code)
out = e.stdout
out = out.decode('utf-8')
return out | python | def git_all(*args, git=maybeloggit, **kwargs):
'Return entire output of git command.'
try:
cmd = git(*args, _err_to_out=True, _decode_errors='replace', **kwargs)
out = cmd.stdout
except sh.ErrorReturnCode as e:
status('exit_code=%s' % e.exit_code)
out = e.stdout
out = out.decode('utf-8')
return out | [
"def",
"git_all",
"(",
"*",
"args",
",",
"git",
"=",
"maybeloggit",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"cmd",
"=",
"git",
"(",
"*",
"args",
",",
"_err_to_out",
"=",
"True",
",",
"_decode_errors",
"=",
"'replace'",
",",
"*",
"*",
"kwargs... | Return entire output of git command. | [
"Return",
"entire",
"output",
"of",
"git",
"command",
"."
] | 32771e0cea6c24fc7902683d14558391395c591f | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/plugins/vgit/git.py#L37-L49 |
229,792 | saulpw/visidata | plugins/vgit/git.py | git_lines | def git_lines(*args, git=maybeloggit, **kwargs):
'Generator of stdout lines from given git command'
err = io.StringIO()
try:
for line in git('--no-pager', _err=err, *args, _decode_errors='replace', _iter=True, _bg_exc=False, **kwargs):
yield line[:-1] # remove EOL
except sh.ErrorReturnCode as e:
status('exit_code=%s' % e.exit_code)
errlines = err.getvalue().splitlines()
if len(errlines) < 3:
for line in errlines:
status(line)
else:
vd().push(TextSheet('git ' + ' '.join(args), errlines)) | python | def git_lines(*args, git=maybeloggit, **kwargs):
'Generator of stdout lines from given git command'
err = io.StringIO()
try:
for line in git('--no-pager', _err=err, *args, _decode_errors='replace', _iter=True, _bg_exc=False, **kwargs):
yield line[:-1] # remove EOL
except sh.ErrorReturnCode as e:
status('exit_code=%s' % e.exit_code)
errlines = err.getvalue().splitlines()
if len(errlines) < 3:
for line in errlines:
status(line)
else:
vd().push(TextSheet('git ' + ' '.join(args), errlines)) | [
"def",
"git_lines",
"(",
"*",
"args",
",",
"git",
"=",
"maybeloggit",
",",
"*",
"*",
"kwargs",
")",
":",
"err",
"=",
"io",
".",
"StringIO",
"(",
")",
"try",
":",
"for",
"line",
"in",
"git",
"(",
"'--no-pager'",
",",
"_err",
"=",
"err",
",",
"*",
... | Generator of stdout lines from given git command | [
"Generator",
"of",
"stdout",
"lines",
"from",
"given",
"git",
"command"
] | 32771e0cea6c24fc7902683d14558391395c591f | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/plugins/vgit/git.py#L51-L65 |
229,793 | saulpw/visidata | plugins/vgit/git.py | git_iter | def git_iter(sep, *args, git=maybeloggit, **kwargs):
'Generator of chunks of stdout from given git command, delineated by sep character'
bufsize = 512
err = io.StringIO()
chunks = []
try:
for data in git('--no-pager', *args, _decode_errors='replace', _out_bufsize=bufsize, _iter=True, _err=err, **kwargs):
while True:
i = data.find(sep)
if i < 0:
break
chunks.append(data[:i])
data = data[i+1:]
yield ''.join(chunks)
chunks.clear()
chunks.append(data)
except sh.ErrorReturnCode as e:
status('exit_code=%s' % e.exit_code)
r = ''.join(chunks)
if r:
yield r
errlines = err.getvalue().splitlines()
if len(errlines) < 3:
for line in errlines:
status(line)
else:
vd().push(TextSheet('git ' + ' '.join(args), errlines)) | python | def git_iter(sep, *args, git=maybeloggit, **kwargs):
'Generator of chunks of stdout from given git command, delineated by sep character'
bufsize = 512
err = io.StringIO()
chunks = []
try:
for data in git('--no-pager', *args, _decode_errors='replace', _out_bufsize=bufsize, _iter=True, _err=err, **kwargs):
while True:
i = data.find(sep)
if i < 0:
break
chunks.append(data[:i])
data = data[i+1:]
yield ''.join(chunks)
chunks.clear()
chunks.append(data)
except sh.ErrorReturnCode as e:
status('exit_code=%s' % e.exit_code)
r = ''.join(chunks)
if r:
yield r
errlines = err.getvalue().splitlines()
if len(errlines) < 3:
for line in errlines:
status(line)
else:
vd().push(TextSheet('git ' + ' '.join(args), errlines)) | [
"def",
"git_iter",
"(",
"sep",
",",
"*",
"args",
",",
"git",
"=",
"maybeloggit",
",",
"*",
"*",
"kwargs",
")",
":",
"bufsize",
"=",
"512",
"err",
"=",
"io",
".",
"StringIO",
"(",
")",
"chunks",
"=",
"[",
"]",
"try",
":",
"for",
"data",
"in",
"g... | Generator of chunks of stdout from given git command, delineated by sep character | [
"Generator",
"of",
"chunks",
"of",
"stdout",
"from",
"given",
"git",
"command",
"delineated",
"by",
"sep",
"character"
] | 32771e0cea6c24fc7902683d14558391395c591f | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/plugins/vgit/git.py#L68-L98 |
229,794 | saulpw/visidata | visidata/graph.py | InvertedCanvas.scaleY | def scaleY(self, canvasY):
'returns plotter y coordinate, with y-axis inverted'
plotterY = super().scaleY(canvasY)
return (self.plotviewBox.ymax-plotterY+4) | python | def scaleY(self, canvasY):
'returns plotter y coordinate, with y-axis inverted'
plotterY = super().scaleY(canvasY)
return (self.plotviewBox.ymax-plotterY+4) | [
"def",
"scaleY",
"(",
"self",
",",
"canvasY",
")",
":",
"plotterY",
"=",
"super",
"(",
")",
".",
"scaleY",
"(",
"canvasY",
")",
"return",
"(",
"self",
".",
"plotviewBox",
".",
"ymax",
"-",
"plotterY",
"+",
"4",
")"
] | returns plotter y coordinate, with y-axis inverted | [
"returns",
"plotter",
"y",
"coordinate",
"with",
"y",
"-",
"axis",
"inverted"
] | 32771e0cea6c24fc7902683d14558391395c591f | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/graph.py#L23-L26 |
229,795 | saulpw/visidata | visidata/path.py | Path.resolve | def resolve(self):
'Resolve pathname shell variables and ~userdir'
return os.path.expandvars(os.path.expanduser(self.fqpn)) | python | def resolve(self):
'Resolve pathname shell variables and ~userdir'
return os.path.expandvars(os.path.expanduser(self.fqpn)) | [
"def",
"resolve",
"(",
"self",
")",
":",
"return",
"os",
".",
"path",
".",
"expandvars",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"self",
".",
"fqpn",
")",
")"
] | Resolve pathname shell variables and ~userdir | [
"Resolve",
"pathname",
"shell",
"variables",
"and",
"~userdir"
] | 32771e0cea6c24fc7902683d14558391395c591f | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/path.py#L92-L94 |
229,796 | saulpw/visidata | visidata/canvas.py | Plotter.getPixelAttrRandom | def getPixelAttrRandom(self, x, y):
'weighted-random choice of attr at this pixel.'
c = list(attr for attr, rows in self.pixels[y][x].items()
for r in rows if attr and attr not in self.hiddenAttrs)
return random.choice(c) if c else 0 | python | def getPixelAttrRandom(self, x, y):
'weighted-random choice of attr at this pixel.'
c = list(attr for attr, rows in self.pixels[y][x].items()
for r in rows if attr and attr not in self.hiddenAttrs)
return random.choice(c) if c else 0 | [
"def",
"getPixelAttrRandom",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"c",
"=",
"list",
"(",
"attr",
"for",
"attr",
",",
"rows",
"in",
"self",
".",
"pixels",
"[",
"y",
"]",
"[",
"x",
"]",
".",
"items",
"(",
")",
"for",
"r",
"in",
"rows",
"i... | weighted-random choice of attr at this pixel. | [
"weighted",
"-",
"random",
"choice",
"of",
"attr",
"at",
"this",
"pixel",
"."
] | 32771e0cea6c24fc7902683d14558391395c591f | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/canvas.py#L181-L185 |
229,797 | saulpw/visidata | visidata/canvas.py | Plotter.getPixelAttrMost | def getPixelAttrMost(self, x, y):
'most common attr at this pixel.'
r = self.pixels[y][x]
c = sorted((len(rows), attr, rows) for attr, rows in list(r.items()) if attr and attr not in self.hiddenAttrs)
if not c:
return 0
_, attr, rows = c[-1]
if isinstance(self.source, BaseSheet) and anySelected(self.source, rows):
attr = CursesAttr(attr, 8).update_attr(colors.color_graph_selected, 10).attr
return attr | python | def getPixelAttrMost(self, x, y):
'most common attr at this pixel.'
r = self.pixels[y][x]
c = sorted((len(rows), attr, rows) for attr, rows in list(r.items()) if attr and attr not in self.hiddenAttrs)
if not c:
return 0
_, attr, rows = c[-1]
if isinstance(self.source, BaseSheet) and anySelected(self.source, rows):
attr = CursesAttr(attr, 8).update_attr(colors.color_graph_selected, 10).attr
return attr | [
"def",
"getPixelAttrMost",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"r",
"=",
"self",
".",
"pixels",
"[",
"y",
"]",
"[",
"x",
"]",
"c",
"=",
"sorted",
"(",
"(",
"len",
"(",
"rows",
")",
",",
"attr",
",",
"rows",
")",
"for",
"attr",
",",
"... | most common attr at this pixel. | [
"most",
"common",
"attr",
"at",
"this",
"pixel",
"."
] | 32771e0cea6c24fc7902683d14558391395c591f | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/canvas.py#L187-L196 |
229,798 | saulpw/visidata | visidata/canvas.py | Plotter.rowsWithin | def rowsWithin(self, bbox):
'return list of deduped rows within bbox'
ret = {}
for y in range(bbox.ymin, bbox.ymax+1):
for x in range(bbox.xmin, bbox.xmax+1):
for attr, rows in self.pixels[y][x].items():
if attr not in self.hiddenAttrs:
for r in rows:
ret[id(r)] = r
return list(ret.values()) | python | def rowsWithin(self, bbox):
'return list of deduped rows within bbox'
ret = {}
for y in range(bbox.ymin, bbox.ymax+1):
for x in range(bbox.xmin, bbox.xmax+1):
for attr, rows in self.pixels[y][x].items():
if attr not in self.hiddenAttrs:
for r in rows:
ret[id(r)] = r
return list(ret.values()) | [
"def",
"rowsWithin",
"(",
"self",
",",
"bbox",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"y",
"in",
"range",
"(",
"bbox",
".",
"ymin",
",",
"bbox",
".",
"ymax",
"+",
"1",
")",
":",
"for",
"x",
"in",
"range",
"(",
"bbox",
".",
"xmin",
",",
"bbox"... | return list of deduped rows within bbox | [
"return",
"list",
"of",
"deduped",
"rows",
"within",
"bbox"
] | 32771e0cea6c24fc7902683d14558391395c591f | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/canvas.py#L205-L214 |
229,799 | saulpw/visidata | visidata/canvas.py | Canvas.setCursorSize | def setCursorSize(self, p):
'sets width based on diagonal corner p'
self.cursorBox = BoundingBox(self.cursorBox.xmin, self.cursorBox.ymin, p.x, p.y)
self.cursorBox.w = max(self.cursorBox.w, self.canvasCharWidth)
self.cursorBox.h = max(self.cursorBox.h, self.canvasCharHeight) | python | def setCursorSize(self, p):
'sets width based on diagonal corner p'
self.cursorBox = BoundingBox(self.cursorBox.xmin, self.cursorBox.ymin, p.x, p.y)
self.cursorBox.w = max(self.cursorBox.w, self.canvasCharWidth)
self.cursorBox.h = max(self.cursorBox.h, self.canvasCharHeight) | [
"def",
"setCursorSize",
"(",
"self",
",",
"p",
")",
":",
"self",
".",
"cursorBox",
"=",
"BoundingBox",
"(",
"self",
".",
"cursorBox",
".",
"xmin",
",",
"self",
".",
"cursorBox",
".",
"ymin",
",",
"p",
".",
"x",
",",
"p",
".",
"y",
")",
"self",
".... | sets width based on diagonal corner p | [
"sets",
"width",
"based",
"on",
"diagonal",
"corner",
"p"
] | 32771e0cea6c24fc7902683d14558391395c591f | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/canvas.py#L371-L375 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.