Exemplo n.º 1
0
 def receive(self):
     parser = Parser()
     print('CLIENT START receiving...')
     while self.connected['connected']:
         # receive messages
         try:
             msgs = parser.parse(self.mode['connect']['socket'].recv(1 << 20))
         except socket.timeout:
             continue
         except OSError:
             break
         # process the messages
         for msg in msgs:
             if msg == 'pause':
                 self.paused = not self.paused
             # close socket
             elif msg == 'close':
                 continue
             # update status
             else:
                 status = json.loads(msg)
                 self.set_status(status)
         # refresh pan
         self.refresh_pan()
     print('CLIENT END receiving...')
Exemplo n.º 2
0
 def func():
     parser = Parser()
     client = self.mode['clients'][id - 1]
     print(f'SERVER START receiving FROM CLIENT-{id}...')
     while self.status['connected'][id]:
         # receive and parse msg
         try:
             msg_strs = parser.parse(client['socket'].recv(1 << 20))
         except socket.timeout:
             continue
         except json.decoder.JSONDecodeError:
             print('\tJSON Decode Error!')
             continue
         # deal with msg
         for msg_str in msg_strs:
             msg = json.loads(msg_str)
             if msg['tag'] == 'close':
                 self.status['connected'][id] = False
             if msg['tag'] == 'move':
                 self.command.add(
                     (tuple(msg['move'][0]), tuple(
                         msg['move'][1]), msg['move'][2]), id)
             elif msg['tag'] == 'clear':
                 self.command.clear_command(id)
     print(f'SERVER END receiving FROM CLIENT-{id}...')
Exemplo n.º 3
0
def load_graph(graph):
    parser = Parser()
    while True:
        start = input('Unesite root dir: ')
        if os.path.isdir(start):
            for fname in os.listdir(start):
                curr = os.path.join(start, fname)
                if os.path.isdir(curr) or curr.endswith('.html'):
                    break
            else:
                err('Nije validna putanja')
            break
        else:
            err('Nije validna putanja')
    current = 0
    for root, dirs, files in os.walk(start):
        for file in files:
            current = loading_rotation(current, 'Ucitavanje grafa...')
            if file[-5:] == '.html':
                path = root + os.path.sep + file
                path_root = os.path.abspath(os.path.dirname(path))
                filepath = path_root + os.path.sep + file
                links, words = parser.parse(path)
                # NOTE(Jovan): Informacije o stranici pretvaraju se u vertex
                vertex = Vertex(filepath, words, links)
                graph.add_vertex(vertex)
    graph.gen_backlinks()
    loading_rotation(current,
                     col.bold + col.green + 'Ucitavanje zavrseno' + col.rst)
    print()
    return graph.vertex_count()
Exemplo n.º 4
0
 def receive(self):
     parser = Parser()
     print(f'CLIENT START receiving FROM SERVER...')
     while self.status['connected']:
         # receive and parse msg
         try:
             msg_strs = parser.parse(self.mode['socket'].recv(1 << 20))
         except socket.timeout:
             continue
         except json.decoder.JSONDecodeError:
             print('\tJSON Decode Error!')
             continue
         # deal with msg
         for msg_str in msg_strs:
             msg = json.loads(msg_str)
             if msg['tag'] == 'close':
                 self.close()
             elif msg['tag'] == 'status':
                 self.map.turn = msg['turn']
                 self.map.set_status(msg['status'])
                 self.command.trim(msg['cc'])
             elif msg['tag'] == 'init':
                 self.map_status = msg['status']
             elif msg['tag'] == 'conquer':
                 self.map.conquer(msg['players'][0], msg['players'][1])
                 self.status['winner'] = self.map.get_winner()
             elif msg['tag'] == 'pause':
                 self.status['paused'] = not self.status['paused']
     print(f'CLIENT END receiving FROM SERVER...')
Exemplo n.º 5
0
    def receive(self, ip, client_socket):
        parser = Parser()
        while self.status == 'accepting' and ip in self.ip_list():
            # receive and parse msg
            try:
                msg_strs = parser.parse(client_socket.recv(1 << 20))
            except socket.timeout:
                continue
            except json.decoder.JSONDecodeError:
                print('JSON Decode Error!')
                continue
            # deal with msg
            for msg_str in msg_strs:
                msg = json.loads(msg_str)
                if msg['tag'] == 'quit':
                    self.clients.remove([ip, client_socket])
                    print(f'THREAD ABORTS: server.receive(ip={ip})')
                    return
                elif msg['tag'] == 'start-game':
                    self.status = 'game'
                    break

        # check abort
        if self.status == 'abort':
            print(f'THREAD ABORTS: server.receive(ip={ip})')
            return

        while self.game is None:
            pass

        print(f'THREAD ENDS: server.receive(ip={ip})')
Exemplo n.º 6
0
def question_handler():
    question = request.get_json()
    user_input = question["user_input_value"]

    parser = Parser(user_input)
    parsed_question = parser.parse()

    if parsed_question != "ignore":
        try:
            gmaps = GmapsFetcher(parsed_question)
            gmaps_json_data = gmaps.get_json_data()

            if gmaps_json_data != "ZERO_RESULTS":
                mwiki = MwikiFetcher(gmaps_json_data[1])
                info = mwiki.get_page_id_and_title()
                extract = mwiki.get_extract(info[0], info[1])
                print(extract)
                return jsonify(gmaps_json_data[0], gmaps_json_data[1], extract)
            else:
                return jsonify(gmaps_json_data)

        except (KeyError, ConnectionError):
            return jsonify("error")

    else:
        return jsonify("ignore")
Exemplo n.º 7
0
 def receive(self):
     parser = Parser()
     print('CLIENT START receiving...')
     while self.connected['connected']:
         # receive messages
         try:
             msgs = parser.parse(
                 self.mode['connect']['socket'].recv(1 << 20))
         except socket.timeout:
             continue
         except OSError:
             break
         # process the messages
         for msg in msgs:
             if msg == 'pause':
                 self.paused = not self.paused
             # close socket
             elif msg == 'close':
                 pass
                 # self.connected['connected'] = False
             # update status
             elif msg.startswith('time'):
                 self.time = msg[4:]
             elif msg.startswith('info'):
                 info = json.loads(msg[4:])
                 self.score, self.time = info['score'], info['time']
             elif msg.startswith('end'):
                 info = json.loads(msg[3:])
                 self.win, self.score, self.time = info['win'], info[
                     'score'], info['time']
             else:
                 status = json.loads(msg)
                 self.set_status(status)
     print('CLIENT END receiving...')
Exemplo n.º 8
0
class TestWikiMedia(unittest.TestCase):
    def test_parse_auto(self):
        iterator = 0

        for questions in mock_questions_list:
            self.parser_test = Parser(questions)
            test_result = self.parser_test.parse()

            expected_result = expected_results[iterator]
            self.assertEqual(test_result, expected_result)

            iterator += 1
Exemplo n.º 9
0
 def func():
     parser = Parser()
     client = self.mode['connect']['clients'][i]
     print(f'SERVER START receiving FROM C{i}...')
     while self.connected['connected']:
         try:
             events_strs = parser.parse(client['socket'].recv(1 << 20))
         except socket.timeout:
             continue
         except json.decoder.JSONDecodeError:
             continue
         for events_str in events_strs:
             events = json.loads(events_str)
             self.players[i + 1].process_pressed(
                 events['key-pressed'], events['key-down'])
     print(f'SERVER END receiving FROM C{i}...')
Exemplo n.º 10
0
def main():
    args = argv()

    if args.replay:
        replay(args.replay)
    else:
        # Create a TCP/IP socket
        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # Bind the socket to the port
        server_address = ('', int(args.port))
        print(colors.Green + "Server Starting on: ", server_address)
        server.bind(server_address)

        # Listen for incoming connections
        server.listen(5)

        while True:
            # Wait for a connection
            print(colors.Blue + 'waiting for a connection' + colors.White)
            connection, client_address = server.accept()
            try:
                print(colors.Green + 'connection from ', client_address[0],
                      'on Port ', client_address[1])

                # Receive the data in small chunks and retransmit it
                while True:
                    data = connection.recv(1024)

                    if data:
                        p = Parser(data)
                        tlv_blob = p.parse()
                        p.print_parsed_data(tlv_blob, client_address)
                        JSON.write_json(tlv_blob, client_address)

                        # print('sending data back to the client')
                        connection.sendall(data)
                    else:
                        print(colors.Red + 'no more data from', client_address)
                        break

            finally:
                # Clean up the connection
                connection.close()
Exemplo n.º 11
0
 def receive(self):
     parser = Parser()
     end = False
     while not end:
         try:
             msg_strs = parser.parse(self.client.recv(1 << 20))
         except socket.timeout:
             continue
         except json.decoder.JSONDecodeError:
             print('\tJSON Decode Error!')
             continue
         # deal with msg
         for msg_str in msg_strs:
             msg = json.loads(msg_str)
             if msg['tag'] == 'status':
                 self.set_status(msg['status'])
             elif msg['tag'] == 'end-game':
                 end = True
     print(f'THREAD ENDS: player[{self.id}].sprites.game.receive()')
Exemplo n.º 12
0
 def receive(self, player_id):
     parser = Parser()
     while self.players[player_id].alive:
         # receive and parse msg
         try:
             msg_strs = parser.parse(self.clients[player_id][1].recv(1 << 20))
         except socket.timeout:
             continue
         except json.decoder.JSONDecodeError:
             print('\tJSON Decode Error!')
             continue
         # deal with msg
         for msg_str in msg_strs:
             msg = json.loads(msg_str)
             if msg['tag'] == 'command':
                 self.execute(player_id, msg['command'])
             elif msg['tag'] == 'pause':
                 if player_id == 0:
                     self.toggle_pause()
     print(f'THREAD ENDS: game.game.receive(player_id={player_id})')
Exemplo n.º 13
0
 def process(self):
     lexer = Lexer(self.source)
     lexer_result = lexer.tokenize()
     parser = Parser(lexer_result, self.sandbox)
     self.expressions = parser.parse()