Ejemplo n.º 1
0
    def data(self, index, role):
        source_index = self.mapToSource(index)
        if source_index.isValid():
            source_data = self.sourceModel().data(source_index, role)
            publication_col = CertifiersTableModel.columns_ids.index('publication')
            publication_index = self.sourceModel().index(source_index.row(), publication_col)
            expiration_col = CertifiersTableModel.columns_ids.index('expiration')
            expiration_index = self.sourceModel().index(source_index.row(), expiration_col)
            written_col = CertifiersTableModel.columns_ids.index('written')
            written_index = self.sourceModel().index(source_index.row(), written_col)

            publication_data = self.sourceModel().data(publication_index, Qt.DisplayRole)
            expiration_data = self.sourceModel().data(expiration_index, Qt.DisplayRole)
            written_data = self.sourceModel().data(written_index, Qt.DisplayRole)
            current_time = QDateTime().currentDateTime().toMSecsSinceEpoch()
            warning_expiration_time = int((expiration_data - publication_data) / 3)
            #logging.debug("{0} > {1}".format(current_time, expiration_data))

            if role == Qt.DisplayRole:
                if source_index.column() == CertifiersTableModel.columns_ids.index('expiration'):
                    if source_data:
                        ts = self.blockchain_processor.adjusted_ts(self.app.currency, source_data)
                        return QLocale.toString(
                            QLocale(),
                            QDateTime.fromTime_t(ts),
                            QLocale.dateTimeFormat(QLocale(), QLocale.ShortFormat)
                        ) + " BAT"
                    else:
                        return ""
                if source_index.column() == CertifiersTableModel.columns_ids.index('publication'):
                    if source_data:
                        ts = self.blockchain_processor.adjusted_ts(self.app.currency, source_data)
                        return QLocale.toString(
                            QLocale(),
                            QDateTime.fromTime_t(ts),
                            QLocale.dateTimeFormat(QLocale(), QLocale.ShortFormat)
                        ) + " BAT"
                    else:
                        return ""
                if source_index.column() == CertifiersTableModel.columns_ids.index('pubkey'):
                    return source_data

            if role == Qt.FontRole:
                font = QFont()
                if not written_data:
                    font.setItalic(True)
                return font

            if role == Qt.ForegroundRole:
                if current_time > ((expiration_data*1000) - (warning_expiration_time*1000)):
                    return QColor("darkorange").darker(120)

            return source_data
Ejemplo n.º 2
0
    def data(self, index, role):
        source_index = self.mapToSource(index)
        source_model = self.sourceModel()
        if not source_index.isValid():
            return QVariant()
        source_data = source_model.data(source_index, role)

        if role == Qt.DisplayRole:
            if index.column() == NetworkTableModel.columns_types.index('is_member'):
                value = {True: QT_TRANSLATE_NOOP("NetworkTableModel", 'yes'),
                         False: QT_TRANSLATE_NOOP("NetworkTableModel", 'no'),
                         None: QT_TRANSLATE_NOOP("NetworkTableModel", 'offline')}
                return value[source_data]

            if index.column() == NetworkTableModel.columns_types.index('pubkey'):
                return source_data[:5]

            if index.column() == NetworkTableModel.columns_types.index('current_block'):
                if source_data == -1:
                    return ""
                else:
                    return source_data

            if index.column() == NetworkTableModel.columns_types.index('address') \
                    or index.column() == NetworkTableModel.columns_types.index('port') \
                    or index.column() == NetworkTableModel.columns_types.index('api'):
                    return "<p>" + source_data.replace('\n', "<br>") + "</p>"

            if index.column() == NetworkTableModel.columns_types.index('current_hash'):
                return source_data[:10]

            if index.column() == NetworkTableModel.columns_types.index('current_time') and source_data:
                ts = self.blockchain_processor.adjusted_ts(self.app.currency, source_data)
                return QLocale.toString(
                            QLocale(),
                            QDateTime.fromTime_t(ts),
                            QLocale.dateTimeFormat(QLocale(), QLocale.ShortFormat)
                        ) + " BAT"

        if role == Qt.TextAlignmentRole:
            if source_index.column() == NetworkTableModel.columns_types.index('address') \
                    or source_index.column() == self.sourceModel().columns_types.index('current_block'):
                return Qt.AlignRight | Qt.AlignVCenter
            if source_index.column() == NetworkTableModel.columns_types.index('is_member'):
                return Qt.AlignCenter

        if role == Qt.FontRole:
            is_root_col = NetworkTableModel.columns_types.index('is_root')
            index_root_col = source_model.index(source_index.row(), is_root_col)
            if source_model.data(index_root_col, Qt.DisplayRole):
                font = QFont()
                font.setBold(True)
                return font

        if role == Qt.BackgroundColorRole and self.app.parameters.dark_theme:
            return source_data.darker()

        return source_data
Ejemplo n.º 3
0
 def new_blocks_handled(self):
     current_block = self.model.current_block()
     current_time = self.model.current_time()
     str_time = QLocale.toString(
                     QLocale(),
                     QDateTime.fromTime_t(current_time),
                     QLocale.dateTimeFormat(QLocale(), QLocale.NarrowFormat)
                 )
     self.view.status_label.setText(self.tr("Blockchain sync : {0} ({1})").format(str_time, str(current_block)[:15]))
Ejemplo n.º 4
0
 def update_time(self):
     dateTime = QDateTime.currentDateTime()
     self.label_time.setText("{0}".format(
         QLocale.toString(
             QLocale(), QDateTime.currentDateTime(),
             QLocale.dateTimeFormat(QLocale(), QLocale.NarrowFormat))))
     timer = QTimer()
     timer.timeout.connect(self.update_time)
     timer.start(1000)
Ejemplo n.º 5
0
    def refresh_status(self):
        """
        Refresh status bar
        """
        logging.debug("Refresh status")
        if self.community:
            text = ""

            current_block_number = self.community.network.current_blockid.number
            if current_block_number:
                text += self.tr(" Block {0}").format(current_block_number)
                try:
                    block = yield from self.community.get_block(current_block_number)
                    text += " ({0})".format(QLocale.toString(
                                QLocale(),
                                QDateTime.fromTime_t(block['medianTime']),
                                QLocale.dateTimeFormat(QLocale(), QLocale.NarrowFormat)
                            ))
                except NoPeerAvailable as e:
                    logging.debug(str(e))
                    text += " ( ### ) "
                except ValueError as e:
                    logging.debug(str(e))

            if len(self.community.network.synced_nodes) == 0:
                self.button_membership.setEnabled(False)
                self.button_certification.setEnabled(False)
                self.button_send_money.setEnabled(False)
            else:
                self.button_membership.setEnabled(True)
                self.button_certification.setEnabled(True)
                self.button_send_money.setEnabled(True)

            if self.community.network.quality > 0.66:
                icon = '<img src=":/icons/connected" width="12" height="12"/>'
            elif self.community.network.quality > 0.33:
                icon = '<img src=":/icons/weak_connect" width="12" height="12"/>'
            else:
                icon = '<img src=":/icons/disconnected" width="12" height="12"/>'

            status_infotext = " - ".join([self.app.notifications[info][0] for info in self.status_info])
            label_text = "{0}{1}".format(icon, text)
            if status_infotext != "":
                label_text += " - {0}".format(status_infotext)

            if self.app.preferences['expert_mode']:
                try:
                    members_pubkeys = yield from self.community.members_pubkeys()
                    label_text += self.tr(" - Median fork window : {0}")\
                        .format(self.community.network.fork_window(members_pubkeys))
                except NoPeerAvailable as e:
                    logging.debug(str(e))
                    label_text += self.tr(" - Median fork window : {0}")\
                        .format("#")

            self.status_label.setText(label_text)
Ejemplo n.º 6
0
 def update_time(self):
     dateTime = QDateTime.currentDateTime()
     self.label_time.setText("{0}".format(QLocale.toString(
                     QLocale(),
                     QDateTime.currentDateTime(),
                     QLocale.dateTimeFormat(QLocale(), QLocale.NarrowFormat)
                 )))
     timer = QTimer()
     timer.timeout.connect(self.update_time)
     timer.start(1000)
Ejemplo n.º 7
0
    def data(self, index, role):
        source_index = self.mapToSource(index)
        source_model = self.sourceModel()
        if not source_index.isValid():
            return QVariant()
        source_data = source_model.data(source_index, role)

        if role == Qt.DisplayRole:
            if index.column() == source_model.columns_types.index('is_member'):
                value = {
                    True: self.tr('yes'),
                    False: self.tr('no'),
                    None: self.tr('offline')
                }
                return value[source_data]

            if index.column() == source_model.columns_types.index('pubkey'):
                return source_data[:5]

            if index.column() == source_model.columns_types.index(
                    'current_block'):
                if source_data == -1:
                    return ""
                else:
                    return source_data

            if index.column() == source_model.columns_types.index(
                    'current_hash'):
                return source_data[:10]

            if index.column() == source_model.columns_types.index(
                    'current_time') and source_data:
                return QLocale.toString(
                    QLocale(), QDateTime.fromTime_t(source_data),
                    QLocale.dateTimeFormat(QLocale(), QLocale.ShortFormat))

        if role == Qt.TextAlignmentRole:
            if source_index.column() == source_model.columns_types.index(
                    'address') or source_index.column() == self.sourceModel(
                    ).columns_types.index('current_block'):
                return Qt.AlignRight | Qt.AlignVCenter
            if source_index.column() == source_model.columns_types.index(
                    'is_member'):
                return Qt.AlignCenter

        if role == Qt.FontRole:
            is_root_col = source_model.columns_types.index('is_root')
            index_root_col = source_model.index(source_index.row(),
                                                is_root_col)
            if source_model.data(index_root_col, Qt.DisplayRole):
                font = QFont()
                font.setBold(True)
                return font

        return source_data
Ejemplo n.º 8
0
    async def refresh_status(self):
        """
        Refresh status bar
        """
        logging.debug("Refresh status")
        if self.community:
            text = ""

            current_block_number = self.community.network.current_blockUID.number
            if current_block_number:
                text += self.tr("Block {0}").format(current_block_number)
                try:
                    block = await self.community.get_block(current_block_number
                                                           )
                    text += " ({0})".format(
                        QLocale.toString(
                            QLocale(),
                            QDateTime.fromTime_t(block['medianTime']),
                            QLocale.dateTimeFormat(QLocale(),
                                                   QLocale.NarrowFormat)))
                except NoPeerAvailable as e:
                    logging.debug(str(e))
                    text += " ( ### ) "
                except errors.DuniterError as e:
                    if e.ucode == errors.BLOCK_NOT_FOUND:
                        logging.debug(str(e))

            if len(self.community.network.synced_nodes) == 0:
                self.button_membership.setEnabled(False)
                self.button_certification.setEnabled(False)
                self.button_send_money.setEnabled(False)
            else:
                self.button_send_money.setEnabled(True)
                self.refresh_quality_buttons()

            if self.community.network.quality > 0.66:
                icon = ':/icons/connected'
            elif self.community.network.quality > 0.33:
                icon = ':/icons/weak_connect'
            else:
                icon = ':/icons/disconnected'

            status_infotext = " - ".join([
                self.account.notifications[info][0]
                for info in self.status_info
            ])
            label_text = text
            if status_infotext != "":
                label_text += " - {0}".format(status_infotext)

            self.status_label.setText(label_text)
            self.label_icon.setPixmap(
                QPixmap(icon).scaled(24, 24, Qt.KeepAspectRatio,
                                     Qt.SmoothTransformation))
Ejemplo n.º 9
0
    async def refresh(self):
        if self.identity and self.identity.local_state != LocalState.NOT_FOUND:
            self.ui.busy.show()
            self.ui.label_uid.setText(self.identity.uid)
            self.ui.label_properties.setText("")
            try:
                identity_selfcert = await self.identity.selfcert(self.community)
                publish_time = await self.community.time(identity_selfcert.timestamp.number)

                join_date = await self.identity.get_join_date(self.community)
                if join_date is None:
                    join_date = self.tr('not a member')
                else:
                    join_date = datetime.datetime.fromtimestamp(join_date).strftime("%d/%m/%Y %I:%M")

            except MembershipNotFoundError:
                join_date = "###"
            except (LookupFailureError, NoPeerAvailable):
                publish_time = None
                join_date = "###"

            if publish_time:
                uid_publish_date = QLocale.toString(
                        QLocale(),
                        QDateTime.fromTime_t(publish_time),
                        QLocale.dateTimeFormat(QLocale(), QLocale.ShortFormat)
                    )
            else:
                uid_publish_date = "###"

            text = self.tr("""
                <table cellpadding="5">
                <tr><td align="right"><b>{:}</b></div></td><td>{:}</td></tr>
                <tr><td align="right"><b>{:}</b></div></td><td>{:}</td></tr>
                <tr><td align="right"><b>{:}</b></div></td><td>{:}</td></tr>
                """).format(
                self.tr('Public key'),
                self.identity.pubkey,
                self.tr('UID Published on'),
                uid_publish_date,
                self.tr('Join date'),
                join_date
            )
            # close html text
            text += "</table>"

            # set text in label
            self.ui.label_properties.setText(text)
            self.ui.busy.hide()
Ejemplo n.º 10
0
    async def refresh_status(self):
        """
        Refresh status bar
        """
        logging.debug("Refresh status")
        if self.community:
            text = ""

            current_block_number = self.community.network.current_blockid.number
            if current_block_number:
                text += self.tr("Block {0}").format(current_block_number)
                try:
                    block = await self.community.get_block(current_block_number)
                    text += " ({0})".format(QLocale.toString(
                                QLocale(),
                                QDateTime.fromTime_t(block['medianTime']),
                                QLocale.dateTimeFormat(QLocale(), QLocale.NarrowFormat)
                            ))
                except NoPeerAvailable as e:
                    logging.debug(str(e))
                    text += " ( ### ) "
                except ValueError as e:
                    logging.debug(str(e))

            if len(self.community.network.synced_nodes) == 0:
                self.button_membership.setEnabled(False)
                self.button_certification.setEnabled(False)
                self.button_send_money.setEnabled(False)
            else:
                self.button_membership.setEnabled(True)
                self.button_certification.setEnabled(True)
                self.button_send_money.setEnabled(True)

            if self.community.network.quality > 0.66:
                icon = ':/icons/connected'
            elif self.community.network.quality > 0.33:
                icon = ':/icons/weak_connect'
            else:
                icon = ':/icons/disconnected'

            status_infotext = " - ".join([self.account.notifications[info][0] for info in self.status_info])
            label_text = text
            if status_infotext != "":
                label_text += " - {0}".format(status_infotext)

            self.status_label.setText(label_text)
            self.label_icon.setPixmap(QPixmap(icon).scaled(24, 24, Qt.KeepAspectRatio, Qt.SmoothTransformation))
Ejemplo n.º 11
0
    def data(self, index, role):
        source_index = self.mapToSource(index)
        source_model = self.sourceModel()
        if not source_index.isValid():
            return QVariant()
        source_data = source_model.data(source_index, role)

        if role == Qt.DisplayRole:
            if index.column() == source_model.columns_types.index('is_member'):
                value = {True: self.tr('yes'), False: self.tr('no'), None: self.tr('offline')}
                return value[source_data]

            if index.column() == source_model.columns_types.index('pubkey'):
                return source_data[:5]

            if index.column() == source_model.columns_types.index('current_block'):
                if source_data == -1:
                    return ""
                else:
                    return source_data

            if index.column() == source_model.columns_types.index('current_hash') :
                return source_data[:10]

            if index.column() == source_model.columns_types.index('current_time') and source_data:
                return QLocale.toString(
                            QLocale(),
                            QDateTime.fromTime_t(source_data),
                            QLocale.dateTimeFormat(QLocale(), QLocale.ShortFormat)
                        )

        if role == Qt.TextAlignmentRole:
            if source_index.column() == source_model.columns_types.index('address') or source_index.column() == self.sourceModel().columns_types.index('current_block'):
                return Qt.AlignRight | Qt.AlignVCenter
            if source_index.column() == source_model.columns_types.index('is_member'):
                return Qt.AlignCenter

        if role == Qt.FontRole:
            is_root_col = source_model.columns_types.index('is_root')
            index_root_col = source_model.index(source_index.row(), is_root_col)
            if source_model.data(index_root_col, Qt.DisplayRole):
                font = QFont()
                font.setBold(True)
                return font

        return source_data
Ejemplo n.º 12
0
    async def refresh(self):
        if self.identity and self.identity.local_state != LocalState.NOT_FOUND:
            self.ui.busy.show()
            self.ui.label_uid.setText(self.identity.uid)
            self.ui.label_properties.setText("")
            try:
                identity_selfcert = await self.identity.selfcert(self.community
                                                                 )
                publish_time = await self.community.time(
                    identity_selfcert.timestamp.number)

                join_date = await self.identity.get_join_date(self.community)
                if join_date is None:
                    join_date = self.tr('not a member')
                else:
                    join_date = datetime.datetime.fromtimestamp(
                        join_date).strftime("%d/%m/%Y %I:%M")

            except MembershipNotFoundError:
                join_date = "###"
            except (LookupFailureError, NoPeerAvailable):
                publish_time = None
                join_date = "###"

            if publish_time:
                uid_publish_date = QLocale.toString(
                    QLocale(), QDateTime.fromTime_t(publish_time),
                    QLocale.dateTimeFormat(QLocale(), QLocale.ShortFormat))
            else:
                uid_publish_date = "###"

            text = self.tr("""
                <table cellpadding="5">
                <tr><td align="right"><b>{:}</b></div></td><td>{:}</td></tr>
                <tr><td align="right"><b>{:}</b></div></td><td>{:}</td></tr>
                <tr><td align="right"><b>{:}</b></div></td><td>{:}</td></tr>
                """).format(self.tr('Public key'), self.identity.pubkey,
                            self.tr('UID Published on'), uid_publish_date,
                            self.tr('Join date'), join_date)
            # close html text
            text += "</table>"

            # set text in label
            self.ui.label_properties.setText(text)
            self.ui.busy.hide()
Ejemplo n.º 13
0
    async def refresh(self):
        if self.identity:
            self.ui.busy.show()
            self.ui.label_uid.setText(self.identity.uid)
            self.ui.label_properties.setText("")
            try:
                join_date = await self.identity.get_join_date(self.community)
            except MembershipNotFoundError:
                join_date = None

            if join_date is None:
                join_date = self.tr('not a member')
            else:
                join_date = datetime.datetime.fromtimestamp(join_date).strftime("%d/%m/%Y %I:%M")


            identity_selfcert = await self.identity.selfcert(self.community)
            uid_publish_date = QLocale.toString(
                    QLocale(),
                    QDateTime.fromTime_t(identity_selfcert.timestamp),
                    QLocale.dateTimeFormat(QLocale(), QLocale.ShortFormat)
                )

            text = self.tr("""
                <table cellpadding="5">
                <tr><td align="right"><b>{:}</b></div></td><td>{:}</td></tr>
                <tr><td align="right"><b>{:}</b></div></td><td>{:}</td></tr>
                <tr><td align="right"><b>{:}</b></div></td><td>{:}</td></tr>
                """).format(
                self.tr('Public key'),
                self.identity.pubkey,
                self.tr('UID Published on'),
                uid_publish_date,
                self.tr('Join date'),
                join_date
            )
            # close html text
            text += "</table>"

            # set text in label
            self.ui.label_properties.setText(text)
            self.ui.busy.hide()
Ejemplo n.º 14
0
    def data(self, index, role):
        source_index = self.mapToSource(index)
        if source_index.isValid():
            source_data = self.sourceModel().data(source_index, role)
            publication_col = CertifiersTableModel.columns_ids.index(
                'publication')
            publication_index = self.sourceModel().index(
                source_index.row(), publication_col)
            expiration_col = CertifiersTableModel.columns_ids.index(
                'expiration')
            expiration_index = self.sourceModel().index(
                source_index.row(), expiration_col)
            written_col = CertifiersTableModel.columns_ids.index('written')
            written_index = self.sourceModel().index(source_index.row(),
                                                     written_col)

            publication_data = self.sourceModel().data(publication_index,
                                                       Qt.DisplayRole)
            expiration_data = self.sourceModel().data(expiration_index,
                                                      Qt.DisplayRole)
            written_data = self.sourceModel().data(written_index,
                                                   Qt.DisplayRole)
            current_time = QDateTime().currentDateTime().toMSecsSinceEpoch()
            warning_expiration_time = int(
                (expiration_data - publication_data) / 3)
            #logging.debug("{0} > {1}".format(current_time, expiration_data))

            if role == Qt.DisplayRole:
                if source_index.column(
                ) == CertifiersTableModel.columns_ids.index('expiration'):
                    if source_data:
                        ts = self.blockchain_processor.adjusted_ts(
                            self.app.currency, source_data)
                        return QLocale.toString(
                            QLocale(), QDateTime.fromTime_t(ts),
                            QLocale.dateTimeFormat(
                                QLocale(), QLocale.ShortFormat)) + " BAT"
                    else:
                        return ""
                if source_index.column(
                ) == CertifiersTableModel.columns_ids.index('publication'):
                    if source_data:
                        ts = self.blockchain_processor.adjusted_ts(
                            self.app.currency, source_data)
                        return QLocale.toString(
                            QLocale(), QDateTime.fromTime_t(ts),
                            QLocale.dateTimeFormat(
                                QLocale(), QLocale.ShortFormat)) + " BAT"
                    else:
                        return ""
                if source_index.column(
                ) == CertifiersTableModel.columns_ids.index('pubkey'):
                    return source_data

            if role == Qt.FontRole:
                font = QFont()
                if not written_data:
                    font.setItalic(True)
                return font

            if role == Qt.ForegroundRole:
                if current_time > ((expiration_data * 1000) -
                                   (warning_expiration_time * 1000)):
                    return QColor("darkorange").darker(120)

            return source_data
Ejemplo n.º 15
0
    def get_localized_data(self):
        localized_data = {}
        #  try to request money parameters
        try:
            params = self.blockchain_service.parameters()
        except NoPeerAvailable as e:
            logging.debug('community parameters error : ' + str(e))
            return None

        localized_data['currency'] = ROOT_SERVERS[self.connection.currency]["display"]
        localized_data['growth'] = params.c
        localized_data['days_per_dividend'] = QLocale().toString(params.dt / 86400, 'f', 2)

        last_ud, last_ud_base = self.blockchain_service.last_ud()
        members_count = self.blockchain_service.last_members_count()
        previous_ud, previous_ud_base = self.blockchain_service.previous_ud()
        previous_ud_time = self.blockchain_service.previous_ud_time()
        previous_monetary_mass = self.blockchain_service.previous_monetary_mass()
        previous_members_count = self.blockchain_service.previous_members_count()

        localized_data['units'] = self.app.current_ref.instance(0,
                                                                self.connection.currency,
                                                                self.app, None).units
        localized_data['diff_units'] = self.app.current_ref.instance(0,
                                                                     self.connection.currency,
                                                                     self.app, None).diff_units

        if last_ud:
            # display float values
            localized_data['ud'] = self.app.current_ref.instance(last_ud * math.pow(10, last_ud_base),
                                              self.connection.currency,
                                              self.app).diff_localized(False, True)

            localized_data['members_count'] = self.blockchain_service.current_members_count()

            computed_dividend = self.blockchain_service.computed_dividend()
            # display float values
            localized_data['ud_plus_1'] = self.app.current_ref.instance(computed_dividend,
                                              self.connection.currency, self.app).diff_localized(False, True)

            localized_data['mass'] = self.app.current_ref.instance(self.blockchain_service.current_mass(),
                                              self.connection.currency, self.app).localized(False, True)

            ud_median_time = self.blockchain_service.last_ud_time()
            ud_median_time = self.blockchain_processor.adjusted_ts(self.app.currency, ud_median_time)

            localized_data['ud_median_time'] = QLocale.toString(
                QLocale(),
                QDateTime.fromTime_t(ud_median_time),
                QLocale.dateTimeFormat(QLocale(), QLocale.ShortFormat)
            )

            next_ud_median_time = self.blockchain_service.last_ud_time() + params.dt
            next_ud_median_time = self.blockchain_processor.adjusted_ts(self.app.currency, next_ud_median_time)

            localized_data['next_ud_median_time'] = QLocale.toString(
                QLocale(),
                QDateTime.fromTime_t(next_ud_median_time),
                QLocale.dateTimeFormat(QLocale(), QLocale.ShortFormat)
            )

            next_ud_reeval = self.blockchain_service.next_ud_reeval()
            next_ud_reeval = self.blockchain_processor.adjusted_ts(self.app.currency, next_ud_reeval)
            localized_data['next_ud_reeval'] = QLocale.toString(
                QLocale(),
                QDateTime.fromTime_t(next_ud_reeval),
                QLocale.dateTimeFormat(QLocale(), QLocale.ShortFormat)
            )

            if previous_ud:
                mass_minus_1_per_member = (float(0) if previous_ud == 0 or previous_members_count == 0 else
                                           previous_monetary_mass / previous_members_count)
                localized_data['mass_minus_1_per_member'] = self.app.current_ref.instance(mass_minus_1_per_member,
                                                  self.connection.currency, self.app) \
                                                  .localized(False, True)
                localized_data['mass_minus_1'] = self.app.current_ref.instance(previous_monetary_mass,
                                                  self.connection.currency, self.app) \
                                                  .localized(False, True)
                # avoid divide by zero !
                if members_count == 0 or previous_members_count == 0:
                    localized_data['actual_growth'] = float(0)
                else:
                    localized_data['actual_growth'] = (last_ud * math.pow(10, last_ud_base)) / (
                    previous_monetary_mass / members_count)

                previous_ud_time = self.blockchain_processor.adjusted_ts(self.app.currency, previous_ud_time)
                localized_data['ud_median_time_minus_1'] = QLocale.toString(
                    QLocale(),
                    QDateTime.fromTime_t(previous_ud_time),
                    QLocale.dateTimeFormat(QLocale(), QLocale.ShortFormat)
                )
        return localized_data
Ejemplo n.º 16
0
    def data(self, index, role):
        source_index = self.mapToSource(index)
        if source_index.isValid():
            source_data = self.sourceModel().data(source_index, role)
            expiration_col = self.sourceModel().columns_ids.index('expiration')
            expiration_index = self.sourceModel().index(source_index.row(), expiration_col)

            STATUS_NOT_MEMBER = 0
            STATUS_MEMBER = 1
            STATUS_EXPIRE_SOON = 3
            status = STATUS_NOT_MEMBER
            expiration_data = self.sourceModel().data(expiration_index, Qt.DisplayRole)
            current_time = QDateTime().currentDateTime().toMSecsSinceEpoch()
            sig_validity = self.sourceModel().sig_validity()
            warning_expiration_time = int(sig_validity / 3)
            #logging.debug("{0} > {1}".format(current_time, expiration_data))

            if expiration_data is not None:
                status = STATUS_MEMBER
                if current_time > (expiration_data*1000):
                    status = STATUS_NOT_MEMBER
                elif current_time > ((expiration_data*1000) - (warning_expiration_time*1000)):
                    status = STATUS_EXPIRE_SOON

            if role == Qt.DisplayRole:
                if source_index.column() in (self.sourceModel().columns_ids.index('renewed'),
                                             self.sourceModel().columns_ids.index('expiration')):
                    if source_data is not None:
                        return QLocale.toString(
                            QLocale(),
                            QDateTime.fromTime_t(source_data).date(),
                            QLocale.dateFormat(QLocale(), QLocale.ShortFormat)
                        )
                    else:
                        return ""
                if source_index.column() == self.sourceModel().columns_ids.index('publication'):
                    if source_data is not None:
                        return QLocale.toString(
                            QLocale(),
                            QDateTime.fromTime_t(source_data),
                            QLocale.dateTimeFormat(QLocale(), QLocale.LongFormat)
                        )
                    else:
                        return ""
                if source_index.column() == self.sourceModel().columns_ids.index('pubkey'):
                    return "pub:{0}".format(source_data[:5])

            if role == Qt.ForegroundRole:
                if status == STATUS_EXPIRE_SOON:
                    return QColor("darkorange").darker(120)
                elif status == STATUS_NOT_MEMBER:
                    return QColor(Qt.red)
                else:
                    return QColor(Qt.blue)
            if role == Qt.DecorationRole and source_index.column() == self.sourceModel().columns_ids.index('uid'):
                if status == STATUS_NOT_MEMBER:
                    return QIcon(":/icons/not_member")
                elif status == STATUS_MEMBER:
                    return QIcon(":/icons/member")
                elif status == STATUS_EXPIRE_SOON:
                    return QIcon(":/icons/member_warning")

            return source_data
Ejemplo n.º 17
0
    async def refresh_labels(self):
        self.busy.show()
        #  try to request money parameters
        try:
            params = await self.community.parameters()
        except NoPeerAvailable as e:
            logging.debug('community parameters error : ' + str(e))
            return False

        #  try to request money variables from last ud block
        try:
            block_ud = await self.community.get_ud_block()
        except NoPeerAvailable as e:
            logging.debug('community get_ud_block error : ' + str(e))
            return False
        try:
            block_ud_minus_1 = await self.community.get_ud_block(x=1)
        except NoPeerAvailable as e:
            logging.debug('community get_ud_block error : ' + str(e))
            return False

        if block_ud:
            # display float values
            localized_ud = await self.account.current_ref.instance(block_ud['dividend'] * math.pow(10, block_ud['unitbase']),
                                                               self.community,
                                                               self.app) \
                .diff_localized(True, self.app.preferences['international_system_of_units'])

            computed_dividend = await self.community.computed_dividend()
            # display float values
            localized_ud_plus_1 = await self.account.current_ref.instance(computed_dividend,
                                                    self.community, self.app)\
                .diff_localized(True, self.app.preferences['international_system_of_units'])

            localized_mass = await self.account.current_ref.instance(block_ud['monetaryMass'],
                                                    self.community, self.app)\
                .diff_localized(True, self.app.preferences['international_system_of_units'])

            localized_ud_median_time = QLocale.toString(
                        QLocale(),
                        QDateTime.fromTime_t(block_ud['medianTime']),
                        QLocale.dateTimeFormat(QLocale(), QLocale.ShortFormat)
                    )

            localized_next_ud_median_time = QLocale.toString(
                        QLocale(),
                        QDateTime.fromTime_t(block_ud['medianTime'] + params['dt']),
                        QLocale.dateTimeFormat(QLocale(), QLocale.ShortFormat)
                    )

            if block_ud_minus_1:
                mass_minus_1 = (float(0) if block_ud['membersCount'] == 0 else
                        block_ud_minus_1['monetaryMass'] / block_ud['membersCount'])
                localized_mass_minus_1_per_member = await self.account.current_ref.instance(mass_minus_1,
                                                                  self.community, self.app)\
                    .diff_localized(True, self.app.preferences['international_system_of_units'])
                localized_mass_minus_1 = await self.account.current_ref.instance(block_ud_minus_1['monetaryMass'],
                                                                  self.community, self.app)\
                    .diff_localized(True, self.app.preferences['international_system_of_units'])
                # avoid divide by zero !
                if block_ud['membersCount'] == 0 or block_ud_minus_1['monetaryMass'] == 0:
                    actual_growth = float(0)
                else:
                    actual_growth = (block_ud['dividend'] * math.pow(10, block_ud['unitbase'])) / (block_ud_minus_1['monetaryMass'] / block_ud['membersCount'])

                localized_ud_median_time_minus_1 = QLocale.toString(
                    QLocale(),
                    QDateTime.fromTime_t(block_ud_minus_1['medianTime']),
                    QLocale.dateTimeFormat(QLocale(), QLocale.ShortFormat)
                )
            else:
                localized_mass_minus_1_per_member = QLocale().toString(
                        float(0), 'f', self.app.preferences['digits_after_comma']
                )
                localized_mass_minus_1 = QLocale().toString(
                        float(0), 'f', self.app.preferences['digits_after_comma']
                )
                actual_growth = float(0)
                localized_ud_median_time_minus_1 = "####"

            # set infos in label
            self.label_general.setText(
                    self.tr("""
                <table cellpadding="5">
                <tr><td align="right"><b>{:}</b></div></td><td>{:} {:}</td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:} {:}</td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:} {:}</td></tr>
                <tr><td align="right"><b>{:2.2%} / {:} days</b></td><td>{:}</td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                </table>
                """).format(
                    localized_ud,
                    self.tr('Universal Dividend UD(t) in'),
                    self.account.current_ref.instance(0, self.community, self.app, None).diff_units,
                    localized_mass_minus_1,
                    self.tr('Monetary Mass M(t-1) in'),
                    self.account.current_ref.instance(0, self.community, self.app, None).units,
                    block_ud['membersCount'],
                    self.tr('Members N(t)'),
                    localized_mass_minus_1_per_member,
                    self.tr('Monetary Mass per member M(t-1)/N(t) in'),
                    self.account.current_ref.instance(0, self.community, self.app, None).diff_units,
                    actual_growth,
                    params['dt'] / 86400,
                    self.tr('Actual growth c = UD(t)/[M(t-1)/N(t)]'),
                    localized_ud_median_time_minus_1,
                    self.tr('Penultimate UD date and time (t-1)'),
                    localized_ud_median_time,
                    self.tr('Last UD date and time (t)'),
                    localized_next_ud_median_time,
                    self.tr('Next UD date and time (t+1)')
                )
            )
        else:
            self.label_general.setText(self.tr('No Universal Dividend created yet.'))

        if block_ud:
            # set infos in label
            self.label_rules.setText(
                    self.tr("""
                <table cellpadding="5">
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                </table>
                """).format(
                    self.tr('{:2.0%} / {:} days').format(params['c'], params['dt'] / 86400),
                    self.tr('Fundamental growth (c) / Delta time (dt)'),
                    self.tr('UD(t+1) = MAX { UD(t) ; c &#215; M(t) / N(t+1) }'),
                    self.tr('Universal Dividend (formula)'),
                    self.tr('{:} = MAX {{ {:} {:} ; {:2.0%} &#215; {:} {:} / {:} }}').format(
                        localized_ud_plus_1,
                        localized_ud,
                        self.account.current_ref.instance(0, self.community, self.app, None).diff_units,
                        params['c'],
                        localized_mass,
                        self.account.current_ref.instance(0, self.community, self.app, None).diff_units,
                        block_ud['membersCount']
                    ),
                    self.tr('Universal Dividend (computed)')
                )
            )
        else:
            self.label_rules.setText(self.tr('No Universal Dividend created yet.'))

        # set infos in label
        ref_template = """
        <table cellpadding="5">
        <tr><th>{:}</th><td>{:}</td></tr>
        <tr><th>{:}</th><td>{:}</td></tr>
        <tr><th>{:}</th><td>{:}</td></tr>
        <tr><th>{:}</th><td>{:}</td></tr>
        </table>
        """
        templates = []
        for ref_class in Referentials:
            ref = ref_class(0, self.community, self.app, None)
            # print(ref_class.__class__.__name__)
            # if ref_class.__class__.__name__ == 'RelativeToPast':
            #     continue
            templates.append(ref_template.format(self.tr('Name'), ref.translated_name(),
                                        self.tr('Units'), ref.units,
                                        self.tr('Formula'), ref.formula,
                                        self.tr('Description'), ref.description
                                        )
                             )

        self.label_referentials.setText('<hr>'.join(templates))

        # set infos in label
        self.label_money.setText(
                self.tr("""
            <table cellpadding="5">
            <tr><td align="right"><b>{:2.0%} / {:} days</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:} {:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:2.0%}</b></td><td>{:}</td></tr>
            </table>
            """).format(
                        params['c'],
                        params['dt'] / 86400,
                        self.tr('Fundamental growth (c)'),
                        params['ud0'],
                        self.tr('Initial Universal Dividend UD(0) in'),
                        self.community.short_currency,
                        params['dt'] / 86400,
                        self.tr('Time period (dt) in days (86400 seconds) between two UD'),
                        params['medianTimeBlocks'],
                        self.tr('Number of blocks used for calculating median time'),
                        params['avgGenTime'],
                        self.tr('The average time in seconds for writing 1 block (wished time)'),
                        params['dtDiffEval'],
                        self.tr('The number of blocks required to evaluate again PoWMin value'),
                        params['blocksRot'],
                        self.tr('The number of previous blocks to check for personalized difficulty'),
                        params['percentRot'],
                        self.tr('The percent of previous issuers to reach for personalized difficulty')
                )
        )

        # set infos in label
        self.label_wot.setText(
                self.tr("""
            <table cellpadding="5">
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            </table>
            """).format(
                        params['sigPeriod'] / 86400,
                        self.tr('Minimum delay between 2 certifications (in days)'),
                        params['sigValidity'] / 86400,
                        self.tr('Maximum age of a valid signature (in days)'),
                        params['sigQty'],
                        self.tr('Minimum quantity of signatures to be part of the WoT'),
                        params['sigStock'],
                        self.tr('Maximum quantity of active certifications made by member.'),
                        params['sigWindow'],
                        self.tr('Maximum delay a certification can wait before being expired for non-writing.'),
                        params['xpercent'],
                        self.tr('Minimum percent of sentries to reach to match the distance rule'),
                        params['msValidity'] / 86400,
                        self.tr('Maximum age of a valid membership (in days)'),
                        params['stepMax'],
                        self.tr('Maximum distance between each WoT member and a newcomer'),
                )
        )
        self.busy.hide()
Ejemplo n.º 18
0
    def data(self, index, role):
        source_index = self.mapToSource(index)
        if source_index.isValid():
            source_data = self.sourceModel().data(source_index, role)
            expiration_col = IdentitiesTableModel.columns_ids.index('expiration')
            expiration_index = self.sourceModel().index(source_index.row(), expiration_col)

            STATUS_NOT_MEMBER = 0
            STATUS_MEMBER = 1
            STATUS_UNKNOWN = 2
            STATUS_EXPIRE_SOON = 3
            status = STATUS_NOT_MEMBER
            expiration_data = self.sourceModel().data(expiration_index, Qt.DisplayRole)
            current_time = QDateTime().currentDateTime().toMSecsSinceEpoch()
            sig_validity = self.sourceModel().sig_validity()
            warning_expiration_time = int(sig_validity / 3)
            #logging.debug("{0} > {1}".format(current_time, expiration_data))

            if expiration_data == 0:
                status = STATUS_UNKNOWN
            elif expiration_data is not None:
                status = STATUS_MEMBER
                if current_time > (expiration_data*1000):
                    status = STATUS_NOT_MEMBER
                elif current_time > ((expiration_data*1000) - (warning_expiration_time*1000)):
                    status = STATUS_EXPIRE_SOON

            if role == Qt.DisplayRole:
                if source_index.column() in (IdentitiesTableModel.columns_ids.index('renewed'),
                                             IdentitiesTableModel.columns_ids.index('expiration')):
                    if source_data:
                        ts = self.blockchain_processor.adjusted_ts(self.app.currency, source_data)
                        return QLocale.toString(
                            QLocale(),
                            QDateTime.fromTime_t(ts).date(),
                            QLocale.dateFormat(QLocale(), QLocale.ShortFormat)
                        )
                    else:
                        return ""
                if source_index.column() == IdentitiesTableModel.columns_ids.index('publication'):
                    if source_data:
                        ts = self.blockchain_processor.adjusted_ts(self.app.currency, source_data)
                        return QLocale.toString(
                            QLocale(),
                            QDateTime.fromTime_t(ts),
                            QLocale.dateTimeFormat(QLocale(), QLocale.LongFormat)
                        )
                    else:
                        return ""
                if source_index.column() == IdentitiesTableModel.columns_ids.index('pubkey'):
                    return source_data
                if source_index.column() == IdentitiesTableModel.columns_ids.index('block'):
                    return str(source_data)[:20]

            if role == Qt.ForegroundRole:
                if status == STATUS_EXPIRE_SOON:
                    return QColor("darkorange").darker(120)
                elif status == STATUS_NOT_MEMBER:
                    return QColor(Qt.red)
                elif status == STATUS_UNKNOWN:
                    return QColor(Qt.black)
                else:
                    return QColor(Qt.blue)

            if role == Qt.FontRole and status == STATUS_UNKNOWN:
                font = QFont()
                font.setItalic(True)
                return font

            if role == Qt.DecorationRole and source_index.column() == IdentitiesTableModel.columns_ids.index('uid'):
                if status == STATUS_NOT_MEMBER:
                    return QIcon(":/icons/not_member")
                elif status == STATUS_MEMBER:
                    return QIcon(":/icons/member")
                elif status == STATUS_EXPIRE_SOON:
                    return QIcon(":/icons/member_warning")

            return source_data
Ejemplo n.º 19
0
    async def refresh_labels(self):
        self.busy.show()
        #  try to request money parameters
        try:
            params = await self.community.parameters()
        except NoPeerAvailable as e:
            logging.debug('community parameters error : ' + str(e))
            return False

        #  try to request money variables from last ud block
        try:
            block_ud = await self.community.get_ud_block()
        except NoPeerAvailable as e:
            logging.debug('community get_ud_block error : ' + str(e))
            return False
        try:
            block_ud_minus_1 = await self.community.get_ud_block(x=1)
        except NoPeerAvailable as e:
            logging.debug('community get_ud_block error : ' + str(e))
            return False

        if block_ud:
            # display float values
            localized_ud = await self.account.current_ref.instance(block_ud['dividend'] * math.pow(10, block_ud['unitbase']),
                                                               self.community,
                                                               self.app) \
                .diff_localized(True, self.app.preferences['international_system_of_units'])

            computed_dividend = await self.community.computed_dividend()
            # display float values
            localized_ud_plus_1 = await self.account.current_ref.instance(computed_dividend,
                                                    self.community, self.app)\
                .diff_localized(True, self.app.preferences['international_system_of_units'])

            localized_mass = await self.account.current_ref.instance(block_ud['monetaryMass'],
                                                    self.community, self.app)\
                .diff_localized(True, self.app.preferences['international_system_of_units'])

            localized_ud_median_time = QLocale.toString(
                QLocale(), QDateTime.fromTime_t(block_ud['medianTime']),
                QLocale.dateTimeFormat(QLocale(), QLocale.ShortFormat))

            localized_next_ud_median_time = QLocale.toString(
                QLocale(),
                QDateTime.fromTime_t(block_ud['medianTime'] + params['dt']),
                QLocale.dateTimeFormat(QLocale(), QLocale.ShortFormat))

            if block_ud_minus_1:
                mass_minus_1 = (float(0) if block_ud['membersCount'] == 0 else
                                block_ud_minus_1['monetaryMass'] /
                                block_ud['membersCount'])
                localized_mass_minus_1_per_member = await self.account.current_ref.instance(mass_minus_1,
                                                                  self.community, self.app)\
                    .diff_localized(True, self.app.preferences['international_system_of_units'])
                localized_mass_minus_1 = await self.account.current_ref.instance(block_ud_minus_1['monetaryMass'],
                                                                  self.community, self.app)\
                    .diff_localized(True, self.app.preferences['international_system_of_units'])
                # avoid divide by zero !
                if block_ud['membersCount'] == 0 or block_ud_minus_1[
                        'monetaryMass'] == 0:
                    actual_growth = float(0)
                else:
                    actual_growth = (block_ud['dividend'] *
                                     math.pow(10, block_ud['unitbase'])) / (
                                         block_ud_minus_1['monetaryMass'] /
                                         block_ud['membersCount'])

                localized_ud_median_time_minus_1 = QLocale.toString(
                    QLocale(),
                    QDateTime.fromTime_t(block_ud_minus_1['medianTime']),
                    QLocale.dateTimeFormat(QLocale(), QLocale.ShortFormat))
            else:
                localized_mass_minus_1_per_member = QLocale().toString(
                    float(0), 'f', self.app.preferences['digits_after_comma'])
                localized_mass_minus_1 = QLocale().toString(
                    float(0), 'f', self.app.preferences['digits_after_comma'])
                actual_growth = float(0)
                localized_ud_median_time_minus_1 = "####"

            # set infos in label
            self.label_general.setText(
                self.tr("""
                <table cellpadding="5">
                <tr><td align="right"><b>{:}</b></div></td><td>{:} {:}</td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:} {:}</td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:} {:}</td></tr>
                <tr><td align="right"><b>{:2.2%} / {:} days</b></td><td>{:}</td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                </table>
                """).format(
                    localized_ud, self.tr('Universal Dividend UD(t) in'),
                    self.account.current_ref.instance(0, self.community,
                                                      self.app,
                                                      None).diff_units,
                    localized_mass_minus_1, self.tr('Monetary Mass M(t-1) in'),
                    self.account.current_ref.instance(
                        0, self.community, self.app,
                        None).units, block_ud['membersCount'],
                    self.tr('Members N(t)'), localized_mass_minus_1_per_member,
                    self.tr('Monetary Mass per member M(t-1)/N(t) in'),
                    self.account.current_ref.instance(0, self.community,
                                                      self.app,
                                                      None).diff_units,
                    actual_growth, params['dt'] / 86400,
                    self.tr('Actual growth c = UD(t)/[M(t-1)/N(t)]'),
                    localized_ud_median_time_minus_1,
                    self.tr('Penultimate UD date and time (t-1)'),
                    localized_ud_median_time,
                    self.tr('Last UD date and time (t)'),
                    localized_next_ud_median_time,
                    self.tr('Next UD date and time (t+1)')))
        else:
            self.label_general.setText(
                self.tr('No Universal Dividend created yet.'))

        if block_ud:
            # set infos in label
            self.label_rules.setText(
                self.tr("""
                <table cellpadding="5">
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                </table>
                """).format(
                    self.tr('{:2.0%} / {:} days').format(
                        params['c'], params['dt'] / 86400),
                    self.tr('Fundamental growth (c) / Delta time (dt)'),
                    self.tr(
                        'UD(t+1) = MAX { UD(t) ; c &#215; M(t) / N(t+1) }'),
                    self.tr('Universal Dividend (formula)'),
                    self.
                    tr('{:} = MAX {{ {:} {:} ; {:2.0%} &#215; {:} {:} / {:} }}'
                       ).format(
                           localized_ud_plus_1, localized_ud,
                           self.account.current_ref.instance(
                               0, self.community, self.app,
                               None).diff_units, params['c'], localized_mass,
                           self.account.current_ref.instance(
                               0, self.community, self.app, None).diff_units,
                           block_ud['membersCount']),
                    self.tr('Universal Dividend (computed)')))
        else:
            self.label_rules.setText(
                self.tr('No Universal Dividend created yet.'))

        # set infos in label
        ref_template = """
        <table cellpadding="5">
        <tr><th>{:}</th><td>{:}</td></tr>
        <tr><th>{:}</th><td>{:}</td></tr>
        <tr><th>{:}</th><td>{:}</td></tr>
        <tr><th>{:}</th><td>{:}</td></tr>
        </table>
        """
        templates = []
        for ref_class in Referentials:
            ref = ref_class(0, self.community, self.app, None)
            # print(ref_class.__class__.__name__)
            # if ref_class.__class__.__name__ == 'RelativeToPast':
            #     continue
            templates.append(
                ref_template.format(self.tr('Name'), ref.translated_name(),
                                    self.tr('Units'), ref.units,
                                    self.tr('Formula'), ref.formula,
                                    self.tr('Description'), ref.description))

        self.label_referentials.setText('<hr>'.join(templates))

        # set infos in label
        self.label_money.setText(
            self.tr("""
            <table cellpadding="5">
            <tr><td align="right"><b>{:2.0%} / {:} days</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:} {:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:2.0%}</b></td><td>{:}</td></tr>
            </table>
            """).format(
                params['c'], params['dt'] / 86400,
                self.tr('Fundamental growth (c)'), params['ud0'],
                self.tr('Initial Universal Dividend UD(0) in'),
                self.community.short_currency, params['dt'] / 86400,
                self.tr(
                    'Time period (dt) in days (86400 seconds) between two UD'),
                params['medianTimeBlocks'],
                self.tr('Number of blocks used for calculating median time'),
                params['avgGenTime'],
                self.
                tr('The average time in seconds for writing 1 block (wished time)'
                   ), params['dtDiffEval'],
                self.
                tr('The number of blocks required to evaluate again PoWMin value'
                   ), params['blocksRot'],
                self.
                tr('The number of previous blocks to check for personalized difficulty'
                   ), params['percentRot'],
                self.
                tr('The percent of previous issuers to reach for personalized difficulty'
                   )))

        # set infos in label
        self.label_wot.setText(
            self.tr("""
            <table cellpadding="5">
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            </table>
            """).format(
                params['sigPeriod'] / 86400,
                self.tr('Minimum delay between 2 certifications (in days)'),
                params['sigValidity'] / 86400,
                self.tr('Maximum age of a valid signature (in days)'),
                params['sigQty'],
                self.tr(
                    'Minimum quantity of signatures to be part of the WoT'),
                params['sigStock'],
                self.tr(
                    'Maximum quantity of active certifications made by member.'
                ),
                params['sigWindow'],
                self.
                tr('Maximum delay a certification can wait before being expired for non-writing.'
                   ),
                params['xpercent'],
                self.
                tr('Minimum percent of sentries to reach to match the distance rule'
                   ),
                params['msValidity'] / 86400,
                self.tr('Maximum age of a valid membership (in days)'),
                params['stepMax'],
                self.tr(
                    'Maximum distance between each WoT member and a newcomer'),
            ))
        self.busy.hide()
Ejemplo n.º 20
0
    def refresh(self):
        #  try to request money parameters
        try:
            params = self.community.parameters
        except Exception as e:
            logging.debug('community parameters error : ' + str(e))
            return False

        #  try to request money variables from last ud block
        try:
            block = self.community.get_ud_block()
        except Exception as e:
            logging.debug('community get_ud_block error : ' + str(e))
            return False
        try:
            block_t_minus_1 = self.community.get_ud_block(1)
        except Exception as e:
            logging.debug('community get_ud_block error : ' + str(e))
            return False

        if block:
            ud = self.get_referential_diff_value(block['dividend'])
            # if referential type is quantitative...
            if self.account.ref_type() == 'q':
                # display int values
                # use the float type of 64bits, to avoid display a 32bit signed integer...
                localized_ud = QLocale().toString(float(ud), 'f', 0)
                localized_mass_per_member = QLocale().toString(
                    float(self.get_referential_diff_value(block['monetaryMass'] / block['membersCount'])), 'f', 0
                )
                localized_monetary_mass = QLocale().toString(
                    float(self.get_referential_diff_value(block['monetaryMass'])), 'f', 0
                )
            else:
                # display float values
                localized_ud = QLocale().toString(ud, 'f', 6)
                localized_mass_per_member = QLocale().toString(
                    self.get_referential_diff_value(block['monetaryMass'] / block['membersCount']), 'f', 6
                )
                localized_monetary_mass = QLocale().toString(
                    self.get_referential_diff_value(block['monetaryMass']), 'f', 6
                )

            # set infos in label
            self.label_general.setText(
                self.tr("""
                <table cellpadding="5">
                <tr><td align="right"><b>{:}</b></div></td><td>{:} {:}</td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:} {:}</td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:} {:}</td></tr>
                <tr><td align="right"><b>{:2.2%} / {:} days</b></td><td>{:}</td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                </table>
                """).format(
                    localized_ud,
                    self.tr('Universal Dividend UD(t) in'),
                    self.get_referential_diff_name(),
                    localized_monetary_mass,
                    self.tr('Monetary Mass M(t) in'),
                    self.get_referential_diff_name(),
                    block['membersCount'],
                    self.tr('Members N(t)'),
                    localized_mass_per_member,
                    self.tr('Monetary Mass per member M(t)/N(t) in'),
                    self.get_referential_diff_name(),
                    block['dividend'] / (block_t_minus_1['monetaryMass'] / block_t_minus_1['membersCount']),
                    params['dt'] / 86400,
                    self.tr('Actual growth c = UD(t)/[M(t-1)/N(t-1)]'),
                    QLocale.toString(
                        QLocale(),
                        QDateTime.fromTime_t(block['medianTime'] + params['dt']),
                        QLocale.dateTimeFormat(QLocale(), QLocale.ShortFormat)
                    ),
                    self.tr('Next UD date and time (t+1)')
                )
            )
        else:
            self.label_general.setText(self.tr('No Universal Dividend created yet.'))

        if block:
            # if referential type is quantitative...
            if self.account.ref_type() == 'q':
                # display int values
                localized_ud_t1 = QLocale().toString(
                    float(
                        self.get_referential_diff_value(
                            math.ceil(
                                max(block['dividend'], params['c'] * block['monetaryMass'] / block['membersCount'])
                            )
                        )
                    ),
                    'f',
                    0
                )
            else:
                # display float values
                localized_ud_t1 = QLocale().toString(
                    float(
                        self.get_referential_diff_value(
                            math.ceil(
                                max(block['dividend'], params['c'] * block['monetaryMass'] / block['membersCount'])
                            )
                        )
                    ),
                    'f',
                    6
                )

            # set infos in label
            self.label_rules.setText(
                self.tr("""
                <table cellpadding="5">
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                </table>
                """).format(
                    self.tr('{:2.0%} / {:} days').format(params['c'], params['dt'] / 86400),
                    self.tr('Fundamental growth (c) / Delta time (dt)'),
                    self.tr('UD(t+1) = MAX { UD(t) ; c &#215; M(t) / N(t) }'),
                    self.tr('Universal Dividend (formula)'),
                    self.tr('{:} = MAX {{ {:} {:} ; {:2.0%} &#215; {:} {:} / {:} }}').format(
                        localized_ud_t1,
                        localized_ud,
                        self.get_referential_diff_name(),
                        params['c'],
                        localized_monetary_mass,
                        self.get_referential_diff_name(),
                        block['membersCount']
                    ),
                    self.tr('Universal Dividend (computed)')
                )
            )
        else:
            self.label_rules.setText(self.tr('No Universal Dividend created yet.'))

        # set infos in label
        self.label_money.setText(
            self.tr("""
            <table cellpadding="5">
            <tr><td align="right"><b>{:2.0%} / {:} days</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:} {:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:2.0%}</b></td><td>{:}</td></tr>
            </table>
            """).format(
                params['c'],
                params['dt'] / 86400,
                self.tr('Fundamental growth (c)'),
                params['ud0'],
                self.tr('Initial Universal Dividend UD(0) in'),
                self.community.short_currency,
                params['dt'] / 86400,
                self.tr('Time period (dt) in days (86400 seconds) between two UD'),
                params['medianTimeBlocks'],
                self.tr('Number of blocks used for calculating median time'),
                params['avgGenTime'],
                self.tr('The average time in seconds for writing 1 block (wished time)'),
                params['dtDiffEval'],
                self.tr('The number of blocks required to evaluate again PoWMin value'),
                params['blocksRot'],
                self.tr('The number of previous blocks to check for personalized difficulty'),
                params['percentRot'],
                self.tr('The percent of previous issuers to reach for personalized difficulty')
            )
        )

        # set infos in label
        self.label_wot.setText(
            self.tr("""
            <table cellpadding="5">
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            </table>
            """).format(
                params['sigDelay'] / 86400,
                self.tr('Minimum delay between 2 identical certifications (in days)'),
                params['sigValidity'] / 86400,
                self.tr('Maximum age of a valid signature (in days)'),
                params['sigQty'],
                self.tr('Minimum quantity of signatures to be part of the WoT'),
                params['sigWoT'],
                self.tr('Minimum quantity of valid made certifications to be part of the WoT for distance rule'),
                params['msValidity'] / 86400,
                self.tr('Maximum age of a valid membership (in days)'),
                params['stepMax'],
                self.tr('Maximum distance between each WoT member and a newcomer'),
            )
        )
Ejemplo n.º 21
0
    def data(self, index, role):
        source_index = self.mapToSource(index)
        if source_index.isValid():
            source_data = self.sourceModel().data(source_index, role)
            expiration_col = IdentitiesTableModel.columns_ids.index('expiration')
            expiration_index = self.sourceModel().index(source_index.row(), expiration_col)

            STATUS_NOT_MEMBER = 0
            STATUS_MEMBER = 1
            STATUS_UNKNOWN = 2
            STATUS_EXPIRE_SOON = 3
            status = STATUS_NOT_MEMBER
            expiration_data = self.sourceModel().data(expiration_index, Qt.DisplayRole)
            current_time = QDateTime().currentDateTime().toMSecsSinceEpoch()
            sig_validity = self.sourceModel().sig_validity()
            warning_expiration_time = int(sig_validity / 3)
            #logging.debug("{0} > {1}".format(current_time, expiration_data))

            if expiration_data == 0:
                status = STATUS_UNKNOWN
            elif expiration_data is not None:
                status = STATUS_MEMBER
                if current_time > (expiration_data*1000):
                    status = STATUS_NOT_MEMBER
                elif current_time > ((expiration_data*1000) - (warning_expiration_time*1000)):
                    status = STATUS_EXPIRE_SOON

            if role == Qt.DisplayRole:
                if source_index.column() in (IdentitiesTableModel.columns_ids.index('renewed'),
                                             IdentitiesTableModel.columns_ids.index('expiration')):
                    if source_data:
                        ts = self.blockchain_processor.adjusted_ts(self.app.currency, source_data)
                        return QLocale.toString(
                            QLocale(),
                            QDateTime.fromTime_t(ts).date(),
                            QLocale.dateFormat(QLocale(), QLocale.ShortFormat)
                        ) + " BAT"
                    else:
                        return ""
                if source_index.column() == IdentitiesTableModel.columns_ids.index('publication'):
                    if source_data:
                        ts = self.blockchain_processor.adjusted_ts(self.app.currency, source_data)
                        return QLocale.toString(
                            QLocale(),
                            QDateTime.fromTime_t(ts),
                            QLocale.dateTimeFormat(QLocale(), QLocale.LongFormat)
                        ) + " BAT"
                    else:
                        return ""
                if source_index.column() == IdentitiesTableModel.columns_ids.index('pubkey'):
                    return source_data
                if source_index.column() == IdentitiesTableModel.columns_ids.index('block'):
                    return str(source_data)[:20]

            if role == Qt.ForegroundRole:
                if status == STATUS_EXPIRE_SOON:
                    return QColor("darkorange").darker(120)
                elif status == STATUS_NOT_MEMBER:
                    return QColor(Qt.red)
                elif status == STATUS_UNKNOWN:
                    return QColor(Qt.black)
                else:
                    return QColor(Qt.blue)

            if role == Qt.FontRole and status == STATUS_UNKNOWN:
                font = QFont()
                font.setItalic(True)
                return font

            if role == Qt.DecorationRole and source_index.column() == IdentitiesTableModel.columns_ids.index('uid'):
                if status == STATUS_NOT_MEMBER:
                    return QIcon(":/icons/not_member")
                elif status == STATUS_MEMBER:
                    return QIcon(":/icons/member")
                elif status == STATUS_EXPIRE_SOON:
                    return QIcon(":/icons/member_warning")

            return source_data
Ejemplo n.º 22
0
    def display_identity_timestamps(self, pubkey, publish_time, join_date,
                                    mstime_remaining, nb_certs):
        """
        Display identity timestamps in localized format
        :param str pubkey:
        :param int publish_time:
        :param int join_date:
        :return:
        """
        if join_date:
            localized_join_date = QLocale.toString(
                QLocale(),
                QDateTime.fromTime_t(join_date),
                QLocale.dateTimeFormat(QLocale(), QLocale.ShortFormat)
            )
        else:
            localized_join_date = "###"

        if publish_time:
            localized_publish_date = QLocale.toString(
                QLocale(),
                QDateTime.fromTime_t(publish_time),
                QLocale.dateTimeFormat(QLocale(), QLocale.ShortFormat)
            )
        else:
            localized_publish_date = "###"

        if mstime_remaining:
            days, remainder = divmod(mstime_remaining, 3600 * 24)
            hours, remainder = divmod(remainder, 3600)
            minutes, seconds = divmod(remainder, 60)
            if days > 0:
                localized_mstime_remaining = "{days} days".format(days=days)
            else:
                localized_mstime_remaining = "{hours} hours and {min} min.".format(hours=hours,
                                                                               min=minutes)
        else:
            localized_mstime_remaining = "###"


        text = self.tr("""
            <table cellpadding="5">
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:} BAT</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:} BAT</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            """).format(
            self.tr('Public key'),
            pubkey,
            self.tr('UID Published on'),
            localized_publish_date,
            self.tr('Join date'),
            localized_join_date,
            self.tr("Expires in"),
            localized_mstime_remaining,
            self.tr("Certs. received"),
            nb_certs
        )

        # close html text
        text += "</table>"

        # set text in label
        self.label_properties.setText(text)
Ejemplo n.º 23
0
    def set_simple_informations(self, data, state):
        if state in (IdentityView.CommunityState.NOT_INIT,
                     IdentityView.CommunityState.OFFLINE):
            self.label_currency.setText("""<html>
                <body>
                <p>
                <span style=" font-size:16pt; font-weight:600;">{currency}</span>
                </p>
                <p>{message}</p>
                </body>
                </html>""".format(currency=data['currency'],
                                  message=IdentityView.simple_message[state]))
            self.button_membership.hide()
        else:
            if data['written']:
                written_value = self.tr("Identity written in blockchain")
            else:
                expiration_text = QLocale.toString(
                    QLocale(), QDateTime.fromTime_t(data['idty_expiration']),
                    QLocale.dateTimeFormat(QLocale(), QLocale.ShortFormat))
                written_value = self.tr("Identity not written in blockchain") + \
                                " (" + self.tr("Expires on : {0}").format(expiration_text) + " BAT)"

            status_value = self.tr(
                "Member") if data['membership_state'] else self.tr(
                    "Non-Member")
            if data['mstime'] > 0:
                membership_action_value = self.tr("Renew membership")
                status_info = ""
                membership_action_enabled = True
            elif data['membership_state']:
                membership_action_value = self.tr("Renew membership")
                status_info = "Your membership expired"
                membership_action_enabled = True
            else:
                membership_action_value = self.tr("Request membership")
                if data['nb_certs'] > data['nb_certs_required']:
                    status_info = self.tr("Registration ready")
                    membership_action_enabled = True
                else:
                    status_info = self.tr("{0} more certifications required")\
                        .format(data['nb_certs_required'] - data['nb_certs'])
                    membership_action_enabled = True

            if data['mstime'] > 0:
                days, hours, minutes, seconds = timestamp_to_dhms(
                    data['mstime'])
                mstime_remaining_text = self.tr("Expires in ")
                if days > 0:
                    mstime_remaining_text += "{days} days".format(days=days)
                else:
                    mstime_remaining_text += "{hours} hours and {min} min.".format(
                        hours=hours, min=minutes)
            else:
                mstime_remaining_text = self.tr("Expired or never published")

            ms_status_color = '#00AA00' if data[
                'membership_state'] else '#FF0000'
            outdistanced_status_color = '#FF0000' if data[
                'is_outdistanced'] else '#00AA00'
            if data['written']:
                written_status_color = "#00AA00"
            elif data['idty_expired']:
                written_status_color = "#FF0000"
            else:
                written_status_color = '#FF6347'

            description_membership = """<html>
<body>
    <p><span style="font-weight:600;">{status_label}</span>
     : <span style="color:{ms_status_color};">{status}</span>
     - <span>{status_info}</span></p>
</body>
</html>""".format(ms_status_color=ms_status_color,
                  status_label=self.tr("Status"),
                  status=status_value,
                  status_info=status_info)
            description_identity = """<html>
<body>
    <p><span style="font-weight:600;">{nb_certs_label}</span> : {nb_certs} <span style="color:{outdistanced_status_color};">({outdistanced_text})</span></p>
    <p><span style="font-weight:600;">{mstime_remaining_label}</span> : {mstime_remaining}</p>
</body>
</html>""".format(nb_certs_label=self.tr("Certs. received"),
                  nb_certs=data['nb_certs'],
                  outdistanced_text=data['outdistanced'],
                  outdistanced_status_color=outdistanced_status_color,
                  mstime_remaining_label=self.tr("Membership"),
                  mstime_remaining=mstime_remaining_text)

            self.label_written.setText("""
<html>
<body>
    <p><span style="font-weight:450; color:{written_status_color};">{written_label}</span></p>
</body>
</html>
""".format(written_label=written_value,
            written_status_color=written_status_color))

            if data['is_identity']:
                self.label_membership.setText(description_membership)
                self.label_identity.setText(description_identity)
                self.button_membership.setText(membership_action_value)
                self.button_membership.setEnabled(membership_action_enabled)
            else:
                self.label_membership.hide()
                self.label_identity.hide()
                self.button_membership.hide()
Ejemplo n.º 24
0
    def data(self, index, role):
        source_index = self.mapToSource(index)
        if source_index.isValid():
            source_data = self.sourceModel().data(source_index, role)
            expiration_col = self.sourceModel().columns_ids.index('expiration')
            expiration_index = self.sourceModel().index(
                source_index.row(), expiration_col)

            STATUS_NOT_MEMBER = 0
            STATUS_MEMBER = 1
            STATUS_EXPIRE_SOON = 3
            status = STATUS_NOT_MEMBER
            expiration_data = self.sourceModel().data(expiration_index,
                                                      Qt.DisplayRole)
            current_time = QDateTime().currentDateTime().toMSecsSinceEpoch()
            sig_validity = self.sourceModel().sig_validity()
            warning_expiration_time = int(sig_validity / 3)
            #logging.debug("{0} > {1}".format(current_time, expiration_data))

            if expiration_data is not None:
                status = STATUS_MEMBER
                if current_time > (expiration_data * 1000):
                    status = STATUS_NOT_MEMBER
                elif current_time > ((expiration_data * 1000) -
                                     (warning_expiration_time * 1000)):
                    status = STATUS_EXPIRE_SOON

            if role == Qt.DisplayRole:
                if source_index.column() in (
                        self.sourceModel().columns_ids.index('renewed'),
                        self.sourceModel().columns_ids.index('expiration')):
                    if source_data is not None:
                        return QLocale.toString(
                            QLocale(),
                            QDateTime.fromTime_t(source_data).date(),
                            QLocale.dateFormat(QLocale(), QLocale.ShortFormat))
                    else:
                        return ""
                if source_index.column() == self.sourceModel(
                ).columns_ids.index('publication'):
                    if source_data is not None:
                        return QLocale.toString(
                            QLocale(), QDateTime.fromTime_t(source_data),
                            QLocale.dateTimeFormat(QLocale(),
                                                   QLocale.LongFormat))
                    else:
                        return ""
                if source_index.column() == self.sourceModel(
                ).columns_ids.index('pubkey'):
                    return "pub:{0}".format(source_data[:5])

            if role == Qt.ForegroundRole:
                if status == STATUS_EXPIRE_SOON:
                    return QColor("darkorange").darker(120)
                elif status == STATUS_NOT_MEMBER:
                    return QColor(Qt.red)
                else:
                    return QColor(Qt.blue)
            if role == Qt.DecorationRole and source_index.column(
            ) == self.sourceModel().columns_ids.index('uid'):
                if status == STATUS_NOT_MEMBER:
                    return QIcon(":/icons/not_member")
                elif status == STATUS_MEMBER:
                    return QIcon(":/icons/member")
                elif status == STATUS_EXPIRE_SOON:
                    return QIcon(":/icons/member_warning")

            return source_data
Ejemplo n.º 25
0
    def refresh(self):
        #  try to request money parameters
        try:
            params = self.community.parameters
        except Exception as e:
            logging.debug('community parameters error : ' + str(e))
            return False

        #  try to request money variables from last ud block
        try:
            block_ud = self.community.get_ud_block()
        except Exception as e:
            logging.debug('community get_ud_block error : ' + str(e))
            return False
        try:
            block_ud_minus_1 = self.community.get_ud_block(1)
        except Exception as e:
            logging.debug('community get_ud_block error : ' + str(e))
            return False

        if block_ud:
            ud = self.get_referential_diff_value(block_ud['dividend'])
            # if referential type is quantitative...
            if self.account.ref_type() == 'q':
                # display int values
                # use the float type of 64bits, to avoid display a 32bit signed integer...
                localized_ud = QLocale().toString(float(ud), 'f', 0)
                # display int values
                localized_ud_plus_1 = QLocale().toString(
                    float(
                        self.get_referential_diff_value(
                            self.community.computed_dividend)), 'f', 0)
                localized_mass = QLocale().toString(
                    float(
                        self.get_referential_diff_value(
                            block_ud['monetaryMass'])), 'f', 0)
                if block_ud_minus_1:
                    localized_mass_minus_1_per_member = QLocale().toString(
                        float(
                            self.get_referential_diff_value(
                                block_ud_minus_1['monetaryMass'] /
                                block_ud['membersCount'])), 'f', 0)
                    localized_mass_minus_1 = QLocale().toString(
                        float(
                            self.get_referential_diff_value(
                                block_ud_minus_1['monetaryMass'])), 'f', 0)
                else:
                    localized_mass_minus_1_per_member = QLocale().toString(
                        float(0), 'f', 0)
                    localized_mass_minus_1 = QLocale().toString(
                        float(0), 'f', 0)
            else:
                # display float values
                localized_ud = QLocale().toString(ud, 'f', 6)
                # display float values
                localized_ud_plus_1 = QLocale().toString(
                    float(
                        self.get_referential_diff_value(
                            self.community.computed_dividend)), 'f', 6)
                localized_mass = QLocale().toString(
                    float(
                        self.get_referential_diff_value(
                            block_ud['monetaryMass'])), 'f', 6)
                if block_ud_minus_1:
                    localized_mass_minus_1_per_member = QLocale().toString(
                        self.get_referential_diff_value(
                            block_ud_minus_1['monetaryMass'] /
                            block_ud['membersCount']), 'f', 6)
                    localized_mass_minus_1 = QLocale().toString(
                        self.get_referential_diff_value(
                            block_ud_minus_1['monetaryMass']), 'f', 6)
                else:
                    localized_mass_minus_1_per_member = QLocale().toString(
                        float(0), 'f', 6)
                    localized_mass_minus_1 = QLocale().toString(
                        float(0), 'f', 6)

            # set infos in label
            self.label_general.setText(
                self.tr("""
                <table cellpadding="5">
                <tr><td align="right"><b>{:}</b></div></td><td>{:} {:}</td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:} {:}</td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:} {:}</td></tr>
                <tr><td align="right"><b>{:2.2%} / {:} days</b></td><td>{:}</td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                </table>
                """).format(
                    localized_ud, self.tr('Universal Dividend UD(t) in'),
                    self.get_referential_diff_name(), localized_mass_minus_1,
                    self.tr('Monetary Mass M(t-1) in'),
                    self.get_referential_diff_name(), block_ud['membersCount'],
                    self.tr('Members N(t)'), localized_mass_minus_1_per_member,
                    self.tr('Monetary Mass per member M(t-1)/N(t) in'),
                    self.get_referential_diff_name(),
                    block_ud['dividend'] / (block_ud_minus_1['monetaryMass'] /
                                            block_ud['membersCount']),
                    params['dt'] / 86400,
                    self.tr('Actual growth c = UD(t)/[M(t-1)/N(t)]'),
                    QLocale.toString(
                        QLocale(),
                        QDateTime.fromTime_t(block_ud['medianTime']),
                        QLocale.dateTimeFormat(QLocale(),
                                               QLocale.ShortFormat)),
                    self.tr('Last UD date and time (t)'),
                    QLocale.toString(
                        QLocale(),
                        QDateTime.fromTime_t(block_ud['medianTime'] +
                                             params['dt']),
                        QLocale.dateTimeFormat(QLocale(),
                                               QLocale.ShortFormat)),
                    self.tr('Next UD date and time (t+1)')))
        else:
            self.label_general.setText(
                self.tr('No Universal Dividend created yet.'))

        if block_ud:
            # set infos in label
            self.label_rules.setText(
                self.tr("""
                <table cellpadding="5">
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                </table>
                """).format(
                    self.tr('{:2.0%} / {:} days').format(
                        params['c'], params['dt'] / 86400),
                    self.tr('Fundamental growth (c) / Delta time (dt)'),
                    self.tr(
                        'UD(t+1) = MAX { UD(t) ; c &#215; M(t) / N(t+1) }'),
                    self.tr('Universal Dividend (formula)'),
                    self.
                    tr('{:} = MAX {{ {:} {:} ; {:2.0%} &#215; {:} {:} / {:} }}'
                       ).format(localized_ud_plus_1, localized_ud,
                                self.get_referential_diff_name(),
                                params['c'], localized_mass,
                                self.get_referential_diff_name(),
                                block_ud['membersCount']),
                    self.tr('Universal Dividend (computed)')))
        else:
            self.label_rules.setText(
                self.tr('No Universal Dividend created yet.'))

        # set infos in label
        self.label_money.setText(
            self.tr("""
            <table cellpadding="5">
            <tr><td align="right"><b>{:2.0%} / {:} days</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:} {:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:2.0%}</b></td><td>{:}</td></tr>
            </table>
            """).format(
                params['c'], params['dt'] / 86400,
                self.tr('Fundamental growth (c)'), params['ud0'],
                self.tr('Initial Universal Dividend UD(0) in'),
                self.community.short_currency, params['dt'] / 86400,
                self.tr(
                    'Time period (dt) in days (86400 seconds) between two UD'),
                params['medianTimeBlocks'],
                self.tr('Number of blocks used for calculating median time'),
                params['avgGenTime'],
                self.
                tr('The average time in seconds for writing 1 block (wished time)'
                   ), params['dtDiffEval'],
                self.
                tr('The number of blocks required to evaluate again PoWMin value'
                   ), params['blocksRot'],
                self.
                tr('The number of previous blocks to check for personalized difficulty'
                   ), params['percentRot'],
                self.
                tr('The percent of previous issuers to reach for personalized difficulty'
                   )))

        # set infos in label
        self.label_wot.setText(
            self.tr("""
            <table cellpadding="5">
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            </table>
            """).format(
                params['sigDelay'] / 86400,
                self.
                tr('Minimum delay between 2 identical certifications (in days)'
                   ),
                params['sigValidity'] / 86400,
                self.tr('Maximum age of a valid signature (in days)'),
                params['sigQty'],
                self.tr(
                    'Minimum quantity of signatures to be part of the WoT'),
                params['sigWoT'],
                self.
                tr('Minimum quantity of valid made certifications to be part of the WoT for distance rule'
                   ),
                params['msValidity'] / 86400,
                self.tr('Maximum age of a valid membership (in days)'),
                params['stepMax'],
                self.tr(
                    'Maximum distance between each WoT member and a newcomer'),
            ))
Ejemplo n.º 26
0
    def get_localized_data(self):
        localized_data = {}
        #  try to request money parameters
        try:
            params = self.blockchain_service.parameters()
        except NoPeerAvailable as e:
            logging.debug('community parameters error : ' + str(e))
            return None

        localized_data['currency'] = ROOT_SERVERS[
            self.connection.currency]["display"]
        localized_data['growth'] = params.c
        localized_data['days_per_dividend'] = QLocale().toString(
            params.dt / 86400, 'f', 2)

        last_ud, last_ud_base = self.blockchain_service.last_ud()
        members_count = self.blockchain_service.last_members_count()
        previous_ud, previous_ud_base = self.blockchain_service.previous_ud()
        previous_ud_time = self.blockchain_service.previous_ud_time()
        previous_monetary_mass = self.blockchain_service.previous_monetary_mass(
        )
        previous_members_count = self.blockchain_service.previous_members_count(
        )

        localized_data['units'] = self.app.current_ref.instance(
            0, self.connection.currency, self.app, None).units
        localized_data['diff_units'] = self.app.current_ref.instance(
            0, self.connection.currency, self.app, None).diff_units

        if last_ud:
            # display float values
            localized_data['ud'] = self.app.current_ref.instance(
                last_ud * math.pow(10, last_ud_base), self.connection.currency,
                self.app).diff_localized(False, True)

            localized_data[
                'members_count'] = self.blockchain_service.current_members_count(
                )

            computed_dividend = self.blockchain_service.computed_dividend()
            # display float values
            localized_data['ud_plus_1'] = self.app.current_ref.instance(
                computed_dividend, self.connection.currency,
                self.app).diff_localized(False, True)

            localized_data['mass'] = self.app.current_ref.instance(
                self.blockchain_service.current_mass(),
                self.connection.currency, self.app).localized(False, True)

            ud_median_time = self.blockchain_service.last_ud_time()
            ud_median_time = self.blockchain_processor.adjusted_ts(
                self.app.currency, ud_median_time)

            localized_data['ud_median_time'] = QLocale.toString(
                QLocale(), QDateTime.fromTime_t(ud_median_time),
                QLocale.dateTimeFormat(QLocale(), QLocale.ShortFormat))

            next_ud_median_time = self.blockchain_service.last_ud_time(
            ) + params.dt
            next_ud_median_time = self.blockchain_processor.adjusted_ts(
                self.app.currency, next_ud_median_time)

            localized_data['next_ud_median_time'] = QLocale.toString(
                QLocale(), QDateTime.fromTime_t(next_ud_median_time),
                QLocale.dateTimeFormat(QLocale(), QLocale.ShortFormat))

            next_ud_reeval = self.blockchain_service.next_ud_reeval()
            next_ud_reeval = self.blockchain_processor.adjusted_ts(
                self.app.currency, next_ud_reeval)
            localized_data['next_ud_reeval'] = QLocale.toString(
                QLocale(), QDateTime.fromTime_t(next_ud_reeval),
                QLocale.dateTimeFormat(QLocale(), QLocale.ShortFormat))

            if previous_ud:
                mass_minus_1_per_member = (float(0) if previous_ud == 0
                                           or previous_members_count == 0 else
                                           previous_monetary_mass /
                                           previous_members_count)
                localized_data['mass_minus_1_per_member'] = self.app.current_ref.instance(mass_minus_1_per_member,
                                                  self.connection.currency, self.app) \
                                                  .localized(False, True)
                localized_data['mass_minus_1'] = self.app.current_ref.instance(previous_monetary_mass,
                                                  self.connection.currency, self.app) \
                                                  .localized(False, True)
                # avoid divide by zero !
                if members_count == 0 or previous_members_count == 0:
                    localized_data['actual_growth'] = float(0)
                else:
                    localized_data['actual_growth'] = (last_ud * math.pow(
                        10, last_ud_base)) / (previous_monetary_mass /
                                              members_count)

                previous_ud_time = self.blockchain_processor.adjusted_ts(
                    self.app.currency, previous_ud_time)
                localized_data['ud_median_time_minus_1'] = QLocale.toString(
                    QLocale(), QDateTime.fromTime_t(previous_ud_time),
                    QLocale.dateTimeFormat(QLocale(), QLocale.ShortFormat))
        return localized_data
Ejemplo n.º 27
0
    def refresh_labels(self):
        self.busy.show()
        #  try to request money parameters
        try:
            params = yield from self.community.parameters()
        except NoPeerAvailable as e:
            logging.debug('community parameters error : ' + str(e))
            return False

        #  try to request money variables from last ud block
        try:
            block_ud = yield from self.community.get_ud_block()
        except NoPeerAvailable as e:
            logging.debug('community get_ud_block error : ' + str(e))
            return False
        try:
            block_ud_minus_1 = yield from self.community.get_ud_block(1)
        except NoPeerAvailable as e:
            logging.debug('community get_ud_block error : ' + str(e))
            return False

        if block_ud:
            # display float values
            localized_ud = yield from self.account.current_ref(block_ud['dividend'],
                                                               self.community,
                                                               self.app)\
                .diff_localized(True, self.app.preferences['international_system_of_units'])

            computed_dividend = yield from self.community.computed_dividend()
            # display float values
            localized_ud_plus_1 = yield from self.account.current_ref(computed_dividend,
                                                    self.community, self.app)\
                .diff_localized(True, self.app.preferences['international_system_of_units'])

            localized_mass = yield from self.account.current_ref(block_ud['monetaryMass'],
                                                    self.community, self.app)\
                .diff_localized(True, self.app.preferences['international_system_of_units'])
            if block_ud_minus_1:
                mass_minus_1 = (float(0) if block_ud['membersCount'] == 0 else
                        block_ud_minus_1['monetaryMass'] / block_ud['membersCount'])
                localized_mass_minus_1_per_member = yield from self.account.current_ref(mass_minus_1,
                                                                  self.community, self.app)\
                    .diff_localized(True, self.app.preferences['international_system_of_units'])
                localized_mass_minus_1 = yield from self.account.current_ref(block_ud_minus_1['monetaryMass'],
                                                                  self.community, self.app)\
                    .diff_localized(True, self.app.preferences['international_system_of_units'])

            else:
                localized_mass_minus_1_per_member = QLocale().toString(
                    float(0), 'f', self.app.preferences['digits_after_comma']
                )
                localized_mass_minus_1 = QLocale().toString(
                    float(0), 'f', self.app.preferences['digits_after_comma']
                )

            # set infos in label
            self.label_general.setText(
                self.tr("""
                <table cellpadding="5">
                <tr><td align="right"><b>{:}</b></div></td><td>{:} {:}</td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:} {:}</td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:} {:}</td></tr>
                <tr><td align="right"><b>{:2.2%} / {:} days</b></td><td>{:}</td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                </table>
                """).format(
                    localized_ud,
                    self.tr('Universal Dividend UD(t) in'),
                    self.account.current_ref.diff_units(self.community.currency),
                    localized_mass_minus_1,
                    self.tr('Monetary Mass M(t-1) in'),
                    self.account.current_ref.diff_units(self.community.currency),
                    block_ud['membersCount'],
                    self.tr('Members N(t)'),
                    localized_mass_minus_1_per_member,
                    self.tr('Monetary Mass per member M(t-1)/N(t) in'),
                    self.account.current_ref.diff_units(self.community.currency),
                    float(0) if block_ud['membersCount'] == 0 or block_ud_minus_1['monetaryMass'] == 0 else
                    block_ud['dividend'] / (block_ud_minus_1['monetaryMass'] / block_ud['membersCount']),

                    params['dt'] / 86400,
                    self.tr('Actual growth c = UD(t)/[M(t-1)/N(t)]'),
                    QLocale.toString(
                        QLocale(),
                        QDateTime.fromTime_t(block_ud_minus_1['medianTime']),
                        QLocale.dateTimeFormat(QLocale(), QLocale.ShortFormat)
                    ),
                    self.tr('Penultimate UD date and time (t-1)'),
                    QLocale.toString(
                        QLocale(),
                        QDateTime.fromTime_t(block_ud['medianTime']),
                        QLocale.dateTimeFormat(QLocale(), QLocale.ShortFormat)
                    ),
                    self.tr('Last UD date and time (t)'),
                    QLocale.toString(
                        QLocale(),
                        QDateTime.fromTime_t(block_ud['medianTime'] + params['dt']),
                        QLocale.dateTimeFormat(QLocale(), QLocale.ShortFormat)
                    ),
                    self.tr('Next UD date and time (t+1)')
                )
            )
        else:
            self.label_general.setText(self.tr('No Universal Dividend created yet.'))

        if block_ud:
            # set infos in label
            self.label_rules.setText(
                self.tr("""
                <table cellpadding="5">
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                </table>
                """).format(
                    self.tr('{:2.0%} / {:} days').format(params['c'], params['dt'] / 86400),
                    self.tr('Fundamental growth (c) / Delta time (dt)'),
                    self.tr('UD(t+1) = MAX { UD(t) ; c &#215; M(t) / N(t+1) }'),
                    self.tr('Universal Dividend (formula)'),
                    self.tr('{:} = MAX {{ {:} {:} ; {:2.0%} &#215; {:} {:} / {:} }}').format(
                        localized_ud_plus_1,
                        localized_ud,
                        self.account.current_ref.diff_units(self.community.currency),
                        params['c'],
                        localized_mass,
                        self.account.current_ref.diff_units(self.community.currency),
                        block_ud['membersCount']
                    ),
                    self.tr('Universal Dividend (computed)')
                )
            )
        else:
            self.label_rules.setText(self.tr('No Universal Dividend created yet.'))

        # set infos in label
        self.label_money.setText(
            self.tr("""
            <table cellpadding="5">
            <tr><td align="right"><b>{:2.0%} / {:} days</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:} {:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:2.0%}</b></td><td>{:}</td></tr>
            </table>
            """).format(
                params['c'],
                params['dt'] / 86400,
                self.tr('Fundamental growth (c)'),
                params['ud0'],
                self.tr('Initial Universal Dividend UD(0) in'),
                self.community.short_currency,
                params['dt'] / 86400,
                self.tr('Time period (dt) in days (86400 seconds) between two UD'),
                params['medianTimeBlocks'],
                self.tr('Number of blocks used for calculating median time'),
                params['avgGenTime'],
                self.tr('The average time in seconds for writing 1 block (wished time)'),
                params['dtDiffEval'],
                self.tr('The number of blocks required to evaluate again PoWMin value'),
                params['blocksRot'],
                self.tr('The number of previous blocks to check for personalized difficulty'),
                params['percentRot'],
                self.tr('The percent of previous issuers to reach for personalized difficulty')
            )
        )

        # set infos in label
        self.label_wot.setText(
            self.tr("""
            <table cellpadding="5">
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            </table>
            """).format(
                params['sigDelay'] / 86400,
                self.tr('Minimum delay between 2 identical certifications (in days)'),
                params['sigValidity'] / 86400,
                self.tr('Maximum age of a valid signature (in days)'),
                params['sigQty'],
                self.tr('Minimum quantity of signatures to be part of the WoT'),
                params['sigWoT'],
                self.tr('Minimum quantity of valid made certifications to be part of the WoT for distance rule'),
                params['msValidity'] / 86400,
                self.tr('Maximum age of a valid membership (in days)'),
                params['stepMax'],
                self.tr('Maximum distance between each WoT member and a newcomer'),
            )
        )
        self.busy.hide()