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

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

    +68

    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
    /*
        * Todo Гавнокод
        * Надо как то поуниверсальнее сделать
        * А то когда модель вмешавается в отображение, это криворукость
        */
        private static String ___recurGet(Dir dir){
            MorphiaQuery dirs = dir.getDirList();
            String  id = dir.getIdAsStr(),
                    name = dir.name;
    
            String html = "<div class=\"bottom-line\">";
            html += "<a href=\"#\" onclick=\"setPrnt('"+id+"')\" id=\""+id+"\">";
            html += name;
            html += "</a>";
            html += "<div class=\"pull-right\">";
            html += "<a href=\"#\" class=\"icon-trash\" onclick=\"deleteNode('"+id+"')\"></a>";
            html += "</div>";
            html += "</div>";
    
            if(dirs.count() < 1)
                return html;
    
            html += "<ul>";
            for(int i = 0; i < dirs.count(); i++){
                html += "<li>";
                html += ___recurGet((Dir)dirs.offset(i).first());
                html += "</li>";
            }
            html += "</ul>";
            return html;
        }
    
        public static String getTreeAsHtml(String _typ){
            MorphiaQuery dirs = getRootDirList().filter("typ",Type.valueOf(_typ));
    
            if(dirs.count() < 1)
                return "Категорий нет";
    
            String html = "<ul id=\"treeView\">";
            for(int i = 0; i < dirs.count(); i++){
                html += "<li>";
                html += ___recurGet((Dir)dirs.offset(i).first());
                html += "</li>";
            }
            html += "</ul>";
            return html;
        }

    В модели "категория" написал метод для получения дерева категории в виде html кода...
    Причем такая генерация должна происходить в view, а сделал как обычно через ж

    haker, 21 Декабря 2012

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

    +54

    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
    function validEmail($email)
    {
    	$isValid = true;
    	$atIndex = strrpos($email, "@");
    	if (is_bool($atIndex) && !$atIndex) {
    		$isValid = false;
    	} else {
    		$domain = substr($email, $atIndex + 1);
    		$local = substr($email, 0, $atIndex);
    		$localLen = strlen($local);
    		$domainLen = strlen($domain);
    		if ($localLen < 1 || $localLen > 64) {
    			// local part length exceeded
    			$isValid = false;
    		} else if ($domainLen < 1 || $domainLen > 255) {
    			// domain part length exceeded
    			$isValid = false;
    		} else if (!strrpos($domain, ".")) {
    			// domain part does not have .
    			$isValid = false;
    		} else if ($domain[0] == '.' || $domain[$domainLen - 1] == '.') {
    			// domain part starts or ends with '.'
    			$isValid = false;
    		} else if ($local[0] == '.' || $local[$localLen - 1] == '.') {
    			// local part starts or ends with '.'
    			$isValid = false;
    		} else if (preg_match('/\\.\\./', $local)) {
    			// local part has two consecutive dots
    			$isValid = false;
    		} else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) {
    			// character not valid in domain part
    			$isValid = false;
    		} else if (preg_match('/\\.\\./', $domain)) {
    			// domain part has two consecutive dots
    			$isValid = false;
    		} else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\", "", $local))) {
    			// character not valid in local part unless 
    			// local part is quoted
    			if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\", "", $local))) {
    				$isValid = false;
    			}
    		}
    		/* if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A"))) {
    		  // domain not found in DNS
    		  $isValid = false;
    		  } */
    	}
    	return $isValid;
    }

    Интересно а автор когдата слишал про filter_var?
    Это все можна заменить на filter_var($input, FILTER_VALIDATE_EMAIL);
    Товаришь программист! Не умеешь срать - не мучай жопу!

    v_anonym, 19 Декабря 2012

    Комментарии (4)
  4. 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)
  5. PHP / Говнокод #12123

    +54

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    $postitle = str_replace (' ', '-', $title);
    				$postitle = str_replace ('/', '', $postitle);
    				$postitle = str_replace ('\\', '', $postitle);
    				$postitle = str_replace (':', '', $postitle);
    				$postitle = str_replace ('<', '', $postitle);
    				$postitle = str_replace ('>', '', $postitle);
    				$postitle = str_replace ('*', '', $postitle);
    				$postitle = str_replace ('?', '', $postitle);
    				$postitle = str_replace ('|', '', $postitle);
    				$postitle = str_replace ('"', '', $postitle);
    				$postitle = preg_replace ('#\[.*?\]#isu', '', $postitle);

    aleksey, 14 Ноября 2012

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

    +43

    1. 1
    2. 2
    3. 3
    4. 4
    public static function create(AdGroupVO $vo)
    {
        UtilLog::debug('FUCK');
        ...

    avixyu, 08 Ноября 2012

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

    +160

    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
    jQuery('#text div.catalog_light div.num input[type="text"]').spinner({max: 999, min: 1});
    jQuery('#text div.catalog_light div.num .ui-spinner-up').html('').css({'width' : '22px'}).css({'height' : '22px'});
    jQuery('#text div.catalog_light div.num .ui-spinner-down').html('').css({'width' : '22px'}).css({'height' : '22px'});
           
    jQuery('#text div.catalog_item_right div.line div.spinner input[type="text"]').spinner({max: 999, min: 1});
    jQuery('#text div.catalog_item_right div.line div.spinner .ui-spinner-up').html('').css({'width' : '22px'}).css({'height' : '22px'});
    jQuery('#text div.catalog_item_right div.line div.spinner .ui-spinner-down').html('').css({'width' : '22px'}).css({'height' : '22px'});
           
    jQuery('#text div.catalog_item_additional div.double table div.spinner input[type="text"]').spinner({max: 999, min: 1});
    jQuery('#text div.catalog_item_additional div.double table div.spinner .ui-spinner-up').html('').css({'width' : '22px'}).css({'height' : '22px'});
    jQuery('#text div.catalog_item_additional div.double table div.spinner .ui-spinner-down').html('').css({'width' : '22px'}).css({'height' : '22px'});
           
    jQuery('#text div.catalog div.content div.text div.spinner input[type="text"]').spinner({max: 999, min: 1});
    jQuery('#text div.catalog div.content div.text div.spinner .ui-spinner-up').html('').css({'width' : '22px'}).css({'height' : '22px'});
    jQuery('#text div.catalog div.content div.text div.spinner .ui-spinner-down').html('').css({'width' : '22px'}).css({'height' : '22px'});

    Zapix, 02 Ноября 2012

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

    +175

    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
    public static IEnumerable<float> Single(float from, float to, float step)
            {
                if (step <= 0.0f) step = (step == 0.0f) ? 1.0f : -step;
     
                if (from <= to)
                {
                    for (float f = from; f <= to; f += step) yield return f;
                }
                else
                {
                    for (float f = from; f >= to; f -= step) yield return f;
                }
            }
     
    public static IEnumerable<double> Double(double from, double to, double step)
            {
                if (step <= 0.0) step = (step == 0.0) ? 1.0 : -step;
     
                if (from <= to)
                {
                    for (double d = from; d <= to; d += step) yield return d;
                }
                else
                {
                    for (double d = from; d >= to; d -= step) yield return d;
                }
            }

    Такие методы накопированы для всех типов данных, которые известны поциенту.
    Но особо интересны эти джва метода

    Unlike some other programmimg languages (notably F#), C# doesn't have any built-in support for dealing with ranges of numbers. The .NET Framework does have the Enumerable.Range() method.
    - It can only deal with Int32's.
    - You can't specify a 'step' from one element of the range to the next. In effect, the step is always one. In this article, I'd therefore like to present a static Range class to deal with these deficiencies.

    http://www.c-sharpcorner.com/uploadfile/b942f9/dealing-with-ranges-of-numbers-in-C-Sharp

    3.14159265, 26 Октября 2012

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

    +63

    1. 1
    Лех, разве код <?php  CREATE DATABASE tbl_name; ?> не должен создать БД?

    Пришло в аське

    kindofbear, 18 Октября 2012

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

    +34

    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
    void
    XmlRpcDispatch::work(double timeout)
    {
        ...
        nEvents = select(maxFd+1, &inFd, &outFd, &excFd, NULL);
        ...
    }
    
    void XmlRpcDispatch::terminate() {
        ...
        XmlRpcSocket::connect(_cmd_sock, "127.0.0.1", port);
        ...
    }

    Не то чтобы говнокод, но забавный костыль. А как еще корректно выйти из select'a, ждущего входящих соединений? Создать соединение самому.

    Steve_Brown, 12 Октября 2012

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

    −102

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
           obj_l = list()
            for obj, obj_id in [(QuizQuestion, quest_id), (QuizAssigment, ass_id), (QuizQuestionAnswer, answ_id)]:
                q_set = getattr(getattr(obj, 'objects'), 'filter')(id=obj_id)
                obj_l.append(getattr(q_set, 'count')() > 0 and q_set[0] or False)
            (False in obj_l or obj_l[2].question != obj_l[0] or (user and obj_l[0].user)) and abort(IntegrityError())

    1) хер такое прочтешь
    2) для осмысления прочитанного нужно выпить
    3) за осмысление такого нужно выпить еще раз
    4) чувак узнал про getattr, хотя стоило вызвать напрямую obj.objects.filter(id=obj_id)
    5) q_set.count() > 0 and q_set[0] or false
    пятая строка поддается пониманию но катастрофически быстро начинает от этого терять смысл

    nimnull, 12 Октября 2012

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