<commit_before># coding=utf-8
""" This module is still experimental!
"""
from .translators import translate_js, DEFAULT_HEADER
import sys
import time
import json
import six
import os
import hashlib

__all__  = ['EvalJs', 'translate_js', 'import_js', 'eval_js']
DEBUG = False


def import_js(path, lib_name, globals):
    """Imports from javascript source file.
      globals is your globals()"""
    with open(path, 'rb') as f:
        js = f.read()
    e = EvalJs()
    e.execute(js)
    var = e.context['var']
    globals[lib_name] = var.to_python()

def eval_js(js):
    """Just like javascript eval. Translates javascript to python,
       executes and returns python object.
       js is javascript source code

       EXAMPLE:
        >>> import js2py
        >>> add = js2py.eval_js('function add(a, b) {return a + b}')
        >>> add(1, 2) + 3
        6
        >>> add('1', 2, 3)
        u'12'
        >>> add.constructor
        function Function() { [python code] }

       NOTE: For Js Number, String, Boolean and other base types returns appropriate python BUILTIN type.
       For Js functions and objects, returns Python wrapper - basically behaves like normal python object.
       If you really want to convert object to python dict you can use to_dict method.
       """
    e = EvalJs()
    return e.eval(js)



class EvalJs(object):
    """This class supports continuous execution of javascript under same context.

        >>> js = EvalJs()
        >>> js.execute('var a = 10;function f(x) {return x*x};')
        >>> js.f(9)
        81
        >>> js.a
        10

        context is a python dict or object that contains python variables that should be available to JavaScript
        For example:
        >>> js = EvalJs({'a': 30})
        >>> js.execute('var x = a')
        >>> js.x
        30

       You can run interactive javascript console with console method!"""
    def __init__(self, context={}):
        self.__dict__['_context'] = {}
        exec(DEFAULT_HEADER, self._context)
        self.__dict__['_var'] = self._context['var'].to_python()
        if not isinstance(context, dict):
            try:
                context = context.__dict__
            except:
                raise TypeError('context has to be either a dict or have __dict__ attr')
        for k, v in six.iteritems(context):
            setattr(self._var, k, v)

    def execute(self, js=None, use_compile_plan=False):
        """executes javascript js in current context

        During initial execute() the converted js is cached for re-use. That means next time you
        run the same javascript snippet you save many instructions needed to parse and convert the
        js code to python code.

        This cache causes minor overhead (a cache dicts is updated) but the Js=>Py conversion process
        is typically expensive compared to actually running the generated python code.

        Note that the cache is just a dict, it has no expiration or cleanup so when running this
        in automated situations with vast amounts of snippets it might increase memory usage.
        """
        try:
            cache = self.__dict__['cache']
        except KeyError:
            cache = self.__dict__['cache'] = {}
        hashkey = hashlib.md5(js).digest()
        try:
            compiled = cache[hashkey]
        except KeyError:
            code = translate_js(js, '', use_compile_plan=use_compile_plan)
            compiled = cache[hashkey] = compile(code, '<EvalJS snippet>', 'exec')
        exec(compiled, self._context)

    def eval(self, expression, use_compile_plan=False):
        """evaluates expression in current context and returns its value"""
        code = 'PyJsEvalResult = eval(%s)'%json.dumps(expression)
        self.execute(code, use_compile_plan=use_compile_plan)
        return self['PyJsEvalResult']

    def execute_debug(self, js):
        """executes javascript js in current context
        as opposed to the (faster) self.execute method, you can use your regular debugger
        to set breakpoints and inspect the generated python code
        """
        code = translate_js(js, '')
        # make sure you have a temp folder:<commit_msg>Fixed typos after renaming a parameter<commit_after># coding=utf-8
""" This module is still experimental!
"""
from .translators import translate_js, DEFAULT_HEADER
import sys
import time
import json
import six
import os
import hashlib

__all__  = ['EvalJs', 'translate_js', 'import_js', 'eval_js']
DEBUG = False


def import_js(path, lib_name, globals):
    """Imports from javascript source file.
      globals is your globals()"""
    with open(path, 'rb') as f:
        js = f.read()
    e = EvalJs()
    e.execute(js)
    var = e.context['var']
    globals[lib_name] = var.to_python()

def eval_js(js):
    """Just like javascript eval. Translates javascript to python,
       executes and returns python object.
       js is javascript source code

       EXAMPLE:
        >>> import js2py
        >>> add = js2py.eval_js('function add(a, b) {return a + b}')
        >>> add(1, 2) + 3
        6
        >>> add('1', 2, 3)
        u'12'
        >>> add.constructor
        function Function() { [python code] }

       NOTE: For Js Number, String, Boolean and other base types returns appropriate python BUILTIN type.
       For Js functions and objects, returns Python wrapper - basically behaves like normal python object.
       If you really want to convert object to python dict you can use to_dict method.
       """
    e = EvalJs()
    return e.eval(js)



class EvalJs(object):
    """This class supports continuous execution of javascript under same context.

        >>> js = EvalJs()
        >>> js.execute('var a = 10;function f(x) {return x*x};')
        >>> js.f(9)
        81
        >>> js.a
        10

        context is a python dict or object that contains python variables that should be available to JavaScript
        For example:
        >>> js = EvalJs({'a': 30})
        >>> js.execute('var x = a')
        >>> js.x
        30

       You can run interactive javascript console with console method!"""
    def __init__(self, context={}):
        self.__dict__['_context'] = {}
        exec(DEFAULT_HEADER, self._context)
        self.__dict__['_var'] = self._context['var'].to_python()
        if not isinstance(context, dict):
            try:
                context = context.__dict__
            except:
                raise TypeError('context has to be either a dict or have __dict__ attr')
        for k, v in six.iteritems(context):
            setattr(self._var, k, v)

    def execute(self, js=None, use_compilation_plan=False):
        """executes javascript js in current context

        During initial execute() the converted js is cached for re-use. That means next time you
        run the same javascript snippet you save many instructions needed to parse and convert the
        js code to python code.

        This cache causes minor overhead (a cache dicts is updated) but the Js=>Py conversion process
        is typically expensive compared to actually running the generated python code.

        Note that the cache is just a dict, it has no expiration or cleanup so when running this
        in automated situations with vast amounts of snippets it might increase memory usage.
        """
        try:
            cache = self.__dict__['cache']
        except KeyError:
            cache = self.__dict__['cache'] = {}
        hashkey = hashlib.md5(js).digest()
        try:
            compiled = cache[hashkey]
        except KeyError:
            code = translate_js(js, '', use_compilation_plan=use_compilation_plan)
            compiled = cache[hashkey] = compile(code, '<EvalJS snippet>', 'exec')
        exec(compiled, self._context)

    def eval(self, expression, use_compilation_plan=False):
        """evaluates expression in current context and returns its value"""
        code = 'PyJsEvalResult = eval(%s)'%json.dumps(expression)
        self.execute(code, use_compilation_plan=use_compilation_plan)
        return self['PyJsEvalResult']

    def execute_debug(self, js):
        """executes javascript js in current context
        as opposed to the (faster) self.execute method, you can use your regular debugger
        to set breakpoints and inspect the generated python code
        """
        code = translate_js(js, '')
        # make sure you have a temp folder:
{'fraction_non_alphanumeric': 0.09533973674848809, 'fraction_numerical': 0.005691924581999288, 'mean_word_length': 2.5054031587697425, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 79, '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': '1251594', 'n_tokens_mistral': 2342, 'n_tokens_neox': 2231, 'n_words': 868}