Example #1
0
    def _compileWrapper(self, pattern, flags = 0):
        """ This function wraps the creation of the the
        regular expresion so that we can catch the
        Syntax Error exception and turn it into a
        Python Exception
        """
        jsFlags = self._convertFlags(flags)

        rObj = None
        errObj = None
        # The Exceptions need to be converted to python exceptions
        # in order to propagate appropriately
        __pragma__('js', '{}',
                   '''
                   try {
                     rObj = new RegExp(pattern, jsFlags)
                   } catch( err ) {
                     errObj = err
                   }
                   ''')

        if ( errObj is not None ):
            raise error(errObj.message, errObj, pattern, flags)

        return(jsFlags, rObj)
Example #2
0
def run (autoTester):
	m0 = Matrix (3, 3, [
		[1, 2, 3],
		[4, 5, 6],
		[7, 8, 10]
	])
	
	m1 = Matrix (3, 3, [
		[10, 20, 30],
		[40, 50, 60],
		[70, 80, 90]
	])
	
	x = 3
	y = x * 4 * x
	fast = 2 * 3
	
	__pragma__ ('opov')
	
	slow = 2 + 3
	m2 = m0 * m1  + m1 * (m0 + m1)
	m3 = 2 * (2 * m0 * 3 * m1 + m2 * 4) * 2
	
	__pragma__ ('noopov')
	
	fast2 = 16 * y + 1
	
	autoTester.check (m0._, m1._)
	autoTester.check (x, y)
	autoTester.check (m2._)
	autoTester.check (m3._)
	autoTester.check (fast, slow, fast2)
Example #3
0
def run (autoTester):
    x = 567
    y = -3
    z = 5 * x + 2 * y
    autoTester.check (x, y, z)

    __pragma__ ('opov')
    
    a = 234 + 3j
    b = 4 - 5j
    c = complex (-6, 7)
    autoTester.check (a, b, c)
    
    t = 6 * x - 3 * y + 7   # Just to check, faster with 'noopov'
    autoTester.check (t)
    
    d = 2 * a
    e = x * b
    f = z + d + e
    g = a / b
    h = a - b
    i = x - c
    j = a - x
    k = b + y
    
    autoTester.check (d, e, f, round (g.real, 2), round (g.imag, 2), h, i, j, k)
    
    __pragma__ ('noopov')
    
Example #4
0
		def repeat (bareFunc):
			__pragma__ ('kwargs')
			def innerFunc (*args, **kwargs):
				autoTester.check ('BEGIN repeatN ({})'.format (n))
				for i in range (n):
					bareFunc (*args, **kwargs)
				autoTester.check ('END repeatN ({})'.format (n))
			__pragma__ ('nokwargs')
			return innerFunc
Example #5
0
	def repeat3 (bareFunc):
		__pragma__ ('kwargs')
		def innerFunc (*args, **kwargs):
			autoTester.check ('BEGIN repeat3')
			for i in range (3):
				bareFunc (*args, **kwargs)
			autoTester.check ('END repeat3')
		__pragma__ ('nokwargs')
		return innerFunc
Example #6
0
    def emit(self, record):
        """
        Emit a record.
        Send the record to the Web server as a percent-encoded dictionary
        """
        if ( type(record) is str ):
            msg = record
        else:
            msg = self.format(record)

        try:
            url = self.url
            data = None
            if self.method == "GET":
                if (url.find('?') >= 0):
                    sep = '&'
                else:
                    sep = '?'
                url = url + "{}msg={}".format(sep, msg)
                url = self.urlencode(url)
            else: # "POST"
                data = "msg={}".format(msg)
                data = self.urlencode(data)

            def ajaxCallback():
                # @note - we should probably do something
                #   like keep track of error messages and
                #   provide a counter of failed pushes ?
                return(0)


            conn = None
            errObj = None
            __pragma__('js', '{}',
                       '''
                       try {
                         conn = new(XMLHttpRequest || ActiveXObject)('MSXML2.XMLHTTP.3.0');
                       } catch( err ) {
                         errObj = err
                       }
                       ''')

            if ( errObj is not None ):
                raise Exception( "Failed Create AJAX Request", errObj )

            if ( conn is None ):
                raise Exception("Invalid Ajax Object")

            conn.open(self.method, url, 1);
            for key,val in self.headers:
                conn.setRequestHeader( key, val )

            conn.onreadystatechange = ajaxCallback
            conn.send(data)

        except Exception:
            self.handleError(record)
Example #7
0
def run (autoTester):
	a = b = c = d = e = f = g = h = i = j = k = l = Test (autoTester)

	__pragma__ ('opov')
			
	a [1:2:3, 4:5:6] = b [7:8:9]
	c [1:2:3] = d [4:5:6, 7:8:9]
	e [1, 1:2:3, 3] = f [4, 4:5:6, 6]
	g [1, 2, 3] = h [1, 2, 3]
	i [1] = j [1]
	k [1:2:3] = l [1:2:3]
Example #8
0
 def __new__ (meta, name, bases, attribs):
     __pragma__ ('jsiter')       # Translate for ... in directly to JavaScript for ... in ... and translate {} to bare {} rather than to dict {}
                                 # Using bare {} as attribs parameter to __new__ avoids dict attributes masking regular attributes
                                 # For more flexibility use __pragma__ ('js', '{}', '''...''')
     upperAttribs = {}
     
     for attribKey in attribs:   # Translates to 'for (var attribKey in attribs)' by virtue of __pragma__ ('jsiter'), to iterate over the attributes of a bare JavaScript {}
         upperAttribs [attribKey if  attribKey.startswith ('__') else attribKey.upper ()] = attribs [attribKey]
         
     __pragma__ ('nojsiter')
         
     return type.__new__ (meta, name, bases, upperAttribs)
Example #9
0
def run (autoTester):
    m0 = Matrix (3, 3, [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 10]
    ])
    
    m1 = Matrix (3, 3, [
        [10, 20, 30],
        [40, 50, 60],
        [70, 80, 90]
    ])
    
    x = 3
    y = x * 4 * x
    fast = 2 * 3
    
    __pragma__ ('opov')
    
    m1 [1][2] = m0 [1][2]
    slow = 2 + 3
    m2 = m0 * m1  + m1 * (m0 + m1)
    m3 = 2 * (2 * m0 * 3 * m1 + m2 * 4) * 2
    autoTester.check (m0 [1][1], m0 [1][2], m1 [1][1], m1 [1][2])
    
    __pragma__ ('noopov')
    
    fast2 = 16 * y + 1
    
    autoTester.check (m0, m1)
    autoTester.check (x, y)
    autoTester.check (m2)
    autoTester.check (m3)
    autoTester.check (fast, slow, fast2)
    
    x = 'marker'
    
    __pragma__ ('opov')
    autoTester.check (f (3, 4, 30, 40, m = 300, n = 400, p = 3000, q = 4000))
    autoTester.check (g (3, 4, 30, 40, m = 300, n = 400, p = 3000, q = 4000))
    
    autoTester.check (set ((1, 2, 3)) == set ((3, 2, 1)))
    autoTester.check (set ((1, 2, 3)) != set ((3, 2, 1)))
    autoTester.check (set ((1, 3)) == set ((3, 2, 1)))
    autoTester.check (set ((1, 3)) != set ((3, 2, 1)))
    autoTester.check (set ((1, 2)) < set ((3, 2, 1)))
    autoTester.check (set ((1, 2, 3)) <= set ((3, 2, 1)))
    autoTester.check (set ((1, 2, 3)) > set ((2, 1)))
    autoTester.check (set ((1, 2, 3)) >= set ((3, 2, 1)))
    
    autoTester.check ((1, 2, 3) == (1, 2, 3))
    autoTester.check ([1, 2, 3] == [1, 2, 3])
    autoTester.check ((1, 2, 3) != (1, 2, 3))
    autoTester.check ([1, 2, 3] != [1, 2, 3])
    autoTester.check ((2, 1, 3) == (1, 2, 3))
    autoTester.check ([2, 1, 3] == [1, 2, 3])
    autoTester.check ((2, 1, 3) != (1, 2, 3))
    autoTester.check ([2, 1, 3] != [1, 2, 3])
    __pragma__ ('noopov')
Example #10
0
def resetLogging():
    """ Reset the handlers and loggers so that we
    can rerun the tests starting from a blank slate.
    """
    __pragma__("skip")
    logging._handlerList = []

    import weakref
    logging._handlers = weakref.WeakValueDictionary()

    logging.root = logging.RootLogger(logging.WARNING)
    logging.Logger.root = logging.root
    logging.Logger.manager = logging.Manager(logging.root)
    logging.root.manager = logging.Logger.manager
    __pragma__("noskip")

    if __envir__.executor_name == __envir__.transpiler_name:
        logging._resetLogging()
Example #11
0
def run (autoTester):
	a = num.array ([
		[0, -2, -1], 
		[2, 1, 3], 
		[1, 1, 2]
	])
	
	autoTester.check ('Matrix a', a.astype ('int32') .tolist (), '<br>')
	
	ai = linalg.inv (a)
	
	autoTester.check ('Matrix ai', ai.astype ('int32') .tolist (), '<br>')
	
	__pragma__ ('opov')
	id = a @ ai
	__pragma__ ('noopov')
	
	autoTester.check ('a @ ai', id.astype ('int32') .tolist (), '<br>')
Example #12
0
def checkFindIter(test, flags = 0):
    """ Test the finditer method
    """
    __pragma__ ('ifdef', '__esv5__')
    if ( '__esv5__' in __symbols__ ):
        test.check("Skip finditer tests in esv5")
        return
    __pragma__('else')
    p = "\\[([\\d]+)\\]"
    r = re.compile(p, flags)
    test.check( r.groups )

    iret = r.finditer(testStr2)
    for m in iret:
        test.check(m.pos)
        test.check(m.endpos)
        test.check(m.string)
        test.check(m.lastindex)
        test.check(m.groups())
        test.check(m.group(0))
        test.check(m.group(1))
        test.check(test.expectException( lambda: m.group(2) ))
        test.check(test.expectException( lambda: m.group(2342)))
        test.check(test.expectException( lambda: m.group("asdf")))
        test.check(m.start(0))
        test.check(m.start(1))
        test.check(test.expectException( lambda: m.start("asdf")))
        test.check(m.end(0))
        test.check(m.end(1))
        test.check(test.expectException( lambda: m.end("asdf")))
    __pragma__('endif')
Example #13
0
    def reflect(self, handler, namespace):

        if not self.original:
            logger.critical("ClassFactory cannnot find Javascript object - has it been loaded?")

        __pragma__('jsiter')

        for eachobj in self.original:
            if self.predicate(eachobj):
                api_obj = self.original[eachobj]
                if not api_obj.hasOwnProperty('prototype'):
                    self.namespace[eachobj] = api_obj
                    continue
                new_name, result = handler(eachobj, api_obj)
                if result is None:
                    self.namespace[new_name] = api_obj
                else:
                    self.namespace[new_name] = result
                    api_obj.prototype.__class__ = result
                    window.Object.setPrototypeOf(result, api_obj)

        __pragma__('nojsiter')
Example #14
0
def checkRegexProperties(test, flags = 0):
    """ This test checks that the appropriate properties
    exist on the Regex object and that these properties
    are read-only.
    """
    r = re.compile(",", flags)
    if ( r is not None ):
        test.check( r.groups )
        test.check( r.pattern )
        test.check( r.flags )
        d = r.groupindex
        __pragma__('skip')
        d = convertMappingDict(d)
        __pragma__('noskip')
        test.check( d )
        # Check Read-only props on regex object
        def assignPattern():
            r.pattern = "asdfasdf"
        test.check(
            test.expectException(assignPattern)
        )
        def assignFlags():
            r.flags = "wer"
        test.check(
            test.expectException(assignFlags)
        )
        def assignGroups():
            r.groups = 1
        test.check(
            test.expectException(assignGroups)
        )
        def assignGroupIndex():
            r.groupindex = 34
        test.check(
            test.expectException(assignGroupIndex)
        )
    else:
        test.checkPad("NULL", 8)
Example #15
0
def escape(string):
    """ Escape a passed string so that we can send it to the
    regular expressions engine.
    """
    ret = None
    def replfunc(m):
        if ( m[0] == "\\" ):
            return("\\\\\\\\")
        else:
            return("\\\\" + m[0])

    # @note - I had an issue getting replfunc to be called in
    #        javascript correctly when I didn't use this pragma
    #        not sure if I was just doing it wrong or what
    __pragma__(
        'js', '{}',
        '''
        var r = /[^A-Za-z\d]/g;
        ret = string.replace(r, replfunc);
        ''')
    if ( ret is not None ):
        return(ret)
    else:
        raise Exception("Failed to escape the passed string")
Example #16
0
 def finditer(self, string, pos, endpos = None):
     """ Like findall but returns an iterator instead of
     a list.
     @see the python docs
     """
     # @note - Transcrypt compiled with `-e 5` does not have
     #    iterator support at this point. Only `-e 6` has
     #    iterator support.
     __pragma__ ('ifdef', '__esv5__')
     raise NotImplementedError("No Iterator Support in es5")
     __pragma__('else')
     mlist = self._findAllMatches(string, pos, endpos)
     ret = map(lambda m: Match(m, string, 0, len(string), self, self._groupindex), mlist)
     return( iter(ret) )
     __pragma__('endif')
Example #17
0
from org.transcrypt.stubs.browser import __pragma__

__pragma__ ('tconv')

def run (autoTester):
    autoTester.check (len ({1:2}))

    autoTester.check ('Select nonemtpy container, if any<br>')

    autoTester.check ((0) or (1, 2, 3))
    autoTester.check (() or (1, 2, 3))
    autoTester.check (() or ())
    
    autoTester.check ((-1) or (0) or (1, 2, 3))
    autoTester.check (() or (0) or (1, 2, 3))
    autoTester.check (() or () or (1, 2, 3))
    autoTester.check (() or () or ())
    
    autoTester.check ([0] or [1, 2, 3])
    autoTester.check ([] or [1, 2, 3])
    autoTester.check ([] or [])
    
    autoTester.check ([-1] or [0] or [1, 2, 3])
    autoTester.check ([] or [0] or [1, 2, 3])
    autoTester.check ([] or [] or [1, 2, 3])
    autoTester.check ([] or [] or [])
    
    autoTester.check ({0} or {1, 2, 3, 4})
    autoTester.check (set () or {1, 2, 3, 4})
    autoTester.check (set () or set ())
    
Example #18
0
# First run a test from the command prompt, generating an HTML file.
# The output of the test is stored in a DIV.
# Also the script is automatically included in the HTML file.
# Loading the HTML file will run the script.
# This will compare the output of the script running in the browswer to the output in the DIV.
# If those two match, the test reports OK, else it reports failure.

from org.transcrypt.stubs.browser import *
from org.transcrypt.stubs.browser import __main__, __envir__, __pragma__

# Don't import __envir__ from __base__ since it will overwrite __buildin__.__envir__ in the browser
# Import from stubs will be skipped in the browser
# ... The ice is a bit thin here

__pragma__("nokwargs")

import itertools

okColor = "green"
errorColor = "red"
highlightColor = "yellow"
testletNameColor = "blue"


class AutoTester:
    def __init__(self):
        self.referenceBuffer = []
        self.testBuffer = []
        self.messageDivId = "message"
        self.referenceDivId = "python"
        self.testDivId = "transcrypt"
Example #19
0
def run (autoTester):
	def repeat3 (bareFunc):
		__pragma__ ('kwargs')
		def innerFunc (*args, **kwargs):
			autoTester.check ('BEGIN repeat3')
			for i in range (3):
				bareFunc (*args, **kwargs)
			autoTester.check ('END repeat3')
		__pragma__ ('nokwargs')
		return innerFunc
		
	def repeatN (n):
		def repeat (bareFunc):
			__pragma__ ('kwargs')
			def innerFunc (*args, **kwargs):
				autoTester.check ('BEGIN repeatN ({})'.format (n))
				for i in range (n):
					bareFunc (*args, **kwargs)
				autoTester.check ('END repeatN ({})'.format (n))
			__pragma__ ('nokwargs')
			return innerFunc
		return repeat

	class Repeater:
		def __init__ (self, n):
			self.n = n
			
		def __call__ (self, bareFunc):
			__pragma__ ('kwargs')
			def innerFunc (*args, **kwargs):
				autoTester.check ('BEGIN repeat3')
				for i in range (self.n):
					bareFunc (*args, **kwargs)
				autoTester.check ('END repeat3')
			__pragma__ ('nokwargs')
			return innerFunc
		
	@repeatN (4)
	@repeat3
	def funcNoArg ():
		autoTester.check ('spam')
		
	funcNoArg ()
	autoTester.check ()

	__pragma__ ('kwargs')
	@repeat3
	@repeatN (2)
	def funcArg (a):
		autoTester.check ('eggs', a)
	__pragma__ ('nokwargs')
		
	funcArg (3)
	autoTester.check ()

	funcArg (a = 4)
	autoTester.check ()

	__pragma__ ('opov')
	@Repeater (3)
	def funcNoArg2 ():
		autoTester.check ('toast')
	__pragma__ ('noopov')

	funcNoArg2 ()
	autoTester.check ()

	__pragma__ ('opov')
	__pragma__ ('kwargs')
	@Repeater (5)
	def funcArg2 (a):
		autoTester.check ('jam', a)
	__pragma__ ('nokwargs')
	__pragma__ ('noopov')

	funcArg2 (3)
	autoTester.check ()

	funcArg2 (a = 4)
	autoTester.check ()

	def next (bareFunc):
		def innerFunc (value):
			return bareFunc (value + 1)
		return innerFunc
		
	@next
	class Number:
		def __init__ (self, value):
			self.value = value
			
	autoTester.check ('two', Number (1) .value)
	
	class Test:	
		@classmethod
		def f (cls, x, y):
			autoTester.check (cls.__name__, x, y)
			
		def g (self, x, y):
			autoTester.check (self.__class__.__name__, x, y)
			
	test = Test ()

	test.f (1, 2)
	test.g (3, 4)
	
	
Example #20
0
# First run a test from the command prompt, generating an HTML file.
# The output of the test is stored in a DIV.
# Also the script is automatically included in the HTML file.
# Loading the HTML file will run the script.
# This will compare the output of the script running in the browswer to the output in the DIV.
# If those two match, the test reports OK, else it reports failure.


from org.transcrypt.stubs.browser import __main__, __envir__, __pragma__
from org.transcrypt.autotester.html import HTMLGenerator, DataConverter, JSTesterUI

# Don't import __envir__ from __base__ since it will overwrite __buildin__.__envir__ in the browser
# Import from stubs will be skipped in the browser
# ... The ice is a bit thin here

__pragma__ ('nokwargs')

import itertools

def getFileLocation(ancestor):
	""" This function needs to crawl up the stack
	and find out where the ancestor caller of
	this function was in the source code of either the
	python or javascript, depending on environment.
	@param ancestor the ancestor of this function that
	  we want to capture file information about.
	@return string indicating the file position and line number
	"""
	if __envir__.executor_name == __envir__.transpiler_name: # js
		s = None
		__pragma__('js', '{}',
Example #21
0
def run(test):
    """
    """

    def func(a,b):
        return(a*b)

    test.check( func(3,4) )
    test.check( callable(func) )

    for a in (True, False):
        test.check( callable(a) )

    a = 1
    test.check( callable(a) )
    a = 2.3
    test.check( callable(a) )
    a = "asdf"
    test.check( callable(a) )

    a = []
    test.check( callable(a) )
    a = [1,2,3,3]
    test.check( callable(a) )
    a = ["asdf", "qwer", "zxcv"]
    test.check( callable(a) )

    a = {"asdf" : 1, "qwer": 2}
    test.check( callable(a) )

    a = set([1,2])
    test.check(callable(a))

    __pragma__('opov')

    class callObj(object):
        def __init__(self, r):
            self._r = r

        def __call__(self):
            return(self._r)

    test.check( callable(callObj) )

    obj = callObj(2)
    test.check(obj())
    test.check( callable(obj) )
    test.check( callable(obj._r) )

    class nonCallObj(object):
        def __init__(self, b):
            self._b = b

        def func(self):
            return(self._b)

    test.check( callable(nonCallObj) )

    obj2 = nonCallObj(2)
    test.check( callable(obj2) )
    test.check( callable(obj2._b) )
    test.check( callable(obj2.func) )

    __pragma__('noopov')

    class nonOpovNonCallObj(object):
        """
        """
        def __init__(self, c):
            self._c = c

        def other(self, b):
            return(self._c * b)

        def _getC(self):
            return(self._c)
        def _setC(self, val):
            self._c = val

        C = property(_getC, _setC)

    obj = nonOpovNonCallObj(4)
    test.check( callable(obj) )
    test.check( callable(obj.other) )
    test.check( callable(obj._c) )
    test.check( callable(obj.C) )

    exc = Exception("asdf")
    test.check( callable(exc) )
Example #22
0
def getFileLocation(ancestor):
	""" This function needs to crawl up the stack
	and find out where the ancestor caller of
	this function was in the source code of either the
	python or javascript, depending on environment.
	@param ancestor the ancestor of this function that
	  we want to capture file information about.
	@return string indicating the file position and line number
	"""
	if __envir__.executor_name == __envir__.transpiler_name: # js
		s = None
		__pragma__('js', '{}',
			'''
			var e = new Error();
			if ( ! e.stack ) {
			  console.log("MAJOR ISSUE: Browser Error lacks Stack");
			} else {
			  s = e.stack;
			}
			''')
		# Now we will process the stack to find the grandparent
		# calling function
		# @note - I'm explicitly not including a 're' module
		#    dependency here
		frames = None
		__pragma__('js', '{}',
			'''
			var linereg = new RegExp("\\n\\r|\\n", "g");
			frames = s.toString().split(linereg);
			''')
		if ( frames is None or (len(frames) < 2)):
			__pragma__('js', '{}', 'console.log("Failed to Split Stack");')
			return("UNKNOWN:???")

		# @note - if the call stack in transcrypts javascript
		#   translation changes then this index may need to change
		#   @todo - need more work here to determine this because
		#     this is fragile
		gpFrame = frames[(ancestor*2 + 1)]
		# This regex splits the string coming from the javascript
		# stacktrace so that we can connect the file and line number
		# runTests (http://localhost:8080/run/autotest.js:3159:8)
		#  func	      URL		      filename	  lineno:colno
		# Group 1 = function
		# Group 2 & 3 = protocol and hostname
		# Group 4 = Path on this host (filename is at the end)
		# Group 5 = lineno
		# Group 6 = column number in file
		frameReg = r"([^(]*)\(?([^:]*:)\/{2,3}([^:/]*:?)([^:]*):(\d+):(\d+)"
		m = None
		__pragma__('js', '{}',
			'''
			var r = new RegExp(frameReg);
			m = r.exec(gpFrame);
			''')
		if m:
			filepath = m[4]
			# Split the filepath and take the last element
			# to the get filename
			pathParts = filepath.split("/")
			filename = pathParts[len(pathParts)-1]
			lineno = m[5]
			return( "{}:{}".format(filename, lineno) )
		else:
			__pragma__('js', '{}', 'console.log("Failed to Match Frame");')
			return("UNKNOWN:???")
	#ELSE
	# Needed because Transcrypt imports are compile time
	__pragma__("skip")
	from inspect import getframeinfo, stack
	s = stack()
	caller = getframeinfo(s[ancestor][0])
	# Trim the file name path so that we don't get
	# a lot of unnecessary content
	filepath = caller.filename
	# @todo - this is a hack - we should use os.path
	pathParts = filepath.split('/')
	filename = "/".join(pathParts[-2:])
	return( "%s:%d" % (filename, caller.lineno))
	__pragma__ ('noskip')
Example #23
0
# Utilities for implementating the unit tests for the
# logging module.
#
from org.transcrypt.stubs.browser import __pragma__, __envir__
import logging

__pragma__("kwargs")

class TestHandler(logging.Handler):
    """ This handler is intended to make it easier to test the
    logging module output without requiring the console or the
    sys.stderr.
    """
    def __init__(self, test, lvl):
        """
        @param test AutoTester object that messages will
          be logged to for unit testing.
        @param level logging level that will be filtered.
        """
        logging.Handler.__init__(self, lvl)
        self._test = test

    def emit(self, record):
        """
        """
        msg = self.format(record)
        self._test.check(msg)

def resetLogging():
    """ Reset the handlers and loggers so that we
    can rerun the tests starting from a blank slate.
Example #24
0
from org.transcrypt.stubs.browser import __pragma__

__pragma__ ('kwargs')

class A:
    def __init__ (self, x = 123, y = 456, *args, m, n = 456, **kwargs):
        self.x = x
        self.y = y
        self.args = args
        self.m = m
        self.n = n
        self.kwargs = kwargs
        self.extra = 'hello'

    def f (self, autoTester):
        autoTester.check (self.x, self.y, self.args, self.m, self.n, self.kwargs, self.extra)
        
class B (A):
    def __init__ (self, x, y = -1, *args, m = -2, n, **kwargs):
        A.__init__ (self, y, x, *args, m = n, n = m, **kwargs)
        
class C:
    __pragma__ ('nokwargs')
    def tricky (self, *args):
        return args
    __pragma__ ('kwargs')
    
def run (autoTester):
    def f (x, y = -1, *args, m = -2, n, **kwargs):
        # BEGIN issue 203, kwargs turned into real dict
        autoTester.check ('#203', kwargs.__class__.__name__)
Example #25
0
def run (autoTester):
    tel = {'guido': 4127, 'jack': 4098}
    autoTester.check (len (tel))
    tel ['sape'] = 4139

    autoTester.check (tel)
    autoTester.check (tel ['jack'])

    del tel ['sape']
    tel ['irv'] = 4127
    autoTester.check (tel)

    autoTester.check (sorted (list (tel.keys ())), False)
    autoTester.check (sorted (tel.keys ()))

    autoTester.check ('guido' in tel)
    autoTester.check ('jack' not in tel)

    autoTester.check (dict ([('guido', 4127), ('jack', 4098), ('sape', 4139)]))
    autoTester.check (
        autoTester.expectException( lambda: dict(1) )
    )
    autoTester.check (
        autoTester.expectException( lambda: dict(134.34) )
    )
    autoTester.check (
        autoTester.expectException( lambda: dict('asdf') )
    )
    autoTester.check (
        autoTester.expectException( lambda: dict(['1234', 1]) )
    )

    autoTester.check( dict ([]))
    autoTester.check (dict ({}))
    autoTester.check (dict ({'asdf': 1, 'qwer': 2}) )

    # check dict copy, Issue # 221
    b = {'a' : 2.01, 'b': -3.3}
    d = dict (b)
    autoTester.check (d)
    b = {'a' : 2, 'b': [1,2,3]}
    d = dict (b)
    autoTester.check (d)
    b = {'a' : None, 'b': set([1,2,3])}
    d = dict (b)
    autoTester.check (d)
    b = {'a' : {'c': 2}, 'b': (1,2)}
    d = dict (b)
    autoTester.check (d)
    autoTester.check (d['a']['c'])
    autoTester.check (d.get('a').get('c'))
    autoTester.check (b.get('a').get('c'))
    d['a']['c'] = 3
    autoTester.check (d.get('a').get('c'))
    autoTester.check (b.get('a').get('c'))

    knights = {'robin': 'the brave', 'gallahad': 'the pure'}

    for k, v in sorted (knights.items ()):
        autoTester.check (k, v)

    if 'gallahad' in knights:
        autoTester.check ('gallahad is a knight') 

    for k in sorted (knights):
        autoTester.check (k)
        
    knight = {'rudolph': 'the righteous'}
    for k in knight:    # Autotest automatic conversion with one knight, since sort order of dict undefined
        autoTester.check (k)
        
    tel = {'guido': 123}
    tel.update({'edsger': 42})
    autoTester.check (tel.setdefault ('linus', 456))
    autoTester.check (tel ['linus'])
    autoTester.check (tel.setdefault ('guido', 789))
    autoTester.check (tel.pop ('guido', 1))
    autoTester.check (tel.pop ('guido', 1))
    autoTester.check (tel.pop ('edsger', 2))
    autoTester.check (tel.pop ('foo', 'bar'))
    autoTester.check (tel.pop ('foo', None))

    # Check compound keys (issue 281)
    
    d = {}
    d ['a'] = 3777
    d [(1, 2)] = 4777
    autoTester.check (d ['a'], d [(1, 2)])

    __pragma__ ('opov')
    d = {}
    d ['a'] = 3777
    d [(1, 2)] = 4777
    autoTester.check (d ['a'], d [(1, 2)])
    __pragma__ ('noopov')
    
    # Check exceptions
    knights = {'robin': 'the brave', 'gallahad': 'the pure'}
    autoTester.check (
        autoTester.expectException ( lambda: knights.pop("batman") )
    )
    autoTester.check (
        autoTester.expectException ( lambda: knights.pop("batman", None) )
    )
    autoTester.check (
        autoTester.expectException ( lambda: knights.pop("batman", "the gullible") )
    )
Example #26
0
from org.transcrypt.stubs.browser import *
from org.transcrypt.stubs.browser import __main__, __envir__, __pragma__

from math import sin, cos, pi

transpiled = __envir__.executor_name == __envir__.transpiler_name

# Imports for Transcrypt, skipped run time by CPython
if __envir__.executor_name == __envir__.transpiler_name:
    import numscrypt as num
    import numscrypt.fft as fft

# Imports for CPython, skipped compile time by Transcrypt
__pragma__('skip')
import numpy as num
import numpy.fft as fft
__pragma__('noskip')

fSample = 4096
tTotal = 2
fSin = 30
fCos = 50


def getNow(
):  # Avoid operator overloading, which would result in the dysfunctional: __new__ __call__ (Date)
    return __new__(Date())


def tCurrent(iCurrent):
    return iCurrent / fSample
Example #27
0
from org.transcrypt.stubs.browser import __pragma__
import org.transcrypt.autotester

import arguments
import attribs_by_name
import callable_test
import classes
import complex_numbers
import conditional_expressions
import control_structures

__pragma__ ('ifdef', '__py3.6__')   # Needed because Transcrypt imports are compile time
if '__py3.6__' in __symbols__:      # Needed because CPython doesn't understand pragma's
    import dashed_numbers
__pragma__ ('endif')

import data_structures
import decorators
import dict_comprehensions
import dictionaries
import div_issues
import div_pulls
import docstrings
import exceptions
import extended_slices

__pragma__ ('ifdef', '__py3.6__')   # Needed because Transcrypt imports are compile time
if '__py3.6__' in __symbols__:      # Needed because CPython doesn't understand pragma's
    import fstrings
__pragma__ ('endif')
Example #28
0
import arguments
import attribs_by_name
import classes
import conditional_expressions
import control_structures
import data_structures
import dict_comprehensions
import dictionaries
import div_fixes
import div_pulls
import exceptions
import extended_slices
import general_functions
import indices_and_slices

__pragma__ ('ifdef', 'e6')	# Needed because Transcrypt imports are compile time
if 'e6' in __symbols__:	# Needed because CPython doesn't understand pragma's
	import iterators_and_generators
__pragma__ ('endif')

import lambda_functions
import list_comprehensions

__pragma__ ('ifdef', 'e6')
if 'e6' in __symbols__:
	import module_itertools
__pragma__ ('endif')

import module_math
import modules
import nonlocals
Example #29
0
def run (autoTester):
	autoTester.check ('sort and sorted<br>')
	a = [1, 5, 3, 2, -1]
	b = ['sun', 'earth', 'moon']
	
	autoTester.check (sorted (a))
	autoTester.check (sorted (b))
	
	a.sort ()
	autoTester.check (a)
	
	b.sort ()
	autoTester.check (b)

	autoTester.check (sorted (a, reverse = True))
	autoTester.check (sorted (b, reverse = True))
	
	a.sort (reverse = True)
	autoTester.check (a)
	
	b.sort (reverse = True)
	autoTester.check (b)
	
	b.sort (key = lambda x: len (x)) 
	autoTester.check (b)

	b.sort (key = lambda x: len (x), reverse = True) 
	autoTester.check (b)

	autoTester.check ('<br><br>dir<br>')
	autoTester.check ([entry for entry in dir (A) if not entry.startswith ('__')])
	autoTester.check ([entry for entry in dir (A()) if not entry.startswith ('__')])
	autoTester.check ([entry for entry in dir (B) if not entry.startswith ('__')])
	autoTester.check ([entry for entry in dir (B()) if not entry.startswith ('__')])

	autoTester.check ('<br><br>any, all, sum<br>')
	list1 = ['ape', 'node', 'mice']
	list2 = ['vim', '', 'jet']
	list3 = ['', '', '']
	list4 = [[1, 2], [1], []]	# Truthyness into play
	autoTester.check (list1, any (list1), all (list1))
	autoTester.check (list2, any (list2), all (list2))
	autoTester.check (list3, any (list3), all (list3))
	autoTester.check (list4, any (list4), all (list4))
	
	autoTester.check (sum (range (5)))
	
	__pragma__ ('ifdef', '__esv6__')
	if '__esv6__' in autoTester.symbols:	
		def generator1 ():
			for i in range (5):
				yield i;
				
		def generator2 ():
			for i in range (5):
				if i % 2:
					yield 0
				else:
					yield i;
					
		def generator3 ():
			for i in range (5):
				yield 0;
				
		autoTester.check (generator1 (), any (generator1 ()), all (generator1 ()))
		autoTester.check (generator2 (), any (generator2 ()), all (generator2 ()))
		autoTester.check (generator3 (), any (generator3 ()), all (generator3 ()))
		
		autoTester.check (sum (generator1 ()))
	__pragma__ ('endif')
Example #30
0
from org.transcrypt.stubs.browser import __pragma__
__pragma__ ('iconv')

def run (autoTester):
    tel = {'guido': 4127, 'jack': 4098}
    autoTester.check (len (tel))
    tel ['sape'] = 4139

    autoTester.check (tel)
    autoTester.check (tel ['jack'])

    del tel ['sape']
    tel ['irv'] = 4127
    autoTester.check (tel)

    autoTester.check (sorted (list (tel.keys ())), False)
    autoTester.check (sorted (tel.keys ()))

    autoTester.check ('guido' in tel)
    autoTester.check ('jack' not in tel)

    autoTester.check (dict ([('guido', 4127), ('jack', 4098), ('sape', 4139)]))
    autoTester.check (
        autoTester.expectException( lambda: dict(1) )
    )
    autoTester.check (
        autoTester.expectException( lambda: dict(134.34) )
    )
    autoTester.check (
        autoTester.expectException( lambda: dict('asdf') )
    )
Example #31
0
from org.transcrypt.stubs.browser import __pragma__
import re
__pragma__("skip")
re.J = (1<<19)
re.JSSTRICT = re.J
__pragma__("noskip")

from basictests import *

def run (test):
    """ basic tests of the re engine. The point is to
    exercise most of the methods to make sure they behave as
    expected. These tests are expected to provide exhaustive
    coverage of the regex engine.
    """
    checkFlagsExist(test)
    escapeTests(test)
    checkMatchProperties(test, re.JSSTRICT)
    checkRegexProperties(test, re.JSSTRICT)

    checkIgnoreCase(test, re.JSSTRICT)

    checkSearchWithGroups(test, re.JSSTRICT)
    checkMatchOps(test, re.JSSTRICT)
    checkMatchWithGroups(test, re.JSSTRICT)
    #checkMatchWithNamedGroups(test, re.JSSTRICT)

    checkFullMatchOps(test, re.JSSTRICT)
    checkFindAllOps(test, re.JSSTRICT)
    checkSplitOps(test, re.JSSTRICT)
    checkSubOps(test, re.JSSTRICT)
Example #32
0
import math
from src.react_utils import (h, e, React, createReactClass, QueryLink)

from src.state import state
from src.i18n import tr
from src import utils
from org.transcrypt.stubs.browser import __pragma__
__pragma__('alias', 'as_', 'as')

__pragma__('skip')
require = window = require = setInterval = setTimeout = setImmediate = None
clearImmediate = clearInterval = clearTimeout = this = document = None
JSON = Math = console = alert = requestAnimationFrame = None
js_undefined = location = localStorage = sessionStorage = None
Date = None
__pragma__('noskip')

ui = require("semantic-ui-react")

slick = require('react-slick')['default']
Alert = require('react-s-alert')['default']


def SliderNav(props):
    return e(ui.Icon,
             js_name="chevron {}".format(props.direction),
             link=True,
             circular=True,
             inverted=True,
             className="slide-next {}".format(props.direction),
             onClick=props.onClick)