def destroyAndSendBack():
		
		# Get which direction is checked in the directionForm
		for element in directionForm:
			if(element.tagName == 'INPUT'):
				if(element.checked == True):
					direction = element.value
		
		#Get chosen puzzle
		chosen = None
		imgSelect = document.getElementById("imageSelect")
		musSelect = document.getElementById("musicSelect")
		
		if(imgSelect.disabled != musSelect.disabled):
			
			if(imgSelect.disabled):
				chosenNum = musSelect.selectedIndex
				chosen = musicPuzzles[chosenNum]
			else:
				chosenNum = musSelect.selectedIndex
				chosen = imagePuzzles[chosenNum]
			
			# Send back information and destroy the state
			destroy_menu("addPuzzleMenu")
			
			enableOpSelect()
			
			sendBack(state,direction,chosen)
		else:
			alert("No puzzle selected")	
 def change_page(ev):
     val = ev.target['data-id']
     # currently unable to create an event to trigger the template
     if val == 'Table':
         doc.getElementById('nav_target').click()
     doc[val].style.display = 'block'
     doc[f'b_{val}'].attrs['class'] = 'current_tab page'
     idx = pages.index(val)
     for i in pages[:idx] + pages[idx + 1:]:
         doc[i].style.display = 'none'
         doc[f'b_{i}'].attrs['class'] = 'page'
def disableOpSelect():
	# Disable operator controls
	opSel = document.getElementById("theoptselect")
	applyButton = document.getElementById("applyButtonID")
	resetState = document.getElementById("RESET_BUTTONID")
	backTrack = document.getElementById("BACKTRACK_BUTTONID")
	
	opSel.disabled = True
	applyButton.disabled = True
	resetState.disabled = True
	backTrack.disabled = True
def enableOpSelect():		
	# Enable op controls
	opSel = document.getElementById("theoptselect")
	applyButton = document.getElementById("applyButtonID")
	resetState = document.getElementById("RESET_BUTTONID")
	backTrack = document.getElementById("BACKTRACK_BUTTONID")
	
	opSel.disabled = False
	applyButton.disabled = False
	resetState.disabled = False
	backTrack.disabled = False
Example #5
0
def fn():
    doc.write('ready')
    codeA = doc.getElementById("coder").innerHTML
    code = codeA
    code = sub(r"<(.|\n)*?>", "", code)
    code = sub(r"(\w+)\((.*)\)", r'<span class="function">\1</span>(\2)', code)
    for x in [
            '%',
            '**=',
            '+=',
            '*=',
            '%=',
            '-=',
            '/=',
            '**',
            '^',
            '>=',
            '<=',
            '+',
            '//=',
            '\\',
            '*',
            '==',
            '=',
    ]:
        code = code.replace(x, f'<span class="operand">{x}</span>')
    for x in [
            'for', 'while', 'import', 'yield', 'from', 'del', 'pass', 'def',
            'if', 'elif', 'else', 'try', 'raise', 'with', 'async', 'finally',
            'except', 'except', 'await ', 'class', 'as', 'and', 'or', 'not',
            'is', 'in', 'False', 'True', 'break', 'continue', 'lambda ',
            'global', 'assert', 'nonlocal'
    ]:
        for y in punctuation:
            code = code.replace(y + x + y, x)
            code = code.replace(x + y, x)
            code = code.replace(y + x, x)
            code = code.replace(x, f'<span class="builtin">{x}</span>')
    strings = {
        r"([fF])'(.*)'": r'<span class="fstring">\1\'\2\'</span>',
        r"([bB])'(.*)'": r'<span class="bytes">\1\'\2\'</span>',
        r"([uU])'(.*)'": r'<span class="string">\1\'\2\'</span>',
        r"([rR])'(.*)'": r'<span class="bytes">\1\'\2\'</span>',
        r"'(.*)'": r'<span class="string">\1\'\2\'</span>',
        r'([fF])"(.*)"': r'<span class="fstring">\1"\2"</span>',
        r'([bB])"(.*)"': r'<span class="bytes">\1"\2"</span>',
        r'([uU])"(.*)"': r'<span class="string">\1"\2"</span>',
        r'([rR])"(.*)"': r'<span class="bytes">\1"\2"</span>',
        r'"(.*)"': r'<span class="string">\1"\2"</span>'
    }
    for string in strings:
        code = sub(string, strings[string], code)
    if codeA != code:
        doc.getElementById("coder").innerHTML = code
Example #6
0
    def __init__(self, name, app_id, id=None, icon=None, startup=None, on_exit=None, factory=None):
        print('Start...')

        App.app = self
        App.app_module = self.__module__.split('.')[0]
        App.app_dir = current_script_path()

        self.name = name
        self._app_id = str(app_id)
        self._id = id if id else identifier()
        self._icon = None

        self.commands = CommandSet(None)

        self._startup_method = startup

        self.default_icon = Icon('tiberius', system=True)
        self.icon = icon
        self._main_window = None
        self._on_exit = None

        self._full_screen_windows = None

        self.on_exit = on_exit

        self._elm = document.getElementById(self.app_id)
Example #7
0
def channel_hangup_complete(data):
    # print('channel_hangup_complete', data)
    global CANVAS
    if (data['direction'] == 'outbound') and ('callee_id_number' in data) and ('caller_id_number' in data):
        if (len(data['caller_id_number']) == 4):
            data['caller_id_number'], data['callee_id_number'] = data['callee_id_number'], data['caller_id_number']

        if len(data['callee_id_number']) == 4:
            if data['hangup_cause'] in ('NO_ANSWER',): # 'NETWORK_OUT_OF_ORDER'):
                if (data['duration'] == -1):
                    Noanswered(data)
                else:
                    print('channel_hangup_complete.outbound DURATION_ERROR', data)
            else:
                # print('channel_hangup_complete: len(callee_id_number) != 4', data)
                if len(data['callee_id_number']) == 4:
                    if (data['callee_id_number'] not in CANVAS):
                        Canvas(data['callee_id_number'])
                    CANVAS[data['callee_id_number']].add_event(data)
        else: # Исходящий
            # print('channel_hangup_complete: len(callee_id_number) != 4', data)
            pass
    else:
        print('channel_hangup_complete.inbound', data)
        if (data['direction'] == 'inbound') and ('callee_id_number' in data) and ('caller_id_number' in data):
            # answered_elements = [answered.id for answered in DOM.getElementsByClassName('answered-phone') if answered.innerHTML == data['caller_id_number']]
            for operator_id in [answered.id.split('.')[1] for answered in DOM.getElementsByClassName('answered-phone') if answered.innerHTML == data['caller_id_number']]:
                # operator_id = el.id.split('.')[1]
                if operator_id in CANVAS:
                    canvas = DOM.getElementById('canvas.'+operator_id)
                    calls = canvas.getElementsByClassName('call-brick') if canvas else []
                    if (len(calls) > 0) and (int(calls[-1].style.marginRight.replace('px', '')) == 0):
                        CANVAS[operator_id].add_event(data)
                        break
Example #8
0
    def run(self):
        def _update_wrapper(i):
            timer.request_animation_frame(_update_wrapper)

            # time between frames
            dt = 1 / 60 * application.time_scale
            time.dt = dt

            mouse.update()

            if hasattr(__main__, 'update') and not application.paused:
                __main__.update()

            for seq in application.sequences:
                seq.update()

            for entity in scene.entities:
                if entity.enabled == False or entity.ignore:
                    continue

                if application.paused and entity.ignore_paused == False:
                    continue

                if hasattr(entity, 'update'):
                    entity.update()

                if hasattr(entity, 'scripts'):
                    for script in entity.scripts:
                        if script.enabled and hasattr(script, 'update'):
                            script.update()

        _update_wrapper(0)

        loading_text = document.getElementById('loading_text')
        loading_text.remove()
Example #9
0
    def drawBoard(self):
        self.newPan = doc.createElementNS("http://www.w3.org/2000/svg", "svg")
        self.newPan.setAttribute("width", self.boardsize[0] * self.boardscale)
        self.newPan.setAttribute("height", self.boardsize[1] * self.boardscale)
        self.newPan.setAttribute(
            "style",
            "background-color:rgb(0,0,0);border-style:solid;border-width:1;border-color:#000;"
        )
        currentDiv = doc.getElementById("div")
        temp = temp = "rgb(" + str(255) + "," + str(127) + "," + str(39) + ")"
        for x in range(self.boardsize[0] - 1):
            line = svg.line(x1="0", y1="0", x2="1", y2="1", stroke=temp)
            line.setAttribute("x1", (x + 1) * self.boardscale)
            line.setAttribute("x2", (x + 1) * self.boardscale)
            line.setAttribute("y1", 0)
            line.setAttribute("y2", self.boardsize[1] * self.boardscale)
            line.setAttribute("stroke-opacity", .17)
            self.newPan.appendChild(line)
        for x in range(self.boardsize[1] - 1):
            line = svg.line(x1="0", y1="0", x2="1", y2="1", stroke=temp)
            line.setAttribute("x1", 0)
            line.setAttribute("x2", self.boardsize[0] * self.boardscale)
            line.setAttribute("y1", (x + 1) * self.boardscale)
            line.setAttribute("y2", (x + 1) * self.boardscale)
            line.setAttribute("stroke-opacity", .17)
            self.newPan.appendChild(line)

        doc.body.insertBefore(self.newPan, currentDiv)
def create_puzzle_list(state):

	boardDiv = document.getElementById("boarddivid")

	listDiv = html.DIV(id="puzzleListDiv", width = GAME_WIDTH, height = GAME_HEIGHT)
	puzzleList = html.OL(id="puzzleList")

	tableWrapper = html.DIV(id="tableWrapper", style = {'position' : 'relative', 'height' : 'auto'})
	scrollDiv = html.DIV(id="tableScroll", style = {'height' : str(GAME_HEIGHT) + 'px', 'overflow' : 'auto'})
	puzzleTable = html.TABLE(id="puzzleTable", style = {'width' : str(GAME_WIDTH) + 'px', 'font-size' : '13px','background-color' : 'rgb(220, 238, 251)' , 'text-align' : 'center'})
	headerRow = html.TR(id="puzzleHeaders", style = {'background-color' : 'rgb(200, 218, 231)'})
	
	headerRow <= html.TH("Number")
	headerRow <= html.TH("Puzzle")
	puzzleTable <= headerRow
	
	# Add puzzles to list
	i = 1
	for puzzle in state["Image_Puzzles"]:
		newRow = html.TR(id="puzzleRow"+ str(i))
		newRow <= html.TD(str(i))
		newRow <= html.TD(puzzle + " (Image Puzzle)")
		puzzleTable <= newRow
		i += 1
	for puzzle in state["Music_Puzzles"]:
		newRow = html.TR(id="puzzleRow"+ str(i))
		newRow <= html.TD(str(i))
		newRow <= html.TD(puzzle + " (Music Puzzle)")
		puzzleTable <= newRow
		i += 1
	
	puzzleTable.border = '10px solid white'
	boardDiv <= puzzleTable
Example #11
0
 def __init__(self, operator_id):
     CANVAS[operator_id] = self
     self.busy = False
     self.to_delete = False
     self.queue = []
     self.duration = 0
     self.operator_id = operator_id
     operator_row = html.DIV(Class="operator-row", Id=operator_id)
     operator_canvas = html.DIV(Class="operator-canvas", Id="canvas."+operator_id)
     operator_info = html.DIV(Class="operator-info", Id="operator."+operator_id)
     operator_name = html.DIV(operator_id, Class="operator-name")
     # operator_width = html.DIV(Class="operator-width", Id="width."+operator_id)
     answered_wait = html.DIV(Class="answered-wait", Id="answered_wait."+self.operator_id)
     answered_duration = html.DIV(Class="answered-duration", Id="answered_duration."+self.operator_id)
     answered_phone = html.DIV(Class="answered-phone", Id="answered_phone."+self.operator_id)
     operator_answered = html.DIV('0', Class="operator-score-answered",
                                  Id="score_answered." + operator_id)
     operator_noanswered = html.DIV('0', Class="operator-score-noanswered", 
                                    Id="score_noanswered." + operator_id)
     operator_info <= operator_name
     # operator_info <= operator_width
     operator_info <= operator_answered
     operator_info <= answered_wait
     operator_info <= answered_duration
     operator_info <= answered_phone
     operator_info <= operator_noanswered
     operator_row <= operator_canvas
     operator_row <= operator_info
     content = DOM.getElementById('content')
     content <= operator_row
Example #12
0
def onload():
    global body
    body = document.getElementById('body')
    json = urlopen('/json')
    global posts
    posts = json[:]
    start = 0
    cs = getCookie('start')
    i = 0
    if (getCookie('up') == '1'):
        setCookie('up', '0')
        cs = None

    for post in posts:
        post['index'] = i
        post['posted'] = 0
        if (cs == post['url']):
            start = i

        i += 1

    body.innerHTML = ''
    i = start
    while i < len(posts) and i < postsinpage + start:
        body.innerHTML += posttotext(posts[i])
        posts[i].posted = 1
        i += 1

    del_ = start
Example #13
0
        def drawBoard(self):
                self.newPan = doc.createElementNS("http://www.w3.org/2000/svg","svg")
                self.newPan.setAttribute("width",self.boardsize[0]*self.boardscale)
                self.newPan.setAttribute("height",self.boardsize[1]*self.boardscale)
                self.newPan.setAttribute("style","background-color:rgb(0,0,0);border-style:solid;border-width:1;border-color:#000;")
                currentDiv = doc.getElementById("div")
                temp = temp = "rgb("+str(255)+","+str(127)+","+str(39)+")"
                for x in range(self.boardsize[0]-1):
                        line = svg.line(x1="0", y1="0", x2="1", y2="1", stroke=temp)
                        line.setAttribute("x1",(x+1)*self.boardscale)
                        line.setAttribute("x2",(x+1)*self.boardscale)
                        line.setAttribute("y1", 0 )
                        line.setAttribute("y2", self.boardsize[1]*self.boardscale)
                        line.setAttribute("stroke-opacity", .17)
                        self.newPan.appendChild( line )
                for x in range(self.boardsize[1]-1):
                        line = svg.line(x1="0", y1="0", x2="1", y2="1", stroke=temp)
                        line.setAttribute("x1", 0 )
                        line.setAttribute("x2", self.boardsize[0]*self.boardscale)
                        line.setAttribute("y1",(x+1)*self.boardscale)
                        line.setAttribute("y2",(x+1)*self.boardscale)
                        line.setAttribute("stroke-opacity", .17)
                        self.newPan.appendChild( line )

                doc.body.insertBefore(self.newPan, currentDiv)
Example #14
0
def update_result(*args, **kwargs):
    left = document.select("#version-main select")[0].value
    right = document.select("#version-diff select")[0].value
    document.select("#version-main span")[0].textContent = left
    document.select("#version-diff span")[0].textContent = right

    document.getElementById("vitrine").innerHTML = '''
    <h2>Working...</h2><div class="entry">
    <h3><label for="vitrine-progress" id="vitrine-progress-label">Loading burger JSONs...</label></h3>
    <progress id="vitrine-progress"></progress>
    </div>
    '''

    if left == "None" and right == "None":
        #window.location = "about"
        return
    elif left == "None":
        data = {"main": right}
        call_worker("vitrine", left)
    elif right == "None":
        data = {"main": left}
        call_worker("vitrine", data)
    else:
        data = {"main": left, "diff": right}
        call_worker("hamburglar", data)
def channel_hangup_complete(data):
    #print (data['event_name'], data)
    set_counters(data)
    call_trace = doc.getElementById('%s.%s' % (data['trunk_name'], data[
                                    'virtual_line'])).getElementsByClassName('call-trace')[0]  # Линия
    if data['direction'] == 'outbound':
        html_ = ''
        if 'caller_id_number' in data:  # Это был не отзвон
            html_ = '<div class="caller-id-number" style="color:green;width:%s;">%s</div>' % (
                data['caller_width'], data['caller_id_number'])
        if data['duration'] > 0:  # Отвчен
            html_ += '<div class="callee-id-number" style="color:green;background:#ddffdd;width:%s;font-size:9px;">%s</div>' % (
                data['callee_width'], data['callee_id_number'])
            html_ += '<div class="callee-timer" style="padding-top:2px;text-align:right;color:white;background:green;width:28px;font-size:9px;">%s+%s</div>' % (data[
                                                                                                                                  'answer_wait'], data['duration'])
        else:
            html_ += '<div class="callee-id-number" style="color:red;background:#ffdddd;width:%s;font-size=9px;">%s</div>' % (
                data['callee_width'], data['callee_id_number'])
            html_ += '<div class="callee-timer" style="padding-top:2px;text-align:right;color:white;background:red;width:12px;font-size:9px;">%s</div>' % data[
                'answer_wait']
    if data['hangup_cause'] == 'NO_USER_RESPONSE':
        html_ += '<div class="hangup-cause">%s</div>' % data['hangup_cause']
    # Результат отметить тут
    html_ += '<div class="event-datetime">%s</div>' % data['event_timestamp']
    call_trace.innerHTML = html_
def destroy_menu(menuName,enabled = True):	
	if(enabled):
		enableOpSelect()
	try:
		menu = document.getElementById(menuName)
		gui.removeChild(menu)
	except:
		console.log("Destroy menu was called on a nonexistent object.")
Example #17
0
def runApp(app):
    try:
        out = document.getElementById("output-id")
        out.innerHTML = ""
        out.appendChild(app.dom())
    except Exception as e:
        out.innerHTML = ""
        out.innerHTML = "Error"
Example #18
0
    def __init__(self, **kwargs):
        self.b = _window

        self.size = (self.b.width, self.b.height)
        self.message = document.getElementById('message')
        self.message = 'Error'
        self.color = color.gray
        self.position = (0, 0)
def populateRuleDisplay(state):
	global ruleDisplay
	
	rHeight = ruleDisplay.height
	tHeight = document.getElementById("rulesTitle").height
	
	tableWrapper = html.DIV(id="tableWrapper", style = {'position' : 'relative', 'height' : 'auto'})
	scrollDiv = html.DIV(id="tableScroll", style = {'height' : str(rHeight - tHeight) + 'px', 'overflow' : 'auto'})
	ruleTable = html.TABLE(id="ruleTable", style = {'width' : '100%', 'font-size' : '13px'})
	headerRow = html.TR(id="ruleHeaders")
	
	headerRow <= html.TH("Number")
	headerRow <= html.TH("Conditions")
	headerRow <= html.TH("Actions")
	
	ruleTable <= headerRow

	for index, rule in enumerate(state["Rules"]):
			
		newRow = html.TR(id = "ruleRow" + str(index + 1))
		newRow <= html.TD(str(index+1), style = {'color' : "white"})
		
		conditionTD = html.TD()
		conditionP = None
		for condition in rule.conditions:
			if(condition.app):
				color = "white"
			else:
				color = "red"
			conditionP = html.P(condition.text + ", ", style = {'color' : color})
			conditionTD <= conditionP
		# Edge case
		if(conditionP is not None):
			conditionP.innerHTML = conditionP.innerHTML[:-2]
		
		actionTD = html.TD()
		actionP = None
		for action in rule.actions:
			if(action.app):
				color = "white"
			else:
				color = "red"
			actionP = html.P(action.text + ", ", style = {'color' : color})
			actionTD <= actionP
		# Edge case 
		if(actionP is not None):
			actionP.innerHTML = actionP.innerHTML[:-2]
		
		newRow <= conditionTD
		newRow <= actionTD

		ruleTable <= newRow
	
	ruleTable.border = '10px solid white'
	scrollDiv <= ruleTable
	tableWrapper <= scrollDiv
	ruleDisplay <= tableWrapper
def set_counters(data):
    counters = doc.getElementById('%s.0' % data['trunk_name'])
    counters = counters.getElementsByClassName('counters')[0]  # Счётчики
    # print ('set_counters: %s' % counters)
    cn = data['counters']
    html_ = '<div class="total">%s</div>' % cn['total']
    html_ += '<div class="answered">%s</div>' % cn['answered']
    html_ += '<div class="rejected">%s</div>' % cn['rejected']
    counters.innerHTML = html_
Example #21
0
def chart2(pair):
    Objcharts['chart2'] = window.echarts.init(
        document.getElementById("echart2"))
    og = w_mod_graphs.MarketTrades1('ohlc', Objcharts['chart2'], axis_sync)
    og.title = pair + " trades"
    og.market = pair
    if pair in Order_pos:
        og.orders = Order_pos[pair]
    og.load_data(ChartData_trades[pair])
Example #22
0
def on_message(ev):
    # message reeived from server
    for event, data in json.loads(ev.data).items():
        el_id = '%s.%s' % (data['header']['address'], data['channel'])
        el = doc.getElementById(el_id)
        if el:
            _class = tuple(set(el.classList) & event_classes)
            if _class:
                el.classList.remove(_class[0])
            el.classList.add(event.lower())
Example #23
0
def chart1(pair):
    jq("#echart1").show()
    Objcharts['chart1'] = window.echarts.init(
        document.getElementById("echart1"))
    og = w_mod_graphs.OrderBook1('orderbook', Objcharts['chart1'], axis_sync)
    og.title = pair + " orderbook"
    og.market = pair
    if pair in Order_pos:
        og.orders = Order_pos[pair]
    if Last_Pair in ChartOb:
        ChartData_ob[pair]['datazoom'] = [
            ChartOb[Last_Pair]['start'], ChartOb[Last_Pair]['end']
        ]
    og.load_data(ChartData_ob[pair])

    def froga(ev):
        print('click')

    document.getElementById("echart1").addEventListener('click', froga)
Example #24
0
def chart4(pair):
    jq("#echart4").show()
    Objcharts['chart4'] = window.echarts.init(
        document.getElementById("echart4"))
    og = w_mod_graphs.SeriesSimple('stoch-rsi', Objcharts['chart4'], axis_sync)
    og.driven = False
    og.title = pair + " stoch-rsi"
    og.market = pair
    og.hard_limits_y = [0, 100]
    og.load_data(ChartData_analisis2[pair])
Example #25
0
def chart6(pair):
    jq("#echart6").show()
    Objcharts['chart6'] = window.echarts.init(
        document.getElementById("echart6"))
    og = w_mod_graphs.SeriesSimple('cci', Objcharts['chart6'], axis_sync)
    og.driven = False
    og.title = pair + " cci"
    og.market = pair
    og.hard_limits_y = [-300, 300]
    og.load_data(ChartData_analisis4[pair])
Example #26
0
def chart3(pair):
    jq("#echart3").show()
    Objcharts['chart3'] = window.echarts.init(
        document.getElementById("echart3"))
    og = w_mod_graphs.SeriesSimple('wavetrends', Objcharts['chart3'],
                                   axis_sync)
    og.driven = False
    og.title = pair + " wavetrends"
    og.market = pair
    og.hard_limits_y = [-80, 80]
    og.load_data(ChartData_analisis1[pair])
Example #27
0
def set_visible(visibility):
    global current_cursor_css

    canvas = document.getElementById(gamejs.display.CANVAS_ID)
    if visibility:
        canvas.style.cursor = current_cursor_css
    else:
        canvas.style.cursor = "none"
    ret = set_visible.visibility
    set_visible.visibility = visibility
    return ret
Example #28
0
    def __timer__(self):
        global SCALE
        canvas = DOM.getElementById("noanswered_canvas."+self.caller_id)
        calls = canvas.getElementsByClassName("noanswered-brick")
        if len(calls) > 0:
            if self.width+SCALE > canvas.clientWidth:
                new_call_width = int(calls[0].style.width.replace('px', '')) - SCALE
                new_call_margin = int(calls[0].style.marginRight.replace('px', '')) + SCALE
                if new_call_width > 0:
                    calls[0].style.width = str(new_call_width)+'px'
                    calls[0].style.marginRight = str(new_call_margin)+'px'
                else:
                    if 'blue' not in calls[0].style['background-color']:
                        DOM.getElementById('score_noanswered').innerHTML = str(int(DOM.getElementById('score_noanswered').innerHTML)-1)
                    canvas.removeChild(calls[0])
                    self.to_delete = (self.width == 0)

                    # DOM.getElementById('score_noanswered.'+self.operator_id).text = str(int(DOM.getElementById('score_noanswered.'+self.operator_id).text)-1)
            else:
                calls[0].style.marginRight = str(int(calls[0].style.marginRight.replace('px', '')) + SCALE) + 'px'
Example #29
0
def set_cursor(sizeOrCSS, hotspot=None, xormasks=None, andmasks=None):
    global current_cursor_css

    if type(sizeOrCSS) is int or type(sizeOrCSS) is float:
        return
    elif type(sizeOrCSS) is str:
        canvas = document.getElementById(gamejs.display.CANVAS_ID)
        canvas.style.cursor = sizeOrCSS
        current_cursor_css - sizeOrCSS
    else:
        return
Example #30
0
def chart1(pair):
    jq("#echart1").show()
    Objcharts['ob'] = window.echarts.init(document.getElementById("echart1"))
    og = w_mod_graphs.OrderBook1(Objcharts['ob'])
    og.title = pair + " orderbook"
    og.market = pair
    og.orders = Order_pos[pair]
    if Last_Pair in ChartOb:
        ChartData_ob[pair]['datazoom'] = [
            ChartOb[Last_Pair]['start'], ChartOb[Last_Pair]['end']
        ]
    og.load_data(ChartData_ob[pair])
Example #31
0
    def __init__(self, data):
        NOANSWER[data['caller_id_number']] = self
        self.event_time = data['event_time'].split('.')[0]
        self.caller_id = data['caller_id_number']
        self.operator_id = data['callee_id_number']
        self.to_delete = False
        answer_wait = int(data['answer_wait'])
        noanswer_brick = html.DIV(Class="noanswered-brick",
                                  title='{}\n{}'.format(self.event_time, 
                                  '\n'.join([oi + ': ' + ('Занят' if c.busy else 'Свободен') for oi, c in CANVAS.items()])),
                                  style={'width': (answer_wait if answer_wait > 0 else 1), 'margin-right': 0,})
        # noanswer_brick.title += '\nОжидание'
        noanswer_canvas = html.DIV(Class="noanswered-canvas", Id="noanswered_canvas."+self.caller_id)
        noanswer_canvas <= noanswer_brick

        noanswer_wait = html.DIV(data['answer_wait'], Class="noanswered-wait")
        noanswer_phone = html.DIV(data['caller_id_number'], Class="noanswered-phone")
        noanswer_operator = html.DIV(data['callee_id_number'], Class="noanswered-operator")
        noanswer_info = html.DIV(Class="noanswered-info")
        noanswer_info <= noanswer_operator
        noanswer_info <= noanswer_wait
        noanswer_info <= noanswer_phone

        noanswer_row = html.DIV(Class="noanswered-row", Id=self.caller_id)

        noanswer_row <= noanswer_canvas
        noanswer_row <= noanswer_info

        DOM.getElementById('noanswered_calls') <= noanswer_row

        self.answer_wait = int(data['answer_wait'])
        DOM.getElementById('score_noanswered').text = str(int(DOM.getElementById('score_noanswered').text)+1)
        DOM.getElementById('score_noanswered.'+self.operator_id).text = str(int(DOM.getElementById('score_noanswered.'+self.operator_id).text)+1)
Example #32
0
def __timer__():
    global CANVAS
    global NOANSWER

    _started = time.time() # Хоть как-то минимизируем дрифт... Плохо всё...
    # print (CANVAS)
    # print (NOANSWER)

    for operator_id, canvas in CANVAS.items():
        # calls = DOM.getElementById(operator_id).getElementsByClassName('call-brick')
        if canvas.to_delete:
            DOM.getElementById('content').removeChild(DOM.getElementById(operator_id))
            del CANVAS[operator_id]
        else:
            canvas.__timer__()

    for caller_id, canvas in NOANSWER.items():
        # calls = DOM.getElementById(caller_id).getElementsByClassName('noanswered-brick')
        if canvas.to_delete:
            DOM.getElementById('noanswered_calls').removeChild(DOM.getElementById(caller_id))
            del NOANSWER[caller_id]
        else:
            canvas.__timer__()

    timer.set_timeout(__timer__, 1000-(time.time()-_started)*1000)
Example #33
0
    def callback(future):
        if active_future is not active_future:
            return

        active_future = None
        try:
            document.getElementById(
                "vitrine").innerHTML = future.result().data.to_dict()['result']
            attach_tooltip_handlers()
        except CancelledError:
            pass
        except webworker.WorkerError as e:
            document.getElementById(
                "vitrine"
            ).innerHTML = '<div class="entry"><h3>Error callback</h3><pre>' + escape(
                str(e)) + '</pre></div>'
        except:
            traceback.print_exc()
            document.getElementById(
                "vitrine"
            ).innerHTML = '<div class="entry"><h3>Error callback</h3><pre>' + escape(
                traceback.format_exc()) + '</pre></div>'
def channel_execute_complete(data):
    print(data['event_name'], data)
    if data['application_data'][0]:
        call_trace = doc.getElementById('%s.%s' % (data['trunk_name'], data[
                                        'virtual_line'])).getElementsByClassName('call-trace')[0]  # Линия
        html_ = call_trace.innerHTML
        if 'application-data' in html_:
            html_ = html_.split('<div class="application-data"')[0]
        app_style = 'color:green;' if data[
            'application_data'] == 'FILE PLAYED' else 'color:red;'
        html_ += '<div class="application-data" style="%s">%s</div>' % (
            app_style, data['application_data'][0])
        html_ += '<div class="event-datetime">%s</div>' % data['event_timestamp']
        call_trace.innerHTML = html_
Example #35
0
def incoming_data(data):
    global Panels
    if 'market_trades' in data['data']:
        market = data['data']['market_trades']['market']
        for p in Panels:
            if Panels[p]['market'] == market:
                jq("#echart_" + p).show()
                obj = window.echarts.init(
                    document.getElementById("echart_" + p))
                og = w_mod_graphs.MarketTrades1(obj)
                og.title = market + " trades"
                og.market = market
                og.load_data(data['data']['market_trades']['data'])
                Panels[p]['echart_obj'] = obj
                Panels[p]['wmgraph_obj'] = og
Example #36
0
    def set_mode(self, resolution=(0, 0), flags=0, depth=0, id="pygame"):
        self.canvas = document.getElementById(id)
        self.screen = self.canvas.getContext('2d')
        if not flags:
            self.canvas.width = resolution[0]
            self.canvas.height = resolution[1]
            rx = 1
            ry = 1
        else:
            self.canvas.width = resolution[0]
            self.canvas.height = resolution[1]
            rx = document[html.BODY][0].width / self.canvas.width
            ry = document[html.BODY][0].height / self.canvas.height
            self.canvas.width = document[html.BODY][0].width
            self.canvas.height = document[html.BODY][0].height

        return Surface((self.canvas.width, self.canvas.height),
                       screen=self.screen, ratio_x=rx, ratio_y=ry, canvas=self.canvas)
def set_up_black_overlay():
	
	gui = document.getElementById("thegui")
	blackOverlay = html.DIV(id = "blackOverlay",
							style = {
								'display' : 'none',
								'position' : 'fixed',
								'top' : '0%',
								'left' : '0%',
								'width' : '100%',
								'height' : '100%',
								'background-color' : 'black',
								'z-index' : '1001',
								'-moz-opacity' : '0.8',
								'opacity' : '.80',
								'filter' : 'alpha(opacity=80)'
								})
	
	gui <= blackOverlay
def getPuzzleIndex(puzzle):
	
	# Get current list of puzzle names
	puzzleTable = document.getElementById("puzzleTable")
	if(puzzleTable is not None):
		i = 0
		
		# Retrieves the name without the puzzle type description
		def getElementName(puzzle):
			name = ""
			paren = False
			i = 0
			while(paren == False and i < len(puzzle)):
				char = puzzle[i]
				nextChar = puzzle[i+1]
				if(nextChar == "("):
					paren = True
				else:
					name += char
				i += 1
			
			return name
			
		# Brython is being stupid so I have to do this 
		# really inefficient method, im so sorry
		onPuzzle = False
		i = 0
		name = ""
		number = None
		for row in puzzleTable:
			if(i > 0):
				for element in row:
					if(onPuzzle):
						name = getElementName(element.innerHTML)
						if(name == puzzle):
							return number
					else:
						number = element.innerHTML
					
					onPuzzle = not onPuzzle
			i += 1
		else:
			return None
def channel_create(data):  # Создание звонка
    # print (data['event_name'], data)
    set_counters(data)
    call_trace = doc.getElementById('%s.%s' % (data['trunk_name'], data['virtual_line']))
    call_trace = call_trace.getElementsByClassName('call-trace')[0]  # Линия
    if data['direction'] == 'inbound':
        html_ = '<div class="caller-id-number" style="width:%s;">%s</div>' % (
            data['caller_width'], data['caller_id_number'])
    else:
        if 'caller_id_number' in data:  # Подбор оператора
            html_ = '<div class="caller-id-number" style="color:darkgray;width:%s;">%s</div>' % (
                data['caller_width'], data['caller_id_number'])
            html_ += '<div class="callee-id-number" style="color:black;background:darkgray;width:%s;">%s</div>' % (data[
                                                                                                                                             'callee_width'], data['callee_id_number'])
        else:  # Отзвон
            html_ = '<div class="callee-id-number" style="color:darkgray;background:white;width:%s;">%s</div>' % (
                data['callee_width'], data['callee_id_number'])
    html_ += '<div class="event-datetime">%s</div>' % data['event_timestamp']
    call_trace.innerHTML = html_
	def destroyAndSendBack():

		if (document.getElementById("actionSelect") is not None):
			action = document.getElementById("actionSelect").value
		else:
			action = None

		if (document.getElementById("aFollowUpSelect") is not None):
			actionF = document.getElementById("aFollowUpSelect").value
		else:
			actionF = None

		if (document.getElementById("textInput") is not None):
			textF = document.getElementById("textInput").value
		else:
			textF = None
		
		aFollowUp = False
		if (action is None or action == "Nothing Selected"):
			alert("No action was selected.")
		else:
			if ((textF is not None and textF.strip() != '') or (actionF is not None and actionF != 'Nothing Selected')):
				aFollowUp = True	
			if (action == "Open Door" and aFollowUp is False
				or action == "Close Door" and aFollowUp is False
				or action == "Display Message" and aFollowUp is False):
				alert("Not enough information was entered.")
			elif(action == "Play Sound" and not url_is_valid(textF)):
				alert("File link was invalid.")
			else:
				#console.log("Debug: Enough info was given.")
				
				destroy_menu("addActionMenu")
				
				# Make sure something was actually put into the text box
				if(textF is not None and textF.strip() != ''):
					# Change display of text box information based on action.
					if(action == "Display Message"):
						actionF = "Display Message: " + "\"" + textF + "\""
					elif(action == "Play Sound"):
						actionF = "Play sound from link: \"" + textF + "\""
					elif(action == "Gain Points"):
						actionF = "Gain " + textF + " Points"
					elif(action == "Lose Points"):
						actionF = "Lose " + textF + " Points"
				if(actionF is not None):
					action = actionF
				
				sendBack(action)	
def channel_answer(data):  # Ответ
    # print (data['event_name'], data)
    set_counters(data)
    call_trace = doc.getElementById('%s.%s' % (data['trunk_name'], data[
                                    'virtual_line'])).getElementsByClassName('call-trace')[0]  # Линия
    #print ('channel_answer 0', data['event_name'], data, call_trace.innerHTML)
    #html_ = ''
    if data['direction'] == 'inbound':
        html_ = '<div class="caller-id-number">%s</div>' % data['caller_id_number']
    else:
        html_ = ''
        if 'caller_id_number' in data:
            html_ = '<div class="caller-id-number" style="color:green;width:%s;">%s</div>' % (
                data['caller_width'], data['caller_id_number'])
        html_ += '<div class="callee-id-number" style="color:green;background:#ddffdd;width:%s;font-size=9px;">%s</div>' % (
            data['callee_width'], data['callee_id_number'])
        html_ += '<div class="callee-timer" style="padding-top:2px;text-align:right;color:white;background:green;width:12px;font-size:9px;height:12px;">%s</div>' % data[
            'answer_wait']
    html_ += '<div class="event-datetime">%s</div>' % data['event_timestamp']
    call_trace.innerHTML = html_
Example #42
0
        def drawBoard(self):
                self.newPan = doc.createElementNS("http://www.w3.org/2000/svg","svg")
                self.newPan.setAttribute("width",self.boardsize[0]*self.boardscale)
                self.newPan.setAttribute("height",self.boardsize[1]*self.boardscale)
                self.newPan.setAttribute("style","background-color:rgb(0,0,0);border-style:solid;border-width:1;border-color:#000;")
                currentDiv = doc.getElementById("div")
                for x in range(self.boardsize[0]-1):
                        line = svg.line(x1="0", y1="0", x2="1", y2="1", stroke="brown", stroke_width="2")
                        line.setAttribute("x1",(x+1)*self.boardscale)
                        line.setAttribute("x2",(x+1)*self.boardscale)
                        line.setAttribute("y1", 0 )
                        line.setAttribute("y2", self.boardsize[1]*self.boardscale)
                        line.setAttribute("stroke-opacity", .2)
                        self.newPan.appendChild( line )
                for x in range(self.boardsize[1]-1):
                        line = svg.line(x1="0", y1="0", x2="1", y2="1", stroke="brown", stroke_width="2")
                        line.setAttribute("x1", 0 )
                        line.setAttribute("x2", self.boardsize[0]*self.boardscale)
                        line.setAttribute("y1",(x+1)*self.boardscale)
                        line.setAttribute("y2",(x+1)*self.boardscale)
                        line.setAttribute("stroke-opacity", .2)
                        self.newPan.appendChild( line )

                for k in self.shiplist:
                        line = svg.line(x1="0", y1="0", x2="1", y2="1", stroke="green", stroke_width="5")
                        line.setAttribute("x1", k.coord[0]*self.boardscale )
                        line.setAttribute("x2", (k.coord[0]+1)*self.boardscale )
                        line.setAttribute("y1", k.coord[1]*self.boardscale )
                        line.setAttribute("y2", (k.coord[1]+1)*self.boardscale )
                        self.newPan.appendChild( line )
                        line = svg.line(x1="0", y1="0", x2="1", y2="1", stroke="green", stroke_width="5")
                        line.setAttribute("x1", k.coord[0]*self.boardscale )
                        line.setAttribute("x2", (k.coord[0]+1)*self.boardscale )
                        line.setAttribute("y1", (k.coord[1]+1)*self.boardscale )
                        line.setAttribute("y2", k.coord[1]*self.boardscale )
                        self.newPan.appendChild( line )

                doc.body.insertBefore(self.newPan, currentDiv)
	def destroyAndSendBack():
		if (document.getElementById("conditionSelect") is not None):
			condition = document.getElementById("conditionSelect").value
		else:
			condition = None

		if (document.getElementById("cFollowUpSelect") is not None):
			conditionF = document.getElementById("cFollowUpSelect").value
		else:
			conditionF = None
		
		if (document.getElementById("textInput") is not None):
			textF = document.getElementById("textInput").value
		else:
			textF = None
		
		cFollowUp = False
		if (condition is None or condition == "Nothing Selected"):
			alert("No condition was selected.")
		else:
			if (conditionF is not None and conditionF != 'Nothing Selected'):
				cFollowUp = True
				
			if ((condition == "Entered Room" or condition == "Solved Puzzle") and cFollowUp is False):
				alert("Not enough information was entered.")
			else:
				#console.log("Debug: Enough info was given.")
				
				destroy_menu("addConditionMenu")
				
				if(textF is not None and textF.strip() != ''):
					if(condition == "Had Points"):
						conditionF = "Had " + textF + " Points."
					elif(condition == "Time Elapsed"):
						conditionF = textF + " minutes elapse."
					else:
						alert("invalid condition for follow up.")
				
				if(conditionF is not None):
					condition = conditionF

				sendBack(condition)	
def playSong(state):
	
	global Pitches

	puzzle = state["Music_Puzzles"][state["Selected_Music"]]
	
	# Music Settings
	tempo = 1.0
	pitchChange = 0.0
	
	notes = puzzle.notes
	
	# Secondary list of notes for permutation based transformations.
	notes2 = []
	
	# Apply transformations
	for transform in puzzle.transformList:
	
		if(transform == "increasePitch"):
			pitchChange = pitchChange + 10.0
			
		if(transform == "decreasePitch"):
			pitchChange = pitchChange - 10.0
			
		if(transform == "increaseTempo"):
			tempo = tempo - 0.5
			
		if(transform == "decreaseTempo"):
			tempo = tempo + 0.5
			
		if(transform == "shuffleNotes"):
			
			# Temp storage array
			notes2 = []
			
			# Group the notes into chords so shuffling doesn't break up chords
			notes = groupIntoChords(notes)
			n = len(notes)
			
			# Shuffle chords/notes of notes2
			# Pad to next odd number for invertibility
			if(n%2==0):
				notes.append([])
				n = n + 1
			for j in range(n):
				notes2.append(notes[(2*j)%(n)])
			
			# Read temp back into original notes array
			notes = readChords(notes2)	
			
		if(transform == "reverseNotes"):
		
			# Temp storage array
			notes2 = []
			
			notes = groupIntoChords(notes)
			n = len(notes) - 1
			
			for i in range(n,-1,-1):
				notes2.append(notes[i])
			
			# Read notes2 back into original notes
			notes = readChords(notes2)

	
	# Play transformed notes
	wait = 0
	timeLimit = 10
	i = 0
	length = len(notes)
	while(i < length):
		note = notes[i]
		wait = note["wait"] * tempo + wait 
		pitch = Pitches[note["pitch"]] + pitchChange
		hold = float(note["hold"]) 

		piano.play({
			'wait' : wait,
			'pitch' : pitch,
			'env' : {'hold' : hold},
			filter : { 'q' : 15 } 
		})
		
		i = i + 1
		
		# Stops the song from playing overtime
		if(wait > timeLimit):
			piano.stop()
			i = length
	
	playButton = document.getElementById("playButton")
		
	if(wait > timeLimit):
		alert("Song cannot be more than " + str(timeLimit) + " seconds long.")
		if(playButton is not None):
			playButton.disabled = True
			buttonDisabled = timer.set_timeout(allowPlay,(timeLimit) * 1000)
	else: 
		if(playButton is not None):
			playButton.disabled = True
			buttonDisabled = timer.set_timeout(allowPlay, int(wait+1) * 1000)
def aFollowUp(state):

	aFollowUp = document.getElementById("aFollowUp")
	
	if (aFollowUp is not None):
		aFollowUp.parentNode.removeChild(aFollowUp)
	
	aFollowUp = html.DIV(id="aFollowUp", style = {"margin" : '10px'})

	actionForm = document.getElementById("actionForm")
	
	action = document.getElementById("actionSelect").value
	
	aFollowUpSelect = html.SELECT(id = "aFollowUpSelect", style = {"margin-left" : "10px"})
	
	if(action == "Open Door"):
		aFollowUp <= "Pick a door:"
		
		doorOp = html.OPTION("Nothing Selected")
		aFollowUpSelect <= doorOp
		
		for index in range(1, 10):
			for side in ['S', 'E']:
				if side == 'S':
					south = index + 3
					if (south < 10):
						doorOp = html.OPTION("Open door between rooms " + str(index) + " and " + str(south))
						aFollowUpSelect <= doorOp
				if side == 'E':
					east = index + 1
					if (east % 3 is not 1):
						doorOp = html.OPTION("Open door between rooms " + str(index) + " and " + str(east))
						aFollowUpSelect <= doorOp					
		'''
		for index, room in enumerate(state["Rooms"]):
			for wall in ['N', 'S', 'E', 'W']:
				doorOp = html.OPTION("Open door in room " + str(index + 1) + " on " + wall + " wall.")
				aFollowUpSelect <= doorOp
		'''		
		'''
		for index, room in enumerate(state["Rooms"]):
			for wall in room.walls.values():
				if wall.hasDoor:
					doorOp = html.OPTION("Open door in room " + str(index + 1) + " on " + wall.loc + " wall.")
					aFollowUpSelect <= doorOp
		'''
		aFollowUp <= aFollowUpSelect
		actionForm <= aFollowUp
		
	elif(action == "Close Door"):
		aFollowUp <= "Pick a door:"
		
		doorOp = html.OPTION("Nothing Selected")
		aFollowUpSelect <= doorOp

		for index in range(1, 10):
			for side in ['S', 'E']:
				if side == 'S':
					south = index + 3
					if (south < 10):
						doorOp = html.OPTION("Close door between rooms " + str(index) + " and " + str(south))
						aFollowUpSelect <= doorOp
				if side == 'E':
					east = index + 1
					if (east % 3 is not 1):
						doorOp = html.OPTION("Close door between rooms " + str(index) + " and " + str(east))
						aFollowUpSelect <= doorOp					
		'''
		for index, room in enumerate(state["Rooms"]):
			for wall in room.walls.values():
				if wall.hasDoor:
					doorOp = html.OPTION("Close Door in room " + str(index + 1) + " on " + wall.loc + " wall.")
					aFollowUpSelect <= doorOp
		'''			
		aFollowUp <= aFollowUpSelect
		actionForm <= aFollowUp
		
	elif(action == "Play Sound"):
		aFollowUp <= "Sound Link:"
		textInput = html.INPUT(type="text", id="textInput", style = {"margin-left" : "10px"})
		aFollowUp <= textInput
		actionForm <= aFollowUp
		
	elif(action == "Display Message"):
		aFollowUp <= "Enter your message:"
		textInput = html.INPUT(type="text", id="textInput", style = {"margin-left" : "10px"})
		aFollowUp <= textInput
		actionForm <= aFollowUp
		
	elif(action == "Unsolve Puzzle"):
	
		aFollowUp <= "Pick a puzzle:"			
		puzzleOp = html.OPTION("Nothing Selected")
		aFollowUpSelect <= puzzleOp
			
		# Puzzles are gathered by searching rooms that have been placed
		# so the rules designer has context for which puzzles to attach conditions too
		for index, room in enumerate(state["Rooms"]):
			for wall in room.walls.values():
				#if wall.puzzle is not None:
				puzzleOp = html.OPTION("Unsolve puzzle in room " + str(index + 1) + " on " + wall.loc + " wall.")
				aFollowUpSelect <= puzzleOp
				
		aFollowUp <= aFollowUpSelect
		actionForm <= aFollowUp		
		
	elif(action == "Gain Points"):
		aFollowUp <= "Gain how many points?"
		textInput = html.INPUT(type="text", id="textInput", style = {"margin-left" : "10px"})
		aFollowUp <= textInput
		actionForm <= aFollowUp
		
	elif(action == "Lose Points"):
		aFollowUp <= "Lose how many points?"
		textInput = html.INPUT(type="text", id="textInput", style = {"margin-left" : "10px"})
		aFollowUp <= textInput
		actionForm <= aFollowUp
	else:
		pass #console.log("Debug: No Action Follow Up expected")	
Example #46
0
from browser import document, window
from math import *

graph = window.JXG.JSXGraph

document.getElementById("graph-container").innerHTML = '<div id="box" class="jxgbox"></div>'
div = document.getElementById("box")

div.style.width  = "400px"
div.style.height = "400px"

board = graph.initBoard("box", {"axis":True,"grid":True})

A = board.create('point',[1,1],{"name": 'Alice'})
B = board.create('point',[2,2],{"name":'Bob'})

f = board.create('functiongraph',[lambda x,unused: A.X() * sin(x)])
Example #47
0
from browser import document

# Hint: The magic number GUID is the id for the pre element used for printer output.
pre = document.getElementById('a5f435e0-c92e-11e2-8b8b-0800200c9a66')
pre.innerHTML = '''
<h1>Hello!</h1>
'''
def hide_loading():
	hide_overlay()
	loadingDiv = document.getElementById("loadingDiv")
	loadingDiv.style.display = "none"
def hide_overlay():
	blackOverlay = document.getElementById("blackOverlay")
	blackOverlay.style.display = "none"
Example #50
0
    ['Carcase meat'      ,  245,  227,  242,  267],
    ['Other meat'        ,  685,  803,  750,  586],
    ['Fish'              ,  147,  160,  122,   93],
    ['Fats and oils'     ,  193,  235,  184,  209],
    ['Sugars'            ,  156,  175,  147,  139],
    ['Fresh potatoes'    ,  720,  874,  566, 1033],
    ['Fresh Veg'         ,  253,  265,  171,  143],
    ['Other Veg'         ,  488,  570,  418,  355],
    ['Processed potatoes',  198,  203,  220,  187],
    ['Processed Veg'     ,  360,  365,  337,  334],
    ['Fresh fruit'       , 1102, 1137,  957,  674],
    ['Cereals'           , 1472, 1582, 1462, 1494],
    ['Beverages'         ,   57,   73,   53,   47],
    ['Soft drinks'       , 1374, 1256, 1572, 1506],
    ['Alcoholic drinks'  ,  375,  475,  458,  135],
    ['Confectionery'     ,   54,   64,   62,   41]
 ]

container = document.getElementById('example')
hot = JSConstructor(window.Handsontable)(container, { 'data': defra})

my_mat = [row[1:] for row in defra[1:]]

print(my_mat)
A1 = my_mat
for i in range(2):
    print()
    Q, R = eigen.decompose_QR(A1)
    A1 = mat.mult(R, Q)
    print(A1)
Example #51
0
from browser import document, window
from math import *

graph = window.JXG.JSXGraph

document.getElementById("graph-container").innerHTML = '<link rel="stylesheet" type="text/css" href="http://jsxgraph.uni-bayreuth.de/distrib/jsxgraph.css" /><div id="box" class="jxgbox"></div>'
div = document.getElementById("box")

div.style.width  = "400px"
div.style.height = "400px"

b = graph.initBoard("box", {"boundingbox":[-10,10,20,-10],"axis":True})

p = b.create('point',[1,4])
dataX = [1,2,3,4,5,6,7,8]
dataY = [0.3,4.0,-1,2.3,7,9,8,9]

b.create('curve',[dataX,dataY],{"strokeColor":'red'})
b.create('curve',[dataX,lambda x,unused: p.X()*sin(x)*x],{"strokeColor":'blue',"dash":1})
def allowPlay():
	playButton = document.getElementById("playButton")
	playButton.disabled = False
def show_loading():
	show_overlay()
	loadingDiv = document.getElementById("loadingDiv")
	loadingDiv.style.display = "initial"
Example #54
0
	touch = event.touches[0]
	x = int(touch.pageX)
	y = int(touch.pageY)
	event.preventDefault()
	shapeRenderer.drawEnd(x, y, context)
	inkManager.endInkCapture()
	
def getAPIKeys():
	inFile = open("config.txt")
	appKey, hmacKey = [line.strip() for line in inFile.readlines()][:2]
	inFile.close()
	return appKey, hmacKey

if __name__ == "__main__":
	pixelRatio = window.devicePixelRatio
	canvas = document.getElementById("canvas")
	context = canvas.getContext("2d")
	canvas.width = window.innerWidth * pixelRatio
	canvas.height = window.innerHeight * pixelRatio
	alert([window.innerWidth, window.innerHeight])
	pointerId = 0
	instanceId = 0
	appKey, hmacKey = getAPIKeys()
	
	MyScript = window.MyScript
	inkManager = JSConstructor(MyScript.InkManager)()
	shapeRenderer = JSConstructor(MyScript.ShapeRenderer)()
	shapeRecognizer = JSConstructor(MyScript.ShapeRecognizer)()
	resetScribble()
	
	document.bind("touchstart", disableScrolling)
	def numbersOnly(ev):
			input = document.getElementById("textInput")
			text = input.value
			input.value = re.sub(r'\D',"",text)
Example #56
0
from browser import timer, html, document

buffer_canvas = document.getElementById("buffer")
buffer_screen = buffer_canvas.getContext('2d')

class Surface(object):
    def __init__(self, size, flags=0,
                 masks=None, screen=False,
                 ratio_x=1, ratio_y=1, canvas=None, img=None):
        self.width = size[0] * ratio_x
        self.height = size[1] * ratio_y
        self.ratio_x = ratio_x
        self.ratio_y = ratio_y
        self.size = size
        self.flags = flags
        self.masks = masks
        self.screen = screen
        self.canvas = canvas
        self.img = img
        self.img_buffer = None

    def blit(self, source, dest, area=None, special_flags=0):
        if self.screen:
            if not source.img_buffer:
                if self.ratio_x != 1 or self.ratio_y != 1:
                    buffer_canvas.width = source.img.width * self.ratio_x
                    buffer_canvas.height = source.img.height * self.ratio_y
                else:
                    buffer_canvas.width = self.canvas.width
                    buffer_canvas.height = self.canvas.height
def cFollowUp(state):
	cFollowUp = document.getElementById("cFollowUp")
	
	if (cFollowUp is not None):
		cFollowUp.parentNode.removeChild(cFollowUp)

	cFollowUp = html.DIV(id="cFollowUp", style = {"margin" : '10px'})
	
	conditionForm = document.getElementById("conditionForm")
	
	condition = document.getElementById("conditionSelect").value
	cFollowUpSelect = html.SELECT(id = "cFollowUpSelect", style = {"margin-left" : "10px"})	
	
	def numbersOnly(ev):
			input = document.getElementById("textInput")
			text = input.value
			input.value = re.sub(r'\D',"",text)
			
	if(condition == "Entered Room"):
		cFollowUp <= "Pick a room:"
		for num in range(1,10):
			roomNum = html.OPTION("Entered Room " + str(num))
			cFollowUpSelect <= roomNum

		cFollowUp <= cFollowUpSelect
		conditionForm <= cFollowUp
		
	elif(condition == "Solved Puzzle"):
	
		cFollowUp <= "Pick a puzzle:"			
		puzzleOp = html.OPTION("Nothing Selected")
		cFollowUpSelect <= puzzleOp
		
		'''
		allPuzzles = []
		# Add puzzles to list
		for puzzleName in state["Image_Puzzles"]:
			allPuzzles.append(puzzleName)
	
		for puzzleName in state["Music_Puzzles"]:
			allPuzzles.append(puzzleName)
			
		#Changed to no longer care where a puzzle is located		
		for index, puzzle in enumerate(allPuzzles):
			puzzleOp = html.OPTION("Solve Puzzle " + str(index) + " : " + str(puzzle))
			cFollowUpSelect <= puzzleOp
		'''
			
		# Puzzles are gathered by searching rooms that have been placed
		# so the rules designer has context for which puzzles to attach conditions too
		for index, room in enumerate(state["Rooms"]):
			for wall in room.walls.values():
				#if wall.puzzle is not None:
				puzzleOp = html.OPTION("Solved puzzle in room " + str(index + 1) + " on " + wall.loc + " wall.")
				cFollowUpSelect <= puzzleOp
				
		cFollowUp <= cFollowUpSelect
		conditionForm <= cFollowUp
		
	elif(condition == "Had Points"):
		
	
		cFollowUp <= "Enter point amount:"
		textInput = html.INPUT(type="text", id="textInput", name = "hasAPattern", style = {"margin-left" : "10px"})
	
		textInput.bind('keyup',validInput)
		
		cFollowUp <= textInput
		conditionForm <= cFollowUp
		
	elif(condition == "Time Elapsed"):
		
		cFollowUp <= "Enter time in minutes:"
		textInput = html.INPUT(type="text", id="textInput", style = {"margin-left" : "10px"})
		
		textInput.bind('keyup',validInput)
		
		cFollowUp <= textInput
		conditionForm <= cFollowUp
		
	else:
		pass #console.log("Debug: No Condition Follow Up expected")	
def show_overlay():
	blackOverlay = document.getElementById("blackOverlay")
	blackOverlay.style.display = "initial"
Example #59
0
x = A(True)
assert x.mybool is True
x.mybool = False
assert x.mybool is False

y = A(False)
assert y.mybool == False

# test setting a callback function
f_called = False
def f(*args, **kwargs):
    global f_called
    f_called = True

element = document.getElementById('dom-test-element-id')
# test passing an additional argument after the callback f
element.addEventListener('click', f, True)
element.click()
assert f_called

# issue 829
# HTML attributes are case-insensitive
class A(html.DIV):
    def __init__(self):
        self.uV = 5
        self.Xyz = "mystring"
        self.zd = {"a": 3}

p = A()
assert not hasattr(p, "XYZ")
Example #60
0
 def animate(self, stepcallback):
    self._renderer.render(self._stage)
    self._w.requestAnimationFrame(stepcallback)
    consoleText2 = document.getElementById("console").value
    self._w.document.getElementById("textarea").value = consoleText2