1. Список говнокодов пользователя rockkley94

    Всего: 4

  2. Python / Говнокод #28524

    +1

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    def __get_column_names(table: str) -> tuple:
        try:
            with conn:
                cur.execute("SELECT name FROM PRAGMA_TABLE_INFO(?)", (table,))
                column_names = cur.fetchall()
        except Exception as excpt:
            print(excpt)
        column_names = tuple(i[0] for i in column_names)
        return column_names
    
    
    def db_register_user(user_data: types.User):
        """
        SQL запрос для внесения данных о пользователе
    
        Args:
            user_data: telebot User объект, содержащий словарь с параметрами пользователя
        """
        user_data = user_data.to_dict()
        column_names: tuple = __get_column_names('Users')
        user_values = tuple(user_data.get(key) for key in column_names if key in user_data)
        try:
            with conn:
                query = 'INSERT INTO Users cn'.replace('cn', str(column_names))+' VALUES (?,?,?,?,0,3)'
                parameters = (*user_values,)
                conn.execute(query, parameters)
        except Exception as excpt:
            print(excpt)
        conn.close()

    На сколько в такой ситуации .format не безопасен? Идея в том, чтобы не объебошится программисту в коде введя неверное значение колонки. Для этого имена колонок берутся из самой базы (есть мысль ещё и типы брать). Есть вариант реализации получше? Спасибо

    rockkley94, 26 Декабря 2022

    Комментарии (22)
  3. Python / Говнокод #28439

    0

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    def make_coffie(water_amount: int = 0) -> object:
        
        class Coffie_Constructor:
            
            def __init__(self, beans_amount: int = 0):
                self.water_amount = water_amount
                self.beans_amount = beans_amount
            
            def __call__(self, milk_amount: int = 0) -> int:
                return self.water_amount + self.beans_amount + milk_amount
    
            def __repr__(self) -> str:
                return 'Not enought call brakets were given'
            
        return Coffie_Constructor
    
    print(make_coffie(120)(50)(50))

    rockkley94, 09 Ноября 2022

    Комментарии (14)
  4. Python / Говнокод #28422

    −1

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    words = ['Broom', 'Being', 'Boring', 'Breeding', 'Dreaming', 'Doing', 'Dancing', 'Drinking',
         'Freezing', 'Falling', 'Flooding', 'Fearing', 'Saying', 'Sleeping', 'Standing',
         'Screaming', 'Running', 'Reading', 'Rolling', 'Rushing', 'Twerking', 'Telling']
    
    def make_rows(row_size: int) -> list:
        row_size = abs(int(row_size)); index = 0; amount = len(words)
        # Найти кол-во групп / Calculate the amount of sublists
        if row_size>amount: row_size=amount
        if row_size > 0:
            subs = (amount // row_size) + 1 if amount % row_size > 0 else amount // row_size
            print(f'Слов: {len(words)} | | Ячеек: {subs}\n')
            # Создать найденное кол-во групп / Create the found amount of sublists
            rows = [[] for i in range(subs)]
            for x in range(amount):
                rows[index].append(words[x])
                if len(rows[index]) == row_size: index += 1
            return rows
        else: return words
            
    print(make_rows(2))

    rockkley94, 19 Октября 2022

    Комментарии (19)
  5. Python / Говнокод #28403

    +1

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    class FileCheckError(Exception):
    
        def __init__(self, check, file):
            self.check = check
            self.file = file
            self.exceptions = ['не является файлом',
                               'не является .wav файлом',
                               'не находится в списке требуемых сэмплов',]
    
        def __str__(self):
            return f'{self.file} {self.exceptions[self.check]}'
    
    
    def validate_pack(pack) -> list:
        """
        Checks for invalid files in a pack folder
        Makes a list of invalid files if found any or
        makes a list of accepted samples
        """
        accepted_samples = []
        found_errors = []
    
        for sample in listdir(pack):
            checks = [isfile(join(pack, sample)),
                      fnmatch(sample, '*.wav'),
                      Path(pack / sample).stem in required_samples, ]
            try:
                for check in range(len(checks)):
                    if not checks[check]:
                        raise FileCheckError(check=check, file=sample)
            except FileCheckError as E:
                found_errors.append(str(E))
                continue
    
            accepted_samples.append(sample)
    
        if len(found_errors) != 0:
            return found_errors
        else:
            return accepted_samples
    
    result = validate_pack(Path('drumpacks/rock'))
    print(result, sep='\n')

    rockkley94, 07 Октября 2022

    Комментарии (8)