1. Лучший говнокод

    В номинации:
    За время:
  2. C++ / Говнокод #8220

    +1007

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    template <typename T, typename U>
    auto operator()(T&& t, U&& u) const
    -> decltype(forward<T>(t) + forward<U>(u)) {
        return forward<T>(t) + forward<U>(u);
    }

    ohlol, 17 Октября 2011

    Комментарии (83)
  3. Си / Говнокод #5186

    +125

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    int function(void) {
        static int i, state = 0;
        switch (state) {
            case 0: /* start of function */
            for (i = 0; i < 10; i++) {
                state = 1; /* so we will come back to "case 1" */
                return i;
                case 1:; /* resume control straight after the return */
            }
        }
    }

    Нестандартное применение свитча.
    Тут оно нафиг не нужно.
    Источник: http://www.gamedev.ru/code/forum/?id=142536

    TarasB, 09 Января 2011

    Комментарии (83)
  4. C++ / Говнокод #3518

    +170

    1. 1
    const volatile void

    Тибетская философия С++. Постоянная изменчивая пустота.

    Говногость, 20 Июня 2010

    Комментарии (83)
  5. Pascal / Говнокод #3143

    +102

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    // тут обычный паскалевский код...
    if x > y then asm // если икс больше игрека
      mov eax, x  // то меняем их значения местами
      mov edx, y
      mov x, edx
      mov y, eax
    end;

    Как поменять значения двух целочисленных переменных, не заводя третью? Года 3 назад я делал примерно так.

    TarasB, 01 Мая 2010

    Комментарии (83)
  6. 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

    Комментарии (82)
  7. Python / Говнокод #26652

    +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
    44. 44
    45. 45
    46. 46
    47. 47
    48. 48
    49. 49
    50. 50
    51. 51
    52. 52
    53. 53
    54. 54
    55. 55
    56. 56
    57. 57
    58. 58
    59. 59
    60. 60
    61. 61
    62. 62
    63. 63
    64. 64
    65. 65
    66. 66
    67. 67
    68. 68
    69. 69
    70. 70
    71. 71
    72. 72
    73. 73
    74. 74
    75. 75
    76. 76
    77. 77
    78. 78
    79. 79
    80. 80
    from vk_bot.vk_config import GROUP_ID, TOKEN
    import vk_api
    from vk_api.bot_longpoll import VkBotLongPoll, VkBotEventType
    import random
    from vk_bot.db_session import *
    from vk_bot.__all_models import BugReport, Comment
    import datetime
    from vk_bot.vacancies import get_vacancies, ServerError
    
    
    def main():
        global_init("feedback/feedback.sqlite")
        vk_session = vk_api.VkApi(
            token=TOKEN)
        vk = vk_session.get_api()
    
        longpoll = VkBotLongPoll(vk_session, GROUP_ID)
        bot_state = {}
    
        def send_msg(msg):
            vk.messages.send(user_id=event.obj.message['from_id'],
                             message=msg,
                             random_id=random.randint(0, 2 ** 64))
    
        for event in longpoll.listen():
            if event.type == VkBotEventType.MESSAGE_NEW:
                if event.obj.message['from_id'] in bot_state and bot_state[event.obj.message['from_id']]:
                    state = bot_state[event.obj.message['from_id']]
                    if state == 1:
                        send_msg('Спасибо, ваше мнение для нас очень важно.')
                        Comment().new(event.obj.message['from_id'], datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                                      event.obj.message['text'])
                        bot_state[event.obj.message['from_id']] = 0
                    elif state == 2:
                        BugReport().new(event.obj.message['from_id'], datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                                        event.obj.message['text'])
                        send_msg('Спасибо за ваш отзыв, мы постараемся исправить проблему в ближайшем будущем.')
                        bot_state[event.obj.message['from_id']] = 0
                    elif state == 4:
                        parameters = [r.strip() for r in event.obj.message['text'].split(',')]
                        try:
                            vacancies = get_vacancies(parameters[0], parameters[1])
                        except ServerError:
                            send_msg('Не удалось получить ответ от сервера, попробуйте позже')
                            bot_state[event.obj.message['from_id']] = 0
                        except Exception:
                            send_msg('Данные введены некорректно, попробуйте заново.')
                            send_msg('Формат: <должность>, <мин. зарплата>')
                        else:
                            if len(vacancies) == 0:
                                send_msg('По данным критериям ничего не найдено')
                            else:
                                vacancy_list = [f"{i}) {v['title']}, {v['salary']}" for i, v in enumerate(vacancies)]
                                send_msg('\n'.join(vacancy_list))
    
                    if bot_state[event.obj.message['from_id']] == 0:
                        send_msg('1 - написать отзыв или предложение\n 2 - сообщить о неправильной работе сайта\n 3 - документация к api\n 4 - посмотреть список доступных вакансий\n иначе напишите сообщение и модератор вскоре на него ответит')
    
                elif event.obj.message['from_id'] not in bot_state:
                    send_msg('1 - написать отзыв или предложение\n 2 - сообщить о неправильной работе сайта\n 3 - документация к api\n 4 - посмотреть список доступных вакансий\n иначе напишите сообщение и модератор вскоре на него ответит')
                    bot_state[event.obj.message['from_id']] = 0
                else:
                    key = event.obj.message['text'][0]
                    if key == '1':
                        send_msg('Пожалуйста, поделитесь вашим мнением по поводу сайта.')
                        bot_state[event.obj.message['from_id']] = 1
                    elif key == '2':
                        send_msg('Пожалуйста, максимально подробно опишите вашу проблему.')
                        bot_state[event.obj.message['from_id']] = 2
                    elif key == '3':
                        send_msg('https://www.youtube.com/watch?v=dQw4w9WgXcQ')
                    elif key == '4':
                        send_msg('Введите название должности и минимальную желаемую зарплату по образцу:<должность>, <мин. зарплата>')
                        bot_state[event.obj.message['from_id']] = 4
                    else:
                        send_msg('Модератор вам скоро ответит, пожалуйста подождите.')
    
    
    if __name__ == '__main__':
        main()

    Код бота поддержки.
    Один из товарищей по проекту ничего в нем не делал,
    а потом чтобы его не выгоняли попросил дать ему хотя бы бота.
    Вот результат.
    Модели и вспомогательные файлы оставлять думаю не имеет смысла, все и так очевидно

    AlexandrovRoman, 13 Мая 2020

    Комментарии (82)
  8. Куча / Говнокод #25722

    0

    1. 1
    2. 2
    Vistefan, пойдёшь дядьку навестить?
    https://habr.com/ru/company/jugru/blog/455936/

    BoeHHblu_nemyx, 16 Июля 2019

    Комментарии (82)
  9. Objective C / Говнокод #24124

    −6

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    + (NSString*)enumToString:(SomeEnum)someEnumValue
    {
    	NSDictionary *strings =
    	@{
    		@(SomeEnumUndefined) : @"Undefined",
    		@(SomeEnumValue1) : @"Value1",
    		@(SomeEnumValue2) : @"Value2",
    		// Ещё 100500 пар
    	};
    
    	return strings[@(someEnumValue)];
    }

    Имена изменены, но смысл понятен. Точнее, непонятен.

    Desktop, 14 Апреля 2018

    Комментарии (82)
  10. PHP / Говнокод #20303

    +6

    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
    $query_list_builder = array(
    	'1000' => " and account = $account_id and creator = $creator_id",
    	'0100' => " and account = $account_id and salepoint = $salepoint_id and creator <> $creator_id ",
    	'0010' => " and account = $account_id and creator <> $creator_id and salepoint <> $salepoint_id ",
    	'0001' => " and account IN ($watchlist) and creator <> $creator_id and salepoint <> $salepoint_id and account <> $account_id ",
    
    	'1100' => " and salepoint = $salepoint_id or creator = $creator_id and account = $account_id ",
    	'1010' => " and account = $account_id and salepoint <> $salepoint_id or creator = $creator_id ",
    	'1001' => " and account IN ($watchlist) and account <> $account_id or creator = $creator_id ",
    
    	'1110' => " and account = $account_id or creator = $creator_id and salepoint = $salepoint_id ",
    	'1101' => " and account IN ($watchlist) and account <> $account_id or creator = $creator_id or salepoint = $salepoint_id ",
    
    	'1111' => " and account IN ($watchlist) or account = $account_id or creator = $creator_id or salepoint = $salepoint_id ",
    	'0000' => " and creator <> $creator_id and salepoint <> $salepoint_id and account NOT IN ($watchlist) ",
    
    	'0011' => " and account IN ($watchlist) and salepoint <> $salepoint_id and creator <> $creator_id ",
    	'0111' => " and account IN ($watchlist) and creator <> $creator_id ",
    	'0110' => " and account = $account_id and creator <> $creator_id ",
    	'0101' => " and account IN ($watchlist) and account <> $account_id or salepoint = $salepoint_id and creator <> $creator_id ",
    	'1011' => " and account IN ($watchlist) and salepoint <> $salepoint_id or creator = $creator_id ",
    );

    daniser, 30 Июня 2016

    Комментарии (82)
  11. C# / Говнокод #20075

    +6

    1. 1
    https://github.com/pascalabcnet/pascalabcnet

    ШОК! Говном компилируется говно. Это рекорд

    dm_fomenok, 25 Мая 2016

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