def __init__(self, timer, base, rule, state1, state2, state3, instruments, limit):
        pygame.init()
        pygame.display.set_caption('Automata')
        self.surface = pygame.display.set_mode((c.WIDTH, c.HEIGHT))
        self.surface.fill(c.BLACK)        

        self.grid = Grid(20, 20, 40, 10, 15, 15)
        self.grid2 = Grid(300, 20, 40, 10, 15, 15)
        self.grid3 = Grid(580, 20, 40, 10, 15, 15)

        self.instruments = instruments

        self.clock = pygame.time.Clock()
        self.timer = timer
        self.repaint_evt = pygame.USEREVENT + 1
        self.sound_evt = pygame.USEREVENT + 2
        self.automata1 = Automata(rule, base, limit, state1)
        self.automata2 = Automata(rule, base, limit, state2)
        self.automata3 = Automata(rule, base, limit, state3)
        self.iterator = 0
        self.iterator2 = 14
        self.iterator3 = 28
        self.j = 0

        pygame.time.set_timer(self.repaint_evt, timer)
        pygame.time.set_timer(self.sound_evt, timer+2)
Esempio n. 2
0
def thompson_concatenate(aut1, aut2):

    if type(aut1) == Automata:
        str1 = aut1.name
        auto1 = aut1
    else:
        str1 = aut1
        auto1 = str2auto(aut1)

    if type(aut2) == Automata:
        str2 = aut2.name
        auto2 = aut2
    else:
        str2 = aut2
        auto2 = str2auto(aut2)

    if debug:
        auto1.display()
        auto2.display()

    auto3 = Automata('(' + str1 + str2 + ')')
    auto3.set_initial_state(auto1.initial_state)
    auto3.set_final_state(auto1.final_state + auto2.final_state - 1)

    for node in auto1.node_list:
        if node.label != auto1.final_state:
            auto3.node_list.append(node)

    for node in auto2.node_list:
        new_node = Anode(node.label + int(auto1.final_state - 1))
        for dest, label in node.connections.items():
            new_node.add_connection(dest + int(auto1.final_state) - 1, label)
        auto3.node_list.append(new_node)

    return auto3
Esempio n. 3
0
def thompson_positive_closure(aut1):
    if type(aut1) == Automata:
        str1 = aut1.name
        auto1 = aut1
    else:
        str1 = aut1
        auto1 = str2auto(aut1)

    if debug:
        auto1.display()

    auto3 = Automata('(' + str1 + '+)')

    auto3.add_node(1)
    auto3.add_node(auto1.final_state + 2)

    auto3.set_initial_state(1)
    auto3.set_final_state(auto1.final_state + 2)

    for node in auto1.node_list:
        new_node = Anode(node.label + 1)
        for dest, label in node.connections.items():
            new_node.add_connection(dest + 1, label)
        if node.label == auto1.final_state:
            new_node.add_connection(2, 'eps')
            new_node.add_connection(auto3.final_state, 'eps')
        auto3.node_list.append(new_node)

    auto3.add_connection(1, 2, 'eps')

    return auto3
Esempio n. 4
0
def main():
    challenge = get_json('/automatabot/challenges/new')
    print_response(challenge)

    print(
        post_json(challenge['challengePath'],
                  Automata(challenge['challenge']).solve()))
Esempio n. 5
0
def SeleniumMutationTrace(folderpath, dirname, config_fname, traces_fname,
                          trace_id, method_id, modes):
    logging.info(" loading config...")
    config = load_config(config_fname)
    config.set_folderpath(folderpath)
    config.set_dirname(dirname)
    config.set_mutation_trace(traces_fname, trace_id)
    config.set_mutation_method(method_id)
    config.set_mutation_modes(modes)

    logging.info(" setting executor...")
    executor = SeleniumExecutor(config.get_browserID(), config.get_url())

    logging.info(" setting crawler...")
    automata = Automata()
    databank = MysqlDataBank("localhost", "jeff", "zj4bj3jo37788", "test")
    crawler = SeleniumCrawler(config, executor, automata, databank)

    logging.info(" crawler start run...")
    crawler.run_mutant()

    logging.info(" end! save automata...")
    automata.save_traces(config)
    automata.save_automata(config)
    Visualizer.generate_html(
        'web',
        os.path.join(config.get_path('root'), config.get_automata_fname()))
Esempio n. 6
0
def main():
    # one = angleClockwise((370.0, 90.0), (130.0, 90.0))
    # two = angleClockwise((50.0, 90.0), (130.0, 90.0))
    # print(one, two)
    # get data from file
    with open(FILEPATH) as f:
        data = f.readline()

    # pass data Automata
    aut = Automata(data)
    aut.print()

    # set up Tk root and frame
    root = Tk()
    root.geometry(str(WIDTH) + "x" + str(HEIGHT) + "+10+10")
    frame = Frame(width=FRAME_WIDTH, height=FRAME_HEIGHT, padx=PAD, pady=PAD)
    frame.pack(fill=BOTH, expand=1)

    # create automata canvas with Automata and Frame
    AutomataCanvas(frame=frame,
                   automata=aut,
                   width=FRAME_WIDTH,
                   height=FRAME_HEIGHT)

    # start Tk
    root.mainloop()
Esempio n. 7
0
def debugTestMain(folderpath, dirname):
    logging.info(" setting config...")
    config = SeleniumConfiguration(Browser.FireFox, "http://140.112.42.145:2000/demo/nothing/main.html")
    config.set_max_depth(1)
    config.set_max_length(5)
    config.set_trace_amount(1)
    config.set_max_states(100)
    config.set_folderpath(folderpath)
    config.set_dirname(dirname)
    config.set_automata_fname('automata.json')
    config.set_traces_fname('traces.json')
    config.set_frame_tags(['iframe'])
    config.set_dom_inside_iframe(True)
    config.set_simple_clickable_tags()
    config.set_simple_inputs_tags()
    config.set_simple_normalizers()

    logging.info(" setting executor...")
    executor = SeleniumExecutor(config.get_browserID(), config.get_url())

    logging.info(" setting crawler...")
    automata = Automata(config)
    databank = InlineDataBank("140.112.42.145:2000", "jeff", "zj4bj3jo37788", "test")
    algorithm = MonkeyCrawler() #DFScrawler()
    crawler = SeleniumCrawler(config, executor, automata, databank, algorithm)

    logging.info(" crawler start run...")
    crawler.run_algorithm()

    logging.info(" end! save automata...")
    algorithm.save_traces()
    automata.save_automata(config.get_automata_fname())
    Visualizer.generate_html('web', os.path.join(config.get_path('root'), config.get_automata_fname()))
    config.save_config('config.json')
Esempio n. 8
0
def SeleniumMain(web_submit_id, folderpath=None, dirname=None):
    logging.info(" connect to mysql")
    print("connect to sql")
    databank = MysqlDataBank("localhost", "root", "", "test")
    url, deep, time = databank.get_websubmit(web_submit_id)

    logging.info(" setting config...")
    print(" setting config...")

    config = SeleniumConfiguration(Browser.PhantomJS, url, folderpath, dirname)
    config.set_max_depth(deep)
    config.set_max_time(int(time)*60)
    config.set_simple_clickable_tags()
    config.set_simple_inputs_tags()
    config.set_simple_normalizers()
    config.set_frame_tags(['iframe'])
    
    logging.info(" setting executor...")
    executor = SeleniumExecutor(config.get_browserID(), config.get_url())
    
    logging.info(" setting crawler...")
    automata = Automata()
    crawler = SeleniumCrawler(config, executor, automata, databank)
    
    logging.info(" crawler start run...")
    automata = crawler.run()
    crawler.close()
    
    logging.info(" end! save automata...")
    automata.save_automata(config)
    automata.save_traces(config)
    Visualizer.generate_html('web', os.path.join(config.get_path('root'), config.get_automata_fname()))
    config.save_config('config.json')
Esempio n. 9
0
def reachable(nfa):
    possible = []
    possible.append(nfa.start[0])
    next_state = []
    next_state.append(nfa.start[0])
    while not next_state == []:
        this_node = next_state[0]
        next_state.remove(this_node)
        for alpha in nfa.alphabet:
            for s in nfa.nodes[this_node].getTransitionState(alpha):
                if s not in possible:
                    possible.append(s)
                    if s not in next_state: next_state.append(s)
    possible.sort()
    new_accept = []
    for s in nfa.accepts:
        if s in possible: new_accept.append(s)
    new_transitions = []
    for x in nfa.transitions:
        if x[0] in possible and x[2] in possible: new_transitions.append(x)
    #print "all states: ",possible
    #print "stating point",nfa.start
    #print new_accept
    #for x in new_transitions: print x
    return Automata(possible, nfa.start, new_accept, new_transitions,
                    nfa.alphabet)
Esempio n. 10
0
    def setUp(self):
        dom1 = '''
            <!DOCTYPE html>
            <html lang="en">
            <head> <meta charset="UTF-8"> <title></title> </head>
            <body>dom1</body>
            </html>
        '''
        state = State(dom1)
        self.automata = Automata()
        self.automata.add_state(state)
        self.assertEqual(len(self.automata.get_states()), 1)
        self.assertEqual(self.automata.get_initial_state().get_id(), self.automata.get_current_state().get_id())
        self.assertEqual(self.automata.get_current_state().get_id(), '0')

        # test adding and removing inputs and forms
        form1 = FormField('form1')
        form1.add_input(InputField('username', '//*[@id="username"]', 'castman'))
        form1.add_input(InputField('password', '', 'p@ssw0rd'))
        form1.add_input(InputField('password', '', 'p@ssw0rd'))
        self.assertEqual(len(form1.get_inputs()), 2)
        form1.remove_input(InputField('username', '//*[@id="username"]', 'castman'))
        self.assertEqual(len(form1.get_inputs()), 1)

        form2 = FormField('', '//*[@id="lst-ib"]')
        clickable = Clickable('', '//*[@id="btn1"]')
        clickable.add_form(form1)
        clickable.add_form(FormField('form1'))
        clickable.add_form(form2)
        self.assertEqual(len(clickable.get_forms()), 2)
        clickable.remove_form(FormField('', '//*[@id="lst-ib"]'))
        self.assertEqual(len(clickable.get_forms()), 1)

        # add the clickable into state 0
        self.automata.get_current_state().add_clickable(clickable)
Esempio n. 11
0
def str2auto(aut1):
    auto1 = Automata(aut1)
    auto1.add_node(1)
    auto1.add_node(2)
    auto1.add_connection(1, 2, aut1)
    auto1.final_state = 2
    return auto1
Esempio n. 12
0
def read_automata(path):
    f = open(path, 'r')
    text = f.readlines()

    states = text[0].strip().strip('{}').split(",")
    alphabet = text[1].strip().strip('{}').split(",")
    initial = text[2].strip().strip('{}')
    final = text[3].strip().strip('{}').split(",")

    delta = []
    for line in text[4:]:
        line = line.replace("#", "").strip()
        s = line[0]
        for i in range(1, len(line), 2):
            [a, ns] = line[i:i + 2]
            if a == '&':
                a = 'λ'
            delta.append(((s, a), ns))

    automata = Automata(alphabet=alphabet,
                        states=states,
                        delta=delta,
                        initial=initial,
                        final=final)

    return automata
def ConstructAutomata(file):
    """Parses the supplied automata file, then constructs and returns an 
       Automata object.

       :param str | file file: File object or URI.
       :rtype: Automata
    """
    fa = FiniteAutomata.parseFile(file)
    # Alphabet check: if there are symbols in the transitions not in the
    # alphabet, throw an exception.
    for trans in fa.Transitions:
        for symbol in trans[1]:
            if symbol not in fa.Alphabet.asList():
                trans_str = trans[0] + ' \''\
                            + " \'".join(trans[1])\
                            + " --> " + trans[2]
                raise Exception("Alphabet Error! The transition:\n\n"\
                                + "    " + trans_str + "\n\n"\
                                + " contains the symbol \'" + symbol + "\' "\
                                + "which is not in the described alphabet!")

    # Note on fa.Start: parseResult objects always return values in lists,
    # so this must be dereferenced.
    return Automata(fa.States, fa.Start[0], fa.Accept, fa.Transitions,\
                    fa.Alphabet)
Esempio n. 14
0
def main():
    archivo = open("prueba.java", "r")
    linea = 1
    estados_aceptacion = ("c0", "c1", "c2", "c3", "c4")
    imprimir_error = False
    conteo_errores = 0
    for line in archivo.readlines():
        if ("0" in line or "1" in line or "2" in line or "3" in line
                or "4" in line or "5" in line or "6" in line or "7" in line
                or "8" in line or "9" in line):
            palabras = line.split(" ")
            for pal in palabras:
                if ("0" in pal or "1" in pal or "2" in pal or "3" in pal
                        or "4" in pal or "5" in pal or "6" in pal or "7" in pal
                        or "8" in pal or "9" in pal):
                    auto = Automata()
                    #pal=pal.replace("\n","")
                    for c in pal:
                        #print(auto.estado)
                        #print(c)
                        auto.calcular_estado(c.lower())
                    if (auto.estado not in estados_aceptacion):
                        #print(auto.estado)
                        imprimir_error = True
                        conteo_errores += 1
        if imprimir_error:
            print("Error en linea: ", linea)
        imprimir_error = False
        linea += 1
    if conteo_errores == 0:
        print("No hay errores lexicos en el programa")
Esempio n. 15
0
 def __init__(self):
     self.lista_liga = ListaLigada()
     self.automata = Automata()
     self.linea: int = 0
     self.linea_lista = ListaLigada()
     self.linea_errores: str = None
     self.log_error: str = None
Esempio n. 16
0
 def test_get_shortest_path(self):
     automata = Automata()
     state0 = State('state0')
     state1 = State('state1')
     state2 = State('state2')
     state3 = State('state3')
     state4 = State('state4')
     state5 = State('state5')
     state6 = State('state6')
     automata.add_state(state0)
     automata.add_state(state1)
     automata.add_state(state2)
     automata.add_state(state3)
     automata.add_state(state4)
     automata.add_state(state5)
     automata.add_state(state6)
     automata.add_edge(state0, state1, Clickable('0-1'))
     automata.add_edge(state0, state2, Clickable('0-2'))
     automata.add_edge(state0, state3, Clickable('0-3'))
     automata.add_edge(state2, state4, Clickable('2-4'))
     automata.add_edge(state4, state5, Clickable('4-5'))
     automata.add_edge(state3, state5, Clickable('3-5'))
     automata.add_edge(state3, state5, Clickable('5-0'))
     automata.add_edge(state5, state6, Clickable('5-6'))
     self.assertEqual(automata.get_shortest_path(state0), [])
     edges = automata.get_shortest_path(state6)
     # 0-3, 3-5, 5-6
     self.assertEqual([int(e[0].get_id()) for e in edges], [0, 3, 5])
Esempio n. 17
0
 def create_grid(self):
     lst = []
     for i in range(self.length):
         temp = []
         for j in range(self.width):
             temp.append(Automata('E', (i, j)))
         lst.append(temp)
     self.cellular_grid = np.array(lst)
Esempio n. 18
0
    def build_basic_struct(value):
        state1 = 1
        state2 = 2
        basic = Automata()
        basic.set_start_state(state1)
        basic.add_final_states(state2)
        basic.add_transitions(state1, state2, value)

        return basic
Esempio n. 19
0
def CBTestMain(folderpath, dirname,web_submit_id):
    logging.info(" Type: Cross Browser Testing")
    logging.info(" connect to mysql")
    print("")
    print("connect to sql")
    databank = MysqlDataBank("localhost", "root", "", "test")
    url, deep, time, b1, b2 = databank.get_websubmit(int(web_submit_id))
    basic_browserID = str(b1)
    other_browserID = str(b2)
    depth = int(deep)

    logging.info(" A new CBT begings...")
    logging.info(" setting config...")
    config = SeleniumConfiguration(int(basic_browserID),int(other_browserID), url)
    # max 3
    config.set_max_depth(int(depth))
    # max 3
    config.set_max_length(int(depth))
    # should be 1
    config.set_trace_amount(1)
    # should be 100 no use?
    config.set_max_states(5)
    config.set_folderpath(folderpath)
    config.set_dirname(dirname)
    config.set_automata_fname('automata.json')
    config.set_traces_fname('traces.json')
    #config.set_frame_tags(['iframe'])
    config.set_dom_inside_iframe(True)
    config.set_simple_clickable_tags()
    config.set_simple_inputs_tags()
    config.set_simple_normalizers()

    logging.info(" setting executor...")
    #nothing here
    executor = CBTExecutor(config.get_browserID(), config.get_url())

    logging.info(" setting crawler...")
    automata = Automata(config)
    #databank = InlineDataBank("140.112.42.145:2000", "jeff", "zj4bj3jo37788", "test")
    databank = InlineDataBank("localhost", "B00901138", "R124249166", "test")
    
    print('start Cross Browser Testing...')
    #acually it's CBT algorithm
    algorithm = CBTCrawler(int(other_browserID),url)

    crawler = SeleniumCrawler(config, executor, automata, databank, algorithm)

    logging.info(" crawler start runing...")
    crawler.run_algorithm()
    
    print(" end! save automata...")
    logging.info(" end! save automata...")
    algorithm.save_traces()
    automata.save_automata(config.get_automata_fname())
    Visualizer.generate_html('web', os.path.join(config.get_path('root'), config.get_automata_fname()))
    config.save_config('config.json')
Esempio n. 20
0
def create_stream(alphabet_size, stream_length, probabilities):
    '''
    function create streams over alphabet 1 to alphabet_sizes
    of length stream_length using probabilities
    param: alphabet_size
    param: stream_length
    param: probabilities - matrix of size alphabet_size x alphabet_size, which describes transition function for automata
    '''
    a = Automata(probabilities)
    return a.gen_stream(stream_length)
Esempio n. 21
0
 def __init__(self):
     self._initialize_buttons()
     self._initialize_button_events()
     self.device = sh1106(spi(device=0, port=0), rotate=2)
     self.device.contrast(255)
     self.automata = Automata(rules_list.current_rule(), self.DIMENSIONS)
     self._repopulate()
     self.start_time = time.time()
     self.paused = False
     self.average_fps = 0
     self.last_measured_time = time.time()
Esempio n. 22
0
def main():
    automataDict = automata_IO.dfa_json_importer("./resources/automata.json")

    alphabet = automataDict["alphabet"]
    initialState = automataDict["initial_state"]
    transitions = automataDict["transitions"]
    acceptingStates = automataDict["accepting_states"]

    automata_IO.dfa_to_dot(automataDict, "automata", "./resources")

    automata = Automata(alphabet, initialState, transitions, acceptingStates)

    _ = Screen("./resources/automata.dot.svg", automata)
Esempio n. 23
0
    def build_star_struct(a: Automata):
        a, m1 = a.new_build_from_number(2)

        star = Automata()
        star.set_start_state(1)
        star.add_final_states(m1)
        star.add_transitions(star.start_state, a.start_state, Automata.EPSILON)
        star.add_transitions(star.start_state, star.final_states[0], Automata.EPSILON)
        star.add_transitions(a.final_states[0], star.final_states[0], Automata.EPSILON)
        star.add_transitions(a.final_states[0], a.start_state, Automata.EPSILON)
        star.add_transition_dict(a.transitions)

        return star
Esempio n. 24
0
 def objective_func(self, x):
     opts = self.vec_to_opts(x)
     print(opts)
     # run automata
     a = Automata(opts)
     a.run()
     stats = a.stats()
     fitness = np.float64(-stats["score_sum"])
     print("Fitness: ", fitness)
     # if fitness < self.best_fitness:
     #     self.best_fitness = fitness
     #     self.best_automata = a
     return fitness
Esempio n. 25
0
def main():
    automataDict = automata_IO.dfa_json_importer("./resources/AFD.json")

    alphabet = automataDict["alphabet"]
    initialState = automataDict["initial_state"]
    transitions = automataDict["transitions"]
    acceptingStates = automataDict["accepting_states"]
    '''Monta a imagem a partir do Json passado'''
    automata_IO.dfa_to_dot(automataDict, "AFD", "./resources")

    automata = Automata(alphabet, initialState, transitions, acceptingStates)
    '''Screen recebe como parametro o caminho da imagem e também o objeto automato'''
    _ = Screen("./resources/AFD.dot.svg", automata)
Esempio n. 26
0
 def __init__(self, configuration, executor):
     self.automata = Automata()
     self.configuration = configuration
     self.executor = executor
     self.exe_stack = []  # stack of executed clickables (events)
     self.invariant_violation = []
     self.num_clickables = {
         'unexamined':
         0,  # num of candidate clickables found with rules in DomAnalyzer
         'true':
         0,  # num of clickables triggered new state (different screen dom)
         'false': 0,  # num of clickables not triggering new state
     }
Esempio n. 27
0
def main():
    texto = open("texto.txt", "r")
    auto = Automata()
    for letra in texto.read():
        if letra == "\n":
            letra = " "
        print(auto.estado)
        print(letra)
        auto.calcular_estado(letra)
    if "c0" in auto.estado or "c1" in auto.estado:
        print("No hay errores en tu escritura")
    else:
        print("Hay un error en el texto")
Esempio n. 28
0
 def dot_construct(automata_1, automata_2):
     [automata_1, m1] = automata_1.copy(1)
     [automata_2, m2] = automata_2.copy(m1)
     state1 = 1
     state2 = m2 - 1
     dot = Automata()
     dot.set_start_state(state1)
     dot.add_final_states(state2)
     dot.add_transition(automata_1.final_states[0], automata_2.start_state,
                        Automata.empty())
     dot.add_transitions(automata_1.transitions)
     dot.add_transitions(automata_2.transitions)
     return dot
Esempio n. 29
0
 def test_load_save(self):
     automata = Automata(fname='test_data/automata-example.json')
     config = B2gConfiguration('test-app-name', 'test-app-id', mkdir=False)
     config.set_path('root', 'test_data')
     config.set_path('dom', 'test_data/dom')
     config.set_path('state', 'test_data/screenshot/state')
     config.set_path('clickable', 'test_data/screenshot/clickable')
     saved_file_path = automata.save(config)
     import filecmp
     self.assertTrue(filecmp.cmp('test_data/automata-example.json', 'test_data/automata.json'))
     try:
         os.remove(saved_file_path)
     except OSError:
         pass
Esempio n. 30
0
    def parse_automata(self, in_file):
        """ :return Automata that contains in in_file"""

        states = self.__init_states(in_file)
        alphabet = self.__init_alphabet(in_file)

        init_state = states[
            (in_file.readline())[:-1]
        ]

        self.__init_final_states(in_file, states)
        self.__init_transitions(in_file, states)

        return Automata(states, alphabet, init_state)