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

    +145

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    if (users.ToList().Count == 0)
    {
              return true;
    }
    else
    {
              return false;
    }

    Mikita, 23 Ноября 2010

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

    +155

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    9. 9
    void XmlElementHandler::startElement(
                        const XMLCh* const uri,
                        const XMLCh* const localname,
                        const XMLCh* const qname,
                        const XERCES_CPP_NAMESPACE_QUALIFIER Attributes& attrs
                        )
    {
      static XmlContext *context = XmlContext::getInstance();
      static XmlParser *parser = XmlParser::getInstance();

    оптимизируем обращения к синглтонам. потому что одной невидимой глобальной переменной явно не достаточно. вот такое щасце в 30+ методах на реализации интерфейса к Xerces-C.

    Dummy00001, 23 Ноября 2010

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

    +179

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    if(
        (s.Find("/0")!=-1)||
        (s.Find("Log10(-")!=-1)||
        (s.Find("Log10(0")!=-1))//stupid user error
    {
    }

    Проверка, есть ли в формуле, введенной пользователем, деление на 0, логарифм от отрицательного числа или логарифм от нуля. Стиль и комментарии автора сохранены.

    Shumway, 23 Ноября 2010

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

    +165

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    9. 9
    //Set different text depending on how long on progressbar progress is
    if (dwStepPercent < 25)
        byText=0;
    else if (dwStepPercent < 50)
        byText=1;
    else if (dwStepPercent < 75)
        byText=2;
    else
        byText=3;

    Отличный способ не делить.

    Shumway, 23 Ноября 2010

    Комментарии (2)
  5. SQL / Говнокод #4721

    −849

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    9. 9
    -- Очищаем поле [PlanItemCodeNorm] от всех записей содержащих не цифры и точку
    UPDATE PIM SET [PlanItemCodeNorm] = ''
    -- SELECT PIM.*
    FROM [dbo].[PlanItem] PIM
    WHERE [PlanItemCodeNorm] <> ''
        AND REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
            REPLACE([PlanItemCodeNorm], '.', '' )
            , '0', '' ), '1', '' ), '2', '' ), '3', '' ), '4', '' ), '5', '' ), '6', '' ), '7', '' ), '8', '' ), '9', ''), '*', '' )
            <> ''

    ....

    HellMaster_HaiL, 23 Ноября 2010

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

    −181

    1. 1
    function hilight { python2 -c 'import sys, re; map(lambda s: sys.stdout.write(re.sub(r"'$1'", lambda m: "\033[1;31m%s\033[0m" % m.group(0), s)), sys.stdin)' }

    Это в Python или в bash?

    ___, 23 Ноября 2010

    Комментарии (1)
  7. C++ / Говнокод #4719

    +155

    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
    /* use <first> of a [std::pair] */
    template<typename _type_, typename _pred_>
    struct use_first {
    	use_first(_type_ val, _pred_ pred) { value = val; predicate = pred; }
    	
    	template<typename _first_type_, typename _second_type_>
    	bool operator()(const std::pair<_first_type_, _second_type_> &pr)
    	{
    		return predicate(pr.first, value);
    	}
    
    private:
    	_type_ value;
    	_pred_ predicate;
    };
    
    /* factory function: use it to init a [use_first] object */
    template<typename _type_, typename _pred_>
    use_first<_type_, _pred_> make_use_first(_type_ value, _pred_ pred)
    {
    	return use_first<_type_, _pred_>(value, pred);
    }
    
    /* usage of [use_first] */
    std::vector< std::pair<int, int> > lol;
    std::vector< std::pair<int, int> >::iterator = std::find_if(lol.begin(), lol.end(), make_use_first(0, std::equal_to()));

    собственно была проблема в том, что в контейнерах(например std::vector, std::deque) хранятся пары(std::pair) и зачастую нужно организовать какие-либо действия либо по первому(first), либо по второму(second) члену из std::pair.
    приведен код только для first, ибо код для second немного похож

    в итоге получилось сие поделие, а еще я люблю обмазаться несвежим....

    Govnoeb, 23 Ноября 2010

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

    +160

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    ob_start();
    $goodsInterested = clone Core::$Controllers->Helpers->Good_Recomendation;
    $goodsInterested->display(array(
    	"modelId" => $this->model['id'],
    	"type" => 'interested',
    ));
    $interested = ob_get_clean();

    В системе виджеты - синглтоны.
    Чтобы как-то хоть работать, клонируем синглтон (!!!)
    Результат приходится оборачивать в ob_start, т.к не предусмотрено ничего типа echo $widget->render();

    mitallast, 23 Ноября 2010

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

    +114

    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
    Ссылка ниже, там много всего, наиболее яркие моменты:
    1. 
    String Conn = (String)((NameValueCollection)Context.GetConfig("system.web/dsnstore"))["sql_site"];
    
    2. 
    qGetSum = new SqlCommand("select abs(ISNULL(sum(doc_bonus),0)) from vdoc where card_id = " + Session["card_id"] + " and dbo.Get_storno(doc_id) = 1", cGetSum);
    
    3. 
    SqlConnection cDiscount2 = new SqlConnection(Conn);
    SqlConnection cDiscount3 = new SqlConnection(Conn);
    
    4.
     log.Text = "Вы определены как:<br><b>" + Session["login"] + "<br><br></b>Бонус:<b>" + Session["bonus"] + "<br><br><a href=\"default.aspx?page=cardedit\">Личная карточка</a></b><br><br>";
    
    5. 
    Имена переменных: card_prefix, error_login_count, logoCMD, 
    
    6. 
    Session["access"] = 1;
    Session["access"] = -1;
    Session["access"] = -2;

    http://www.cyberforum.ru/asp-net/thread195915.html

    HIMen, 23 Ноября 2010

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

    +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
    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
    $extentions = array('1','2','3','6'); # определяем типы разрешенных файлов
    $Filedatasize = $_FILES['Filedata']['size']; 
    $width = 200; # Максимальная ширина миниатюры
    $height = 160;	# Максимальная высота миниатюры
    $file_type = exif_imagetype($_FILES['Filedata']['tmp_name']); # определяем тип файла
    if (in_array($file_type, $extentions) && ($maxfilesize >= $Filedatasize)){
    	switch ($file_type) {
    		case '2': $file_type = '.jpg'; break;
    		case '3': $file_type = '.png'; break;
    		case '1': $file_type = '.gif'; break;			
    		case '6': $file_type = '.bmp'; break;
    	}
    	if ($_POST['select_catalog'] > 0){
    		mysql_query("INSERT INTO `images` (`id_catalog`) VALUES ('".$_POST['select_catalog']."');") or die("MySQL Error: " . mysql_error());
    	} else {
    		 mysql_query("INSERT INTO `images` (`image_title`) VALUES (' ');") or die("MySQL Error: " . mysql_error());
    	}
    	$image_id = mysql_insert_id();
    	mysql_query("UPDATE `images` SET `image_name_d` = '".$image_id.$file_type."', `image_name_s` = '".$image_id."_m".$file_type."' WHERE `images`.`id_images` = ".$image_id.";") or die("MySQL Error: " . mysql_error());
    	$image_mini = $image_id.'_m'.$file_type;
    	$image_normal = $image_id.$file_type;
    	
    	$ext = $file_type; # Получаем формат уменьшаемого изображения
    	list($width_orig, $height_orig) = getimagesize($_FILES['Filedata']['tmp_name']); # получаем размеры изображения
    	
    	#высчитываем 
    	$ratio_orig = $width_orig/$height_orig;		
    	if ($width/$height > $ratio_orig) {
    		$width = $height*$ratio_orig;
    	} else {
    		$height = $width/$ratio_orig;
    	}
    	$image_p = imagecreatetruecolor($width, $height);
    	switch ($ext) {
    		case '.jpg': $source = imagecreatefromjpeg($_FILES['Filedata']['tmp_name']); break;
    		case '.gif': $source = imagecreatefromgif($_FILES['Filedata']['tmp_name']); break;
    		case '.png': $source = imagecreatefrompng($_FILES['Filedata']['tmp_name']); break;			
    		case '.bmp': $source = imagecreatefromwbmp($_FILES['Filedata']['tmp_name']); break;
    	}
    	imagecopyresampled($image_p, $source, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
    	switch ($ext) {
    		case '.jpg': imagejpeg($image_p, 'gallery/'.$image_mini, 100); break;                
    		case '.gif': imagegif($image_p, 'gallery/'.$image_mini);  break;                
    		case '.png': imagepng($image_p, 'gallery/'.$image_mini); break;                
    		case '.bmp': imagewbmp($image_p, 'gallery/'.$image_mini); break;
    	}
    	
    	# освобождаем память
    	imagedestroy($image_p);
    	imagedestroy($source);	
    	if (($width_orig >= 1600) or ($height_orig >= 1200)) {
    		$width = 1600; # Максимальная ширина
    		$height = 1200;	# Максимальная высота
    		$ratio_orig = $width_orig/$height_orig;		
    		if ($width/$height > $ratio_orig) {
    			$width = $height*$ratio_orig;
    		} else {
    			$height = $width/$ratio_orig;
    		}
    		$image_p = imagecreatetruecolor($width, $height);
    		switch ($ext) {
    			case '.jpg': $source = imagecreatefromjpeg($_FILES['Filedata']['tmp_name']); break;
    			case '.gif': $source = imagecreatefromgif($_FILES['Filedata']['tmp_name']); break;
    			case '.png': $source = imagecreatefrompng($_FILES['Filedata']['tmp_name']); break;			
    			case '.bmp': $source = imagecreatefromwbmp($_FILES['Filedata']['tmp_name']); break;
    			}
    		imagecopyresampled($image_p, $source, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
    			switch ($ext) {
    				case '.jpg': imagejpeg($image_p, 'gallery/'.$image_normal, 100); break;                
    				case '.gif': imagegif($image_p, 'gallery/'.$image_normal);  break;                
    				case '.png': imagepng($image_p, 'gallery/'.$image_normal); break;                
    				case '.bmp': imagewbmp($image_p, 'gallery/'.$image_normal); break;
    			}
    		
    		# освобождаем память
    		imagedestroy($image_p);
    		imagedestroy($source);
    			
    	} else {
    		move_uploaded_file($_FILES['Filedata']['tmp_name'], 'gallery/'.$image_normal);
    	}
    }	
    chmod('gallery/' . $image_normal, 0777);
    $return['src'] = 'gallery/' . $image_normal;

    ZekMan, 23 Ноября 2010

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