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

    В номинации:
    За время:
  2. Куча / Говнокод #27314

    +1

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    # PowerShell
    
    switch ($true)
    {
        ($firstNumber -gt $secondNumber) {Write-Output ("{0} > {1}" -F $firstNumber, $secondNumber)}
        ($firstNumber -eq $secondNumber) {Write-Output ("{0} == {1}" -F $firstNumber, $secondNumber)}
        ($firstNumber -lt $secondNumber) {Write-Output ("{0} < {1}" -F $firstNumber, $secondNumber)}
    }

    Интересный такой свитч-кейс (https://stackoverflow.com/questions/57063932/powershell-overriding-assignment-and-comparison-operators)

    groser, 24 Марта 2021

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

    +1

    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
    #include <iostream>
    
    template<typename T>
    struct CrtpBase {
        static float base_func()
        {
            std::cout << "CrtpBase::base_func(), " << typeid(T).name() << "::int_field == "
                << T::int_field << std::endl;
            return 16.0f;
        }
    
        static inline float x = base_func();
    };
    
    struct A: public CrtpBase<A> {
        void func_a()
        {
            base_func();
        }
    
        static inline int int_field = 16;
    };
    
    struct B : public CrtpBase<B> {
        void func_b()
        {
            std::cout << "B::func_b(), no CrtpBase<B>::base_func() call" << std::endl;
        }
    };
    
    
    int main()
    {
        A a;
        a.func_a();
    
        B b;
        b.func_b();
    }

    [temp.inst]/2:
    Unless a class template specialization is a declared specialization,
    the class template specialization is implicitly instantiated when
    the specialization is referenced in a context that requires a
    completely-defined object type or when the completeness of the
    class type affects the semantics of the program.

    [temp.inst]/3:
    The implicit instantiation of a class template specialization causes
    (3.1) -- the implicit instantiation of the declarations, but not of the definitions, of
    the non-deleted class member functions, member classes, scoped member enumerations,
    static data members, member templates, and friends; and
    (3.2) -- the implicit instantiation of the definitions of deleted member functions,
    unscoped member enumerations, and member anonymous unions.

    [temp.inst]/4:
    Unless a member of a templated class is a declared specialization, the specialization
    of the member is implicitly instantiated when the specialization is referenced in a
    context that requires the member definition to exist or if the existence of the definition
    of the member affects the semantics of the program; in particular, the initialization
    (and any associated side effects) of a static data member does not occur unless the
    static data member is itself used in a way that requires the definition of the static
    data member to exist.


    Таким образом, по стандарту CrtpBase<B>::x не должен быть инициализирован, поскольку он нигде не used in a way that requires the definition of the static data member to exist. Правильные компиляторы (gcc и clang) это понимают и компилируют код, а вот Visual Studio зачем-то пытается инициализировать CrtpBase<B>::x и нон-конформно ломается.

    PolinaAksenova, 24 Марта 2021

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

    +1

    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
    namespace detail {
        template<entity_event_t Event>
        struct EventHasEntityStateConstructor {
            // Sanity check
            static_assert(static_cast<int32_t>(Event) >= 0
                          && static_cast<int32_t>(Event) < ENTITY_EVENTS_COUNT);
    
        private:
            struct TwoChar {
                char a, b;
            };
    
            template<typename T>
            constexpr static TwoChar _check(
                decltype(
                    T(std::declval<const entityState_t &>())
                )*
            );
    
            template<typename T>
            constexpr static char _check(...);
    
        public:
            constexpr inline static bool value = (sizeof(_check<EntityEvent<Event>>(nullptr)) == sizeof(TwoChar));
        };
    
        template<typename BusT, entity_event_t Event>
        bool defaultEntityEventPublisher(const BusT & bus, const entityState_t & eventEntity)
        {
            static_assert(EventHasEntityStateConstructor<Event>::value,
                          "defaultEntityEventFactory<Event>() instantiated for a custom\n"
                          "event that does not have a (const entityState_t & eventEntity) constructor.\n"
                          "This should not happen (you'll get a more obscured compiler error anyway)!");
            return bus.publishEmplace<EntityEvent<Event>>(eventEntity);
        }
    
        template<typename BusT, typename T, T... Is>
        constexpr std::array<EntityEventPublisherPtr<BusT>, sizeof...(Is)>
            createDefaultEntityEventFactories(std::integer_sequence<T, Is...>)
        {
            return {
                [](auto i) -> EntityEventPublisherPtr<BusT> {
                    if constexpr (EventHasEntityStateConstructor<static_cast<entity_event_t>(i.value)>::value) {
                        return &defaultEntityEventPublisher<BusT, static_cast<entity_event_t>(i.value)>;
                    } else {
                        return nullptr;
                    }
                }(std::integral_constant<T, Is>{})...
            };
        }
    }
    
    // An (event_number -> EntityState<event_number> 'publishing factory' function) mapping;
    // if event N could not be constructed from a single entityState_t reference
    // then this table would contain nullptr at the index N
    template<typename BusT>
    const std::array<EntityEventPublisherPtr<BusT>, ENTITY_EVENTS_COUNT> & getDefaultEntityEventsPublishers() noexcept
    {
        static auto factories = detail::createDefaultEntityEventFactories<BusT>(std::make_integer_sequence<int32_t, ENTITY_EVENTS_COUNT>());
        return factories;
    }
    
    template<typename BusT>
    EntityEventPublisherPtr<BusT> tryGetDefaultEntityEventPublisher(entity_event_t event) noexcept
    {
        auto eventNum = static_cast<int32_t>(event);
        if (eventNum >= 0 && eventNum < ENTITY_EVENTS_COUNT) {
            return getDefaultEntityEventsPublishers<BusT>()[eventNum];
        } else {
            return nullptr;
        }
    }

    PolinaAksenova, 21 Марта 2021

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

    +1

    1. 1
    Class HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor

    https://javadoc.io/doc/org.aspectj/aspectjweaver/1.8.10/org/aspectj/weaver/patterns/HasThisTypePatternTriedToSneakInSomeGene ricOrParameterizedTypePatternMatchingStu ffAnywhereVisitor.html

    6oHo6o, 21 Марта 2021

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

    +1

    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
    // https://gcc.gnu.org/onlinedocs/gcc-10.1.0/gcc/Common-Function-Attributes.html
    
    access
    access (access-mode, ref-index)
    access (access-mode, ref-index, size-index)
    
    // примеры:
    
    __attribute__ ((access (read_only, 1))) int puts (const char*);
    __attribute__ ((access (read_only, 1, 2))) void* memcpy (void*, const void*, size_t);
    
    __attribute__ ((access (read_write, 1), access (read_only, 2))) char* strcat (char*, const char*);
    
    __attribute__ ((access (write_only, 1), access (read_only, 2))) char* strcpy (char*, const char*);
    __attribute__ ((access (write_only, 1, 2), access (read_write, 3))) int fgets (char*, int, FILE*);

    В GCC 10 какой-то новый атрибут access появился, чтоб более строго что-то там гарантировать:

    The access attribute enables the detection of invalid or unsafe accesses by functions to which they apply or their callers, as well as write-only accesses to objects that are never read from. Such accesses may be diagnosed by warnings such as -Wstringop-overflow, -Wuninitialized, -Wunused, and others.

    The access attribute specifies that a function to whose by-reference arguments the attribute applies accesses the referenced object according to access-mode. The access-mode argument is required and must be one of three names: read_only, read_write, or write_only. The remaining two are positional arguments.

    The required ref-index positional argument denotes a function argument of pointer (or in C++, reference) type that is subject to the access. The same pointer argument can be referenced by at most one distinct access attribute.

    The optional size-index positional argument denotes a function argument of integer type that specifies the maximum size of the access. The size is the number of elements of the type referenced by ref-index, or the number of bytes when the pointer type is void*. When no size-index argument is specified, the pointer argument must be either null or point to a space that is suitably aligned and large for at least one object of the referenced type (this implies that a past-the-end pointer is not a valid argument). The actual size of the access may be less but it must not be more.

    j123123, 14 Марта 2021

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

    +1

    1. 1
    Как крестьяне говна поели

    This function is defined as the RtlSecureZeroMemory function (see WinBase.h). The implementation of RtlSecureZeroMemory is provided inline and can be used on any version of Windows (see WinNT.h.)

    Use this function instead of ZeroMemory when you want to ensure that your data will be overwritten promptly, as some C++ compilers can optimize a call to ZeroMemory by removing it entirely.

    Petro-san, 10 Марта 2021

    Комментарии (80)
  8. JavaScript / Говнокод #27288

    +1

    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
    function main() {
        print("Hello", 1, false, true, parseInt("01"), parseFloat("00.1"));
    }
    
    // ASM
    ; ModuleID = 'LLVMDialectModule'
    source_filename = "LLVMDialectModule"
    target datalayout = "e-m:w-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
    target triple = "x86_64-pc-windows-msvc"
    
    @__true__ = internal constant [5 x i8] c"true\00"
    @__false__ = internal constant [6 x i8] c"false\00"
    @frmt_9481649210695450612 = internal constant [19 x i8] c"%s %d %s %s %d %f\0A\00"
    @s_3144841719139014728 = internal constant [5 x i8] c"00.1\00"
    @s_12300967985959445949 = internal constant [3 x i8] c"01\00"
    @s_1772061916968062023 = internal constant [6 x i8] c"Hello\00"
    
    declare i8* @malloc(i64)
    
    declare void @free(i8*)
    
    declare i32 @printf(i8*, ...)
    
    declare float @atof(i8*)
    
    declare i32 @atoi(i8*)
    
    define void @main() !dbg !3 {
      %1 = call i32 @atoi(i8* getelementptr inbounds ([3 x i8], [3 x i8]* @s_12300967985959445949, i64 0, i64 0)), !dbg !7
      %2 = call float @atof(i8* getelementptr inbounds ([5 x i8], [5 x i8]* @s_3144841719139014728, i64 0, i64 0)), !dbg !9
      %3 = fpext float %2 to double, !dbg !10
      %4 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([19 x i8], [19 x i8]* @frmt_9481649210695450612, i64 0, i64 0), i8* getelementptr inbounds ([6 x i8], [6 x i8]* @s_1772061916968062023, i64 0, i64 0), i32 1, i8* getelementptr inbounds ([6 x i8], [6 x i8]* @__false__, i64 0, i64 0), i8* getelementptr inbounds ([5 x i8], [5 x i8]* @__true__, i64 0, i64 0), i32 %1, double %3), !dbg !10
      br label %5, !dbg !11
    
    5:                                                ; preds = %0
      ret void, !dbg !11
    }
    
    !llvm.dbg.cu = !{!0}
    !llvm.module.flags = !{!2}

    Продолжение писания уе..(зачеркнуто) супер компилятора с TypeScript (JavaScript) в нативный код.

    как обычно компилим просто

    set LIBPATH=C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\SDK\ScopeCppSDK\vc 15\VC\lib
    set SDKPATH=C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\SDK\ScopeCppSDK\vc 15\SDK\lib
    tsc.exe --emit=llvm C:\temp\1.ts 2>1.ll
    llc.exe --filetype=obj -o=out.o 1.ll
    lld.exe -flavor link out.o "%LIBPATH%\libcmt.lib" "%LIBPATH%\libvcruntime.lib" "%SDKPATH%\kernel32.lib" "%SDKPATH%\libucrt.lib" "%SDKPATH%\uuid.lib"

    получаетм Ехе и грузим его. и результат

    =====================================
    и выполнение

    C:\>out.exe
    Hello 1 false true 1 0.100000

    ASD_77, 09 Марта 2021

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

    +1

    1. 1
    Просто оффтоп #16

    #1: https://govnokod.ru/20162 https://govnokod.xyz/_20162
    #2: https://govnokod.ru/25329 https://govnokod.xyz/_25329
    #3: https://govnokod.ru/25415 https://govnokod.xyz/_25415
    #4: (vanished) https://govnokod.xyz/_25472
    #5: https://govnokod.ru/25693 https://govnokod.xyz/_25693
    #6: (vanished) https://govnokod.xyz/_26649
    #7: https://govnokod.ru/26672 https://govnokod.xyz/_26672
    #8: https://govnokod.ru/26924 https://govnokod.xyz/_26924
    #9: https://govnokod.ru/27072 https://govnokod.xyz/_27072
    #10: https://govnokod.ru/27086 https://govnokod.xyz/_27086
    #11: https://govnokod.ru/27122 https://govnokod.xyz/_27122
    #12: https://govnokod.ru/27153 https://govnokod.xyz/_27153
    #13: https://govnokod.ru/27159 https://govnokod.xyz/_27159
    #14: https://govnokod.ru/27200 https://govnokod.xyz/_27200
    #15: https://govnokod.ru/27237 https://govnokod.xyz/_27237

    nepeKamHblu_nemyx, 03 Марта 2021

    Комментарии (3504)
  10. Go / Говнокод #27261

    +1

    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
    // https://docs.docker.com/engine/api/v1.24/#create-a-container
    
    POST /v1.24/containers/create HTTP/1.1
    Content-Type: application/json
    Content-Length: 12345
    
    {
           "Hostname": "",
           "Domainname": "",
           "User": "",
           "AttachStdin": false,
           "AttachStdout": true,
           "AttachStderr": true,
           "Tty": false,
           "OpenStdin": false,
           "StdinOnce": false,
           "Env": [
                   "FOO=bar",
                   "BAZ=quux"
           ],
           ...
    }

    Ядро предоставляет сисколл execve. Execve принимает переменные окружения в виде массива строк A=B -
    не знаю конкретных причин, почему так сделано, но скорее всего просто потому что писать хэшмапу под
    это дело, которая еще и будет выкинута из памяти через относительно небольшое время - дело дорогое и
    ненужное, плюс наверняка какой-нибудь лишний пердолинг со стеком.
    https://man7.org/linux/man-pages/man2/execve.2.html

    Го, "человеческий язык" с поддержкой обычных мап из коробки, ничтоже сумляшеся не замечает никакой
    проблемы и заставляет пользователя передавать переменные окружения в том же формате, потому что у
    языка не только синтаксис должен быть таким же тупым, как программист на нём и вообще мы же тут
    делаем вид, что мы C, только лучше.
    https://golang.org/pkg/os/exec/#example_Command_environment

    Докер, "человеческий сервис" с HTTP API, использующим формат JSON с поддержкой обычных мап из коробки,
    ничтоже сумляшеся не замечает никакой проблемы и заставляет пользователя передавать переменные
    окружения в том же формате, потому что на программист на языке должен быть тупым, как этот язык.
    https://docs.docker.com/engine/api/v1.24/#create-a-container

    В результате мы имеем пачку долбоебов, из-за которых оперирующие (мапами / объектами / словарями / как угодно назовите)
    нормальные люди должны вести себя как типичные гошники.

    Fike, 17 Февраля 2021

    Комментарии (42)
  11. Java / Говнокод #27258

    +1

    1. 1
    .

    https://vc.ru/flood/149783-podgotovte-nomer-pablik-steytik-dzhava-tochka-pomoshchnik-oleg-zachital-sboy-vo-vremya-testa-v-koll-centre-tinkoff

    3_dar, 17 Февраля 2021

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