示例#1
0
def start(event):
    "get quantity of points and clusters"
    global nval, nclus
    nclus = int(document["numclusters"].value)
    nval = int(document["numvalues"].value)
    if nval + 1 < nclus:
        "an additional value will come later on"
        alert("Please provide sufficient values to cluster.")
        nval = -1  # marks lack of valid input yet
        nclus = 0
        document["numclusters"].value = ""
        document["numvalues"].value = ""
        return
    if nclus < 2:
        alert("Please request a nontrivial clustering.")
        nval = -1  # marks lack of valid input yet
        nclus = 0
        document["numclusters"].value = ""
        document["numvalues"].value = ""
        return
    document["numclusters"].disabled = True
    document["numvalues"].disabled = True
    document['value'].disabled = False
    document['value'].placeholder = "Please input value " + str(
        i) + " and submit it"
    document['submitbutton'].disabled = False
示例#2
0
def play_ai(ev):
    alert(ev.target.id)
    global t
    t = Test("human", ev.target.id, 1)
    t.run()
    updateBoard()
    return 1
	def destroyAndSendBack():
		conditionName = conditionSelect.value
		if(conditionName == "None Selected"):
			alert("Select a condition to delete")
		else:
			destroy_menu("deleteConditionMenu")
			sendBack(conditionName)
	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 destroyAndSendBack():
		actionName = actionSelect.value
		if(actionName == "None Selected"):
			alert("Select an action to delete")
		else:
			destroy_menu("deleteActionMenu")
			sendBack(actionName)
示例#6
0
文件: script.py 项目: wartytoad/lbtc
def show_values(event):
    N = int(document["input1"].value)
    k = int(document["input2"].value)
    select = document["select"]
    long_display = bool(select.options[select.selectedIndex].value)
    output = run(N, k, long_display)
    alert(output)
示例#7
0
 def onClick(self, event):
     if currentuser is None:
         alert(
             "In order to save or open files, you need to log in.\nPlease click the login button."
         )
     else:
         fileopendialog.open("./users/" + currentuser)
示例#8
0
文件: script2.py 项目: wartytoad/lbtc
def show_values(event):
    N = document["input1"].value
    k = document["input2"].value
    select = document["select"]
    long_display = select.options[select.selectedIndex].value
    output = run(N, k, long_display)
    alert(output)
示例#9
0
 def oncomplete(request):
     global currentuser
     response = request.text.strip()
     if response == "OK":
         currentuser = username
         if self.returnaction: self.returnaction(username)
         alert("Username created.  You are now logged in.")
示例#10
0
 def handler(ev):
     card_number = document[node].value
     if card_number:
         if is_valid_cc(card_number):
             alert("Card is valid!!")
         else:
             alert("Card is NOT valid!!")
示例#11
0
def save_configuration(filename):
    try:
        with open(filename, "w") as fileout:
            global configuration
            fileout.write(json.dump(configuration))
    except Exception as e:
        alert("Error occured: " + str(e))
示例#12
0
 def oncomplete(request):
     response = request.text.strip()
     if response == "True":
         alert("Sorry - this username is already in use.")
     else:
         self.hide()
         self.createusername(username)
示例#13
0
def agregar(evt):
	ultimo=0
	global componentes

	data={"boxes":[]}
	l=[]
	for elem in s(".tab")[0].children:
	    if len(elem.children)>0:
	      widget=elem.children[0]
	      tipo=widget.get(selector="select[name=tipo]")[0].value
	      name=widget.get(selector="input[name=name]")[0].value
	      valor=widget.get(selector="input[name=value]")[0].value
	      titulo=widget.get(selector="input[name=titulo]")[0].value
	      opcion=widget.get(selector="select[name=opcion]")[0].value
	      tabla=widget.get(selector="select[name=tabla]")[0].value
	      depende=widget.get(selector="select[name=depende]")[0].value
	      campo={titulo:tipo,"name":name,"value":valor}
	      if opcion!="":
	      	campo["opcion"]=opcion
	      if tabla!="":
	      	campo["tabla"]=tabla
	      if depende!="":
	      	campo["depende"]=depende
	      l.append(campo)

	data["boxes"].append(l)
	for k,elem in enumerate(s(".custom-section").iterables):
	  if len(elem.children)==0:
	   if ultimo==None:
	    	ultimo=k
	  else:
	   	ultimo=None
	alert(componentes["widget-campo-boxes"].run(data))
	if componentes["widget-campo-boxes"]!=None and ultimo!=None:    
   		s(".custom-section")[ultimo].innerHTML=componentes["widget-campo-boxes"].run(data)
def create_image_puzzle(state):
	# Prompt the user for a image url
	url = window.prompt("Enter a complete URL for a picture. Say 'cancel' to cancel.", "images/force.jpg")
	if(url is None):
	
		return None
		
	elif(url_is_valid(url)):
	
		
		newState = copy_state(state)
		
		# Get name, make sure there are no copies
		name = getName(url)
		name = check_puzzle_name(state,name)
	
		newPuzzle = ImagePuzzle(url)
		
		# Add newPuzzle to dictionary
		newState["Image_Puzzles"][name] = newPuzzle
		newState["Selected_Image"] = name

		return newState
		
	else:
	
		alert("URL was not valid. Try again.")
		# Recurse
		return create_image_puzzle(state)	
示例#15
0
def get_type(e):
    global tree
    global treeType
    if e.target.value == 'avl':
        tree = avl.Tree()
        del document['nav']
        n = create_nav()
        document['container'] <= n
        document['container'] <= html.DIV(id='output')
        document['container'] <= html.DIV(id='tree')
        document['h1'].text = 'AVL tree'
        treeType = 'AVL'
    elif e.target.value == 'bst':
        tree = bst.Tree()
        del document['nav']
        n = create_nav()
        n <= html.BUTTON('DSW', id='dsw-btn', Class='btn')
        document['container'] <= n
        document['container'] <= html.DIV(id='output')
        document['container'] <= html.DIV(id='tree')
        document['dsw-btn'].bind('click', dsw_event)
        document['h1'].text = 'BST tree'
        treeType = 'BST'
    else:
        alert("Something went wrong. Please refresh this page.")
    document['insert-btn'].bind('click', insert_event)
    document['delete-btn'].bind('click', delete_event)
    document['min-btn'].bind('click', min_event)
    document['max-btn'].bind('click', max_event)
    document['inorder-btn'].bind('click', inorder_event)
    document['preorder-btn'].bind('click', preorder_event)
    document['postorder-btn'].bind('click', postorder_event)
示例#16
0
def onEnter(evt):
    if evt.keyCode == 13:
        evt.preventDefault()
        if entrada.value != "":
            exibirNumeros()
        else:
            alert("Entrada vazia")
示例#17
0
def generate_command(e):
    for pos in state:
        if state[pos]:
            started = True
            break
    else:
        started = False
    rack = document["rack-letters"].value
    if not started and len(rack) != 7:
        alert("Must have 7 tiles in rack since board is empty")
        return
    elif not started:
        call_god(f"start {rack}")
    else:
        command = f"help {rack} "
        for i in range(SIZE):
            for j in range(SIZE):
                if not state[(i, j)]:
                    c = '0'
                elif state[(i, j)][0] == '?':
                    c = str.lower(state[(i, j)][-1])
                else:
                    c = state[(i, j)]
                command += f"{c}"
        call_god(command)
示例#18
0
def do_play():
    src = window.getCode()
    try:
        success = True
        try:
            # try and run the code in the web worker!!!!
            graphics_main.start(src)
            #myWorker.send(["run", src])
            #pynode_graphlib._exec_code(src)
        except Exception as exc:
            alert("Error!")
            traceback.print_exc(file=sys.stderr)
            handle_exception()
            success = False
        clear_button_run()
        document["runPause"].style.display = "inherit"
        document["run"].bind("click", button_pause)
        if success:
            #graphics.run()
            play_events()
        else:
            end_playing()
        sys.exit()
    except:
        pass
示例#19
0
def load_state(e):
    global state, current
    value = document["status-text"].value
    buffer_state = dict()
    if len(value) != SIZE**2:
         alert(f"Format error: State input must have exactly {SIZE**2} characters. {len(value)} characters found.")
         return
    for n in range(SIZE**2):
        if not str.isalpha(value[n]) and value[n] != '0':
            alert("Format error: State input is not correctly formatted (only letters and digit 0 are allowed)")
            return
        i, j = n // SIZE, n % SIZE
        if value[n] == '0':
            buffer_state[(i, j)] = None
        else:
            buffer_state[(i, j)] = value[n]
    if current:
        unmake_current()
    state = buffer_state
    for pos in state:
        letter = state[pos]
        if not letter:
            img_path = None
        elif str.isupper(letter):
            img_path = f"tiles/{letter}.jpg"
        else:
            img_path = f"tiles/blanks/{str.upper(letter)}.jpg"
        set_square_bg_img(pos, img_path)
示例#20
0
def main(i):
    def animate(i):
        global id
        id = raf(animate)
        draw()

    def draw():
        Game.context.clearRect(0, 0, Game.canvas.width, Game.canvas.height)
        lvl.draw()
        Mob.update('Puce')
        player.update()
        Mob.draw('Puce')
        player.draw()

    global p
    p.style = {'display': "none"}

    Game.canvas = html.CANVAS(width=SET.WINDOW_SIZE[0], height=SET.WINDOW_SIZE[1])
    mL = (doc.body.clientWidth - SET.WINDOW_SIZE[0]) / 2
    Game.canvas.style = {"border": "1px solid black", 'marginLeft': "{}px".format(mL)}
    Game.context = Game.canvas.getContext("2d")

    if not Game.canvas:
        alert("Can't access to the canvas")
    Game.context = Game.canvas.getContext('2d')
    if not Game.context:
        alert("Can't access to the canvas")
    lvl = Level()
    player = Player(lvl)
    doc.body.addEventListener("keydown", player.player_event)
    doc.body.addEventListener("keyup", player.player_event)

    animate(0)

    doc.body.append(Game.canvas)
示例#21
0
    def load(self, *args):
        if "kanban" in storage:
            txt = storage["kanban"]
            try:
                eval("kanban = " + txt)
            except BaseException as e:
                kanban = None

            try:
                if kanban is None:
                    raise KanbanException(
                        "could not load data from storage (use 'Save' to initialize it)."
                    )

                if kanban.schema_revision != self.kanban.schema_revision:
                    raise KanbanException(
                        "storage schema does not match application schema (use 'Save' to re-initialize it)"
                    )

                self.kanban = kanban

            except KanbanException as e:
                alert(e.msg)

            except:
                del storage["kanban"]

        self.draw()
示例#22
0
def gameloop():
    global cboard, redsturn, selectedtile, ai, whowon, glt

    if not redsturn and whowon != 'done':
        # has the game been won?
        whowon = getiswon(cboard)
        if whowon == NOWIN:
            # alert(getgapmoves(cboard, BLACK))
            move = getgaim(ai, cboard, BLACK)
            # alert(move)
            cboard = domakemove(cboard, move)
            # alert(getgapmoves(cboard, RED))
            # print board
            printboard(cboard)
            redsturn = True
            # has the game been won?
            whowon = getiswon(cboard)

    if whowon == REDWON:
        alert("Red won!")
        redsturn = False  # user can't move after a win
        whowon = 'done'  # stop the annoying alert
        timer.clearinterval(glt)
    elif whowon == BLACKWON:
        alert("Black won!")
        redsturn = False  # user can't move after a win
        whowon = 'done'  # stop the annoying alert
        timer.clearinterval(glt)
示例#23
0
 def stack_trace_dialog(self, title, message, content, retry=False):
     print('Not implemented. Show to info dialog')
     alert(title+'\n'+message)
     print('title:', title)
     print('message:', message)
     print('content:', content)
     return None
def handleApplyButtonClick(evt):
	# get selected operator.
	global Operators, opSelect, current_state, STATE_STACK
	global BACKTRACK_BUTTON, RESET_BUTTON

	# Get Operators
	i = opSelect.selectedIndex
	op = Operators[i]
	#sendBack = recieveNewState
	
	if (type(op) is Operator): # Get state straight from the operator
		new_state = op.state_transf(current_state)
		recieveNewState(new_state)
		
	elif (type(op) is AsyncOperator): #Pass it function to get new state

		try:	
			# Gives the state transfer function the new state.
			# receiveNewState that you see above
			# is the callback function called when 
			# op.state_transf finishes execution.
			op.state_transf(current_state,recieveNewState)
			
		except (Exception) as e:
			alert("An error occured when applying this operator. Error: "+str(e))		
	else:
		console.log("apples")
示例#25
0
    def load(self, *args):
        if "kanban" in storage:
            txt = storage["kanban"]
            try:
                eval("kanban = " + txt)
            except BaseException as e:
                kanban = None

            try:
                if kanban is None:
                    raise KanbanException("could not load data from storage "
                        "(use 'Save' to initialize it).")

                if kanban.schema_revision != self.kanban.schema_revision:
                    raise KanbanException("storage schema does not match "
                        "application schema (use 'Save' to re-initialize it)")

                self.kanban = kanban

            except KanbanException as e:
                alert(e.msg)

            except:
                del storage["kanban"]

        self.draw()
示例#26
0
def broker(op):
    if op[0] == "snapshot_start":
        document[
            'lblsnapshot_status'].innerHTML = "<strong> {}</strong>".format(
                "Calculating")
        document['lblsnapshot_holders'].innerHTML = " ?"
        document['lblsnapshot_balance'].innerHTML = " ?"
    elif op[0] == "snapshot_end":
        document[
            'lblsnapshot_holders'].innerHTML = "<strong> {}</strong>".format(
                op[3])
        document[
            'lblsnapshot_balance'].innerHTML = "<strong> {}</strong>".format(
                op[2])
        document[
            'lblsnapshot_costs'].innerHTML = "<strong> {}</strong>".format(
                op[4])
        document[
            'lblsnapshot_status'].innerHTML = "<strong> {}</strong>".format(
                "OK")
        document['btnsnapshot'].disabled = False
        document['btnlaunch'].disabled = False
    elif op[0] == "csv_exported":
        document['dcsv'].innerHTML = '<a href="{}">{}</a>'.format(
            op[2], "Top holders CSV")
    elif op[0] == "csv_data":
        table_summary(op[2:])
    elif op[0] == "launch_error":
        alert(op[1])
示例#27
0
文件: bmi.py 项目: ogawa-yu/DevHome
def calc_bmi():
    weight = float(document["weight"].value)
    height = float(document["height"].value)

    bmi = str(weight / height**2)
    result = document["result"]
    result.text = bmi
    alert(bmi)
def mySuccess(param1, param2):
	alert("hello")
	def regularSuccess(rec):
		console.log(rec.text)
		console.log(param1)
		console.log(param2)
		
	return regularSuccess	
示例#29
0
def load_configuration(filename):
    try:
        with open(filename, "r") as filein:
            global configuration, profile
            configuration = json.loads(filein.read())
            profile = configuration["selected_profile"]
    except Exception as e:
        alert("Error occured: " + str(e))
示例#30
0
文件: main.py 项目: kwarwp/henrietta
 def foi():
     historia, _ = self.historia.sai()
     palavras = len(historia.split())
     temas = "peix aqu conch templo".split()
     tema = sum(1 for palavra in temas if palavra in historia)
     pontos = palavras + 5 * tema
     alert("pontos: {}".format(pontos))
     if pontos > 10:
         INVENTARIO.bota(elemento)
示例#31
0
def createFunctionFromPython(string):
    try:
        exec(string + """
window.getPlayersCommands = getPlayersCommands""")
    except Exception as e:
        alert(e)
        return 1
    else:
        return 0
示例#32
0
 def conta_historia(*_):
     historia = input("Conte aqui a sua historia")
     palavras = len(historia.split())
     temas = "peix aqu conch templo".split()
     tema = sum(1 for palavra in temas if palavra in historia)
     pontos = palavras+ 5*tema
     alert("pontos: {}".format(pontos))
     if pontos > 10:
         INVENTARIO.bota(peixe)
示例#33
0
def dsw_event(e):
    global tree
    if treeType == 'AVL':
        alert("You cannot run DSW for AVL tree.")
        return
    tree.dsw(tree.root)
    result = tree.toDICT(tree.root)
    console.log(result)
    update_tree(tree.root)
示例#34
0
 def oncomplete(request):
     global currentuser
     response = request.text.strip()
     if response == "True":
         self.hide()
         currentuser = username
         if self.returnaction: self.returnaction(username)
     else:
         alert("Sorry - this username does not exist.")
示例#35
0
def compute_hash(evt):
    value = this().input_text
    if not value:
        alert("You need to enter a value")
        return
    hash_object = hashes[this().algo]()
    hash_object.update(value.encode())
    hex_value = hash_object.hexdigest()
    this().hash_value = hex_value
示例#36
0
文件: dashboard.py 项目: Enforcer/PAW
 def on_complete(req):
     response = loads(req.text)
     if response['success']:
         document['boardSelect'] <= OPTION(name, value=response['id'], **{'data-background': 1, 'data-star': 'false'})
         document['boardNameInput'].style.display = 'none'
         document['boardSelect'].style.display = ''
         updateAddBoardButtonState()
     else:
         alert(response['message'])
示例#37
0
文件: dashboard.py 项目: Enforcer/PAW
 def task_add_callback(req):
     if req.status == 201:
         new_task = loads(req.text)
         boards_id = new_task['board_list'].split('/')[-2]
         container = document['tasks_for_list_' + str(boards_id)]
         appendTask(new_task, container)
         event.target.value = ''
     else:
         alert('Dodanie zadania nie powiodło się')
 def export(self):
     result = "(storage %s\nmessages (%s)\nflags(%s))" % (
         self.storage.export(),
         (" ".join("(%s %s)" % (k, v.export())
                   for (k, v) in sorted(self.messages.items()))),
         (" ".join(str(flag) for flag in self.flags)))
     if self.verbose:
         alert("Creating\n\n%s" % result)
         window.console.log(result)
     return result
示例#39
0
def save_buffer():
    name = doc["save-name"].value
    if name == "":
        alert("Please type a name")
        return
    text = editor.getValue()
    saves = json.loads(storage["saves"])
    saves[name] = text
    storage["saves"] = json.dumps(saves)
    update_saves()
示例#40
0
文件: app.py 项目: pbandierapaiva/nut
	def complete(self,r):
		if r.status==200 or r.status==0:
			result = json.loads(r.text)
			if len(result)==0:
				alert("Nenhum alimento encontrado")
				self.sel.style.display = 'none'
				return
			self.sel.clear()
			for l in result:
				self.sel.style.display = 'block'
				self.sel.style.width='90pw'
				self.sel<=OPTION(l[1], value=l[0])
示例#41
0
def _open(ev):
    if not __BRYTHON__.has_websocket:
        alert("WebSocket is not supported by your browser")
        return
    global ws

    # open a web socket
    ws = websocket.WebSocket("ws://localhost:8765")

    ws.bind('open',on_open)
    ws.bind('message',on_message)
    ws.bind('close',on_close)
    ws.bind('error',on_error)
示例#42
0
文件: app.py 项目: pbandierapaiva/nut
	def completeFetch(self,r):
		if r.status==200 or r.status==0:
			result = json.loads(r.text)
			self.clear()
			if len(result)==0:
				alert("Nenhum nutriente encontrado")
				self.style.display = 'none'
				return
			for l in result:
				self.style.display = 'block'
				#self.sel.style.width='90pw'
				#self.sel<=OPTION(l[1], value=l[0])
				self<=TR(TD(l[0]) + TD(l[1]) + TD(l[2]))
示例#43
0
def echo(event): 
    N = 10000 
    a = 0 
    tm0 = time.time() 
    for i in range(0,N): 
        a += 1 
    tms = time.time() - tm0 
    ostr = " == %s %s %s == " % (document["zone"].value, tm0, tms) 
    #print 
    #print "ostr", ostr 
    #print 
    sys.stdout.write(ostr) 
    alert(ostr) 
    assert 0, "hhhhhhhhhhhhhh errrrrrrrr %s " % tms 
def find_applicable_op_indexes(OPERATORS, current_state):
  res = []
  for idx, op in enumerate(OPERATORS):
    try:
      pre = op.precond
    except:
      alert("No precondition for operator: "+str(op))
      return
    try:
      if pre(current_state):
      	res += [idx]
    except (Exception) as e:
      alert("Bad state or bad precondition with operator "+op.name+" and current state.")
  return res
def drawPuzzle(wall,type,x3,y3,x4,y4):
	global board
	
	# Caution: Sensitive variable, keep it around 1 for a good sized puzzle.
	PUZZLE_SIZE = 1.2
	# map (p)uzzle coords to wall coords before translation
	(px1,py1,px2,py2,px3,py3,px4,py4) = (wall.x1,wall.y1,wall.x2,wall.y2,x3,y3,x4,y4)
	
	# fit the (p)uzzle into a smaller trapezoid
	if (wall.loc == 'E' or wall.loc == 'W'):
		py1 += 1/PUZZLE_SIZE * (1/4)
		py2 -= 1/PUZZLE_SIZE * (1/4)
		py3 -= 1/PUZZLE_SIZE * (1/5)
		py4 += 1/PUZZLE_SIZE * (1/5)
		
		if(wall.loc == 'E'):
			tx = x4 + (1/2) * (wall.x1 - x4)
			ty = wall.y1 + (1/2) * (wall.y2 - wall.y1) + 0.06
		else:
			tx = wall.x1 + (1/2) * (x4 - wall.x1)
			ty = wall.y1 + (1/2) * (wall.y2 - wall.y1) + 0.06
	
	elif (wall.loc == 'N' or wall.loc == 'S'):
		px1 += 1/PUZZLE_SIZE * (1/4)
		px2 -= 1/PUZZLE_SIZE * (1/4)
		px3 -= 1/PUZZLE_SIZE * (1/5)
		px4 += 1/PUZZLE_SIZE * (1/5)
		
		if(wall.loc == 'N'):
			tx = wall.x1 + (1/2) * (wall.x2 - wall.x1)
			ty = wall.y1 + (1/2) * (y3 - wall.y1) + 0.06
		else:
			tx = wall.x1 + (1/2) * (wall.x2 - wall.x1)
			ty = y4 + (1/2) * (wall.y1 - y4) + 0.06
	else:
		alert("drawPuzzle wall location check broke")
	
	# puzzle index number from puzzle list
	number = getPuzzleIndex(wall.puzzle)
	
	# Create puzzle polygon
	fill = "green"	
	puzzleDiv = create_polygon(px1,py1,px2,py2,px3,py3,px4,py4, fill = fill)

	APANEL <= puzzleDiv
	
	if(number is not None):
		textSvg = create_text(number,tx,ty)
		APANEL <= textSvg
示例#46
0
文件: main.py 项目: labase/surdonews
    def ajuda(self):
        hint = "http://icons.iconarchive.com/icons/oxygen-icons.org/oxygen/256/Actions-help-hint-icon.png"
        flag = None

        # Ao clicar na dica
        def clicou(_):
            alert("Procure a sala do médico.\nO relatório está com ele.")

        # Se a dica não está no inventário
        if not "hint" in INVENTARIO.inventario:
            alert("Você quer saber o período de vacinação?\nEle está com o médico em sua sala.")
            INVENTARIO.bota("hint", hint, clicou)
        # Se ela estiver
        else:
            alert("Achou o relatorio? Não?\nVocê procurou na sala certa?")
示例#47
0
    def on_complete(cls, req):
        """
        Callback called when the request was received.
        """
        # handle http errors
        if not (req.status == 200 or req.status == 0):
            alert("Couldn't connect to authority base.")
            LogView.add(
                "Error when calling Aleph authority base: %s" % req.text
            )
            AuthorBar.hide()
            return

        AuthorBar.hide()
        cls.set_select(json.loads(req.text))
def playAmbientAudio(url, hold, callback = None):
	global Wad
	global aAudio
	global oldUrl
	if(url is not None):
		
		# Will play Ambient music for 10 minutes
		if(url != oldUrl):
			oldUrl = url
			aAudio = Wad({'source' : url, 'env' : {'hold' : hold}, 'callback' : callback})
		else:
			if(callback is not None):
				callback()
		aAudio.play()
	else:
		alert("no url provided")
示例#49
0
 def excInfos(self, test, err):
     tb = err[2]
     infos = []
     while tb:
         fname = tb.tb_frame.f_code.co_filename
         if fname == test.__class__.__module__:
             infos.append(tb.tb_lineno)
         tb = tb.tb_next
     try:
         str(err[1]).splitlines()
     except:
         alert(err[1])
         alert(type(err[1]))
     return [html.TD("line %s - %s: %s" %(infos[-1], 
         err[0].__name__, 
         str(err[1]).splitlines()[0]), Class="error_message")]
示例#50
0
文件: main.py 项目: labase/surdonews
    def pega_card(self):
        riocard = "https://www.cartaoriocard.com.br/rcc/static/img/personal-1.png"
        Card.passou = True
        flag = None

        def clicou(_):
            # hipótese de flag
            if INVENTARIO.cena == self or INVENTARIO.cena == self.metro:
                alert("Você precisa encostar o passe no leitor")
            else:
                alert("Você não está num meio de transporte.")

        if not "card" in INVENTARIO.inventario:
            alert("Você pega o seu RioCard")
            INVENTARIO.bota("card", riocard, clicou)
        else:
            alert("A gaveta está vazia")
def drawDoor(wall,x3,y3,x4,y4):

	# Caution: Sensitive variable, keep it around 2 for a good sized door.
	DOOR_SIZE = 1.2

	# map (f)rame coords to wall coords before translation
	(fx1,fy1,fx2,fy2,fx3,fy3,fx4,fy4) = (wall.x1,wall.y1,wall.x2,wall.y2,x3,y3,x4,y4)
	
	# fit the door (f)rame into a smaller trapezoid
	if (wall.loc == 'E' or wall.loc == 'W'):
		fy1 += 1/DOOR_SIZE * (3/8)
		fy2 -= 1/DOOR_SIZE * (3/8)
		fy3 -= 1/DOOR_SIZE * (4/15)
		fy4 += 1/DOOR_SIZE * (4/15)
		
	elif (wall.loc == 'N' or wall.loc == 'S'):
		fx1 += 1/DOOR_SIZE * (3/8)
		fx2 -= 1/DOOR_SIZE * (3/8)
		fx3 -= 1/DOOR_SIZE * (4/15)
		fx4 += 1/DOOR_SIZE * (4/15)
	else:
		alert("drawDoor wall location check broke")
	
	# Create frame and door polygons
	if(wall.doorOpen):
		frameDiv = create_polygon(fx1,fy1,fx2,fy2,fx3,fy3,fx4,fy4, fill = "rgb(190, 208, 221)")
	else:

		pattern = svg.pattern(id="door",height="100%",width = "100%")
		window.addAttribute(pattern,"patternContentUnits","objectBoundingBox")
		
		img = svg.image(xlink_href="images/door.jpg", x="0",y="0", height="1", width="1")
		window.addAttribute(img,"preserveAspectRatio","none")
		
		pattern <= img
		
		defs = svg.defs()
		defs <= pattern
		APANEL <= defs	
		
		frameDiv = create_polygon(fx1,fy1,fx2,fy2,fx3,fy3,fx4,fy4, fill = "url(#door)")

	
	# Append polygon to svg panel	
	APANEL <= frameDiv
示例#52
0
 def excInfos(self, test, err):
     tb = err[2]
     infos = []
     while tb:
         fname = tb.tb_frame.f_code.co_filename
         if fname == sys.modules[test.__class__.__module__].__file__:
             infos.append(tb.tb_lineno)
         tb = tb.tb_next
     infos = infos or ['<nc>']
     try:
         str(err[1]).splitlines()
     except:
         alert(err[1])
         alert(type(err[1]))
     lines = "\n".join(f"line {line}" for line in infos[:-1])
     return [html.TD(lines + "\nline %s - %s: %s" %(infos[-1],
         err[0].__name__,
         str(err[1]).splitlines()[0].replace('<', '&lt;')),
             Class="error_message")]
示例#53
0
文件: main.py 项目: labase/surdonews
    def pega_relat(self):
        relat = "http://www.ufjf.br/sri-sou-servidor-ufjf/files/2014/04/Very-Basic-Document-icon.jpg"
        flag = None

        def clicou(_):
            # Mostra o texto do relatório ao clicar no icone
            alert(
                "O SUS e o Ministério da Saúde promovem a Campanha Nacional de Vacinação contra a Gripe, que começa no dia 4 e vai até o dia 22 de maio " \
                "como o dia de mobilização nacional. Trabalhadores da área de saúde, presos e funcionários do sistema prisional também serão vacinados contra o vírus. ")

        if not "relat" in INVENTARIO.inventario:
            alert("Boa tarde. Sim, você quer o meu relatório.\nBom, aqui está.")
            alert("Você pegou o relatório!")
            # Inclui o relatório ao inventário e retira a dica
            INVENTARIO.bota("relat", relat, clicou)
            if "hint" in INVENTARIO.inventario:
                INVENTARIO.tira("hint")
        else:
            input("Você já pegou o meu relatório.\nTenha um bom dia.")
def create_music_puzzle(state, sendBack):
	
	url = window.prompt("Enter a complete URL for a json music file. Say 'cancel' to cancel.", "music/twinkleTwinkle.txt")
	
	if(url is not None):
		if(url_is_valid(url)):
			
			# Double nested to allow use of name parameter
			def requestSuccess(name):
				# When the request is recieved
				def requestSuccess2(req):
					if(req.status == 200 or req.status == 0):
						newState = copy_state(state)
						# Assign name to song using data from JSON object
						song = json.loads(req.responseText)
						newPuzzle = MusicPuzzle(song["notes"])
						newState["Music_Puzzles"][name] = newPuzzle
						newState["Selected_Music"] = name
						
						# Hide loading visualization
						hide_loading()
						
						sendBack(newState)
					else:
						print("request failure")
				return requestSuccess2
			
			# Show loading visualization
			show_loading()
			
			# Get name, make sure there are no copies
			name = getName(url)
			name = check_puzzle_name(state,name)
			
			request = ajax.ajax()
			request.open('GET',url,True)
			request.bind("complete",requestSuccess(name))
			request.send()
	
		else:
			alert("URL was not valid. Try again.")
			create_music_puzzle(state, sendBack)
	def done():
		for transform in puzzle.transformList:
			if (transform == "vertFlip"):
				canMan.vertFlip()
			elif (transform == "horizFlip"):
				canMan.horizFlip()
			elif (transform == "shuffleRows"):
				canMan.shuffleRows()
			elif (transform == "shuffleRowsInverse"):
				canMan.shuffleRowsInverse()
			elif (transform == "shuffleColumns"):
				canMan.shuffleColumns()
			elif (transform == "shuffleColumnsInverse"):
				canMan.shuffleColumnsInverse()
			elif (transform == "pixelCrossover"):
				canMan.pixelCrossover()
			elif (transform == "pixelCrossoverInverse"):
				canMan.pixelCrossoverInverse()
			else:
				alert("Not supported transform")
def remove_wall_object_from_room(state, side):
	room_num = state["Selected_Room"]
	rooms = state["Rooms"]
	wall = state["Rooms"][room_num].walls[side]
	if(wall.hasDoor):
		wall.hasDoor = False
		if side == 'N':
			wall = rooms[room_num - 3].walls['S']
		elif side == 'S':
			wall = rooms[room_num + 3].walls['N']
		elif side == 'E':
			wall = rooms[room_num + 1].walls['W']
		elif side == 'W':
			wall = rooms[room_num - 1].walls['E']
		wall.hasDoor = False
		check_rules(state)
	elif(wall.puzzle is not None):
		wall.puzzle = None
		check_rules(state)
	else:
		alert("no puzzle or door to remove")
def add_door_to_room(state, room_num, side, openOrClosed):
	ROOMS = state["Rooms"]
	
	ROOMS[room_num].walls[side].hasDoor = True
	ROOMS[room_num].walls[side].doorOpen = openOrClosed
	if side == 'N':
		ROOMS[room_num - 3].walls['S'].hasDoor = True
		ROOMS[room_num - 3].walls['S'].doorOpen = openOrClosed
	elif side == 'S':
		ROOMS[room_num + 3].walls['N'].hasDoor = True
		ROOMS[room_num + 3].walls['N'].doorOpen = openOrClosed
	elif side == 'E':
		ROOMS[room_num + 1].walls['W'].hasDoor = True
		ROOMS[room_num + 1].walls['W'].doorOpen = openOrClosed
	elif side == 'W':
		ROOMS[room_num - 1].walls['E'].hasDoor = True
		ROOMS[room_num - 1].walls['E'].doorOpen = openOrClosed
	else:
		alert("Error: Invalid direction passed to add_door")
	
	check_rules(state)
def handleApplyButtonClick(evt):
  # get selected operator.
  global OPSELECT, CURRENT_STATE, STATE_STACK
  global BACKTRACK_BUTTON, RESET_BUTTON
  i = OPSELECT.selectedIndex
  op = OPERATORS[i]
  try:
    new_state = op.state_transf(CURRENT_STATE)
    CURRENT_STATE = new_state
    render_state(CURRENT_STATE)
    STATE_STACK.append(new_state) # Push.
    BACKTRACK_BUTTON.disabled = False
    RESET_BUTTON.disabled = False
    if GOAL_TEST(CURRENT_STATE):
      # If the current state is a goal state, issue a message.
      # The message may be provided by the template.
      # Otherwise, we use a default message.
      global statusline
      if 'GOAL_MESSAGE_FUNCTION' in globals():
        mes = GOAL_MESSAGE_FUNCTION(CURRENT_STATE)
        statusline.text = mes
        alert(mes)
      else:
        mes = "Congratulations! You have reached a goal state."
        statusline.text = mes
        alert("You have achieved a goal state!")
    else:
      statusline.text = "Solving is in progress."
    repopulate_operator_choices(find_applicable_op_indexes(OPERATORS, CURRENT_STATE))
  except (Exception) as e:
    alert("An error occured when applying this operator. Error: "+str(e))
def add_wallpaper_to_room(state):
	
	# Prompt the user for wallpaper url 
	url = window.prompt("Enter a complete URL for a wallpaper. Say 'cancel' to cancel.", "images/wall.jpg")
	if(url is None):
	
		return None
		
	elif(url_is_valid(url)):
	
		newState = copy_state(state)
		room = newState["Rooms"][newState["Selected_Room"]]
		for loc in room.walls:
			room.walls[loc].wallpaperurl = url
		
		return newState
		
	else:
	
		alert("URL was not valid. Try again.")
		
		# Recurse
		return add_wallpaper_to_room(state)
示例#60
0
    def get(cls):
        """
        Get code selected by user.

        Returns:
            str: Code or None in case that user didn't selected anything yet.
        """
        if cls.is_twoconspect:
            return cls.subconspect_el.value or None

        input_value = cls.input_el.value.strip()

        # blank user input -> no value was yet set
        if not input_value:
            return None

        mdt = conspectus.mdt_by_name.get(input_value)

        if not mdt:
            alert("Invalid sub-conspect `%s`!" % input_value)
            return None

        return mdt