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

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

    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
    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
    81. 81
    82. 82
    83. 83
    84. 84
    85. 85
    86. 86
    87. 87
    88. 88
    89. 89
    90. 90
    91. 91
    92. 92
    93. 93
    94. 94
    95. 95
    96. 96
    97. 97
    98. 98
    99. 99
    /* Windows doesn't support the fork() call; so we fake it by invoking
       another copy of Wget with the same arguments with which we were
       invoked.  The child copy of Wget should perform the same initialization
       sequence as the parent; so we should have two processes that are
       essentially identical.  We create a specially named section object that
       allows the child to distinguish itself from the parent and is used to
       exchange information between the two processes.  We use an event object
       for synchronization.  */
    static void
    fake_fork (void)
    {
      char exe[MAX_PATH + 1];
      DWORD exe_len, le;
      SECURITY_ATTRIBUTES sa;
      HANDLE section, event, h[2];
      STARTUPINFO si;
      PROCESS_INFORMATION pi;
      struct fake_fork_info *info;
      char *name;
      BOOL rv;
    
      section = pi.hProcess = pi.hThread = NULL;
    
      /* Get the fully qualified name of our executable.  This is more reliable
         than using argv[0].  */
      exe_len = GetModuleFileName (GetModuleHandle (NULL), exe, sizeof (exe));
      if (!exe_len || (exe_len >= sizeof (exe)))
        return;
    
      sa.nLength = sizeof (sa);
      sa.lpSecurityDescriptor = NULL;
      sa.bInheritHandle = TRUE;
    
      /* Create an anonymous inheritable event object that starts out
         non-signaled.  */
      event = CreateEvent (&sa, FALSE, FALSE, NULL);
      if (!event)
        return;
    
      /* Create the child process detached form the current console and in a
         suspended state.  */
      xzero (si);
      si.cb = sizeof (si);
      rv = CreateProcess (exe, GetCommandLine (), NULL, NULL, TRUE,
                          CREATE_SUSPENDED | DETACHED_PROCESS,
                          NULL, NULL, &si, &pi);
      if (!rv)
        goto cleanup;
    
      /* Create a named section object with a name based on the process id of
         the child.  */
      name = make_section_name (pi.dwProcessId);
      section =
          CreateFileMapping (INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0,
                             sizeof (struct fake_fork_info), name);
      le = GetLastError();
      xfree (name);
      /* Fail if the section object already exists (should not happen).  */
      if (!section || (le == ERROR_ALREADY_EXISTS))
        {
          rv = FALSE;
          goto cleanup;
        }
    
      /* Copy the event handle into the section object.  */
      info = MapViewOfFile (section, FILE_MAP_WRITE, 0, 0, 0);
      if (!info)
        {
          rv = FALSE;
          goto cleanup;
        }
    
      info->event = event;
    
      UnmapViewOfFile (info);
    
      /* Start the child process.  */
      rv = ResumeThread (pi.hThread);
      if (!rv)
        {
          TerminateProcess (pi.hProcess, (DWORD) -1);
          goto cleanup;
        }
    
      /* Wait for the child to signal to us that it has done its part.  If it
         terminates before signaling us it's an error.  */
    
      h[0] = event;
      h[1] = pi.hProcess;
      rv = WAIT_OBJECT_0 == WaitForMultipleObjects (2, h, FALSE, 5 * 60 * 1000);
      if (!rv)
        goto cleanup;
    
      info = MapViewOfFile (section, FILE_MAP_READ, 0, 0, 0);
      if (!info)
        {
          rv = FALSE;
          goto cleanup;
        }

    Из исходников wget.

    https://git.savannah.gnu.org/cgit/wget.git/tree/src/mswindows.c

    rOBHOBO3Hblu_nemyx, 06 Декабря 2024

    Комментарии (12)
  3. PHP / Говнокод #28801

    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
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    <?php
    
    function filter($var, $type)
    {
         switch ($type[0])
         {
             case 1: $var = 'intval('.$var.')';
             break;
             case 2: $var = 'trim('.$var.')';
             break;
         }
         switch ($type[1])
         {
             case 1: $var = 'intval('.$var.')';
             break;
             case 2: $var = 'trim('.$var.')';
             break;
         }
         return $var;
    }
    $var3 = 233;
    echo filter($var3, [1,2]);
    ?>

    Шедевр:
    https://php.ru/forum/threads/nuzhna-pomosch-po-kodu.101533

    MouseZver, 22 Июня 2023

    Комментарии (12)
  4. Lua / Говнокод #28744

    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
    18. 18
    local function isEven(number)
        local code = "return "
        for i = 1, number do
            code = code .. "false"
            if i ~= number then
                code = code .. " =="
            end
        end
    
        return load(code)()
    end
    
    print("Enter number: ")
    if isEven(tonumber(io.read())) then
        print("Number is even")
    else
        print("Number is odd")
    end

    Определяет чётность числа. Работает для чисел >= 1 (Желательно <= 1000, чем лучше компьютер, тем больше)

    pidoras123, 16 Апреля 2023

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

    −1

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    9. 9
    def auth_2FA(request):
        mail = request.POST.get('mail')
        user = User.objects.get(email=mail)
        code2FA = request.POST.get('code2FA')
        if pyotp.TOTP(user.secret).verify(code2FA):
            auth.login(request, user)
            return redirect(settings.HOME_PAGE)
        else:
            ...

    # Безопасность
    Django, двухфакторка.
    Защиты от перебора нет, пароль не проверяется. Зная только mail можно залогиниться перебрав код из 6 цифр

    Doorman5302, 01 Марта 2023

    Комментарии (12)
  6. Python / Говнокод #28367

    0

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    >>> import math
    >>> n = math.factorial(1559)
    >>> n
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: Exceeds the limit (4300) for integer string conversion

    https://github.com/sympy/sympy/issues/24033

    Какой багфикс )))

    3_dar, 12 Сентября 2022

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

    0

    1. 1
    2. 2
    3. 3
    def decode_flag(event_states: str) -> bool:
        flag = 1 if int(event_states, 16) & 10_000_000_000_000_000 else 0
        return bool(flag)

    Кусок из реального коммерческого проекта
    Есть стринга из 8 символов - флагов (0 или 1), но нас интересует только 4 символ в ней

    lpjakewolfskin, 08 Сентября 2022

    Комментарии (12)
  8. Python / Говнокод #28279

    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
    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
    81. 81
    82. 82
    83. 83
    84. 84
    85. 85
    86. 86
    87. 87
    88. 88
    89. 89
    90. 90
    91. 91
    92. 92
    93. 93
    94. 94
    95. 95
    '''
    Main file of bot
    Главный фаил бота
    '''
    from discord.ext import commands
    
    import wotb_api
    import settings
    import messages as m
    from messages_gen import pars
    from settings import bot_settings
    
    
    class App():
        '''
        Main class of bot
        Главный класс бота
        '''
        def __init__(self):
            self.pars = pars()
            self.msg = m.msg()
            self.api = wotb_api.API()
            self.bot = commands.Bot(command_prefix=
                                    bot_settings['command_prefix'])
            self.__token__ = settings.bot_settings['TOKEN']
    
        def error_handler(self,data):
            '''
            Сопостовляем полученную ошибку со словарём
            и возвращаем True если данные совпадают
            со словарём ошибок.
            '''
            for i in self.api.error_list:
                if data == i:
                    return True
            return False
    
        def main(self):
            '''
            Здесь описанна логика бота, и его взаимодействие
            с другими модулями
            '''
            @self.bot.command()
            async def stats(ctx):
                command = ctx.message.content
                command = command.split(' ')
                print(f'Запрос: {command}')
    
                if len(command) == 2:
                    player_data = self.api.get_player_stats(command[1])
                    if self.error_handler(player_data):
                        await ctx.send(embed = self.
                                       msg.return_error_emb(player_data))
                    else:
                        embed = self.pars.get_data(player_data,
                                                   self.api.last_id)
                        await ctx.send(embed = embed)
    
                elif len(command) == 3:
                    player_data = self.api.get_player_stats(command[1],
                                                            command[2])
                    if self.error_handler(player_data):
                        await ctx.send(embed = self.
                                       msg.return_error_emb(player_data))
                    else:
                        embed = self.pars.get_data(player_data,
                                                   self.api.last_id)
                        await ctx.send(embed = embed)
    
                elif len(command) > 3:
                    await ctx.send(embed = self.msg.return_error_emb('CFE'))
                else:
                    await ctx.send(embed = self.msg.return_error_emb('NN'))
    
            @self.bot.command()
            async def ver(ctx):
                await ctx.send(embed = self.msg.about_embed())
    
            @self.bot.command()
            async def server(ctx):
                command = ctx.message.content
                command = command.split(' ')
    
                if len(command) == 2:
                    if command[1].lower() == 'all':
                        s_status = ''
                        s_status = self.api.get_server_status('all')
                        if self.error_handler(s_status):
                            embed = ''
                            embed = self.msg.return_error_emb(s_status)
                            await ctx.send(embed = embed)
                        else:
                            embed = ''
                            embed = self.pars.server_status_all(s_status)
                            await ctx.send(embed = embed)

    Как вам код в плане читаемости. Pylint дал мне 9.78/10 балов (это не полный код)

    Non_type_object, 17 Июля 2022

    Комментарии (12)
  9. JavaScript / Говнокод #28183

    −9

    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
    81. 81
    82. 82
    83. 83
    84. 84
    85. 85
    86. 86
    87. 87
    88. 88
    89. 89
    90. 90
    91. 91
    92. 92
    93. 93
    94. 94
    95. 95
    const puppeteer = require('puppeteer-core');
    const fs = require('fs');
    const getCurrentLine = require('get-current-line').default;
    const { execFileSync } = require('child_process');
    
    const data = fs.readFileSync('aviso.bz.cookies.json');
    const cookies = JSON.parse(data.toString());
    
    function randomInteger(min, max) {
      let rand = min - 0.5 + Math.random() * (max - min + 1);
      return Math.round(rand);
    }
    
    function delay(time) {
       return new Promise(function(resolve) {
           setTimeout(resolve, time*1000)
       });
    }
    
    function delay2(time) {
       return new Promise(function(resolve) {
           setTimeout(resolve, time)
       });
    }
    
    let ext = '/home/user/aviso/extensions/1.42.4_0';
    
    (async () => {
      const browser = await puppeteer.launch({
        headless: false,
        defaultViewport: null,
        executablePath: '/usr/bin/chromium',
    devtools: false,
        args: [
    '--start-maximized',
    //'--user-agent="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.88 Safari/537.36"',
    //`--disable-extensions-except=${ext}`,
    //`--load-extension=${ext}`
     ]
      });
    
      const page = await browser.newPage();
      await page.setDefaultNavigationTimeout(0);
    
      let newPage;
    
      await page.setCookie(...cookies);
      await page.goto('https://aviso.bz/work-youtube', {waitUntil: 'networkidle0'});
    //await delay(1000);
      let c = 0;
      while(true) {
    
      if(c == 100) {
        await page.reload({ waitUntil: ["networkidle0", "domcontentloaded"] });
        c = 0;
      }
    
    let t = await page.$('[id^="ads-link-"]');
    if(t == null) {
    console.log('wait new tasks...');
    await delay(10);
    await page.reload({ waitUntil: ["networkidle0", "domcontentloaded"] });
    c = 0;
    continue;
    }
    let tt = await t.evaluate((q) => getComputedStyle(q).display);
    if(tt == 'none') {
    console.log('del inactive')
    page.evaluate(q => { document.querySelector('[id^="ads-link-"]').remove(); })
    continue;
    }
    
    let tr = await page.$('tr[class^="ads_"]');
    let span = await tr.$('[onclick^="funcjs[\'start_youtube"]');
    let title = await span.evaluate(el => el.textContent.trim());
    console.log('title: \''+title+'\'');
    let sec = await tr.$('td[align="right"] span[class="serf-text"]');
    let secs = await sec.evaluate(el => el.textContent.trim());
    console.log('sec: ' + secs.split(' ')[0]);
    
    let newPagePromise = new Promise(x => browser.once('targetcreated', target => x(target.page())));
    
    //await page.waitForSelector('tr[class^="ads_"] span[onclick^="funcjs[\'start_youtube"]');
    //let x = await page.$('tr[class^="ads_"] span[onclick^="funcjs[\'start_youtube"]');
    //console.log(x.click);
    await page.waitForTimeout(2000);
    try {
    await page.click('tr[class^="ads_"] span[onclick^="funcjs[\'start_youtube"]');
    }
    catch(e) {
    console.log('error! del item');
    await page.evaluate(() => {
        document.querySelector('tr[class^="ads_"]').remove()
      });
    continue; } await page.waitForSelector('span[onclick^="funcjs[\'open_window\']"]', { timeout: 60000 }); await delay2(randomInteger(700, 2000)); await page.click('span[onclick^="funcjs[\'open_window\']"]'); newPage = await newPagePromise; await newPage.bringToFront(); const userAgent = await newPage.evaluate(() => navigator.userAgent ); console.log(userAgent) //let pages = await browser.pages(); console.log('> '+newPage.url()); await newPage.waitForSelector('tr[id="timer-tr-block"]', { timeout: 200000 }); await delay(randomInteger(2, 4)); console.log('yt click'); const frame = await newPage.waitForSelector('iframe'); let rect = await newPage.evaluate(el => { let {width, height} = el.getBoundingClientRect(); return {width, height}; }, frame); await newPage.mouse.click(rect.width / 2, rect.height / 2); //execFileSync('xdotool', ['mousemove', '960', '611']); //execFileSync('xdotool', ['click', '1']); console.log('waiting'); await newPage.waitForSelector('a[href=""]', { timeout: 200000 }); console.log('ok'); await delay2(randomInteger(900, 1500)); //console.log('> '+newPage.url()); await newPage.close(); await delay2(500); await page.bringToFront(); await page.evaluate(() => { document.querySelector('tr[class^="ads_"]').remove() }); await delay(randomInteger(1, 3)); console.log('c: '+ ++c +"\n"); } await browser.close(); })();

    автосборщик бабла для aviso

    paroljanet, 23 Мая 2022

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

    0

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    public function validate($mailAddress)
    {
        $this->mailAddress = $mailAddress;
        if($this->validateMailAddress()) {
            if ($this->checkMXRecord()) {
                throw new \Exception('Mail is valid');
            }
        }
        throw new \Exception('Mail is invalid');
    }

    pefigah572, 04 Мая 2022

    Комментарии (12)
  11. JavaScript / Говнокод #27957

    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
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    // @strict: true
    // @lib: es2020
    // @declaration: true
    type BadFlatArray<Arr, Depth extends number> = {
        obj: {
            "done": Arr,
            "recur": Arr extends ReadonlyArray<infer InnerArr>
            ? BadFlatArray<InnerArr, [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20][Depth]>
            : Arr
        }[Depth extends -1 ? "done" : "recur"]
    }["obj"];
    
    declare function flat<A, D extends number = 1>(
        arr: A,
        depth?: D
    ): BadFlatArray<A, D>[]
    
    function foo<T>(arr: T[], depth: number) {
        return flat(arr, depth);
    }
    
    function main() {
        foo<number>([1.0, 2.0], 2);
    }

    спорим вы нихрена не поняли что это такое?

    ASD_77, 16 Января 2022

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