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

    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
    #include <iostream>
    #include <algorithm>
    #include <functional>
    #include <map>
    #include <string>
    
    int main()
    {
        using namespace std::placeholders;
    
        std::map<std::string, int> karta;
        std::vector<std::string> goroda{ "foo", "bar", "foo" };
    
        std::for_each(goroda.begin(), goroda.end(), std::bind(
            static_cast<
                std::pair<decltype(karta)::iterator, bool>
                (decltype(karta)::*)(const decltype(karta)::key_type&, decltype(karta)::mapped_type&&)>
                    (&decltype(karta)::insert_or_assign),
            std::ref(karta),
            _1,
            std::bind(
                std::plus<decltype(karta)::mapped_type>(),
                1,
                std::bind(
                    static_cast<decltype(karta)::mapped_type&(decltype(karta)::*)(const decltype(karta)::key_type &)>
                    (&decltype(karta)::operator[]),
                    std::ref(karta),
                    _1))
        ));
        std::cout << "foo: " << karta["foo"] << "\nbar: " << karta["bar"] << '\n';
        
        return EXIT_SUCCESS;
    }

    #24802, переписанный в функциональном modern C++ стиле.
    Переделать бы ещё это под итераторы, чтобы двух обращений к мапе не было…

    gost, 24 Сентября 2018

    Комментарии (37)
  2. Lua / Говнокод #24804

    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
    --Запрос в яндекс за спичером
    function thstart(text)
      
      local th = [[
      love.filesystem.remove("tmp.ogg");
      local str = ...
      local encodeURI = function(str)
    		if (str) then
    			str = string.gsub (str, "\n", "\r\n")
    			str = string.gsub (str, "([^%w ])",
    				function (c) return string.format ("%%%02X", string.byte(c)) end)
            str = string.gsub (str, " ", "+")
    	   end
    	   return str
      end
      str = encodeURI(str)
      local http = require("socket.http");
      body = http.request("https://tts.voicetech.yandex.net/generate?text="..str.."&format=mp3&lang=ru-RU&speaker=kolya&emotion=evil&key=069b6659-984b-4c5f-880e-aaedcfd84102&speed=0.8")
      if body then
        love.filesystem.write("tmp.mp3",body)
        love.thread.getChannel('im'):push("tmp.mp3")
      else
        love.thread.getChannel('im'):push("err")
      end
      --love.thread.getChannel('im'):push("err")
      ]]
      tred = nil
      tred = love.thread.newThread(th);  
      tred:start(text);
    end
    
    function thpop()
      local info = love.thread.getChannel( 'im' ):pop()
      if info then
        if info == "err" then
          return "err"
        else
          return info
        end
      end
      return nil
    end

    3oJIoTou_xyu, 24 Сентября 2018

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

    +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
    struct A { 
      virtual int transmogrify();
    };
     
    struct B : A {
      int transmogrify() override { new(this) A; return 2; }
    };
     
    int A::transmogrify() { new(this) B; return 1; }
     
    static_assert(sizeof(B) == sizeof(A));
    
    int main() {
      A i;
      int n = i.transmogrify();
      // int m = i.transmogrify(); // undefined behavior
      int m = std::launder(&i)->transmogrify(); // OK
      assert(m + n == 3);
    }

    Yo dawg, we heard you like kostyli, so we put our kostyli into your kostyli, so that you can use kostyli to support our kostyli!

    https://en.cppreference.com/w/cpp/utility/launder

    А если серьезно, мне еще не удалось соорудить пример, чтоб код с std::launder и без него работали по разному.

    Elvenfighter, 24 Сентября 2018

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

    +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
    #include <map>
    #include <stdio.h>
    #include <vector>
    using namespace std;
     
    int main() {
       map<string, int> karta;
       for (auto pituh : vector<string> {"foo", "bar", "foo"}) {
        	karta[pituh]++;
       }
       printf("foo: %d\nbar: %d\n", karta["foo"], karta["bar"]);
       return 0;
    }

    <?php

    $karta = [];
    foreach (["foo", "bar", "foo"] as $pituh) {
    if (!isset($karta[$pituh])) {
    $karta[$pituh] = 0;
    }
    $karta[$pituh]++;
    }
    echo "foo: {$karta['foo']}\nbar: {$karta['bar']}\n";


    Поэтому за что я?

    guestinxo, 24 Сентября 2018

    Комментарии (22)
  5. PHP / Говнокод #24800

    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
    // CVE-2012-5692
    
    /* 4015. */        static public function get($name) 
    /* 4016. */        { 
    /* 4017. */            // Check internal data first 
    /* 4018. */            if ( isset( self::$_cookiesSet[ $name ] ) ) 
    /* 4019. */            { 
    /* 4020. */                return self::$_cookiesSet[ $name ]; 
    /* 4021. */            } 
    /* 4022. */            else if ( isset( $_COOKIE[ipsRegistry::$settings['cookie_id'].$name] ) ) 
    /* 4023. */            { 
    /* 4024. */                $_value = $_COOKIE[ ipsRegistry::$settings['cookie_id'].$name ]; 
    /* 4025. */    
    /* 4026. */                if ( substr( $_value, 0, 2 ) == 'a:' ) 
    /* 4027. */                { 
    /* 4028. */                    return unserialize( stripslashes( urldecode( $_value ) ) ); 
    /* 4029. */                } 
    
    /*  
    The vulnerability is caused due to this method unserialize user input passed through cookies without a proper 
    sanitization. The only one check is done at line 4026,  where is controlled that the serialized string starts 
    with 'a:',  but this is not  sufficient to prevent a  "PHP Object Injection"  because an attacker may send  a 
    serialized string which represents an array of objects.  This can be  exploited to execute arbitrary PHP code 
    via the  "__destruct()" method of the  "dbMain" class,  which calls the "writeDebugLog" method to write debug 
    info into a file.  PHP code may  be injected  only through the  $_SERVER['QUERY_STRING']  variable,  for this 
    reason successful exploitation of this vulnerability requires short_open_tag to be enabled. 
    */

    Если вы думаете, что самое плохое, что ждёт ваш уютный сайт на «PHP» — это Роберт-брось-таблицу, то вы глубоко ошибаетесь.

    CSRF verification passed.

    gost, 23 Сентября 2018

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

    −2

    1. 1
    https://habr.com/post/423889/

    Публикация отхватила неебическое количество плюсов.

    LinuxGovno, 21 Сентября 2018

    Комментарии (25)
  7. Lua / Говнокод #24797

    0

    1. 1
    return x > 0 and true or false

    imring, 21 Сентября 2018

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

    −1

    1. 1
    2. 2
    3. 3
    4. 4
    const (
    	millisPerSecond     = int64(time.Second / time.Millisecond)
    	nanosPerMillisecond = int64(time.Millisecond / time.Nanosecond)
    )

    Автор предусмотрел возможность изменения СИ.

    cheshir, 21 Сентября 2018

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

    −3

    1. 1
    Внимайте мне, Земли обитатели!

    Я открою вам истину, которую веками скрывали от вас – число ноль является ничем иным как выдумкой враждебной к вам Галактической Империи. Он является лишь помехой в вычислениях, и привел к деградации вашей цивилизации. Откажитесь от него! И математика простой и понятной станет, и вам путь к просветлению и силе откроется!

    MasterJoda, 21 Сентября 2018

    Комментарии (11)
  10. Python / Говнокод #24794

    −1

    1. 1
    2. 2
    3. 3
    4. 4
    if len(item['createdOn']):
        item['createdOn'] = strptime(item['createdOn'], '%Y.%m.%d %H:%M:%S')
    else:
        del item['createdOn']

    mef1stofel, 21 Сентября 2018

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