1. Список говнокодов пользователя j123123

    Всего: 331

  2. C++ / Говнокод #24235

    −1

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    // https://github.com/dotnet/coreclr/blob/a589e3926a1780256fdb52376f8681fe047daf54/src/vm/binder.cpp#L503-L511
    
    const MscorlibBinder::OffsetAndSizeCheck MscorlibBinder::OffsetsAndSizes[] =
    {
        #define DEFINE_CLASS_U(nameSpace, stringName, unmanagedType) \
            { PTR_CSTR((TADDR) g_ ## nameSpace ## NS ), PTR_CUTF8((TADDR) # stringName), sizeof(unmanagedType), 0, 0, 0 },
        
        #define DEFINE_FIELD_U(stringName, unmanagedContainingType, unmanagedOffset) \
            { 0, 0, 0, PTR_CUTF8((TADDR) # stringName), offsetof(unmanagedContainingType, unmanagedOffset), sizeof(((unmanagedContainingType*)1)->unmanagedOffset) },
        #include "mscorlib.h"
    };

    Дух старой школы всё еще живет в майкрософт

    j123123, 08 Мая 2018

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

    −2

    1. 1
    2. 2
    Золотце
    https://lj.rossia.org/users/sadkov/103320.html?nc=55

    OpenGL - говно опенсурсное
    Попытался реализовать getPixel и putPixel на OpenGL, в результате получение одного пикселя занимает болшьшую часть времени выполнения программы. Другие люди тоже жалуются на тормознутость функций OpenGL, вроде glDrawPixels и glReadPixels

    https://stackoverflow.com/questions/39821850/why-is-glreadpixels-so-slow-and-are-there-any-alternative
    https://stackoverflow.com/questions/36534933/gldrawpixels-vs-textures-to-draw-a-2d-buffer-in-opengl

    >glDrawPixels is known to be very slow

    Зачем вообще нужно все это 3d ускорение? В DOS все было идеально:
    ((uint8_t*)(0xB8000))[y*320+x] = pixel

    почему нельзя современным программам предоставить такой 0xB8000 адрес и пару регистров вывода? Зачем все эти ритуалы? И да, MMU и protected mode значительно замедляют доступ к памяти, посему современный DOS работал бы на порядок быстрей Windows/Linux. Протекция памяти оправдана только на этапе разработки программы, а для release билда ее лучше отключить, чтобы иметь прямой доступ к реальной памяти.

    И я не одинок в негодовании:
    https://stackoverflow.com/questions/39430404/drawing-pixels-in-opengl

    >I'm using integrated GPU (Intel HD graphics 4000), as far as I know CPU and GPU share the same memory so why is it that I need to download? Why is it impossible to get a pointer?

    Начинаю думать, что Unabomber был прав во всем - надо к чертям взорвать офисы мразотных бюрократов из Khronos Group.

    j123123, 05 Мая 2018

    Комментарии (48)
  4. Java / Говнокод #24217

    +3

    1. 1
    http://www.ssw.uni-linz.ac.at/Research/Papers/Wuerthinger07/Wuerthinger07.pdf

    Как известно, в языках C и C++ есть проблема с buffer overflow, в то время как в языке Java такой проблемы нет (баги в реализации самой JVM не рассматриваем). В языке Java, как и в многих других подобных языках для анскиллябр заедушных, не могущих в сырые указатели, сделали проверки границ массива. В говноязыке C++ впрочем тоже есть какая-то такая питушня, например std::vector::at выполняет роверку выхода индекса за границы диапазона вектора. Только вот в язык JVM давно уже внедряют такую хреноту, как array bounds check elimination, т.е. убирание проверок, когда на этапе компиляции можно доказать, что такие проверки не нужны.

    В какой версии C++ сделают чтоб std::vector::at тоже вот так могло автозаменяться на небезопасный аналог если компилятор доказал что там эти проверки не нужны?

    j123123, 03 Мая 2018

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

    0

    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
    if (cond1)
    {
      do_shit1();
    }
    else if (cond2)
    {
      do_shit2();
    }
    else if (cond3)
    {
      do_shit3();
    }
    else if (cond4)
    {
      do_shit4();
    }

    Вот например есть такая вот типичная хуита, предположим что я знаю, что среди этих cond1 cond2 ... только один может быть true, остальные условия всегда будет ложными.
    И в этой сраной цепочке из if - else if можно перемещать if блоки без изменения логики. НО в языке Си (да и в C++ я уверен тоже) нет способа сказать компилятору что-то вроде "только одно из условий true, так что ты, сраный компилятор, можешь переделывать эту хуиту, и даже убрать else, если процессор в таком случае (при if(cond1) {do_shit1();}; if(cond2) {do_shit2();}; ... ) будет эту ссанину быстрее обрабатывать".
    Какие-нибудь языки программирования такую оптимизацию вообще умеют?

    j123123, 03 Мая 2018

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

    0

    1. 1
    2. 2
    3. 3
    https://twitter.com/i_am_romochka/status/986936174538383365
    UDP: кинул тебе за щеку
    TCP: кинул тебе за щеку, ПРОВЕРЯЙ

    А откуда эта хуита с "защекой" пошла? Не с говнокода ли?

    j123123, 20 Апреля 2018

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

    −1

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    9. 9
    Antony Polukhin
     in 
    pro.cxx
    Кстати, в EWG одобрили constexpr контейнеры http://open-std.org/JTC1/SC22/WG21/docs/papers/2018/p0784r1.html
    так что есть все шансы к С++20 писать:
    constexpr std::string result = foo();
    t.me/ProCxx
    /184343
    Mar 16 at 10:47

    Library pragmatism

    Current implementations of standard libraries sometimes perform various raw storage operations through interfaces other than the standard allocator and allocator traits. That may make it difficult to make the associated components usable in constexpr components. Based on a cursory examination of current practices, we therefore propose to start only with the requirement that the container templates in the [containers] clause be usable in constexpr evaluation, when instantiated over literal types and the default allocator. In particular, this excludes std::string, std::variant, and various other allocating components. Again, it is our hope we will be able to extend support to more components in the future.

    With regards to the default allocator and allocator traits implementation, the majority of the work is envisioned in the constexpr evaluator: It will recognize those specific components and implement their members directly (without necessarily regarding the library definition).
    We might, however, consider decorating the class members with the constexpr keyword. Also, some implementations provide extra members in these class templates (such as libc++'s allocator_traits<A>::__construct_forward ) that perform non-constexpr-friendly operations (memcpy, in particular). Lifting such members to standard status would help interoperability between library and compiler implementations.

    j123123, 16 Марта 2018

    Комментарии (10)
  8. Куча / Говнокод #23908

    +6

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    9. 9
    https://www.opennet.ru/opennews/art.shtml?num=48234
    
    Создатели редактора кода Atom из компании GitHub развивают новый
    экспериментальный текстовый редактор Xray, который также построен
    с использованием фреймворка Electron, но примечателен тем, что для
    повышения надёжности и производительности ядро редактора с
    реализацией базовой логики написано на языке Rust, интерфейс
    оформлен на JavaScript/CSS с применением фреймворка React, а для
    отрисовки текста применяется WebGL.

    Чем вообще руководствуются люди, делающие IDE из кусков браузера? Нахрена там JavaScript/CSS, нахрена там React? Еще и Rust приплели зачем-то.
    Может это чтоб всякие фронтенд-разрабы возрадовались, потому что теперь их умение писать хуиту на жабаскрипте применимо для написания говноплагинов к этой хуите? А как же бекенд? Пусть дополнительно встроят туда PHP MySQL чтоб никто не ушел обиженным.

    j123123, 11 Марта 2018

    Комментарии (270)
  9. Си / Говнокод #23862

    +2

    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
    // https://github.com/Samsung/ADBI/blob/3e424c45386b0a36c57211da819021cb1929775a/idk/include/division.h#L138
    
    /* Long division by 10. */
    static unsigned long long int div10l(unsigned long long int v) {
    
        /* It's a kind of magic.  We achieve 64-bit (long) division by dividing the two 32-bit halfs of the number 64-bit
         * number.  The first (most significant) half can produce a rest when dividing, which has to be carried over to the
         * second half.  The rest_add table contains values added to the second half after dividing depending on the rest
         * from the first division.  This allows evaluation of a result which is almost correct -- it can be either the
         * expected result, or the expected result plus one.  The error can be easily detected and corrected.
         */
        
        /* one dream */
        static unsigned long long int rest_add[] = {
            0x00000000, 0x1999999a, 0x33333334, 0x4ccccccd, 0x66666667,
            0x80000001, 0x9999999a, 0xb3333334, 0xcccccccd, 0xe6666667
        };
        
        /* one soul */
        unsigned long long int a = div10((unsigned int)(v >> 32));
        unsigned long long int b = div10((unsigned int)(v & 0xffffffff));
        
        /* one prize */
        int ri = (v >> 32) - a * 10;
        
        /* one goal */
        unsigned long long int ret = (a << 32) + b + rest_add[ri];
        
        /* one golden glance */
        if (ret * 10L > v) {
            //printf("OGG %llu %llu\n", ret * 10, v);
            --ret;
        }
        
        /* of what should be */
        return ret;
    }

    Деление на 10. Но зачем? Неужели компилятор настолько туп, что сам не может этого сделать?
    И да, эти туповатые комментарии one dream, one soul это отсылка к песне Queen - A Kind of Magic https://youtu.be/0p_1QSUsbsM

    j123123, 03 Марта 2018

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

    0

    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
    // http://www.compiler.su/prodolzhenie-tsikla-i-vykhod-iz-nego.php
    // В PHP выход из вложенного цикла выглядит, на мой взгляд, значительно элегантнее. После «break» указывается количество вложенных циклов, которые должен «покинуть» оператор «break». В приведённом примере, который аналогичен приведённому выше для Java, «break» должен «пересечь» две фигурные скобки «}», чтобы оказаться за пределами двух циклов.
    
    for($i=0; $i < $Imax; ++$i)
    {
       // ...
       for($j=0; $j < $Jmax; ++$j)
       {
          // ...
          if(условие) 
              break 2;
          // ...
       }
       // ...
    }

    Интересно, а почему б нечто подобное не сделать для функций? Ну например есть функция a() которая вызывает функцию b() которая вызывает функцию c(), которая вызывает функцию d(), и например в функции d() чтоб сделать особый return_3, который бы вернул управление на три уровня вниз, сразу в функцию a()? Хотя не, хуйня, надо ведь еще знать, какой там тип возвращается в функцию a() из функции b().
    То ли дело ассемблер. Можно тупо отмотать стек в нужное место

    j123123, 16 Февраля 2018

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

    0

    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
    // enum_helper_pre.h
    
    #ifndef delimiter 
        #define delimiter , 
    #endif 
     
     
    #ifndef enumeration_begin 
        #define enumeration_begin(arg) enum arg { 
    #endif 
     
    #ifndef enumeration_end 
        #ifdef last_enumerator 
            #define enumeration_end delimiter last_enumerator } 
        #else 
            #define enumeration_end } 
        #endif 
    #endif 
     
    #ifndef declare_member 
        #define declare_member(arg) arg 
    #endif 
     
    #ifndef member_value 
        #define member_value(arg) = arg 
    #endif 
    
    
    // enum_helper_post.h
    
    #undef delimiter 
    #undef enumeration_begin 
    #undef enumeration_end 
    #undef last_enumerator 
    #undef declare_member 
    #undef member_value
    
    
    // color.h
    
    #include "enum_helper_pre.h" 
     
    enumeration_begin(color) 
    declare_member(RED) member_value(-2) delimiter 
    declare_member(GREEN) delimiter 
    declare_member(BLUE) member_value(5) delimiter 
    declare_member(BRIGHTNESS) 
    enumeration_end; 
     
    #include "enum_helper_post.h"
    
    
    // main.cpp
    
    #include <iostream> 
    #include <string> 
    #include <boost/bimap.hpp> 
    #include <boost/preprocessor/stringize.hpp> 
     
    #include "color.h" 
     
    int main(int argc,char* argv[]) 
    { 
        typedef boost::bimap<color,std::string> map_type; 
        map_type color_map; 
        #define declare_member(arg) color_map.insert( map_type::value_type(arg,BOOST_PP_STRINGIZE(arg)) ) 
        #define delimiter ; 
        #define enumeration_begin(arg) 
        #define enumeration_end 
        #define member_value(arg) 
        #include "color.h" 
     
        std::cout<<color_map.left.at(RED)<<std::endl; 
        std::cout<<color_map.left.at(BLUE)<<std::endl; 
        std::cout<<color_map.right.at("GREEN")<<std::endl; 
        std::cout<<color_map.right.at("BRIGHTNESS")<<std::endl; 
        return 0; 
    }
    
    // Output
    
    RED 
    BLUE 
    -1 
    6

    Нарыл эту хуйню на http://www.quizful.net/post/enum-types-c

    j123123, 06 Февраля 2018

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