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

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

    +42

    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 Message {
    public:
        explicit Message(Level level);
        ~Message();
    
        Level level() const { return level_; }
        const time_t& time() const { return time_; }
        std::string text() const { return s_.str(); }
        bool enabled() const { return enabled_; }
    
        template<class T>
        Message& operator << (const T& t)
        {
            if (enabled_)
                s_ << t;
            return *this;
        }                                                                                       
    
        Message(Message& msg) { moveFrom(msg); }
        Message& operator = (Message& msg) { moveFrom(msg); return *this; }
        struct Ref {
            explicit Ref(Message& msg): msg_(&msg) {}
            Message* msg_;
        };                                                                                                                                
        operator Ref() { return Ref(*this); }
        Message(Ref r) { moveFrom(*r.msg_); }
        Message& operator = (Ref r) { moveFrom(*r.msg_); return *this; }
    
    private:
        Level level_;
        time_t time_;
        std::ostringstream s_;
        bool enabled_;
    
        void moveFrom(Message& msg)
        {
            level_ = msg.level_;
            time_ = msg.time_;
            s_.str(msg.s_.str());
            enabled_ = msg.enabled_;
            msg.enabled_ = false;
        }
    };

    move головного мозга

    roman-kashitsyn, 30 Октября 2014

    Комментарии (13)
  3. C++ / Говнокод #16543

    +42

    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
    int complexFunction(int flag)
    {
        QMutexLocker locker(&mutex);
    
        int retVal = 0;
    
        switch (flag) {
        case 0:
        case 1:
            return moreComplexFunction(flag);
        case 2:
            {
                int status = anotherFunction();
                if (status < 0)
                    return -2;
                retVal = status + flag;
            }
            break;
        default:
            if (flag > 10)
                return -1;
            break;
        }
    
        return retVal;
    }

    Пора добавлять отдельную ветку для фрейворка Qt. Это просто клад, так извратить все принципы програмирования :-). Этот код из справки к этому чуду. QMutexLocker - целый класс для того чтобы не нужно было разблокировать мьютекс при выходе из функции! Так они скоро и до сборщика мусора с неявной типизацией дойдут!
    P.S. У кого есть Qq попробуйте в "коде" сборки qmake вызвать include внутри функции.

    rst256, 15 Августа 2014

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

    +42

    1. 1
    if (sql->FieldByName("ID")->AsString > "0")

    bormand, 25 Июля 2014

    Комментарии (55)
  5. C++ / Говнокод #14504

    +42

    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
    #include <time.h>
    #include <string>
    #include <iostream>
    #include <functional>
    
    using namespace std::placeholders;
    
    class F
    {
            int inc;
    
    public:
    
            F( int inc_v ): inc( inc_v ) {};
    
            int calc( int x )
            {
                    return x + inc;
            };
    };
    
    F a1( -10 );
    F a2( 11 );
    
    int f1( int x )
    {
            return x - 10;
    };
    
    int f2( int x )
    {
            return x + 11;
    };
    
            struct my_ftor
            {
                    F *obj;
                    int (F::*meth)(int);
                    int operator()(int x)
                    {
                            return (obj->*meth)( x );
                    };
                    my_ftor() {};
                    my_ftor( F *x, int(F::*y)(int) ) : obj(x), meth(y) {};
            };
    
    template<typename functor_type>
    void test( std::function<functor_type(int)> filler, char *name )
    {
            const int size = 1000;
            const int iters = 10000;
    
            int beg_time, end_time;
    
            functor_type funcs[ size ];
    
            beg_time = clock();
            for ( int i = 0; i < iters; i++ )
            {
                    for ( int j = 0; j < size; j++ )
                    {
                            funcs[ j ] = filler(j);
                    }
            };
            end_time = clock();
            float creation = ((float)(end_time - beg_time) / CLOCKS_PER_SEC);
    
            beg_time = clock();
            int res = 0;
            for ( int i = 0; i < iters; i++ )
            {
                    for ( int j = 0; j < size; j++ )
                    {
                            res = funcs[ j ]( res );
                    };
            };
            end_time = clock();
            float execution = ((float)(end_time - beg_time) / CLOCKS_PER_SEC);
            std::cout << name << " creation time: " << creation << " execution time: " << execution << " result: " << res << "\n";
    }
    
    int main(int c, char * * v) 
    {
            test<int(*)(int)>( [](int i) {return i % 2 ? f1 : f2; }, "simple &function test" );
    
            test<std::function<int(int)>>( [](int i) {return i % 2 ? f1 : f2; }, "functor &function test" );
    
            test<std::function<int(int)>>( [](int i) {return i % 2 ? std::bind( &F::calc, &a1, _1 ) : std::bind( &F::calc, &a2, _1 ); }, "functor &object test" );
    
            test<my_ftor>( [](int i) {return i % 2 ? my_ftor( &a1, &F::calc ) : my_ftor( &a2, &F::calc ); }, "obj->*meth struct test" );
    
            std::cout << "END\n";
            return 0;
    }

    http://ideone.com/1iNzR
    Чем код так долго занимается?
    simple &function test creation time: 0.05 execution time: 0.09 result: 5000000
    functor &function test creation time: 0.51 execution time: 0.14 result: 5000000
    functor &object test creation time: 1.25 execution time: 0.14 result: 5000000
    obj->*meth struct test creation time: 0.12 execution time: 0.05 result: 5000000
    END

    LispGovno, 05 Февраля 2014

    Комментарии (58)
  6. PHP / Говнокод #12436

    +42

    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
    function test($method)
    {
      $picfile = 'pic1.png';
      $bgfile = 'output.png';
      $background = 'pic2.png';
      $foreground = 'pic3.png';
    
      if ($method == 'Imagick') {
        $img = new Imagick($picfile);
    
        $mask = new Imagick($background);
        $img->compositeImage($mask, imagick::COMPOSITE_COPYOPACITY, 0, 0);
        $mask->destroy();
    
        $overlay = new Imagick($foreground);
        $img->compositeImage($overlay, imagick::COMPOSITE_OVER, 0, 0);
        $overlay->destroy();
    
        $img->setImageFormat('png');
        file_put_contents($bgfile, $img->getImageBlob()); // $img->writeImage($bgfile) работает медленнее
        $img->destroy();
      } else if ($method == 'Wand') {
        $img = NewMagickWand();
        MagickReadImage($img, $picfile);
    
        $mask = NewMagickWand();
        MagickReadImage($mask, $background);
        MagickCompositeImage($img, $mask, MW_CopyOpacityCompositeOp, 0, 0);
        DestroyMagickWand($mask);
    
        $overlay = NewMagickWand();
        MagickReadImage($overlay, $foreground);
        MagickCompositeImage($img, $overlay, MW_OverlayCompositeOp , 0, 0);
        DestroyMagickWand($overlay);
    
        MagickSetImageFormat($img, 'png');
        file_put_contents($bgfile, MagickGetImagesBlob($img)); // ditto
        DestroyMagickWand($img);
      } else {
        $cmdline = 'convert -compose copy-opacity ' . $picfile . ' ' . $background . ' -composite';
        $cmdline .= ' -compose src-over ' . $foreground . ' -composite ' . $bgfile;
        exec($cmdline);
      }
    }
    
    $methods = array('Imagick', 'Wand', 'Command line');
    foreach ($methods as $m) {
      $start_time = microtime(true);
      for ($i = 0; $i < 4; $i++) {
        test($m);
      }
      $elapsed_time = microtime(true) - $start_time;
      echo 'Method: ' . $m . '; elapsed ' . strval($elapsed_time) . PHP_EOL;
    }

    Результаты выполнения на локальной машине:
    Method: Imagick; elapsed 0.45...
    Method: Wand; elapsed 0.82...
    Method: Command line; elapsed 0.87...
    Результаты выполнения на VPS:
    Method: Imagick; elapsed 79.64...
    Method: Wand; elapsed 151.64...
    Method: Command line; elapsed 46.49...

    Что-то тут не так...

    inkanus-gray, 17 Января 2013

    Комментарии (5)
  7. PHP / Говнокод #12300

    +42

    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
    function Utf2Win($s){ return Utf8($s,'w') ; }  
    function Win2Utf($s){ return Utf8($s,'u') ; }  
    function Utf8($s, $sTo = 'utf2win'){  
       $a = array();  
      for ($i=128; $i <= 191; $i++){  
       $a['utf'][] = ($i<144) ? chr(209).chr($i) : chr(208).chr($i);  
       $a['win'][] = ($i<144) ? chr($i + 112) : chr($i + 48) ;  
      }  
      $a['utf'][] = chr(208) . chr(129);  
      $a['win'][] = chr(168);  
      $a['utf'][] = chr(209) . chr(145);  
      $a['win'][] = chr(184);
    
      $a['utf'][] = chr(209) . chr(78);  
      $a['win'][] = chr(73);
    
      $a['utf'][] ='в„–';
      $a['win'][] = '№';
    
       if(in_array(strtolower($sTo), array('utf2win','w','cp1251','windows-1251')))  
         return str_replace($a['utf'], $a['win'], $s);  
       if(in_array(strtolower($sTo), array('win2utf','u','utf8','utf-8')))  
         return str_replace($a['win'], $a['utf'], $s);  
    } 
    
    function getfield_csv($string,$index)
    {
      $arr = explode(";",$string);
      return $arr[$index];
    }
    
    function read_csv($file)
    {
      $hFile = fopen($file,"r");
        $source_data_utf = fread($hFile,filesize($file));
      fclose($hFile);
      
      $source_data = Utf2Win($source_data_utf);
      
      $arr_source_data = explode("\r\n",$source_data);
      
      for($i=0;$i<count($arr_source_data);$i++)
      {
        $arr_source_data[$i] = str_replace(chr(239).chr(187).chr(191), "", $arr_source_data[$i]);
        $result[] = Array();
        $result[count($result)-1]['Ds'] = getfield_csv($arr_source_data[$i], 0);
        $result[count($result)-1]['Fkp'] = getfield_csv($arr_source_data[$i], 5);
        $result[count($result)-1]['Tgg'] = getfield_csv($arr_source_data[$i], 3);
        $result[count($result)-1]['Pol'] = getfield_csv($arr_source_data[$i], 4);
        $result[count($result)-1]['Tr'] = getfield_csv($arr_source_data[$i], 6);
      }
      return $result;
    }

    clauclauclau, 17 Декабря 2012

    Комментарии (4)
  8. PHP / Говнокод #12164

    +42

    1. 1
    2. 2
    if( !empty($data['date']) )
          $data['date'] = preg_replace("/(\d+)\.(\d+)\.(\d+)/", "$3.$2.$1", $data['date']);

    nicksevenfold, 21 Ноября 2012

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

    +42

    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
    <?php 
    if (isset($_GET['file'])) {
    	$dirname = 'download';
    	$file = (string) $_GET['file'];
    	$file = $dirname . DIRECTORY_SEPARATOR . trim($file);
    	if (is_file($file)) {
    		header('Content-Description: File Transfer');
    		header('Content-Type: application/octet-stream');
    		header('Content-Disposition: attachment; filename=' . basename($file));
    		header('Content-Transfer-Encoding: binary');
    		header('Expires: 0');
    		header('Cache-Control: must-revalidate');
    		header('Pragma: public');
    		header('Content-Length: ' . filesize($file));
    		ob_clean();
    		flush();
    		readfile($file);
    		exit();
    	}
    }

    вопрос:
    Нужно чтобы при клике по ссылке запускалось скачивание файла, но ссылка должна быть не прямая как site.ru/download/file1.rar
    - а вот такая: site.ru/download/1/

    ответ:
    создайте файл download.php и папку download для файлов.
    использовать так: localhost/download.php?file=01.jpg

    ahref, 20 Октября 2012

    Комментарии (8)
  10. C++ / Говнокод #11865

    +42

    1. 1
    2. 2
    3. 3
    4. 4
    objbase.h:
    
    #define __STRUCT__ struct
    #define interface __STRUCT__

    спасибо Микрософт за счастливое детство соответствие стандарту при засирании глобального неймспейса своими больными фантазиями

    defecate-plusplus, 03 Октября 2012

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

    +42

    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
    std::string loc =
    	( {
    		const char *str = "";
    
    		switch (location) {
    		case Net::HANDSHAKE_TIMEOUT:
    			str = _(" due to handshake timeout");
    			break;
    		case Net::RECV_HANDSHAKE:
    			str = _(" while waiting for handshake");
    			break;
    		case Net::HANDSHAKE_DATA:
    			str = _(" due to unsupported handshake data");
    			break;
    		case Net::HANDSHAKE_AUTH:
    			str = _(" while parsing handshake data");
    			break;
    		case Net::WAIT_DEVICE:
    			str = _(" while waiting for device");
    			break;
    		case Net::TRANSFER_DATA:
    			str = _(" while transferring data");
    			break;
    		}
    		str;
    	});

    Я хуею с юных оптимизаторов.

    gvy, 28 Августа 2012

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