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


Python PersistentMapping.values方法代码示例

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


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

示例1: test_persistent_mapping

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import values [as 别名]
 def test_persistent_mapping(self):
     value = PersistentMapping({'foo': 'bar'})
     self.assertEquals({u'foo': u'bar'}, json_compatible(value))
     self.assertEquals('{"foo": "bar"}', json.dumps(json_compatible(value)))
     self.assertIsInstance(json_compatible(value.keys()[0]),
                           unicode,
                           'Dict keys should be converted recursively.')
     self.assertIsInstance(json_compatible(value.values()[0]),
                           unicode,
                           'Dict values should be converted recursively.')
开发者ID:casdr,项目名称:plone.restapi,代码行数:12,代码来源:test_serializer_converters.py

示例2: checkBasicOps

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import values [as 别名]
    def checkBasicOps(self):
        from persistent.mapping import PersistentMapping
        m = PersistentMapping({'x': 1}, a=2, b=3)
        m['name'] = 'bob'
        self.assertEqual(m['name'], "bob")
        self.assertEqual(m.get('name', 42), "bob")
        self.assert_('name' in m)

        try:
            m['fred']
        except KeyError:
            pass
        else:
            self.fail("expected KeyError")
        self.assert_('fred' not in m)
        self.assertEqual(m.get('fred'), None)
        self.assertEqual(m.get('fred', 42), 42)

        keys = m.keys()
        keys.sort()
        self.assertEqual(keys, ['a', 'b', 'name', 'x'])

        values = m.values()
        values.sort()
        self.assertEqual(values, [1, 2, 3, 'bob'])

        items = m.items()
        items.sort()
        self.assertEqual(items,
                         [('a', 2), ('b', 3), ('name', 'bob'), ('x', 1)])

        keys = list(m.iterkeys())
        keys.sort()
        self.assertEqual(keys, ['a', 'b', 'name', 'x'])

        values = list(m.itervalues())
        values.sort()
        self.assertEqual(values, [1, 2, 3, 'bob'])

        items = list(m.iteritems())
        items.sort()
        self.assertEqual(items,
                         [('a', 2), ('b', 3), ('name', 'bob'), ('x', 1)])
开发者ID:Andyvs,项目名称:TrackMonthlyExpenses,代码行数:45,代码来源:testPersistentMapping.py

示例3: checkBasicOps

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import values [as 别名]
    def checkBasicOps(self):
        from persistent.mapping import PersistentMapping

        m = PersistentMapping({"x": 1}, a=2, b=3)
        m["name"] = "bob"
        self.assertEqual(m["name"], "bob")
        self.assertEqual(m.get("name", 42), "bob")
        self.assert_("name" in m)

        try:
            m["fred"]
        except KeyError:
            pass
        else:
            self.fail("expected KeyError")
        self.assert_("fred" not in m)
        self.assertEqual(m.get("fred"), None)
        self.assertEqual(m.get("fred", 42), 42)

        keys = m.keys()
        keys.sort()
        self.assertEqual(keys, ["a", "b", "name", "x"])

        values = m.values()
        values.sort()
        self.assertEqual(values, [1, 2, 3, "bob"])

        items = m.items()
        items.sort()
        self.assertEqual(items, [("a", 2), ("b", 3), ("name", "bob"), ("x", 1)])

        keys = list(m.iterkeys())
        keys.sort()
        self.assertEqual(keys, ["a", "b", "name", "x"])

        values = list(m.itervalues())
        values.sort()
        self.assertEqual(values, [1, 2, 3, "bob"])

        items = list(m.iteritems())
        items.sort()
        self.assertEqual(items, [("a", 2), ("b", 3), ("name", "bob"), ("x", 1)])
开发者ID:grodniewicz,项目名称:oship,代码行数:44,代码来源:testPersistentMapping.py

示例4: CoreFilter

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import values [as 别名]
class CoreFilter(Persistent):
    """Core persistent record filter implementation"""

    implements(IRecordFilter)

    def __init__(self, *args, **kwargs):
        super(CoreFilter, self).__init__(*args, **kwargs)
        self._uid = str(uuid.uuid4())
        self.reset(**kwargs)

    def reset(self, **kwargs):
        self.operator = kwargs.get('operator', 'AND')
        self._queries = PersistentMapping()
        self._order = PersistentList()

    def validate(self, schema):
        for q in self._queries.values():
            if not q.validate(schema):
                raise ValidationError(q.fieldname)

    def build(self, schema):
        self.validate(schema)
        return filter_query(self, schema)

    def add(self, query=None, **kwargs):
        if query is None:
            ## attempt to make query from kwargs given either
            ## field/comparator/value or fieldname/comparator/value
            field = kwargs.get('field', None)
            fieldname = kwargs.get('fieldname', None)
            if not (field or fieldname):
                raise ValueError('Field missing for query construction')
            if fieldname is None and field:
                fieldname = field.__name__
            comparator = kwargs.get('comparator', None)
            value = kwargs.get('value', None)
            if not (value and comparator):
                raise ValueError('Missing value or comparator')
            query = FieldQuery(fieldname, comparator, value)
        fieldname = query.fieldname
        self._queries[fieldname] = query
        self._order.append(fieldname)

    def remove(self, query):
        if IFieldQuery.providedBy(query):
            query = query.fieldname
        if query not in self._queries:
            raise KeyError('Query not found (fieldname: %s)' % query)
        del(self._queries[query])
        self._order.remove(query)

    ## RO mapping interface
    def get(self, name, default=None):
        return self._queries.get(name, default)

    def __len__(self):
        return len(self._order)

    def __getitem__(self, name):
        v = self.get(name, None)
        if v is None:
            raise KeyError(name)  # fieldname not found
        return v

    def __contains__(self, name):
        if IFieldQuery.providedBy(name):
            name = name.field.__name__
        return name in self._order

    def keys(self):
        return list(self._order)

    def iterkeys(self):
        return self._order.__iter__()

    def itervalues(self):
        return itertools.imap(lambda k: self.get(k), self.iterkeys())

    def iteritems(self):
        return itertools.imap(lambda k: (k, self.get(k)), self.iterkeys())

    def values(self):
        return list(self.itervalues())

    def items(self):
        return list(self.iteritems())
开发者ID:upiq,项目名称:uu.formlibrary,代码行数:88,代码来源:filters.py

示例5: TracTicket

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import values [as 别名]
class TracTicket(Item):
    
    implements(ITracTicket)

    def __init__(self, id=None, **kwargs):
        super(TracTicket, self).__init__(id, **kwargs)
        self.priorities = PersistentMapping()
        self.estimate = 0.0

    def Title(self):
        return '# %s: %s' % (self.getId(), self.title.encode('utf-8'))

    def _adapter(self):
        if getattr(self, '_v_trac_adapter', None) is None:
            self._v_trac_adapter = self.__parent__._adapter()
        return self._v_trac_adapter

    def sync(self):
        """Sync local metadata with upstream."""
        listing = self.__parent__
        adapter = self._adapter()
        data = adapter.get(int(self.getId()))
        self._ticket_text = data.get('description', '')
        self.title = _u(data.get('summary', self.getId()))
        self.component = data.get('component', '')
        self.task_type = data.get('type', '')
        self.status = data.get('status', '')
        self.milestone = data.get('milestone', '')
        # estimated hours assumes TimingAndEstimationPlugin
        self.estimate = float(data.get('estimatedhours', 0.0))
        # parent assumes ChildTicketsPlugin
        parent = data.get('parent', '')
        self.parent = int(parent[1:].strip()) if parent else None
        listing.index(self)
        self.reindexObject()

    def url(self):
        """
        Get the base URL from parent listing, but remove any
        authentication credentials -- then use to construct link
        to ticket.
        """
        baseurl = self.__parent__.url.split('/login')[0]
        parts = urlparse.urlparse(baseurl)
        netloc = parts.netloc
        if '@' in netloc:
            netloc = netloc.split('@')[1]
        base = '%s://%s%s' % (parts.scheme, netloc, parts.path)
        return '/'.join((base, 'ticket', self.getId()))

    def text(self):
        if not getattr(self, '_ticket_text', None):
            self.sync()
        return self._ticket_text

    def children(self, uids=False):
        listing = self.__parent__
        keys = listing.children_for(int(self.getId()))
        keys = filter(lambda k: str(k) in listing, keys)
        if uids:
            _get = lambda k: listing.get(str(k))
            return [IUUID(_get(k)) for k in keys]
        return keys

    def score(self):
        return sum(
            filter(
                lambda v: v is not None,
                self.priorities.values()
                )
            )

    def reward_ratio(self):
        if self.estimate > 0.0:
            return self.score() / self.estimate
        return None
开发者ID:upiq,项目名称:uu.trac,代码行数:78,代码来源:content.py

示例6: __init__

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import values [as 别名]
class ContentGroupManager:
    """ """

    def __init__(self):
        self.__groups_collection = PersistentMapping()

    def __add_group_item(self, id, name, filter, pattern):
        #create a new item
        item = ContentGroup(id, name, filter, pattern)
        self.__groups_collection[id] = item

    def __update_group_item(self, id, name, filter, pattern):
        #modify an item
        item = self.__groups_collection.get(id)
        if item is not None:
            item.name =     name
            item.filter =   filter
            item.pattern =  pattern
            self.__groups_collection[id] = item

    def __delete_group_item(self, id):
        #delete an item
        try:    del(self.__groups_collection[id])
        except: pass


    #################
    #   BASIC API   #
    #################
    def get_groups_collection(self):
        #return the groups collection
        return self.__groups_collection

    def get_groups_ids(self):
        #get the groups ids
        return self.__groups_collection.keys()

    def get_groups_list(self):
        #get a list with all items
        return utils.utSortObjsListByAttr(self.__groups_collection.values(), 'name')

    def get_group_item(self, id):
        #get an item
        try:    return self.__groups_collection[id]
        except: return None

    def get_group_item_data(self, id):
        #get an item data
        item = self.get_group_item(id)
        if item is not None: 
            return ['update',
                    item.id,
                    item.name,
                    item.filter,
                    item.pattern,
                    item.start,
                    item.maxResults,
                    item.g_filter,
                    item.restrict,
                    item.safeSearch,
                    item.language,
                    item.inputencoding,
                    item.outputencoding,
                    item.http_proxy,
                    item.search_type]
        else:
            return ['add', '', '', '', '']

    def add_group_item(self, id, name, filter, pattern):
        #create a new item
        self.__add_group_item(id, name, filter, pattern)

    def update_group_item(self, id, name, filter, pattern):
        #modify an item
        self.__update_group_item(id, name, filter, pattern)

    def update_google_props(self, id, start, maxResults, filter, restrict, safeSearch,
                            language, inputencoding, outputencoding, http_proxy):
        #update the Google search properties
        msg = 0
        item = self.__groups_collection.get(id)
        if item is not None:
            #set data
            try:
                #check if integer values
                start =            int(start)
                maxResults =       int(maxResults)
                filter =           int(filter)
                safeSearch =       int(safeSearch)
            except:
                msg = 1
            if not msg:
                #set data
                item.start =            start
                item.maxResults =       maxResults
                item.g_filter =         filter
                item.safeSearch =       safeSearch
                item.restrict =         restrict
                item.language =         language
                item.inputencoding =    inputencoding
#.........这里部分代码省略.........
开发者ID:eea,项目名称:ALiSS_agents,代码行数:103,代码来源:content_group_manager.py

示例7: NounBayesClassifier

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import values [as 别名]
class NounBayesClassifier(Persistent):
    """
    """
    implements(IContentClassifier)
    
    def __init__(self,tagger=None,noNounRanksToKeep = 20):
        """
        """
        self.noNounRanksToKeep = noNounRanksToKeep
        self.trainingDocs = PersistentMapping()
        self.allNouns = OOSet()
        
        self.classifier = None
        self.trainAfterUpdate = True
    
    def addTrainingDocument(self,doc_id,tags):
        """
        """
        storage = getUtility(INounPhraseStorage)
        importantNouns = storage.getNounTerms(doc_id,self.noNounRanksToKeep)
        
        self.trainingDocs[doc_id] = (importantNouns,tags)
        self.allNouns = union(self.allNouns,OOSet(importantNouns))
    
    def train(self):
        """
        """
        presentNouns = dict()
        trainingData = []
        if not self.allNouns:
            storage = getUtility(INounPhraseStorage)
            for key in self.trainingDocs.keys():
                importantNouns = storage.getNounTerms(
                    key,
                    self.noNounRanksToKeep)
                self.allNouns = union(self.allNouns,OOSet(importantNouns))
        for item in self.allNouns:
            presentNouns.setdefault(item,0)
        
        for (nouns,tags) in self.trainingDocs.values():
            nounPresence = presentNouns.copy()
            for noun in nouns:
                nounPresence[noun] = 1
            for tag in tags:
                trainingData.append((nounPresence,tag,))
        if trainingData:
            self.classifier = NaiveBayesClassifier.train(trainingData)
    
    def classify(self,doc_id):
        """
        """
        if not self.classifier:
            return []
        
        presentNouns = dict()
        for item in self.allNouns:
            presentNouns.setdefault(item,0)
        
        storage = getUtility(INounPhraseStorage)
        importantNouns = storage.getNounTerms(doc_id,self.noNounRanksToKeep)
        for noun in importantNouns:
            if noun in presentNouns.keys():
                presentNouns[noun] = 1
        return self.classifier.classify(presentNouns)
    
    def probabilityClassify(self,doc_id):
        """
        """
        if not self.classifier:
            return []
        
        presentNouns = dict()
        for item in self.allNouns:
            presentNouns.setdefault(item,0)
        storage = getUtility(INounPhraseStorage)
        importantNouns = storage.getNounTerms(doc_id,self.noNounRanksToKeep)
        for noun in importantNouns:
            if noun in presentNouns.keys():
                presentNouns[noun] = 1
        return self.classifier.prob_classify(presentNouns)
    
    def clear(self):
        """Wipes the classifier's data.
        """
        self.allNouns.clear()
        self.trainingDocs.clear()
    
    def tags(self):
        if not self.classifier:
            return []
        return self.classifier.labels()
        
开发者ID:soerensigfusson,项目名称:collective.classification,代码行数:93,代码来源:nounbayesclassifier.py

示例8: __init__

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import values [as 别名]
class StopWordManager:
    """ StopWordManager contains the stopwords list """

    def __init__(self):
        self.__stopwords_collection = PersistentMapping()

    def __add_stopword_item(self, id, stopword):
        #create a new item
        item = StopWord(id, stopword)
        self.__stopwords_collection[id] = item

    def __update_stopword_item(self, id, stopword):
        #modify an item
        item = self.__stopwords_collection.get(id)
        if item is not None:
            item.stopword = stopword
            self.__stopwords_collection[id] = item

    def __delete_stopword_item(self, id):
        #delete an item
        try:    del(self.__stopwords_collection[id])
        except: pass

    def __write_stopwords(self):
        #save stopwords to 'aliss_stopwords.txt'
        if not os.path.isdir(ALISS_STOPWORDS_PATH):
            os.mkdir(ALISS_STOPWORDS_PATH)

        sw_file = open(ALISS_STOPWORDS_FILE, 'w')
        f_write = sw_file.write
        f_write("# language = english\n")
        for w in self.get_stopwords_list():
            f_write("%s\n" % w.stopword)
        sw_file.close()


    #################
    #   BASIC API   #
    #################
    def add_stopword_item(self, id, stopword):
        #create a new item
        self.__add_stopword_item(id, stopword)
        self.__write_stopwords()

    def update_stopword_item(self, id, stopword):
        #modify an item
        self.__update_stopword_item(id, stopword)
        self.__write_stopwords()

    def delete_stopword_item(self, ids):
        #delete 1 or more items
        map(self.__delete_stopword_item, ids)
        self.__write_stopwords()


    #################
    #   GETTERS     #
    #################
    def get_stopwords_collection(self):
        #get the collection
        return self.__stopwords_collection

    def get_stopwords_list(self):
        #get a list with all items
        return utils.utSortObjsListByAttr(self.__stopwords_collection.values(), 'stopword')

    def get_stopword_item(self, id):
        #get an item
        try:    return self.__stopwords_collection[id]
        except: return None

    def get_stopword_item_data(self, id):
        #get an item data
        item = self.get_stopword_item(id)
        if item is not None: 
            return ['update', item.id, item.stopword]
        else:
            return ['add', '', '']

    def check_duplicate(self, word):
        #return True if a duplicate is found
        l_word = utils.formatString(word)
        for k in self.get_stopwords_list():
            if l_word == utils.formatString(k.stopword):
                return 1
        return 0


    ##############
    #   EXPORT   #
    ##############
    def export_stopwords(self, orig_url):
        #create exported stopwords XML
        r = []
        ra = r.append

        #XLIFF header
        ra('<?xml version="1.0" encoding="UTF-8"?>')
        ra('<!DOCTYPE xliff SYSTEM "http://www.oasis-open.org/committees/xliff/documents/xliff.dtd">')
        ra('<!-- XLIFF Format Copyright © OASIS Open 2001-2003 -->')
#.........这里部分代码省略.........
开发者ID:eea,项目名称:ALiSS_agents,代码行数:103,代码来源:stopwords_manager.py


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