<commit_before>from __future__ import print_function

import os
import time
import tempfile
import threading
import numpy as np
import warnings
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

from .compat import Image, Server


HOST = os.environ.get('PYMOL_RPCHOST', 'localhost')
PORT = 9123


class MolViewer(object):
    def __init__(self, host=HOST, port=PORT):
        self.host = host
        self.port = int(port)
        self._thread = threading.Thread(
            target=os.system,
            args=(('pymol -RQ',)),
        )
        self._thread.daemon = True

        if hasattr(self, '_server'):
            self._add_methods()

    def _add_methods(self):
        for method in self._server.system.listMethods():
            if method[0].islower():
                setattr(self, method, getattr(self._server, method))

    def start(self):
        if self._thread.is_alive():
            print("A PyMOL RPC server is already running.")
            return
        self._thread.start()
        self._server = Server(
            uri="http://%s:%d/RPC2" % (self.host, self.port)
        )

    def display(self):
        """Display PyMol session using matplotlib

        Returns
        -------
        fig : matplotlib.pyplot.figure

        """
        fig = plt.figure(figsize=(20, 20))
        ax = fig.add_subplot(111)
        ax.axis('off')
        png_filename = 'tmp_png_file_for_ipymol' + '.png'
        self._server.do("cmd.png('%s')" % png_filename )
        ax.imshow(mpimg.imread(png_filename))
        os.remove(png_filename)
        return fig<commit_msg>_add_methods fails if the Server is not ready yet. Using a try-except in a while loop it's possible to wait until the server is online, then execute _add_methods.<commit_after>from __future__ import print_function

import os
import time
import tempfile
import threading
import numpy as np
import warnings
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

from .compat import Image, Server


HOST = os.environ.get('PYMOL_RPCHOST', 'localhost')
PORT = 9123


class MolViewer(object):
    def __init__(self, host=HOST, port=PORT):
        self.host = host
        self.port = int(port)
        self._thread = threading.Thread(
            target=os.system,
            args=(('pymol -RQ',)),
        )
        self._thread.daemon = True

    def _add_methods(self):
        for method in self._server.system.listMethods():
            if method[0].islower():
                setattr(self, method, getattr(self._server, method))

    def start(self):
        if self._thread.is_alive():
            print("A PyMOL RPC server is already running.")
            return
        self._thread.start()
        self._server = Server(
            uri="http://%s:%d/RPC2" % (self.host, self.port)
        )

        # check if the server is online yet, then add methods
        server_online = False
        while not server_online:
            try:
                if hasattr(self, '_server'):
                    self._add_methods()
                server_online = True
            except:
                pass

    def display(self):
        """Display PyMol session using matplotlib

        Returns
        -------
        fig : matplotlib.pyplot.figure

        """
        fig = plt.figure(figsize=(20, 20))
        ax = fig.add_subplot(111)
        ax.axis('off')
        png_filename = 'tmp_png_file_for_ipymol' + '.png'
        self._server.do("cmd.png('%s')" % png_filename )
        ax.imshow(mpimg.imread(png_filename))
        os.remove(png_filename)
        return fig
{'fraction_non_alphanumeric': 0.1087866108786611, 'fraction_numerical': 0.007252440725244073, 'mean_word_length': 2.1236933797909407, 'pattern_counts': {'":': 0, '<': 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': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2523588', 'n_tokens_mistral': 1095, 'n_tokens_neox': 1055, 'n_words': 270}