当前位置: 首页>>代码示例>>Python>>正文


Python cPickle.loads方法代码示例

本文整理汇总了Python中cPickle.loads方法的典型用法代码示例。如果您正苦于以下问题:Python cPickle.loads方法的具体用法?Python cPickle.loads怎么用?Python cPickle.loads使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在模块cPickle的用法示例。

在下文中一共展示了cPickle.loads方法的28个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: _augment_images_worker

# 需要导入模块: import cPickle [as 别名]
# 或者: from cPickle import loads [as 别名]
def _augment_images_worker(self, augseq, queue_source, queue_result):
        """Worker function that endlessly queries the source queue (input
        batches), augments batches in it and sends the result to the output
        queue."""
        while True:
            # wait for a new batch in the source queue and load it
            batch_str = queue_source.get()
            batch = pickle.loads(batch_str)

            # augment the batch
            if batch.images is not None and batch.keypoints is not None:
                augseq_det = augseq.to_deterministic()
                batch.images_aug = augseq_det.augment_images(batch.images)
                batch.keypoints_aug = augseq_det.augment_keypoints(batch.keypoints)
            elif batch.images is not None:
                batch.images_aug = augseq.augment_images(batch.images)
            elif batch.keypoints is not None:
                batch.keypoints_aug = augseq.augment_keypoints(batch.keypoints)

            # send augmented batch to output queue
            queue_result.put(pickle.dumps(batch, protocol=-1)) 
开发者ID:aleju,项目名称:cat-bbs,代码行数:23,代码来源:train.py


示例2: test_Node_save

# 需要导入模块: import cPickle [as 别名]
# 或者: from cPickle import loads [as 别名]
def test_Node_save():
    test_list = [1,2,3]
    generic_node = mdp.Node()
    generic_node.dummy_attr = test_list
    # test string save
    copy_node_pic = generic_node.save(None)
    copy_node = cPickle.loads(copy_node_pic)
    assert generic_node.dummy_attr == copy_node.dummy_attr,\
           'Node save (string) method did not work'
    copy_node.dummy_attr[0] = 10
    assert generic_node.dummy_attr != copy_node.dummy_attr,\
           'Node save (string) method did not work'
    # test file save
    dummy_file = tempfile.mktemp(prefix='MDP_', suffix=".pic",
                                 dir=py.test.mdp_tempdirname)
    generic_node.save(dummy_file, protocol=1)
    dummy_file = open(dummy_file, 'rb')
    copy_node = cPickle.load(dummy_file)
    assert generic_node.dummy_attr == copy_node.dummy_attr,\
           'Node save (file) method did not work'
    copy_node.dummy_attr[0] = 10
    assert generic_node.dummy_attr != copy_node.dummy_attr,\
           'Node save (file) method did not work' 
开发者ID:ME-ICA,项目名称:me-ica,代码行数:25,代码来源:test_node_operations.py


示例3: testFlow_save

# 需要导入模块: import cPickle [as 别名]
# 或者: from cPickle import loads [as 别名]
def testFlow_save():
    dummy_list = [1,2,3]
    flow = _get_default_flow()
    flow[0].dummy_attr = dummy_list
    # test string save
    copy_flow_pic = flow.save(None)
    copy_flow = cPickle.loads(copy_flow_pic)
    assert flow[0].dummy_attr == copy_flow[0].dummy_attr, \
           'Flow save (string) method did not work'
    copy_flow[0].dummy_attr[0] = 10
    assert flow[0].dummy_attr != copy_flow[0].dummy_attr, \
           'Flow save (string) method did not work'
    # test file save
    dummy_file = tempfile.mktemp(prefix='MDP_', suffix=".pic",
                                 dir=py.test.mdp_tempdirname)
    flow.save(dummy_file, protocol=1)
    dummy_file = open(dummy_file, 'rb')
    copy_flow = cPickle.load(dummy_file)
    assert flow[0].dummy_attr == copy_flow[0].dummy_attr, \
           'Flow save (file) method did not work'
    copy_flow[0].dummy_attr[0] = 10
    assert flow[0].dummy_attr != copy_flow[0].dummy_attr, \
           'Flow save (file) method did not work' 
开发者ID:ME-ICA,项目名称:me-ica,代码行数:25,代码来源:test_flows.py


示例4: unpickle_args

# 需要导入模块: import cPickle [as 别名]
# 或者: from cPickle import loads [as 别名]
def unpickle_args(items):
    '''Takes a dict and unpickles values whose keys are found in
    '_pickled' key.

    >>> unpickle_args({'_pickled': ['foo']. 'foo': ['I3%0A.']})
    {'foo': 3}
    '''
    # Technically there can be more than one _pickled value. At this point
    # we'll just use the first one
    pickled= items.pop('_pickled', None)
    if pickled is None:
        return items

    pickled_keys = pickled[0].split(',')
    ret = {}
    for key, vals in items.items():
        if key in pickled_keys:
            ret[key] = [pickle.loads(val) for val in vals]
        else:
            ret[key] = vals
    return ret 
开发者ID:jmarth,项目名称:plugin.video.kmediatorrent,代码行数:23,代码来源:common.py


示例5: load_object

# 需要导入模块: import cPickle [as 别名]
# 或者: from cPickle import loads [as 别名]
def load_object(self, value):
        """The reversal of :meth:`dump_object`.  This might be called with
        None.
        """
        if value is None:
            return None
        if value.startswith(b"!"):
            try:
                return pickle.loads(value[1:])
            except pickle.PickleError:
                return None
        try:
            return int(value)
        except ValueError:
            # before 0.8 we did not have serialization.  Still support that.
            return value 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:18,代码来源:cache.py


示例6: from_metadata

# 需要导入模块: import cPickle [as 别名]
# 或者: from cPickle import loads [as 别名]
def from_metadata(cls, metadata, rng=None):
        if rng is None: rng = gu.gen_rng(0)
        # Unpickle the sklearn ols.
        skl_ols = cPickle.loads(
            base64.b64decode(metadata['params']['regressor_binary']))
        metadata['params']['regressor'] = skl_ols
        ols = cls(
            outputs=metadata['outputs'],
            inputs=metadata['inputs'],
            params=metadata['params'],
            distargs=metadata['distargs'],
            rng=rng)
        # json keys are strings -- convert back to integers.
        x = ((int(k), v) for k, v in metadata['data']['x'].iteritems())
        Y = ((int(k), v) for k, v in metadata['data']['Y'].iteritems())
        ols.data = Data(x=OrderedDict(x), Y=OrderedDict(Y))
        ols.N = metadata['N']
        return ols 
开发者ID:probcomp,项目名称:cgpm,代码行数:20,代码来源:ols.py


示例7: from_metadata

# 需要导入模块: import cPickle [as 别名]
# 或者: from cPickle import loads [as 别名]
def from_metadata(cls, metadata, rng=None):
        if rng is None: rng = gu.gen_rng(0)
        # Unpickle the sklearn forest.
        forest = cPickle.loads(
            base64.b64decode(metadata['params']['forest_binary']))
        metadata['params']['forest'] = forest
        forest = cls(
            outputs=metadata['outputs'],
            inputs=metadata['inputs'],
            hypers=metadata['hypers'],
            params=metadata['params'],
            distargs=metadata['distargs'],
            rng=rng)
        # json keys are strings -- convert back to integers.
        x = ((int(k), v) for k, v in metadata['data']['x'].iteritems())
        Y = ((int(k), v) for k, v in metadata['data']['Y'].iteritems())
        forest.data = Data(x=OrderedDict(x), Y=OrderedDict(Y))
        forest.N = metadata['N']
        forest.counts = metadata['counts']
        return forest 
开发者ID:probcomp,项目名称:cgpm,代码行数:22,代码来源:forest.py


示例8: load_object

# 需要导入模块: import cPickle [as 别名]
# 或者: from cPickle import loads [as 别名]
def load_object(self, value):
        """The reversal of :meth:`dump_object`.  This might be called with
        None.
        """
        if value is None:
            return None
        if value.startswith(b'!'):
            try:
                return pickle.loads(value[1:])
            except pickle.PickleError:
                return None
        try:
            return int(value)
        except ValueError:
            # before 0.8 we did not have serialization.  Still support that.
            return value 
开发者ID:jpush,项目名称:jbox,代码行数:18,代码来源:cache.py


示例9: __init__

# 需要导入模块: import cPickle [as 别名]
# 或者: from cPickle import loads [as 别名]
def __init__(self, env, clear, ivfidx=None):
        MemStorage.__init__(self)

        self.env = env
        dbname = 'db%06d' % ivfidx if ivfidx else 'db'
        self.db = LMDBAccessor(self.env, dbname)

        if clear:
            self.clear()

        with self.env.begin() as txn:
            self.num_items = txn.stat(self.db.db)['entries']
            if self.num_items > 0:
                cursor = txn.cursor(self.db.db)
                keys = []
                codes = []
                for key, code in cursor:
                    # print len(key), [ord(c) for c in key], unpack('i', key)[0]
                    keys.append(unpack('i', key)[0])
                    codes.append(pickle.loads(code))
                self.keys = np.array(keys)
                self.codes = np.vstack(tuple(codes)) 
开发者ID:hdidx,项目名称:hdidx,代码行数:24,代码来源:lmdb_storage.py


示例10: unpickle_dict

# 需要导入模块: import cPickle [as 别名]
# 或者: from cPickle import loads [as 别名]
def unpickle_dict(items):
    """un-pickles a dictionary that was pickled with `pickle_dict`.

    Args:
        items (dict): A pickled dictionary.

    Returns:
        dict: An un-pickled dictionary.
    """
    pickled_keys = items.pop('_pickled', '').split(',')
    ret = {}
    for k, v in items.items():
        if k in pickled_keys:
            ret[k] = pickle.loads(v)
        else:
            ret[k] = v
    return ret 
开发者ID:afrase,项目名称:kodiswift,代码行数:19,代码来源:common.py


示例11: TestCustomFormat

# 需要导入模块: import cPickle [as 别名]
# 或者: from cPickle import loads [as 别名]
def TestCustomFormat():
    OpenClipboard()
    try:
        # Just for the fun of it pickle Python objects through the clipboard
        fmt = RegisterClipboardFormat("Python Pickle Format")
        import cPickle
        pickled_object = Foo(a=1, b=2, Hi=3)
        SetClipboardData(fmt, cPickle.dumps( pickled_object ) )
        # Now read it back.
        data = GetClipboardData(fmt)
        loaded_object = cPickle.loads(data)
        assert cPickle.loads(data) == pickled_object, "Didnt get the correct data!"

        print "Clipboard custom format tests worked correctly"
    finally:
        CloseClipboard() 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:18,代码来源:win32clipboardDemo.py


示例12: ListTableColumns

# 需要导入模块: import cPickle [as 别名]
# 或者: from cPickle import loads [as 别名]
def ListTableColumns(self, table):
        """Return a list of columns in the given table.
        [] if the table doesn't exist.
        """
        assert isinstance(table, str)
        if contains_metastrings(table):
            raise ValueError, "bad table name: contains reserved metastrings"

        columnlist_key = _columns_key(table)
        if not getattr(self.db, "has_key")(columnlist_key):
            return []
        pickledcolumnlist = getattr(self.db, "get_bytes",
                self.db.get)(columnlist_key)
        if pickledcolumnlist:
            return pickle.loads(pickledcolumnlist)
        else:
            return [] 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:19,代码来源:dbtables.py


示例13: _extract

# 需要导入模块: import cPickle [as 别名]
# 或者: from cPickle import loads [as 别名]
def _extract(self, rec):
        if rec is None:
            return None
        else:
            key, data = rec
            # Safe in Python 2.x because expresion short circuit
            if sys.version_info[0] < 3 or isinstance(data, bytes) :
                return key, cPickle.loads(data)
            else :
                return key, cPickle.loads(bytes(data, "iso8859-1"))  # 8 bits

    #----------------------------------------------
    # Methods allowed to pass-through to self.dbc
    #
    # close, count, delete, get_recno, join_item


#--------------------------------------------------------------------------- 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:20,代码来源:dbshelve.py


示例14: test_float

# 需要导入模块: import cPickle [as 别名]
# 或者: from cPickle import loads [as 别名]
def test_float(self):
        for_bin_protos = [4.94e-324, 1e-310]
        neg_for_bin_protos = [-x for x in for_bin_protos]
        test_values = [0.0, 7e-308, 6.626e-34, 0.1, 0.5,
                       3.14, 263.44582062374053, 6.022e23, 1e30]
        test_proto0_values = test_values + [-x for x in test_values]
        test_values = test_proto0_values + for_bin_protos + neg_for_bin_protos

        for value in test_proto0_values:
            pickle = self.dumps(value, 0)
            got = self.loads(pickle)
            self.assertEqual(value, got)

        for proto in pickletester.protocols[1:]:
            for value in test_values:
                pickle = self.dumps(value, proto)
                got = self.loads(pickle)
                self.assertEqual(value, got)

    # Backwards compatibility was explicitly broken in r67934 to fix a bug. 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:22,代码来源:test_xpickle.py


示例15: from_string

# 需要导入模块: import cPickle [as 别名]
# 或者: from cPickle import loads [as 别名]
def from_string(s):
        return pickle.loads(s) 
开发者ID:aleju,项目名称:cat-bbs,代码行数:4,代码来源:plotting.py


示例16: load_from_filepath

# 需要导入模块: import cPickle [as 别名]
# 或者: from cPickle import loads [as 别名]
def load_from_filepath(fp):
        #return json.loads(open(, "r").read())
        with open(fp, "r") as f:
            history = pickle.load(f)
        return history 
开发者ID:aleju,项目名称:cat-bbs,代码行数:7,代码来源:plotting.py


示例17: get_batch

# 需要导入模块: import cPickle [as 别名]
# 或者: from cPickle import loads [as 别名]
def get_batch(self):
        """Returns a batch from the queue of augmented batches."""
        batch_str = self.queue_result.get()
        batch = pickle.loads(batch_str)
        return batch 
开发者ID:aleju,项目名称:cat-bbs,代码行数:7,代码来源:train.py


示例18: load_object

# 需要导入模块: import cPickle [as 别名]
# 或者: from cPickle import loads [as 别名]
def load_object(self, value):
        """The reversal of :meth:`dump_object`.  This might be callde with
        None.
        """
        if value is None:
            return None
        if value.startswith('!'):
            return pickle.loads(value[1:])
        try:
            return int(value)
        except ValueError:
            # before 0.8 we did not have serialization.  Still support that.
            return value 
开发者ID:jojoin,项目名称:cutout,代码行数:15,代码来源:rediscache.py


示例19: get

# 需要导入模块: import cPickle [as 别名]
# 或者: from cPickle import loads [as 别名]
def get(self, key):
        now = time()
        expires, value = self._cache.get(key, (0, None))
        if expires > time():
            return pickle.loads(value) 
开发者ID:jojoin,项目名称:cutout,代码行数:7,代码来源:memcache.py


示例20: _process_task

# 需要导入模块: import cPickle [as 别名]
# 或者: from cPickle import loads [as 别名]
def _process_task(self, data, task_callable, task_index):
        """Add a task, if possible without blocking.

        It blocks when the maximum number of threads is reached (given by
        n_threads) or when the system is not able to start a new thread.
        """
        task_started = False
        while not task_started:
            if self._n_active_threads >= self._n_threads:
                # release lock for other threads and wait
                self._lock.release()
                time.sleep(SLEEP_TIME)
                self._lock.acquire()
            else:
                self._lock.release()
                task_callable = task_callable.fork()
                if self.copy_callable:
                    # create a deep copy of the task_callable,
                    # since it might not be thread safe 
                    # (but the fork is still required)
                    as_str = pickle.dumps(task_callable, -1)
                    task_callable = pickle.loads(as_str)
                try:
                    thread = threading.Thread(target=self._task_thread,
                                              args=(data, task_callable,
                                                    task_index))
                    thread.start()
                    task_started = True
                except Exception:
                    if self.verbose:
                        print ("unable to create new thread,"
                               " waiting 2 seconds...")
                    time.sleep(2) 
开发者ID:ME-ICA,项目名称:me-ica,代码行数:35,代码来源:thread_schedule.py


示例21: unpickle_dict

# 需要导入模块: import cPickle [as 别名]
# 或者: from cPickle import loads [as 别名]
def unpickle_dict(items):
    '''Returns a dict pickled with pickle_dict'''
    pickled_keys = items.pop('_pickled', '').split(',')
    ret = {}
    for key, val in items.items():
        if key in pickled_keys:
            ret[key] = pickle.loads(val)
        else:
            ret[key] = val
    return ret 
开发者ID:jmarth,项目名称:plugin.video.kmediatorrent,代码行数:12,代码来源:common.py


示例22: get

# 需要导入模块: import cPickle [as 别名]
# 或者: from cPickle import loads [as 别名]
def get(self, key, default=None):
        if key in self._db:
            expires, value = pickle.loads(self._db[key])
            if not expires or expires > self._now:
                return value
            else:
                del(self._db[key])
        return default 
开发者ID:RIPE-NCC,项目名称:ripe-atlas-tools,代码行数:10,代码来源:cache.py


示例23: python_value

# 需要导入模块: import cPickle [as 别名]
# 或者: from cPickle import loads [as 别名]
def python_value(self, value):
        if value is not None:
            if isinstance(value, unicode_type):
                value = value.encode('raw_unicode_escape')
            return pickle.loads(value) 
开发者ID:danielecook,项目名称:Quiver-alfred,代码行数:7,代码来源:fields.py


示例24: get

# 需要导入模块: import cPickle [as 别名]
# 或者: from cPickle import loads [as 别名]
def get(self, timeout=None):
        """Receive, decode and return data from the pipe. Block
        gevent-cooperatively until data is available or timeout expires. The
        default decoder is ``pickle.loads``.

        :arg timeout: ``None`` (default) or a ``gevent.Timeout``
            instance. The timeout must be started to take effect and is
            canceled when the first byte of a new message arrives (i.e.
            providing a timeout does not guarantee that the method completes
            within the timeout interval).

        :returns: a Python object.

        Raises:
            - :exc:`gevent.Timeout` (if provided)
            - :exc:`GIPCError`
            - :exc:`GIPCClosed`
            - :exc:`pickle.UnpicklingError`

        Recommended usage for silent timeout control::

            with gevent.Timeout(TIME_SECONDS, False) as t:
                reader.get(timeout=t)

        .. warning::

            The timeout control is currently not available on Windows,
            because Windows can't apply select() to pipe handles.
            An ``OSError`` is expected to be raised in case you set a
            timeout.
        """
        self._validate()
        with self._lock:
            if timeout:
                # Wait for ready-to-read event.
                h = gevent.get_hub()
                h.wait(h.loop.io(self._fd, 1))
                timeout.cancel()
            msize, = struct.unpack("!i", self._recv_in_buffer(4).getvalue())
            bindata = self._recv_in_buffer(msize).getvalue()
        return self._decoder(bindata) 
开发者ID:jgehrcke,项目名称:gipc,代码行数:43,代码来源:gipc.py


示例25: test_pickle

# 需要导入模块: import cPickle [as 别名]
# 或者: from cPickle import loads [as 别名]
def test_pickle(ms_lib):
    buff = pickle.dumps(ms_lib)
    mnew = pickle.loads(buff)
    assert ms_lib._arctic_lib.get_name() == mnew._arctic_lib.get_name()

    assert "arctic_test.TEST" in str(ms_lib)
    assert str(ms_lib) == repr(ms_lib) 
开发者ID:man-group,项目名称:arctic,代码行数:9,代码来源:test_metadata_store.py


示例26: test_arctic_set_get_state

# 需要导入模块: import cPickle [as 别名]
# 或者: from cPickle import loads [as 别名]
def test_arctic_set_get_state():
    sentinel.mongo_host = Mock(nodes={("host", "port")})
    with patch('arctic._cache.Cache.__init__', autospec=True, return_value=None):
        store = Arctic(sentinel.mongo_host, allow_secondary="allow_secondary", app_name="app_name",
                       socketTimeoutMS=1234, connectTimeoutMS=2345, serverSelectionTimeoutMS=3456)
        buff = pickle.dumps(store)
        mnew = pickle.loads(buff)
        assert mnew.mongo_host == "host:port"
        assert mnew._allow_secondary == "allow_secondary"
        assert mnew._application_name == "app_name"
        assert mnew._socket_timeout == 1234
        assert mnew._connect_timeout == 2345
        assert mnew._server_selection_timeout == 3456 
开发者ID:man-group,项目名称:arctic,代码行数:15,代码来源:test_arctic.py


示例27: loads

# 需要导入模块: import cPickle [as 别名]
# 或者: from cPickle import loads [as 别名]
def loads(*args, **kwargs):
    # NumPy 1.15.0, 2017-12-10
    warnings.warn(
        "np.core.numeric.loads is deprecated, use pickle.loads instead",
        DeprecationWarning, stacklevel=2)
    return pickle.loads(*args, **kwargs) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:8,代码来源:numeric.py


示例28: get

# 需要导入模块: import cPickle [as 别名]
# 或者: from cPickle import loads [as 别名]
def get(self, key):
        try:
            expires, value = self._cache[key]
            if expires == 0 or expires > time():
                return pickle.loads(value)
        except (KeyError, pickle.PickleError):
            return None 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:9,代码来源:cache.py



注:本文中的cPickle.loads方法示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。