Пример #1
0
 def __init__(self, packet, table_map, table_subscribed):
     super(RowsEvent, self).__init__(packet)
     self._payload = packet[23:]
     self._table_map = table_map
     self._table_subscribed = table_subscribed
     
     head = self._payload
     # header
     head, self.table_id = utils.read_int(head, 6)
     head, self.flags = utils.read_int(head, 2)
     # with MySQL 5.6.x there will be other data following.
     
     # body
     head, self.number_of_columns = utils.read_lc_int(head)
     columns_present_bitmap_len = (self.number_of_columns + 7) / 8
     head, columns_present_bitmap1 = utils.read_int(head, 
                                     columns_present_bitmap_len)
     if self.header.event_type == EventType.UPDATE_ROWS_EVENT:
         head, columns_present_bitmap2 = utils.read_int(head, 
                                         columns_present_bitmap_len)
     # read rows.
     null_bitmap_len = (self.number_of_columns + 7) / 8;
     head, null_bitmap = utils.read_int(head, null_bitmap_len)
     row = {}
     for i in range(self.number_of_columns):
         is_null = True if ((null_bitmap[i/8] >> (i%8)) & 0x01) else False
Пример #2
0
 def _pkt_parse_eof(self, buf):
     """Parse a MySQL EOF-packet"""
     res = {}
     buf = buf[1:] # disregard the first checking byte
     (buf, res['warning_count']) = utils.read_int(buf, 2)
     (buf, res['status_flag']) = utils.read_int(buf, 2)
     return res
Пример #3
0
 def _pkt_parse_field(self, buf):
     """Parse a MySQL Field-packet"""
     field = {}
     (buf,field['catalog']) = utils.read_lc_string(buf)
     (buf,field['db']) = utils.read_lc_string(buf)
     (buf,field['table']) = utils.read_lc_string(buf)
     (buf,field['org_table']) = utils.read_lc_string(buf)
     (buf,field['name']) = utils.read_lc_string(buf)
     (buf,field['org_name']) = utils.read_lc_string(buf)
     buf = buf[1:] # filler 1 * \x00
     (buf,field['charset']) = utils.read_int(buf, 2)
     (buf,field['length']) = utils.read_int(buf, 4)
     (buf,field['type']) = utils.read_int(buf, 1)
     (buf,field['flags']) = utils.read_int(buf, 2)
     (buf,field['decimal']) = utils.read_int(buf, 1)
     buf = buf[2:] # filler 2 * \x00
     
     res = (
         field['name'],
         field['type'],
         None, # display_size
         None, # internal_size
         None, # precision
         None, # scale
         ~field['flags'] & FieldFlag.NOT_NULL, # null_ok
         field['flags'], # MySQL specific
         )
     return res
Пример #4
0
    def _parse(self):
        version = ''
        options = 0
        srvstatus = 0

        buf = self.data
        (buf,self.protocol) = utils.read_int(buf,1)
        (buf,version) = utils.read_string(buf,end='\x00')
        (buf,thrdid) = utils.read_int(buf,4)
        (buf,scramble) = utils.read_bytes(buf, 8)
        buf = buf[1:] # Filler 1 * \x00
        (buf,srvcap) = utils.read_int(buf,2)
        (buf,charset) = utils.read_int(buf,1)
        (buf,serverstatus) = utils.read_int(buf,2)
        buf = buf[13:] # Filler 13 * \x00
        (buf,scramble_next) = utils.read_bytes(buf,12)
        scramble += scramble_next

        self.info = {
            'version' : version,
            'thrdid' : thrdid,
            'seed' : scramble,
            'capabilities' : srvcap,
            'charset' : charset,
            'serverstatus' : serverstatus,
        }
Пример #5
0
    def parse_column(self, packet):
        """Parse a MySQL column-packet"""
        column = {}
        (packet, column['catalog']) = utils.read_lc_string(packet[4:])
        (packet, column['db']) = utils.read_lc_string(packet)
        (packet, column['table']) = utils.read_lc_string(packet)
        (packet, column['org_table']) = utils.read_lc_string(packet)
        (packet, column['name']) = utils.read_lc_string(packet)
        (packet, column['org_name']) = utils.read_lc_string(packet)
        packet = packet[1:]  # filler 1 * \x00
        (packet, column['charset']) = utils.read_int(packet, 2)
        (packet, column['length']) = utils.read_int(packet, 4)
        (packet, column['type']) = utils.read_int(packet, 1)
        (packet, column['flags']) = utils.read_int(packet, 2)
        (packet, column['decimal']) = utils.read_int(packet, 1)
        packet = packet[2:]  # filler 2 * \x00

        return (
            column['name'],
            column['type'],
            None,  # display_size
            None,  # internal_size
            None,  # precision
            None,  # scale
            ~column['flags'] & FieldFlag.NOT_NULL,  # null_ok
            column['flags'],  # MySQL specific
        )
Пример #6
0
    def parse_column(self, packet):
        """Parse a MySQL column-packet"""
        column = {}
        (packet, column['catalog']) = utils.read_lc_string(packet[4:])
        (packet, column['db']) = utils.read_lc_string(packet)
        (packet, column['table']) = utils.read_lc_string(packet)
        (packet, column['org_table']) = utils.read_lc_string(packet)
        (packet, column['name']) = utils.read_lc_string(packet)
        (packet, column['org_name']) = utils.read_lc_string(packet)
        packet = packet[1:] # filler 1 * \x00
        (packet, column['charset']) = utils.read_int(packet, 2)
        (packet, column['length']) = utils.read_int(packet, 4)
        (packet, column['type']) = utils.read_int(packet, 1)
        (packet, column['flags']) = utils.read_int(packet, 2)
        (packet, column['decimal']) = utils.read_int(packet, 1)
        packet = packet[2:] # filler 2 * \x00

        return (
            column['name'],
            column['type'],
            None, # display_size
            None, # internal_size
            None, # precision
            None, # scale
            ~column['flags'] & FieldFlag.NOT_NULL, # null_ok
            column['flags'], # MySQL specific
            )
Пример #7
0
 def _pkt_parse_field(self, buf):
     """Parse a MySQL Field-packet"""
     field = {}
     (buf,field['catalog']) = utils.read_lc_string(buf)
     (buf,field['db']) = utils.read_lc_string(buf)
     (buf,field['table']) = utils.read_lc_string(buf)
     (buf,field['org_table']) = utils.read_lc_string(buf)
     (buf,field['name']) = utils.read_lc_string(buf)
     (buf,field['org_name']) = utils.read_lc_string(buf)
     buf = buf[1:] # filler 1 * \x00
     (buf,field['charset']) = utils.read_int(buf, 2)
     (buf,field['length']) = utils.read_int(buf, 4)
     (buf,field['type']) = utils.read_int(buf, 1)
     (buf,field['flags']) = utils.read_int(buf, 2)
     (buf,field['decimal']) = utils.read_int(buf, 1)
     buf = buf[2:] # filler 2 * \x00
     
     res = (
         field['name'],
         field['type'],
         None, # display_size
         None, # internal_size
         None, # precision
         None, # scale
         ~field['flags'] & FieldFlag.NOT_NULL, # null_ok
         field['flags'], # MySQL specific
         )
     return res
Пример #8
0
 def _pkt_parse_eof(self, buf):
     """Parse a MySQL EOF-packet"""
     res = {}
     buf = buf[1:] # disregard the first checking byte
     (buf, res['warning_count']) = utils.read_int(buf, 2)
     (buf, res['status_flag']) = utils.read_int(buf, 2)
     return res
Пример #9
0
 def __init__(self, packet, table_map, table_subscribed, ctl_conn):
     super(TableMapEvent, self).__init__(packet)
     self._payload = packet[24:]
     self._ctl_conn = ctl_conn
     head = self._payload
     
     head, self.table_id = utils.read_int(head, 6)
     # add or modify table map.
     if self.table_id not in table_map:
         table_map[self.table_id] = {"schema":None, "table":None, "column_schemas":[]}           
     if self.schema in table_subscribed and self.table in table_subscribed[self.schema]:
         table_map[self.table_id]["column_schemas"] = \
            self.__get_table_informations(self.schema, self.table)
            
     head, self.flags = utils.read_int(head, 2)
     head, schema_name_len = utils.read_int(head, 1)
     head, self.schema = utils.read_bytes(head, schema_name_len)
     self.schema = str(self.schema)
     table_map[self.table_id]["schema"] = self.schema
     head, _ = utils.read_bytes(head, 1) #filler
     head, table_name_len = utils.read_int(head, 1)
     head, self.table = utils.read_bytes(head, table_name_len)
     self.table = str(self.table)
     table_map[self.table_id]["table"] = self.table
     head, _ = utils.read_bytes(head, 1) #filler
     head, self.columns_cnt = utils.read_lc_int(head)
     head, column_types = utils.read_bytes(head, self.columns_cnt)
     for i in range(0, self.columns_cnt):
         schema = table_map[self.table_id]["column_schemas"][i]
         t = ord(column_types[i])
         schema["TYPE_ID"] = t
         head, _ = self.__read_metadata(t, schema, head)
Пример #10
0
 def _parse(self):
     buf = self.data
     (buf,self.field_count) = utils.read_int(buf,1)
     (buf,self.affected_rows) = utils.read_lc_int(buf)
     (buf,self.insert_id) = utils.read_lc_int(buf)
     (buf,self.server_status) = utils.read_int(buf,2)
     (buf,self.warning_count) = utils.read_int(buf,2)
     if buf:
         (buf,self.info_msg) = utils.read_lc_string(buf)
Пример #11
0
def extract_gma(in_path, out_path):
    if path_exists(out_path):
        rmtree(out_path)
    if not path_exists(out_path):
        path_make_directories(out_path)
    """
    Takes an input path, and output path,
    and creates a directory from the gma input.
    """
    data, file = get_header(
        in_path)  # Call the function. Might as well, keep it dry.

    file_num = 0
    files = []

    while utils.read_int(file) != 0:
        file_data = {}
        file_num += 1
        file_data['name'] = utils.read_null_string(file)
        file_data['size'] = utils.read_int(file, 8)
        file_data['crc'] = utils.read_int(file)
        files.append(file_data)

    for key in range(file_num):
        content = file.read(files[key]["size"])

        if crc32(content) != files[key]['crc']:
            raise IOError("CRC of data from " + files[key]['name'] +
                          " failed to pass CRC.")

        tmp_out_path = path_join(out_path, files[key]['name'])
        if not path_exists(path_get_directory(tmp_out_path)):
            path_make_directories(path_get_directory(tmp_out_path))
        with open(tmp_out_path, 'wb') as new_file:
            new_file.write(content)
        _, ext = path_ext(tmp_out_path)
        if ext == ".lua":
            with open(tmp_out_path, 'rb') as new_file:
                cnt = new_file.read()
                cset = chardet.detect(cnt)['encoding']
                if cset is None:
                    cset = "ascii"
                # print(tmp_out_path, cset)
                cnt = cnt.decode(cset, errors="ignore")
                cnt = cnt.replace("//", "--")
                cnt = cnt.replace("/*", "--[[")
                cnt = cnt.replace("*/", "--]]")
            with open(tmp_out_path, 'w', encoding="utf8") as new_file:
                new_file.write(cnt)

    with open(path_join(out_path, "addon.json"), 'w',
              encoding="utf8") as new_file:
        new_file.write(data['info'])

    file.close()
    return data
Пример #12
0
    def parse_eof(self, packet):
        """Parse a MySQL EOF-packet"""
        if not (packet[4] == '\xfe' and len(packet) <= 9):
            raise errors.InterfaceError("Failed parsing EOF packet.")

        res = {}
        packet = packet[5:] # disregard the first checking byte
        (packet, res['warning_count']) = utils.read_int(packet, 2)
        (packet, res['status_flag']) = utils.read_int(packet, 2)
        return res
Пример #13
0
    def parse_eof(self, packet):
        """Parse a MySQL EOF-packet"""
        if not (packet[4] == '\xfe' and len(packet) <= 9):
            raise errors.InterfaceError("Failed parsing EOF packet.")

        res = {}
        packet = packet[5:]  # disregard the first checking byte
        (packet, res['warning_count']) = utils.read_int(packet, 2)
        (packet, res['status_flag']) = utils.read_int(packet, 2)
        return res
Пример #14
0
 def _pkt_parse_ok(self, buf):
     """Parse a MySQL OK-packet"""
     ok = {}
     (buf,ok['field_count']) = utils.read_int(buf,1)
     (buf,ok['affected_rows']) = utils.read_lc_int(buf)
     (buf,ok['insert_id']) = utils.read_lc_int(buf)
     (buf,ok['server_status']) = utils.read_int(buf,2)
     (buf,ok['warning_count']) = utils.read_int(buf,2)
     if buf:
         (buf,ok['info_msg']) = utils.read_lc_string(buf)
     return ok
Пример #15
0
 def _pkt_parse_ok(self, buf):
     """Parse a MySQL OK-packet"""
     ok = {}
     (buf,ok['field_count']) = utils.read_int(buf,1)
     (buf,ok['affected_rows']) = utils.read_lc_int(buf)
     (buf,ok['insert_id']) = utils.read_lc_int(buf)
     (buf,ok['server_status']) = utils.read_int(buf,2)
     (buf,ok['warning_count']) = utils.read_int(buf,2)
     if buf:
         (buf,ok['info_msg']) = utils.read_lc_string(buf)
     return ok
Пример #16
0
def main():
    ans = True
    while ans:
        lo = utils.read_int('min?')
        hi = utils.read_int('max?')
        primes = p.prime_range(lo, hi)
        result = average(*primes)
        print('total primes in range ({}-{}) is {}'.format(
            lo, hi, len(primes)))

        print('average of {} is {}'.format(primes, result))

        ans = utils.read_bool('continue?')
Пример #17
0
def rsa():
    """
    Test RSA
    """

    # Decrypt
    res_image_stream = open('decrypt_rsa.jpg', 'wb')
    with open('tests/encrypted.txt', 'rb') as encrypted:
        d = read_int(encrypted)
        n = read_int(encrypted)

        if d != 6126098115646990325497939754751346680273131840506753785808675623744493660811:
            raise Exception('Not equal d')

        if n != 11714199531846391552190233593088023207845451372578311171850728357335472002497:
            raise Exception('Not equal n')

        e = 8486391357485896322440256533131770617523773615720428244581337759609685018543

        rsa = Rsa(n, e, d)
        rsa.decrypt(encrypted, res_image_stream)

    res_image_stream.close()

    # Encrypt
    res_encrypted = open('encrypted_rsa.txt', 'wb')
    with open('tests/decrypted.jpg', 'rb') as image_stream:
        rsa.encrypt(image_stream, res_encrypted)

    res_encrypted.close()

    # Test encrypt
    test_encrypt = open('test_encrypt.jpg', 'wb')
    with open('encrypted_rsa.txt', 'rb') as res_encrypted:
        d = read_int(res_encrypted)
        n = read_int(res_encrypted)

        if d != 6126098115646990325497939754751346680273131840506753785808675623744493660811:
            raise Exception('Not equal d')

        if n != 11714199531846391552190233593088023207845451372578311171850728357335472002497:
            raise Exception('Not equal n')

        e = 8486391357485896322440256533131770617523773615720428244581337759609685018543

        rsa = Rsa(n, e, d)
        rsa.decrypt(res_encrypted, test_encrypt)

    test_encrypt.close()

    print(rsa.keygen())
Пример #18
0
Файл: rsa.py Проект: jokly/rsa
    def decrypt(self, reader, writer):
        length = os.fstat(reader.fileno()).st_size
        pos = reader.tell()

        while pos < length - 32:
            c = pow(read_int(reader), self.d, self.n)
            bytes_arr = c.to_bytes(8, byteorder='big')
            writer.write(bytes_arr)
            pos += 32

        c = pow(read_int(reader), self.d, self.n)
        bytes_arr = c.to_bytes(8, byteorder='big')

        if bytes_arr[7] != 0x08:
            writer.write(bytes_arr[:8 - bytes_arr[7]])
Пример #19
0
 def _pkt_parse_handshake(self, buf):
     """Parse a MySQL Handshake-packet"""
     res = {}
     (buf,res['protocol']) = utils.read_int(buf,1)
     (buf,res['server_version_original']) = utils.read_string(buf,end='\x00')
     (buf,res['server_threadid']) = utils.read_int(buf,4)
     (buf,res['scramble']) = utils.read_bytes(buf, 8)
     buf = buf[1:] # Filler 1 * \x00
     (buf,res['capabilities']) = utils.read_int(buf,2)
     (buf,res['charset']) = utils.read_int(buf,1)
     (buf,res['server_status']) = utils.read_int(buf,2)
     buf = buf[13:] # Filler 13 * \x00
     (buf,scramble_next) = utils.read_bytes(buf,12)
     res['scramble'] += scramble_next
     return res
Пример #20
0
 def _pkt_parse_handshake(self, buf):
     """Parse a MySQL Handshake-packet"""
     res = {}
     (buf,res['protocol']) = utils.read_int(buf,1)
     (buf,res['server_version_original']) = utils.read_string(buf,end='\x00')
     (buf,res['server_threadid']) = utils.read_int(buf,4)
     (buf,res['scramble']) = utils.read_bytes(buf, 8)
     buf = buf[1:] # Filler 1 * \x00
     (buf,res['capabilities']) = utils.read_int(buf,2)
     (buf,res['charset']) = utils.read_int(buf,1)
     (buf,res['server_status']) = utils.read_int(buf,2)
     buf = buf[13:] # Filler 13 * \x00
     (buf,scramble_next) = utils.read_bytes(buf,12)
     res['scramble'] += scramble_next
     return res
Пример #21
0
def read_multi():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect(('121.41.58.181', 22536))
    conn_str = 'm=TJ;u=qq1277;p=abc898;EX_SIZE=1;'
    send_bytes = struct.pack('%ss' % len(conn_str), conn_str)
    print send_bytes

    sock.send(conn_str)
    kline = models.KLineData(datetime.datetime.fromtimestamp(0))
    while True:
        # print 'try to recv package head'
        total_length = utils.read_int(sock)
        # print 'package length is %s' % total_length
        if total_length == 16:
            #print utils.read_raw_data(sock, 16)
            break
        read_size = 0

        while read_size < total_length:
            zip_length = utils.read_int(sock)
            read_size += 4

            if zip_length > 16777216:
                # print 'Recv a text package, length is %s' % zip_length
                # data = utils.read_raw_data(sock, zip_length)
                # read_size += zip_length
                # print data
                break

            if zip_length <= 0:
                # print "invalid package length"
                continue

            ori_length = utils.read_int(sock)

            # print 'to recv zip pacakge, length is %s, ori length is %s' %  (zip_length, ori_length)
            data = utils.read_raw_data(sock, zip_length - 4)

            parsed_data = parse_zlib(data)
            if parsed_data.label.startswith('TJCU'):
                if (is_same_min(kline.time, parsed_data.time)):
                    update(kline, parsed_data)
                else:
                    kline = models.KLineData(parsed_data.time, open = parsed_data.new_price, close = parsed_data.new_price)
                    save(kline)
                #print 'parsed data is %s, name is %s' % (parsed_data, parsed_data.name)

            read_size += zip_length
Пример #22
0
 def _parse(self):
     buf = self.data
     
     (buf,self.catalog) = utils.read_lc_string(buf)
     (buf,self.db) = utils.read_lc_string(buf)
     (buf,self.table) = utils.read_lc_string(buf)
     (buf,self.org_table) = utils.read_lc_string(buf)
     (buf,self.name) = utils.read_lc_string(buf)
     (buf,self.org_name) = utils.read_lc_string(buf)
     buf = buf[1:] # filler 1 * \x00
     (buf,self.charset) = utils.read_int(buf, 2)
     (buf,self.length) = utils.read_int(buf, 4)
     (buf,self.type) = utils.read_int(buf, 1)
     (buf,self.flags) = utils.read_int(buf, 2)
     (buf,self.decimal) = utils.read_int(buf, 1)
     buf = buf[2:] # filler 2 * \x00
Пример #23
0
 def is_error(self):
     header = utils.read_int(self._body, 1)[1]
     if 0xff == header:
         log.debug("received err packet.")
         return True
     else:
         return False
Пример #24
0
def get_exception(packet):
    """Returns an exception object based on the MySQL error
    
    Returns an exception object based on the MySQL error in the given
    packet.
    
    Returns an Error-Object.
    """
    errno = errmsg = None

    if packet[4] != '\xff':
        raise ValueError("Packet is not an error packet")

    sqlstate = None
    try:
        packet = packet[5:]
        (packet, errno) = utils.read_int(packet, 2)
        if packet[0] != '\x23':
            # Error without SQLState
            errmsg = packet
        else:
            (packet, sqlstate) = utils.read_bytes(packet[1:], 5)
            errmsg = packet
    except Exception as err:
        return InterfaceError("Failed getting Error information (%r)" % err)
    else:
        return get_mysql_exception(errno, errmsg, sqlstate)
Пример #25
0
def get_exception(packet):
    """Returns an exception object based on the MySQL error
    
    Returns an exception object based on the MySQL error in the given
    packet.
    
    Returns an Error-Object.
    """
    errno = errmsg = None
    
    if packet[4] != '\xff':
        raise ValueError("Packet is not an error packet")
    
    sqlstate = None
    try:
        packet = packet[5:]
        (packet, errno) = utils.read_int(packet, 2)
        if packet[0] != '\x23':
            # Error without SQLState
            errmsg = packet
        else:
            (packet, sqlstate) = utils.read_bytes(packet[1:], 5)
            errmsg = packet
    except Exception, err:
        return InterfaceError("Failed getting Error information (%r)" % err)
Пример #26
0
 def parse_handshake(self, packet):
     """Parse a MySQL Handshake-packet"""
     res = {}
     (packet, res['protocol']) = utils.read_int(packet[4:], 1)
     (packet, res['server_version_original']) = utils.read_string(
         packet, end='\x00')
     (packet, res['server_threadid']) = utils.read_int(packet, 4)
     (packet, res['scramble']) = utils.read_bytes(packet, 8)
     packet = packet[1:] # Filler 1 * \x00
     (packet, res['capabilities']) = utils.read_int(packet, 2)
     (packet, res['charset']) = utils.read_int(packet, 1)
     (packet, res['server_status']) = utils.read_int(packet, 2)
     packet = packet[13:] # Filler 13 * \x00
     (packet, scramble_next) = utils.read_bytes(packet, 12)
     res['scramble'] += scramble_next
     return res
Пример #27
0
def sell_ticket(cinema):
    cinema.show_rooms()
    n = utils.read_int("Introduce el número de sala: ")
    if n is not None:
        room = cinema.get_room(n)
        if room is not None:
            room.show_free()
            seat = utils.read_int("Introduce el número de butaca: ")
            if seat is not None:
                if room.select_seat(seat):
                    print("Se ha reservado la butaca")
                    #room.show_all()
                else:
                    print("La butaca es incorrecta")
        else:
            print("El número de sala es incorrecto")
Пример #28
0
def choose_function():
    print("Выберите нелинейное уравнение")
    counter = 0
    for pair in functions:
        print(str(counter) + ": " + pair[0])
        counter += 1
    num = utils.read_int(0, len(functions) - 1, "Выберите номер уравнения")
    return num
Пример #29
0
    def parse_ok(self, packet):
        """Parse a MySQL OK-packet"""
        if not packet[4] == '\x00':
            raise errors.InterfaceError("Failed parsing OK packet.")

        ok = {}
        try:
            (packet, ok['field_count']) = utils.read_int(packet[4:], 1)
            (packet, ok['affected_rows']) = utils.read_lc_int(packet)
            (packet, ok['insert_id']) = utils.read_lc_int(packet)
            (packet, ok['server_status']) = utils.read_int(packet, 2)
            (packet, ok['warning_count']) = utils.read_int(packet, 2)
            if packet:
                (packet, ok['info_msg']) = utils.read_lc_string(packet)
        except ValueError:
            raise errors.InterfaceError("Failed parsing OK packet.")
        return ok
Пример #30
0
def new_room(cinema):
    n = utils.read_int("Introduce el número de butacas: ")
    if n is not None:
        if n > 0:
            cinema.new_room(n)
            print("La sala ha sido dada de alta correctamente.")
        else:
            print("La sala debe tener al menos una butaca.")
Пример #31
0
def get_option(prompt: str, options: List[str]) -> int:
    numbered_options = [
        '{}. {}'.format(number + 1, option)
        for number, option in enumerate(options)
    ]
    full_prompt = '\n'.join([prompt] + numbered_options +
                            ['Wybór (1-{}): '.format(len(options))])
    return read_int(full_prompt, (1, len(options)))
Пример #32
0
    def parse_ok(self, packet):
        """Parse a MySQL OK-packet"""
        if not packet[4] == '\x00':
            raise errors.InterfaceError("Failed parsing OK packet.")

        ok = {}
        try:
            (packet, ok['field_count']) = utils.read_int(packet[4:], 1)
            (packet, ok['affected_rows']) = utils.read_lc_int(packet)
            (packet, ok['insert_id']) = utils.read_lc_int(packet)
            (packet, ok['server_status']) = utils.read_int(packet, 2)
            (packet, ok['warning_count']) = utils.read_int(packet, 2)
            if packet:
                (packet, ok['info_msg']) = utils.read_lc_string(packet)
        except ValueError:
            raise errors.InterfaceError("Failed parsing OK packet.")
        return ok
Пример #33
0
 def parse_handshake(self, packet):
     """Parse a MySQL Handshake-packet"""
     res = {}
     (packet, res['protocol']) = utils.read_int(packet[4:], 1)
     (packet,
      res['server_version_original']) = utils.read_string(packet,
                                                          end='\x00')
     (packet, res['server_threadid']) = utils.read_int(packet, 4)
     (packet, res['scramble']) = utils.read_bytes(packet, 8)
     packet = packet[1:]  # Filler 1 * \x00
     (packet, res['capabilities']) = utils.read_int(packet, 2)
     (packet, res['charset']) = utils.read_int(packet, 1)
     (packet, res['server_status']) = utils.read_int(packet, 2)
     packet = packet[13:]  # Filler 13 * \x00
     (packet, scramble_next) = utils.read_bytes(packet, 12)
     res['scramble'] += scramble_next
     return res
Пример #34
0
def reset_room(cinema):
    cinema.show_rooms()
    n = utils.read_int("Introduce el número de sala: ")
    if n is not None:
        if cinema.reset_room(n):
            print("Sala libre")
        else:
            print("El número de sala es incorrecto")
Пример #35
0
def show_room(cinema):
    cinema.show_rooms()
    n = utils.read_int("Introduce el número de sala: ")
    if n is not None:
        room = cinema.get_room(n)
        if room is not None:
            print(room)
            room.show_all()
Пример #36
0
def new_film(cinema):
    cinema.show_rooms()
    n = utils.read_int("Introduce el número de sala: ")
    if n is not None:
        film = input("Introduce el título de la película: ")
        if cinema.new_film(n, film):
            print("La película ha sido dada de alta satisfactoriamente.")
        else:
            print("Las sala indicada no existe")
Пример #37
0
    def is_eof(self, buf):
        """
        Check if the given buffer is a MySQL EOF Packet. It should
        start with \xfe and be smaller 9 bytes.

        Returns boolean.
        """
        l = utils.read_int(buf, 3)[1]
        if buf and buf[4] == '\xfe' and l < 9:
            return True
        return False
Пример #38
0
    def from_bytes(cls, buffer):

        # we need to re-read the type byte
        buffer.seek(-1, 1)
        type_byte = buffer.read1(1)[0]

        fin = type_byte & 0x20 > 0
        data_len_present = type_byte & 0x10 > 0
        offset_len = type_byte & 0x0C >> 2

        stream_id_len = (type_byte & 0x03)

        stream_id = read_int(stream_id_len, buffer)
        offset = read_int(offset_len, buffer)

        if not data_len_present:
            data_length = len(bytedata)
        else:
            data_length = read_int(2, buffer)

        return cls(stream_id, offset, fin, buffer.read1(data_length))
Пример #39
0
    def from_bytes(cls, buffer):

        # we need to re-read the type byte
        buffer.seek(-1, 1)
        type_byte = buffer.read1(1)[0]
        ll = type_byte & 0x0c
        if type_byte & 0x10:
            num_blocks = buffer.read1(1)[0]
        else:
            num_blocks = 1

        num_ts = buffer.read1(1)[0]
        largest_acknowledged_len = (1, 2, 4, 6)[ll >> 2]
        largest_acknowledged = read_int(largest_acknowledged_len, buffer)
        ack_delay = read_int(2, buffer)
        ack_blocks = []
        ack_blocks.append(read_int(largest_acknowledged_len, buffer))
        for i in range(1, num_blocks):
            ack_blocks.append(
                (read_int(1, buffer), read_int(largest_acknowledged_len,
                                               buffer)))

        timestapms = []
        if num_ts:
            timestapms.append((buffer.read1(1)[0], read_int(4, buffer)))
        for i in range(1, num_ts):
            timestapms.append((buffer.read1(1)[0], read_ufloat16(buffer)))

        return cls(largest_acknowledged, ack_delay, ack_blocks, timestapms)
Пример #40
0
 def __init__(self, buf):
     self.timestamp = utils.read_int(buf, 4)[1]
     self.event_type = utils.read_int(buf[4:], 1)[1]
     self.server_id = utils.read_int(buf[5:], 4)[1]
     self.event_size = utils.read_int(buf[9:], 4)[1]
     self.log_pos = utils.read_int(buf[13:], 4)[1]
     self.flags = utils.read_int(buf[17:], 2)[1]
Пример #41
0
 def __init__(self, buf):
     self.timestamp = utils.read_int(buf, 4)[1]
     self.event_type = utils.read_int(buf[4:], 1)[1]
     self.server_id = utils.read_int(buf[5:], 4)[1]
     self.event_size = utils.read_int(buf[9:], 4)[1]
     self.log_pos = utils.read_int(buf[13:], 4)[1]
     self.flags = utils.read_int(buf[17:], 2)[1]
Пример #42
0
def get_header(in_path):
    """Extracts the gma header from the input file."""
    if not path_exists(in_path):
        raise IOError("in_path " + in_path + " does not exist.")

    file = open(in_path, 'rb')
    data = {}

    data['identifier'] = utils.read_length_string(file, 4)
    if data['identifier'] != "GMAD":
        raise IOError("in_path `" + in_path + "` does not contain .gma file.")

    data['gmadversion'] = utils.read_int(file, 1)
    data['steamid'] = utils.read_int(file, 8)
    data['timestamp'] = utils.read_int(file, 8)
    data['required'] = utils.read_int(file, 1)
    data['title'] = utils.read_null_string(file)
    data['info'] = utils.read_null_string(file)
    data['author'] = utils.read_null_string(file)
    data['version'] = utils.read_int(file)

    return data, file
Пример #43
0
def main():
    # create_date_set(lambda x: np.sin(x), np.linspace(0, 10, 10, endpoint=True), "sin.txt")
    # x, y = read_data("sin.txt")
    # a, b, c, d = spline.get_coefficients(x, y)
    # show(x, y, b, c, d, lambda t: np.sin(t))
    func_num = utils.choose_from_map(functions)
    section = utils.read_section("Введите интервал, используя разделитель ;",
                                 ";")
    n = utils.read_int(
        0, 100, "Укажите количество узлов для вычисления уравнения сплайнов")
    x = np.linspace(section[0], section[1], n, endpoint=True)
    y = functions[func_num][1](x)
    a, b, c, d = spline.get_coefficients(x, y)
    show(x, y, b, c, d, functions[func_num][1])
Пример #44
0
 def raise_error(cls, buf):
     """Raise an errors.Error when buffer has a MySQL error"""
     errno = errmsg = None
     try:
         buf = buf[5:]
         (buf, errno) = utils.read_int(buf, 2)
         if buf[0] != '\x23':
             # Error without SQLState
             errmsg = buf
         else:
             (buf, sqlstate) = utils.read_bytes(buf[1:], 5)
             errmsg = buf
     except Exception, e:
         raise errors.InterfaceError("Failed getting Error information (%r)"\
             % e)
Пример #45
0
def raise_error(buf):
    """Raise an errors.Error when buffer has a MySQL error"""
    errno = errmsg = None
    try:
        buf = buf[5:]
        (buf,errno) = utils.read_int(buf, 2)
        if buf[0] != '\x23':
            # Error without SQLState
            errmsg = buf
        else:
            (buf,sqlstate) = utils.read_bytes(buf[1:],5)
            errmsg = buf
    except Exception, e:
        raise InterfaceError("Failed getting Error information (%r)"\
            % e)
Пример #46
0
 def _parse(self):
     buf = self.data
     
     if buf[0] != '\xff':
         raise errors.InterfaceError('Expected an Error Packet.')
     buf = buf[1:]
     
     (buf,self.errno) = utils.read_int(buf, 2)
     
     if buf[0] != '\x23':
         # Error without SQLState
         self.errmsg = buf
     else:
         (buf,self.sqlstate) = utils.read_bytes(buf[1:],5)
         self.errmsg = buf
Пример #47
0
def main():
    options = [new_room, new_film, sell_ticket, reset_room, show_room]
    cinema = Cinema()
    while True:
        print("************")
        menu()
        n = utils.read_int("Selecciona una opción: ")
        if n is not None:
            if n == 0:
                break
            elif n > 0 and n < 6:
                options[n - 1](cinema)
            else:
                print("Opción incorrecta")

    print("Hasta pronto!")
Пример #48
0
def get_alphabet() -> str:
    default_alphabet = ''.join(
        get_characters_between('0', '9') + get_characters_between('a', 'z') +
        get_characters_between('A', 'Z'))
    select_number_of_letters = 'Liczba dostępnych liter (od 1 do {})'.format(
        len(default_alphabet))
    select_alphabet = 'Wprowadzenie wszystkich dostępnych liter'
    mode = get_option('Proszę wybrać metodę wprowadzenia alfabetu: ',
                      [select_number_of_letters, select_alphabet])
    if mode == 1:
        alphabet = default_alphabet[:read_int(select_number_of_letters +
                                              ': ', (1,
                                                     len(default_alphabet)))]
    else:
        alphabet = ''.join(sorted(list(set(input(select_alphabet + ': ')))))
    print('Wyznaczony alfabet: {}'.format(alphabet))
    return alphabet
Пример #49
0
 def _parse(self):
     buf = self.data
     
     buf = buf[1:] # disregard the first checking byte
     (buf, self.warning_count) = utils.read_int(buf, 2)
     (buf, self.status_flag) = utils.read_int(buf, 2)
Пример #50
0
def get_max_game_length() -> int:
    return read_int('Proszę wybrać maksymalną liczbę ruchów: ', (1, None))