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

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

    +159

    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
    <?
    function flevel($exp)
    {
    include_once "config/mysql.php";
    
    	$querylevel = "SELECT maxexp FROM level";
    	$levelquery = mysql_query($querylevel);
    	while($rowslvl = mysql_fetch_row($levelquery))
    	{
    	$levelarr[] = $rowslvl[0];
    	}
    	
    	
    	
    	switch(TRUE)
        {
    		
        case ($exp <= $levelarr[0]):
        return $level = "1";
        break;
    
        case ($exp <= $levelarr[1]):
        return $level = "2";
        break;
    
        case ($exp <= $levelarr[2]):
        return $level = "3";
        break;
    
        case ($exp <= $levelarr[3]):
        return $level = "4";
        break;
    	
    	case ($exp <= $levelarr[4]):
        return $level = "5";
        break;
    	
    	case ($exp <= $levelarr[5]):
        return $level = "6";
        break;
    	
    	case ($exp <= $levelarr[6]):
        return $level = "7";
        break;
    	
    	case ($exp <= $levelarr[7]):
        return $level = "8";
        break;
    	
    	case ($exp <= $levelarr[8]):
        return $level = "9";
        break;
    	
    	case ($exp <= $levelarr[9]):
        return $level = "10";
        break;
    	
    	case ($exp <= $levelarr[10]):
        return $level = "11";
        break;
    	
    	case ($exp <= $levelarr[11]):
        return $level = "12";
        break;
    	/* ... */
    	case ($exp <= $levelarr[42]):
        return $level = "43";
        break;
    	
    	case ($exp <= $levelarr[43]):
        return $level = "44";
        break;
    	
    	case ($exp <= $levelarr[44]):
        return $level = "45";
        break;
    	
    	case ($exp <= $levelarr[45]):
        return $level = "46";
        break;
    	
    	case ($exp <= $levelarr[46]):
        return $level = "47";
        break;
    	
    	case ($exp <= $levelarr[47]):
        return $level = "48";
        break;
    	
    	case ($exp <= $levelarr[48]):
        return $level = "49";
        break;
    	
    	case ($exp > $levelarr[49]):
        return $level = "50";
        break;
        }
    }
    ?>

    Пришел в проект по созданию веб игры, смотрю организацию проекта... Жопа там, что папки, что код, что база одно и тоже, каша. Вот нашел одну забавную функцию. Она возвращает уровень персонажа судя по кол-во XP. Вместо того что бы писать 'SELECT `level` FROM `level` WHERE `minexp` <= ' . $exp . ' AND `maxexp` > ' . $exp надо было switch .. case писать. Нету слов.

    volter9, 11 Июня 2014

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

    +166

    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
    $response = LINQ::from($products->as_array('id'))
                        ->join($images)
                        ->on(function ($from_key, $from_value, $join_key, $join_value){
                            return $from_key === $join_key;
                        })
                        ->select(function($from_key, $from_value, $join_key, $join_value)use($searchStr){
                            $replaceStr = '<span class="badge badge-success">'.$searchStr.'</span>';
                            return array(
                               'title' => str_ireplace($searchStr, $replaceStr, $from_value->title),
                               'href' => '/product/'.$from_value->alias.'.html',
                               'thumb' => '/public/'.$join_value->thumb
                            );
                        })
                        ->result();

    Так бывает когда приверженца C# заставляют писать на PHP. Он обязательно напишет свой аналог LINQ с театром и балеринами, а потом будет ныть о том, что в похапе нет нормальных лямбд.

    Strannik1941, 08 Июня 2014

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

    +133

    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
    //checks if the string is a hex stream e.g. "31 32 33 6A F8"
            private bool _IsHexStream(string sValue)
            {
                sValue = sValue.Trim();
    
                
                if (sValue.Length < 2)
                {
                    return false;
                }
    
                for (int i = 0; i < sValue.Length; i++)
                {
                    if(_IsHexChar(Convert.ToChar(sValue.Substring(i,1))) == false)
                    {
                        return false;
                    }
                }
    
                //every third char must be a space, only possible in case of two bytes
                if (sValue.Length > 3)
                {
                    for (int i = 2; i < sValue.Length; i += 3)
                    {
                        string sBuffer = sValue.Substring(i, 1);
    
                        if (sBuffer.Equals(" ") == false)
                        {
                            return false;
                        }
                    }
                }
    
                //string is a hex stream 
                return true;
            }

    blackhearted, 02 Июня 2014

    Комментарии (22)
  5. JavaScript / Говнокод #16082

    +161

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    var percent = 0;
    setInterval(function() {
        if(percent < 100) {
            percent += 10;
            showprogress(percent);
        }
    }, 50);

    Прогресс-бар асинхронной загрузки картинки

    kissarat, 30 Мая 2014

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

    +156

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    9. 9
    $html = file_get_contents('http://2ip.ru/'); 
    preg_match_all('#<big id=\"d_clip_button\">(.*?)</big>#', $html, $ip); 
    $ip2 = $ip[1][0]; 
    
    if($pass == $pass2) 
    {$data = file_get_contents("http://$server$domain/$catalog/$files$format?login=$login&pass=$pass&email=$email&name=$name&famil=$famil&skype=$skype&ip=$ip2"); 
    MessageBox("$data", "Ответ с сервера"); 
    }else{ 
    messageDlg("Пароли не совпадают!", mtWarning, MB_OK);}

    Вот такая незамысловатая регистрация на сервере. GET запросом с использованием file_get_contents. Ну и конечно же серверу надо обязательно отправить свой ip.

    any0ne2567, 17 Апреля 2014

    Комментарии (22)
  7. Java / Говнокод #15661

    +65

    1. 1
    2. 2
    3. 3
    4. 4
    Graphics2D g = ...;
    String str = "Some string";
    FontRenderContext frc = g.getFontRenderContext();
    double height = g.getFont().createGlyphVector(frc, str).getPixelBounds(null, 0, 0).getHeight();

    Мне нужно было узнать точную высоту строки, которую я рисую на объекте Image. Спасибо stackoverflow за то, что он есть, по-моему, до этого способа просто невозможно догадаться, даже копая документацию, за несколько часов...

    evg_ever, 03 Апреля 2014

    Комментарии (22)
  8. Си / Говнокод #15628

    +136

    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
    #include <stdio.h>
    #include <inttypes.h>
    
    inline uint8_t mid_ch (uint8_t a, uint8_t b, uint8_t res)
    {
      if (b == 0){ if (a >= 2) return mid_ch (a-2, b  , res+1); else return res;}
      if (a == 0){ if (b >= 2) return mid_ch (a  , b-2, res+1); else return res;}
      return mid_ch (a-1, b-1, res+1);
    }
    
    uint64_t mid_0_ch (uint64_t a, uint64_t b)
    {
      return mid_ch(a, b, 0);
    }
    
    
    int main(void)
    {
      printf("%u %u", mid_0_ch (253, 123), (253+123)/2);
      return 0;
    }

    Нахождение среднего арифметического двух чисел через рекурсию. Сначала сделал для uint64_t чтобы это имело смысл, ведь сложение двух 64-битных чисел с записью результата в третье может привести к целочисленному переполнению (для 64-битных чисел, сложение которых может привести к переполнению, этот код работал чрезвычайно медленно, поэтому я ограничился 8-битными). При таком наркоманско-рекурсивном алгоритме этого переполнения не будет. 128-битные типы есть только как нестандартное расширение, но тогда еще возникает вопрос, как найди среднее арифметическое двух таких 128-битных чисел? А если есть 256-битные, то как тогда их них находить среднеарифметическое... ну и так далее.
    Можно эту проблему еще решать через битовые маски т.е. убрать из обеих чисел самые старшие биты (предварительно сохранив их), сложить эти два числа, поделить на два, потом уже эти сохраненные биты вида 10000... или 0000... оба поделить на 2(сдвинуть на один разряд) и прибавить. Наркоманство какое-то.
    Почему бы не сделать в С некий особый целочисленный тип, в котором любая фигня влезет, но который бы использовался только временно для промежуточных вычислений, чтобы не делать бэкапы битиков всяких?

    j123123, 31 Марта 2014

    Комментарии (22)
  9. Assembler / Говнокод #15608

    +137

    1. 001
    2. 002
    3. 003
    4. 004
    5. 005
    6. 006
    7. 007
    8. 008
    9. 009
    10. 010
    11. 011
    12. 012
    13. 013
    14. 014
    15. 015
    16. 016
    17. 017
    18. 018
    19. 019
    20. 020
    21. 021
    22. 022
    23. 023
    24. 024
    25. 025
    26. 026
    27. 027
    28. 028
    29. 029
    30. 030
    31. 031
    32. 032
    33. 033
    34. 034
    35. 035
    36. 036
    37. 037
    38. 038
    39. 039
    40. 040
    41. 041
    42. 042
    43. 043
    44. 044
    45. 045
    46. 046
    47. 047
    48. 048
    49. 049
    50. 050
    51. 051
    52. 052
    53. 053
    54. 054
    55. 055
    56. 056
    57. 057
    58. 058
    59. 059
    60. 060
    61. 061
    62. 062
    63. 063
    64. 064
    65. 065
    66. 066
    67. 067
    68. 068
    69. 069
    70. 070
    71. 071
    72. 072
    73. 073
    74. 074
    75. 075
    76. 076
    77. 077
    78. 078
    79. 079
    80. 080
    81. 081
    82. 082
    83. 083
    84. 084
    85. 085
    86. 086
    87. 087
    88. 088
    89. 089
    90. 090
    91. 091
    92. 092
    93. 093
    94. 094
    95. 095
    96. 096
    97. 097
    98. 098
    99. 099
    100. 100
    ascdec proc near
    mov di,0
    mov si,0
    xor dx,dx
    mov bx,offset buf
    add bx,10
    mov cx,11
    lo0:
    dec bx
    dec cx
    jcxz ex0
    mov al,[bx]
    cmp al,255
    je lo0
    lo1:
    sub al,30h 
    push bx
    push cx
    mov bx,offset deci
    xor dx,dx
    mov cx,word ptr[bx+2]
    mov bx,word ptr[bx]
    mov ah,0
    call mult32 
    add di,ax
    adc si,dx
    mov bx,offset deci
    mov ax,[bx]
    mov dx,[bx+2]
    call multen
    mov bx,offset deci
    mov [bx],ax
    mov [bx+2],dx
    pop cx
    pop bx
    dec bx
    dec cx
    jcxz ex0
    mov al,[bx]
    jmp lo1
    ex0:
    mov ax,di
    mov dx,si
    test dx,8000h
    jz enda
    jmp error
    enda:
    cmp minus,2dh
    jne pl1
    call ccc
    pl1:
    ret
    ascdec endp
    multen proc near
    push bx
    push cx
    mov bx,10
    mov cx,0
    call mult32
    pop cx
    pop bx
    ret
    multen endp
    mult32 proc near 
    push si
    push di
    push dx
    push ax
    test dx,8000h 
    jz ml
    call ucc
    push dx
    push ax
    ml:
    mov dx,cx
    mov ax,bx
    test dx,8000h  
    jz ml0
    call ucc 
    mov bx,ax
    mov cx,dx
    ml0:
    pop ax
    pop dx
    mov si,0
    mov di,0
    mul bx ;AX*BX
    mov di,ax
    mov si,dx
    pop ax
    mul cx ;AX*CX
    add si,ax
    pop dx
    ucc proc near
    dec ax
    sbb dx,0
    not ax
    not dx
    ret
    ucc endp

    Превращение строки в число.

    Abbath, 27 Марта 2014

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

    +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
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    // функция квадрата расстояния на гексагональном поле
    Fixed SDist2 (Fixed dx, Fixed dy)
    {
    	return (dx*dx+dy*dy+dx*dy);
    }
    
    // а теперь типа находим ближайшее целое, ближайшее в гексагональном смысле
          const Fixed rx = int(rtx), ry = int(rty);
    			const Fixed 
    				d00 = SDist2(rx    -rtx, ry    -rty),
    				d10 = SDist2(rx+fx1-rtx, ry    -rty),
    				d01 = SDist2(rx    -rtx, ry+fx1-rty),
    				d11 = SDist2(rx+fx1-rtx, ry+fx1-rty);
    
    			int x,y;
    			if (d00<d10 && d00<d01 && d00<d11) 
    			{
    				x=int(rx); y=int(ry);
    			} else if (d10<d01 && d10<d11)
    			{
    				x=int(rx)+1; y=int(ry);
    			} else if (d01<d11)
    			{
    				x=int(rx); y=int(ry)+1;
    			} else
    			{
    				x=int(rx)+1; y=int(ry)+1;
    			}

    изящно не получилось

    TarasB, 18 Марта 2014

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

    +15

    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
    #include <iostream>
    #include <string>
    #include <vector>
    #include <list>
    #include <algorithm>
    #include <iterator>
    #include <sstream>
    #include <assert.h>
    using namespace std;
    template<class Container, class Iterator> 
    size_t position(Container&& c, Iterator pos){
        return size_t(distance(begin(c), pos));
    }
    template<class Container, class Iterator, class Iterator2> 
    string sposition(Container&& c, const pair<Iterator, Iterator2>& pos){
        ostringstream r;
        r << "(" << position(c, pos.first) << ", " << position(c, pos.second) << ")";
        return r.str();
    }
    template<class Container, class Value> 
    pair<typename remove_reference<Container>::type::iterator, typename remove_reference<Container>::type::iterator>
     binary_search(Container&& source, const Value& item){
        assert(is_sorted(begin(source), end(source)));
        const auto empty = make_pair(source.end(), source.end());
        auto l = begin(source), r=end(source), m=l;
        while(true){
            if(l==r)
                return empty;
            const auto lr = distance(l,r);
            m = next(l, lr/2);
            if(*m<item)
                l = m;
            if(*m>item)
                r = m;
            if(*m==item)
                break;
            if(l!=r && next(l)==r)
                return empty;
        }
        cout<<"part1"<<endl;
        auto l1=l, r1=m, l2=m, r2=r;
        while(true){
            const auto lr1 = distance(l1, r1);
            m = next(l1, lr1/2);
            if(*m<item)
                l1 = m;
            if(*m>=item)
                r1 = m;
            if(l1==r1 || (*l1<item && *r1>=item))
                break;
        }
        cout<<"part2"<<endl;
        while(true){
            const auto lr2 = distance(l2, r2);
            m = next(l2, lr2/2);
            if(*m<=item)
                l2 = m;
            if(*m>item)
                r2 = m;
            if(l2==r2 || (*l2>=item && (r==r2 || *r2>item)))
                break;
        }
        cout<<"part3"<<endl;
        return {r1, next(l2)};
    }
    int main(){
        vector<int> s{5,7,7,7,9,19,23};
        list<int> s2(s.begin()+1, s.end());
        cout<<sposition(s, binary_search(s, 7))<<endl;
        cout<<sposition(s2, binary_search(s2, 7))<<endl;
        cout<<sposition(s, binary_search(s, 9))<<endl;
        cout<<sposition(s, binary_search(s, 5))<<endl;
        cout<<sposition(s, binary_search(s, 23))<<endl;
        cout<<sposition(s, binary_search(s, 0))<<endl;
        vector<int> e;
        cout<<sposition(e, binary_search(e, 0))<<endl;
        cout<<sposition(s, binary_search(s, 25))<<endl;
        cout<<sposition(s, binary_search(s, 10))<<endl;
        return 0;
    }

    http://coliru.stacked-crooked.com/a/0f74a4661c06cd68
    Специально для @Пи, раз ему хачкель не нравится.

    LispGovno, 14 Марта 2014

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