Beispiel #1
0
def do_cgi():
    """
    This is called when the script is run as a cgi script.
    """
    # get the fields sent by the browser
    fs = cgi.FieldStorage()
    # start writing a response
    out = StringIO()
    # initialize the header dictionary
    header_dict = {}
    # get some environment variables from the cgi
    document_root = os.getenv('DOCUMENT_ROOT')
    script_filename = os.getenv('SCRIPT_FILENAME')
    # try to generate some useful data to send to the user
    try:
        if not list(fs):
            # if the page was called with no arguments then show a directory html page
            doc_directory = os.path.join(document_root, 'phydoc')
            header_dict['Content-Type'] = 'text/html'
            write_directory_html(script_directory, doc_directory, out)
        else:
            # the page was called with arguments so get a response from the module
            scriptid = fs.getfirst('myscript')
            if not scriptid:
                raise DispatchError('no script snippet was specified')
            if not re.match(r'^\d{8}[a-zA-Z]$', scriptid):
                raise DispatchError(
                    'the specified script name did not meet the format requirements'
                )
            try:
                module = __import__(
                    scriptid, globals(), locals(),
                    ['__doc__', 'handler', 'get_form', 'get_response'])
            except ImportError:
                raise DispatchError('the script could not be imported')
            # process the module differently depending on its type
            if hasattr(module, 'get_form') and hasattr(module, 'get_response'):
                # This is the more advanced dispatch method.
                # Determine whether we are asking for a form or for a response.
                if len(fs.keys()) == 1:
                    # send a form
                    form_html = module.get_form()
                    header_dict['Content-Type'] = 'text/html'
                    print >> out, '<html>'
                    title = SnippetUtil.docstring_to_title(module.__doc__)
                    if title:
                        print >> out, '<head>'
                        print >> out, '<title>'
                        print >> out, title
                        print >> out, '</title>'
                        print >> out, '</head>'
                    print >> out, '<body>'
                    print >> out, SnippetUtil.docstring_to_html(module.__doc__)
                    print >> out, '<br/><br/>'
                    print >> out, '<form method="post">'
                    print >> out, '<input type="hidden" name="myscript" value="%s"/>' % scriptid
                    print >> out, form_html
                    print >> out, '<br/><br/>'
                    print >> out, '<input type="submit" name="mysubmit" value="Submit"/><br/>'
                    print >> out, '</form>'
                    print >> out, '</body>'
                    print >> out, '</html>'
                else:
                    content_info, content_text = module.get_response(fs)
                    header_dict.update(content_info)
                    out.write(content_text)
            else:
                raise DispatchError(
                    'no web interface was found for this script')
    except (DirectoryError, DispatchError, HandlingError), e:
        header_dict['Content-Type'] = 'text/plain'
        print >> out, 'Error:', e
Beispiel #2
0
    print >> out, 'S:'
    print >> out, S
    print >> out
    print >> out, 'pseudoinverse of S:'
    print >> out, S_pinv
    print >> out
    return out.getvalue().strip()

def get_response_content(fs):
    return process(fs.ntaxa) + '\n'

def get_ordered_ids(tree):
    """
    Maybe I could use postorder here instead.
    @param tree: a tree
    @return: a list of ids beginning with the leaves
    """
    ordered_ids = []
    ordered_ids.extend(id(node) for node in tree.gen_tips())
    ordered_ids.extend(id(node) for node in tree.gen_internal_nodes())
    return ordered_ids

def main(args):
    print process(args.ntaxa)

if __name__ == '__main__': 
    parser = argparse.ArgumentParser(description=SnippetUtil.docstring_to_title(__doc__))
    parser.add_argument('--ntaxa', type=int, default=5, help='number of taxa in the tree') 
    args = parser.parse_args() 
    main(args) 
Beispiel #3
0
def handler(req):
    """
    If no arguments were provided then display the directory of scripts.
    Otherwise if a valid myscript identifier was provided then dispatch the request to the script.
    Otherwise show an error message.
    """
    try:
        field_storage = mod_python.util.FieldStorage(req)
        scriptid = field_storage.getfirst('myscript')
        if not req.args:
            # if the page was called with no arguments then show a directory html page
            try:
                script_directory = get_script_directory(req)
                doc_directory = os.path.join(get_doc_root(req), 'phydoc')
            except DirectoryError as e:
                req.content_type = "text/plain"
                print >> req, 'Error:', e
            else:
                req.content_type = "text/html"
                page_buffer = StringIO()
                write_directory_html(script_directory, doc_directory,
                                     page_buffer)
                req.write(page_buffer.getvalue())
        else:
            # the page was called with arguments so get a response from the module
            if not scriptid:
                raise DispatchError('no script snippet was specified')
            if not re.match(r'^\d{8}[a-zA-Z]$', scriptid):
                raise DispatchError(
                    'the specified script name did not meet the format requirements'
                )
            try:
                module = __import__(
                    scriptid, globals(), locals(),
                    ['__doc__', 'handler', 'get_form', 'get_response'])
            except ImportError:
                raise DispatchError('the script could not be imported')
            # process the module differently depending on its type
            if hasattr(module, 'get_form') and hasattr(module, 'get_response'):
                # This is the more advanced dispatch method.
                # Determine whether we are asking for a form or for a response.
                if len(field_storage.keys()) == 1:
                    # send a form
                    form_html = module.get_form()
                    req.content_type = "text/html"
                    print >> req, '<html>'
                    title = SnippetUtil.docstring_to_title(module.__doc__)
                    if title:
                        print >> req, '<head>'
                        print >> req, '<title>'
                        print >> req, title
                        print >> req, '</title>'
                        print >> req, '</head>'
                    print >> req, '<body>'
                    print >> req, SnippetUtil.docstring_to_html(module.__doc__)
                    print >> req, '<br/><br/>'
                    print >> req, '<form method="post">'
                    print >> req, '<input type="hidden" name="myscript" value="%s"/>' % scriptid
                    print >> req, form_html
                    print >> req, '<br/><br/>'
                    print >> req, '<input type="submit" name="mysubmit" value="Submit"/><br/>'
                    print >> req, '</form>'
                    print >> req, '</body>'
                    print >> req, '</html>'
                else:
                    content_info, content_text = module.get_response(
                        field_storage)
                    for key, value in content_info:
                        if key == 'Content-Type':
                            req.content_type = value
                        else:
                            req.headers_out[key] = value
                    req.write(content_text)
            else:
                raise DispatchError(
                    'no web interface was found for this script')
    except DispatchError as e:
        req.content_type = "text/plain"
        print >> req, 'Error:', e
    except HandlingError as e:
        req.content_type = "text/plain"
        print >> req, 'Error:', e
    # pretend everything is OK
    return mod_python.apache.OK
Beispiel #4
0
 def index(self):
     out = StringIO()
     self._init_form()
     form_html = Form.get_html_string(self.form_objects)
     print >> out, '<html>'
     print >> out, '<head>'
     title = SnippetUtil.docstring_to_title(self.module.__doc__)
     if title:
         print >> out, '<title>'
         print >> out, title
         print >> out, '</title>'
     print >> out, FormHeaderJs.get_header_script_text(
         self.form_objects, self.form_presets)
     print >> out, '</head>'
     print >> out, '<body>'
     lines = smallutil.get_stripped_lines(StringIO(self.module.__doc__))
     if lines:
         print >> out, lines[0]
     else:
         print >> out, gray_span('untitled')
     print >> out, '<br/>'
     print >> out, '<code>',
     if self.source_link:
         relative_link = '../' + self.source_link
         print >> out, '<a href="%s">source code</a>' % relative_link
     else:
         print >> out, gray_span('source code')
     print >> out, '</code>'
     print >> out, '<br/><br/>'
     print >> out
     if len(lines) > 1:
         print >> out, '<!-- long description -->'
         for line in lines[1:]:
             print >> out, line
         print >> out, '<br/><br/>'
     else:
         print >> out, '<!-- no long description available -->'
     print >> out
     print >> out, '<!-- main form -->'
     print >> out, '<div style="float: left;">'
     print >> out, '<form id="mainform" action="process" method="post">'
     if form_html:
         print >> out, form_html
         print >> out, '<br/><br/>'
     print >> out, '<input type="submit" name="submit" value="view"/>'
     print >> out, '<input type="submit" name="submit" value="download"/>'
     print >> out, '<br/>'
     print >> out, '</form>'
     print >> out, '</div>'
     print >> out
     if self.form_presets:
         print >> out, '<!-- preset configurations -->'
         print >> out, '<div style="float: left;">'
         print >> out, '<fieldset>'
         print >> out, '<legend>preset configurations</legend>'
         button_tags = []
         default_preset = Form.get_default_preset(self.form_objects)
         for i, preset in enumerate([default_preset] + self.form_presets):
             tag = get_preset_button_tag(i, preset.description)
             button_tags.append(tag)
         print >> out, '<br/>\n'.join(button_tags)
         print >> out, '</fieldset>'
         print >> out, '</div>'
         print >> out
     print >> out, '</body>'
     print >> out, '</html>'
     return out.getvalue().rstrip()
Beispiel #5
0
 def index(self):
     out = StringIO()
     self._init_form()
     form_html = Form.get_html_string(self.form_objects)
     print >> out, '<html>'
     print >> out, '<head>'
     title = SnippetUtil.docstring_to_title(self.module.__doc__)
     if title:
         print >> out, '<title>'
         print >> out, title
         print >> out, '</title>'
     print >> out, FormHeaderJs.get_header_script_text(
             self.form_objects,
             self.form_presets)
     print >> out, '</head>'
     print >> out, '<body>'
     lines = smallutil.get_stripped_lines(StringIO(self.module.__doc__))
     if lines:
         print >> out, lines[0]
     else:
         print >> out, gray_span('untitled')
     print >> out, '<br/>'
     print >> out, '<code>',
     if self.source_link:
         relative_link = '../' + self.source_link
         print >> out, '<a href="%s">source code</a>' % relative_link
     else:
         print >> out, gray_span('source code')
     print >> out, '</code>'
     print >> out, '<br/><br/>'
     print >> out
     if len(lines) > 1:
         print >> out, '<!-- long description -->'
         for line in lines[1:]:
             print >> out, line
         print >> out, '<br/><br/>'
     else:
         print >> out, '<!-- no long description available -->'
     print >> out
     print >> out, '<!-- main form -->'
     print >> out, '<div style="float: left;">'
     print >> out, '<form id="mainform" action="process" method="post">'
     if form_html:
         print >> out, form_html
         print >> out, '<br/><br/>'
     print >> out, '<input type="submit" name="submit" value="view"/>'
     print >> out, '<input type="submit" name="submit" value="download"/>'
     print >> out, '<br/>'
     print >> out, '</form>'
     print >> out, '</div>'
     print >> out
     if self.form_presets:
         print >> out, '<!-- preset configurations -->'
         print >> out, '<div style="float: left;">'
         print >> out, '<fieldset>'
         print >> out, '<legend>preset configurations</legend>'
         button_tags = []
         default_preset = Form.get_default_preset(self.form_objects)
         for i, preset in enumerate([default_preset] + self.form_presets):
             tag = get_preset_button_tag(i, preset.description)
             button_tags.append(tag)
         print >> out, '<br/>\n'.join(button_tags)
         print >> out, '</fieldset>'
         print >> out, '</div>'
         print >> out
     print >> out, '</body>'
     print >> out, '</html>'
     return out.getvalue().rstrip()
Beispiel #6
0
def handler(req):
    """
    If no arguments were provided then display the directory of scripts.
    Otherwise if a valid myscript identifier was provided then dispatch the request to the script.
    Otherwise show an error message.
    """
    import mod_python
    # redirect to the code page if no args were passed
    if not req.args:
        req.content_type = "text/html"
        print >> req, '<head>'
        print >> req, '<meta HTTP-EQUIV="REFRESH" content="0; url=/code">'
        print >> req, '</head>'
        print >> req, '<body></body>'
        return mod_python.apache.OK
    try:
        field_storage = mod_python.util.FieldStorage(req)
        scriptid = field_storage.getfirst('myscript')
        if not scriptid:
            raise DispatchError('no script snippet was specified')
        if not re.match(r'^\d{8}[a-zA-Z]$', scriptid):
            raise DispatchError(
                'the specified script name did not meet the format requirements'
            )
        try:
            module = __import__(
                scriptid, globals(), locals(),
                ['__doc__', 'handler', 'get_form', 'get_response'])
        except ImportError:
            raise DispatchError('the script could not be imported')
        # process the module differently depending on its type
        if hasattr(module, 'get_form') and hasattr(module, 'get_response'):
            # This is the more advanced dispatch method.
            # Get the form data.
            form_data = module.get_form()
            # Determine whether we are asking for a form or for a response.
            if len(field_storage.keys()) == 1:
                # the form from the module is either a string or a list of form objects
                if type(form_data) is str:
                    form_html = form_data
                else:
                    form_html = Form.get_html_string(form_data)
                req.content_type = str('text/html')
                print >> req, '<html>'
                title = SnippetUtil.docstring_to_title(module.__doc__)
                if title:
                    print >> req, '<head>'
                    print >> req, '<title>'
                    print >> req, title
                    print >> req, '</title>'
                    print >> req, '</head>'
                print >> req, '<body>'
                print >> req, SnippetUtil.docstring_to_html(module.__doc__)
                print >> req, '<br/><br/>'
                print >> req, '<form method="post">'
                print >> req, '<input type="hidden" name="myscript" value="%s"/>' % scriptid
                print >> req, form_html
                print >> req, '<br/><br/>'
                print >> req, '<input type="submit" name="mysubmit" value="Submit"/><br/>'
                print >> req, '</form>'
                print >> req, '</body>'
                print >> req, '</html>'
            else:
                # possibly parse the field storage data according to the form data
                if type(form_data) is not str:
                    for form_item in form_data:
                        form_item.process_fieldstorage(field_storage)
                # get the response
                content_info, content_text = module.get_response(field_storage)
                for key, value in content_info:
                    if key == 'Content-Type':
                        req.content_type = value
                    else:
                        req.headers_out[key] = value
                req.write(content_text)
        else:
            raise DispatchError('no web interface was found for this script')
    except ImportError as e:
        req.content_type = "text/plain"
        print >> req, 'Uncaught ImportError:', e
    except DispatchError as e:
        req.content_type = "text/plain"
        print >> req, 'Error:', e
    except HandlingError as e:
        req.content_type = "text/plain"
        print >> req, 'Error:', e
    except Form.FormError as e:
        req.content_type = "text/plain"
        print >> req, 'Form validation error:', e
    # pretend everything is OK
    return mod_python.apache.OK
Beispiel #7
0
def get_ordered_ids(tree):
    """
    Maybe I could use postorder here instead.
    @param tree: a tree
    @return: a list of ids beginning with the leaves
    """
    ordered_ids = []
    ordered_ids.extend(id(node) for node in tree.gen_tips())
    ordered_ids.extend(id(node) for node in tree.gen_internal_nodes())
    return ordered_ids


def main(args):
    print process(args.ntaxa, args.nseconds)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description=SnippetUtil.docstring_to_title(__doc__))
    parser.add_argument('--nseconds',
                        type=int,
                        default=0,
                        help='seconds to run or 0 to run until ctrl-c')
    parser.add_argument('--ntaxa',
                        type=int,
                        default=5,
                        help='number of taxa in each sampled tree topology')
    args = parser.parse_args()
    main(args)
Beispiel #8
0
def handler(req):
    """
    If no arguments were provided then display the directory of scripts.
    Otherwise if a valid myscript identifier was provided then dispatch the request to the script.
    Otherwise show an error message.
    """
    import mod_python
    # redirect to the code page if no args were passed
    if not req.args:
        req.content_type = "text/html"
        print >> req, '<head>'
        print >> req, '<meta HTTP-EQUIV="REFRESH" content="0; url=/code">'
        print >> req, '</head>'
        print >> req, '<body></body>'
        return mod_python.apache.OK
    try:
        field_storage = mod_python.util.FieldStorage(req)
        scriptid = field_storage.getfirst('myscript')
        if not scriptid:
            raise DispatchError('no script snippet was specified')
        if not re.match(r'^\d{8}[a-zA-Z]$', scriptid):
            raise DispatchError('the specified script name did not meet the format requirements')
        try:
            module = __import__(scriptid, globals(), locals(), ['__doc__', 'handler', 'get_form', 'get_response'])
        except ImportError:
            raise DispatchError('the script could not be imported')
        # process the module differently depending on its type
        if hasattr(module, 'get_form') and hasattr(module, 'get_response'):
            # This is the more advanced dispatch method.
            # Get the form data.
            form_data = module.get_form()
            # Determine whether we are asking for a form or for a response.
            if len(field_storage.keys()) == 1:
                # the form from the module is either a string or a list of form objects
                if type(form_data) is str:
                    form_html = form_data
                else:
                    form_html = Form.get_html_string(form_data)
                req.content_type = str('text/html')
                print >> req, '<html>'
                title = SnippetUtil.docstring_to_title(module.__doc__)
                if title:
                    print >> req, '<head>'
                    print >> req, '<title>'
                    print >> req, title
                    print >> req, '</title>'
                    print >> req, '</head>'
                print >> req, '<body>'
                print >> req, SnippetUtil.docstring_to_html(module.__doc__)
                print >> req, '<br/><br/>'
                print >> req, '<form method="post">'
                print >> req, '<input type="hidden" name="myscript" value="%s"/>' % scriptid
                print >> req, form_html
                print >> req, '<br/><br/>'
                print >> req, '<input type="submit" name="mysubmit" value="Submit"/><br/>'
                print >> req, '</form>'
                print >> req, '</body>'
                print >> req, '</html>'
            else:
                # possibly parse the field storage data according to the form data
                if type(form_data) is not str:
                    for form_item in form_data:
                        form_item.process_fieldstorage(field_storage)
                # get the response
                content_info, content_text = module.get_response(field_storage)
                for key, value in content_info:
                    if key == 'Content-Type':
                        req.content_type = value
                    else:
                        req.headers_out[key] = value
                req.write(content_text)
        else:
            raise DispatchError('no web interface was found for this script')
    except ImportError as e:
        req.content_type = "text/plain"
        print >> req, 'Uncaught ImportError:', e
    except DispatchError as e:
        req.content_type = "text/plain"
        print >> req, 'Error:', e
    except HandlingError as e:
        req.content_type = "text/plain"
        print >> req, 'Error:', e
    except Form.FormError as e:
        req.content_type = "text/plain"
        print >> req, 'Form validation error:', e
    # pretend everything is OK
    return mod_python.apache.OK
Beispiel #9
0
def do_cgi():
    """
    This is called when the script is run as a cgi script.
    """
    # get the fields sent by the browser
    fs = cgi.FieldStorage()
    # start writing a response
    out = StringIO()
    # initialize the header dictionary
    header_dict = {}
    # get some environment variables from the cgi
    document_root = os.getenv('DOCUMENT_ROOT')
    script_filename = os.getenv('SCRIPT_FILENAME')
    # try to generate some useful data to send to the user
    try:
        if not list(fs):
            # if the page was called with no arguments then show a directory html page
            doc_directory = os.path.join(document_root, 'phydoc')
            header_dict['Content-Type'] = 'text/html'
            write_directory_html(script_directory, doc_directory, out)
        else:
            # the page was called with arguments so get a response from the module
            scriptid = fs.getfirst('myscript')
            if not scriptid:
                raise DispatchError('no script snippet was specified')
            if not re.match(r'^\d{8}[a-zA-Z]$', scriptid):
                raise DispatchError('the specified script name did not meet the format requirements')
            try:
                module = __import__(scriptid, globals(), locals(), ['__doc__', 'handler', 'get_form', 'get_response'])
            except ImportError:
                raise DispatchError('the script could not be imported')
            # process the module differently depending on its type
            if hasattr(module, 'get_form') and hasattr(module, 'get_response'):
                # This is the more advanced dispatch method.
                # Determine whether we are asking for a form or for a response.
                if len(fs.keys()) == 1:
                    # send a form
                    form_html = module.get_form()
                    header_dict['Content-Type'] = 'text/html'
                    print >> out, '<html>'
                    title = SnippetUtil.docstring_to_title(module.__doc__)
                    if title:
                        print >> out, '<head>'
                        print >> out, '<title>'
                        print >> out, title
                        print >> out, '</title>'
                        print >> out, '</head>'
                    print >> out, '<body>'
                    print >> out, SnippetUtil.docstring_to_html(module.__doc__)
                    print >> out, '<br/><br/>'
                    print >> out, '<form method="post">'
                    print >> out, '<input type="hidden" name="myscript" value="%s"/>' % scriptid
                    print >> out, form_html
                    print >> out, '<br/><br/>'
                    print >> out, '<input type="submit" name="mysubmit" value="Submit"/><br/>'
                    print >> out, '</form>'
                    print >> out, '</body>'
                    print >> out, '</html>'
                else:
                    content_info, content_text = module.get_response(fs)
                    header_dict.update(content_info)
                    out.write(content_text)
            else:
                raise DispatchError('no web interface was found for this script')
    except (DirectoryError, DispatchError, HandlingError), e:
        header_dict['Content-Type'] = 'text/plain'
        print >> out, 'Error:', e
Beispiel #10
0
def handler(req):
    """
    If no arguments were provided then display the directory of scripts.
    Otherwise if a valid myscript identifier was provided then dispatch the request to the script.
    Otherwise show an error message.
    """
    try:
        field_storage = mod_python.util.FieldStorage(req)
        scriptid = field_storage.getfirst('myscript')
        if not req.args:
            # if the page was called with no arguments then show a directory html page
            try:
                script_directory = get_script_directory(req)
                doc_directory = os.path.join(get_doc_root(req), 'phydoc')
            except DirectoryError as e:
                req.content_type = "text/plain"
                print >> req, 'Error:', e
            else:
                req.content_type = "text/html"
                page_buffer = StringIO()
                write_directory_html(script_directory, doc_directory, page_buffer)
                req.write(page_buffer.getvalue())
        else:
            # the page was called with arguments so get a response from the module
            if not scriptid:
                raise DispatchError('no script snippet was specified')
            if not re.match(r'^\d{8}[a-zA-Z]$', scriptid):
                raise DispatchError('the specified script name did not meet the format requirements')
            try:
                module = __import__(scriptid, globals(), locals(), ['__doc__', 'handler', 'get_form', 'get_response'])
            except ImportError:
                raise DispatchError('the script could not be imported')
            # process the module differently depending on its type
            if hasattr(module, 'get_form') and hasattr(module, 'get_response'):
                # This is the more advanced dispatch method.
                # Determine whether we are asking for a form or for a response.
                if len(field_storage.keys()) == 1:
                    # send a form
                    form_html = module.get_form()
                    req.content_type = "text/html"
                    print >> req, '<html>'
                    title = SnippetUtil.docstring_to_title(module.__doc__)
                    if title:
                        print >> req, '<head>'
                        print >> req, '<title>'
                        print >> req, title
                        print >> req, '</title>'
                        print >> req, '</head>'
                    print >> req, '<body>'
                    print >> req, SnippetUtil.docstring_to_html(module.__doc__)
                    print >> req, '<br/><br/>'
                    print >> req, '<form method="post">'
                    print >> req, '<input type="hidden" name="myscript" value="%s"/>' % scriptid
                    print >> req, form_html
                    print >> req, '<br/><br/>'
                    print >> req, '<input type="submit" name="mysubmit" value="Submit"/><br/>'
                    print >> req, '</form>'
                    print >> req, '</body>'
                    print >> req, '</html>'
                else:
                    content_info, content_text = module.get_response(field_storage)
                    for key, value in content_info:
                        if key == 'Content-Type':
                            req.content_type = value
                        else:
                            req.headers_out[key] = value
                    req.write(content_text)
            else:
                raise DispatchError('no web interface was found for this script')
    except DispatchError as e:
        req.content_type = "text/plain"
        print >> req, 'Error:', e
    except HandlingError as e:
        req.content_type = "text/plain"
        print >> req, 'Error:', e
    # pretend everything is OK
    return mod_python.apache.OK