Ejemplo n.º 1
0
def query(request):
    input = request.POST.get('query', '')
    if settings.DEBUG and not input:
        input = request.GET.get('query', '')
        
    if settings.LOG_QUERIES:
        query_log = Query(query=input, error=True,
            browser=request.META.get('HTTP_USER_AGENT', ''),
            remote_user=request.META.get('REMOTE_USER', ''),
            remote_addr=request.META.get('REMOTE_ADDR', ''),
            remote_host=request.META.get('REMOTE_HOST', ''),
            meta=unicode(request.META),
            log='',
        )
        query_log.save()
    
    user_definitions = request.session.get('definitions')
    definitions.set_user_definitions(user_definitions)
    try:
        evaluation = Evaluation(input, definitions, timeout=settings.TIMEOUT, format='xml')
    except Exception, exc:
        if settings.DEBUG and settings.DISPLAY_EXCEPTIONS:
            evaluation = Evaluation()
            info = traceback.format_exception(*sys.exc_info())
            info = '\n'.join(info)
            msg = 'Exception raised: %s\n\n%s' % (exc, info)             
            evaluation.results = [Result([Message('System', 'exception', msg)], None, None)]
        else:
            raise
Ejemplo n.º 2
0
def query(request):
    from mathics.core.parser import MultiLineFeeder

    input = request.POST.get('query', '')
    if settings.DEBUG and not input:
        input = request.GET.get('query', '')

    if settings.LOG_QUERIES:
        query_log = Query(
            query=input,
            error=True,
            browser=request.META.get('HTTP_USER_AGENT', ''),
            remote_user=request.META.get('REMOTE_USER', ''),
            remote_addr=request.META.get('REMOTE_ADDR', ''),
            remote_host=request.META.get('REMOTE_HOST', ''),
            meta=six.text_type(request.META),
            log='',
        )
        query_log.save()

    user_definitions = request.session.get('definitions')
    definitions.set_user_definitions(user_definitions)
    evaluation = Evaluation(definitions, format='xml', output=WebOutput())
    feeder = MultiLineFeeder(input, '<notebook>')
    results = []
    try:
        while not feeder.empty():
            expr = evaluation.parse_feeder(feeder)
            if expr is None:
                results.append(Result(evaluation.out, None,
                                      None))  # syntax errors
                evaluation.out = []
                continue
            result = evaluation.evaluate(expr, timeout=settings.TIMEOUT)
            if result is not None:
                results.append(result)
    except Exception as exc:
        if settings.DEBUG and settings.DISPLAY_EXCEPTIONS:
            info = traceback.format_exception(*sys.exc_info())
            info = '\n'.join(info)
            msg = 'Exception raised: %s\n\n%s' % (exc, info)
            results.append(
                Result([Message('System', 'exception', msg)], None, None))
        else:
            raise
    result = {
        'results': [result.get_data() for result in results],
    }
    request.session['definitions'] = definitions.get_user_definitions()

    if settings.LOG_QUERIES:
        query_log.timeout = evaluation.timeout
        query_log.result = six.text_type(result)  # evaluation.results
        query_log.error = False
        query_log.save()

    return JsonResponse(result)
Ejemplo n.º 3
0
def create_output(tests, output_xml, output_tex):
    for format, output in [('xml', output_xml), ('tex', output_tex)]:
        definitions.reset_user_definitions()
        for test in tests.tests:
            key = test.key
            evaluation = Evaluation(definitions, format=format, catch_interrupt=False)
            results = evaluation.parse_evaluate(test.test)
            output[key] = {
                'query': test.test,
                'results': [r.get_data() for r in results],
            }
Ejemplo n.º 4
0
def test_case(test, tests, index=0, subindex=0, quiet=False, section=None):
    test, wanted_out, wanted = test.test, test.outs, test.result

    def fail(why):
        part, chapter, section = tests.part, tests.chapter, tests.section
        print("%sTest failed: %s in %s / %s\n%s\n%s\n" %
              (sep, section, part, chapter, test, why))
        return False

    if not quiet:
        if section:
            print("%s %s / %s %s" % (stars, tests.chapter, section, stars))
        print("%4d (%2d): TEST %s" % (index, subindex, test))

    feeder = SingleLineFeeder(test, "<test>")
    evaluation = Evaluation(definitions,
                            catch_interrupt=False,
                            output=TestOutput())
    try:
        query = evaluation.parse_feeder(feeder)
        if query is None:
            # parsed expression is None
            result = None
            out = evaluation.out
        else:
            result = evaluation.evaluate(query)
            out = result.out
            result = result.result
    except Exception as exc:
        fail("Exception %s" % exc)
        info = sys.exc_info()
        sys.excepthook(*info)
        return False

    if not compare(result, wanted):
        fail_msg = "Result: %s\nWanted: %s" % (result, wanted)
        if out:
            fail_msg += "\nAdditional output:\n"
            fail_msg += "\n".join(str(o) for o in out)
        return fail(fail_msg)
    output_ok = True
    if len(out) != len(wanted_out):
        output_ok = False
    else:
        for got, wanted in zip(out, wanted_out):
            if not got == wanted:
                output_ok = False
                break
    if not output_ok:
        return fail(
            "Output:\n%s\nWanted:\n%s" %
            ("\n".join(str(o)
                       for o in out), "\n".join(str(o) for o in wanted_out)))
    return True
Ejemplo n.º 5
0
def query(request):
    from mathics.core.parser import MultiLineFeeder

    input = request.POST.get('query', '')
    if settings.DEBUG and not input:
        input = request.GET.get('query', '')

    if settings.LOG_QUERIES:
        query_log = Query(query=input, error=True,
                          browser=request.META.get('HTTP_USER_AGENT', ''),
                          remote_user=request.META.get('REMOTE_USER', ''),
                          remote_addr=request.META.get('REMOTE_ADDR', ''),
                          remote_host=request.META.get('REMOTE_HOST', ''),
                          meta=six.text_type(request.META),
                          log='',
                          )
        query_log.save()

    user_definitions = request.session.get('definitions')
    definitions.set_user_definitions(user_definitions)
    evaluation = Evaluation(definitions, format='xml', output=WebOutput())
    feeder = MultiLineFeeder(input, '<notebook>')
    results = []
    try:
        while not feeder.empty():
            expr = evaluation.parse_feeder(feeder)
            if expr is None:
                results.append(Result(evaluation.out, None, None))  # syntax errors
                evaluation.out = []
                continue
            result = evaluation.evaluate(expr, timeout=settings.TIMEOUT)
            if result is not None:
                results.append(result)
    except Exception as exc:
        if settings.DEBUG and settings.DISPLAY_EXCEPTIONS:
            info = traceback.format_exception(*sys.exc_info())
            info = '\n'.join(info)
            msg = 'Exception raised: %s\n\n%s' % (exc, info)
            results.append(Result([Message('System', 'exception', msg)], None, None))
        else:
            raise
    result = {
        'results': [result.get_data() for result in results],
    }
    request.session['definitions'] = definitions.get_user_definitions()

    if settings.LOG_QUERIES:
        query_log.timeout = evaluation.timeout
        query_log.result = six.text_type(result)  # evaluation.results
        query_log.error = False
        query_log.save()

    return JsonResponse(result)
Ejemplo n.º 6
0
def create_output(tests, output_xml, output_tex):
    for format, output in [('xml', output_xml), ('tex', output_tex)]:
        definitions.reset_user_definitions()
        for test in tests.tests:
            key = test.key
            evaluation = Evaluation(definitions,
                                    format=format,
                                    catch_interrupt=False)
            results = evaluation.parse_evaluate(test.test)
            output[key] = {
                'query': test.test,
                'results': [r.get_data() for r in results],
            }
Ejemplo n.º 7
0
def test_case(test, tests, index=0, quiet=False):
    test, wanted_out, wanted = test.test, test.outs, test.result
    part, chapter, section = tests.part, tests.chapter, tests.section

    def fail(why):
        print("%sTest failed: %s in %s / %s\n%s\n%s\n" % (
            sep, section, part, chapter, test, why))
        return False

    if not quiet:
        print('%4d. TEST %s' % (index, test))

    feeder = SingleLineFeeder(test, '<test>')
    evaluation = Evaluation(definitions, catch_interrupt=False, output=TestOutput())
    try:
        query = evaluation.parse_feeder(feeder)
        if query is None:
            # parsed expression is None
            result = None
            out = evaluation.out
        else:
            result = evaluation.evaluate(query)
            out = result.out
            result = result.result
    except Exception as exc:
        fail("Exception %s" % exc)
        info = sys.exc_info()
        sys.excepthook(*info)
        return False

    if not compare(result, wanted):
        fail_msg = "Result: %s\nWanted: %s" % (result, wanted)
        if out:
            fail_msg += "\nAdditional output:\n"
            fail_msg += '\n'.join(six.text_type(o) for o in out)
        return fail(fail_msg)
    output_ok = True
    if len(out) != len(wanted_out):
        output_ok = False
    else:
        for got, wanted in zip(out, wanted_out):
            if not got == wanted:
                output_ok = False
                break
    if not output_ok:
        return fail("Output:\n%s\nWanted:\n%s" % (
            '\n'.join(six.text_type(o) for o in out),
            '\n'.join(six.text_type(o) for o in wanted_out)))
    return True
Ejemplo n.º 8
0
    def do_execute(self,
                   code,
                   silent,
                   store_history=True,
                   user_expressions=None,
                   allow_stdin=False):

        if not silent:
            from mathics.core.parser import MultiLineFeeder

            definitions = Definitions(add_builtin=True)
            evaluation = Evaluation(definitions, format='xml')

            feeder = MultiLineFeeder(code, '<notebook>')
            results = []
            try:
                while not feeder.empty():
                    expr = evaluation.parse_feeder(feeder)
                    if expr is None:
                        results.append(Result(evaluation.out, None, None))
                        evaluation.out = []
                        continue
                    result = evaluation.evaluate(expr, timeout=20)
                    if result is not None:
                        results.append(result)
            except Exception as exc:
                raise

            for result in results:
                result_data = result.get_data()

                result_html = self.preprocess_output(result_data['result'])

                display_data = {
                    'data': {
                        'text/html': result_html
                    },
                    'metadata': {},
                }

                self.send_response(self.iopub_socket, 'display_data',
                                   display_data)

        return {
            'status': 'ok',
            'execution_count': self.execution_count,
            'payload': [],
            'user_expressions': {},
        }
Ejemplo n.º 9
0
def create_output(tests, output_xml, output_tex):
    for format, output in [('xml', output_xml), ('tex', output_tex)]:
        definitions.reset_user_definitions()
        for test in tests.tests:
            key = test.key
            evaluation = Evaluation(definitions, format=format, catch_interrupt=False, output=TestOutput())
            result = evaluation.parse_evaluate(test.test)
            if result is None:
                result = []
            else:
                result = [result.get_data()]
            output[key] = {
                'query': test.test,
                'results': result,
            }
Ejemplo n.º 10
0
    def __init__(self, add_builtin=False, builtin_filename=None, extension_modules=[]) -> None:
        super(Definitions, self).__init__()
        self.builtin = {}
        self.user = {}
        self.pymathics = {}
        self.definitions_cache = {}
        self.lookup_cache = {}
        self.proxy = defaultdict(set)
        self.now = 0    # increments whenever something is updated

        if add_builtin:
            from mathics.builtin import modules, contribute
            from mathics.core.evaluation import Evaluation
            from mathics.settings import ROOT_DIR

            loaded = False
            if builtin_filename is not None:
                builtin_dates = [get_file_time(module.__file__)
                                 for module in modules]
                builtin_time = max(builtin_dates)
                if get_file_time(builtin_filename) > builtin_time:
                    builtin_file = open(builtin_filename, 'rb')
                    self.builtin = pickle.load(builtin_file)
                    loaded = True
            if not loaded:
                contribute(self)
                for module in extension_modules:
                    try:
                        loaded_module = self.load_pymathics_module(module, remove_on_quit=False)
                    except PyMathicsLoadException as e:
                        print(e.module + ' is not a valid pymathics module.')
                        continue
                    except ImportError as e:
                        print(e.__repr__())
                        continue
                    #print(module + loaded_module.pymathics_version_data['version'] + "  by " + loaded_module.pymathics_version_data['author'])

                if builtin_filename is not None:
                    builtin_file = open(builtin_filename, 'wb')
                    pickle.dump(self.builtin, builtin_file, -1)

            # Load symbols from the autoload folder
            for root, dirs, files in os.walk(os.path.join(ROOT_DIR, 'autoload')):
                for path in [os.path.join(root, f) for f in files if f.endswith('.m')]:
                    Expression('Get', String(path)).evaluate(Evaluation(self))

            # Move any user definitions created by autoloaded files to
            # builtins, and clear out the user definitions list. This
            # means that any autoloaded definitions become shared
            # between users and no longer disappear after a Quit[].
            #
            # Autoloads that accidentally define a name in Global`
            # could cause confusion, so check for this.
            #
            for name in self.user:
                if name.startswith('Global`'):
                    raise ValueError("autoload defined %s." % name)
            self.builtin.update(self.user)
            self.user = {}
            self.clear_cache()
Ejemplo n.º 11
0
def main():
    quit_command = (sys.platform == 'win32') and 'CTRL-BREAK' or 'CONTROL-C'
    
    print_version(is_server=False)
    print_license()
    print u"Quit by pressing %s" % quit_command
    
    print ''
    
    definitions = Definitions(add_builtin=True)
    
    try:
        while True:
            input = raw_input('>> ')
            
            def out_callback(out):
                print to_output(unicode(out))
                
            evaluation = Evaluation(input, definitions, timeout=30, out_callback=out_callback)
            
            for result in evaluation.results:
                if result.result is not None:
                    print ' = %s' % to_output(unicode(result.result))
    except (KeyboardInterrupt, SystemExit):
        print "\n\nGood bye!\n"
Ejemplo n.º 12
0
    def __init__(self, add_builtin=False, builtin_filename=None):
        super(Definitions, self).__init__()
        self.builtin = {}
        self.user = {}
        self.autoload_stage = False

        if add_builtin:
            from mathics.builtin import modules, contribute
            from mathics.core.evaluation import Evaluation
            from mathics.settings import ROOT_DIR

            loaded = False
            if builtin_filename is not None:
                builtin_dates = [
                    get_file_time(module.__file__) for module in modules
                ]
                builtin_time = max(builtin_dates)
                if get_file_time(builtin_filename) > builtin_time:
                    builtin_file = open(builtin_filename, 'r')
                    self.builtin = pickle.load(builtin_file)
                    loaded = True
            if not loaded:
                contribute(self)
                if builtin_filename is not None:
                    builtin_file = open(builtin_filename, 'w')
                    pickle.dump(self.builtin, builtin_file, -1)

            self.autoload_stage = True
            for root, dirs, files in os.walk(  # noqa
                    os.path.join(ROOT_DIR, 'autoload')):

                for f in filter(lambda x: x.endswith('.m'), files):
                    with open(os.path.join(root, f)) as stream:
                        Evaluation(stream.read(), self, timeout=30)
            self.autoload_stage = False
Ejemplo n.º 13
0
def get_session_evaluation(session):
    evaluation = _evaluations.get(session.session_key)
    if evaluation is None:
        definitions = Definitions(add_builtin=True)
        evaluation = Evaluation(definitions, format='xml', output=WebOutput())
        _evaluations[session.session_key] = evaluation
    return evaluation
Ejemplo n.º 14
0
def get_session_evaluation(session):
    evaluation = _evaluations.get(session.session_key)
    if evaluation is None:
        definitions = Definitions(add_builtin=True)
        # We set the formatter to "unformatted" so that we can use
        # our own custom formatter that understand better how to format
        # in the context of mathics-django.
        # Previously, one specific format, like "xml" had to fit all.
        evaluation = Evaluation(definitions,
                                format="unformatted",
                                output=WebOutput())
        _evaluations[session.session_key] = evaluation
        evaluation.format_output = lambda expr, format: format_output(
            evaluation, expr, format)
        autoload_files(definitions, ROOT_DIR, "autoload")
    return evaluation
Ejemplo n.º 15
0
def mathics_system_info(defs):
    def eval(name, needs_head=True):
        evaled = name().evaluate(evaluation)
        if needs_head:
            return evaled.head.to_python(string_quotes=False)
        else:
            return evaled.to_python(string_quotes=False)

    evaluation = Evaluation(defs, output=None)
    return {
        "$Machine": sys.platform,
        "$MachineName": platform.uname().node,
        "$ProcessID": os.getppid(),
        "$ProcessorType": platform.machine(),
        "$SystemID": sys.platform,
        "$UserName": eval(msystem.UserName),
        "$SystemMemory": eval(msystem.SystemMemory),
        "MemoryAvailable[]": eval(msystem.MemoryAvailable, needs_head=False),
        "$SystemTimeZone": eval(datentime.SystemTimeZone),
        "MachinePrecision": eval(numeric.MachinePrecision_),
        "$BaseDirectory": eval(filesystem.BaseDirectory),
        "$RootDirectory": eval(filesystem.RootDirectory),
        "$HomeDirectory": eval(filesystem.HomeDirectory),
        "$InstallationDirectory": eval(filesystem.InstallationDirectory),
        "$TemporaryDirectory": eval(filesystem.TemporaryDirectory),
    }
Ejemplo n.º 16
0
    def _eval(self, code):
        """
        Evaluates a command inside the Mathics interpreter and returns the output
        as a Mathics result.

        EXAMPLES::

            sage: mathics._eval('1+1').last_eval  # optional - mathics
            <Integer: 2>
        """
        self._lazy_init()
        S = self._session
        expr = S.evaluate(code)
        from mathics.core.evaluation import Evaluation
        ev = Evaluation(S.definitions)
        return ev.evaluate(expr)
Ejemplo n.º 17
0
def _test_group(k, *group):
    for i, a in enumerate(group):
        for j, b in enumerate(group):
            if i == j:
                continue
            evaluation = Evaluation(definitions, catch_interrupt=False)
            try:
                is_same_under_sameq = Expression('SameQ', a,
                                                 b).evaluate(evaluation)
            except Exception as exc:
                print("Exception %s" % exc)
                info = sys.exc_info()
                sys.excepthook(*info)
                return False

            is_same = a.same(b)
            if is_same != _symbol_truth_value(is_same_under_sameq):
                print(
                    "%sTest failed: %s and %s are inconsistent under same() and SameQ\n"
                    % (sep, repr(a), repr(b)))
                return False

            if is_same and hash(a) != hash(b):
                print(
                    "%sTest failed: hashes for %s and %s must be equal but are not\n"
                    % (sep, repr(a), repr(b)))
                return False
Ejemplo n.º 18
0
 def _pythonized_mathics_expr(*x):
     inner_evaluation = Evaluation(definitions=evaluation.definitions)
     vars = dict(list(zip(names, x[: len(names)])))
     pyexpr = expr.replace_vars(vars)
     pyexpr = Expression("N", pyexpr).evaluate(inner_evaluation)
     res = pyexpr.to_python(n_evaluation=inner_evaluation)
     return res
Ejemplo n.º 19
0
    def do_execute(self,
                   code,
                   silent,
                   store_history=True,
                   user_expressions=None,
                   allow_stdin=False):
        # TODO update user definitions

        response = {
            'payload': [],
            'user_expressions': {},
        }

        formats = {
            'text/plain': 'text',
            'text/html': 'xml',
            'text/latex': 'tex',
        }

        try:
            self.init_web_engine()

            evaluation = Evaluation(self.definitions,
                                    output=KernelOutput(self),
                                    format=formats)

            result = evaluation.parse_evaluate(code, timeout=settings.TIMEOUT)

            if result:
                self.result_callback(result)
        except Exception as exc:
            stack = traceback.format_exception(*sys.exc_info())

            self.out_callback(
                Print('An error occured: ' + str(exc) + '\n\n' +
                      '\n'.join(stack)))

            # internal error
            response['status'] = 'error'
            response['ename'] = 'System:exception'
            response['traceback'] = stack
        else:
            response['status'] = 'ok'

        response['execution_count'] = self.definitions.get_line_no()

        return response
Ejemplo n.º 20
0
def test_case(test, tests, index=0, quiet=False):
    test, wanted_out, wanted = test.test, test.outs, test.result
    part, chapter, section = tests.part, tests.chapter, tests.section

    def fail(why):
        print("%sTest failed: %s in %s / %s\n%s\n%s\n" %
              (sep, section, part, chapter, test, why))
        return False

    if not quiet:
        print('%4d. TEST %s' % (index, test))
    evaluation = Evaluation(definitions, catch_interrupt=False)
    try:
        results = evaluation.parse_evaluate(test)
    except Exception as exc:
        fail("Exception %s" % exc)
        info = sys.exc_info()
        sys.excepthook(*info)
        return False

    if results:
        if len(results) > 1:
            return fail("Too many results: %s" % results)
        result = results[0].result
        out = results[0].out
    else:
        result = None
        out = []
    if not compare(result, wanted):
        fail_msg = "Result: %s\nWanted: %s" % (result, wanted)
        if out:
            fail_msg += "\nAdditional output:\n"
            fail_msg += '\n'.join(six.text_type(o) for o in out)
        return fail(fail_msg)
    output_ok = True
    if len(out) != len(wanted_out):
        output_ok = False
    else:
        for got, wanted in zip(out, wanted_out):
            if not got == wanted:
                output_ok = False
                break
    if not output_ok:
        return fail("Output:\n%s\nWanted:\n%s" % ('\n'.join(
            six.text_type(o)
            for o in out), '\n'.join(six.text_type(o) for o in wanted_out)))
    return True
Ejemplo n.º 21
0
    def do_execute(self, code, silent, store_history=True, user_expressions=None,
                   allow_stdin=False):
        #Initialize mathjax... It should be a beter place to do it inside the imathics kernel
        if not self.mathjax_initialized:
            self.mathjax_initialized = True
            self.Display(Javascript(''' 
               MathJax.Hub.Config({jax: ["input/TeX","input/MathML","input/AsciiMath","output/HTML-CSS","output/NativeMML",
               "output/PreviewHTML"],extensions: ["tex2jax.js","mml2jax.js","asciimath2jax.js","MathMenu.js","MathZoom.js",
               "fast-preview.js", "AssistiveMML.js"],TeX: { extensions: ["AMSmath.js","AMSsymbols.js","noErrors.js",
               "noUndefined.js"]}});''',
                                    lib="https://cdn.mathjax.org/mathjax/latest/MathJax.js"))
        # TODO update user definitions

        response = {
            'payload': [],
            'user_expressions': {},
        }

        try:
            evaluation = Evaluation(code, self.definitions, out_callback=self.out_callback,
                                    timeout=settings.TIMEOUT,format="xml")
        except Exception as exc:
            response['status'] = 'error'
            response['ename'] = 'System:exception'
            response['traceback'] = traceback.format_exception(*sys.exc_info())
            evaluation = Evaluation()
            raise exc
        else:
            response['status'] = 'ok'

        if not silent:
            for result in evaluation.results:
                if result.result is not None:
                    xmlchain = result.result
                    xmlchain= MathicsKernel.svg_open_tag.sub("<mtable><mtr><mtd><annotation-xml encoding=\"text/html\" ><svg",xmlchain)
                    xmlchain= MathicsKernel.svg_close_tag.sub("</svg></annotation-xml></mtd></mtr></mtable>",xmlchain)
                    data = {
                        'text/html': xmlchain,
                        # TODO html / mathjax output
                    }
                    
                    content = {'execution_count': result.line_no, 'data': data, 'metadata': {}}
                    self.send_response(self.iopub_socket, 'execute_result', content)

        response['execution_count'] = self.definitions.get_line()

        return response
Ejemplo n.º 22
0
def test_case(test, tests, index=0, quiet=False):
    test, wanted_out, wanted = test.test, test.outs, test.result
    part, chapter, section = tests.part, tests.chapter, tests.section

    def fail(why):
        print("%sTest failed: %s in %s / %s\n%s\n%s\n" % (
            sep, section, part, chapter, test, why))
        return False

    if not quiet:
        print('%4d. TEST %s' % (index, test))
    evaluation = Evaluation(definitions, catch_interrupt=False)
    try:
        results = evaluation.parse_evaluate(test)
    except Exception as exc:
        fail("Exception %s" % exc)
        info = sys.exc_info()
        sys.excepthook(*info)
        return False

    if results:
        if len(results) > 1:
            return fail("Too many results: %s" % results)
        result = results[0].result
        out = results[0].out
    else:
        result = None
        out = []
    if not compare(result, wanted):
        fail_msg = "Result: %s\nWanted: %s" % (result, wanted)
        if out:
            fail_msg += "\nAdditional output:\n"
            fail_msg += '\n'.join(six.text_type(o) for o in out)
        return fail(fail_msg)
    output_ok = True
    if len(out) != len(wanted_out):
        output_ok = False
    else:
        for got, wanted in zip(out, wanted_out):
            if not got == wanted:
                output_ok = False
                break
    if not output_ok:
        return fail("Output:\n%s\nWanted:\n%s" % (
            '\n'.join(six.text_type(o) for o in out),
            '\n'.join(six.text_type(o) for o in wanted_out)))
    return True
Ejemplo n.º 23
0
def create_output(tests, output_xml, output_tex):
    for format, output in [('xml', output_xml), ('tex', output_tex)]:
        reset_user_definitions()
        for test in tests.tests:
            key = test.key
            evaluation = Evaluation(definitions,
                                    format=format,
                                    catch_interrupt=False)
            result = evaluation.parse_evaluate(test.test)
            if result is None:
                result = []
            else:
                result = [result.get_data()]
            output[key] = {
                'query': test.test,
                'results': result,
            }
Ejemplo n.º 24
0
def mathics_shell(shell):
    while True:
        try:
            evaluation = Evaluation(shell.definitions,
                                    output=TerminalOutput(shell))
            query = evaluation.parse_feeder(shell)
            if query is None:
                continue
            result = evaluation.evaluate(query, timeout=settings.TIMEOUT)
            if result is not None:
                shell.print_result(result)
        except (KeyboardInterrupt):
            print('\nKeyboardInterrupt')
        except (SystemExit, EOFError):
            break
        finally:
            shell.reset_lineno()
Ejemplo n.º 25
0
def onload(definitions):
#    from mathics.builtin import box_constructs
#    box_constructs["System`GraphicsBox"] = AsyGraphicsBox(expression=False)
#    box_constructs["System`Graphics3DBox"] = AsyGraphics3DBox(expression=False)
    MathicsExport._extdict["pdf"] = "PDF"
    definitions.set_ownvalue("Settings`UseAsyForGraphics2D", SymbolTrue)
    for root, dirs, files in os.walk(os.path.join(ROOT_DIR, "autoload")):
        for path in [os.path.join(root, f) for f in files if f.endswith(".m")]:
            Expression("Get", String(path)).evaluate(Evaluation(definitions))
Ejemplo n.º 26
0
 def evaluate(self, text):
     evaluation = Evaluation(text,
                             self.definitions,
                             timeout=30,
                             out_callback=out_callback)
     for result in evaluation.results:
         if result.result is not None:
             print self.get_out_prompt() + to_output(unicode(
                 result.result)) + '\n'
Ejemplo n.º 27
0
 def __init__(self,
              add_builtin=True,
              catch_interrupt=False,
              form="InputForm"):
     self.definitions = Definitions(add_builtin)
     self.evaluation = Evaluation(definitions=self.definitions,
                                  catch_interrupt=catch_interrupt)
     self.form = form
     self.last_result = None
Ejemplo n.º 28
0
def run():
    global result
    # prompt = '(1+a)(1+b)(1+c)(1+d)(1+e)//Expand'
    # prompt = 'f/@Range[20000];'
    # prompt = 'Plus @@ Range[50000]'
    # prompt = 'Range[100000];'
    try:
        # prompt = 'SetAttributes[v, Flat]; v[x_]:={x}; v[a,b]'
        # prompt = """(Plus@@Symbol/@CharacterRange["a","z"])^2//Expand;"""
        # prompt = (
        #     'Plus@@f/@Symbol/@StringJoin/@Tuples[CharacterRange["a","z"],2]')
        # prompt = 'FullForm[Nest[1+Sqrt[1+#]&, x, 20]]'
        # prompt = '1+2'
        prompt = 'DensityPlot[x*y,{x,-1,1},{y,-1,1}]'
        evaluation = Evaluation(definitions, format='xml')
        result = evaluation.parse_evaluate(prompt)
    except KeyboardInterrupt:
        result = 'INTERRUPTED'
Ejemplo n.º 29
0
def run():
    global result
    # prompt = '(1+a)(1+b)(1+c)(1+d)(1+e)//Expand'
    # prompt = 'f/@Range[20000];'
    # prompt = 'Plus @@ Range[50000]'
    # prompt = 'Range[100000];'
    try:
        # prompt = 'SetAttributes[v, Flat]; v[x_]:={x}; v[a,b]'
        # prompt = """(Plus@@Symbol/@CharacterRange["a","z"])^2//Expand;"""
        # prompt = (
        #     'Plus@@f/@Symbol/@StringJoin/@Tuples[CharacterRange["a","z"],2]')
        # prompt = 'FullForm[Nest[1+Sqrt[1+#]&, x, 20]]'
        # prompt = '1+2'
        prompt = 'DensityPlot[x*y,{x,-1,1},{y,-1,1}]'
        evaluation = Evaluation(definitions, format='xml')
        result = evaluation.parse_evaluate(prompt)
    except KeyboardInterrupt:
        result = 'INTERRUPTED'
Ejemplo n.º 30
0
def create_output(tests, output, format="tex"):
    definitions.reset_user_definitions()
    for test in tests.tests:
        if test.private:
            continue
        key = test.key
        evaluation = Evaluation(definitions,
                                format=format,
                                catch_interrupt=False,
                                output=TestOutput())
        result = evaluation.parse_evaluate(test.test)
        if result is None:
            result = []
        else:
            result = [result.get_data()]
        output[key] = {
            "query": test.test,
            "results": result,
        }
Ejemplo n.º 31
0
def query(request):
    input = request.POST.get('query', '')
    if settings.DEBUG and not input:
        input = request.GET.get('query', '')

    if settings.LOG_QUERIES:
        query_log = Query(query=input, error=True,
                          browser=request.META.get('HTTP_USER_AGENT', ''),
                          remote_user=request.META.get('REMOTE_USER', ''),
                          remote_addr=request.META.get('REMOTE_ADDR', ''),
                          remote_host=request.META.get('REMOTE_HOST', ''),
                          meta=six.text_type(request.META),
                          log='',
                          )
        query_log.save()

    user_definitions = request.session.get('definitions')
    definitions.set_user_definitions(user_definitions)
    evaluation = Evaluation(definitions, format='xml')
    try:
        results = evaluation.parse_evaluate(input, timeout=settings.TIMEOUT)
    except Exception as exc:
        if settings.DEBUG and settings.DISPLAY_EXCEPTIONS:
            info = traceback.format_exception(*sys.exc_info())
            info = '\n'.join(info)
            msg = 'Exception raised: %s\n\n%s' % (exc, info)
            results = [Result([Message('System', 'exception', msg)], None, None)]
        else:
            raise
    result = {
        'results': [result.get_data() for result in results],
    }
    request.session['definitions'] = definitions.get_user_definitions()

    if settings.LOG_QUERIES:
        query_log.timeout = evaluation.timeout
        query_log.result = six.text_type(result)  # evaluation.results
        query_log.error = False
        query_log.save()

    return JsonResponse(result)
Ejemplo n.º 32
0
    def __init__(self, add_builtin=False, builtin_filename=None):
        super(Definitions, self).__init__()
        self.builtin = {}
        self.user = {}

        self.definitions_cache = {}
        self.lookup_cache = {}
        self.proxy = defaultdict(set)
        self.now = 0  # increments whenever something is updated

        if add_builtin:
            from mathics.builtin import modules, contribute
            from mathics.core.evaluation import Evaluation
            from mathics.settings import ROOT_DIR

            loaded = False
            if builtin_filename is not None:
                builtin_dates = [
                    get_file_time(module.__file__) for module in modules
                ]
                builtin_time = max(builtin_dates)
                if get_file_time(builtin_filename) > builtin_time:
                    builtin_file = open(builtin_filename, 'rb')
                    self.builtin = pickle.load(builtin_file)
                    loaded = True
            if not loaded:
                contribute(self)
                if builtin_filename is not None:
                    builtin_file = open(builtin_filename, 'wb')
                    pickle.dump(self.builtin, builtin_file, -1)

            for root, dirs, files in os.walk(os.path.join(
                    ROOT_DIR, 'autoload')):
                for path in [
                        os.path.join(root, f) for f in files
                        if f.endswith('.m')
                ]:
                    Expression('Get', String(path)).evaluate(Evaluation(self))

            # Move any user definitions created by autoloaded files to
            # builtins, and clear out the user definitions list. This
            # means that any autoloaded definitions become shared
            # between users and no longer disappear after a Quit[].
            #
            # Autoloads that accidentally define a name in Global`
            # could cause confusion, so check for this.
            #
            for name in self.user:
                if name.startswith('Global`'):
                    raise ValueError("autoload defined %s." % name)
            self.builtin.update(self.user)
            self.user = {}
            self.clear_cache()
Ejemplo n.º 33
0
def load_settings(shell):
    autoload_files(shell.definitions, get_srcdir(), "autoload")
    settings_file = ensure_settings()
    if settings_file == "":
        return
    with open(settings_file, "r") as src:
        feeder = MathicsFileLineFeeder(src)
        try:
            while not feeder.empty():
                evaluation = Evaluation(
                    shell.definitions,
                    output=TerminalOutput(shell),
                    catch_interrupt=False,
                    format="text",
                )
                query = evaluation.parse_feeder(feeder)
                if query is None:
                    continue
                evaluation.evaluate(query)
        except (KeyboardInterrupt):
            print("\nKeyboardInterrupt")
    return True
Ejemplo n.º 34
0
def create_output(tests, doc_data, format="xml"):
    definitions.reset_user_definitions()
    for test in tests.tests:
        if test.private:
            continue
        key = test.key
        evaluation = Evaluation(definitions,
                                format=format,
                                catch_interrupt=True,
                                output=TestOutput())
        try:
            result = evaluation.parse_evaluate(test.test)
        except:
            result = None
        if result is None:
            result = []
        else:
            result = [result.get_data()]
        doc_data[key] = {
            "query": test.test,
            "results": result,
        }
Ejemplo n.º 35
0
    def do_execute(self, code, silent, store_history=True, user_expressions=None,
                   allow_stdin=False):
        # TODO update user definitions

        response = {
            'payload': [],
            'user_expressions': {},
        }

        formats = {
            'text/plain': 'text',
            'text/html': 'xml',
            'text/latex': 'tex',
        }

        try:
            self.init_web_engine()

            evaluation = Evaluation(self.definitions, output=KernelOutput(self), format=formats)

            result = evaluation.parse_evaluate(code, timeout=settings.TIMEOUT)

            if result:
                self.result_callback(result)
        except Exception as exc:
            stack = traceback.format_exception(*sys.exc_info())

            self.out_callback(Print('An error occured: ' + str(exc) + '\n\n' + '\n'.join(stack)))

            # internal error
            response['status'] = 'error'
            response['ename'] = 'System:exception'
            response['traceback'] = stack
        else:
            response['status'] = 'ok'

        response['execution_count'] = self.definitions.get_line_no()

        return response
Ejemplo n.º 36
0
    def do_execute(self, code, silent, store_history=True, user_expressions=None,
                   allow_stdin=False):
        # TODO update user definitions

        response = {
            'payload': [],
            'user_expressions': {},
        }

        evaluation = Evaluation(self.definitions, result_callback=self.result_callback,
                                out_callback=self.out_callback, clear_output_callback=self.clear_output_callback,
                                display_data_callback=self.display_data_callback)
        try:
            results = evaluation.parse_evaluate(code, timeout=settings.TIMEOUT)
        except Exception as exc:
            # internal error
            response['status'] = 'error'
            response['ename'] = 'System:exception'
            response['traceback'] = traceback.format_exception(*sys.exc_info())
            results = []
        else:
            response['status'] = 'ok'
        response['execution_count'] = self.definitions.get_line_no()
        return response
Ejemplo n.º 37
0
def query(request):
    input = request.POST.get('query', '')
    if settings.DEBUG and not input:
        input = request.GET.get('query', '')

    if settings.LOG_QUERIES:
        query_log = Query(
            query=input,
            error=True,
            browser=request.META.get('HTTP_USER_AGENT', ''),
            remote_user=request.META.get('REMOTE_USER', ''),
            remote_addr=request.META.get('REMOTE_ADDR', ''),
            remote_host=request.META.get('REMOTE_HOST', ''),
            meta=unicode(request.META),
            log='',
        )
        query_log.save()

    user_definitions = request.session.get('definitions')
    definitions.set_user_definitions(user_definitions)
    try:
        evaluation = Evaluation(input,
                                definitions,
                                timeout=settings.TIMEOUT,
                                format='xml')
    except Exception, exc:
        if settings.DEBUG and settings.DISPLAY_EXCEPTIONS:
            evaluation = Evaluation()
            info = traceback.format_exception(*sys.exc_info())
            info = '\n'.join(info)
            msg = 'Exception raised: %s\n\n%s' % (exc, info)
            evaluation.results = [
                Result([Message('System', 'exception', msg)], None, None)
            ]
        else:
            raise
Ejemplo n.º 38
0
    def evaluate(self, text):
        def to_output(text):
            line_number = self.get_last_line_number()
            newline = '\n' + ' ' * len('Out[{0}]= '.format(line_number))
            return newline.join(text.splitlines())

        def out_callback(out):
            print to_output(unicode(out))

        evaluation = Evaluation(text,
                                self.definitions,
                                timeout=settings.TIMEOUT,
                                out_callback=out_callback)
        for result in evaluation.results:
            if result.result is not None:
                print(self.get_out_prompt() +
                      to_output(unicode(result.result)) + '\n')
Ejemplo n.º 39
0
def test_case(test, tests, index=0, quiet=False):
    test, wanted_out, wanted = test.test, test.outs, test.result
    part, chapter, section = tests.part, tests.chapter, tests.section

    def fail(why):
        print u"%sTest failed: %s in %s / %s\n%s\n%s\n" % (sep, section, part,
                                                           chapter, test, why)
        return False

    if not quiet:
        print '%4d. TEST %s' % (index, test)
    try:
        evaluation = Evaluation(test, definitions, catch_interrupt=False)
    except Exception, exc:
        fail(u"Exception %s" % exc)
        info = sys.exc_info()
        sys.excepthook(*info)
        return False
Ejemplo n.º 40
0
def main():
    argparser = argparse.ArgumentParser(
        prog='mathics',
        usage='%(prog)s [options] [FILE]',
        add_help=False,
        description="Mathics is a general-purpose computer algebra system.",
        epilog="""Please feel encouraged to contribute to Mathics! Create
            your own fork, make the desired changes, commit, and make a pull
            request.""")

    argparser.add_argument(
        'FILE', nargs='?', type=argparse.FileType('r'),
        help='execute commands from FILE')

    argparser.add_argument(
        '--help', '-h', help='show this help message and exit', action='help')

    argparser.add_argument(
        '--persist', help='go to interactive shell after evaluating FILE or -e',
        action='store_true')

    argparser.add_argument(
        '--quiet', '-q', help='don\'t print message at startup',
        action='store_true')

    argparser.add_argument(
        '-script', help='run a mathics file in script mode',
        action='store_true')

    argparser.add_argument(
        '--execute', '-e', action='append', metavar='EXPR',
        help='evaluate EXPR before processing any input files (may be given '
        'multiple times)')

    argparser.add_argument(
        '--colors', nargs='?', help='interactive shell colors')

    argparser.add_argument(
        '--no-completion', help="disable tab completion", action='store_true')

    argparser.add_argument(
        '--no-readline', help="disable line editing (implies --no-completion)",
        action='store_true')

    argparser.add_argument(
        '--version', '-v', action='version',
        version='%(prog)s ' + __version__)

    args = argparser.parse_args()

    quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-D'

    definitions = Definitions(add_builtin=True)
    definitions.set_line_no(0)

    shell = TerminalShell(
        definitions, args.colors, want_readline=not(args.no_readline),
        want_completion=not(args.no_completion))

    if args.execute:
        for expr in args.execute:
            print(shell.get_in_prompt() + expr)
            evaluation = Evaluation(shell.definitions, out_callback=shell.out_callback)
            result = evaluation.parse_evaluate(expr, timeout=settings.TIMEOUT)
            shell.print_result(result)

        if not args.persist:
            return

    if args.FILE is not None:
        feeder = FileLineFeeder(args.FILE)
        try:
            while not feeder.empty():
                evaluation = Evaluation(shell.definitions, out_callback=shell.out_callback, catch_interrupt=False)
                query = evaluation.parse_feeder(feeder)
                if query is None:
                    continue
                evaluation.evaluate(query, timeout=settings.TIMEOUT)
        except (KeyboardInterrupt):
            print('\nKeyboardInterrupt')

        if args.persist:
            definitions.set_line_no(0)
        else:
            return

    if not args.quiet:
        print()
        print(version_string + '\n')
        print(license_string + '\n')
        print("Quit by pressing {0}\n".format(quit_command))

    while True:
        try:
            evaluation = Evaluation(shell.definitions, out_callback=shell.out_callback)
            query = evaluation.parse_feeder(shell)
            if query is None:
                continue
            result = evaluation.evaluate(query, timeout=settings.TIMEOUT)
            if result is not None:
                shell.print_result(result)
        except (KeyboardInterrupt):
            print('\nKeyboardInterrupt')
        except (SystemExit, EOFError):
            print("\n\nGood bye!\n")
            break
        finally:
            shell.reset_lineno()
Ejemplo n.º 41
0
def main():
    argparser = argparse.ArgumentParser(
        prog='mathics',
        usage='%(prog)s [options] [FILE]',
        add_help=False,
        description="Mathics is a general-purpose computer algebra system.",
        epilog="""Please feel encouraged to contribute to Mathics! Create
            your own fork, make the desired changes, commit, and make a pull
            request.""")

    argparser.add_argument(
        'FILE', nargs='?', type=argparse.FileType('r'),
        help='execute commands from FILE')

    argparser.add_argument(
        '--help', '-h', help='show this help message and exit', action='help')

    argparser.add_argument(
        '--persist', help='go to interactive shell after evaluating FILE or -e',
        action='store_true')

    argparser.add_argument(
        '--quiet', '-q', help='don\'t print message at startup',
        action='store_true')

    argparser.add_argument(
        '-script', help='run a mathics file in script mode',
        action='store_true')

    argparser.add_argument(
        '--execute', '-e', action='append', metavar='EXPR',
        help='evaluate EXPR before processing any input files (may be given '
        'multiple times)')

    argparser.add_argument(
        '--colors', nargs='?', help='interactive shell colors')

    argparser.add_argument(
        '--no-completion', help="disable tab completion", action='store_true')

    argparser.add_argument(
        '--no-readline', help="disable line editing (implies --no-completion)",
        action='store_true')

    argparser.add_argument(
        '--version', '-v', action='version',
        version='%(prog)s ' + __version__)

    args = argparser.parse_args()

    quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-D'

    definitions = Definitions(add_builtin=True)
    definitions.set_ownvalue('$Line', Integer(0))  # Reset the line number

    shell = TerminalShell(
        definitions, args.colors, want_readline=not(args.no_readline),
        want_completion=not(args.no_completion))

    if not (args.quiet or args.script):
        print()
        print(version_string + '\n')
        print(license_string + '\n')
        print("Quit by pressing {0}\n".format(quit_command))

    if args.execute:
        for expr in args.execute:
            print(shell.get_in_prompt() + expr)
            evaluation = Evaluation(shell.definitions, out_callback=shell.out_callback)
            exprs = evaluation.parse(expr)
            results = evaluation.evaluate(exprs, timeout=settings.TIMEOUT)
            shell.print_results(results)

        if not args.persist:
            return

    if args.FILE is not None:
        lines = args.FILE.readlines()
        if args.script and lines[0].startswith('#!'):
            lines[0] = ''

        results = []
        query_gen = parse_lines(lines, shell.definitions)
        evaluation = Evaluation(shell.definitions, out_callback=shell.out_callback)
        try:
            for query in query_gen:
                results.extend(evaluation.evaluate([query], timeout=settings.TIMEOUT))
        except TranslateError as exc:
            evaluation.recursion_depth = 0
            evaluation.stopped = False
            evaluation.message('Syntax', exc.msg, *exc.args)
        except (KeyboardInterrupt):
            print('\nKeyboardInterrupt')
        except (SystemExit, EOFError):
            print("\n\nGood bye!\n")

        if not args.persist:
            return

    total_input = ""
    while True:
        try:
            evaluation = Evaluation(shell.definitions, out_callback=shell.out_callback)
            line = shell.read_line(shell.get_in_prompt(continued=total_input != ''))
            total_input += line
            try:
                query = parse(total_input, shell.definitions)
            except TranslateError as exc:
                if line == '' or not isinstance(exc, IncompleteSyntaxError):
                    evaluation.message('Syntax', exc.msg, *exc.args)
                    total_input = ""
                continue
            total_input = ""
            if query is None:
                continue
            results = evaluation.evaluate([query], timeout=settings.TIMEOUT)
            shell.print_results(results)
        except (KeyboardInterrupt):
            print('\nKeyboardInterrupt')
        except (SystemExit, EOFError):
            print("\n\nGood bye!\n")
            break