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

Python ordereddict.OrderedDict类代码示例

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

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



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

示例1: get_loan_list

 def get_loan_list(self):
     accounts = OrderedDict()
     # New website
     for table in self.document.xpath('//div[@class="panel"]'):
         title = table.getprevious()
         if title is None:
             continue
         account_type = self.ACCOUNT_TYPES.get(self.parser.tocleanstring(title), Account.TYPE_UNKNOWN)
         for tr in table.xpath('./table/tbody/tr[contains(@id,"MM_SYNTHESE_CREDITS") and contains(@id,"IdTrGlobal")]'):
             tds = tr.findall('td')
             if len(tds) == 0 :
                 continue
             for i in tds[0].xpath('.//a/strong'):
                 label = i.text.strip()
                 break
             balance = Decimal(FrenchTransaction.clean_amount(self.parser.tocleanstring(tds[-1])))
             account = Account()
             account.id = label.split(' ')[-1]
             account.label = unicode(label)
             account.type = account_type
             account.balance = -abs(balance)
             account.currency = account.get_currency(self.parser.tocleanstring(tds[-1]))
             account._card_links = []
             accounts[account.id] = account
     return accounts.itervalues()
开发者ID:dasimon,项目名称:weboob,代码行数:25,代码来源:pages.py


示例2: format

    def format(self, obj, selected_fields=None):
        """
        Format an object to be human-readable.
        An object has fields which can be selected.
        If the object provides an iter_fields() method, the formatter will
        call it. It can be used to specify the fields order.

        @param obj  [object] object to format
        @param selected_fields  [tuple] fields to display. If None, all fields are selected
        @return  a string of the formatted object
        """
        assert isinstance(obj, (dict, CapBaseObject, tuple))

        if isinstance(obj, dict):
            item = obj
        elif isinstance(obj, tuple):
            item = OrderedDict([(k, v) for k, v in obj])
        else:
            item = self.to_dict(obj, selected_fields)

        if item is None:
            return None

        if self.MANDATORY_FIELDS:
            missing_fields = set(self.MANDATORY_FIELDS) - set(item.keys())
            if missing_fields:
                raise MandatoryFieldsNotFound(missing_fields)

        formatted = self.format_dict(item=item)
        if formatted:
            self.after_format(formatted)
        return formatted
开发者ID:jocelynj,项目名称:weboob,代码行数:32,代码来源:iformatter.py


示例3: get_list

    def get_list(self):
        accounts = OrderedDict()

        for tr in self.document.getiterator('tr'):
            first_td = tr.getchildren()[0]
            if (first_td.attrib.get('class', '') == 'i g' or first_td.attrib.get('class', '') == 'p g') \
               and first_td.find('a') is not None:

                a = first_td.find('a')
                link = a.get('href', '')
                if link.startswith('POR_SyntheseLst'):
                    continue

                url = urlparse(link)
                p = parse_qs(url.query)
                if not 'rib' in p:
                    continue

                for i in (2,1):
                    balance = FrenchTransaction.clean_amount(tr.getchildren()[i].text)
                    currency = Account.get_currency(tr.getchildren()[i].text)
                    if len(balance) > 0:
                        break
                balance = Decimal(balance)

                id = p['rib'][0]
                if id in accounts:
                    account = accounts[id]
                    if not account.coming:
                        account.coming = Decimal('0.0')
                    account.coming += balance
                    account._card_links.append(link)
                    continue

                account = Account()
                account.id = id
                account.label = unicode(a.text).strip().lstrip(' 0123456789').title()
                account._link_id = link
                account._card_links = []

                # Find accounting amount
                page = self.browser.get_document(self.browser.openurl(link))
                coming = self.find_amount(page, u"Opérations à venir")
                accounting = self.find_amount(page, u"Solde comptable")

                if accounting is not None and accounting + (coming or Decimal('0')) != balance:
                    self.logger.warning('%s + %s != %s' % (accounting, coming, balance))

                if accounting is not None:
                    balance = accounting

                if coming is not None:
                    account.coming = coming
                account.balance = balance
                account.currency = currency

                accounts[account.id] = account

        return accounts.itervalues()
开发者ID:blckshrk,项目名称:Weboob,代码行数:59,代码来源:pages.py


示例4: get_list

    def get_list(self):
        accounts = OrderedDict()

        # Old website
        for table in self.document.xpath('//table[@cellpadding="1"]'):
            account_type = Account.TYPE_UNKNOWN
            for tr in table.xpath('./tr'):
                tds = tr.findall('td')
                if tr.attrib.get('class', '') == 'DataGridHeader':
                    account_type = self.ACCOUNT_TYPES.get(tds[1].text.strip(), Account.TYPE_UNKNOWN)
                else:
                    label = ''
                    i = 1
                    a = None
                    while label == '' and i < len(tds):
                        a = tds[i].find('a')
                        if a is None:
                            continue

                        label = self.parser.tocleanstring(a)
                        i += 1

                    balance = ''
                    i = -1
                    while balance == '' and i > -len(tds):
                        try:
                            balance = self.parser.tocleanstring(tds[i].xpath('./a')[0])
                        except KeyError:
                            balance = u''.join([txt.strip() for txt in tds[i].itertext()])
                        i -= 1
                    self._add_account(accounts, a, label, account_type, balance)

        if len(accounts) == 0:
            # New website
            for table in self.document.xpath('//div[@class="panel"]'):
                title = table.getprevious()
                if title is None:
                    continue
                account_type = self.ACCOUNT_TYPES.get(self.parser.tocleanstring(title), Account.TYPE_UNKNOWN)
                for tr in table.xpath('.//tr'):
                    tds = tr.findall('td')
                    for i in xrange(len(tds)):
                        a = tds[i].find('a')
                        if a is not None:
                            break

                    if a is None:
                        continue

                    label = self.parser.tocleanstring(tds[0])
                    balance = self.parser.tocleanstring(tds[-1])

                    self._add_account(accounts, a, label, account_type, balance)

        return accounts.itervalues()
开发者ID:vicnet,项目名称:weboob,代码行数:55,代码来源:pages.py


示例5: get_profile

    def get_profile(self):
        title = self.parser.select(self.document.getroot(), 'title', 1)
        if title.text == 'OkCupid: Account Not Found':
            return None

        profile = {}
        profile['id'] = unicode(title.text[len('OkCupid: '):])
        profile['data'] = OrderedDict()

        profile_p = self.parser.select(self.document.getroot(), "//div[@id='page_content']//p", method='xpath')

        profile['data']['infos'] = ProfileNode('infos', u'Informations', OrderedDict(), flags=ProfileNode.SECTION)

        info = {
                        'age' : unicode(profile_p[1].text.split(' / ')[0]),
                        'sex' : unicode(profile_p[1].text.split(' / ')[1]),
                        'orientation' : unicode(profile_p[1].text.split(' / ')[2]),
                        'relationship' : unicode(profile_p[1].text.split(' / ')[3]),
            }

        for key, val in info.iteritems():
            profile['data']['infos'].value[key] = ProfileNode(key, key.capitalize(), val)

        div_essays = self.parser.select(self.document.getroot(), "//div[@class='essay']", method='xpath')
        h3_essays = self.parser.select(self.document.getroot(), "//div[@id='page_content']//h3", method='xpath')
        essays = OrderedDict(zip(h3_essays, div_essays))

        profile['data']['look_for'] = ProfileNode('look_for', u'Look for', OrderedDict(), flags=ProfileNode.SECTION)
        profile['data']['details'] = ProfileNode('details', u'Details', OrderedDict(), flags=ProfileNode.SECTION)
        profile['data']['essays'] = ProfileNode('essays', u'Essays', OrderedDict(), flags=ProfileNode.SECTION)

        for label, val in essays.iteritems():
            label = unicode(label.text).strip()
            txt = self.parser.tocleanstring(val)
            if 'looking for' in label:
                for i, li in enumerate(val.xpath('.//li')):
                    profile['data']['look_for'].value['look_for_%s' % i] = ProfileNode('look_for_%s' % i, '', li.text.strip())
            elif 'summary' in label and 'summary' not in profile:
                profile['summary'] = txt
            else:
                key = label.replace(' ', '_')
                profile['data']['essays'].value[key] = ProfileNode(key, label, txt)

        details_div = self.parser.select(self.document.getroot(), "//div[@id='details']//li", method='xpath')
        for elem in details_div:
            label = unicode(elem.getchildren()[0].text.strip())
            val = unicode(elem.getchildren()[1].text.strip())
            key = label.lower().replace(' ', '_')
            profile['data']['details'].value[key] = ProfileNode(key, label, val)

        return profile
开发者ID:Konubinix,项目名称:weboob,代码行数:51,代码来源:pages.py


示例6: get_list

    def get_list(self):
        accounts = OrderedDict()

        # Old website
        for table in self.document.xpath('//table[@cellpadding="1"]'):
            account_type = Account.TYPE_UNKNOWN
            for tr in table.xpath('./tr'):
                tds = tr.findall('td')
                if tr.attrib.get('class', '') == 'DataGridHeader':
                    account_type = self.ACCOUNT_TYPES.get(tds[1].text.strip()) or\
                                   self.ACCOUNT_TYPES.get(self.parser.tocleanstring(tds[2])) or\
                                   self.ACCOUNT_TYPES.get(self.parser.tocleanstring(tds[3]), Account.TYPE_UNKNOWN)
                else:
                    # On the same row, there are many accounts (for example a
                    # check accound and a card one).
                    if len(tds) > 4:
                        for i, a in enumerate(tds[2].xpath('./a')):
                            label = self.parser.tocleanstring(a)
                            balance = self.parser.tocleanstring(tds[-2].xpath('./a')[i])
                            self._add_account(accounts, a, label, account_type, balance)
                    # Only 4 tds on banque de la reunion website.
                    elif len(tds) == 4:
                        for i, a in enumerate(tds[1].xpath('./a')):
                            label = self.parser.tocleanstring(a)
                            balance = self.parser.tocleanstring(tds[-1].xpath('./a')[i])
                            self._add_account(accounts, a, label, account_type, balance)

        if len(accounts) == 0:
            # New website
            for table in self.document.xpath('//div[@class="panel"]'):
                title = table.getprevious()
                if title is None:
                    continue
                account_type = self.ACCOUNT_TYPES.get(self.parser.tocleanstring(title), Account.TYPE_UNKNOWN)
                for tr in table.xpath('.//tr'):
                    tds = tr.findall('td')
                    for i in xrange(len(tds)):
                        a = tds[i].find('a')
                        if a is not None:
                            break

                    if a is None:
                        continue

                    label = self.parser.tocleanstring(tds[0])
                    balance = self.parser.tocleanstring(tds[-1])

                    self._add_account(accounts, a, label, account_type, balance)

        return accounts.itervalues()
开发者ID:dasimon,项目名称:weboob,代码行数:50,代码来源:pages.py


示例7: on_loaded

 def on_loaded(self):
     self.accounts = OrderedDict()
     self.parse_table('comptes',         Account.TYPE_CHECKING)
     self.parse_table('comptesEpargne',  Account.TYPE_SAVINGS)
     self.parse_table('comptesTitres',   Account.TYPE_MARKET)
     self.parse_table('comptesVie',      Account.TYPE_DEPOSIT)
     self.parse_table('comptesRetraireEuros')
开发者ID:Boussadia,项目名称:weboob,代码行数:7,代码来源:accountlist.py


示例8: on_loaded

 def on_loaded(self):
     self.accounts = OrderedDict()
     self.parse_table("comptes")
     self.parse_table("comptesEpargne")
     self.parse_table("comptesTitres")
     self.parse_table("comptesVie")
     self.parse_table("comptesRetraireEuros")
开发者ID:hugues,项目名称:weboob,代码行数:7,代码来源:accountlist.py


示例9: AccountList

class AccountList(Page):
    def on_loaded(self):
        if self.document.xpath(u'//h2[text()="%s"]' % u'ERREUR'):
            raise BrowserUnavailable()
        self.accounts = OrderedDict()
        self.parse_table('comptes',         Account.TYPE_CHECKING)
        self.parse_table('comptesEpargne',  Account.TYPE_SAVINGS)
        self.parse_table('comptesTitres',   Account.TYPE_MARKET)
        self.parse_table('comptesVie',      Account.TYPE_DEPOSIT)
        self.parse_table('comptesRetraireEuros')

    def get_accounts_list(self):
        return self.accounts.itervalues()

    def parse_table(self, what, actype=Account.TYPE_UNKNOWN):
        tables = self.document.xpath("//table[@id='%s']" % what, smart_strings=False)
        if len(tables) < 1:
            return

        lines = tables[0].xpath(".//tbody/tr")
        for line in lines:
            account = Account()
            tmp = line.xpath("./td//a")[0]
            account.label = to_unicode(tmp.text)
            account.type = actype
            account._link_id = tmp.get("href")
            if 'BourseEnLigne' in account._link_id:
                account.type = Account.TYPE_MARKET

            tmp = line.xpath("./td/span/strong")
            if len(tmp) >= 2:
                tmp_id = tmp[0].text
                tmp_balance = tmp[1].text
            else:
                tmp_id = line.xpath("./td//span")[1].text
                tmp_balance = tmp[0].text

            account.id = tmp_id
            account.currency = account.get_currency(tmp_balance)
            account.balance = Decimal(FrenchTransaction.clean_amount(tmp_balance))

            if account.id in self.accounts:
                a = self.accounts[account.id]
                a._card_links.append(account._link_id)
                if not a.coming:
                    a.coming = Decimal('0.0')
                a.coming += account.balance
            else:
                account._card_links = []
                self.accounts[account.id] = account

                page = self.browser.get_page(self.browser.openurl(self.browser.buildurl('/voscomptes/canalXHTML/comptesCommun/imprimerRIB/init-imprimer_rib.ea', ('compte.numero', account.id))))
                account.iban = page.get_iban()

    def get_account(self, id):
        try:
            return self.accounts[id]
        except KeyError:
            raise AccountNotFound('Unable to find account: %s' % id)
开发者ID:dasimon,项目名称:weboob,代码行数:59,代码来源:accountlist.py


示例10: on_loaded

 def on_loaded(self):
     if self.document.xpath(u'//h2[text()="%s"]' % u'ERREUR'):
         raise BrowserUnavailable()
     self.accounts = OrderedDict()
     self.parse_table('comptes',         Account.TYPE_CHECKING)
     self.parse_table('comptesEpargne',  Account.TYPE_SAVINGS)
     self.parse_table('comptesTitres',   Account.TYPE_MARKET)
     self.parse_table('comptesVie',      Account.TYPE_DEPOSIT)
     self.parse_table('comptesRetraireEuros')
开发者ID:nojhan,项目名称:weboob-devel,代码行数:9,代码来源:accountlist.py


示例11: get_list

    def get_list(self):
        accounts = OrderedDict()

        for tr in self.document.getiterator('tr'):
            first_td = tr.getchildren()[0]
            if (first_td.attrib.get('class', '') == 'i g' or first_td.attrib.get('class', '') == 'p g') \
               and first_td.find('a') is not None:

                a = first_td.find('a')
                link = a.get('href', '')
                if link.startswith('POR_SyntheseLst'):
                    continue

                url = urlparse(link)
                p = parse_qs(url.query)
                if not 'rib' in p:
                    continue

                for i in (2,1):
                    balance = FrenchTransaction.clean_amount(tr.getchildren()[i].text.strip(' EUR'))
                    if len(balance) > 0:
                        break
                balance = Decimal(balance)

                id = p['rib'][0]
                if id in accounts:
                    account = accounts[id]
                    if not account.coming:
                        account.coming = Decimal('0.0')
                    account.coming += balance
                    account._card_links.append(link)
                    continue

                account = Account()
                account.id = id
                account.label = unicode(a.text).strip().lstrip(' 0123456789').title()
                account._link_id = link
                account._card_links = []

                account.balance = balance

                accounts[account.id] = account

        return accounts.itervalues()
开发者ID:eirmag,项目名称:weboob,代码行数:44,代码来源:pages.py


示例12: on_loaded

    def on_loaded(self):
        for script in self.document.xpath('//script'):
            text = script.text
            if text is None:
                continue
            m = re.search("window.location.replace\('([^']+)'\);", text)
            if m:
                self.browser.location(m.group(1))

        try:
            self.browser.select_form(name='banque')
        except FormNotFoundError:
            pass
        else:
            self.browser.set_all_readonly(False)
            accounts = OrderedDict()
            for tr in self.document.getroot().cssselect('table.compteTable > tbody > tr'):
                if len(tr.findall('td')) == 0:
                    continue
                attr = tr.xpath('.//a')[0].attrib.get('onclick', '')
                m = re.search("value = '(\w+)';(checkAndSubmit\('\w+','(\w+)','(\w+)'\))?", attr)
                if m:
                    typeCompte = m.group(1)
                    tagName = m.group(3)
                    if tagName is not None:
                        value = self.document.xpath('//input[@name="%s"]' % m.group(3))[int(m.group(4))].attrib['value']
                    else:
                        value = typeCompte
                    accounts[value] = (typeCompte, tagName)

            try:
                typeCompte, tagName = accounts[self.browser.accnum]
                value = self.browser.accnum
            except KeyError:
                accnums = ', '.join(accounts.keys())
                if self.browser.accnum != '00000000000':
                    self.logger.warning(u'Unable to find account "%s". Available ones: %s' % (self.browser.accnum, accnums))
                elif len(accounts) > 1:
                    self.logger.warning('There are several accounts, please use "accnum" backend parameter to force the one to use (%s)' % accnums)
                value, (typeCompte, tagName) = accounts.popitem(last=False)
            self.browser['typeCompte'] = typeCompte
            if tagName is not None:
                self.browser[tagName] = [value]
            self.browser.submit()
开发者ID:Boussadia,项目名称:weboob,代码行数:44,代码来源:pages.py


示例13: AccountList

class AccountList(BasePage):
    def on_loaded(self):
        self.accounts = OrderedDict()
        self.parse_table('comptes',         Account.TYPE_CHECKING)
        self.parse_table('comptesEpargne',  Account.TYPE_SAVINGS)
        self.parse_table('comptesTitres',   Account.TYPE_MARKET)
        self.parse_table('comptesVie',      Account.TYPE_DEPOSIT)
        self.parse_table('comptesRetraireEuros')

    def get_accounts_list(self):
        return self.accounts.itervalues()

    def parse_table(self, what, actype=Account.TYPE_UNKNOWN):
        tables = self.document.xpath("//table[@id='%s']" % what, smart_strings=False)
        if len(tables) < 1:
            return

        lines = tables[0].xpath(".//tbody/tr")
        for line in lines:
            account = Account()
            tmp = line.xpath("./td//a")[0]
            account.label = to_unicode(tmp.text)
            account.type = actype
            account._link_id = tmp.get("href")
            if 'BourseEnLigne' in account._link_id:
                account.type = Account.TYPE_MARKET

            tmp = line.xpath("./td/span/strong")
            if len(tmp) >= 2:
                tmp_id = tmp[0].text
                tmp_balance = tmp[1].text
            else:
                tmp_id = line.xpath("./td//span")[1].text
                tmp_balance = tmp[0].text

            account.id = tmp_id
            account.currency = account.get_currency(tmp_balance)
            account.balance = Decimal(FrenchTransaction.clean_amount(tmp_balance))

            if account.id in self.accounts:
                a = self.accounts[account.id]
                a._card_links.append(account._link_id)
                if not a.coming:
                    a.coming = Decimal('0.0')
                a.coming += account.balance
            else:
                account._card_links = []
                self.accounts[account.id] = account

    def get_account(self, id):
        try:
            return self.accounts[id]
        except KeyError:
            raise AccountNotFound('Unable to find account: %s' % id)
开发者ID:Boussadia,项目名称:weboob,代码行数:54,代码来源:accountlist.py


示例14: __init__

 def __init__(self, name, backend):
     self.my_id = backend.browser.get_userid()
     self.name = 'wiki/weboob/%s' % name
     self.description = None
     self.date = None
     self.begin = None
     self.end = None
     self.location = None
     self.winner = None
     self.backend = backend
     self.members = OrderedDict()
     self.load()
开发者ID:juliaL03,项目名称:weboob,代码行数:12,代码来源:boobathon.py


示例15: parse_profile

    def parse_profile(self, profile, consts):
        if profile['online']:
            self.status = Contact.STATUS_ONLINE
            self.status_msg = u'online'
            self.status_msg = u'since %s' % profile['last_cnx']
        else:
            self.status = Contact.STATUS_OFFLINE
            self.status_msg = u'last connection %s' % profile['last_cnx']

        self.summary = html2text(profile.get('announce', '')).strip().replace('\n\n', '\n')
        if len(profile.get('shopping_list', '')) > 0:
            self.summary += u'\n\nLooking for:\n%s' % html2text(profile['shopping_list']).strip().replace('\n\n', '\n')

        for photo in profile['pics']:
            self.set_photo(photo.split('/')[-1],
                              url=photo + '/full',
                              thumbnail_url=photo + '/small',
                              hidden=False)
        self.profile = OrderedDict()

        if 'sex' in profile:
            for section, d in self.TABLE.iteritems():
                flags = ProfileNode.SECTION
                if section.startswith('_'):
                    flags |= ProfileNode.HEAD
                if (section.startswith('+') and int(profile['sex']) != 1) or \
                   (section.startswith('-') and int(profile['sex']) != 0):
                    continue

                section = section.lstrip('_+-')

                s = ProfileNode(section, section.capitalize(), OrderedDict(), flags=flags)

                for key, builder in d.iteritems():
                    try:
                        value = builder.get_value(profile, consts[int(profile['sex'])])
                    except KeyError:
                        pass
                    else:
                        s.value[key] = ProfileNode(key, key.capitalize().replace('_', ' '), value)

                self.profile[section] = s

        self._aum_profile = profile
开发者ID:eirmag,项目名称:weboob,代码行数:44,代码来源:contact.py


示例16: format

    def format(self, obj, selected_fields=None, alias=None):
        """
        Format an object to be human-readable.
        An object has fields which can be selected.

        :param obj: object to format
        :type obj: BaseObject or dict
        :param selected_fields: fields to display. If None, all fields are selected
        :type selected_fields: tuple
        :param alias: an alias to use instead of the object's ID
        :type alias: unicode
        """
        if isinstance(obj, BaseObject):
            if selected_fields:  # can be an empty list (nothing to do), or None (return all fields)
                obj = obj.copy()
                for name, value in obj.iter_fields():
                    if name not in selected_fields:
                        delattr(obj, name)

            if self.MANDATORY_FIELDS:
                missing_fields = set(self.MANDATORY_FIELDS) - set([name for name, value in obj.iter_fields()])
                if missing_fields:
                    raise MandatoryFieldsNotFound(missing_fields)

            formatted = self.format_obj(obj, alias)
        else:
            try:
                obj = OrderedDict(obj)
            except ValueError:
                raise TypeError('Please give a BaseObject or a dict')

            if selected_fields:
                obj = obj.copy()
                for name, value in obj.iteritems():
                    if name not in selected_fields:
                        obj.pop(name)

            if self.MANDATORY_FIELDS:
                missing_fields = set(self.MANDATORY_FIELDS) - set(obj.iterkeys())
                if missing_fields:
                    raise MandatoryFieldsNotFound(missing_fields)

            formatted = self.format_dict(obj)

        if formatted:
            self.output(formatted)
        return formatted
开发者ID:frankrousseau,项目名称:weboob,代码行数:47,代码来源:iformatter.py


示例17: Event

class Event(object):
    def __init__(self, name, backend):
        self.my_id = backend.browser.get_userid()
        self.name = 'wiki/weboob/%s' % name
        self.description = None
        self.date = None
        self.begin = None
        self.end = None
        self.location = None
        self.winner = None
        self.backend = backend
        self.members = OrderedDict()
        self.load()

    def get_me(self):
        return self.members.get(self.backend.browser.get_userid(), None)

    def currently_in_event(self):
        if not self.date or not self.begin or not self.end:
            return False

        return self.begin < datetime.now() < self.end

    def is_closed(self):
        return self.end < datetime.now()

    def format_duration(self):
        if not self.begin or not self.end:
            return None

        delta = self.end - self.begin
        return '%02d:%02d' % (delta.seconds/3600, delta.seconds%3600)

    def check_time_coherence(self):
        """
        Check if the end's day is before the begin's one, in
        case it stops at the next day (eg. 15h->1h).

        If it occures, add a day.
        """
        if self.begin > self.end:
            self.end = self.end + timedelta(1)

    def load(self):
        self.content = self.backend.get_content(self.name)
        self.members.clear()
        member = None
        for line in self.content.content.split('\n'):
            line = line.strip()
            if line.startswith('h1. '):
                self.title = line[4:]
            elif line.startswith('h3=. '):
                m = re.match('h3=. Event finished. Winner is "(.*)":/users/(\d+)\!', line)
                if not m:
                    print >>self.stderr, 'Unable to parse h3=: %s' % line
                    continue
                self.winner = Member(int(m.group(2)), m.group(1))
            elif line.startswith('h2. '):
                continue
            elif line.startswith('h3. '):
                m = re.match('h3. "(.*)":/users/(\d+)', line)
                if not m:
                    print >>self.stderr, 'Unable to parse user "%s"' % line
                    continue
                member = Member(int(m.group(2)), m.group(1))
                if member.id == self.my_id:
                    member.is_me = True
                if self.winner is not None and member.id == self.winner.id:
                    self.winner = member
                self.members[member.id] = member
            elif self.description is None and len(line) > 0 and line != '{{TOC}}':
                self.description = line
            elif line.startswith('* '):
                m = re.match('\* \*(\w+)\*: (.*)', line)
                if not m:
                    continue
                key, value = m.group(1), m.group(2)
                if member is None:
                    if key == 'Date':
                        self.date = self.parse_date(value)
                    elif key == 'Start' or key == 'Begin':
                        self.begin = self.parse_time(value)
                    elif key == 'End':
                        self.end = self.parse_time(value)
                        self.check_time_coherence()
                    elif key == 'Location':
                        self.location = value
                else:
                    if key == 'Repository':
                        m = re.match('"(.*.git)":.*', value)
                        if m:
                            member.repository = m.group(1)
                        else:
                            member.repository = value
                    elif key == 'Hardware':
                        member.hardware = value
                    elif key == 'Availabilities':
                        member.availabilities = value
            elif line.startswith('[['):
                m = re.match('\[\[(\w+)\]\]\|\[\[(\w+)\]\]\|(.*)\|', line)
#.........这里部分代码省略.........
开发者ID:juliaL03,项目名称:weboob,代码行数:101,代码来源:boobathon.py


示例18: __init__

 def __init__(self, *args, **kwargs):
     super(ListElement, self).__init__(*args, **kwargs)
     self.logger = getLogger(self.__class__.__name__.lower())
     self.objects = OrderedDict()
开发者ID:ffourcot,项目名称:weboob,代码行数:4,代码来源:elements.py


示例19: ListElement

class ListElement(AbstractElement):
    item_xpath = None
    flush_at_end = False
    ignore_duplicate = False

    def __init__(self, *args, **kwargs):
        super(ListElement, self).__init__(*args, **kwargs)
        self.logger = getLogger(self.__class__.__name__.lower())
        self.objects = OrderedDict()

    def __call__(self, *args, **kwargs):
        for key, value in kwargs.iteritems():
            self.env[key] = value

        return self.__iter__()

    def find_elements(self):
        """
        Get the nodes that will have to be processed.
        This method can be overridden if xpath filters are not
        sufficient.
        """
        if self.item_xpath is not None:
            for el in self.el.xpath(self.item_xpath):
                yield el
        else:
            yield self.el

    def __iter__(self):
        self.parse(self.el)

        items = []
        for el in self.find_elements():
            for attrname in dir(self):
                attr = getattr(self, attrname)
                if isinstance(attr, type) and issubclass(attr, AbstractElement) and attr != type(self):
                    item = attr(self.page, self, el)
                    item.handle_loaders()
                    items.append(item)

        for item in items:
            for obj in item:
                obj = self.store(obj)
                if obj and not self.flush_at_end:
                    yield obj

        if self.flush_at_end:
            for obj in self.flush():
                yield obj

        self.check_next_page()

    def flush(self):
        for obj in self.objects.itervalues():
            yield obj

    def check_next_page(self):
        if not hasattr(self, 'next_page'):
            return

        next_page = getattr(self, 'next_page')
        try:
            value = self.use_selector(next_page)
        except (AttributeNotFound, XPathNotFound):
            return

        if value is None:
            return

        raise NextPage(value)


    def store(self, obj):
        if obj.id:
            if obj.id in self.objects:
                if self.ignore_duplicate:
                    self.logger.warning('There are two objects with the same ID! %s' % obj.id)
                    return
                else:
                    raise DataError('There are two objects with the same ID! %s' % obj.id)
            self.objects[obj.id] = obj
        return obj
开发者ID:ffourcot,项目名称:weboob,代码行数:82,代码来源:elements.py


示例20: registerEvent

    def registerEvent(self):
        selection = self.ui.modulesList.selectedItems()
        if not selection:
            return

        try:
            module = self.weboob.modules_loader.get_or_load_module(unicode(selection[0].text()).lower())
        except ModuleLoadError:
            module = None

        if not module:
            return

        dialog = QDialog(self)
        vbox = QVBoxLayout(dialog)
        if module.website:
            website = 'on the website <b>%s</b>' % module.website
        else:
            website = 'with the module <b>%s</b>' % module.name
        vbox.addWidget(QLabel('To create an account %s, please provide this information:' % website))
        formlayout = QFormLayout()
        props_widgets = OrderedDict()
        for key, prop in module.klass.ACCOUNT_REGISTER_PROPERTIES.iteritems():
            widget = QtValue(prop)
            formlayout.addRow(QLabel(u'%s:' % prop.label), widget)
            props_widgets[prop.id] = widget

        vbox.addLayout(formlayout)
        buttonBox = QDialogButtonBox(dialog)
        buttonBox.setStandardButtons(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
        self.connect(buttonBox, SIGNAL("accepted()"), dialog.accept)
        self.connect(buttonBox, SIGNAL("rejected()"), dialog.reject)
        vbox.addWidget(buttonBox)

        end = False
        while not end:
            end = True
            if dialog.exec_():
                account = Account()
                account.properties = {}
                for key, widget in props_widgets.iteritems():
                    try:
                        v = widget.get_value()
                    except ValueError as e:
                        QMessageBox.critical(self, self.tr('Invalid value'),
                            unicode(self.tr('Invalid value for field "%s":<br /><br />%s')) % (key, e))
                        end = False
                        break
                    else:
                        account.properties[key] = v
                if end:
                    try:
                        module.klass.register_account(account)
                    except AccountRegisterError as e:
                        QMessageBox.critical(self, self.tr('Error during register'),
                            unicode(self.tr('Unable to register account %s:<br /><br />%s')) % (website, e))
                        end = False
                    else:
                        for key, value in account.properties.iteritems():
                            if key in self.config_widgets:
                                self.config_widgets[key][1].set_value(value)
开发者ID:kyrre,项目名称:weboob,代码行数:61,代码来源:backendcfg.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python db.DB类代码示例发布时间:2022-05-26
下一篇:
Python misc.to_unicode函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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