當前位置: 首頁>>代碼示例>>Python>>正文


Python bz2.compress方法代碼示例

本文整理匯總了Python中bz2.compress方法的典型用法代碼示例。如果您正苦於以下問題:Python bz2.compress方法的具體用法?Python bz2.compress怎麽用?Python bz2.compress使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在bz2的用法示例。


在下文中一共展示了bz2.compress方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _test_partial_input

# 需要導入模塊: import bz2 [as 別名]
# 或者: from bz2 import compress [as 別名]
def _test_partial_input(self, mode):
        class MyStringIO(StringIO.StringIO):
            hit_eof = False
            def read(self, n):
                if self.hit_eof:
                    raise AssertionError("infinite loop detected in tarfile.open()")
                self.hit_eof = self.pos == self.len
                return StringIO.StringIO.read(self, n)
            def seek(self, *args):
                self.hit_eof = False
                return StringIO.StringIO.seek(self, *args)

        data = bz2.compress(tarfile.TarInfo("foo").tobuf())
        for x in range(len(data) + 1):
            try:
                tarfile.open(fileobj=MyStringIO(data[:x]), mode=mode)
            except tarfile.ReadError:
                pass # we have no interest in ReadErrors 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:20,代碼來源:test_tarfile.py

示例2: _test_partial_input

# 需要導入模塊: import bz2 [as 別名]
# 或者: from bz2 import compress [as 別名]
def _test_partial_input(self, mode):
        class MyBytesIO(io.BytesIO):
            hit_eof = False
            def read(self, n):
                if self.hit_eof:
                    raise AssertionError("infinite loop detected in "
                                         "tarfile.open()")
                self.hit_eof = self.tell() == len(self.getvalue())
                return super(MyBytesIO, self).read(n)
            def seek(self, *args):
                self.hit_eof = False
                return super(MyBytesIO, self).seek(*args)

        data = bz2.compress(tarfile.TarInfo("foo").tobuf())
        for x in range(len(data) + 1):
            try:
                tarfile.open(fileobj=MyBytesIO(data[:x]), mode=mode)
            except tarfile.ReadError:
                pass # we have no interest in ReadErrors 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:21,代碼來源:test_tarfile.py

示例3: __init__

# 需要導入模塊: import bz2 [as 別名]
# 或者: from bz2 import compress [as 別名]
def __init__(self, path="./libsimilarity/libsimilarity.so"):
        super(SIMILARITYNative, self).__init__(True)

        self._u = cdll.LoadLibrary( path )

        self._u.compress.restype = c_uint
        self._u.ncd.restype = c_int
        self._u.ncs.restype = c_int
        self._u.cmid.restype = c_int
        self._u.entropy.restype = c_double
        self._u.levenshtein.restype = c_uint

        self._u.kolmogorov.restype = c_uint
        self._u.bennett.restype = c_double
        self._u.RDTSC.restype = c_double

        self.__libsim_t = LIBSIMILARITY_T()

        self.set_compress_type( ZLIB_COMPRESS ) 
開發者ID:xtiankisutsa,項目名稱:MARA_Framework,代碼行數:21,代碼來源:similarity.py

示例4: _ncd

# 需要導入模塊: import bz2 [as 別名]
# 或者: from bz2 import compress [as 別名]
def _ncd(self, s1, s2, s1size=0, s2size=0):
        if s1size == 0:
            s1size = self.compress(s1)

        if s2size == 0:
            s2size = self.compress(s2)

        s3size = self.compress(s1+s2)

        smax = max(s1size, s2size)
        smin = min(s1size, s2size)

        res = (abs(s3size - smin)) / float(smax)
        if res > 1.0:
            res = 1.0

        return res, s1size, s2size, 0 
開發者ID:xtiankisutsa,項目名稱:MARA_Framework,代碼行數:19,代碼來源:similarity.py

示例5: binaryToAttributes

# 需要導入模塊: import bz2 [as 別名]
# 或者: from bz2 import compress [as 別名]
def binaryToAttributes(cls, binary):
        """
        Turn a bytestring, or None, into SimpleDB attributes.
        """
        if binary is None: return {u'numChunks': 0}
        assert isinstance(binary, bytes)
        assert len(binary) <= cls.maxBinarySize()
        # The use of compression is just an optimization. We can't include it in the maxValueSize
        # computation because the compression ratio depends on the input.
        compressed = bz2.compress(binary)
        if len(compressed) > len(binary):
            compressed = b'U' + binary
        else:
            compressed = b'C' + compressed
        encoded = base64.b64encode(compressed)
        assert len(encoded) <= cls._maxEncodedSize()
        n = cls.maxValueSize
        chunks = (encoded[i:i + n] for i in range(0, len(encoded), n))
        attributes = {cls._chunkName(i): chunk for i, chunk in enumerate(chunks)}
        attributes.update({u'numChunks': len(attributes)})
        return attributes 
開發者ID:DataBiosphere,項目名稱:toil,代碼行數:23,代碼來源:utils.py

示例6: test_get

# 需要導入模塊: import bz2 [as 別名]
# 或者: from bz2 import compress [as 別名]
def test_get(self, zk_mock):
        """Test fetching a report.
        """
        content = '\n'.join([
            'a,b,c',
            '1,2,3',
            '4,5,6'
        ])
        zk_mock.get.return_value = (bz2.compress(content.encode()), None)

        result = self.report.get('foo')

        zk_mock.get.assert_called_with('/reports/foo')
        pd.util.testing.assert_frame_equal(
            result,
            pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=['a', 'b', 'c'])
        ) 
開發者ID:Morgan-Stanley,項目名稱:treadmill,代碼行數:19,代碼來源:scheduler_test.py

示例7: test_deserialize_dataframe_bz2

# 需要導入模塊: import bz2 [as 別名]
# 或者: from bz2 import compress [as 別名]
def test_deserialize_dataframe_bz2(self):
        """Test deserializing a compressed dataframe."""
        content = bz2.compress(
            b'\n'.join(
                [
                    b'a,b,c',
                    b'1,2,3',
                    b'4,5,6'
                ]
            )
        )

        result = reports.deserialize_dataframe(content)
        pd.util.testing.assert_frame_equal(
            result,
            pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=['a', 'b', 'c'])
        ) 
開發者ID:Morgan-Stanley,項目名稱:treadmill,代碼行數:19,代碼來源:reports_test.py

示例8: test_queueMessages_processes_files_message_instantly

# 需要導入模塊: import bz2 [as 別名]
# 或者: from bz2 import compress [as 別名]
def test_queueMessages_processes_files_message_instantly(self):
        worker = StatusWorkerService(sentinel.dbtasks)
        mock_processMessage = self.patch(worker, "_processMessage")
        contents = b"These are the contents of the file."
        encoded_content = encode_as_base64(bz2.compress(contents))
        message = self.make_message()
        message["files"] = [
            {
                "path": "sample.txt",
                "encoding": "uuencode",
                "compression": "bzip2",
                "content": encoded_content,
            }
        ]
        nodes_with_tokens = yield deferToDatabase(self.make_nodes_with_tokens)
        node, token = nodes_with_tokens[0]
        yield worker.queueMessage(token.key, message)
        self.assertThat(mock_processMessage, MockCalledOnceWith(node, message)) 
開發者ID:maas,項目名稱:maas,代碼行數:20,代碼來源:test_api_twisted.py

示例9: test_queueMessages_handled_invalid_nodekey_with_instant_msg

# 需要導入模塊: import bz2 [as 別名]
# 或者: from bz2 import compress [as 別名]
def test_queueMessages_handled_invalid_nodekey_with_instant_msg(self):
        worker = StatusWorkerService(sentinel.dbtasks)
        mock_processMessage = self.patch(worker, "_processMessage")
        contents = b"These are the contents of the file."
        encoded_content = encode_as_base64(bz2.compress(contents))
        message = self.make_message()
        message["files"] = [
            {
                "path": "sample.txt",
                "encoding": "uuencode",
                "compression": "bzip2",
                "content": encoded_content,
            }
        ]
        nodes_with_tokens = yield deferToDatabase(self.make_nodes_with_tokens)
        node, token = nodes_with_tokens[0]
        yield deferToDatabase(token.delete)
        yield worker.queueMessage(token.key, message)
        self.assertThat(mock_processMessage, MockNotCalled()) 
開發者ID:maas,項目名稱:maas,代碼行數:21,代碼來源:test_api_twisted.py

示例10: test_status_with_file_bad_encoder_fails

# 需要導入模塊: import bz2 [as 別名]
# 或者: from bz2 import compress [as 別名]
def test_status_with_file_bad_encoder_fails(self):
        node = factory.make_Node(
            interface=True, status=NODE_STATUS.COMMISSIONING
        )
        contents = b"These are the contents of the file."
        encoded_content = encode_as_base64(bz2.compress(contents))
        payload = {
            "event_type": "finish",
            "result": "FAILURE",
            "origin": "curtin",
            "name": "commissioning",
            "description": "Commissioning",
            "timestamp": datetime.utcnow(),
            "files": [
                {
                    "path": "sample.txt",
                    "encoding": "uuencode",
                    "compression": "bzip2",
                    "content": encoded_content,
                }
            ],
        }
        with ExpectedException(ValueError):
            self.processMessage(node, payload) 
開發者ID:maas,項目名稱:maas,代碼行數:26,代碼來源:test_api_twisted.py

示例11: test_status_with_file_bad_compression_fails

# 需要導入模塊: import bz2 [as 別名]
# 或者: from bz2 import compress [as 別名]
def test_status_with_file_bad_compression_fails(self):
        node = factory.make_Node(
            interface=True, status=NODE_STATUS.COMMISSIONING
        )
        contents = b"These are the contents of the file."
        encoded_content = encode_as_base64(bz2.compress(contents))
        payload = {
            "event_type": "finish",
            "result": "FAILURE",
            "origin": "curtin",
            "name": "commissioning",
            "description": "Commissioning",
            "timestamp": datetime.utcnow(),
            "files": [
                {
                    "path": "sample.txt",
                    "encoding": "base64",
                    "compression": "jpeg",
                    "content": encoded_content,
                }
            ],
        }
        with ExpectedException(ValueError):
            self.processMessage(node, payload) 
開發者ID:maas,項目名稱:maas,代碼行數:26,代碼來源:test_api_twisted.py

示例12: load

# 需要導入模塊: import bz2 [as 別名]
# 或者: from bz2 import compress [as 別名]
def load(cls, branch, kv_store, msg_cls, hash):
        #  Update the branch's config store
        blob = kv_store[hash]
        if cls.compress:
            blob = decompress(blob)
        data = loads(blob)

        config_hash = data['config']
        config_data = cls.load_config(kv_store, msg_cls, config_hash)

        children_list = data['children']
        assembled_children = {}
        node = branch._node
        for field_name, meta in children_fields(msg_cls).iteritems():
            child_msg_cls = tmp_cls_loader(meta.module, meta.type)
            children = []
            for child_hash in children_list[field_name]:
                child_node = node._mknode(child_msg_cls)
                child_node.load_latest(child_hash)
                child_rev = child_node.latest
                children.append(child_rev)
            assembled_children[field_name] = children
        rev = cls(branch, config_data, assembled_children)
        return rev 
開發者ID:opencord,項目名稱:voltha,代碼行數:26,代碼來源:config_rev_persisted.py

示例13: _write_repodata

# 需要導入模塊: import bz2 [as 別名]
# 或者: from bz2 import compress [as 別名]
def _write_repodata(package_dir, repodata_dict):
    data = json.dumps(repodata_dict, indent=2, sort_keys=True)
    # strip trailing whitespace
    data = '\n'.join(line.rstrip() for line in data.splitlines())
    # make sure we have newline at the end
    if not data.endswith('\n'):
        data += '\n'

    with open(os.path.join(package_dir,
                           'repodata.json'), 'w') as fo:
        fo.write(data)

    # compress repodata.json into the bz2 format. some conda commands still
    # need it
    bz2_path = os.path.join(package_dir, 'repodata.json.bz2')
    with open(bz2_path, 'wb') as fo:
        fo.write(bz2.compress(data.encode('utf-8'))) 
開發者ID:Valassis-Digital-Media,項目名稱:conda-mirror,代碼行數:19,代碼來源:conda_mirror.py

示例14: bz2_pack

# 需要導入模塊: import bz2 [as 別名]
# 或者: from bz2 import compress [as 別名]
def bz2_pack(source):
    """
    Returns `source` as bzip2-compressed Python script
    """
    import bz2
    compressed = base64.b64encode(bz2.compress(
        source.encode('utf-8'))).decode('utf-8')
    return f'import bz2,base64;exec(bz2.decompress(base64.b64decode("{compressed}")))' 
開發者ID:PyObfx,項目名稱:PyObfx,代碼行數:10,代碼來源:packer.py

示例15: gz_pack

# 需要導入模塊: import bz2 [as 別名]
# 或者: from bz2 import compress [as 別名]
def gz_pack(source):
    """
    Returns `source` as gzip-compressed Python script
    """
    import zlib
    compressed = base64.b64encode(zlib.compress(source.encode('utf-8'))).decode('utf-8')
    return f'import zlib,base64;exec(zlib.decompress(base64.b64decode("{compressed}")))' 
開發者ID:PyObfx,項目名稱:PyObfx,代碼行數:9,代碼來源:packer.py


注:本文中的bz2.compress方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。