1. JavaScript / Говнокод #14130

    +153

    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
    App.ns.SomeClass.prototype = {
        addMessage: function(status, msg, timeDelay) {
            if (status === false || status === this.STATUS_ERROR) {
                status = this.STATUS_ERROR;
                delay = timeDelay || 5; // default delay of msg box for error is 5 seconds. 
            }
            if (!timeDelay) {
                // 1 character - 1/7 sec 
                delay = msg.length / 7;
                if ((delay < 3) && !(timeDelay)) {
                    delay = 3;
                } else if ((delay > 30) && !(timeDelay)) {
                    delay = 30;
                    }
            }
            // показываем messagebox
        }
    };

    Кручу-верчу, запутать хочу.

    Elvenfighter, 24 Ноября 2013

    Комментарии (4)
  2. Pascal / Говнокод #14129

    +132

    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
    procedure tnewthread.checkfiles; // процедура выполняется в потоке
    var
      i:integer;
      status:tstatus;
      ptmp:array of char;
      temp:string;
      len:integer;
      fstream:tfilestream;
    begin
      flist.Clear;
      findfiles(findpath);
      for i:=flist.Count-1 downto 0 do
      begin
        status:=s_ok;
        try
          try
            fstream:=tfilestream.Create(flist[i],fmopenread);
            fstream.Position:=0;
            setlength(ptmp,fstream.size);
            fstream.Read(pointer(ptmp)^,fstream.size);
          except
            status:=s_error;
          end;
        finally
          fstream.free;
        end;
        temp:=string(pchar(ptmp));
        temp:=stringreplace(temp,'&nbsp;',' ',[rfreplaceall]);
        temp:=stringreplace(temp,'&gt;','>',[rfreplaceall]);
        temp:=stringreplace(temp,'&nbsp;',' ',[rfreplaceall]);
        temp:=stringreplace(temp,'&lt;','<',[rfreplaceall]);
        temp:=stringreplace(temp,'&amp;','&',[rfreplaceall]);
        temp:=stringreplace(temp,'&quot;','"',[rfreplaceall]);
        temp:=stringreplace(temp,'&copy;',#169,[rfreplaceall]);
        temp:=stringreplace(temp,#10,#13#10,[rfreplaceall]);
        Len := Length(temp);
        try
          try
            fstream:=tfilestream.Create('C:\1.txt',fmcreate); // заменил в целях теста, не помогает.
            fstream.Position:=0;
              fstream.WriteBuffer(temp[1], Len); // в этом  месте поток вылетает с ошибкой "Range check error"
          except
            status:=s_error;
          end;
        finally
          fstream.free;
        end;
        if status=s_ok then
        begin
          addfileinfo(flist[i]); 
          shrecyclefile(flist[i]);
        end
        else
        begin
          adderrinfo(flist[i]); // синхронизируемся с мемо и добавляем в него красную строчку с именем файла
          shmovefile(flist[i],erroroutputpath +'\' + extractfilename(flist[i])); // перемещаем файл в директорию с файлами, при обр. которых произошла ошибка
        end;
      end;
    end;

    Процедура для обработки текстовых файлов. Имеем дремлющий поток, залоченный waitsingleobject, который будит
    таймерная функция, если в папке есть по крайней мере 1 файл. т.е. одновременно к файлам обращается 1 поток.
    При разлочивании поток немедленно начинает заполнять лист именами файлов, после чего начинает прогонять их
    через процедуру-обработчик. Но вот беда - возникает ошибка range check error. причем возникает только в доп.потоке -
    вне потока все работает нормально. Товарищи ,не подскажете, в чем лажа? (

    Stertor, 24 Ноября 2013

    Комментарии (38)
  3. JavaScript / Говнокод #14128

    +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
    function foo(id) {
          document.getElementById('1').style.display='none';
          document.getElementById('46').style.display='none';
          document.getElementById('2').style.display='none';
          document.getElementById('53').style.display='none';
          document.getElementById('55').style.display='none';
          document.getElementById('56').style.display='none';
          document.getElementById('57').style.display='none';
          document.getElementById('58').style.display='none';
    if (document.getElementById(id).style.display == "none")
             {document.getElementById(id).style.display = "block"}
    else
             {document.getElementById(id).style.display = "none"}
    }

    Прислали с бывшей работы.
    %%Саша, я таки ушёл.%%

    хуита, 24 Ноября 2013

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

    −132

    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
    1.TextWindow.WriteLine ("Напиши число от 0 до 9 и я переведу его на английский")
    
    2.Число = TextWindow.ReadNumber()
    
    3.If Число = "0" Then
    
    4.TextWindow.WriteLine ("Zero")
    
    5.ElseIf Число = "1" Then
    
    6.TextWindow.WriteLine ("One")
    
    7.ElseIf Число = "2" Then
    
    8.TextWindow.WriteLine ("Two")
    
    9.ElseIf Число = "3" Then
    
    10.TextWindow.WriteLine ("Three")
    
    11.ElseIf Число = "4" Then
    
    12.TextWindow.WriteLine ("Four")
    
    13.ElseIf Число = "5" Then
    
    14.TextWindow.WriteLine ("Five")
    
    15.ElseIf Число = "6" Then
    
    16.TextWindow.WriteLine ("Six")
    
    17.ElseIf Число = "7" Then
    
    18.TextWindow.WriteLine ("Seven")
    
    19.ElseIf Число = "8" Then
    
    20.TextWindow.WriteLine ("Eight")
    
    21.ElseIf Число = "9" Then
    
    22.TextWindow.WriteLine ("Nine")
    
    23.Else
    
    24.TextWindow.WriteLine ("Не знаю таких больших цифр")
    
    25.EndIf

    elseif число=10 then
    msgbox "программа бо-бо"
    else
    msgbox "программа бо-бо"

    http://vbbook.ru/small-basic/ysloviya--primeru-small-basic/

    Stertor, 23 Ноября 2013

    Комментарии (40)
  5. Куча / Говнокод #14126

    +120

    1. 1
    http://cs409725.vk.me/v409725134/612b/bo_sT8EuYK4.jpg

    LispGovno, 22 Ноября 2013

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

    +13

    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
    //Сегодня QuestionGovno.
    //Допустим есть код:
    #include <iostream>
    using namespace std;
    class T{};
    struct M{M(T){}};
    struct G{G(T){}};
    
    int f(M){return 0;}
    bool f(G){return 0;}
    
    int main() {
    	bool a(f(T()));
    	return 0;
    }

    Казалось бы должна быть неоднозначность при компиляции, так как компилятор не знает какую перегрузку f бы выбрать.
    И как бы так оно и есть:
    http://ideone.com/o21NDg
    Логично? Логично.
    Но стандарт считает по другому:
    http://en.cppreference.com/w/cpp/language/overload_resolution
    Смотрите пункт:
    Best viable function
    F1 is determined to be a better function than F2 if implicit conversions for all arguments of F1 are not worse than the implicit conversions for all arguments of F2, and
    ...
    2) or. if not that, (only in context of non-class initialization by conversion), the standard conversion sequence from the return type of F1 to the type being initialized is better than the standard conversion sequence from the return type of F2

    Как мне повторить поведение, которое указано в стандарте?

    LispGovno, 22 Ноября 2013

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

    +65

    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
    public class Path {
    	private String path;	
    	private char winSep = '\\';
    	private char unixSep = '/';
    	
    	public void set(String path){				
    		if(!path.endsWith(File.separator)){ 
    			path.concat(File.separator);
     		}
    		this.path = path;
    		if(File.separatorChar == winSep && path.charAt(0) == unixSep){ 
    			this.path = path.replace(unixSep, winSep).substring(1); 
     		}		
    				
    	 }
    
    	public String get(){
    		String path = new String(this.path);
     		return path;  	
    	}
    	
    	public String getRoot(){
    		String root = null;
    		 if(File.separatorChar == unixSep){ 
    			root = "/";
    		} 		
    		if(File.separatorChar == winSep){ 
    			root = this.path.substring(0, this.path.indexOf(winSep)+1);
    		}		
    		return root;
    	}
    	
    }

    в 6 йаве нету класса Path, пришлось самому делать костыль-велосипед. тут где-то ошибочка есть, пока не смотрел.

    spivti, 22 Ноября 2013

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

    +130

    1. 1
    List<KeyValuePair<string, string>> documentList = GetList();

    использование списка пар ключ-значение вместо словаря (Dictionary<string, string>)

    mozg_raka, 22 Ноября 2013

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

    +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
    /*
     -----------------------------------------------------------------
     Отмечаем все темы как прочитанные
     -----------------------------------------------------------------
     */
    $req = mysql_query("SELECT `forum`.`id`
                FROM `forum` LEFT JOIN `cms_forum_rdm` ON `forum`.`id` = `cms_forum_rdm`.`topic_id` AND `cms_forum_rdm`.`user_id` = '$user_id'
                WHERE `forum`.`type`='t'
                AND `cms_forum_rdm`.`topic_id` Is Null");
    while ($res = mysql_fetch_assoc($req)) {
        mysql_query("INSERT INTO `cms_forum_rdm` SET
                        `topic_id` = '" . $res['id'] . "',
                        `user_id` = '$user_id',
                        `time` = '" . time() . "'");
    }
    $req = mysql_query("SELECT `forum`.`id` AS `id`
                FROM `forum` LEFT JOIN `cms_forum_rdm` ON `forum`.`id` = `cms_forum_rdm`.`topic_id` AND `cms_forum_rdm`.`user_id` = '$user_id'
                WHERE `forum`.`type`='t'
                AND `forum`.`time` > `cms_forum_rdm`.`time`");
    while ($res = mysql_fetch_array($req)) {
        mysql_query("UPDATE `cms_forum_rdm` SET
                        `time` = '" . time() . "'
                        WHERE `topic_id` = '" . $res['id'] . "' AND `user_id` = '$user_id'");
    }

    Один из самых популярных мобильных движков - JohnCMS.

    Скрипт отмечает темы форума как прочтенные. Частенько бывает за сотню непрочитанных тем. А я посещаю редко, так у меня вообще за тысячу переваливает иногда.

    Max_Coder, 21 Ноября 2013

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

    +18

    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
    class figure
    {
    //...
    };
    
    class triugolnik: public figure
    {
    //...
    };
    
    class kvadrat: public figure
    {
    //...
    };
    
    #define PAIR(f0, f1) std::make_tuple(std::type_index(typeid(f0)), std::type_index(typeid(f1)))
    
    int PloshadTrehFigur(const figure& f0, const figure& f1, const figure& f2);//forward declaration
    int PloshadDvuhFigur(const figure& f0, const figure& f1)
    {
      static const std::unordered_map<
        std::tuple<std::type_index, std::type_index>, std::function<int(const figure&, const figure&)> 
      > caller 
        {
           {PAIR(triugolnik, kvadrat), ploshadTriugolnikIKvadrat},
           {PAIR(kvadrat, triugolnik), lispGovno::flip(ploshadTriugolnikIKvadrat)},
           {PAIR(kvadrat, kvadrat), ploshadKvadratIKvadrat},
           {PAIR(triugolnik, triugolnik), ploshadTriugolnikITriugolnik}
        };
        const auto& f = caller.find(PAIR(f0, f1));
        assert(f!=caller.end());
        f(f0, f1);
    }
    
    #undef PAIR

    Наш ответ Чемберлену:
    http://govnokod.ru/13933
    lispGovno::flip - flip такой же как в хаскель из моей особой мегабиблиотеки победителя каждый день.
    Шах и мат господа присяжные засидатели. Мультиметоды в крестах есть и реализуются за 5 минут.
    В сишке аналогично. Все анскилябры залезли под кровати.
    Визитары размазанные по коду сосут и трудно поддерживаются.

    LispGovno, 20 Ноября 2013

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