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

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

    +146

    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
    getInsideText($part1[0],'<string>','</string>',1,true);
    
    function getInsideText($str,$fstr,$lstr,$limit=0,$trim=true){
        $temp_arr=array();
        $lcnt=0;
        while(strpos($str,$fstr)!==false && ($limit ? $lcnt<$limit : true)){
            $fpos=($fstr ? strpos($str,$fstr)+strlen($fstr) : 0);
            $str=substr($str,$fpos);
            $lpos=strpos($str,$lstr);
            $val=($lpos!==false ? substr($str,0,$lpos) : $str);
            $temp_arr[]=($trim ? trim($val) : $val);
            $str=substr($str,$lpos+strlen($lstr));
            $lcnt++;
        }
        return ($limit==1 ? (isset($temp_arr[0]) ? $temp_arr[0] : '') : $temp_arr);
    }

    Конечный автомат своими силами.

    alexx, 21 Марта 2013

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

    +16

    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
    class Context;
    
    class AbstractState
    {
    	Context * m_context;
    
    protected:
    	Context * context() const { return m_context; }
    
    public:
    	AbstractState(Context * context) : m_context(context) { };
    	virtual ~AbstractState() { }
    	virtual void doSomething() = 0;
    };
    
    class Context
    {
    	std::unique_ptr<AbstractState> m_state;
    
    public:
    	enum State
    	{
    		State1,
    		State2,
    	};
    	Context() { switchToState(State1); }
    	void switchToState(State newState);
    	void doSomething() { m_state->doSomething(); }
    	void someCleanup() { }
    };
    
    class ConcreteState1 : public AbstractState
    {
    public:
    	ConcreteState1(Context * context) : AbstractState(context) { }
    	virtual void doSomething()
    	{
    		context()->switchToState(Context::State2);
    		context()->someCleanup();
    	}
    };
    
    class ConcreteState2 : public AbstractState
    {
    public:
    	ConcreteState2(Context * context) : AbstractState(context) { }
    	virtual void doSomething()
    	{
    		context()->switchToState(Context::State1);
    		context()->someCleanup();
    	}
    };
    
    void Context::switchToState(State newState)
    {
    	switch(newState)
    	{
    	case State1:
    		m_state.reset(new ConcreteState1(this));
    		return;
    	case State2:
    		m_state.reset(new ConcreteState2(this));
    		return;
    	}
    }

    Бывает, на меня находит состояние "сначала делай, потом думай", благо результат был быстро обнаружен отладчиком.

    Xom94ok, 10 Марта 2013

    Комментарии (1)
  4. SQL / Говнокод #12661

    −169

    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
    DECLARE @IsPerson BIT  
     ,@ContactTypeID INT  
    
     SET @ContactTypeID = CASE WHEN @IsPerson = 0 THEN 3 ELSE 4 END  
    
     IF (LEN(ISNULL(@FirstName,'')) <= 0 AND LEN(ISNULL(@LastName,'')) <= 0 AND (LEN(@EntityName) > 0 OR LEN(@TradingAs) > 0))  
     BEGIN  
      SET @IsPerson = 0  
     END   
     ELSE  
     BEGIN  
      SET @IsPerson = 1  
     END

    Такая себе Stored Procedure...
    Magic numbers - это всё фигня. Меня всегда интересовало, почему тип контакта всегда 4?
    И, да, строки идут именно в такой очерёдности.

    kore_sar, 28 Февраля 2013

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

    +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
    //...
                    else if (data.indexOf('none') == -1)
                    {
                        // Экспорт в работе
                        // Повторять запрос раз в nSec секунд.
                        nSec = 3;
                        document.getElementById("export_loading").show();
                        setTimeout("loadFile({{subject_id}}, '')", nSec*1000);
                    }
    //...
    <div class='loader' id="export_loading" style="visibility: hidden; display: inline-block; text-align: center; margin-right: 13px;"><img src='/app/images/loading.gif'/> идёт формирование списка авторов</div>
    <div id="messages_container" style="visibility: hidden; padding: 0px 30px 0 35px;">
    </div>

    Чувак вообще прикалывается)

    greevex, 27 Февраля 2013

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

    +146

    1. 1
    strtotime(date('Y-m-d H:i:s'))

    xscript, 25 Февраля 2013

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

    +152

    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
    function fixMootoolsJSON(thing) {
        var i, member, pattern = /^"\[.*\]"$/, copy;
        if (thing instanceof Array) {
            for (i = 0; i < thing.length; i++) {
                member = thing[i];
                if (typeof member == "string" && pattern.test(member)) {
                    thing[i] = fixMootoolsJSON(JSON.decode(member));
                }
            }
        } else if (typeof thing == "object") {
            copy = { };
            for (i in thing) {
                if (thing.hasOwnProperty(i)) {
                    copy[i] = fixMootoolsJSON(JSON.decode(thing[i]));
                }
            }
            for (i in copy) {
                if (copy.hasOwnProperty(i)) {
                    thing[i] = copy[i];
                }
            }
        }
        return thing;
    }

    http://outsourceror.blogspot.co.il/2011/04/mootools-intrudes-on-native-json-and.html

    Но вы не подумайте, оказалось, что я был первый (в нашем небольшом коллективе), кто это заметил, а (в нашем небольшом коллективе) было принято JSON прям как есть в базу сохранять...

    wvxvw, 24 Февраля 2013

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

    +142

    1. 1
    2. 2
    3. 3
    4. 4
    $arr = date("w", strtotime($date_bron));
    $date = $arr;
    if ($arr == 0)
         $date = 0;

    Система бронирования столика для бара...

    unst, 17 Февраля 2013

    Комментарии (1)
  9. Куча / Говнокод #12603

    +141

    1. 1
    http://rosettacode.org/wiki/Category:Programming_Tasks

    Сегодня это реально сразу куча.

    LispGovno, 16 Февраля 2013

    Комментарии (1)
  10. Java / Говнокод #12601

    +77

    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
    byte[] buffer = new byte[BUFFER_SIZE];
    ReadState readState = ReadState.BOUNDARY;
    
    InputStream input = request.getInputStream();
    int read = input.read(buffer);
    int pos = 0;
    
    // This is a fail-safe to prevent infinite loops from occurring in some environments
    int loopCounter = 20;
    
    while (read > 0 && loopCounter > 0) {
        for (int i = 0; i < read; i++) {
            switch (readState) {
                // Pos is calculated...
                case BOUNDARY: 
                case HEADERS: 
                case DATA: 
            }
        }
    
        if (pos < read) {
            // move the bytes that weren't read to the start of the buffer
            int bytesNotRead = read - pos;
            System.arraycopy(buffer, pos, buffer, 0, bytesNotRead);
            read = input.read(buffer, bytesNotRead, buffer.length - bytesNotRead);
    
            // Decrement loopCounter if no data was readable
            if (read == 0) {
                loopCounter--;
            }
    
            read += bytesNotRead;
        } else {
            read = input.read(buffer);
        }
    }

    Кусок исходников из недров JBoss Seam(наткнулся профайлером).
    Пацаны пофиксили багу с бесконечным циклом и 100 утилизацией CPU.
    Весь класс:
    https://www.java2s.com/Open-Source/Java/JBoss/jboss-seam-2.2.0/org/jboss/seam/web/MultipartRequestImpl.java.htm
    Версия с бесконечным циклом:
    http://www.docjar.com/html/api/org/jboss/seam/web/MultipartRequestImpl.java.html

    psvm, 16 Февраля 2013

    Комментарии (1)
  11. PHP / Говнокод #12579

    +127

    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
    /* Групповые операции с обращениями */
    public function issuegroupopsAction() {
        $this->_helper->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $operation = $this->_request->getPost('operation');
        define('RTF_SYMBOL_PAGE_BREAK', '\page');
        try {
            // Валидация
            if(!in_array($operation, array('print-letters', 'print-work-order'))) {
                throw new Exception('Неверная операция');
            }
            $issue_numbers = explode(';', (string)$_POST['issues']);
            if(!count($issue_numbers)) {
                throw new Exception('Не выбрано ни одного обращения.');
            }
            // Вычитка указанных обращений
            $filter = new Type_Issue_Filter(array('issue_number' => $issue_numbers));
            $paginator = new Type_Paginator;
            $paginator->items_per_page = 40;
            $issues = services::Issue()->records($this->user->sessionId, $filter, array('executant', 'address'), 'number', $paginator);
            if(!count($issues->items)) {
                throw new Exception('Выбранные обращения не найдены.');
            }
            $templateMaker = new Prodom_Rtf_TemplateMaker;
            $templatesDir = dirname(__FILE__).'/templates/';
            $outputFiles = array();
            // Вид операции с группой обращений
            switch($operation) {
                case 'print-letters': {
                    // Сформирвать письма
                    $templateMaker->readTemplatesFromRtfFile($templatesDir.'templates.rtf');
                    $outputFiles = array('executants_%u.rtf' => array('issue2', 'letter1'), 'declarant_%u.rtf' => array('letter2'));
                    break;
                }
                case 'print-work-order': {
                    // Печать заказ-нарядов
                    if(!is_null($this->user->organization->issue_form_template)) {
                        // Если для организации определен свой собственный шаблон
                        $templateMaker->readTemplatesFromRtfFile($templatesDir.$this->user->organization->issue_form_template);
                    } else {
                        // Если шаблон явно не определен
                        $templateMaker->readTemplatesFromRtfFile($templatesDir.'templates.rtf');
                    }
                    $outputFiles = array('issue_%u.rtf' => array('issue1'));
                    break;
                }
            }
            $toworkIssueIds = array();
            $outputs = array_fill_keys(array_keys($outputFiles), null);
            // Перебор выбранных пользователем обращений
            foreach($issues->items as $issue) {
                // Переводим все новые обращения в статус "В работе"
                $issue_new_statuses = array(ISSUE_STATUS_NEW, ISSUE_STATUS_CONFIRMED);
                if(($operation == 'print-work-order') && in_array($issue->status_id, $issue_new_statuses) && ($issue->org_executor_id == $this->user->organization->id)) {
                    $toworkIssueIds[] = $issue->id;
                }
                // Подготовка полей обращения для печати на формах
                $fields = $this->getIssuePrintFields($issue);
                foreach($outputFiles as $fileName => $needTemplates) {
                    foreach($needTemplates as $template_code) {
                        $out = $templateMaker->getAppliedTemplate($template_code, $fields);
                        $outputs[$fileName] .= ($outputs[$fileName] ? RTF_SYMBOL_PAGE_BREAK : null) . $out;
                    }
                }
            }
            if(count($toworkIssueIds)) {
                $resp = services::Issue()->changeStatusMultiple($this->user->sessionId, $toworkIssueIds, ISSUE_STATUS_INWORK, null, null, null);
            }
            // Если на выходе только один файл, отправляем rtf
            if(count($outputs) == 1) {
                foreach($outputs as $fileName => $fileBody) {
                    // Генерация случайного имени файла
                    $fileName = str_replace('%u', substr(md5(implode('_', $issue_numbers)), 0, 7), $fileName);
                    // Вывод файла пользователю
                    header('Content-type: application/rtf');
                    header("Content-Disposition: attachment; filename={$fileName}");
                    echo $templateMaker->getHeader().$fileBody.$templateMaker->getFooter();
                }
            } else {
                // Eсли на выходе больше одного файла, пакуем их архивом
                header("Content-type: application/octet-stream");
                header("Content-Disposition: attachment; filename=issues.zip");
                header("Content-Description: Files of an applicant");
                // Создаем ZIP архив
                $zip = new ZipFile();
                foreach($outputs as $fileName => $fileBody) {
                    // Генерация случайного имени файла
                    $fileName = str_replace('%u', substr(md5(implode('_', $issue_numbers)), 0, 7), $fileName);
                    // Вывод файла пользователю в браузер
                    $fileBody = $templateMaker->getHeader().$fileBody.$templateMaker->getFooter();
                    $zip->addFile($fileBody, $fileName);
                }
                echo $zip->file();
            }
        }
        catch(Exception $ex) {
            die($ex->getMessage());
        }
    }

    Функция распечатки документов с отчетами по выбранным обращениям

    sciner, 13 Февраля 2013

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