1. C++ / Говнокод #15739

    +9

    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
    class t_item{
    public:
    #define DEF_PRO_STRUCT_INFO(NAME,PARENT,OWNER)NAME(t_item)
    #define DEF_PRO_VARIABLE(ADDBEG,ADDVAR,ADDEND)\
    ADDBEG()\
    ADDVAR(0,string,name,DEF,$,$)\
    ADDVAR(1,int,next,SET,0,$)\
    ADDEND()
    //=====+>>>>>t_item
    #include "QapGenStruct.inl"
    //<<<<<+=====t_item
    public:
    };

    LispGovno, 12 Апреля 2014

    Комментарии (14)
  2. Куча / Говнокод #15738

    +125

    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
    % -*- mode: Prolog -*-
    
    :- module e9.
    :- interface.
    :- import_module io.
    :- pred main(io::di, io::uo) is cc_multi.
    
    :- implementation.
    :- import_module int, float, list, string, math.
    
    :- func root(int) = int.
    root(Number) = floor_to_int(sqrt(float(Number))).
    
    :- func squares_under(int, int) = list(int).
    squares_under(From, To) = Result:-
        (Square = From * From,
         (if Square =< To
         then Result = [Square | squares_under(From + 1, To)]
         else Result = [])).
    
    :- pred list_to_disjunction(list(int)::in, int::out) is nondet.
    list_to_disjunction([Head | Tail], Result):-
        (Result = Head; list_to_disjunction(Tail, Result)).
    
    :- pred summands_of(list(int)::in, int::in, { int, int, int }::out) is cc_nondet.
    summands_of(Squares, Sum, { A, B, C }):-
        list_to_disjunction(Squares, As),
        list_to_disjunction(Squares, Bs),
        list_to_disjunction(Squares, Cs),
        As < Bs, Bs < Cs,
        As + Bs = Cs,
        root(As) + root(Bs) + root(Cs) = Sum,
        A = As, B = Bs, C = Cs.
    
    main(!IO):-
        Sum = 1000,
        Squares = squares_under(1, Sum * Sum),
        (if summands_of(Squares, Sum, { A, B, C })
        then io.format("Answer: A = %d, B = %d, C = %d\n", [i(A), i(B), i(C)], !IO)
        else io.format("No solutions\n", [], !IO)).

    Давно как-то мы не вспоминали Прожект Ойлер.
    Язык: Меркури,
    Эффективность решения: наверное, полный пиздец.

    Для тех, кому нечем заняться: http://joyreactor.com/post/954661

    wvxvw, 12 Апреля 2014

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

    +145

    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
    stManager && stManager.add(['emoji.js'], function () {
        var allEmojiCodes = [/*коды смайлов*/"D83DDE0A"],
            function EmojiMy() {
                this.bindAll(this, 'process', 'onClick', 'onKeyDown', 'toggleSmileBtn', 'parseAddedNodes', 'globalHandler', 'eventHandler', 'showMore', 'sendSticker', 'tabSwitch');
                this.counter = 0;
                this.current = {
                    tooltip: null
                };
            }
        EmojiMy.prototype.bindAll = function (obj) {
            var bind = function (func, context) {
                var args = [].slice.call(arguments, 2);
    
                if (typeof context == "string") {
                    args.unshift(func[context], func);
                    return bind.apply(this, args);
                }
    
                return function () {
                    var unshiftArgs = args.concat([].slice.call(arguments));
                    return func.apply(context, unshiftArgs);
                };
            },
            funcs = Array.prototype.slice.call(arguments, 1);
            if (funcs.length === 0) throw new Error("bindAll must be passed function names");
            funcs.forEach(function (f) {
                obj[f] = bind(obj[f], obj);
            });
            return obj;
        };
        EmojiMy.prototype.init = function () {
            ajax.post('im', {
                act: 'get_emoji_list'
            }, {
                onDone: function (codes) {
                    Emoji.allEmojiCodes = allEmojiCodes;
                }
            });
            observer.observe(document.querySelector('body'), {
                childList: true,
                subtree: true,
                attributes: true,
                attributeFilter: ['style']
            });
    
            this.process();
        };
        (qwe = new EmojiMy()).init();
    });

    Помогите исправить ошибки не могу вообще не как, выполняется с ошибками

    remus, 12 Апреля 2014

    Комментарии (0)
  4. Куча / Говнокод #15735

    +130

    1. 1
    <input id="resetbutton" class="btn btn-info" type="reset" value="Reset" name="reset"></input>

    Джун порадовал. Не хватает комментария "Шоб наверняка!"

    Keeper, 12 Апреля 2014

    Комментарии (3)
  5. Си / Говнокод #15734

    +133

    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
    #ifndef _TOGGLE_H_
    #define _TOGGLE_H_
    
    #include <winbase.h>
    #include "Python.h"
    
    #define ID(X) "id(" #X ")"
    
    #define SET_OBJ_POINTER(OBJ, NAME)\
        OBJ = (PyObject *)PyLong_AsLong\    
        (PyRun_String(ID(NAME), Py_eval_input,\
        PyEval_GetGlobals(), PyEval_GetLocals()))
    
    //////////////////////////////////////////////////////
    
    PyObject * __Py_None__;
    PyObject * __Py_True__;
    PyObject * __Py_False__;
    PyObject * __Py_NotImplemented__;
    
    #undef  Py_None
    #undef  Py_True
    #undef  Py_False
    #undef  Py_NotImplemented
    
    #define Py_None __Py_None__
    #define Py_True __Py_True__
    #define Py_False __Py_False__
    #define Py_NotImplemented __Py_NotImplemented__
    
    //////////////////////////////////////////////////////
    
    static void initToggle(void) {
        SET_OBJ_POINTER(Py_None, None);
        SET_OBJ_POINTER(Py_True, True);
        SET_OBJ_POINTER(Py_False, False);
        SET_OBJ_POINTER(Py_NotImplemented, NotImplemented);
    }
    
    int WINAPI DllMain(HANDLE hinstDLL, DWORD dwReason, LPVOID lpvReserved) {
        initToggle();
        return 1;
    }
    
    #endif

    Раскопал на старой флешке костыль, позволяющий компилить сишные модули для питона прям на кпк под WinMobile с помощью портанутой gcc. Была там бага - не видел собранный модуль Py_None, Py_True и т.д из python.dll. При помощи макроса SET_OBJ_POINTER приходилось вытаскивать указатели на них.

    Pythoner, 12 Апреля 2014

    Комментарии (0)
  6. Куча / Говнокод #15733

    +129

    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
    <script>
    // Browser Window Size and Position
    // copyright Stephen Chapman, 3rd Jan 2005, 8th Dec 2005
    // you may copy these functions but please keep the copyright notice as well
    function pageWidth()
    { return window.innerWidth != null ? window.innerWidth : document.documentElement && document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body != null ? document.body.clientWidth : null; }
    function pageHeight()
    { return window.innerHeight != null ? window.innerHeight : document.documentElement && document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body != null ? document.body.clientHeight : null; }
    function posLeft()
    { return typeof window.pageXOffset != 'undefined' ? window.pageXOffset : document.documentElement && document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ? document.body.scrollLeft : 0; }
    function posTop()
    { return typeof window.pageYOffset != 'undefined' ? window.pageYOffset : document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ? document.body.scrollTop : 0; }
    function posRight()
    { return posLeft() + pageWidth(); }
    function posBottom()
    { return posTop() + pageHeight(); }
    
    function SetWindowSize(s, h, w) {
        var wid = pageWidth();
        var hei = pageHeight();
        var n_wid = Math.round(wid * w);
        var n_hei = Math.round(hei * h);
        s.SetWidth(n_wid);
        s.SetHeight(n_hei);
    }
    function SetWindowW(s, w) {
        var wid = pageWidth();
        var n_wid = Math.round(wid * w);
        s.SetWidth(n_wid);
    }
    </script>
    <html>
    ...
                <td>
                    <dx:ASPxButton ID="AddCopyTemplate" runat="server" Text="Создать копию" 
                        AutoPostBack="False" 
                        CssFilePath="~/App_Themes/Office2010Black/{0}/styles.css" 
                        CssPostfix="Office2010Black" 
                        SpriteCssFilePath="~/App_Themes/Office2010Black/{0}/sprite.css" 
                        Wrap="True" >
                        <ClientSideEvents Click="function(s, e) {
    	AddCopyTemplate();
    }" Init="function(s, e) {
    	Get_Sizes_wid(s,1075);
    }" />
                    </dx:ASPxButton>
                </td>
                <td>
                    <dx:ASPxButton ID="AddTemplate" runat="server" Text="Создать" 
                        AutoPostBack="False" 
                        CssFilePath="~/App_Themes/Office2010Black/{0}/styles.css" 
                        CssPostfix="Office2010Black" 
                        SpriteCssFilePath="~/App_Themes/Office2010Black/{0}/sprite.css">
                        <ClientSideEvents Click="function(s, e) {
    	AddTemplateClick();
    }" Init="function(s, e) {
    	Get_Sizes_wid(s,1075);
    }" />
                    </dx:ASPxButton>
                </td>
    ...
    </html>

    я даже не знаю, в какой раздел это постить, но пусть будет тут.
    товарищ, пользовался горячелюбимыми контролами от DevExpress, которые работают херпойми как, но сейчас не об этом.
    в секции ClientSideEvents есть скрипты, которые выполняются на клиенте при старте, так вот он и поставил туда вызов функции, которая выставляет размеры для элементов.
    это одностраничное приложение на 1100 строк только одной размеки, где используется огромное количество различных элементов, панели, гриды, гнопки, модальные окна, и много всего прочего... и ни у одного из них не заданы вообще никакие размеры, все работает на этих JS функциях.
    эти волшебные цифры, которые передаются в функцию рассчитаны на его монитор, и как только они отрываются на другом мониторе с другим разрешением, то эти две кнопки занимают примерно 80% экрана.
    а самое главное, что модальные окна занимают примерно 80% высоты и ширины экрана, и сначала они рисуются по центру экрана, а потом увеличиваются функцией, из-за чего они уезжают за границы экрана

    Lokich, 11 Апреля 2014

    Комментарии (6)
  7. Си / Говнокод #15732

    +133

    1. 1
    2. 2
    3. 3
    if (access(path, aflag) && mkfifo(path, mode) {
            exit(-1);
    }

    Весьма интуитивная запись условия

    evg_ever, 11 Апреля 2014

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

    +14

    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
    string modify( const string & str )
    {
    	if( str.size() == 0 ) return "00";
    	if( str.size() == 1 ) return "0" + str;
    	return string( str.end() - 2, str.end() );
    }
    
    string modify4( const string & str )
    {
    	if( str.size() == 0 ) return "0000";
    	if( str.size() == 1 ) return "000" + str;
    	if( str.size() == 2 ) return "00" + str;
    	if( str.size() == 3 ) return "0" + str;
    	return string( str.end() - 4, str.end() );
    }
    
    string TimeISOFormat( time_t cur )
    {
    	char buf[32];
    	struct tm * timeinfo;
    	timeinfo = localtime ( &cur );
    	strftime(buf, 32, "%y", timeinfo);
    	string year(buf);
    	strftime(buf, 32, "%m", timeinfo);
    	string month(buf);
    	strftime(buf, 32, "%d", timeinfo);
    	string day(buf);
    	strftime(buf, 32, "%H", timeinfo);
    	string hour(buf);
    	strftime(buf, 32, "%M", timeinfo);
    	string minute(buf);
    	strftime(buf, 32, "%S", timeinfo);
    	string second(buf);
    	return modify4( year ) + "-" + modify( month ) + "-" + modify( day ) + "T" + modify( hour )+ ":" + modify( minute )+ ":" + modify( second );
    }
    
    string CurrentTimeISOFormat()
    {
    	time_t cur = CurrentTime();
    	char buf[32];
    	struct tm * timeinfo;
    	timeinfo = localtime ( &cur );
    	strftime(buf, 32, "%y", timeinfo);
    	string year(buf);
    	strftime(buf, 32, "%m", timeinfo);
    	string month(buf);
    	strftime(buf, 32, "%d", timeinfo);
    	string day(buf);
    	strftime(buf, 32, "%H", timeinfo);
    	string hour(buf);
    	strftime(buf, 32, "%M", timeinfo);
    	string minute(buf);
    	strftime(buf, 32, "%S", timeinfo);
    	string second(buf);
    	return modify4( year ) + "-" + modify( month ) + "-" + modify( day ) + "T" + modify( hour )+ ":" + modify( minute )+ ":" + modify( second );
    }
    
    time_t CurrentTime()
    {
    	time_t rawtime = 0;
    	time(&rawtime);
    	return rawtime;
    }

    brainiac, 11 Апреля 2014

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

    −404

    1. 1
    [UIColor colorWithRed:0.3046875f green:0.72265625f blue:0.7421875f alpha:YES];

    Долго подбирал цвета, наверно. Да, и alpha - это float, а не bool.

    mr.The, 11 Апреля 2014

    Комментарии (10)
  10. Pascal / Говнокод #15729

    +83

    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
    initialization
      //done this way so we can have a separate stack just for FPC under Unix systems
      GStackClass :=
        {$IFDEF USE_VCL_POSIX}
        TIdStackVCLPosix
        {$ELSE}
          {$IFDEF UNIX}
            {$IFDEF KYLIXCOMPAT}
            TIdStackLibc
            {$ENDIF}
            {$IFDEF USE_BASEUNIX}
            TIdStackUnix
            {$ENDIF}
          {$ENDIF}
          {$IFDEF WINDOWS}
          TIdStackWindows
          {$ENDIF}
          {$IFDEF DOTNET}
          TIdStackDotNet
          {$ENDIF}
        {$ENDIF}
      ;
      GStackCriticalSection := TIdCriticalSection.Create;
      {$IFNDEF DOTNET}
        {$IFDEF REGISTER_EXPECTED_MEMORY_LEAK}
      IndyRegisterExpectedMemoryLeak(GStackCriticalSection);
        {$ENDIF}
      {$ENDIF}
    finalization
      // Dont Free. If shutdown is from another Init section, it can cause GPF when stack
      // tries to access it. App will kill it off anyways, so just let it leak
      {$IFDEF FREE_ON_FINAL}
      FreeAndNil(GStackCriticalSection);
      {$ENDIF}
    end.

    Выдержка из IdStack.pas. Без комментариев.

    Предыcтория.
    fastmm постоянно сообщал об утечках памяти в моих программах, использующих Indy: решил разобраться.
    Оказалось, что ошибки возникали при использовании IdStack, по умолчанию этот модуль используют почти все компоненты из палитры.

    brutushafens, 11 Апреля 2014

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