1. C# / Говнокод #7621

    +116

    1. 1
    2. 2
    repositoryBugzilla.Open();
    repositoryBugzilla.Close();

    Вот такой код я нашел у себя в проекте.

    abbbbbbbbbb, 23 Августа 2011

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

    +163

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    // ����� �������� � �������
        if (!function_exists('indexOf')) {
            function indexOf($needle, $haystack) {
                for($i = 0; $i < count($haystack); $i++) {
                    if ($haystack[$i] == $needle) {
                        return true;
                    }
                }
                return false;
            }
        }

    По просьбе трудящихся... (#7616)
    Кто угадает, что это за функция?
    Ответ: это велосипедная конструкция-заменитель in_array

    xStream, 23 Августа 2011

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

    +137

    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
    xxx: Скажите пожалуйста нубоюзеру, как в сишарпе извлечь корень определённой степени?
    yyy: http://msdn.microsoft.com/ru-ru/library/system.math.sqrt.aspx (Math.Sqrt, Возвращает квадратный корень из указанного числа.)
    xxx: Спасибо, но желательно бы не только >квадратный< корень, но и заданной степени.
    yyy: Делай через циклы или рекурсивно.
    double SuperSquare(double number, int n)
    {
     double result = number;
     for(int i = 0; i < n; i++)
     {
     result = Math.Sqrt(result)
     }
     return result;
    }
    // Както так

    Инновационный способ вычислять корень заданной степени.

    flawy, 23 Августа 2011

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

    −86

    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
    #Ханойские башни, для ручного решения.
    
    start = [3,2,1]
    a, b, c = [s for s in start], [], []
    
    def printTower( n ):
      s = ''
      if n.lower() == 'a':
        s = a
      elif n.lower() == 'b':
        s = b
      elif n.lower() == 'c':
        s = c
      else:
        raise
      print(n.upper()+':',s)
    
    def printTowers():
      printTower('a')
      printTower('b')
      printTower('c')
    
    def getLast( n ):
      if n.lower() == 'a':
        return 1000 if len(a)==0 else a[-1]
      elif n.lower() == 'b':
        return 1000 if len(b)==0 else b[-1]
      elif n.lower() == 'c':
        return 1000 if len(c)==0 else c[-1]
      else:
        raise
    
    def getTower( n ):
      if n.lower() == 'a':
        return a
      elif n.lower() == 'b':
        return b
      elif n.lower() == 'c':
        return c
      else:
        raise
    
    def moveTower():
      fromP = input('С какой башни двигать?').lower()
      toP = input('На какую башню двигать?').lower()
      lastF = getLast(fromP)
      lastT = getLast(toP)
      if lastT>lastF:
        getTower(toP).append(getTower(fromP).pop())
      else:
        raise
      printTowers()
    
    printTowers()
    
    while b!=start:
      moveTower()

    Принял слабого снотворного и сел читать Корнилова (Программирование шахмат и других логических игр) (думал быстро усну, книга очень скучная).
    Когда пришёл в себя увидел на экране ЭТО.
    P.S. Оно работает.

    Fai, 23 Августа 2011

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

    +156

    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
    <?php
    	include_once "database.php";
    	
    	$db = NewPDO();
    	$search = $db->prepare("SELECT w.wine_name as wine_name, w.year as wine_year, gv.variety as wine_variety, wn.winery_name as winery_name,r.region_name as region_name
    							FROM wine w
    							JOIN wine_variety wv ON w.wine_id = wv.wine_id
    							JOIN grape_variety gv ON wv.variety_id = gv.variety_id
    							JOIN winery wn ON w.winery_id = wn.winery_id JOIN region r ON wn.region_id = r.region_id
    							WHERE w.wine_name LIKE :in_wine_name AND wn.winery_name LIKE :in_winery_name AND r.region_name LIKE :in_region_name
    							ORDER BY w.wine_name ASC , w.year ASC , gv.variety ASC");
    	$wine_name = '%'.htmlspecialchars($_GET["wine"]).'%';
    	$winery_name = '%'.htmlspecialchars($_GET["winery"]).'%';
    	$region = '%'.htmlspecialchars($_GET["region"]).'%';
    	
    	$search->bindValue(':in_wine_name',$wine_name,PDO::PARAM_STR);
    	$search->bindValue(':in_winery_name',$winery_name,PDO::PARAM_STR);
    	$search->bindValue(':in_region_name',$region,PDO::PARAM_STR);
    	
    	$search->execute();
    	echo "<table>";
    	if ($search->columnCount() > 0)
    	{
    		echo "<tr align=\"center\">
    				<th>
    					Wine
    				</th>
    				<th>
    					Year
    				</th>
    				<th>
    					Variety
    				</th>
    				<th>
    					Winery
    				</th>
    				<th>
    					Region
    				</th>
    			  </tr>";
    		while($row = $search->fetch())
    		{
    			echo "<tr align=\"left\">
    					<td width=\"80\">
    						".$row["wine_name"]."
    					</td>
    					<td width=\"50\">
    						".$row["wine_year"]."
    					</td>
    					<td width=\"90\">
    						".$row["wine_variety"]."
    					</td>
    					<td width=\"230\">
    						".$row["winery_name"]."
    					</td>
    					<td>
    						".$row["region_name"]."
    					</td>
    				  </tr>";
    		}
    		echo "<tr>
    			  	<td colspan=\"5\">
    					".$search->rowCount()." records found matching your criteria.
    				</td>
    		      </tr>";
    	}
    	else
    	{
    		echo "<tr><td>No records match your search criteria</td></tr>";
    	}
    	echo "</table>";
    ?>

    Вот такой вот полнотекстовый поиск с выводом результата

    denis90, 23 Августа 2011

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

    +170

    1. 1
    include($b2bcontext_path."modules/"."costyl".".php");

    Самое интересное - инклюд безусловный. Он просто есть. Костыль - он такой костыль...

    xStream, 22 Августа 2011

    Комментарии (25)
  7. Objective C / Говнокод #7615

    −112

    1. 1
    2. 2
    3. 3
    4. 4
    - (void)applicationDidReceiveMemoryWarning:(UIApplication *)application
    {
        [KQCache clearCache];
    }

    memory warning?
    значит надо очистить, и пох какая memory!

    huibla, 22 Августа 2011

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

    +163

    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
    function hideblock(elemid) {
    $('#'+elemid).fadeOut(300);
    setCookie(elemid,'hidden',365);
    $('#i_restore').fadeIn(300);
    }
    
    function restoreblock() {
    $('#i_blog').fadeIn(300);
    $('#i_search').fadeIn(300);
    $('#i_chat').fadeIn(300);
    $('#i_stat').fadeIn(300);
    $('#i_links').fadeIn(300);
    $('#i_tags').fadeIn(300);
    eraseCookie('i_blog');eraseCookie('i_search');eraseCookie('i_chat');eraseCookie('i_stat');eraseCookie('i_links');eraseCookie('i_tags');
    $('#i_restore').fadeOut(300);
    }
    
    
    
    ------------
    
    
    
    
    if (getCookie('i_blog')=='hidden') {$('#i_blog').hide();};
    if (getCookie('i_search')=='hidden') {$('#i_search').hide();};
    if (getCookie('i_chat')=='hidden') {$('#i_chat').hide();};
    if (getCookie('i_stat')=='hidden') {$('#i_stat').hide();};
    if (getCookie('i_links')=='hidden') {$('#i_links').hide();};
    if (getCookie('i_tags')=='hidden') {$('#i_tags').hide();};
    if (!(getCookie('i_links')=='hidden')&&!(getCookie('i_blog')=='hidden')&&!(getCookie('i_stat')=='hidden')&&!(getCookie('i_chat')=='hidden')&&!(getCookie('i_search')=='hidden')&&!(getCookie('i_tags')=='hidden')) {$('#i_restore').hide();};

    Nuff said

    satan, 22 Августа 2011

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

    +150

    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
    // don't show any errors to end user
    error_reporting(0);
    	
    // error handler function
    function my_error_handler($errno, $errstr, $errfile, $errline) {
    		
        $date = date('d/M/Y:H:i:s O');
    		
        // \r\n for cozy look on win machines
        $error_str = "{$date} | [error] #{$errno}: {$errfile}:{$errline} {$errstr} \r\n";
    		
        // *.txt for win machines
        error_log($error_str, 3, 'C:\AppServ\www\error_log.txt');
    		
        // don't execute php internal error handler
        return true;
    }
    
    set_error_handler('my_error_handler');
    	
    // throws error
    echo date();

    Рубрика: Советы от Говнокода.
    В связи с #7594. Fatal errors не ловит (пхп, хуле), но их и не нужно показывать пользователю, все остальные ошибки пишем в лог на сервер.
    Ошибка в логе выглядит так:
    21/Aug/2011:16:50:52 +0000 | [error] #2: C:\AppServ\www\4.php:22 date() expects at least 1 parameter, 0 given

    Yurik, 21 Августа 2011

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

    +161

    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
    int b;
    int c();
    
    template<class u, class v>
    struct IsSameType
    {
    	enum {r=0};
    };
    
    template<class u>
    struct IsSameType<u,u>
    {
    	enum {r=1};
    };
    
    //...
    cout<<IsSameType<decltype(b),decltype(c())>::r<<endl;
    cout<<IsSameType<decltype(b),decltype((b))>::r<<endl;
    cout<<IsSameType<decltype(c()),decltype((b))>::r<<endl;

    Сегодня увидим новую плюшку, что нам подарил новый стандарт С++0х.
    1)Что на экране получим после выполнения данной программы?
    2)Какие реально decltype возвращает типы в данных случаях?
    Желательно ответить на оба вопроса, не компилируя. ^_^

    Говногость, 21 Августа 2011

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