Python io.BytesIO() Examples

The following are code examples for showing how to use io.BytesIO(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: AboveTustin   Author: kevinabrandon   File: screenshot.py    MIT License 9 votes vote down vote up
def screenshot(self, name):
        '''
        screenshot()
        Takes a screenshot of the browser
        '''
        if do_crop:
            print('cropping screenshot')
            #  Grab screenshot rather than saving
            im = self.browser.get_screenshot_as_png()
            im = Image.open(BytesIO(im))

            #  Crop to specifications
            im = im.crop((crop_x, crop_y, crop_width, crop_height))
            im.save(name)
        else:
            self.browser.save_screenshot(name)
        print("success saving screenshot: %s" % name)
        return name 
Example 2
Project: badge-o-matic   Author: markuslindenberg   File: online.py    BSD 2-Clause "Simplified" License 7 votes vote down vote up
def main():
	pdf = BytesIO()

	# Find all IPv6 addresses with global scope
	ips = [dict(a['attrs'])['IFA_ADDRESS'] for a in IPRoute().get_addr() if a['scope'] == 0 and a['family'] == 10]

	if ips:
		c = Canvas(pdf, pagesize=(PAGE_W, PAGE_H))
		hello(c, 'http://[%s]/badge' % ips[0])
	else:
		# ToDo: Legacy IP bild
		c = Canvas(pdf, pagesize=(PAGE_W, PAGE_H))
		
	c.showPage()
	c.save()
	lpr = subprocess.Popen(['lpr', '-P', PRINTER], stdin=subprocess.PIPE)
	lpr.communicate(pdf.getvalue())
	if lpr.returncode != 0:
		pass 
Example 3
Project: fs_image   Author: facebookincubator   File: open_url.py    MIT License 7 votes vote down vote up
def open_url(url: str) -> Iterator[BytesIO]:
    parsed_url = requests.utils.urlparse(url)
    if parsed_url.scheme == 'file':
        assert parsed_url.netloc == '', f'Bad file URL: {url}'
        with open(requests.utils.unquote(parsed_url.path), 'rb') as infile:
            yield infile
    elif parsed_url.scheme in ['http', 'https']:
        # verify=True is the default, but I want to be explicit about HTTPS,
        # since this function receives GPG key material.
        with requests.get(url, stream=True, verify=True) as r:
            r.raise_for_status()
            yield r.raw  # A file-like `io`-style object for the HTTP stream
            if r.raw.isclosed():   # Proxy for "all data was consumed"
                # Sadly, requests 2.x does not verify content-length :/
                # We could check r.raw.length_remaining, likely equivalent.
                actual_size = r.raw.tell()
                header_size = int(r.headers['content-length'])
                assert actual_size == header_size, (actual_size, header_size)
    else:  # pragma: no cover
        raise RuntimeError(f'Unknown URL scheme in {url}') 
Example 4
Project: odorik   Author: nijel   File: test_main.py    GNU General Public License v3.0 6 votes vote down vote up
def execute(args, binary=False, settings=None, stdout=None):
    """Execute command and return output."""
    if settings is None:
        settings = ()
    elif not settings:
        settings = None
    if binary and sys.version_info < (3, 0):
        output = BytesIO()
    else:
        output = StringIO()
    backup = sys.stdout
    try:
        sys.stdout = output
        if stdout:
            stdout = output
        main(args=args, settings=settings, stdout=stdout)
    finally:
        sys.stdout = backup
    return output.getvalue() 
Example 5
Project: incubator-spot   Author: apache   File: serializer.py    Apache License 2.0 6 votes vote down vote up
def deserialize(rawbytes):
    '''
        Deserialize given bytes according to the supported Avro schema.

    :param rawbytes: A buffered I/O implementation using an in-memory bytes buffer.
    :returns       : List of ``str`` objects, extracted from the binary stream.
    :rtype         : ``list``
    '''
    decoder = avro.io.BinaryDecoder(io.BytesIO(rawbytes))
    reader  = avro.io.DatumReader(avro.schema.parse(AVSC))

    try: return reader.read(decoder)[list.__name__]
    except Exception as exc:
        logging.getLogger('SPOT.INGEST.COMMON.SERIALIZER')\
            .error('[{0}] {1}'.format(exc.__class__.__name__, exc.message))

    return [] 
Example 6
Project: incubator-spot   Author: apache   File: serializer.py    Apache License 2.0 6 votes vote down vote up
def serialize(value):
    '''
        Convert a ``list`` object to an avro-encoded format.

    :param value: List of ``str`` objects.
    :returns    : A buffered I/O implementation using an in-memory bytes buffer.
    :rtype      : ``str``
    '''
    writer   = avro.io.DatumWriter(avro.schema.parse(AVSC))
    rawbytes = io.BytesIO()

    try:
        writer.write({ list.__name__: value }, avro.io.BinaryEncoder(rawbytes))
        return rawbytes
    except avro.io.AvroTypeException:
        logging.getLogger('SPOT.INGEST.COMMON.SERIALIZER')\
            .error('The type of ``{0}`` is not supported by the Avro schema.'
            .format(type(value).__name__))

    return None 
Example 7
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def check_read_with_bad_crc(self, compression):
        """Tests that files with bad CRCs raise a BadZipfile exception when read."""
        zipdata = self.zips_with_bad_crc[compression]

        # Using ZipFile.read()
        with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
            self.assertRaises(zipfile.BadZipfile, zipf.read, 'afile')

        # Using ZipExtFile.read()
        with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
            with zipf.open('afile', 'r') as corrupt_file:
                self.assertRaises(zipfile.BadZipfile, corrupt_file.read)

        # Same with small reads (in order to exercise the buffering logic)
        with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
            with zipf.open('afile', 'r') as corrupt_file:
                corrupt_file.MIN_READ_SIZE = 2
                with self.assertRaises(zipfile.BadZipfile):
                    while corrupt_file.read(2):
                        pass 
Example 8
Project: pyblish-win   Author: pyblish   File: test_aifc.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_read_written(self):
        def read_written(self, what):
            f = io.BytesIO()
            getattr(aifc, '_write_' + what)(f, x)
            f.seek(0)
            return getattr(aifc, '_read_' + what)(f)
        for x in (-1, 0, 0.1, 1):
            self.assertEqual(read_written(x, 'float'), x)
        for x in (float('NaN'), float('Inf')):
            self.assertEqual(read_written(x, 'float'), aifc._HUGE_VAL)
        for x in ('', 'foo', 'a' * 255):
            self.assertEqual(read_written(x, 'string'), x)
        for x in (-0x7FFFFFFF, -1, 0, 1, 0x7FFFFFFF):
            self.assertEqual(read_written(x, 'long'), x)
        for x in (0, 1, 0xFFFFFFFF):
            self.assertEqual(read_written(x, 'ulong'), x)
        for x in (-0x7FFF, -1, 0, 1, 0x7FFF):
            self.assertEqual(read_written(x, 'short'), x)
        for x in (0, 1, 0xFFFF):
            self.assertEqual(read_written(x, 'ushort'), x) 
Example 9
Project: pyblish-win   Author: pyblish   File: test_aifc.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_write_params_singles(self):
        fout = aifc.open(io.BytesIO(), 'wb')
        fout.aifc()
        fout.setnchannels(1)
        fout.setsampwidth(2)
        fout.setframerate(3)
        fout.setnframes(4)
        fout.setcomptype('NONE', 'name')
        self.assertEqual(fout.getnchannels(), 1)
        self.assertEqual(fout.getsampwidth(), 2)
        self.assertEqual(fout.getframerate(), 3)
        self.assertEqual(fout.getnframes(), 0)
        self.assertEqual(fout.tell(), 0)
        self.assertEqual(fout.getcomptype(), 'NONE')
        self.assertEqual(fout.getcompname(), 'name')
        fout.writeframes('\x00' * 4 * fout.getsampwidth() * fout.getnchannels())
        self.assertEqual(fout.getnframes(), 4)
        self.assertEqual(fout.tell(), 4) 
Example 10
Project: slidoc   Author: mitotic   File: sdserver.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def uploadSession(self, uploadType, sessionNumber, fname1, fbody1, fname2='', fbody2='', modify=None, create=False, rollingOver=False, modimages='', deleteSlideNum=0):
        # Return null string on success or error message
        if self.previewActive():
            raise Exception('Already previewing session')

        if Options['debug']:
            print >> sys.stderr, 'sdserver.uploadSession:', uploadType, sessionNumber, fname1, len(fbody1 or ''), fname2, len(fbody2 or ''), modify, modimages, deleteSlideNum

        zfile = None
        if fname2:
            if not fname2.endswith('.zip'):
                return 'Invalid zip archive name %s; must have extension .zip' % fname2
            try:
                zfile = zipfile.ZipFile(io.BytesIO(fbody2))
            except Exception, excp:
                raise Exception('Error in loading zip archive: ' + str(excp)) 
Example 11
Project: slidoc   Author: mitotic   File: sdserver.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def imageUpload(self, sessionName, imageFile, fname, fbody, autonumber=None):
        if Options['debug']:
            print >> sys.stderr, 'ActionHandler:imageUpload', sessionName, imageFile, fname, autonumber, len(fbody)
        if not self.previewActive():
            raise tornado.web.HTTPError(404, log_message='CUSTOM:Not previewing session')
        if not imageFile:
            imgName = re.sub(r'[^\w,.+-]', '', fname.strip().replace(' ','_'))
            if imgName and not autonumber:
                imageFile = imgName
            else:
                imageFile = (md2md.IMAGE_FMT % self.previewState['new_image_number']) + os.path.splitext(fname)[1].lower()
            self.previewState['new_image_number'] += 1
        if not self.previewState['image_zipfile']:
            self.previewState['image_zipbytes'] = io.BytesIO()
            self.previewState['image_zipfile'] = zipfile.ZipFile(self.previewState['image_zipbytes'], 'a')
        imagePath = sessionName+'_images/' + imageFile
        self.previewState['image_zipfile'].writestr(imagePath, fbody)
        self.previewState['image_paths'][imageFile] = imagePath
        self.previewState['modimages'] = 'append'

        self.set_header('Content-Type', 'application/json')
        self.write( json.dumps( {'result': 'success', 'imageFile': imageFile} ) ) 
Example 12
Project: fs_image   Author: facebookincubator   File: render_subvols.py    MIT License 5 votes vote down vote up
def add_sendstream_to_subvol_set(subvols: SubvolumeSet, sendstream: bytes):
    parsed = parse_send_stream(BytesIO(sendstream))
    mutator = SubvolumeSetMutator.new(subvols, next(parsed))
    for i in parsed:
        mutator.apply_item(i)
    return mutator.subvolume


# We could do this on each `mutator.subvol` in `add_...`, but that would
# make `add_...` less reusable.  E.g., it would preclude cross-subvolume
# clone detection. 
Example 13
Project: fs_image   Author: facebookincubator   File: test_parse_dump.py    MIT License 5 votes vote down vote up
def _parse_lines_to_list(s: Sequence[bytes]) -> List[SendStreamItem]:
    return list(parse_btrfs_dump(io.BytesIO(b'\n'.join(s) + b'\n'))) 
Example 14
Project: fs_image   Author: facebookincubator   File: test_parse_send_stream.py    MIT License 5 votes vote down vote up
def _parse_stream_bytes(s: bytes) -> io.BytesIO:
    return parse_send_stream(io.BytesIO(s)) 
Example 15
Project: fs_image   Author: facebookincubator   File: test_parse_send_stream.py    MIT License 5 votes vote down vote up
def test_errors(self):
        with self.assertRaisesRegex(RuntimeError, "Magic b'xxx', not "):
            check_magic(io.BytesIO(b'xxx'))
        with self.assertRaisesRegex(RuntimeError, 'we require version 1'):
            check_version(io.BytesIO(b'abcd'))
        with self.assertRaisesRegex(RuntimeError, 'Not enough bytes'):
            file_unpack('<Q', io.BytesIO(b''))

        cmd_header_2_attrs = struct.pack(
            '<IHI',
            2 * (2 + 2 + 3),  # length excluding this header
            CommandKind.MKFILE.value,
            0,  # crc32c
        )

        with self.assertRaisesRegex(RuntimeError, 'CommandHead.* got 0 bytes'):
            read_command(io.BytesIO(cmd_header_2_attrs))

        with self.assertRaisesRegex(RuntimeError, 'AttributeH.* got 0 bytes'):
            read_attribute(io.BytesIO(struct.pack(
                '<HH',
                AttributeKind.PATH.value,
                3,  # length excluding this header -- error: we write no data!
            )))

        with self.assertRaisesRegex(RuntimeError, '\\.PATH occurred twice'):
            read_command(io.BytesIO(cmd_header_2_attrs + struct.pack(
                '<' + 'HH3s' * 2,  # 2 attributes

                AttributeKind.PATH.value,
                3,  # length excluding this header
                b'cat',

                AttributeKind.PATH.value,
                3,  # length excluding this header
                b'dog',
            ))) 
Example 16
Project: fs_image   Author: facebookincubator   File: test_parse_repodata.py    MIT License 5 votes vote down vote up
def _rpm_set(infile: BytesIO, rd: Repodata):
    rpms = set()
    with get_rpm_parser(rd) as parser:
        while True:  # Exercise feed-in-chunks behavior
            chunk = infile.read(127)  # Our repodatas are tiny
            if not chunk:
                break
            rpms.update(parser.feed(chunk))
    assert len(rpms) > 0  # we have no empty test repos
    return rpms 
Example 17
Project: fs_image   Author: facebookincubator   File: test_parse_repodata.py    MIT License 5 votes vote down vote up
def test_sqlite_edge_cases(self):
        for repo_path, repomd in find_test_repos(self.repos_root):
            _, sql_rd = self._xml_and_sqlite_primaries(repomd)
            with open(repo_path / sql_rd.location, 'rb') as sf:
                bz_data = sf.read()
            # Some in-the-wild primary SQLite dbs are .gz, while all of ours
            # are .bz2, so let's recompress.
            gzf = BytesIO()
            with gzip.GzipFile(fileobj=gzf, mode='wb') as gz_out:
                gz_out.write(bz2.decompress(bz_data))
            gzf.seek(0)
            self.assertEqual(
                _rpm_set(gzf, sql_rd._replace(location='X-primary.sqlite.gz')),
                _rpm_set(BytesIO(bz_data), sql_rd),
            )
            with self.assertRaisesRegex(RuntimeError, '^Unused data after '):
                _rpm_set(BytesIO(bz_data + b'oops'), sql_rd)
            with self.assertRaisesRegex(RuntimeError, 'archive is incomplete'):
                _rpm_set(BytesIO(bz_data[:-5]), sql_rd) 
Example 18
Project: fs_image   Author: facebookincubator   File: test_common.py    MIT License 5 votes vote down vote up
def test_read_chunks(self):
        self.assertEqual(
            [b'first', b'secon', b'd'],
            list(read_chunks(BytesIO(b'firstsecond'), 5)),
        ) 
Example 19
Project: fs_image   Author: facebookincubator   File: cli.py    MIT License 5 votes vote down vote up
def main(argv, from_file: BytesIO, to_file: BytesIO):
    parser = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    Storage.add_argparse_arg(
        parser, '--storage', required=True,
        help='JSON blob for creating a Storage instance.',
    )
    parser.add_argument('--debug', action='store_true', help='Log more?')
    subparsers = parser.add_subparsers(help='Sub-commands have help.')

    parser_get = subparsers.add_parser('get', help='Download blob to stdout')
    parser_get.add_argument('storage_id', help='String of the form KEY:ID')
    parser_get.set_defaults(to_file=to_file)
    parser_get.set_defaults(func=get)

    parser_put = subparsers.add_parser(
        'put', help='Write a blob from stdin, print its ID to stdout',
    )
    parser_put.set_defaults(from_file=from_file)
    parser_put.set_defaults(to_file=to_file)  # For the storage ID
    parser_put.set_defaults(func=put)

    args = parser.parse_args(argv)
    init_logging(debug=args.debug)

    args.func(args) 
Example 20
Project: paws   Author: funkybob   File: wsgi.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def form(self):
        if self.content_type == 'application/x-www-form-urlencoded':
            data = parse_qs(self.body)
        if self.content_type == 'multipart/form-data':
            data = parse_multipart(BytesIO(self.body), self.content_data)
        return MultiDict(data) 
Example 21
Project: paws   Author: funkybob   File: multipart.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, data, filename=''):
        self.data = data
        self.filename = filename
        self.file = BytesIO(data) 
Example 22
Project: paws   Author: funkybob   File: request.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def form(self):
        if self.content_type == 'application/x-www-form-urlencoded':
            data = parse_qs(self.body)
        if self.content_type == 'multipart/form-data':
            data = parse_multipart(BytesIO(b64decode(self.body)), self.content_data)
        return MultiDict(data) 
Example 23
Project: leapp-repository   Author: oamg   File: library.py    Apache License 2.0 5 votes vote down vote up
def extract_tgz64(s):
    stream = io.BytesIO(base64.b64decode(s))
    tar = tarfile.open(fileobj=stream, mode='r:gz')
    tar.extractall('/')
    tar.close() 
Example 24
Project: leapp-repository   Author: oamg   File: library.py    Apache License 2.0 5 votes vote down vote up
def get_tgz64(filenames):
    stream = io.BytesIO()
    tar = tarfile.open(fileobj=stream, mode='w:gz')
    for filename in filenames:
        if os.path.isfile(filename):
            tar.add(filename)
    tar.close()

    return base64.b64encode(stream.getvalue())


# Check services from the ntp packages for migration 
Example 25
Project: leapp-repository   Author: oamg   File: unit_test.py    Apache License 2.0 5 votes vote down vote up
def test_tgz64(monkeypatch):
    f, name = tempfile.mkstemp()
    os.close(f)
    tgz64 = library.get_tgz64([name])

    stream = io.BytesIO(base64.b64decode(tgz64))
    tar = tarfile.open(fileobj=stream, mode='r:gz')
    names = tar.getnames()

    tar.close()
    os.unlink(name)

    assert names == [name.lstrip('/')] 
Example 26
Project: clikit   Author: sdispater   File: string_input_stream.py    MIT License 5 votes vote down vote up
def __init__(self, string=""):  # type: (str) -> None
        self._stream = BytesIO()

        super(StringInputStream, self).__init__(self._stream)

        self.set(string) 
Example 27
Project: pyblish-win   Author: pyblish   File: pindent.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def complete_string(source, stepsize = STEPSIZE, tabsize = TABSIZE, expandtabs = EXPANDTABS):
    input = io.BytesIO(source)
    output = io.BytesIO()
    pi = PythonIndenter(input, output, stepsize, tabsize, expandtabs)
    pi.complete()
    return output.getvalue()
# end def complete_string 
Example 28
Project: pyblish-win   Author: pyblish   File: pindent.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def delete_string(source, stepsize = STEPSIZE, tabsize = TABSIZE, expandtabs = EXPANDTABS):
    input = io.BytesIO(source)
    output = io.BytesIO()
    pi = PythonIndenter(input, output, stepsize, tabsize, expandtabs)
    pi.delete()
    return output.getvalue()
# end def delete_string 
Example 29
Project: pyblish-win   Author: pyblish   File: pindent.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def reformat_string(source, stepsize = STEPSIZE, tabsize = TABSIZE, expandtabs = EXPANDTABS):
    input = io.BytesIO(source)
    output = io.BytesIO()
    pi = PythonIndenter(input, output, stepsize, tabsize, expandtabs)
    pi.reformat()
    return output.getvalue()
# end def reformat_string 
Example 30
Project: pyblish-win   Author: pyblish   File: test_gzip.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_read_with_extra(self):
        # Gzip data with an extra field
        gzdata = (b'\x1f\x8b\x08\x04\xb2\x17cQ\x02\xff'
                  b'\x05\x00Extra'
                  b'\x0bI-.\x01\x002\xd1Mx\x04\x00\x00\x00')
        with gzip.GzipFile(fileobj=io.BytesIO(gzdata)) as f:
            self.assertEqual(f.read(), b'Test') 
Example 31
Project: pyblish-win   Author: pyblish   File: test_imghdr.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_closed_file(self):
        stream = open(self.testfile, 'rb')
        stream.close()
        with self.assertRaises(ValueError) as cm:
            imghdr.what(stream)
        stream = io.BytesIO(self.testdata)
        stream.close()
        with self.assertRaises(ValueError) as cm:
            imghdr.what(stream) 
Example 32
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_files(test):
    yield TESTFN2
    with TemporaryFile() as f:
        yield f
        test.assertFalse(f.closed)
    with io.BytesIO() as f:
        yield f
        test.assertFalse(f.closed) 
Example 33
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_damaged_zipfile(self):
        """Check that zipfiles with missing bytes at the end raise BadZipFile."""
        # - Create a valid zip file
        fp = io.BytesIO()
        with zipfile.ZipFile(fp, mode="w") as zipf:
            zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
        zipfiledata = fp.getvalue()

        # - Now create copies of it missing the last N bytes and make sure
        #   a BadZipFile exception is raised when we try to open it
        for N in range(len(zipfiledata)):
            fp = io.BytesIO(zipfiledata[:N])
            self.assertRaises(zipfile.BadZipfile, zipfile.ZipFile, fp) 
Example 34
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_unsupported_compression(self):
        # data is declared as shrunk, but actually deflated
        data = (b'PK\x03\x04.\x00\x00\x00\x01\x00\xe4C\[email protected]\x00\x00\x00'
        b'\x00\x02\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00x\x03\x00PK\x01'
        b'\x02.\x03.\x00\x00\x00\x01\x00\xe4C\[email protected]\x00\x00\x00\x00\x02\x00\x00'
        b'\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
        b'\x80\x01\x00\x00\x00\x00xPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00'
        b'/\x00\x00\x00!\x00\x00\x00\x00\x00')
        with zipfile.ZipFile(io.BytesIO(data), 'r') as zipf:
            self.assertRaises(NotImplementedError, zipf.open, 'x') 
Example 35
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def check_testzip_with_bad_crc(self, compression):
        """Tests that files with bad CRCs return their name from testzip."""
        zipdata = self.zips_with_bad_crc[compression]

        with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
            # testzip returns the name of the first corrupt file, or None
            self.assertEqual('afile', zipf.testzip()) 
Example 36
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_zipfile_with_short_extra_field(self):
        """If an extra field in the header is less than 4 bytes, skip it."""
        zipdata = (
            b'PK\x03\x04\x14\x00\x00\x00\x00\x00\x93\x9b\[email protected]\x8b\x9e'
            b'\xd9\xd3\x01\x00\x00\x00\x01\x00\x00\x00\x03\x00\x03\x00ab'
            b'c\x00\x00\x00APK\x01\x02\x14\x03\x14\x00\x00\x00\x00'
            b'\x00\x93\x9b\[email protected]\x8b\x9e\xd9\xd3\x01\x00\x00\x00\x01\x00\x00'
            b'\x00\x03\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00'
            b'\x00\x00\x00abc\x00\x00PK\x05\x06\x00\x00\x00\x00'
            b'\x01\x00\x01\x003\x00\x00\x00%\x00\x00\x00\x00\x00'
        )
        with zipfile.ZipFile(io.BytesIO(zipdata), 'r') as zipf:
            # testzip returns the name of the first corrupt file, or None
            self.assertIsNone(zipf.testzip()) 
Example 37
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_deflated(self):
        for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
            self.zip_test(f, zipfile.ZIP_DEFLATED) 
Example 38
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_open_deflated(self):
        for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
            self.zip_open_test(f, zipfile.ZIP_DEFLATED) 
Example 39
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_random_open_deflated(self):
        for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
            self.zip_random_open_test(f, zipfile.ZIP_DEFLATED) 
Example 40
Project: pyblish-win   Author: pyblish   File: test_uuid.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_find_mac(self):
        data = '''\

fake hwaddr
cscotun0  Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
eth0      Link encap:Ethernet  HWaddr 12:34:56:78:90:ab
'''
        def mock_popen(cmd):
            return io.BytesIO(data)

        path = os.environ.get("PATH", os.defpath).split(os.pathsep)
        path.extend(('/sbin', '/usr/sbin'))
        for dir in path:
            executable = os.path.join(dir, 'ifconfig')
            if (os.path.exists(executable) and
                os.access(executable, os.F_OK | os.X_OK) and
                not os.path.isdir(executable)):
                break
        else:
            self.skipTest('requires ifconfig')

        with test_support.swap_attr(os, 'popen', mock_popen):
            mac = uuid._find_mac(
                command='ifconfig',
                args='',
                hw_identifiers=['hwaddr'],
                get_index=lambda x: x + 1,
            )
            self.assertEqual(mac, 0x1234567890ab) 
Example 41
Project: pyblish-win   Author: pyblish   File: test_aifc.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_read_raises(self):
        f = io.BytesIO('\x00')
        self.assertRaises(EOFError, aifc._read_ulong, f)
        self.assertRaises(EOFError, aifc._read_long, f)
        self.assertRaises(EOFError, aifc._read_ushort, f)
        self.assertRaises(EOFError, aifc._read_short, f) 
Example 42
Project: pyblish-win   Author: pyblish   File: test_aifc.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_write_long_string_raises(self):
        f = io.BytesIO()
        with self.assertRaises(ValueError):
            aifc._write_string(f, 'too long' * 255) 
Example 43
Project: pyblish-win   Author: pyblish   File: test_aifc.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_read_wrong_form(self):
        b1 = io.BytesIO('WRNG' + struct.pack('>L', 0))
        b2 = io.BytesIO('FORM' + struct.pack('>L', 4) + 'WRNG')
        self.assertRaises(aifc.Error, aifc.open, b1)
        self.assertRaises(aifc.Error, aifc.open, b2) 
Example 44
Project: pyblish-win   Author: pyblish   File: test_aifc.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_read_no_comm_chunk(self):
        b = io.BytesIO('FORM' + struct.pack('>L', 4) + 'AIFF')
        self.assertRaises(aifc.Error, aifc.open, b) 
Example 45
Project: pyblish-win   Author: pyblish   File: test_aifc.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_read_wrong_marks(self):
        b = 'FORM' + struct.pack('>L', 4) + 'AIFF'
        b += 'COMM' + struct.pack('>LhlhhLL', 18, 0, 0, 0, 0, 0, 0)
        b += 'SSND' + struct.pack('>L', 8) + '\x00' * 8
        b += 'MARK' + struct.pack('>LhB', 3, 1, 1)
        with captured_stdout() as s:
            f = aifc.open(io.BytesIO(b))
        self.assertEqual(s.getvalue(), 'Warning: MARK chunk contains '
                                       'only 0 markers instead of 1\n')
        self.assertEqual(f.getmarkers(), None) 
Example 46
Project: pyblish-win   Author: pyblish   File: test_aifc.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_read_comm_kludge_compname_even(self):
        b = 'FORM' + struct.pack('>L', 4) + 'AIFC'
        b += 'COMM' + struct.pack('>LhlhhLL', 18, 0, 0, 0, 0, 0, 0)
        b += 'NONE' + struct.pack('B', 4) + 'even' + '\x00'
        b += 'SSND' + struct.pack('>L', 8) + '\x00' * 8
        with captured_stdout() as s:
            f = aifc.open(io.BytesIO(b))
        self.assertEqual(s.getvalue(), 'Warning: bad COMM chunk size\n')
        self.assertEqual(f.getcompname(), 'even') 
Example 47
Project: pyblish-win   Author: pyblish   File: test_aifc.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_read_comm_kludge_compname_odd(self):
        b = 'FORM' + struct.pack('>L', 4) + 'AIFC'
        b += 'COMM' + struct.pack('>LhlhhLL', 18, 0, 0, 0, 0, 0, 0)
        b += 'NONE' + struct.pack('B', 3) + 'odd'
        b += 'SSND' + struct.pack('>L', 8) + '\x00' * 8
        with captured_stdout() as s:
            f = aifc.open(io.BytesIO(b))
        self.assertEqual(s.getvalue(), 'Warning: bad COMM chunk size\n')
        self.assertEqual(f.getcompname(), 'odd') 
Example 48
Project: pyblish-win   Author: pyblish   File: test_aifc.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_write_params_raises(self):
        fout = aifc.open(io.BytesIO(), 'wb')
        wrong_params = (0, 0, 0, 0, 'WRNG', '')
        self.assertRaises(aifc.Error, fout.setparams, wrong_params)
        self.assertRaises(aifc.Error, fout.getparams)
        self.assertRaises(aifc.Error, fout.setnchannels, 0)
        self.assertRaises(aifc.Error, fout.getnchannels)
        self.assertRaises(aifc.Error, fout.setsampwidth, 0)
        self.assertRaises(aifc.Error, fout.getsampwidth)
        self.assertRaises(aifc.Error, fout.setframerate, 0)
        self.assertRaises(aifc.Error, fout.getframerate)
        self.assertRaises(aifc.Error, fout.setcomptype, 'WRNG', '')
        fout.aiff()
        fout.setnchannels(1)
        fout.setsampwidth(1)
        fout.setframerate(1)
        fout.setnframes(1)
        fout.writeframes('\x00')
        self.assertRaises(aifc.Error, fout.setparams, (1, 1, 1, 1, 1, 1))
        self.assertRaises(aifc.Error, fout.setnchannels, 1)
        self.assertRaises(aifc.Error, fout.setsampwidth, 1)
        self.assertRaises(aifc.Error, fout.setframerate, 1)
        self.assertRaises(aifc.Error, fout.setnframes, 1)
        self.assertRaises(aifc.Error, fout.setcomptype, 'NONE', '')
        self.assertRaises(aifc.Error, fout.aiff)
        self.assertRaises(aifc.Error, fout.aifc) 
Example 49
Project: pyblish-win   Author: pyblish   File: test_aifc.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_write_header_raises(self):
        fout = aifc.open(io.BytesIO(), 'wb')
        self.assertRaises(aifc.Error, fout.close)
        fout = aifc.open(io.BytesIO(), 'wb')
        fout.setnchannels(1)
        self.assertRaises(aifc.Error, fout.close)
        fout = aifc.open(io.BytesIO(), 'wb')
        fout.setnchannels(1)
        fout.setsampwidth(1)
        self.assertRaises(aifc.Error, fout.close) 
Example 50
Project: pyblish-win   Author: pyblish   File: test_aifc.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_write_header_comptype_raises(self):
        for comptype in ('ULAW', 'ulaw', 'ALAW', 'alaw', 'G722'):
            fout = aifc.open(io.BytesIO(), 'wb')
            fout.setsampwidth(1)
            fout.setcomptype(comptype, '')
            self.assertRaises(aifc.Error, fout.close)
            fout.initfp(None) 
Example 51
Project: pyblish-win   Author: pyblish   File: test_aifc.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_write_markers_raises(self):
        fout = aifc.open(io.BytesIO(), 'wb')
        self.assertRaises(aifc.Error, fout.setmark, 0, 0, '')
        self.assertRaises(aifc.Error, fout.setmark, 1, -1, '')
        self.assertRaises(aifc.Error, fout.setmark, 1, 0, None)
        self.assertRaises(aifc.Error, fout.getmark, 1)
        fout.initfp(None) 
Example 52
Project: pyblish-win   Author: pyblish   File: test_memoryio.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_sizeof(self):
        basesize = support.calcobjsize(b'P2PP2P')
        check = self.check_sizeof
        self.assertEqual(object.__sizeof__(io.BytesIO()), basesize)
        check(io.BytesIO(), basesize )
        check(io.BytesIO(b'a'), basesize + 1 + 1 )
        check(io.BytesIO(b'a' * 1000), basesize + 1000 + 1 ) 
Example 53
Project: xadmin_bugfix   Author: vip68   File: export.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_xlsx_export(self, context):
        datas = self._get_datas(context)
        output = io.BytesIO()
        export_header = (
            self.request.GET.get('export_xlsx_header', 'off') == 'on')

        model_name = self.opts.verbose_name
        book = xlsxwriter.Workbook(output)
        sheet = book.add_worksheet(
            u"%s %s" % (_(u'Sheet'), force_text(model_name)))
        styles = {'datetime': book.add_format({'num_format': 'yyyy-mm-dd hh:mm:ss'}),
                  'date': book.add_format({'num_format': 'yyyy-mm-dd'}),
                  'time': book.add_format({'num_format': 'hh:mm:ss'}),
                  'header': book.add_format({'font': 'name Times New Roman', 'color': 'red', 'bold': 'on', 'num_format': '#,##0.00'}),
                  'default': book.add_format()}

        if not export_header:
            datas = datas[1:]
        for rowx, row in enumerate(datas):
            for colx, value in enumerate(row):
                if export_header and rowx == 0:
                    cell_style = styles['header']
                else:
                    if isinstance(value, datetime.datetime):
                        cell_style = styles['datetime']
                    elif isinstance(value, datetime.date):
                        cell_style = styles['date']
                    elif isinstance(value, datetime.time):
                        cell_style = styles['time']
                    else:
                        cell_style = styles['default']
                sheet.write(rowx, colx, value, cell_style)
        book.close()

        output.seek(0)
        return output.getvalue() 
Example 54
Project: xadmin_bugfix   Author: vip68   File: export.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_xls_export(self, context):
        datas = self._get_datas(context)
        output = io.BytesIO()
        export_header = (
            self.request.GET.get('export_xls_header', 'off') == 'on')

        model_name = self.opts.verbose_name
        book = xlwt.Workbook(encoding='utf8')
        sheet = book.add_sheet(
            u"%s %s" % (_(u'Sheet'), force_text(model_name)))
        styles = {'datetime': xlwt.easyxf(num_format_str='yyyy-mm-dd hh:mm:ss'),
                  'date': xlwt.easyxf(num_format_str='yyyy-mm-dd'),
                  'time': xlwt.easyxf(num_format_str='hh:mm:ss'),
                  'header': xlwt.easyxf('font: name Times New Roman, color-index red, bold on', num_format_str='#,##0.00'),
                  'default': xlwt.Style.default_style}

        if not export_header:
            datas = datas[1:]
        for rowx, row in enumerate(datas):
            for colx, value in enumerate(row):
                if export_header and rowx == 0:
                    cell_style = styles['header']
                else:
                    if isinstance(value, datetime.datetime):
                        cell_style = styles['datetime']
                    elif isinstance(value, datetime.date):
                        cell_style = styles['date']
                    elif isinstance(value, datetime.time):
                        cell_style = styles['time']
                    else:
                        cell_style = styles['default']
                sheet.write(rowx, colx, value, style=cell_style)
        book.save(output)

        output.seek(0)
        return output.getvalue() 
Example 55
Project: cyberdisc-bot   Author: CyberDiscovery   File: fun.py    MIT License 5 votes vote down vote up
def create_text_image(self, ctx: Context, person: str, text: str):
        """
        Creates an image of a given person with the specified text.
        """
        if len(text) > 100:
            return await ctx.send(":no_entry_sign: Your text must be shorter than 100 characters.")
        drawing_text = textwrap.fill(text, 20)
        font = ImageFont.truetype("cdbot/resources/Dosis-SemiBold.ttf", 150)

        text_layer = Image.new("RGBA", (1920, 1080), (0, 0, 0, 0))
        text_layer_drawing = ImageDraw.Draw(text_layer)
        text_layer_drawing.text((0, 0), drawing_text, fill=(0, 0, 0), align="center", font=font)

        cropped_text_layer = text_layer.crop(text_layer.getbbox())
        cropped_text_layer.thumbnail((170, 110))

        image = Image.open(f"cdbot/resources/{person}SaysBlank.png")

        x = int((image.width / 5 + 20) - (cropped_text_layer.width / 2))
        y = int((image.height / 5 + 50 / 2) - (cropped_text_layer.height / 2))

        image.paste(cropped_text_layer, (x, y), cropped_text_layer)
        image_bytes = BytesIO()
        image.save(image_bytes, format="PNG")
        image_bytes.seek(0)
        await ctx.send(file=File(image_bytes, filename=f"{person}.png")) 
Example 56
Project: drydock   Author: airshipit   File: bootaction.py    Apache License 2.0 5 votes vote down vote up
def tarbuilder(asset_list=None):
        """Create a tar file from rendered assets.

        Add each asset in ``asset_list`` to a tar file with the defined
        path and permission. The assets need to have the rendered_bytes field
        populated. Return a tarfile.TarFile.

        :param hostname: the hostname the tar is destined for
        :param balltype: the type of assets being included
        :param asset_list: list of objects.BootActionAsset instances
        """
        tarbytes = io.BytesIO()
        tarball = tarfile.open(
            mode='w:gz', fileobj=tarbytes, format=tarfile.GNU_FORMAT)
        asset_list = [
            a for a in asset_list if a.type != BootactionAssetType.PackageList
        ]
        for a in asset_list:
            fileobj = io.BytesIO(a.rendered_bytes)
            tarasset = tarfile.TarInfo(name=a.path)
            tarasset.size = len(a.rendered_bytes)
            tarasset.mode = a.permissions if a.permissions else 0o600
            tarasset.uid = 0
            tarasset.gid = 0
            tarball.addfile(tarasset, fileobj=fileobj)
        tarball.close()
        return tarbytes.getvalue() 
Example 57
Project: drydock   Author: airshipit   File: test_bootaction_context.py    Apache License 2.0 5 votes vote down vote up
def test_bootaction_context(self, falcontest, seed_bootaction_multinode):
        """Test that the API will return a boot action context"""
        for n, c in seed_bootaction_multinode.items():
            url = "/api/v1.0/bootactions/nodes/%s/units" % n
            auth_hdr = {'X-Bootaction-Key': "%s" % c['identity_key']}

            result = falcontest.simulate_get(url, headers=auth_hdr)

            assert result.status == falcon.HTTP_200

            fileobj = io.BytesIO(result.content)
            t = tarfile.open(mode='r:gz', fileobj=fileobj)
            t.close() 
Example 58
Project: drydock   Author: airshipit   File: test_api_bootaction.py    Apache License 2.0 5 votes vote down vote up
def test_bootaction_context(self, falcontest, seed_bootaction):
        """Test that the API will return a boot action context"""
        url = "/api/v1.0/bootactions/nodes/%s/units" % seed_bootaction[
            'nodename']
        auth_hdr = {'X-Bootaction-Key': "%s" % seed_bootaction['identity_key']}

        result = falcontest.simulate_get(url, headers=auth_hdr)

        assert result.status == falcon.HTTP_200

        fileobj = io.BytesIO(result.content)
        tarfile.open(mode='r:gz', fileobj=fileobj) 
Example 59
Project: drydock   Author: airshipit   File: test_bootaction_tarbuilder.py    Apache License 2.0 5 votes vote down vote up
def test_bootaction_tarbuilder(self, input_files, deckhand_ingester,
                                   setup):
        objects.register_all()

        input_file = input_files.join("deckhand_fullsite.yaml")

        design_state = DrydockState()
        design_ref = "file://%s" % str(input_file)

        design_status, design_data = deckhand_ingester.ingest_data(
            design_state=design_state, design_ref=design_ref)

        target_host = 'compute01'

        ba = design_data.get_bootaction('helloworld')
        action_id = ulid2.generate_binary_ulid()
        action_key = os.urandom(32)
        assets = ba.render_assets(target_host, design_data, action_id,
                                  action_key, design_ref)

        assert len(assets) > 0

        tarbytes = BootactionUtils.tarbuilder(assets)

        assert tarbytes is not None

        fileobj = io.BytesIO(tarbytes)
        tarball = tarfile.open(mode='r:gz', fileobj=fileobj)

        tarasset = tarball.getmember('/var/tmp/hello.sh')

        assert tarasset.mode == 0o555 
Example 60
Project: BASS   Author: Cisco-Talos   File: funcdb.py    GNU General Public License v2.0 5 votes vote down vote up
def add(self, db, **kwargs):
        db_data = db.data.copy()
        db_data["functions"] = _filter_functions(db.data["functions"], **kwargs)
        data = pickle.dumps(db_data)
        result = requests.post("{:s}/function".format(self.url), files = {"file": BytesIO(data)})
        if result.status_code != 200:
            raise RuntimeError("Request failed with status code {:d}".format(result.status_code)) 
Example 61
Project: BASS   Author: Cisco-Talos   File: funcdb.py    GNU General Public License v2.0 5 votes vote down vote up
def find_raw(self, db, **kwargs):
        db_data = db.data.copy()
        db_data["functions"] = _filter_functions(db.data["functions"], **kwargs)
        data = pickle.dumps(db_data)
        result = requests.post("{:s}/function/find/raw".format(self.url), files = {"file": BytesIO(data)})
        if result.status_code == 200:
            return True
        elif result.status_code == 404:
            return False
        else:
            raise RuntimeError("Request failed with status code {:d}".format(result.status_code)) 
Example 62
Project: BASS   Author: Cisco-Talos   File: funcdb.py    GNU General Public License v2.0 5 votes vote down vote up
def find_mnem(self, db, **kwargs):
        db_data = db.data.copy()
        db_data["functions"] = _filter_functions(db.data["functions"], **kwargs)
        data = pickle.dumps(db_data)
        result = requests.post("{:s}/function/find/mnem".format(self.url), files = {"file": BytesIO(data)})
        if result.status_code == 200:
            return True
        elif result.status_code == 404:
            return False
        else:
            raise RuntimeError("Request failed with status code {:d}".format(result.status_code)) 
Example 63
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: formparser.py    Apache License 2.0 5 votes vote down vote up
def default_stream_factory(total_content_length, filename, content_type,
                           content_length=None):
    """The stream factory that is used per default."""
    if total_content_length > 1024 * 500:
        return TemporaryFile('wb+')
    return BytesIO() 
Example 64
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: formparser.py    Apache License 2.0 5 votes vote down vote up
def default_stream_factory(total_content_length, filename, content_type,
                           content_length=None):
    """The stream factory that is used per default."""
    if total_content_length > 1024 * 500:
        return TemporaryFile('wb+')
    return BytesIO() 
Example 65
Project: django-xadmin   Author: MarkHoo   File: export.py    MIT License 5 votes vote down vote up
def get_xlsx_export(self, context):
        datas = self._get_datas(context)
        output = io.BytesIO()
        export_header = (
            self.request.GET.get('export_xlsx_header', 'off') == 'on')

        model_name = self.opts.verbose_name
        book = xlsxwriter.Workbook(output)
        sheet = book.add_worksheet(
            u"%s %s" % (_(u'Sheet'), force_text(model_name)))
        styles = {'datetime': book.add_format({'num_format': 'yyyy-mm-dd hh:mm:ss'}),
                  'date': book.add_format({'num_format': 'yyyy-mm-dd'}),
                  'time': book.add_format({'num_format': 'hh:mm:ss'}),
                  'header': book.add_format({'font': 'name Times New Roman', 'color': 'red', 'bold': 'on', 'num_format': '#,##0.00'}),
                  'default': book.add_format()}

        if not export_header:
            datas = datas[1:]
        for rowx, row in enumerate(datas):
            for colx, value in enumerate(row):
                if export_header and rowx == 0:
                    cell_style = styles['header']
                else:
                    if isinstance(value, datetime.datetime):
                        cell_style = styles['datetime']
                    elif isinstance(value, datetime.date):
                        cell_style = styles['date']
                    elif isinstance(value, datetime.time):
                        cell_style = styles['time']
                    else:
                        cell_style = styles['default']
                sheet.write(rowx, colx, value, cell_style)
        book.close()

        output.seek(0)
        return output.getvalue() 
Example 66
Project: django-xadmin   Author: MarkHoo   File: export.py    MIT License 5 votes vote down vote up
def get_xls_export(self, context):
        datas = self._get_datas(context)
        output = io.BytesIO()
        export_header = (
            self.request.GET.get('export_xls_header', 'off') == 'on')

        model_name = self.opts.verbose_name
        book = xlwt.Workbook(encoding='utf8')
        sheet = book.add_sheet(
            u"%s %s" % (_(u'Sheet'), force_text(model_name)))
        styles = {'datetime': xlwt.easyxf(num_format_str='yyyy-mm-dd hh:mm:ss'),
                  'date': xlwt.easyxf(num_format_str='yyyy-mm-dd'),
                  'time': xlwt.easyxf(num_format_str='hh:mm:ss'),
                  'header': xlwt.easyxf('font: name Times New Roman, color-index red, bold on', num_format_str='#,##0.00'),
                  'default': xlwt.Style.default_style}

        if not export_header:
            datas = datas[1:]
        for rowx, row in enumerate(datas):
            for colx, value in enumerate(row):
                if export_header and rowx == 0:
                    cell_style = styles['header']
                else:
                    if isinstance(value, datetime.datetime):
                        cell_style = styles['datetime']
                    elif isinstance(value, datetime.date):
                        cell_style = styles['date']
                    elif isinstance(value, datetime.time):
                        cell_style = styles['time']
                    else:
                        cell_style = styles['default']
                sheet.write(rowx, colx, value, style=cell_style)
        book.save(output)

        output.seek(0)
        return output.getvalue() 
Example 67
Project: django-xadmin   Author: MarkHoo   File: export.py    MIT License 5 votes vote down vote up
def get_xlsx_export(self, context):
        datas = self._get_datas(context)
        output = io.BytesIO()
        export_header = (
            self.request.GET.get('export_xlsx_header', 'off') == 'on')

        model_name = self.opts.verbose_name
        book = xlsxwriter.Workbook(output)
        sheet = book.add_worksheet(
            u"%s %s" % (_(u'Sheet'), force_text(model_name)))
        styles = {'datetime': book.add_format({'num_format': 'yyyy-mm-dd hh:mm:ss'}),
                  'date': book.add_format({'num_format': 'yyyy-mm-dd'}),
                  'time': book.add_format({'num_format': 'hh:mm:ss'}),
                  'header': book.add_format({'font': 'name Times New Roman', 'color': 'red', 'bold': 'on', 'num_format': '#,##0.00'}),
                  'default': book.add_format()}

        if not export_header:
            datas = datas[1:]
        for rowx, row in enumerate(datas):
            for colx, value in enumerate(row):
                if export_header and rowx == 0:
                    cell_style = styles['header']
                else:
                    if isinstance(value, datetime.datetime):
                        cell_style = styles['datetime']
                    elif isinstance(value, datetime.date):
                        cell_style = styles['date']
                    elif isinstance(value, datetime.time):
                        cell_style = styles['time']
                    else:
                        cell_style = styles['default']
                sheet.write(rowx, colx, value, cell_style)
        book.close()

        output.seek(0)
        return output.getvalue() 
Example 68
Project: django-xadmin   Author: MarkHoo   File: export.py    MIT License 5 votes vote down vote up
def get_xlsx_export(self, context):
        datas = self._get_datas(context)
        output = io.BytesIO()
        export_header = (
            self.request.GET.get('export_xlsx_header', 'off') == 'on')

        model_name = self.opts.verbose_name
        book = xlsxwriter.Workbook(output)
        sheet = book.add_worksheet(
            u"%s %s" % (_(u'Sheet'), force_text(model_name)))
        styles = {'datetime': book.add_format({'num_format': 'yyyy-mm-dd hh:mm:ss'}),
                  'date': book.add_format({'num_format': 'yyyy-mm-dd'}),
                  'time': book.add_format({'num_format': 'hh:mm:ss'}),
                  'header': book.add_format({'font': 'name Times New Roman', 'color': 'red', 'bold': 'on', 'num_format': '#,##0.00'}),
                  'default': book.add_format()}

        if not export_header:
            datas = datas[1:]
        for rowx, row in enumerate(datas):
            for colx, value in enumerate(row):
                if export_header and rowx == 0:
                    cell_style = styles['header']
                else:
                    if isinstance(value, datetime.datetime):
                        cell_style = styles['datetime']
                    elif isinstance(value, datetime.date):
                        cell_style = styles['date']
                    elif isinstance(value, datetime.time):
                        cell_style = styles['time']
                    else:
                        cell_style = styles['default']
                sheet.write(rowx, colx, value, cell_style)
        book.close()

        output.seek(0)
        return output.getvalue() 
Example 69
Project: slidoc   Author: mitotic   File: sdserver.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def zipdir(dirpath, inner=False):
    basedir = dirpath if inner else os.path.dirname(dirpath)
    stream = io.BytesIO()
    zfile = zipfile.ZipFile(stream, 'w')
    for dirname, subdirs, files in os.walk(dirpath):
        if dirname != basedir:
            zfile.write(dirname, os.path.relpath(dirname, basedir))
        for filename in files:
            fpath = os.path.join(dirname, filename)
            relpath = os.path.relpath(fpath, basedir)
            zfile.write(fpath, relpath)
    zfile.close()
    return stream.getvalue() 
Example 70
Project: slidoc   Author: mitotic   File: sdserver.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def pptx2md(self, filename, file_content, slides_zip=None, zip_images=False):
        import pptx2md
        pptx_opts = {}
        pptx_opts['img_dir'] = filename + '_images'
        if zip_images:
            pptx_opts['img_dir'] += '.zip'
        ppt_parser = pptx2md.PPTXParser(pptx_opts)
        slides_zip_handle = io.BytesIO(slides_zip) if slides_zip else None
        md_text, images_zipdata = ppt_parser.parse_pptx(io.BytesIO(file_content), filename+'.pptx', slides_zip_handle, nofile=True)
        return md_text, images_zipdata 
Example 71
Project: slidoc   Author: mitotic   File: md2md.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, cmd_args, images_zipdata=None, files_url=''):
        self.cmd_args = cmd_args
        self.files_url = files_url
        self.arg_check(cmd_args)
        self.images_zipfile = None
        self.images_map = {}
        self.content_zip_bytes = None
        self.content_zip = None
        self.content_image_paths = set()
        if images_zipdata:
            self.images_zipfile = zipfile.ZipFile(io.BytesIO(images_zipdata), 'r')
            self.images_map = dict( (os.path.basename(fpath), fpath) for fpath in self.images_zipfile.namelist() if os.path.basename(fpath))
        if 'zip' in self.cmd_args.images:
            self.content_zip_bytes = io.BytesIO()
            self.content_zip = zipfile.ZipFile(self.content_zip_bytes, 'w')

        self.skipping_notes = False
        self.cells_buffer = []
        self.buffered_markdown = []
        self.output = []
        self.imported_links = {}
        self.imported_defs = OrderedDict()
        self.imported_refs = OrderedDict()
        self.exported_refs = OrderedDict()
        self.image_refs = {}
        self.old_defs = OrderedDict()
        self.new_defs = OrderedDict()
        self.filedir = ''
        self.filename = ''
        self.fname = ''
        self.renumber_count = cmd_args.renumber 
Example 72
Project: badge-o-matic   Author: markuslindenberg   File: webapp.py    BSD 2-Clause "Simplified" License 4 votes vote down vote up
def badge():
    name = request.form['name'][:MAX_CHARS_PER_LINE] if 'name' in request.form else ''
    name2 = request.form['name2'][:MAX_CHARS_PER_LINE] if 'name2' in request.form else ''
    nick = request.form['nick'][:MAX_CHARS_PER_LINE] if 'nick' in request.form else ''
    community = request.form['community'][:MAX_CHARS_PER_LINE] if 'community' in request.form else ''

    pdf = BytesIO()
    c = Canvas(pdf, pagesize=(BADGE_W, BADGE_H))

    c.translate(ORIGIN_X, ORIGIN_Y)

    ico_center = 7*mm
    offset = HEIGHT+2*mm

    c.setFillGray(0.66)
    c.setFont('Awesome', 42)
    c.drawCentredString(ico_center, offset-42*pica/12, '\uf007')
    c.setFont('Awesome', 38)
    c.drawCentredString(ico_center, offset-(2*42+40)*pica/12, '\uf1fa')
    c.drawCentredString(ico_center, offset-(2*42+2*40)*pica/12, '\uf041')

    txt_start = 15*mm

    c.setFillGray(0.0)
    c.setFont('LeagueGothic', 42)
    c.drawString(txt_start, offset-42*pica/12, name)
    c.drawString(txt_start, offset-2*42*pica/12, name2)
    c.setFont('LeagueGothic', 38)
    c.drawString(txt_start, offset-(2*42+40)*pica/12, nick)
    c.drawString(txt_start, offset-(2*42+2*40)*pica/12, community)

    evt_width = 38*pica/12
    evt_start = WIDTH - evt_width

    img_width = 20*mm
    img_start = evt_start - img_width
    c.drawImage(path.join(path.dirname(__file__), 'images/ffrhein_logo_claim_line_rot.png'), img_start, 0, img_width, HEIGHT, mask=None, preserveAspectRatio=True, anchor='c')

    c.rotate(90)
    c.rect(0, -WIDTH, HEIGHT, evt_width, 0, 1)
    c.setFillGray(1.0)
    c.drawCentredString(HEIGHT/2, -WIDTH+MARGIN_R, 'routing days')  

    c.showPage()
    c.save()
    _print(pdf.getvalue())
    pdf.close()

    # response = make_response('Meh')
    # response.headers['Content-Type'] = 'text/plain'
    # return response
    return redirect('/badge/printing.html') 
Example 73
Project: fs_image   Author: facebookincubator   File: test_repo_downloader.py    MIT License 4 votes vote down vote up
def _check_download_error(self, url_regex, corrupt_file_fn, error_cls):
        original_open_url = repo_downloader.open_url

        def my_open_url(url):
            if re.match(url_regex, url):
                with original_open_url(url) as f:
                    return BytesIO(corrupt_file_fn(f.read()))
            return original_open_url(url)

        with tempfile.TemporaryDirectory() as storage_dir:
            downloader = self._make_downloader(storage_dir, '0/good_dog')
            with mock.patch.object(repo_downloader, 'open_url') as mock_fn:
                mock_fn.side_effect = my_open_url
                bad_snapshot = downloader.download()
                self._check_snapshot(
                    bad_snapshot, _GOOD_DOG_LOCATIONS, has_errors=True,
                )
                # Exactly one of RPMs & repodatas will have an error.
                storage_id_to_obj, = [
                    sito for sito in [
                        bad_snapshot.storage_id_to_rpm,
                        bad_snapshot.storage_id_to_repodata,
                    ] if any(not isinstance(sid, str) for sid in sito)
                ]
                yield self._check_storage_id_error(storage_id_to_obj, error_cls)

            # Re-downloading outside of the mock results in the same
            # snapshot, but with the error corrected.
            good_snapshot = downloader.download()
            self._check_snapshot(good_snapshot, _GOOD_DOG_LOCATIONS)
            self._check_repomd_equal(good_snapshot.repomd, bad_snapshot.repomd)
            for good_sito, bad_sito in [
                (
                    good_snapshot.storage_id_to_rpm,
                    bad_snapshot.storage_id_to_rpm,
                ),
                (
                    good_snapshot.storage_id_to_repodata,
                    bad_snapshot.storage_id_to_repodata,
                ),
            ]:
                # Compare the bad snapshot with the good.
                self.assertEqual(len(good_sito), len(bad_sito))
                for bad_sid, bad_obj in bad_sito.items():
                    if isinstance(bad_sid, str):
                        # By reusing the bad snapshot's storage ID, we
                        # implicitly check that the DB prevented double-
                        # storage of the objects.
                        self.assertEqual(bad_obj, good_sito[bad_sid])
                    # else:
                    #     We can't compare much since it's annoying to find
                    #     the corresponding object in `good_sido`. 
Example 74
Project: autolims   Author: scottbecker   File: custom_connection.py    MIT License 4 votes vote down vote up
def get_raw_file(self, data_id, file_path):
        """
        Get zip file with given data_id. Downloads to memory and returns a Python ZipFile by default.
        When dealing with larger files where it may not be desired to load the entire file into memory,
        specifying `file_path` will enable the file to be downloaded locally.
    
        Example Usage:
    
        .. code-block:: python
    
            small_zip_id = 'd12345'
            small_zip = api.get_zip(small_zip_id)
    
            my_big_zip_id = 'd99999'
            api.get_zip(my_big_zip_id, file_path='big_file.zip')
    
        Parameters
        ----------
        data_id: data_id
            Data id of file to download
        file_path: Optional[str]
            Path to file which to save the response to. If specified, will not return ZipFile explicitly.
    
        Returns
        ----------
        zip: zipfile.ZipFile
            A Python ZipFile is returned unless `file_path` is specified
    
        """
        import zipfile
        from io import BytesIO
        route = self.get_route('get_data_zip', data_id=data_id)
        req = self.get(route, status_response={'200': lambda resp: resp}, stream=True)
        if file_path:
            f = open(file_path, 'wb')
            # Buffer download of data into memory with smaller chunk sizes
            chunk_sz = 1024  # 1kb chunks
            for chunk in req.iter_content(chunk_sz):
                if chunk:
                    f.write(chunk)
            f.close()
            print("Zip file downloaded locally to {}.".format(file_path))
        else:
            return zipfile.ZipFile(BytesIO(req.content)) 
Example 75
Project: gog-galaxy-plugin-downloader   Author: Slashbunny   File: download.py    GNU General Public License v3.0 4 votes vote down vote up
def download_plugins(data, dest):
    """
    Downloads and extracts plugins

    If the destination directory already exists, the plugin is skipped
    """
    for name, data in data.items():
        version = data['version']
        guid = data['guid']
        url = data['url']
        if 'archive_path' in data:
            archive_path = data['archive_path']
        else:
            archive_path = None

        # Destination directory
        dest_dir = os.path.join(dest, name + '_' + guid)

        if os.path.isdir(dest_dir):
            # If destination path exists, check the version that is installed
            with open(os.path.join(dest_dir, 'manifest.json')) as m:
                data = json.load(m)
                existing_version = data['version']

                # Close json file
                m.close()

                # Version already matches
                if version == existing_version:
                    print('NOTICE: Skipping "{}" download, "{}" already exists'
                          .format(name, version))
                    continue
                # Version does not match, delete old plugin and download
                else:
                    shutil.rmtree(dest_dir)
                    print('Upgrading {} plugin'.format(name))

        # Passed Pre-Download Checks
        print('Downloading "{}" version "{}" ({})'
              .format(name, version, guid))

        # Download zip file into memory
        plugin_url = urlopen(url)
        plugin_zip = zipfile.ZipFile(BytesIO(plugin_url.read()))

        # Extract zip directly into destination if there are no sub-folders
        #  to deal with
        if not archive_path:
            plugin_zip.extractall(path=dest_dir)
        else:
            # Create temporary directory for extraction
            tmp_dir = tempfile.TemporaryDirectory(prefix='galaxy-plugin')

            # Extract zip to temporary directory
            plugin_zip.extractall(path=tmp_dir.name)

            # Move sub-directory into final destination directory
            shutil.move(os.path.join(tmp_dir.name, archive_path), dest_dir)

            # Cleanup temporary directory
            tmp_dir.cleanup() 
Example 76
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: test.py    Apache License 2.0 4 votes vote down vote up
def __init__(self, path='/', base_url=None, query_string=None,
                 method='GET', input_stream=None, content_type=None,
                 content_length=None, errors_stream=None, multithread=False,
                 multiprocess=False, run_once=False, headers=None, data=None,
                 environ_base=None, environ_overrides=None, charset='utf-8'):
        path_s = make_literal_wrapper(path)
        if query_string is None and path_s('?') in path:
            path, query_string = path.split(path_s('?'), 1)
        self.charset = charset
        self.path = iri_to_uri(path)
        if base_url is not None:
            base_url = url_fix(iri_to_uri(base_url, charset), charset)
        self.base_url = base_url
        if isinstance(query_string, (bytes, text_type)):
            self.query_string = query_string
        else:
            if query_string is None:
                query_string = MultiDict()
            elif not isinstance(query_string, MultiDict):
                query_string = MultiDict(query_string)
            self.args = query_string
        self.method = method
        if headers is None:
            headers = Headers()
        elif not isinstance(headers, Headers):
            headers = Headers(headers)
        self.headers = headers
        if content_type is not None:
            self.content_type = content_type
        if errors_stream is None:
            errors_stream = sys.stderr
        self.errors_stream = errors_stream
        self.multithread = multithread
        self.multiprocess = multiprocess
        self.run_once = run_once
        self.environ_base = environ_base
        self.environ_overrides = environ_overrides
        self.input_stream = input_stream
        self.content_length = content_length
        self.closed = False

        if data:
            if input_stream is not None:
                raise TypeError('can\'t provide input stream and data')
            if isinstance(data, text_type):
                data = data.encode(self.charset)
            if isinstance(data, bytes):
                self.input_stream = BytesIO(data)
                if self.content_length is None:
                    self.content_length = len(data)
            else:
                for key, value in _iter_data(data):
                    if isinstance(value, (tuple, dict)) or \
                       hasattr(value, 'read'):
                        self._add_file_from_data(key, value)
                    else:
                        self.form.setlistdefault(key).append(value) 
Example 77
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: test.py    Apache License 2.0 4 votes vote down vote up
def get_environ(self):
        """Return the built environ."""
        input_stream = self.input_stream
        content_length = self.content_length
        content_type = self.content_type

        if input_stream is not None:
            start_pos = input_stream.tell()
            input_stream.seek(0, 2)
            end_pos = input_stream.tell()
            input_stream.seek(start_pos)
            content_length = end_pos - start_pos
        elif content_type == 'multipart/form-data':
            values = CombinedMultiDict([self.form, self.files])
            input_stream, content_length, boundary = \
                stream_encode_multipart(values, charset=self.charset)
            content_type += '; boundary="%s"' % boundary
        elif content_type == 'application/x-www-form-urlencoded':
            #py2v3 review
            values = url_encode(self.form, charset=self.charset)
            values = values.encode('ascii')
            content_length = len(values)
            input_stream = BytesIO(values)
        else:
            input_stream = _empty_stream

        result = {}
        if self.environ_base:
            result.update(self.environ_base)

        def _path_encode(x):
            return wsgi_encoding_dance(url_unquote(x, self.charset), self.charset)

        qs = wsgi_encoding_dance(self.query_string)

        result.update({
            'REQUEST_METHOD':       self.method,
            'SCRIPT_NAME':          _path_encode(self.script_root),
            'PATH_INFO':            _path_encode(self.path),
            'QUERY_STRING':         qs,
            'SERVER_NAME':          self.server_name,
            'SERVER_PORT':          str(self.server_port),
            'HTTP_HOST':            self.host,
            'SERVER_PROTOCOL':      self.server_protocol,
            'CONTENT_TYPE':         content_type or '',
            'CONTENT_LENGTH':       str(content_length or '0'),
            'wsgi.version':         self.wsgi_version,
            'wsgi.url_scheme':      self.url_scheme,
            'wsgi.input':           input_stream,
            'wsgi.errors':          self.errors_stream,
            'wsgi.multithread':     self.multithread,
            'wsgi.multiprocess':    self.multiprocess,
            'wsgi.run_once':        self.run_once
        })
        for key, value in self.headers.to_wsgi_list():
            result['HTTP_%s' % key.upper().replace('-', '_')] = value
        if self.environ_overrides:
            result.update(self.environ_overrides)
        return result 
Example 78
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: test.py    Apache License 2.0 4 votes vote down vote up
def __init__(self, path='/', base_url=None, query_string=None,
                 method='GET', input_stream=None, content_type=None,
                 content_length=None, errors_stream=None, multithread=False,
                 multiprocess=False, run_once=False, headers=None, data=None,
                 environ_base=None, environ_overrides=None, charset='utf-8'):
        path_s = make_literal_wrapper(path)
        if query_string is None and path_s('?') in path:
            path, query_string = path.split(path_s('?'), 1)
        self.charset = charset
        self.path = iri_to_uri(path)
        if base_url is not None:
            base_url = url_fix(iri_to_uri(base_url, charset), charset)
        self.base_url = base_url
        if isinstance(query_string, (bytes, text_type)):
            self.query_string = query_string
        else:
            if query_string is None:
                query_string = MultiDict()
            elif not isinstance(query_string, MultiDict):
                query_string = MultiDict(query_string)
            self.args = query_string
        self.method = method
        if headers is None:
            headers = Headers()
        elif not isinstance(headers, Headers):
            headers = Headers(headers)
        self.headers = headers
        if content_type is not None:
            self.content_type = content_type
        if errors_stream is None:
            errors_stream = sys.stderr
        self.errors_stream = errors_stream
        self.multithread = multithread
        self.multiprocess = multiprocess
        self.run_once = run_once
        self.environ_base = environ_base
        self.environ_overrides = environ_overrides
        self.input_stream = input_stream
        self.content_length = content_length
        self.closed = False

        if data:
            if input_stream is not None:
                raise TypeError('can\'t provide input stream and data')
            if isinstance(data, text_type):
                data = data.encode(self.charset)
            if isinstance(data, bytes):
                self.input_stream = BytesIO(data)
                if self.content_length is None:
                    self.content_length = len(data)
            else:
                for key, value in _iter_data(data):
                    if isinstance(value, (tuple, dict)) or \
                       hasattr(value, 'read'):
                        self._add_file_from_data(key, value)
                    else:
                        self.form.setlistdefault(key).append(value) 
Example 79
Project: slidoc   Author: mitotic   File: sdserver.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def postAction(self, subpath):
        previewingSession = self.previewActive()
        site_prefix = '/'+Options['site_name'] if Options['site_name'] else ''
        action, sep, subsubpath = subpath.partition('/')
        sessionName = subsubpath
        if not sessionName:
            sessionName = self.get_argument('sessionname', '')

        if action == '_edit':
            if not Options['source_dir']:
                raise tornado.web.HTTPError(403, log_message='CUSTOM:Must specify source_dir to edit')
            sessionType = self.get_argument('sessiontype', '')
            slideNumber = self.get_argument('slide', '')
            newNumber = self.get_argument('move', '')
            if slideNumber.isdigit():
                slideNumber = int(slideNumber)
            else:
                slideNumber = None
            if newNumber.isdigit():
                newNumber = int(newNumber)
            else:
                newNumber = None

            if previewingSession and previewingSession != sessionName:
                if slideNumber:
                    self.set_header('Content-Type', 'application/json')
                    self.write( json.dumps( {'result': 'error', 'error': 'Cannot edit sessions while previewing another session '+previewingSession} ) )
                else:
                    self.displayMessage('Cannot edit sessions while previewing session: <a href="%s/_preview/index.html">%s</a><p></p>' % (site_prefix, previewingSession))
                return

            if self.get_argument('rollover',''):
                # Close all session websockets (forcing reload)
                IOLoop.current().add_callback(WSHandler.closeSessionConnections, sessionName)
                return self.rollover(sessionName, slideNumber)

            if self.get_argument('truncate',''):
                # Close all session websockets (forcing reload)
                IOLoop.current().add_callback(WSHandler.closeSessionConnections, sessionName)
                return self.rollover(sessionName, slideNumber, truncateOnly=True)

            sessionText = self.get_argument('sessiontext', '')
            fromSession = self.get_argument('fromsession', '')
            fromSite = self.get_argument('fromsite', '')
            deleteSlide = self.get_argument('deleteslide', '')
            sessionModify = sessionName if self.get_argument('sessionmodify', '') else ''
            update = self.get_argument('update', '')

            imageZip = None
            if 'zipimages' in self.request.files:
                fileinfo = self.request.files['zipimages'][0]
                try:
                    imageZip = zipfile.ZipFile(io.BytesIO(fileinfo['body']))
                except Exception, excp:
                    raise tornado.web.HTTPError(404, log_message='CUSTOM:Error in reading image zip file: '+str(excp))
                zfile = zipfile.ZipFile(io.BytesIO(), 'w')
                for ipath in zfile.namelist():
                    zfile.writestr(sessionNext+'_images/'+os.path.basename(ipath), ifile.read(ipath))

            return self.editSession(sessionName, sessionType=sessionType, update=update, sessionText=sessionText, fromSession=fromSession, fromSite=fromSite,
                                    slideNumber=slideNumber, newNumber=newNumber, deleteSlide=deleteSlide, modify=sessionModify, imageZip=imageZip) 
Example 80
Project: django-xadmin   Author: MarkHoo   File: export.py    MIT License 2 votes vote down vote up
def get_xls_export(self, context):
        datas = self._get_datas(context)
        output = io.BytesIO()
        export_header = (
            self.request.GET.get('export_xls_header', 'off') == 'on')

        model_name = self.opts.verbose_name
        book = xlwt.Workbook(encoding='utf8')
        sheet = book.add_sheet(
            u"%s %s" % (_(u'Sheet'), force_text(model_name)))
        styles = {'datetime': xlwt.easyxf(num_format_str='yyyy-mm-dd hh:mm:ss'),
                  'date': xlwt.easyxf(num_format_str='yyyy-mm-dd'),
                  'time': xlwt.easyxf(num_format_str='hh:mm:ss'),
                  'header': xlwt.easyxf('font: name Times New Roman, color-index red, bold on', num_format_str='#,##0.00'),
                  'default': xlwt.Style.default_style}

        if not export_header:
            datas = datas[1:]
        for rowx, row in enumerate(datas):
            for colx, value in enumerate(row):
                if export_header and rowx == 0:
                    cell_style = styles['header']
                else:
                    if isinstance(value, datetime.datetime):
                        cell_style = styles['datetime']
                    elif isinstance(value, datetime.date):
                        cell_style = styles['date']
                    elif isinstance(value, datetime.time):
                        cell_style = styles['time']
                    else:
                        cell_style = styles['default']
                sheet.write(rowx, colx, value, style=cell_style)
        book.save(output)

        output.seek(0)
        return output.getvalue()