<commit_before>"""
This module manages all market related activities
"""
import ast
from base64 import b64decode, b64encode
import gnupg
import hashlib
import json
import logging
from PIL import Image, ImageOps
import random
from StringIO import StringIO
import traceback
import re
from tornado import ioloop

from node import constants
from node.data_uri import DataURI
from node.orders import Orders
from node.protocol import proto_page, query_page
import bitcoin
import time


class Market(object):
    """This class manages the active market for the application"""

    def __init__(self, transport, db_connection):
        """Class constructor defines the basic attributes and callbacks

        Attributes:
          transport (CryptoTransportLayer): Transport layer
              for messaging between nodes.
          dht (DHT): For storage across the network (distributed hash table).
          market_id (int): Indicates which local market we're working with.
          peers: Active peers/nodes on the P2P network
          db_connection: Database ORM handler
          orders: Orders for goods from database
          pages:
          mypage:
          signature: Digitial signature
          nickname: Short name of the node - a synonym for GUID
          log: Log handler
          settings: Local settings
          gpg: Public PGP key class
        """

        # Current
        self.transport = transport
        self.dht = transport.dht
        self.market_id = transport.market_id
        self.peers = self.dht.get_active_peers()
        self.db_connection = db_connection

        self.pages = {}
        self.mypage = None
        self.signature = None
        self.nickname = ""
        self.log = logging.getLogger(
            "[%s] %s" % (self.market_id, self.__class__.__name__))
        self.settings = self.transport.settings

        self.gpg = gnupg.GPG()

        self.all_messages = (
            'query_myorders',
            'peer',
            'query_page',
            'query_listing',
            'query_listings',
            'inbox_message'
        )

        # Register callbacks for incoming events
        self.transport.add_callbacks([
            (
                msg,
                {
                    'cb': getattr(self, 'on_%s' % msg),
                    'validator_cb': getattr(self, 'validate_on_%s' % msg)
                }
            )
            for msg in self.all_messages
        ])

        self.nickname = self.settings.get('nickname', '')

        # Recurring republish for DHT
        self.start_listing_republisher()

        self.orders = Orders(transport, self.market_id, db_connection, self.gpg)

    def start_listing_republisher(self):
        # Periodically refresh buckets
        loop = ioloop.IOLoop.instance()
        refresh_cb = ioloop.PeriodicCallback(self.dht._refresh_node,
                                             constants.REFRESH_TIMEOUT,
                                             io_loop=loop)
        refresh_cb.start()

    def disable_welcome_screen(self):
        """This just flags the welcome screen to not show on startup"""
        self.db_connection.update_entries(
            "settings",
            {"welcome": "disable"},
            {'market_id': self.transport.market_id}
        )

    def private_key(self):
        """Returns private key for local node"""
        return self.settings['secret']

    def on_listing_results(self, results):
        """Add incoming information to log"""
        self.log.debug("Listings %s", results)

    @staticmethod
    def process_contract_image(image):
        """Get image from web client for use on server side"""
        uri = DataURI(image)
        image_data = uri.data
        # mime_type = uri.mimetype
        charset = uri.charset

        image = Image.open(StringIO(image_data))
        cropped_image = ImageOps.fit(image, (200, 200), centering=(0.5, 0.5))
        data = StringIO()
        cropped_image.save(data, format='PNG', quality=75, optimize=True)
        new_uri = DataURI.make(
            'image/png',
            charset=charset,
            base64=True,
            data=data.getvalue())
        data.close()

        return new_uri
<commit_msg>Fix notary welcome screen bug<commit_after>"""
This module manages all market related activities
"""
import ast
from base64 import b64decode, b64encode
import gnupg
import hashlib
import json
import logging
from PIL import Image, ImageOps
import random
from StringIO import StringIO
import traceback
import re
from tornado import ioloop

from node import constants
from node.data_uri import DataURI
from node.orders import Orders
from node.protocol import proto_page, query_page
import bitcoin
import time


class Market(object):
    """This class manages the active market for the application"""

    def __init__(self, transport, db_connection):
        """Class constructor defines the basic attributes and callbacks

        Attributes:
          transport (CryptoTransportLayer): Transport layer
              for messaging between nodes.
          dht (DHT): For storage across the network (distributed hash table).
          market_id (int): Indicates which local market we're working with.
          peers: Active peers/nodes on the P2P network
          db_connection: Database ORM handler
          orders: Orders for goods from database
          pages:
          mypage:
          signature: Digitial signature
          nickname: Short name of the node - a synonym for GUID
          log: Log handler
          settings: Local settings
          gpg: Public PGP key class
        """

        # Current
        self.transport = transport
        self.dht = transport.dht
        self.market_id = transport.market_id
        self.peers = self.dht.get_active_peers()
        self.db_connection = db_connection

        self.pages = {}
        self.mypage = None
        self.signature = None
        self.nickname = ""
        self.log = logging.getLogger(
            "[%s] %s" % (self.market_id, self.__class__.__name__))
        self.settings = self.transport.settings

        self.gpg = gnupg.GPG()

        self.all_messages = (
            'query_myorders',
            'peer',
            'query_page',
            'query_listing',
            'query_listings',
            'inbox_message'
        )

        # Register callbacks for incoming events
        self.transport.add_callbacks([
            (
                msg,
                {
                    'cb': getattr(self, 'on_%s' % msg),
                    'validator_cb': getattr(self, 'validate_on_%s' % msg)
                }
            )
            for msg in self.all_messages
        ])

        self.nickname = self.settings.get('nickname', '')

        # Recurring republish for DHT
        self.start_listing_republisher()

        self.orders = Orders(transport, self.market_id, db_connection, self.gpg)

    def start_listing_republisher(self):
        # Periodically refresh buckets
        loop = ioloop.IOLoop.instance()
        refresh_cb = ioloop.PeriodicCallback(self.dht._refresh_node,
                                             constants.REFRESH_TIMEOUT,
                                             io_loop=loop)
        refresh_cb.start()

    def disable_welcome_screen(self):
        """This just flags the welcome screen to not show on startup"""
        self.db_connection.update_entries(
            "settings",
            {"welcome": "disable"},
            {'market_id': self.transport.market_id}
        )
        self.settings['welcome'] = 'disable'

    def private_key(self):
        """Returns private key for local node"""
        return self.settings['secret']

    def on_listing_results(self, results):
        """Add incoming information to log"""
        self.log.debug("Listings %s", results)

    @staticmethod
    def process_contract_image(image):
        """Get image from web client for use on server side"""
        uri = DataURI(image)
        image_data = uri.data
        # mime_type = uri.mimetype
        charset = uri.charset

        image = Image.open(StringIO(image_data))
        cropped_image = ImageOps.fit(image, (200, 200), centering=(0.5, 0.5))
        data = StringIO()
        cropped_image.save(data, format='PNG', quality=75, optimize=True)
        new_uri = DataURI.make(
            'image/png',
            charset=charset,
            base64=True,
            data=data.getvalue())
        data.close()

        return new_uri

{'fraction_non_alphanumeric': 0.08493118456652159, 'fraction_numerical': 0.004940595224091284, 'mean_word_length': 2.0288564303526897, 'pattern_counts': {'":': 2, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2918184', 'n_tokens_mistral': 2339, 'n_tokens_neox': 2228, 'n_words': 642}