• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python util.sorted函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中trac.util.sorted函数的典型用法代码示例。如果您正苦于以下问题:Python sorted函数的具体用法?Python sorted怎么用?Python sorted使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: expand_macro

    def expand_macro(self, formatter, name, content):
        args, kw = util.parse_args(content)
        prefix = args and args[0] or None
        format = kw.get('format', '')
        minsize = max(int(kw.get('min', 2)), 2)
        depth = int(kw.get('depth', -1))
        start = prefix and prefix.count('/') or 0

        wiki = formatter.wiki
        pages = sorted([page for page in wiki.get_pages(prefix) \
                        if 'WIKI_VIEW' in formatter.perm('wiki', page)])
        pagelangs = {}
        for page in pages:
            name, lang = util.split_lang(page, '')
            langs = pagelangs.get(name, [])
            if lang not in langs:
                langs.append(lang)
            pagelangs[name] = langs
        pages = sorted(pagelangs.keys()) # collection of default pages

        upages, spages = self.split_pages(pages)

        def format_page_name(page, split=False):
            try:
                # for trac 0.11                
                return wiki.format_page_name(page, split=split)
            except:
                # for trac 0.10
                if split:
                    return self.PAGE_SPLIT_RE.sub(r"\1 \2", page)
                return page
        def split(page):
            if format != 'group':
                return [format_page_name(page)]
            else:
                return self.SPLIT_RE.split(format_page_name(page, split=True))
        
        # Group by Wiki word and/or Wiki hierarchy
        upages, spages = [[(split(page), page) for page in pages
                           if depth < 0 or depth >= page.count('/') - start]
                          for pages in (upages, spages)]
                          
        def split_in_groups(group):
            """Return list of pagename or (key, sublist) elements"""
            groups = []
            for key, subgrp in groupby(group, lambda (k,p): k and k[0] or ''):
                subgrp = [(k[1:],p) for k,p in subgrp]
                if key and len(subgrp) >= minsize:
                    sublist = split_in_groups(sorted(subgrp))
                    if len(sublist) == 1:
                        elt = (key+sublist[0][0], sublist[0][1])
                    else:
                        elt = (key, sublist)
                    groups.append(elt)
                else:
                    for elt in subgrp:
                        groups.append(elt[1])
            return groups
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:58,代码来源:macros.py


示例2: _get_candidate_subjects

 def _get_candidate_subjects(self, not_in_list = []):
     candidates = []
     users = [user for user in self._get_all_users() 
              if user not in not_in_list]
     candidates += sorted(users)
     candidates += sorted([group.__str__() for group in self.authz.get_groups() 
                           if group.__str__() not in not_in_list])
     #self.env.log.debug("Candidates:")
     #for c in candidates:
     #    self.env.log.debug("   %s" % c)             
     return candidates
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:11,代码来源:admin_ui.py


示例3: _get_candidate_subjects

 def _get_candidate_subjects(self, not_in_list = []):
     candidates = []
     if '*' not in not_in_list:
       candidates.append('*')
       
     users = [user for user in self.account_manager.get_users() 
              if user not in not_in_list]
     candidates += sorted(users)
     candidates += sorted([group.__str__() for group in self.authz.get_groups() 
                           if group.__str__() not in not_in_list])
     self.env.log.debug("Candidates:")
     for c in candidates:
         self.env.log.debug("   %s" % c)             
     return candidates
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:14,代码来源:admin_ui.py


示例4: render_macro

    def render_macro(self, req, name, content):
        intertracs = {}
        for key, value in self.config.options('intertrac'):
            idx = key.rfind('.') # rsplit only in 2.4
            if idx > 0: # 0 itself doesn't help much: .xxx = ...
                prefix, attribute = key[:idx], key[idx+1:]
                intertrac = intertracs.setdefault(prefix, {})
                intertrac[attribute] = value
            else:
                intertracs[key] = value # alias

        def generate_prefix(prefix):
            intertrac = intertracs[prefix]
            if isinstance(intertrac, basestring):
                yield html.TR(html.TD(html.B(prefix)),
                              html.TD('Alias pour ', html.B(intertrac)))
            else:
                url = intertrac.get('url', '')
                if url:
                    title = intertrac.get('title', url)
                    yield html.TR(html.TD(html.A(html.B(prefix),
                                                 href=url + '/timeline')),
                                  html.TD(html.A(title, href=url)))

        return html.TABLE(class_="wiki intertrac")(
            html.TR(html.TH(html.EM('Prefix')), html.TH(html.EM('Site Trac'))),
            [generate_prefix(p) for p in sorted(intertracs.keys())])
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:27,代码来源:intertrac.py


示例5: render_admin_panel

	def render_admin_panel(self, req, cat, page, path_info):
		db = self.env.get_db_cnx()
		cursor = db.cursor()
		field = dict([(field['name'], field) for field in TicketSystem(self.env).get_ticket_fields()])[page]
		cursor.execute('SELECT sid, value FROM hidevals WHERE field = %s', (field['name'],))
		values = cursor.fetchall()
		enabled = field['name'] not in HideValsSystem(self.env).dont_filter
		if req.method == 'POST':
			if req.args.get('add'):
				group = req.args['group']
				value = req.args['value']
				if (group, value) not in values:
					cursor.execute('INSERT INTO hidevals (sid, field, value) VALUES (%s, %s, %s)', (group, field['name'], value))
					db.commit()
			elif req.args.get('remove'):
				sel = req.args.getlist('sel')
				for val in sel:
					group, value = val.split('#', 1)
					cursor.execute('DELETE FROM hidevals WHERE sid = %s AND field = %s AND value = %s', (group, field['name'], value))
					db.commit()
			elif req.args.get('toggle'):
				new_val = HideValsSystem(self.env).dont_filter[:]
				if enabled:
					new_val.append(field['name'])
				else:
					new_val.remove(field['name']) 
				self.config.set('hidevals', 'dont_filter', ', '.join(sorted(new_val)))
				self.config.save()
					
			req.redirect(req.href.admin(cat, page))

		data = {'field' : field,
				'values' : [{'group': g, 'value': v} for g, v in values],
				'enabled' : enabled}
		return 'admin_hidevals.html', data
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:35,代码来源:admin.py


示例6: _edit_path

 def _edit_path(self, req, cat, page, path_info):
     """
         Populates the editpath.* parts of the hdf
         @return the value of editgroup.url or None
     """
     data = {}
     editpath = url2pathname(path_info[path_info.index('/')+1:len(path_info)])            
     paths = [(p.get_repo(), p.get_path()) for p in self.authz.get_paths()]
     validpath = self._get_valid_path(paths, editpath)
     if validpath:
         data['editpath_name'] = editpath
         data['editpath_url'] = pathname2url(editpath)
         pathmembers = self.authz.find_path(validpath[1], validpath[0])
         editpath_members = []
         for member in pathmembers:
             read = write = ""
             if member.is_read():
                 read = "checked"
             if member.is_write():
                 write = "checked"
             
             editpath_members.append({'subject' : member.get_member().__str__(),
                                      'read' : read,
                                      'write' : write})
         data['editpath_members'] = sorted(editpath_members, key=lambda member : member['subject'].lower())
         
         # Populate member candidates
         not_in_list = [m.get_member().__str__() for m in pathmembers]
         candidates = self._get_candidate_subjects(not_in_list)
         if candidates != []:
            data['editpath_candidates'] = candidates
         return data['editpath_url'], data
     return None, {} 
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:33,代码来源:admin_ui.py


示例7: expand_macro

    def expand_macro(self, formatter, name, content):
        intertracs = {}
        for key, value in self.config.options('intertrac'):
            idx = key.rfind('.') # rsplit only in 2.4
            if idx > 0: # 0 itself doesn't help much: .xxx = ...
                prefix, attribute = key[:idx], key[idx+1:]
                intertrac = intertracs.setdefault(prefix, {})
                intertrac[attribute] = value
            else:
                intertracs[key] = value # alias

        def generate_prefix(prefix):
            intertrac = intertracs[prefix]
            if isinstance(intertrac, basestring):
                yield tag.tr(tag.td(tag.b(prefix)),
                             tag.td('Alias for ', tag.b(intertrac)))
            else:
                url = intertrac.get('url', '')
                if url:
                    title = intertrac.get('title', url)
                    yield tag.tr(tag.td(tag.a(tag.b(prefix),
                                              href=url + '/timeline')),
                                 tag.td(tag.a(title, href=url)))

        return tag.table(class_="wiki intertrac")(
            tag.tr(tag.th(tag.em('Prefix')), tag.th(tag.em('Trac Site'))),
            [generate_prefix(p) for p in sorted(intertracs.keys())])
开发者ID:gdgkyoto,项目名称:kyoto-gtug,代码行数:27,代码来源:intertrac.py


示例8: render_macro

    def render_macro(self, req, name, filter):
        from trac.config import Option
        from trac.wiki.formatter import wiki_to_html, wiki_to_oneliner

        filter = filter or ""

        sections = set([section for section, option in Option.registry.keys() if section.startswith(filter)])

        return html.DIV(class_="tracini")(
            [
                (
                    html.H2("[%s]" % section, id="%s-section" % section),
                    html.TABLE(class_="wiki")(
                        html.TBODY(
                            [
                                html.TR(
                                    html.TD(html.TT(option.name)), html.TD(wiki_to_oneliner(option.__doc__, self.env))
                                )
                                for option in Option.registry.values()
                                if option.section == section
                            ]
                        )
                    ),
                )
                for section in sorted(sections)
            ]
        )
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:27,代码来源:macros.py


示例9: save

    def save(self):
        """Write the configuration options to the primary file."""
        if not self.filename:
            return

        # Only save options that differ from the defaults
        sections = []
        for section in self.sections():
            options = []
            for option in self[section]:
                default = self.site_parser.has_option(section, option) and \
                          self.site_parser.get(section, option)
                current = self.parser.has_option(section, option) and \
                          self.parser.get(section, option)
                if current is not False and current != default:
                    options.append((option, current))
            if options:
                sections.append((section, sorted(options)))

        fileobj = file(self.filename, 'w')
        try:
            print>>fileobj, '# -*- coding: utf-8 -*-'
            print>>fileobj
            for section, options in sections:
                print>>fileobj, '[%s]' % section
                for key, val in options:
                    if key in self[section].overridden:
                        print>>fileobj, '# %s = <set in global trac.ini>' % key
                    else:
                        val = val.replace(CRLF, '\n').replace('\n', '\n ')
                        print>>fileobj, '%s = %s' % \
                                        (key, to_unicode(val).encode('utf-8'))
                print>>fileobj
        finally:
            fileobj.close()
开发者ID:cyphactor,项目名称:lifecyclemanager,代码行数:35,代码来源:config.py


示例10: process_request

 def process_request(self, req):
     mode = req.args.get('mode', 'view')
     all_fields = []
     standard_fields = set()
     for f in TicketSystem(self.env).get_ticket_fields():
         all_fields.append(f['name'])
         if not f.get('custom'):
             standard_fields.add(f['name'])
             
     if 'owner' in all_fields:
         curr_idx = all_fields.index('owner')
         if 'cc' in all_fields:
             insert_idx = all_fields.index('cc')
         else:
             insert_idx = len(all_fields)
         if curr_idx < insert_idx:
             all_fields.insert(insert_idx, all_fields[curr_idx])
             del all_fields[curr_idx]
     
     for t in self.types:
         fields = set(getattr(self, t+'_fields'))
         if self.include_std:
             fields.update(standard_fields)
         fields.update(self.forced_fields)
         req.hdf['condfields.types.%s'%t] = dict([
             (f, f in fields) for f in all_fields
         ])
     req.hdf['condfields.mode'] = mode
     req.hdf['condfields.all_fields'] = list(all_fields)
     req.hdf['condfields.ok_fields'] = sorted(set(all_fields) - self.forced_fields, key=lambda x: all_fields.index(x))
     return 'condfields.cs', 'text/javascript'
开发者ID:creswick,项目名称:trac-condfields,代码行数:31,代码来源:web_ui.py


示例11: _do_config

 def _do_config(self, req):
     if req.method == 'POST':
         selected_class = req.args.get('selected')
         self.config.set('account-manager', 'password_store', selected_class)
         selected = self.account_manager.password_store
         for attr, option in _getoptions(selected):
             newvalue = req.args.get('%s.%s' % (selected_class, attr))
             if newvalue is not None:
                 self.config.set(option.section, option.name, newvalue)
                 self.config.save()
     try:
         selected = self.account_manager.password_store
     except AttributeError:
         selected = None
     sections = [
         {'name': store.__class__.__name__,
          'classname': store.__class__.__name__,
          'selected': store is selected,
          'options': [
             {'label': attr,
              'name': '%s.%s' % (store.__class__.__name__, attr),
              'value': option.__get__(store, store),
             }
             for attr, option in _getoptions(store)
          ],
         } for store in self.account_manager.stores
     ]
     sections = sorted(sections, key=lambda i: i['name'])
     req.hdf['sections'] = sections
     return 'admin_accountsconfig.cs', None
开发者ID:lkraav,项目名称:trachacks,代码行数:30,代码来源:admin.py


示例12: render_macro

    def render_macro(self, req, name, content):
        prefix = content or None

        wiki = WikiSystem(self.env)

        return html.UL([html.LI(html.A(wiki.format_page_name(page),
                                       href=req.href.wiki(page)))
                        for page in sorted(wiki.get_pages(prefix))])
开发者ID:cyphactor,项目名称:lifecyclemanager,代码行数:8,代码来源:macros.py


示例13: _render_directory

    def _render_directory(self, req, repos, node, rev=None):
        req.perm.assert_permission('BROWSER_VIEW')

        # Entries metadata
        info = []
        for entry in node.get_entries():
            info.append({
                'name': entry.name,
                'fullpath': entry.path,
                'is_dir': entry.isdir,
                'content_length': entry.content_length,
                'size': pretty_size(entry.content_length),
                'rev': entry.rev,
                'log_href': req.href.log(entry.path, rev=rev),
                'browser_href': req.href.browser(entry.path, rev=rev)
            })
        changes = get_changes(self.env, repos, [i['rev'] for i in info])

        # Ordering of entries
        order = req.args.get('order', 'name').lower()
        desc = req.args.has_key('desc')

        if order == 'date':
            def file_order(a):
                return changes[a['rev']]['date_seconds']
        elif order == 'size':
            def file_order(a):
                return (a['content_length'],
                        embedded_numbers(a['name'].lower()))
        else:
            def file_order(a):
                return embedded_numbers(a['name'].lower())

        dir_order = desc and 1 or -1

        def browse_order(a):
            return a['is_dir'] and dir_order or 0, file_order(a)
        info = sorted(info, key=browse_order, reverse=desc)

        switch_ordering_hrefs = {}
        for col in ('name', 'size', 'date'):
            switch_ordering_hrefs[col] = req.href.browser(
                node.path, rev=rev, order=col,
                desc=(col == order and not desc and 1 or None))

        # ''Zip Archive'' alternate link
        patterns = self.downloadable_paths
        if node.path and patterns and \
               filter(None, [fnmatchcase(node.path, p) for p in patterns]):
            zip_href = req.href.changeset(rev or repos.youngest_rev, node.path,
                                          old=rev, old_path='/', format='zip')
            add_link(req, 'alternate', zip_href, 'Zip Archive',
                     'application/zip', 'zip')

        req.hdf['browser'] = {'order': order, 'desc': desc and 1 or 0,
                              'items': info, 'changes': changes,
                              'order_href': switch_ordering_hrefs}
开发者ID:yeoupooh,项目名称:tow,代码行数:57,代码来源:browser.py


示例14: write_groups

    def write_groups(self, groups):
        """write new group file"""
        group_file_name = self.get_group_filename()
        
        #load the file into the memory
        if os.path.exists(group_file_name):
            group_file = file(group_file_name, 'w')
            try:
                for group_name in sorted(groups):
                    if groups[group_name]: #if non empty
                        group_file.write('%s: %s\n' % (
                            group_name,
                            ' '.join(sorted(groups[group_name]))
                        ))
            finally:
                group_file.close()

        self.env.log.debug('htgroup-editor wrote %r' % (group_file_name,))
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:18,代码来源:admin.py


示例15: _do_htgroup

    def _do_htgroup(self, req):
        """Provide a list of groups, a current group name and a list
        of users in the current group.
        """
        # get the groups from the database file
        groups = self.get_groups()
        
        # prepare the selection and user list
        group_name = req.args.get('group')
        if not group_name or group_name not in groups:
            # no group name given, try to use a default
            if groups: #not empty
                group_name = sorted(groups.keys())[0]
            else:
                group_name = None
        
        
        # process forms/commands
        if req.method == 'POST':
            if req.args.get('add'):
                new_group = req.args.get('new_group')
                new_user = req.args.get('new_user')
                groups.setdefault(new_group, []).append(new_user)
                self.write_groups(groups)
                req.hdf['message'] = u'added %s to %s' % (new_user, new_group)
            elif req.args.get('remove') and req.args.get('group'):
                sel = req.args.get('sel')
                sel = isinstance(sel, list) and sel or [sel]
                for user in sel:
                    groups[req.args.get('group')].remove(user)
                self.write_groups(groups)
                req.hdf['message'] = u'removed %s from %s' % (sel, req.args.get('group'))
        # listst and other info
        req.hdf['groups'] = sorted(groups.keys())
        listing_enabled = isinstance(group_name, basestring) and group_name in groups
        if listing_enabled:
            req.hdf['group'] = group_name
            req.hdf['members'] = sorted(groups[group_name])

        req.hdf['listing_enabled'] = listing_enabled
        req.hdf['selection_enabled'] = len(groups.keys()) > 1
        return 'htgroup_editor.cs', None
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:42,代码来源:admin.py


示例16: get_supported_conversions

 def get_supported_conversions(self, mimetype):
     """Return a list of target MIME types in same form as
     `IContentConverter.get_supported_conversions()`, but with the converter
     component appended. Output is ordered from best to worst quality."""
     converters = []
     for converter in self.converters:
         for k, n, e, im, om, q in converter.get_supported_conversions():
             if im == mimetype and q > 0:
                 converters.append((k, n, e, im, om, q, converter))
     converters = sorted(converters, key=lambda i: i[-2], reverse=True)
     return converters
开发者ID:gdgkyoto,项目名称:kyoto-gtug,代码行数:11,代码来源:api.py


示例17: render_one

 def render_one(page, langs):
     result = [tag.a(wiki.format_page_name(page),
                     href=formatter.href.wiki(page))]
     if langs:
         for lang in sorted(langs):
             result.append(', ')
             p = '%s.%s' % (page, lang)
             result.append(tag.a(lang or 'default',
                                 style='color:#833',
                                 href=formatter.href.wiki(p)))
         result[1] = ' ('
         result.append(')')
     return result
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:13,代码来源:macros.py


示例18: test_conversions

 def test_conversions(self):
     conversions = self.mimeview.get_supported_conversions(
         'trac.ticket.Ticket')
     expected = sorted([('csv', 'Comma-delimited Text', 'csv',
                        'trac.ticket.Ticket', 'text/csv', 8,
                        self.ticket_module),
                       ('tab', 'Tab-delimited Text', 'tsv',
                        'trac.ticket.Ticket', 'text/tab-separated-values', 8,
                        self.ticket_module),
                        ('rss', 'RSS Feed', 'xml',
                         'trac.ticket.Ticket', 'application/rss+xml', 8,
                         self.ticket_module)],
                       key=lambda i: i[-1], reverse=True)
     self.assertEqual(expected, conversions)
开发者ID:gdgkyoto,项目名称:kyoto-gtug,代码行数:14,代码来源:conversion.py


示例19: select

 def select(cls, env, db=None):
     if not db:
         db = env.get_db_cnx()
     cursor = db.cursor()
     cursor.execute("SELECT name,time,description FROM version")
     versions = []
     for name, time, description in cursor:
         version = cls(env)
         version.name = name
         version.time = time and int(time) or None
         version.description = description or ''
         versions.append(version)
     def version_order(v):
         return (v.time or sys.maxint, embedded_numbers(v.name))
     return sorted(versions, key=version_order, reverse=True)
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:15,代码来源:model.py


示例20: get_info

    def get_info( self, timestamp=None ):
        model = Requirement(self.env)
        met = RequirementMetric(model)

        results = met.entropy(timestamp)
        if results is None:
            self.no_results()
        else:
            total_entropy = results[0]
            avg_entropy = results[1]
            components_entropies = results[2]
            req_entropies = results[3]
            fp_entropies = results[4]
            object_entropies = results[5]

            # Ease division below
            if total_entropy == 0:
                total_entropy = 1;

            reqs = []
            for req, entropy in req_entropies.iteritems():
                my_fp = Fp(self.env, id=req[1])['name']
                my_obj = Object(self.env, id=req[2])['name']
                reqs.append({'name': '<'+req[0]+' '+my_fp+' '+my_obj+'>',
                             'link': self.req.href.requirement(req[0]+
                                     '-'+my_fp+'-'+my_obj),
                             'entropy': '%.3f' % entropy})

            components = []
            for comp, entropy in components_entropies.iteritems():
                components.append({'name': comp,
                                   'percent': '%.1f' % (100 * entropy / total_entropy)})
            self.req.hdf['graph_path'] = self.req.href.requirements()+'/graph/'

            self.req.hdf['reqs'] = sorted(reqs, lambda x,y: cmp(float(y['entropy']), float(x['entropy'])))
            self.req.hdf['components'] = sorted(components, lambda x,y: cmp(x['name'], y['name']))
开发者ID:cyphactor,项目名称:lifecyclemanager,代码行数:36,代码来源:view.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python compat.set函数代码示例发布时间:2022-05-27
下一篇:
Python util.shorten_line函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap